text
stringlengths 5
1.04M
|
|---|
// 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 "base/basictypes.h"
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/memory/ref_counted.h"
#include "base/message_loop/message_loop.h"
#include "base/path_service.h"
#include "base/values.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/extensions/api/preferences_private/preferences_private_api.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extension_function_test_utils.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/signin/profile_oauth2_token_service_factory.h"
#include "chrome/browser/sync/profile_sync_components_factory_mock.h"
#include "chrome/browser/sync/profile_sync_service.h"
#include "chrome/browser/sync/profile_sync_service_factory.h"
#include "chrome/browser/sync/supervised_user_signin_manager_wrapper.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/base/testing_profile.h"
#include "components/bookmarks/common/bookmark_constants.h"
#include "components/sync_driver/sync_prefs.h"
#include "content/public/browser/browser_context.h"
#include "extensions/test/extension_test_message_listener.h"
#if defined(OS_CHROMEOS)
#include "chromeos/chromeos_switches.h"
#endif
using extensions::PreferencesPrivateGetSyncCategoriesWithoutPassphraseFunction;
namespace {
class FakeProfileSyncService : public ProfileSyncService {
public:
explicit FakeProfileSyncService(Profile* profile)
: ProfileSyncService(
scoped_ptr<ProfileSyncComponentsFactory>(
new ProfileSyncComponentsFactoryMock()),
profile,
make_scoped_ptr<SupervisedUserSigninManagerWrapper>(NULL),
ProfileOAuth2TokenServiceFactory::GetForProfile(profile),
browser_sync::MANUAL_START),
sync_initialized_(true),
initialized_state_violation_(false) {}
~FakeProfileSyncService() override {}
static KeyedService* BuildFakeProfileSyncService(
content::BrowserContext* context) {
return new FakeProfileSyncService(static_cast<Profile*>(context));
}
void set_sync_initialized(bool sync_initialized) {
sync_initialized_ = sync_initialized;
}
bool initialized_state_violation() { return initialized_state_violation_; }
// ProfileSyncService:
bool SyncActive() const override { return sync_initialized_; }
void AddObserver(ProfileSyncServiceBase::Observer* observer) override {
if (sync_initialized_)
initialized_state_violation_ = true;
// Set sync initialized state to true so the function will run after
// OnStateChanged is called.
sync_initialized_ = true;
base::MessageLoop::current()->PostTask(
FROM_HERE,
base::Bind(&ProfileSyncServiceBase::Observer::OnStateChanged,
base::Unretained(observer)));
}
syncer::ModelTypeSet GetEncryptedDataTypes() const override {
if (!sync_initialized_)
initialized_state_violation_ = true;
syncer::ModelTypeSet type_set;
type_set.Put(syncer::AUTOFILL);
return type_set;
}
syncer::ModelTypeSet GetPreferredDataTypes() const override {
if (!sync_initialized_)
initialized_state_violation_ = true;
syncer::ModelTypeSet preferred_types =
syncer::UserSelectableTypes();
preferred_types.Remove(syncer::TYPED_URLS);
return preferred_types;
}
private:
bool sync_initialized_;
// Set to true if a function is called when sync_initialized is in an
// unexpected state.
mutable bool initialized_state_violation_;
DISALLOW_COPY_AND_ASSIGN(FakeProfileSyncService);
};
class PreferencesPrivateApiTest : public ExtensionApiTest {
public:
PreferencesPrivateApiTest() : browser_(NULL), service_(NULL) {}
~PreferencesPrivateApiTest() override {}
void SetUpCommandLine(base::CommandLine* command_line) override {
#if defined(OS_CHROMEOS)
command_line->AppendSwitch(
chromeos::switches::kIgnoreUserProfileMappingForTests);
#endif
}
void SetUpOnMainThread() override {
ExtensionApiTest::SetUpOnMainThread();
base::FilePath path;
PathService::Get(chrome::DIR_USER_DATA, &path);
path = path.AppendASCII("test_profile");
if (!base::PathExists(path))
CHECK(base::CreateDirectory(path));
Profile* profile =
Profile::CreateProfile(path, NULL, Profile::CREATE_MODE_SYNCHRONOUS);
sync_driver::SyncPrefs sync_prefs(profile->GetPrefs());
sync_prefs.SetKeepEverythingSynced(false);
ProfileManager* profile_manager = g_browser_process->profile_manager();
profile_manager->RegisterTestingProfile(profile, true, false);
service_ = static_cast<FakeProfileSyncService*>(
ProfileSyncServiceFactory::GetInstance()->SetTestingFactoryAndUse(
profile, &FakeProfileSyncService::BuildFakeProfileSyncService));
browser_ = new Browser(Browser::CreateParams(
profile, chrome::HOST_DESKTOP_TYPE_NATIVE));
}
// Calls GetSyncCategoriesWithoutPassphraseFunction and verifies that the
// results returned are the expected ones.
void TestGetSyncCategoriesWithoutPassphraseFunction();
protected:
Browser* browser_;
FakeProfileSyncService* service_;
private:
DISALLOW_COPY_AND_ASSIGN(PreferencesPrivateApiTest);
};
void
PreferencesPrivateApiTest::TestGetSyncCategoriesWithoutPassphraseFunction() {
scoped_refptr<PreferencesPrivateGetSyncCategoriesWithoutPassphraseFunction>
function(
new PreferencesPrivateGetSyncCategoriesWithoutPassphraseFunction);
ASSERT_TRUE(extension_function_test_utils::RunFunction(
function.get(), "[]", browser_, extension_function_test_utils::NONE));
EXPECT_FALSE(service_->initialized_state_violation());
const base::ListValue* result = function->GetResultList();
EXPECT_EQ(1u, result->GetSize());
const base::ListValue* categories = NULL;
ASSERT_TRUE(result->GetList(0, &categories));
EXPECT_NE(categories->end(),
categories->Find(base::StringValue(bookmarks::kBookmarksFileName)));
EXPECT_NE(categories->end(),
categories->Find(base::StringValue(chrome::kPreferencesFilename)));
EXPECT_EQ(categories->end(),
categories->Find(base::StringValue("Autofill"))) <<
"Encrypted categories should not be present";
EXPECT_EQ(categories->end(),
categories->Find(base::StringValue("Typed URLs"))) <<
"Unsynced categories should not be present";
}
IN_PROC_BROWSER_TEST_F(PreferencesPrivateApiTest,
GetSyncCategoriesWithoutPassphrase) {
TestGetSyncCategoriesWithoutPassphraseFunction();
}
// Verifies that we wait for the sync service to be ready before checking
// encryption status.
IN_PROC_BROWSER_TEST_F(PreferencesPrivateApiTest,
GetSyncCategoriesWithoutPassphraseAsynchronous) {
service_->set_sync_initialized(false);
TestGetSyncCategoriesWithoutPassphraseFunction();
}
} // namespace
|
// <Snippet1>
using namespace System;
using namespace System::Collections;
void FindMyObject( ArrayList^ myList, Object^ myObject );
void PrintValues( IEnumerable^ myList );
int main()
{
// Creates and initializes a new ArrayList. BinarySearch requires
// a sorted ArrayList.
ArrayList^ myAL = gcnew ArrayList;
for ( int i = 0; i <= 4; i++ )
myAL->Add( i * 2 );
// Displays the ArrayList.
Console::WriteLine( "The Int32 ArrayList contains the following:" );
PrintValues( myAL );
// Locates a specific object that does not exist in the ArrayList.
Object^ myObjectOdd = 3;
FindMyObject( myAL, myObjectOdd );
// Locates an object that exists in the ArrayList.
Object^ myObjectEven = 6;
FindMyObject( myAL, myObjectEven );
}
void FindMyObject( ArrayList^ myList, Object^ myObject )
{
int myIndex = myList->BinarySearch( myObject );
if ( myIndex < 0 )
Console::WriteLine( "The object to search for ({0}) is not found. The next larger object is at index {1}.", myObject, ~myIndex );
else
Console::WriteLine( "The object to search for ({0}) is at index {1}.", myObject, myIndex );
}
void PrintValues( IEnumerable^ myList )
{
IEnumerator^ myEnum = myList->GetEnumerator();
while ( myEnum->MoveNext() )
{
Object^ obj = safe_cast<Object^>(myEnum->Current);
Console::Write( " {0}", obj );
}
Console::WriteLine();
}
/*
This code produces the following output.
The Int32 ArrayList contains the following:
0 2 4 6 8
The object to search for (3) is not found. The next larger object is at index 2.
The object to search for (6) is at index 3.
*/
// </Snippet1>
|
///////////////////////////////////////////////////////////////////////////////
// 2014-01-26 P.Murat
///////////////////////////////////////////////////////////////////////////////
// conditions
#include "ConditionsService/inc/ConditionsHandle.hh"
#include "ConditionsService/inc/AcceleratorParams.hh"
#include "Stntuple/mod/InitStntupleDataBlocks.hh"
#include "Stntuple/obj/TVDetDataBlock.hh"
#include "MCDataProducts/inc/SimParticle.hh"
#include "MCDataProducts/inc/StepPointMC.hh"
#include "MCDataProducts/inc/StepPointMCCollection.hh"
#include "MCDataProducts/inc/PtrStepPointMCVectorCollection.hh"
#include "GlobalConstantsService/inc/GlobalConstantsHandle.hh"
#include "GlobalConstantsService/inc/ParticleDataTable.hh"
#include "Mu2eUtilities/inc/SimParticleTimeOffset.hh"
#include "Stntuple/mod/THistModule.hh"
#include "Stntuple/base/TNamedHandle.hh"
//-----------------------------------------------------------------------------
Int_t StntupleInitMu2eVDetDataBlock(TStnDataBlock* Block, AbsEvent* AnEvent, int Mode)
{
static int initialized(0);
static char oname[] = "StntupleInitMu2eVirtualDataBlock";
static mu2e::SimParticleTimeOffset* _timeOffsets(NULL);
static char step_module_label[100], step_description[100];
int ev_number, rn_number, nhits;
char module_name [100], time_offsets_name[100];
ev_number = AnEvent->event();
rn_number = AnEvent->run();
if (Block->Initialized(ev_number,rn_number)) return 0;
TVDetDataBlock* data = (TVDetDataBlock*) Block;
data->Clear();
if (initialized == 0) {
initialized = 1;
data->GetModuleLabel("TimeOffsetMapsHandle",module_name);
data->GetDescription("TimeOffsetMapsHandle",time_offsets_name);
THistModule* m = static_cast<THistModule*> (THistModule::GetListOfModules()->FindObject(module_name));
TNamedHandle* nh = static_cast<TNamedHandle*> (m->GetFolder()->FindObject(time_offsets_name));
_timeOffsets = static_cast<mu2e::SimParticleTimeOffset*> (nh->Object());
}
//-----------------------------------------------------------------------------
// virtual hit information
//-----------------------------------------------------------------------------
data->GetModuleLabel("mu2e::StepPointMCCollection",step_module_label);
data->GetDescription("mu2e::StepPointMCCollection",step_description);
art::Handle<mu2e::StepPointMCCollection> step_handle;
const mu2e::StepPointMCCollection* list_of_hits(0);
static mu2e::GlobalConstantsHandle<mu2e::ParticleDataTable> pdt;
mu2e::ParticleDataTable::maybe_ref info;
mu2e::ConditionsHandle<mu2e::AcceleratorParams> accPar("ignored");
double _mbtime = accPar->deBuncherPeriod;
if (step_module_label[0] != 0) {
if (step_description[0] != 0)
AnEvent->getByLabel(step_module_label, step_description, step_handle);
if (step_handle.isValid()) list_of_hits = step_handle.product();
}
if (list_of_hits == NULL) {
char warning[500];
snprintf(warning,500," WARNING: StepPointMCCollection by %s:%s is missing. BAIL OUT\n",
step_module_label,step_description);
mf::LogWarning(oname) << warning;
return -1;
}
// load simulation time offsets for this event: timeOffsets may not be defined yet (stages 1, 2, 3)
if (_timeOffsets) _timeOffsets->updateMap(*AnEvent);
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
nhits = list_of_hits->size();
const mu2e::StepPointMC* step;
art::Ptr<mu2e::SimParticle> sim;
TVDetHitData* hit;
int vdIndex, pdg_id, gen_index;
float time;
float energyKin, energy;
float mass;
float mc_mom;
float mc_momX, mc_momY, mc_momZ;
float mc_posX, mc_posY, mc_posZ;
float min_energy(40.);
for (int i=0; i<nhits; i++) {
step = &list_of_hits->at(i);
sim = step->simParticle();
if (!(sim->fromGenerator())) goto NEXT_VHIT;
vdIndex = step->volumeId();
if (_timeOffsets) {
//-----------------------------------------------------------------------------
// time - within the microbunch
//-----------------------------------------------------------------------------
double tx = _timeOffsets->timeWithOffsetsApplied(*step);
time = fmod(tx,_mbtime);
}
else time = step->time();
pdg_id = sim->pdgId();
info = pdt->particle(pdg_id);
mass = info.ref().mass();
energy = sqrt(step->momentum().mag2() + mass*mass);
energyKin = energy - mass;
if (energy < min_energy) goto NEXT_VHIT;
gen_index = sim->genParticle()->generatorId().id();
mc_mom = step->momentum().mag();
mc_momX = step->momentum().x();
mc_momY = step->momentum().y();
mc_momZ = step->momentum().z();
//-----------------------------------------------------------------------------
// poor-man global-to-detector (tracker) coordinate system transformation
//-----------------------------------------------------------------------------
mc_posX = step->position().x()+3904.;
mc_posY = step->position().y();
mc_posZ = step->position().z()-10200;
hit = data->NewHit();
hit->Set(vdIndex, time, mass, energyKin, energy,
pdg_id, gen_index,
mc_mom, mc_momX, mc_momY, mc_momZ,
mc_posX, mc_posY, mc_posZ);
NEXT_VHIT:;
}
data->f_RunNumber = rn_number;
data->f_EventNumber = ev_number;
return 0;
}
|
/*
Copyright 2020 Neijwiert
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 "General.h"
#include "RenSharpGameModeClass.h"
#include "RenSharp.h"
RenSharpGameModeClass::RenSharpGameModeClass()
{
}
RenSharpGameModeClass::~RenSharpGameModeClass()
{
RenSharpRootEventClass::Get_Instance().GameMode_Destructed(this);
}
void RenSharpGameModeClass::Init()
{
RenSharpRootEventClass::Get_Instance().GameMode_Init(this);
}
|
class Solution {
public:
void allPossibleCombs(int num,vector<vector<int>> &sol,vector<int> &temp,int k,int sum){
if(k == 0){
if(sum == 0){
sol.push_back(temp);
}
return;
}
if(num > 9){
return;
}
if(sum < num){
return;
}
temp.push_back(num);
allPossibleCombs(num+1,sol,temp,k-1,sum-num);
temp.pop_back();
allPossibleCombs(num+1,sol,temp,k,sum);
}
vector<vector<int>> combinationSum3(int k, int n) {
vector<vector<int>> sol;
if((k*(k+1))/2 > n){
return sol;
}
vector<int> temp;
allPossibleCombs(1,sol,temp,k,n);
return sol;
}
};
|
/*
* Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
#ifndef SHARE_VM_UTILITIES_OSTREAM_HPP
#define SHARE_VM_UTILITIES_OSTREAM_HPP
#include "memory/allocation.hpp"
#include "runtime/timer.hpp"
#include "utilities/globalDefinitions.hpp"
DEBUG_ONLY(class ResourceMark;)
// Output streams for printing
//
// Printing guidelines:
// Where possible, please use tty->print() and tty->print_cr().
// For product mode VM warnings use warning() which internally uses tty.
// In places where tty is not initialized yet or too much overhead,
// we may use jio_printf:
// jio_fprintf(defaultStream::output_stream(), "Message");
// This allows for redirection via -XX:+DisplayVMOutputToStdout and
// -XX:+DisplayVMOutputToStderr
class outputStream : public ResourceObj {
protected:
int _indentation; // current indentation
int _width; // width of the page
int _position; // position on the current line
int _newlines; // number of '\n' output so far
julong _precount; // number of chars output, less _position
TimeStamp _stamp; // for time stamps
char* _scratch; // internal scratch buffer for printf
size_t _scratch_len; // size of internal scratch buffer
void update_position(const char* s, size_t len);
static const char* do_vsnprintf(char* buffer, size_t buflen,
const char* format, va_list ap,
bool add_cr,
size_t& result_len) ATTRIBUTE_PRINTF(3, 0);
// calls do_vsnprintf and writes output to stream; uses an on-stack buffer.
void do_vsnprintf_and_write_with_automatic_buffer(const char* format, va_list ap, bool add_cr) ATTRIBUTE_PRINTF(2, 0);
// calls do_vsnprintf and writes output to stream; uses the user-provided buffer;
void do_vsnprintf_and_write_with_scratch_buffer(const char* format, va_list ap, bool add_cr) ATTRIBUTE_PRINTF(2, 0);
// calls do_vsnprintf, then writes output to stream.
void do_vsnprintf_and_write(const char* format, va_list ap, bool add_cr) ATTRIBUTE_PRINTF(2, 0);
public:
// creation
outputStream(int width = 80);
outputStream(int width, bool has_time_stamps);
// indentation
outputStream& indent();
void inc() { _indentation++; };
void dec() { _indentation--; };
void inc(int n) { _indentation += n; };
void dec(int n) { _indentation -= n; };
int indentation() const { return _indentation; }
void set_indentation(int i) { _indentation = i; }
void fill_to(int col);
void move_to(int col, int slop = 6, int min_space = 2);
// sizing
int width() const { return _width; }
int position() const { return _position; }
int newlines() const { return _newlines; }
julong count() const { return _precount + _position; }
void set_count(julong count) { _precount = count - _position; }
void set_position(int pos) { _position = pos; }
// printing
void print(const char* format, ...) ATTRIBUTE_PRINTF(2, 3);
void print_cr(const char* format, ...) ATTRIBUTE_PRINTF(2, 3);
void vprint(const char *format, va_list argptr) ATTRIBUTE_PRINTF(2, 0);
void vprint_cr(const char* format, va_list argptr) ATTRIBUTE_PRINTF(2, 0);
void print_raw(const char* str) { write(str, strlen(str)); }
void print_raw(const char* str, int len) { write(str, len); }
void print_raw_cr(const char* str) { write(str, strlen(str)); cr(); }
void print_raw_cr(const char* str, int len){ write(str, len); cr(); }
void print_data(void* data, size_t len, bool with_ascii);
void put(char ch);
void sp(int count = 1);
void cr();
void cr_indent();
void bol() { if (_position > 0) cr(); }
// Time stamp
TimeStamp& time_stamp() { return _stamp; }
void stamp();
void stamp(bool guard, const char* prefix, const char* suffix);
void stamp(bool guard) {
stamp(guard, "", ": ");
}
// Date stamp
void date_stamp(bool guard, const char* prefix, const char* suffix);
// A simplified call that includes a suffix of ": "
void date_stamp(bool guard) {
date_stamp(guard, "", ": ");
}
// portable printing of 64 bit integers
void print_jlong(jlong value);
void print_julong(julong value);
// flushing
virtual void flush() {}
virtual void write(const char* str, size_t len) = 0;
virtual void rotate_log(bool force, outputStream* out = NULL) {} // GC log rotation
virtual ~outputStream() {} // close properly on deletion
// Caller may specify their own scratch buffer to use for printing; otherwise,
// an automatic buffer on the stack (with O_BUFLEN len) is used.
void set_scratch_buffer(char* p, size_t len) { _scratch = p; _scratch_len = len; }
void dec_cr() { dec(); cr(); }
void inc_cr() { inc(); cr(); }
};
// standard output
// ANSI C++ name collision
extern outputStream* tty; // tty output
class streamIndentor : public StackObj {
private:
outputStream* _str;
int _amount;
public:
streamIndentor(outputStream* str, int amt = 2) : _str(str), _amount(amt) {
_str->inc(_amount);
}
~streamIndentor() { _str->dec(_amount); }
};
// advisory locking for the shared tty stream:
class ttyLocker: StackObj {
friend class ttyUnlocker;
private:
intx _holder;
public:
static intx hold_tty(); // returns a "holder" token
static void release_tty(intx holder); // must witness same token
static bool release_tty_if_locked(); // returns true if lock was released
static void break_tty_lock_for_safepoint(intx holder);
ttyLocker() { _holder = hold_tty(); }
~ttyLocker() { release_tty(_holder); }
};
// Release the tty lock if it's held and reacquire it if it was
// locked. Used to avoid lock ordering problems.
class ttyUnlocker: StackObj {
private:
bool _was_locked;
public:
ttyUnlocker() {
_was_locked = ttyLocker::release_tty_if_locked();
}
~ttyUnlocker() {
if (_was_locked) {
ttyLocker::hold_tty();
}
}
};
// for writing to strings; buffer will expand automatically
class stringStream : public outputStream {
protected:
char* buffer;
size_t buffer_pos;
size_t buffer_length;
bool buffer_fixed;
DEBUG_ONLY(ResourceMark* rm;)
public:
stringStream(size_t initial_bufsize = 256);
stringStream(char* fixed_buffer, size_t fixed_buffer_size);
~stringStream();
virtual void write(const char* c, size_t len);
size_t size() { return buffer_pos; }
const char* base() { return buffer; }
void reset() { buffer_pos = 0; _precount = 0; _position = 0; }
char* as_string();
};
class fileStream : public outputStream {
protected:
FILE* _file;
bool _need_close;
public:
fileStream() { _file = NULL; _need_close = false; }
fileStream(const char* file_name);
fileStream(const char* file_name, const char* opentype);
fileStream(FILE* file, bool need_close = false) { _file = file; _need_close = need_close; }
~fileStream();
bool is_open() const { return _file != NULL; }
void set_need_close(bool b) { _need_close = b;}
virtual void write(const char* c, size_t len);
size_t read(void *data, size_t size, size_t count) { return ::fread(data, size, count, _file); }
char* readln(char *data, int count);
int eof() { return feof(_file); }
long fileSize();
void rewind() { ::rewind(_file); }
void flush();
};
CDS_ONLY(extern fileStream* classlist_file;)
// unlike fileStream, fdStream does unbuffered I/O by calling
// open() and write() directly. It is async-safe, but output
// from multiple thread may be mixed together. Used by fatal
// error handler.
class fdStream : public outputStream {
protected:
int _fd;
bool _need_close;
public:
fdStream(const char* file_name);
fdStream(int fd = -1) { _fd = fd; _need_close = false; }
~fdStream();
bool is_open() const { return _fd != -1; }
void set_fd(int fd) { _fd = fd; _need_close = false; }
int fd() const { return _fd; }
virtual void write(const char* c, size_t len);
void flush() {};
};
void ostream_init();
void ostream_init_log();
void ostream_exit();
void ostream_abort();
// In the non-fixed buffer case an underlying buffer will be created and
// managed in C heap. Not MT-safe.
class bufferedStream : public outputStream {
protected:
char* buffer;
size_t buffer_pos;
size_t buffer_max;
size_t buffer_length;
bool buffer_fixed;
public:
bufferedStream(size_t initial_bufsize = 256, size_t bufmax = 1024*1024*10);
bufferedStream(char* fixed_buffer, size_t fixed_buffer_size, size_t bufmax = 1024*1024*10);
~bufferedStream();
virtual void write(const char* c, size_t len);
size_t size() { return buffer_pos; }
const char* base() { return buffer; }
void reset() { buffer_pos = 0; _precount = 0; _position = 0; }
char* as_string();
};
#define O_BUFLEN 2000 // max size of output of individual print() methods
#ifndef PRODUCT
class networkStream : public bufferedStream {
private:
int _socket;
public:
networkStream();
~networkStream();
bool connect(const char *host, short port);
bool is_open() const { return _socket != -1; }
int read(char *buf, size_t len);
void close();
virtual void flush();
};
#endif
#endif // SHARE_VM_UTILITIES_OSTREAM_HPP
|
/*
Part of Scallop Transcript Assembler
(c) 2017 by Mingfu Shao, Carl Kingsford, and Carnegie Mellon University.
Part of Altai
(c) 2021 by Xiaofei Carl Zang, Mingfu Shao, and The Pennsylvania State University.
See LICENSE for licensing.
*/
#include <map>
#include <algorithm>
#include <cassert>
#include "gene.h"
int gene::clear()
{
transcripts.clear();
t2i.clear();
return 0;
}
int gene::assign(const vector<transcript> &v)
{
clear();
for(int i = 0; i < v.size(); i++)
{
add_transcript(v[i]);
}
return 0;
}
int gene::add_transcript(const item&e)
{
assert(e.feature == "transcript");
if(t2i.find(e.transcript_id) == t2i.end())
{
t2i.insert(pair<string, int>(e.transcript_id, t2i.size()));
transcripts.push_back(transcript(e));
}
else
{
int k = t2i[e.transcript_id];
transcripts[k].assign(e);
}
return 0;
}
int gene::add_transcript(const transcript &t)
{
assert(t2i.find(t.transcript_id) == t2i.end());
t2i.insert(pair<string, int>(t.transcript_id, t2i.size()));
transcripts.push_back(t);
return 0;
}
int gene::add_exon(const item&e)
{
assert(e.feature == "exon");
if(t2i.find(e.transcript_id) != t2i.end())
{
int k = t2i[e.transcript_id];
transcripts[k].add_exon(e);
}
else
{
transcript t;
t.assign(e);
t.add_exon(e);
add_transcript(t);
}
return 0;
}
int gene::set_gene_id(const string &id)
{
for(int i = 0; i < transcripts.size(); i++)
{
transcripts[i].gene_id = id;
}
return 0;
}
int gene::filter_single_exon_transcripts()
{
vector<transcript> vv;
t2i.clear();
for(int i = 0; i < transcripts.size(); i++)
{
if(transcripts[i].exons.size() <= 1) continue;
t2i.insert(pair<string, int>(transcripts[i].transcript_id, vv.size()));
vv.push_back(transcripts[i]);
}
transcripts = vv;
return 0;
}
int gene::filter_low_coverage_transcripts(double min_coverage)
{
vector<transcript> vv;
t2i.clear();
for(int i = 0; i < transcripts.size(); i++)
{
if(transcripts[i].coverage < min_coverage) continue;
t2i.insert(pair<string, int>(transcripts[i].transcript_id, vv.size()));
vv.push_back(transcripts[i]);
}
transcripts = vv;
return 0;
}
int gene::sort()
{
for(int i = 0; i < transcripts.size(); i++)
{
transcripts[i].sort();
}
return 0;
}
int gene::shrink()
{
for(int i = 0; i < transcripts.size(); i++)
{
transcripts[i].shrink();
}
return 0;
}
int gene::assign_RPKM(double factor)
{
for(int i = 0; i < transcripts.size(); i++)
{
transcripts[i].assign_RPKM(factor);
}
return 0;
}
set<as_pos32> gene::get_exon_boundaries() const
{
set<as_pos32> s;
for(int k = 0; k < transcripts.size(); k++)
{
const vector<PI32> &v = transcripts[k].exons;
for(int i = 0; i < v.size(); i++)
{
as_pos32 l = v[i].first;
as_pos32 r = v[i].second;
s.insert(l);
s.insert(r);
}
}
return s;
}
PI32 gene::get_bounds() const
{
PI32 pp(as_pos32(-1), as_pos32(-1));
for(int k = 0; k < transcripts.size(); k++)
{
PI32 p = transcripts[k].get_bounds();
if(pp.first.p32 == -1 || pp.first.rightto(p.first)) pp.first = p.first;
if(pp.second.p32 == -1 || pp.second.leftto(p.second)) pp.second = p.second;
}
return pp;
}
string gene::get_seqname() const
{
if(transcripts.size() == 0) return "";
else return transcripts[0].seqname;
}
string gene::get_gene_id() const
{
if(transcripts.size() == 0) return "";
else return transcripts[0].gene_id;
}
int gene::write(ofstream &fout) const
{
for(int i = 0; i < transcripts.size(); i++)
{
transcripts[i].write(fout);
}
return 0;
}
|
// Copyright (C) 1994-2020 Free Software Foundation, Inc.
//
// This file is part of GCC.
//
// GCC is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, or (at your option)
// any later version.
// GCC is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// Under Section 7 of GPL version 3, you are granted additional
// permissions described in the GCC Runtime Library Exception, version
// 3.1, as published by the Free Software Foundation.
// You should have received a copy of the GNU General Public License and
// a copy of the GCC Runtime Library Exception along with this program;
// see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
// <http://www.gnu.org/licenses/>.
#include <typeinfo>
namespace std {
bad_typeid::~bad_typeid() _GLIBCXX_USE_NOEXCEPT { }
const char*
bad_typeid::what() const _GLIBCXX_USE_NOEXCEPT
{
return "std::bad_typeid";
}
} // namespace std
|
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2018, STEREOLABS.
//
// All rights reserved.
//
// 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 "zed_wrapper_nodelet.hpp"
#ifndef NDEBUG
#include <ros/console.h>
#endif
#include <rosgraph_msgs/Clock.h>
#include <nav_msgs/Odometry.h>
#include <nav_msgs/Path.h>
#include <sensor_msgs/Imu.h>
#include <sensor_msgs/distortion_models.h>
#include <sensor_msgs/image_encodings.h>
#include <sensor_msgs/point_cloud2_iterator.h>
#include <stereo_msgs/DisparityImage.h>
#include <geometry_msgs/PoseWithCovarianceStamped.h>
#include <tf2_geometry_msgs/tf2_geometry_msgs.h>
using namespace std;
namespace zed_wrapper {
#ifndef DEG2RAD
#define DEG2RAD 0.017453293
#endif
ZEDWrapperNodelet::ZEDWrapperNodelet() : Nodelet() {}
ZEDWrapperNodelet::~ZEDWrapperNodelet() {
if (mDevicePollThread.joinable()) {
mDevicePollThread.join();
}
if (mPcThread.joinable()) {
mPcThread.join();
}
}
void ZEDWrapperNodelet::onInit() {
mStopNode = false;
mPcDataReady = false;
#ifndef NDEBUG
if (ros::console::set_logger_level(ROSCONSOLE_DEFAULT_NAME,
ros::console::levels::Debug)) {
ros::console::notifyLoggerLevelsChanged();
}
#endif
// Launch file parameters
mCamResol = sl::RESOLUTION_HD720;
mCamQuality = sl::DEPTH_MODE_PERFORMANCE;
mCamSensingMode = sl::SENSING_MODE_STANDARD;
mCamFrameRate = 30;
mGpuId = -1;
mZedId = 0;
mZedSerialNumber = 0;
mOdometryDb = "";
mImuPubRate = 100.0;
mPathPubRate = 1.0;
mInitialTrackPose.resize(6);
mOpenniDepthMode = false;
mTrackingReady = false;
for (size_t i = 0; i < 6; i++) {
mInitialTrackPose[i] = 0.0f;
}
mCamMatResizeFactor = 1.0;
mVerbose = true;
mNh = getMTNodeHandle();
mNhNs = getMTPrivateNodeHandle();
// Set default coordinate frames
mNhNs.param<std::string>("pose_frame", mMapFrameId, "map");
mNhNs.param<std::string>("odometry_frame", mOdometryFrameId, "odom");
mNhNs.param<std::string>("base_frame", mBaseFrameId, "base_link");
mNhNs.param<std::string>("camera_frame", mCameraFrameId, "zed_camera_center");
mNhNs.param<std::string>("imu_frame", mImuFrameId, "imu_link");
mNhNs.param<std::string>("left_camera_frame", mLeftCamFrameId,
"left_camera_frame");
mNhNs.param<std::string>("left_camera_optical_frame", mLeftCamOptFrameId,
"left_camera_optical_frame");
mNhNs.param<std::string>("right_camera_frame", mRightCamFrameId,
"right_camera_frame");
mNhNs.param<std::string>("right_camera_optical_frame", mRightCamOptFrameId,
"right_camera_optical_frame");
mDepthFrameId = mLeftCamFrameId;
mDepthOptFrameId = mLeftCamOptFrameId;
// Note: Depth image frame id must match color image frame id
mCloudFrameId = mDepthOptFrameId;
mRgbFrameId = mDepthFrameId;
mRgbOptFrameId = mCloudFrameId;
mDisparityFrameId = mDepthFrameId;
mDisparityOptFrameId = mDepthOptFrameId;
mConfidenceFrameId = mDepthFrameId;
mConfidenceOptFrameId = mDepthOptFrameId;
// Get parameters from launch file
mNhNs.getParam("resolution", mCamResol);
mNhNs.getParam("frame_rate", mCamFrameRate);
checkResolFps();
mNhNs.getParam("verbose", mVerbose);
mNhNs.getParam("quality", mCamQuality);
mNhNs.getParam("sensing_mode", mCamSensingMode);
mNhNs.getParam("openni_depth_mode", mOpenniDepthMode);
mNhNs.getParam("gpu_id", mGpuId);
mNhNs.getParam("zed_id", mZedId);
mNhNs.getParam("depth_stabilization", mDepthStabilization);
int tmp_sn = 0;
mNhNs.getParam("serial_number", tmp_sn);
if (tmp_sn > 0) {
mZedSerialNumber = static_cast<int>(tmp_sn);
}
mNhNs.getParam("camera_model", mZedUserCamModel);
mNhNs.getParam("publish_pose_covariance", mPublishPoseCovariance);
// Publish odometry tf
mNhNs.param<bool>("publish_tf", mPublishTf, true);
mNhNs.param<bool>("publish_map_tf", mPublishMapTf, true);
mNhNs.param<bool>("camera_flip", mCameraFlip, false);
if (mZedSerialNumber > 0) {
NODELET_INFO_STREAM("SN : " << mZedSerialNumber);
}
// Print order frames
NODELET_INFO_STREAM("pose_frame \t\t -> " << mMapFrameId);
NODELET_INFO_STREAM("odometry_frame \t\t -> " << mOdometryFrameId);
NODELET_INFO_STREAM("base_frame \t\t -> " << mBaseFrameId);
NODELET_INFO_STREAM("camera_frame \t\t -> " << mCameraFrameId);
NODELET_INFO_STREAM("imu_link \t\t -> " << mImuFrameId);
NODELET_INFO_STREAM("left_camera_frame \t -> " << mLeftCamFrameId);
NODELET_INFO_STREAM("left_camera_optical_frame -> " << mLeftCamOptFrameId);
NODELET_INFO_STREAM("right_camera_frame \t -> " << mRightCamFrameId);
NODELET_INFO_STREAM("right_camera_optical_frame -> " << mRightCamOptFrameId);
NODELET_INFO_STREAM("depth_frame \t\t -> " << mDepthFrameId);
NODELET_INFO_STREAM("depth_optical_frame \t -> " << mDepthOptFrameId);
NODELET_INFO_STREAM("disparity_frame \t -> " << mDisparityFrameId);
NODELET_INFO_STREAM("disparity_optical_frame -> " << mDisparityOptFrameId);
NODELET_INFO_STREAM("Camera Flip [" << (mCameraFlip ? "TRUE" : "FALSE") << "]");
// Status of odometry TF
NODELET_INFO_STREAM("Broadcasting " << mOdometryFrameId << " [" << (mPublishTf ? "TRUE" : "FALSE") << "]");
// Status of map TF
NODELET_INFO_STREAM("Broadcasting " << mMapFrameId << " [" << ((mPublishTf &&
mPublishMapTf) ? "TRUE" : "FALSE") << "]");
std::string img_topic = "image_rect_color";
std::string img_raw_topic = "image_raw_color";
// Set the default topic names
string left_topic = "left/" + img_topic;
string left_raw_topic = "left/" + img_raw_topic;
string left_cam_info_topic = "left/camera_info";
string left_cam_info_raw_topic = "left/camera_info_raw";
string right_topic = "right/" + img_topic;
string right_raw_topic = "right/" + img_raw_topic;
string right_cam_info_topic = "right/camera_info";
string right_cam_info_raw_topic = "right/camera_info_raw";
string rgb_topic = "rgb/" + img_topic;
string rgb_raw_topic = "rgb/" + img_raw_topic;
string rgb_cam_info_topic = "rgb/camera_info";
string rgb_cam_info_raw_topic = "rgb/camera_info_raw";
string depth_topic = "depth/";
if (mOpenniDepthMode) {
NODELET_INFO_STREAM("Openni depth mode activated");
depth_topic += "depth_raw_registered";
} else {
depth_topic += "depth_registered";
}
string depth_cam_info_topic = "depth/camera_info";
string disparity_topic = "disparity/disparity_image";
string point_cloud_topic = "point_cloud/cloud_registered";
string conf_img_topic = "confidence/confidence_image";
string conf_map_topic = "confidence/confidence_map";
string pose_topic = "pose";
string pose_cov_topic = "pose_with_covariance";
string odometry_topic = "odom";
string odom_path_topic = "path_odom";
string map_path_topic = "path_map";
string imu_topic = "imu/data";
string imu_topic_raw = "imu/data_raw";
mNhNs.getParam("rgb_topic", rgb_topic);
mNhNs.getParam("rgb_raw_topic", rgb_raw_topic);
mNhNs.getParam("rgb_cam_info_topic", rgb_cam_info_topic);
mNhNs.getParam("rgb_cam_info_raw_topic", rgb_cam_info_raw_topic);
mNhNs.getParam("left_topic", left_topic);
mNhNs.getParam("left_raw_topic", left_raw_topic);
mNhNs.getParam("left_cam_info_topic", left_cam_info_topic);
mNhNs.getParam("left_cam_info_raw_topic", left_cam_info_raw_topic);
mNhNs.getParam("right_topic", right_topic);
mNhNs.getParam("right_raw_topic", right_raw_topic);
mNhNs.getParam("right_cam_info_topic", right_cam_info_topic);
mNhNs.getParam("right_cam_info_raw_topic", right_cam_info_raw_topic);
mNhNs.getParam("depth_topic", depth_topic);
mNhNs.getParam("depth_cam_info_topic", depth_cam_info_topic);
mNhNs.getParam("disparity_topic", disparity_topic);
mNhNs.getParam("confidence_img_topic", conf_img_topic);
mNhNs.getParam("confidence_map_topic", conf_map_topic);
mNhNs.getParam("point_cloud_topic", point_cloud_topic);
mNhNs.getParam("pose_topic", pose_topic);
pose_cov_topic = pose_topic + "_with_covariance";
mNhNs.getParam("odometry_topic", odometry_topic);
mNhNs.getParam("imu_topic", imu_topic);
mNhNs.getParam("imu_topic_raw", imu_topic_raw);
mNhNs.getParam("imu_pub_rate", mImuPubRate);
mNhNs.getParam("path_pub_rate", mPathPubRate);
mNhNs.getParam("path_max_count", mPathMaxCount);
if (mPathMaxCount < 2 && mPathMaxCount != -1) {
mPathMaxCount = 2;
}
// Create camera info
sensor_msgs::CameraInfoPtr rgb_cam_info_msg_(new sensor_msgs::CameraInfo());
sensor_msgs::CameraInfoPtr left_cam_info_msg_(new sensor_msgs::CameraInfo());
sensor_msgs::CameraInfoPtr right_cam_info_msg_(new sensor_msgs::CameraInfo());
sensor_msgs::CameraInfoPtr rgb_cam_info_raw_msg_(new sensor_msgs::CameraInfo());
sensor_msgs::CameraInfoPtr left_cam_info_raw_msg_(new sensor_msgs::CameraInfo());
sensor_msgs::CameraInfoPtr right_cam_info_raw_msg_(new sensor_msgs::CameraInfo());
sensor_msgs::CameraInfoPtr depth_cam_info_msg_(new sensor_msgs::CameraInfo());
mRgbCamInfoMsg = rgb_cam_info_msg_;
mLeftCamInfoMsg = left_cam_info_msg_;
mRightCamInfoMsg = right_cam_info_msg_;
mRgbCamInfoRawMsg = rgb_cam_info_raw_msg_;
mLeftCamInfoRawMsg = left_cam_info_raw_msg_;
mRightCamInfoRawMsg = right_cam_info_raw_msg_;
mDepthCamInfoMsg = depth_cam_info_msg_;
// SVO
mNhNs.param<std::string>("svo_filepath", mSvoFilepath, std::string());
// Initialization transformation listener
mTfBuffer.reset(new tf2_ros::Buffer);
mTfListener.reset(new tf2_ros::TransformListener(*mTfBuffer));
// Initialize tf2 transformation
mNhNs.getParam("initial_tracking_pose", mInitialTrackPose);
set_pose(mInitialTrackPose[0], mInitialTrackPose[1], mInitialTrackPose[2],
mInitialTrackPose[3], mInitialTrackPose[4], mInitialTrackPose[5]);
// Try to initialize the ZED
if (!mSvoFilepath.empty()) {
mZedParams.svo_input_filename = mSvoFilepath.c_str();
mZedParams.svo_real_time_mode = true;
// mPubClock = mNh.advertise<rosgraph_msgs::Clock>("/clock", 1);
// NODELET_INFO("Advertised on topic /clock");
mSvoMode = true;
} else {
mZedParams.camera_fps = mCamFrameRate;
mZedParams.camera_resolution = static_cast<sl::RESOLUTION>(mCamResol);
if (mZedSerialNumber == 0) {
mZedParams.camera_linux_id = mZedId;
} else {
bool waiting_for_camera = true;
while (waiting_for_camera) {
// Ctrl+C check
if (!mNhNs.ok()) {
mStopNode = true; // Stops other threads
std::lock_guard<std::mutex> lock(mCloseZedMutex);
NODELET_DEBUG("Closing ZED");
mZed.close();
NODELET_DEBUG("ZED pool thread finished");
return;
}
sl::DeviceProperties prop = sl_tools::getZEDFromSN(mZedSerialNumber);
if (prop.id < -1 ||
prop.camera_state == sl::CAMERA_STATE::CAMERA_STATE_NOT_AVAILABLE) {
std::string msg = "ZED SN" + to_string(mZedSerialNumber) +
" not detected ! Please connect this ZED";
NODELET_INFO_STREAM(msg.c_str());
std::this_thread::sleep_for(std::chrono::milliseconds(2000));
} else {
waiting_for_camera = false;
mZedParams.camera_linux_id = prop.id;
}
}
}
}
std::string ver = sl_tools::getSDKVersion(mVerMajor, mVerMinor, mVerSubMinor);
NODELET_INFO_STREAM("SDK version : " << ver);
#if (ZED_SDK_MAJOR_VERSION<2)
NODELET_WARN_STREAM("Please consider to upgrade to latest SDK version to "
"get better performances");
mZedParams.coordinate_system = sl::COORDINATE_SYSTEM_IMAGE;
NODELET_INFO_STREAM("Camera coordinate system : COORDINATE_SYSTEM_IMAGE");
mIdxX = 2;
mIdxY = 0;
mIdxZ = 1;
mSignX = 1;
mSignY = -1;
mSignZ = -1;
#elif (ZED_SDK_MAJOR_VERSION==2 && ZED_SDK_MINOR_VERSION<5)
NODELET_WARN_STREAM("Please consider to upgrade to latest SDK version to "
"get latest features");
mZedParams.coordinate_system = sl::COORDINATE_SYSTEM_RIGHT_HANDED_Z_UP;
NODELET_INFO_STREAM("Camera coordinate system : COORDINATE_SYSTEM_RIGHT_HANDED_Z_UP");
mIdxX = 1;
mIdxY = 0;
mIdxZ = 2;
mSignX = 1;
mSignY = -1;
mSignZ = 1;
#else
mZedParams.coordinate_system = sl::COORDINATE_SYSTEM_RIGHT_HANDED_Z_UP_X_FWD;
NODELET_INFO_STREAM("Camera coordinate system : COORDINATE_SYSTEM_RIGHT_HANDED_Z_UP_X_FWD");
mIdxX = 0;
mIdxY = 1;
mIdxZ = 2;
mSignX = 1;
mSignY = 1;
mSignZ = 1;
#endif
mZedParams.coordinate_units = sl::UNIT_METER;
mZedParams.depth_mode = static_cast<sl::DEPTH_MODE>(mCamQuality);
mZedParams.sdk_verbose = mVerbose;
mZedParams.sdk_gpu_id = mGpuId;
mZedParams.depth_stabilization = mDepthStabilization;
mZedParams.camera_image_flip = mCameraFlip;
sl::ERROR_CODE err = sl::ERROR_CODE_CAMERA_NOT_DETECTED;
while (err != sl::SUCCESS) {
err = mZed.open(mZedParams);
NODELET_INFO_STREAM(toString(err));
std::this_thread::sleep_for(std::chrono::milliseconds(2000));
if (!mNhNs.ok()) {
mStopNode = true; // Stops other threads
std::lock_guard<std::mutex> lock(mCloseZedMutex);
NODELET_DEBUG("Closing ZED");
mZed.close();
NODELET_DEBUG("ZED pool thread finished");
return;
}
}
mZedRealCamModel = mZed.getCameraInformation().camera_model;
std::string camModelStr = "LAST";
if (mZedRealCamModel == sl::MODEL_ZED) {
camModelStr = "ZED";
if (mZedUserCamModel != 0) {
NODELET_WARN("Camera model does not match user parameter. Please modify "
"the value of the parameter 'camera_model' to 0");
}
} else if (mZedRealCamModel == sl::MODEL_ZED_M) {
camModelStr = "ZED M";
if (mZedUserCamModel != 1) {
NODELET_WARN("Camera model does not match user parameter. Please modify "
"the value of the parameter 'camera_model' to 1");
}
}
NODELET_INFO_STREAM("CAMERA MODEL : " << mZedRealCamModel);
mZedSerialNumber = mZed.getCameraInformation().serial_number;
// Dynamic Reconfigure parameters
mDynRecServer = boost::make_shared<dynamic_reconfigure::Server<zed_wrapper::ZedConfig>>();
dynamic_reconfigure::Server<zed_wrapper::ZedConfig>::CallbackType f;
f = boost::bind(&ZEDWrapperNodelet::dynamicReconfCallback, this, _1, _2);
mDynRecServer->setCallback(f);
mNhNs.getParam("mat_resize_factor", mCamMatResizeFactor);
if (mCamMatResizeFactor < 0.1) {
mCamMatResizeFactor = 0.1;
NODELET_WARN_STREAM(
"Minimum allowed values for 'mat_resize_factor' is 0.1");
}
if (mCamMatResizeFactor > 1.0) {
mCamMatResizeFactor = 1.0;
NODELET_WARN_STREAM(
"Maximum allowed values for 'mat_resize_factor' is 1.0");
}
mNhNs.getParam("confidence", mCamConfidence);
mNhNs.getParam("max_depth", mCamMaxDepth);
mNhNs.getParam("exposure", mCamExposure);
mNhNs.getParam("gain", mCamGain);
mNhNs.getParam("auto_exposure", mCamAutoExposure);
if (mCamAutoExposure) {
mTriggerAutoExposure = true;
}
// Create all the publishers
// Image publishers
image_transport::ImageTransport it_zed(mNh);
mPubRgb = it_zed.advertise(rgb_topic, 1); // rgb
NODELET_INFO_STREAM("Advertised on topic " << rgb_topic);
mPubRawRgb = it_zed.advertise(rgb_raw_topic, 1); // rgb raw
NODELET_INFO_STREAM("Advertised on topic " << rgb_raw_topic);
mPubLeft = it_zed.advertise(left_topic, 1); // left
NODELET_INFO_STREAM("Advertised on topic " << left_topic);
mPubRawLeft = it_zed.advertise(left_raw_topic, 1); // left raw
NODELET_INFO_STREAM("Advertised on topic " << left_raw_topic);
mPubRight = it_zed.advertise(right_topic, 1); // right
NODELET_INFO_STREAM("Advertised on topic " << right_topic);
mPubRawRight = it_zed.advertise(right_raw_topic, 1); // right raw
NODELET_INFO_STREAM("Advertised on topic " << right_raw_topic);
mPubDepth = it_zed.advertise(depth_topic, 1); // depth
NODELET_INFO_STREAM("Advertised on topic " << depth_topic);
mPubConfImg = it_zed.advertise(conf_img_topic, 1); // confidence image
NODELET_INFO_STREAM("Advertised on topic " << conf_img_topic);
// Confidence Map publisher
mPubConfMap = mNh.advertise<sensor_msgs::Image>(conf_map_topic, 1); // confidence map
NODELET_INFO_STREAM("Advertised on topic " << conf_map_topic);
// Disparity publisher
mPubDisparity = mNh.advertise<stereo_msgs::DisparityImage>(disparity_topic, 1);
NODELET_INFO_STREAM("Advertised on topic " << disparity_topic);
// PointCloud publisher
mPubCloud = mNh.advertise<sensor_msgs::PointCloud2>(point_cloud_topic, 1);
NODELET_INFO_STREAM("Advertised on topic " << point_cloud_topic);
// Camera info publishers
mPubRgbCamInfo = mNh.advertise<sensor_msgs::CameraInfo>(rgb_cam_info_topic, 1); // rgb
NODELET_INFO_STREAM("Advertised on topic " << rgb_cam_info_topic);
mPubLeftCamInfo = mNh.advertise<sensor_msgs::CameraInfo>(left_cam_info_topic, 1); // left
NODELET_INFO_STREAM("Advertised on topic " << left_cam_info_topic);
mPubRightCamInfo = mNh.advertise<sensor_msgs::CameraInfo>(right_cam_info_topic, 1); // right
NODELET_INFO_STREAM("Advertised on topic " << right_cam_info_topic);
mPubDepthCamInfo = mNh.advertise<sensor_msgs::CameraInfo>(depth_cam_info_topic, 1); // depth
NODELET_INFO_STREAM("Advertised on topic " << depth_cam_info_topic);
// Raw
mPubRgbCamInfoRaw = mNh.advertise<sensor_msgs::CameraInfo>(rgb_cam_info_raw_topic, 1); // raw rgb
NODELET_INFO_STREAM("Advertised on topic " << rgb_cam_info_raw_topic);
mPubLeftCamInfoRaw = mNh.advertise<sensor_msgs::CameraInfo>(left_cam_info_raw_topic, 1); // raw left
NODELET_INFO_STREAM("Advertised on topic " << left_cam_info_raw_topic);
mPubRightCamInfoRaw = mNh.advertise<sensor_msgs::CameraInfo>(right_cam_info_raw_topic, 1); // raw right
NODELET_INFO_STREAM("Advertised on topic " << right_cam_info_raw_topic);
// Odometry and Map publisher
mPubPose = mNh.advertise<geometry_msgs::PoseStamped>(pose_topic, 1);
NODELET_INFO_STREAM("Advertised on topic " << pose_topic);
if (mPublishPoseCovariance) {
mPubPoseCov = mNh.advertise<geometry_msgs::PoseWithCovarianceStamped>(pose_cov_topic, 1);
NODELET_INFO_STREAM("Advertised on topic " << pose_cov_topic);
}
mPubOdom = mNh.advertise<nav_msgs::Odometry>(odometry_topic, 1);
NODELET_INFO_STREAM("Advertised on topic " << odometry_topic);
// Camera Path
if (mPathPubRate > 0) {
mPubOdomPath = mNh.advertise<nav_msgs::Path>(odom_path_topic, 1, true);
NODELET_INFO_STREAM("Advertised on topic " << odom_path_topic);
mPubMapPath = mNh.advertise<nav_msgs::Path>(map_path_topic, 1, true);
NODELET_INFO_STREAM("Advertised on topic " << map_path_topic);
mPathTimer = mNhNs.createTimer(ros::Duration(1.0 / mPathPubRate),
&ZEDWrapperNodelet::pathPubCallback, this);
if (mPathMaxCount != -1) {
NODELET_DEBUG_STREAM("Path vectors reserved " << mPathMaxCount << " poses.");
mOdomPath.reserve(mPathMaxCount);
mMapPath.reserve(mPathMaxCount);
NODELET_DEBUG_STREAM("Path vector sizes: " << mOdomPath.size() << " " << mMapPath.size());
}
} else {
NODELET_INFO_STREAM("Path topics not published -> mPathPubRate: " << mPathPubRate);
}
// Imu publisher
if (mImuPubRate > 0 && mZedRealCamModel == sl::MODEL_ZED_M) {
mPubImu = mNh.advertise<sensor_msgs::Imu>(imu_topic, 500);
NODELET_INFO_STREAM("Advertised on topic " << imu_topic << " @ "
<< mImuPubRate << " Hz");
mPubImuRaw = mNh.advertise<sensor_msgs::Imu>(imu_topic_raw, 500);
NODELET_INFO_STREAM("Advertised on topic " << imu_topic_raw << " @ "
<< mImuPubRate << " Hz");
mFrameTimestamp = ros::Time::now();
mImuTimer = mNhNs.createTimer(ros::Duration(1.0 / mImuPubRate),
&ZEDWrapperNodelet::imuPubCallback, this);
} else if (mImuPubRate > 0 && mZedRealCamModel == sl::MODEL_ZED) {
NODELET_WARN_STREAM(
"'imu_pub_rate' set to "
<< mImuPubRate << " Hz"
<< " but ZED camera model does not support IMU data publishing.");
}
// Services
mSrvSetInitPose = mNh.advertiseService("set_initial_pose", &ZEDWrapperNodelet::on_set_pose, this);
mSrvResetOdometry = mNh.advertiseService("reset_odometry", &ZEDWrapperNodelet::on_reset_odometry, this);
mSrvResetTracking = mNh.advertiseService("reset_tracking", &ZEDWrapperNodelet::on_reset_tracking, this);
// Start Pointcloud thread
mPcThread = std::thread(&ZEDWrapperNodelet::pointcloud_thread_func, this);
// Start pool thread
mDevicePollThread = std::thread(&ZEDWrapperNodelet::device_poll_thread_func, this);
}
void ZEDWrapperNodelet::checkResolFps() {
switch (mCamResol) {
case sl::RESOLUTION_HD2K:
if (mCamFrameRate != 15) {
NODELET_WARN_STREAM("Wrong FrameRate ("
<< mCamFrameRate
<< ") for the resolution HD2K. Set to 15 FPS.");
mCamFrameRate = 15;
}
break;
case sl::RESOLUTION_HD1080:
if (mCamFrameRate == 15 || mCamFrameRate == 30) {
break;
}
if (mCamFrameRate > 15 && mCamFrameRate < 30) {
NODELET_WARN_STREAM("Wrong FrameRate ("
<< mCamFrameRate
<< ") for the resolution HD1080. Set to 15 FPS.");
mCamFrameRate = 15;
} else if (mCamFrameRate > 30) {
NODELET_WARN_STREAM("Wrong FrameRate ("
<< mCamFrameRate
<< ") for the resolution HD1080. Set to 30 FPS.");
mCamFrameRate = 30;
} else {
NODELET_WARN_STREAM("Wrong FrameRate ("
<< mCamFrameRate
<< ") for the resolution HD1080. Set to 15 FPS.");
mCamFrameRate = 15;
}
break;
case sl::RESOLUTION_HD720:
if (mCamFrameRate == 15 || mCamFrameRate == 30 || mCamFrameRate == 60) {
break;
}
if (mCamFrameRate > 15 && mCamFrameRate < 30) {
NODELET_WARN_STREAM("Wrong FrameRate ("
<< mCamFrameRate
<< ") for the resolution HD720. Set to 15 FPS.");
mCamFrameRate = 15;
} else if (mCamFrameRate > 30 && mCamFrameRate < 60) {
NODELET_WARN_STREAM("Wrong FrameRate ("
<< mCamFrameRate
<< ") for the resolution HD720. Set to 30 FPS.");
mCamFrameRate = 30;
} else if (mCamFrameRate > 60) {
NODELET_WARN_STREAM("Wrong FrameRate ("
<< mCamFrameRate
<< ") for the resolution HD720. Set to 60 FPS.");
mCamFrameRate = 60;
} else {
NODELET_WARN_STREAM("Wrong FrameRate ("
<< mCamFrameRate
<< ") for the resolution HD720. Set to 15 FPS.");
mCamFrameRate = 15;
}
break;
case sl::RESOLUTION_VGA:
if (mCamFrameRate == 15 || mCamFrameRate == 30 || mCamFrameRate == 60 ||
mCamFrameRate == 100) {
break;
}
if (mCamFrameRate > 15 && mCamFrameRate < 30) {
NODELET_WARN_STREAM("Wrong FrameRate ("
<< mCamFrameRate
<< ") for the resolution VGA. Set to 15 FPS.");
mCamFrameRate = 15;
} else if (mCamFrameRate > 30 && mCamFrameRate < 60) {
NODELET_WARN_STREAM("Wrong FrameRate ("
<< mCamFrameRate
<< ") for the resolution VGA. Set to 30 FPS.");
mCamFrameRate = 30;
} else if (mCamFrameRate > 60 && mCamFrameRate < 100) {
NODELET_WARN_STREAM("Wrong FrameRate ("
<< mCamFrameRate
<< ") for the resolution VGA. Set to 60 FPS.");
mCamFrameRate = 60;
} else if (mCamFrameRate > 100) {
NODELET_WARN_STREAM("Wrong FrameRate ("
<< mCamFrameRate
<< ") for the resolution VGA. Set to 100 FPS.");
mCamFrameRate = 100;
} else {
NODELET_WARN_STREAM("Wrong FrameRate ("
<< mCamFrameRate
<< ") for the resolution VGA. Set to 15 FPS.");
mCamFrameRate = 15;
}
break;
default:
NODELET_WARN_STREAM("Invalid resolution. Set to HD720 @ 30 FPS");
mCamResol = 2;
mCamFrameRate = 30;
}
}
void ZEDWrapperNodelet::initTransforms() {
// >>>>> Dynamic transforms
mBase2OdomTransf.setIdentity();
mOdom2MapTransf.setIdentity();
// <<<<< Dynamic transforms
// >>>>> Static transforms
// Sensor to Base link
try {
// Save the transformation from base to frame
geometry_msgs::TransformStamped s2b =
mTfBuffer->lookupTransform(mBaseFrameId, mDepthFrameId, mFrameTimestamp);
// Get the TF2 transformation
tf2::fromMsg(s2b.transform, mSensor2BaseTransf);
} catch (tf2::TransformException& ex) {
NODELET_WARN_THROTTLE(
10.0, "The tf from '%s' to '%s' does not seem to be available, "
"will assume it as identity!",
mDepthFrameId.c_str(), mBaseFrameId.c_str());
NODELET_DEBUG("Transform error: %s", ex.what());
mSensor2BaseTransf.setIdentity();
}
// <<<<< Static transforms
}
void ZEDWrapperNodelet::set_pose(float xt, float yt, float zt, float rr,
float pr, float yr) {
// ROS pose
tf2::Quaternion q;
q.setRPY(rr, pr, yr);
//tf2::Vector3 orig(xt, yt, zt);
// mBase2OdomTransf.setOrigin(orig);
// mBase2OdomTransf.setRotation(q);
// mOdom2MapTransf.setIdentity();
initTransforms();
// SL pose
sl::float4 q_vec;
q_vec[0] = q.x();
q_vec[1] = q.y();
q_vec[2] = q.z();
q_vec[3] = q.w();
sl::Orientation r(q_vec);
mInitialPoseSl.setTranslation(sl::Translation(xt, yt, zt));
mInitialPoseSl.setOrientation(r);
}
bool ZEDWrapperNodelet::on_set_pose(
zed_wrapper::set_initial_pose::Request& req,
zed_wrapper::set_initial_pose::Response& res) {
mInitialTrackPose.resize(6);
mInitialTrackPose[0] = req.x;
mInitialTrackPose[1] = req.y;
mInitialTrackPose[2] = req.z;
mInitialTrackPose[3] = req.R;
mInitialTrackPose[4] = req.P;
mInitialTrackPose[5] = req.Y;
set_pose(mInitialTrackPose[0], mInitialTrackPose[1], mInitialTrackPose[2],
mInitialTrackPose[3], mInitialTrackPose[4], mInitialTrackPose[5]);
if (mTrackingActivated) {
mZed.resetTracking(mInitialPoseSl);
}
res.done = true;
return true;
}
bool ZEDWrapperNodelet::on_reset_tracking(
zed_wrapper::reset_tracking::Request& req,
zed_wrapper::reset_tracking::Response& res) {
if (!mTrackingActivated) {
res.reset_done = false;
return false;
}
mNhNs.getParam("initial_tracking_pose", mInitialTrackPose);
if (mInitialTrackPose.size() != 6) {
NODELET_WARN_STREAM("Invalid Initial Pose size (" << mInitialTrackPose.size()
<< "). Using Identity");
mInitialPoseSl.setIdentity();
initTransforms();
} else {
set_pose(mInitialTrackPose[0], mInitialTrackPose[1], mInitialTrackPose[2],
mInitialTrackPose[3], mInitialTrackPose[4], mInitialTrackPose[5]);
}
if (mZed.resetTracking(mInitialPoseSl) == sl::SUCCESS) {
return true;
}
return false;
}
bool ZEDWrapperNodelet::on_reset_odometry(
zed_wrapper::reset_odometry::Request& req,
zed_wrapper::reset_odometry::Response& res) {
mResetOdom = true;
res.reset_done = true;
return true;
}
void ZEDWrapperNodelet::start_tracking() {
NODELET_INFO_STREAM("*** Starting Positional Tracking ***");
mNhNs.getParam("odometry_DB", mOdometryDb);
mNhNs.getParam("pose_smoothing", mPoseSmoothing);
mNhNs.getParam("spatial_memory", mSpatialMemory);
mNhNs.getParam("floor_alignment", mFloorAlignment);
mNhNs.getParam("init_odom_with_first_valid_pose", mInitOdomWithPose);
NODELET_INFO_STREAM("Init Odometry with first valid pose data : " << (mInitOdomWithPose ? "ENABLED" : "DISABLED"));
if (mInitialTrackPose.size() != 6) {
NODELET_WARN_STREAM("Invalid Initial Pose size (" << mInitialTrackPose.size()
<< "). Using Identity");
mInitialPoseSl.setIdentity();
initTransforms();
} else {
set_pose(mInitialTrackPose[0], mInitialTrackPose[1], mInitialTrackPose[2],
mInitialTrackPose[3], mInitialTrackPose[4], mInitialTrackPose[5]);
}
if (mOdometryDb != "" && !sl_tools::file_exist(mOdometryDb)) {
mOdometryDb = "";
NODELET_WARN("odometry_DB path doesn't exist or is unreachable.");
}
// Tracking parameters
sl::TrackingParameters trackParams;
trackParams.area_file_path = mOdometryDb.c_str();
trackParams.enable_pose_smoothing = mPoseSmoothing;
NODELET_INFO_STREAM("Pose Smoothing : " << (trackParams.enable_pose_smoothing ? "ENABLED" : "DISABLED"));
trackParams.enable_spatial_memory = mSpatialMemory;
NODELET_INFO_STREAM("Spatial Memory : " << (trackParams.enable_spatial_memory ? "ENABLED" : "DISABLED"));
trackParams.initial_world_transform = mInitialPoseSl;
#if ((ZED_SDK_MAJOR_VERSION>2) || (ZED_SDK_MAJOR_VERSION==2 && ZED_SDK_MINOR_VERSION>=6))
trackParams.set_floor_as_origin = mFloorAlignment;
NODELET_INFO_STREAM("Floor Alignment : " << (trackParams.set_floor_as_origin ? "ENABLED" : "DISABLED"));
#else
if (mFloorAlignment) {
NODELET_WARN("Floor Alignment is available with ZED SDK >= v2.6");
}
#endif
mZed.enableTracking(trackParams);
mTrackingActivated = true;
NODELET_INFO("Tracking ENABLED");
}
void ZEDWrapperNodelet::publishOdom(tf2::Transform base2odomTransf, sl::Pose& slPose, ros::Time t) {
nav_msgs::Odometry odom;
odom.header.stamp = t;
odom.header.frame_id = mPublishMapTf ? mMapFrameId : mOdometryFrameId; // frame
odom.child_frame_id = mBaseFrameId; // camera_frame
// conversion from Tranform to message
geometry_msgs::Transform base2odom = tf2::toMsg(base2odomTransf);
// Add all value in odometry message
odom.pose.pose.position.x = base2odom.translation.x;
odom.pose.pose.position.y = base2odom.translation.y;
odom.pose.pose.position.z = base2odom.translation.z;
odom.pose.pose.orientation.x = base2odom.rotation.x;
odom.pose.pose.orientation.y = base2odom.rotation.y;
odom.pose.pose.orientation.z = base2odom.rotation.z;
odom.pose.pose.orientation.w = base2odom.rotation.w;
// >>>>> Odometry pose covariance if available
#if ((ZED_SDK_MAJOR_VERSION>2) || (ZED_SDK_MAJOR_VERSION==2 && ZED_SDK_MINOR_VERSION>=6))
if (!mSpatialMemory && mPublishPoseCovariance) {
for (size_t i = 0; i < odom.pose.covariance.size(); i++) {
// odom.pose.covariance[i] = static_cast<double>(slPose.pose_covariance[i]); // TODO USE THIS WHEN STEP BY STEP COVARIANCE WILL BE AVAILABLE IN CAMERA_FRAME
odom.pose.covariance[i] = static_cast<double>(mLastZedPose.pose_covariance[i]);
}
}
#endif
// <<<<< Odometry pose covariance if available
// Publish odometry message
mPubOdom.publish(odom);
}
void ZEDWrapperNodelet::publishPose(ros::Time t) {
tf2::Transform base_pose;
base_pose.setIdentity();
if (mPublishMapTf) {
// Look up the transformation from base frame to map
try {
// Save the transformation from base to frame
geometry_msgs::TransformStamped b2m =
mTfBuffer->lookupTransform(mMapFrameId, mBaseFrameId, ros::Time(0));
// Get the TF2 transformation
tf2::fromMsg(b2m.transform, base_pose);
} catch (tf2::TransformException& ex) {
NODELET_WARN_THROTTLE(
10.0, "The tf from '%s' to '%s' does not seem to be available, "
"will assume it as identity!",
mBaseFrameId.c_str(), mMapFrameId.c_str());
NODELET_DEBUG("Transform error: %s", ex.what());
}
} else if (mPublishTf) {
// Look up the transformation from base frame to odom frame
try {
// Save the transformation from base to frame
geometry_msgs::TransformStamped b2o =
mTfBuffer->lookupTransform(mOdometryFrameId, mBaseFrameId, ros::Time(0));
// Get the TF2 transformation
tf2::fromMsg(b2o.transform, base_pose);
} catch (tf2::TransformException& ex) {
NODELET_WARN_THROTTLE(
10.0, "The tf from '%s' to '%s' does not seem to be available, "
"will assume it as identity!",
mBaseFrameId.c_str(), mOdometryFrameId.c_str());
NODELET_DEBUG("Transform error: %s", ex.what());
}
}
std_msgs::Header header;
header.stamp = mFrameTimestamp;
header.frame_id = mPublishMapTf ? mMapFrameId : mOdometryFrameId; // frame
geometry_msgs::Pose pose;
if (mPublishTf) {
// conversion from Tranform to message
geometry_msgs::Transform base2frame = tf2::toMsg(base_pose);
// Add all value in Pose message
pose.position.x = base2frame.translation.x;
pose.position.y = base2frame.translation.y;
pose.position.z = base2frame.translation.z;
pose.orientation.x = base2frame.rotation.x;
pose.orientation.y = base2frame.rotation.y;
pose.orientation.z = base2frame.rotation.z;
pose.orientation.w = base2frame.rotation.w;
} else {
sl::Translation translation = mLastZedPose.getTranslation();
sl::Orientation quat = mLastZedPose.getOrientation();
pose.position.x = mSignX * translation(mIdxX);
pose.position.y = mSignY * translation(mIdxY);
pose.position.z = mSignZ * translation(mIdxZ);
pose.orientation.x = mSignX * quat(mIdxX);
pose.orientation.y = mSignY * quat(mIdxY);
pose.orientation.z = mSignZ * quat(mIdxZ);
pose.orientation.w = quat(3);
}
if (mPubPose.getNumSubscribers() > 0) {
geometry_msgs::PoseStamped poseNoCov;
poseNoCov.header = header;
poseNoCov.pose = pose;
// Publish pose stamped message
mPubPose.publish(poseNoCov);
}
if (mPublishPoseCovariance) {
if (mPubPoseCov.getNumSubscribers() > 0) {
geometry_msgs::PoseWithCovarianceStamped poseCov;
poseCov.header = header;
poseCov.pose.pose = pose;
// >>>>> Odometry pose covariance if available
#if ((ZED_SDK_MAJOR_VERSION>2) || (ZED_SDK_MAJOR_VERSION==2 && ZED_SDK_MINOR_VERSION>=6))
if (!mSpatialMemory) {
for (size_t i = 0; i < poseCov.pose.covariance.size(); i++) {
// odom.pose.covariance[i] = static_cast<double>(slPose.pose_covariance[i]); // TODO USE THIS WHEN STEP BY STEP COVARIANCE WILL BE AVAILABLE IN CAMERA_FRAME
poseCov.pose.covariance[i] = static_cast<double>(mLastZedPose.pose_covariance[i]);
}
}
#endif
// <<<<< Odometry pose covariance if available
// Publish pose with covariance stamped message
mPubPoseCov.publish(poseCov);
}
}
}
void ZEDWrapperNodelet::publishOdomFrame(tf2::Transform odomTransf, ros::Time t) {
geometry_msgs::TransformStamped transformStamped;
transformStamped.header.stamp = t;
transformStamped.header.frame_id = mOdometryFrameId;
transformStamped.child_frame_id = mBaseFrameId;
// conversion from Tranform to message
transformStamped.transform = tf2::toMsg(odomTransf);
// Publish transformation
mTransformOdomBroadcaster.sendTransform(transformStamped);
}
void ZEDWrapperNodelet::publishPoseFrame(tf2::Transform baseTransform, ros::Time t) {
geometry_msgs::TransformStamped transformStamped;
transformStamped.header.stamp = t;
transformStamped.header.frame_id = mMapFrameId;
transformStamped.child_frame_id = mOdometryFrameId;
// conversion from Tranform to message
transformStamped.transform = tf2::toMsg(baseTransform);
// Publish transformation
mTransformPoseBroadcaster.sendTransform(transformStamped);
}
void ZEDWrapperNodelet::publishImuFrame(tf2::Transform imuTransform, ros::Time t) {
geometry_msgs::TransformStamped transformStamped;
transformStamped.header.stamp = t;
transformStamped.header.frame_id = mCameraFrameId;
transformStamped.child_frame_id = mImuFrameId;
// conversion from Tranform to message
transformStamped.transform = tf2::toMsg(imuTransform);
// Publish transformation
mTransformImuBroadcaster.sendTransform(transformStamped);
}
void ZEDWrapperNodelet::publishImage(sl::Mat img,
image_transport::Publisher& pubImg,
string imgFrameId, ros::Time t) {
pubImg.publish(sl_tools::imageToROSmsg(img, imgFrameId, t));
}
void ZEDWrapperNodelet::publishDepth(sl::Mat depth, ros::Time t) {
if (!mOpenniDepthMode) {
mPubDepth.publish(sl_tools::imageToROSmsg(depth, mDepthOptFrameId, t));
return;
}
// OPENNI CONVERSION (meter -> millimeters - float32 -> uint16)
sensor_msgs::ImagePtr depthMessage = boost::make_shared<sensor_msgs::Image>();
depthMessage->header.stamp = t;
depthMessage->header.frame_id = mDepthOptFrameId;
depthMessage->height = depth.getHeight();
depthMessage->width = depth.getWidth();
int num = 1; // for endianness detection
depthMessage->is_bigendian = !(*(char*)&num == 1);
depthMessage->step = depthMessage->width * sizeof(uint16_t);
depthMessage->encoding = sensor_msgs::image_encodings::MONO16;
size_t size = depthMessage->step * depthMessage->height;
depthMessage->data.resize(size);
uint16_t* data = (uint16_t*)(&depthMessage->data[0]);
int dataSize = depthMessage->width * depthMessage->height;
sl::float1* depthDataPtr = depth.getPtr<sl::float1>();
for (int i = 0; i < dataSize; i++) {
*(data++) = static_cast<uint16_t>(std::round(*(depthDataPtr++) * 1000)); // in mm, rounded
}
mPubDepth.publish(depthMessage);
}
void ZEDWrapperNodelet::publishDisparity(sl::Mat disparity, ros::Time t) {
sl::CameraInformation zedParam =
mZed.getCameraInformation(sl::Resolution(mMatWidth, mMatHeight));
sensor_msgs::ImagePtr disparity_image = sl_tools::imageToROSmsg(disparity, mDisparityFrameId, t);
stereo_msgs::DisparityImage msg;
msg.image = *disparity_image;
msg.header = msg.image.header;
msg.f = zedParam.calibration_parameters.left_cam.fx;
msg.T = zedParam.calibration_parameters.T.x;
msg.min_disparity = msg.f * msg.T / mZed.getDepthMaxRangeValue();
msg.max_disparity = msg.f * msg.T / mZed.getDepthMinRangeValue();
mPubDisparity.publish(msg);
}
void ZEDWrapperNodelet::pointcloud_thread_func() {
std::unique_lock<std::mutex> lock(mPcMutex);
while (!mStopNode) {
while (!mPcDataReady) { // loop to avoid spurious wakeups
if (mPcDataReadyCondVar.wait_for(lock, std::chrono::milliseconds(500)) == std::cv_status::timeout) {
// Check thread stopping
if (mStopNode) {
return;
} else {
continue;
}
}
}
publishPointCloud();
mPcDataReady = false;
}
NODELET_DEBUG("Pointcloud thread finished");
}
void ZEDWrapperNodelet::publishPointCloud() {
// Initialize Point Cloud message
// https://github.com/ros/common_msgs/blob/jade-devel/sensor_msgs/include/sensor_msgs/point_cloud2_iterator.h
int ptsCount = mMatWidth * mMatHeight;
mPointcloudMsg.header.stamp = mPointCloudTime;
if (mPointcloudMsg.width != mMatWidth || mPointcloudMsg.height != mMatHeight) {
mPointcloudMsg.header.frame_id = mPointCloudFrameId; // Set the header values of the ROS message
mPointcloudMsg.is_bigendian = false;
mPointcloudMsg.is_dense = false;
mPointcloudMsg.width = mMatWidth;
mPointcloudMsg.height = mMatHeight;
sensor_msgs::PointCloud2Modifier modifier(mPointcloudMsg);
modifier.setPointCloud2Fields(4,
"x", 1, sensor_msgs::PointField::FLOAT32,
"y", 1, sensor_msgs::PointField::FLOAT32,
"z", 1, sensor_msgs::PointField::FLOAT32,
"rgb", 1, sensor_msgs::PointField::FLOAT32);
}
// Data copy
sl::Vector4<float>* cpu_cloud = mCloud.getPtr<sl::float4>();
float* ptCloudPtr = (float*)(&mPointcloudMsg.data[0]);
#if ((ZED_SDK_MAJOR_VERSION>2) || (ZED_SDK_MAJOR_VERSION==2 && ZED_SDK_MINOR_VERSION>=5) )
memcpy(ptCloudPtr, (float*)cpu_cloud,
4 * ptsCount * sizeof(float)); // We can do a direct memcpy since data organization is the same
#else
#pragma omp parallel for
for (size_t i = 0; i < ptsCount; ++i) {
ptCloudPtr[i * 4 + 0] = mSignX * cpu_cloud[i][mIdxX];
ptCloudPtr[i * 4 + 1] = mSignY * cpu_cloud[i][mIdxY];
ptCloudPtr[i * 4 + 2] = mSignZ * cpu_cloud[i][mIdxZ];
ptCloudPtr[i * 4 + 3] = cpu_cloud[i][3];
}
#endif
// Pointcloud publishing
mPubCloud.publish(mPointcloudMsg);
}
void ZEDWrapperNodelet::publishCamInfo(sensor_msgs::CameraInfoPtr camInfoMsg,
ros::Publisher pubCamInfo, ros::Time t) {
static int seq = 0;
camInfoMsg->header.stamp = t;
camInfoMsg->header.seq = seq;
pubCamInfo.publish(camInfoMsg);
seq++;
}
void ZEDWrapperNodelet::fillCamInfo(sl::Camera& zed, sensor_msgs::CameraInfoPtr leftCamInfoMsg,
sensor_msgs::CameraInfoPtr rightCamInfoMsg, string leftFrameId,
string rightFrameId, bool rawParam /*= false*/) {
sl::CalibrationParameters zedParam;
if (rawParam) {
zedParam = zed.getCameraInformation(sl::Resolution(mMatWidth, mMatHeight))
.calibration_parameters_raw;
} else {
zedParam = zed.getCameraInformation(sl::Resolution(mMatWidth, mMatHeight))
.calibration_parameters;
}
float baseline = zedParam.T[0];
leftCamInfoMsg->distortion_model =
sensor_msgs::distortion_models::PLUMB_BOB;
rightCamInfoMsg->distortion_model =
sensor_msgs::distortion_models::PLUMB_BOB;
leftCamInfoMsg->D.resize(5);
rightCamInfoMsg->D.resize(5);
leftCamInfoMsg->D[0] = zedParam.left_cam.disto[0]; // k1
leftCamInfoMsg->D[1] = zedParam.left_cam.disto[1]; // k2
leftCamInfoMsg->D[2] = zedParam.left_cam.disto[4]; // k3
leftCamInfoMsg->D[3] = zedParam.left_cam.disto[2]; // p1
leftCamInfoMsg->D[4] = zedParam.left_cam.disto[3]; // p2
rightCamInfoMsg->D[0] = zedParam.right_cam.disto[0]; // k1
rightCamInfoMsg->D[1] = zedParam.right_cam.disto[1]; // k2
rightCamInfoMsg->D[2] = zedParam.right_cam.disto[4]; // k3
rightCamInfoMsg->D[3] = zedParam.right_cam.disto[2]; // p1
rightCamInfoMsg->D[4] = zedParam.right_cam.disto[3]; // p2
leftCamInfoMsg->K.fill(0.0);
rightCamInfoMsg->K.fill(0.0);
leftCamInfoMsg->K[0] = static_cast<double>(zedParam.left_cam.fx);
leftCamInfoMsg->K[2] = static_cast<double>(zedParam.left_cam.cx);
leftCamInfoMsg->K[4] = static_cast<double>(zedParam.left_cam.fy);
leftCamInfoMsg->K[5] = static_cast<double>(zedParam.left_cam.cy);
leftCamInfoMsg->K[8] = 1.0;
rightCamInfoMsg->K[0] = static_cast<double>(zedParam.right_cam.fx);
rightCamInfoMsg->K[2] = static_cast<double>(zedParam.right_cam.cx);
rightCamInfoMsg->K[4] = static_cast<double>(zedParam.right_cam.fy);
rightCamInfoMsg->K[5] = static_cast<double>(zedParam.right_cam.cy);
rightCamInfoMsg->K[8] = 1.0;
leftCamInfoMsg->R.fill(0.0);
rightCamInfoMsg->R.fill(0.0);
for (size_t i = 0; i < 3; i++) {
// identity
rightCamInfoMsg->R[i + i * 3] = 1;
leftCamInfoMsg->R[i + i * 3] = 1;
}
if (rawParam) {
std::vector<float> R_ = sl_tools::convertRodrigues(zedParam.R);
float* p = R_.data();
for (int i = 0; i < 9; i++) {
rightCamInfoMsg->R[i] = p[i];
}
}
leftCamInfoMsg->P.fill(0.0);
rightCamInfoMsg->P.fill(0.0);
leftCamInfoMsg->P[0] = static_cast<double>(zedParam.left_cam.fx);
leftCamInfoMsg->P[2] = static_cast<double>(zedParam.left_cam.cx);
leftCamInfoMsg->P[5] = static_cast<double>(zedParam.left_cam.fy);
leftCamInfoMsg->P[6] = static_cast<double>(zedParam.left_cam.cy);
leftCamInfoMsg->P[10] = 1.0;
// http://docs.ros.org/api/sensor_msgs/html/msg/CameraInfo.html
rightCamInfoMsg->P[3] = static_cast<double>(-1 * zedParam.left_cam.fx * baseline);
rightCamInfoMsg->P[0] = static_cast<double>(zedParam.right_cam.fx);
rightCamInfoMsg->P[2] = static_cast<double>(zedParam.right_cam.cx);
rightCamInfoMsg->P[5] = static_cast<double>(zedParam.right_cam.fy);
rightCamInfoMsg->P[6] = static_cast<double>(zedParam.right_cam.cy);
rightCamInfoMsg->P[10] = 1.0;
leftCamInfoMsg->width = rightCamInfoMsg->width = static_cast<uint32_t>(mMatWidth);
leftCamInfoMsg->height = rightCamInfoMsg->height = static_cast<uint32_t>(mMatHeight);
leftCamInfoMsg->header.frame_id = leftFrameId;
rightCamInfoMsg->header.frame_id = rightFrameId;
}
void ZEDWrapperNodelet::dynamicReconfCallback(zed_wrapper::ZedConfig& config,
uint32_t level) {
switch (level) {
case 0:
mCamConfidence = config.confidence;
NODELET_INFO("Reconfigure confidence : %d", mCamConfidence);
break;
case 1:
mCamExposure = config.exposure;
NODELET_INFO("Reconfigure exposure : %d", mCamExposure);
break;
case 2:
mCamGain = config.gain;
NODELET_INFO("Reconfigure gain : %d", mCamGain);
break;
case 3:
mCamAutoExposure = config.auto_exposure;
if (mCamAutoExposure) {
mTriggerAutoExposure = true;
}
NODELET_INFO("Reconfigure auto control of exposure and gain : %s",
mCamAutoExposure ? "Enable" : "Disable");
break;
case 4:
mCamMatResizeFactor = config.mat_resize_factor;
NODELET_INFO("Reconfigure mat_resize_factor: %g", mCamMatResizeFactor);
mCamDataMutex.lock();
mMatWidth = static_cast<size_t>(mCamWidth * mCamMatResizeFactor);
mMatHeight = static_cast<size_t>(mCamHeight * mCamMatResizeFactor);
NODELET_DEBUG_STREAM("Data Mat size : " << mMatWidth << "x" << mMatHeight);
// Update Camera Info
fillCamInfo(mZed, mLeftCamInfoMsg, mRightCamInfoMsg, mLeftCamOptFrameId,
mRightCamOptFrameId);
fillCamInfo(mZed, mLeftCamInfoRawMsg, mRightCamInfoRawMsg, mLeftCamOptFrameId,
mRightCamOptFrameId, true);
mRgbCamInfoMsg = mDepthCamInfoMsg = mLeftCamInfoMsg; // the reference camera is
// the Left one (next to
// the ZED logo)
mRgbCamInfoRawMsg = mLeftCamInfoRawMsg;
mCamDataMutex.unlock();
break;
case 5:
mCamMaxDepth = config.max_depth;
NODELET_INFO("Reconfigure max depth : %g", mCamMaxDepth);
break;
}
}
void ZEDWrapperNodelet::pathPubCallback(const ros::TimerEvent& e) {
uint32_t mapPathSub = mPubMapPath.getNumSubscribers();
uint32_t odomPathSub = mPubOdomPath.getNumSubscribers();
tf2::Transform base_to_odom;
base_to_odom.setIdentity();
tf2::Transform base_to_map;
base_to_map.setIdentity();
// Look up the transformation from base frame to odom
if (mPublishTf) {
try {
// Save the transformation from base to frame
geometry_msgs::TransformStamped b2o =
mTfBuffer->lookupTransform(mOdometryFrameId, mBaseFrameId, ros::Time(0));
// Get the TF2 transformation
tf2::fromMsg(b2o.transform, base_to_odom);
} catch (tf2::TransformException& ex) {
NODELET_WARN_THROTTLE(
10.0, "The tf from '%s' to '%s' does not seem to be available, "
"will assume it as identity!",
mBaseFrameId.c_str(), mOdometryFrameId.c_str());
NODELET_DEBUG("Transform error: %s", ex.what());
}
}
if (mPublishMapTf) {
// Look up the transformation from base frame to map
try {
// Save the transformation from base to frame
geometry_msgs::TransformStamped b2m =
mTfBuffer->lookupTransform(mMapFrameId, mBaseFrameId, ros::Time(0));
// Get the TF2 transformation
tf2::fromMsg(b2m.transform, base_to_map);
} catch (tf2::TransformException& ex) {
NODELET_WARN_THROTTLE(
10.0, "The tf from '%s' to '%s' does not seem to be available, "
"will assume it as identity!",
mBaseFrameId.c_str(), mOdometryFrameId.c_str());
NODELET_DEBUG("Transform error: %s", ex.what());
}
}
geometry_msgs::PoseStamped odomPose;
geometry_msgs::PoseStamped mapPose;
odomPose.header.stamp = mFrameTimestamp;
odomPose.header.frame_id = mPublishMapTf ? mMapFrameId : mOdometryFrameId; // frame
// conversion from Tranform to message
geometry_msgs::Transform base2odom = tf2::toMsg(base_to_odom);
// Add all value in Pose message
odomPose.pose.position.x = base2odom.translation.x;
odomPose.pose.position.y = base2odom.translation.y;
odomPose.pose.position.z = base2odom.translation.z;
odomPose.pose.orientation.x = base2odom.rotation.x;
odomPose.pose.orientation.y = base2odom.rotation.y;
odomPose.pose.orientation.z = base2odom.rotation.z;
odomPose.pose.orientation.w = base2odom.rotation.w;
if (mPublishMapTf) {
mapPose.header.stamp = mFrameTimestamp;
mapPose.header.frame_id = mMapFrameId; // map_frame
// conversion from Tranform to message
geometry_msgs::Transform base2map = tf2::toMsg(base_to_map);
// Add all value in Pose message
mapPose.pose.position.x = base2map.translation.x;
mapPose.pose.position.y = base2map.translation.y;
mapPose.pose.position.z = base2map.translation.z;
mapPose.pose.orientation.x = base2map.rotation.x;
mapPose.pose.orientation.y = base2map.rotation.y;
mapPose.pose.orientation.z = base2map.rotation.z;
mapPose.pose.orientation.w = base2map.rotation.w;
}
// Circular vector
if (mPathMaxCount != -1) {
if (mOdomPath.size() == mPathMaxCount) {
NODELET_DEBUG("Path vectors full: rotating ");
std::rotate(mOdomPath.begin(), mOdomPath.begin() + 1, mOdomPath.end());
std::rotate(mMapPath.begin(), mMapPath.begin() + 1, mMapPath.end());
mMapPath[mPathMaxCount - 1] = mapPose;
mOdomPath[mPathMaxCount - 1] = odomPose;
} else {
//NODELET_DEBUG_STREAM("Path vectors adding last available poses");
mMapPath.push_back(mapPose);
mOdomPath.push_back(odomPose);
}
} else {
//NODELET_DEBUG_STREAM("No limit path vectors, adding last available poses");
mMapPath.push_back(mapPose);
mOdomPath.push_back(odomPose);
}
if (mapPathSub > 0 && mPublishMapTf) {
nav_msgs::Path mapPath;
mapPath.header.frame_id = mMapFrameId;
mapPath.header.stamp = mFrameTimestamp;
mapPath.poses = mMapPath;
mPubMapPath.publish(mapPath);
}
if (odomPathSub > 0) {
nav_msgs::Path odomPath;
odomPath.header.frame_id = mPublishMapTf ? mMapFrameId : mOdometryFrameId;
odomPath.header.stamp = mFrameTimestamp;
odomPath.poses = mOdomPath;
mPubOdomPath.publish(odomPath);
}
}
void ZEDWrapperNodelet::imuPubCallback(const ros::TimerEvent& e) {
std::lock_guard<std::mutex> lock(mCloseZedMutex);
if (!mZed.isOpened()) {
return;
}
uint32_t imu_SubNumber = mPubImu.getNumSubscribers();
uint32_t imu_RawSubNumber = mPubImuRaw.getNumSubscribers();
if (imu_SubNumber < 1 && imu_RawSubNumber < 1) {
return;
}
ros::Time t;
if (mSvoMode) {
t = ros::Time::now();
} else {
t = sl_tools::slTime2Ros(mZed.getTimestamp(sl::TIME_REFERENCE_IMAGE));
}
sl::IMUData imu_data;
mZed.getIMUData(imu_data, sl::TIME_REFERENCE_CURRENT);
if (imu_SubNumber > 0) {
sensor_msgs::Imu imu_msg;
imu_msg.header.stamp = mFrameTimestamp; // t;
imu_msg.header.frame_id = mImuFrameId;
imu_msg.orientation.x = mSignX * imu_data.getOrientation()[mIdxX];
imu_msg.orientation.y = mSignY * imu_data.getOrientation()[mIdxY];
imu_msg.orientation.z = mSignZ * imu_data.getOrientation()[mIdxZ];
imu_msg.orientation.w = imu_data.getOrientation()[3];
imu_msg.angular_velocity.x = mSignX * imu_data.angular_velocity[mIdxX] * DEG2RAD;
imu_msg.angular_velocity.y = mSignY * imu_data.angular_velocity[mIdxY] * DEG2RAD;
imu_msg.angular_velocity.z = mSignZ * imu_data.angular_velocity[mIdxZ] * DEG2RAD;
imu_msg.linear_acceleration.x = mSignX * imu_data.linear_acceleration[mIdxX];
imu_msg.linear_acceleration.y = mSignY * imu_data.linear_acceleration[mIdxY];
imu_msg.linear_acceleration.z = mSignZ * imu_data.linear_acceleration[mIdxZ];
for (int i = 0; i < 3; ++i) {
int r = 0;
if (i == 0) {
r = mIdxX;
} else if (i == 1) {
r = mIdxY;
} else {
r = mIdxZ;
}
imu_msg.orientation_covariance[i * 3 + 0] =
imu_data.orientation_covariance.r[r * 3 + mIdxX] * DEG2RAD * DEG2RAD;
imu_msg.orientation_covariance[i * 3 + 1] =
imu_data.orientation_covariance.r[r * 3 + mIdxY] * DEG2RAD * DEG2RAD;
imu_msg.orientation_covariance[i * 3 + 2] =
imu_data.orientation_covariance.r[r * 3 + mIdxZ] * DEG2RAD * DEG2RAD;
imu_msg.linear_acceleration_covariance[i * 3 + 0] =
imu_data.linear_acceleration_convariance.r[r * 3 + mIdxX];
imu_msg.linear_acceleration_covariance[i * 3 + 1] =
imu_data.linear_acceleration_convariance.r[r * 3 + mIdxY];
imu_msg.linear_acceleration_covariance[i * 3 + 2] =
imu_data.linear_acceleration_convariance.r[r * 3 + mIdxZ];
imu_msg.angular_velocity_covariance[i * 3 + 0] =
imu_data.angular_velocity_convariance.r[r * 3 + mIdxX] * DEG2RAD * DEG2RAD;
imu_msg.angular_velocity_covariance[i * 3 + 1] =
imu_data.angular_velocity_convariance.r[r * 3 + mIdxY] * DEG2RAD * DEG2RAD;
imu_msg.angular_velocity_covariance[i * 3 + 2] =
imu_data.angular_velocity_convariance.r[r * 3 + mIdxZ] * DEG2RAD * DEG2RAD;
}
mPubImu.publish(imu_msg);
}
if (imu_RawSubNumber > 0) {
sensor_msgs::Imu imu_raw_msg;
imu_raw_msg.header.stamp = mFrameTimestamp; // t;
imu_raw_msg.header.frame_id = mImuFrameId;
imu_raw_msg.angular_velocity.x = mSignX * imu_data.angular_velocity[mIdxX] * DEG2RAD;
imu_raw_msg.angular_velocity.y = mSignY * imu_data.angular_velocity[mIdxY] * DEG2RAD;
imu_raw_msg.angular_velocity.z = mSignZ * imu_data.angular_velocity[mIdxZ] * DEG2RAD;
imu_raw_msg.linear_acceleration.x =
mSignX * imu_data.linear_acceleration[mIdxX];
imu_raw_msg.linear_acceleration.y =
mSignY * imu_data.linear_acceleration[mIdxY];
imu_raw_msg.linear_acceleration.z =
mSignZ * imu_data.linear_acceleration[mIdxZ];
for (int i = 0; i < 3; ++i) {
int r = 0;
if (i == 0) {
r = mIdxX;
} else if (i == 1) {
r = mIdxY;
} else {
r = mIdxZ;
}
imu_raw_msg.linear_acceleration_covariance[i * 3 + 0] =
imu_data.linear_acceleration_convariance.r[r * 3 + mIdxX];
imu_raw_msg.linear_acceleration_covariance[i * 3 + 1] =
imu_data.linear_acceleration_convariance.r[r * 3 + mIdxY];
imu_raw_msg.linear_acceleration_covariance[i * 3 + 2] =
imu_data.linear_acceleration_convariance.r[r * 3 + mIdxZ];
imu_raw_msg.angular_velocity_covariance[i * 3 + 0] =
imu_data.angular_velocity_convariance.r[r * 3 + mIdxX] * DEG2RAD * DEG2RAD;
imu_raw_msg.angular_velocity_covariance[i * 3 + 1] =
imu_data.angular_velocity_convariance.r[r * 3 + mIdxY] * DEG2RAD * DEG2RAD;
imu_raw_msg.angular_velocity_covariance[i * 3 + 2] =
imu_data.angular_velocity_convariance.r[r * 3 + mIdxZ] * DEG2RAD * DEG2RAD;
}
imu_raw_msg.orientation_covariance[0] =
-1; // Orientation data is not available in "data_raw" -> See ROS REP145
// http://www.ros.org/reps/rep-0145.html#topics
mPubImuRaw.publish(imu_raw_msg);
}
// Publish IMU tf only if enabled
if (mPublishTf) {
// Camera to pose transform from TF buffer
tf2::Transform cam_to_pose;
std::string poseFrame;
// Look up the transformation from base frame to map link
try {
poseFrame = mPublishMapTf ? mMapFrameId : mOdometryFrameId;
// Save the transformation from base to frame
geometry_msgs::TransformStamped c2p =
mTfBuffer->lookupTransform(poseFrame, mCameraFrameId, ros::Time(0));
// Get the TF2 transformation
tf2::fromMsg(c2p.transform, cam_to_pose);
} catch (tf2::TransformException& ex) {
NODELET_WARN_THROTTLE(
10.0, "The tf from '%s' to '%s' does not seem to be available. "
"IMU TF not published!",
mCameraFrameId.c_str(), mMapFrameId.c_str());
NODELET_DEBUG_THROTTLE(1.0, "Transform error: %s", ex.what());
return;
}
// IMU Quaternion in Map frame
tf2::Quaternion imu_q;
imu_q.setX(mSignX * imu_data.getOrientation()[mIdxX]);
imu_q.setY(mSignY * imu_data.getOrientation()[mIdxY]);
imu_q.setZ(mSignZ * imu_data.getOrientation()[mIdxZ]);
imu_q.setW(imu_data.getOrientation()[3]);
// Pose Quaternion from ZED Camera
tf2::Quaternion map_q = cam_to_pose.getRotation();
// Difference between IMU and ZED Quaternion
tf2::Quaternion delta_q = imu_q * map_q.inverse();
tf2::Transform imu_pose;
imu_pose.setIdentity();
imu_pose.setRotation(delta_q);
// Note, the frame is published, but its values will only change if someone
// has subscribed to IMU
publishImuFrame(imu_pose, mFrameTimestamp); // publish the imu Frame
}
}
void ZEDWrapperNodelet::device_poll_thread_func() {
ros::Rate loop_rate(mCamFrameRate);
// Timestamp initialization
if (mSvoMode) {
mFrameTimestamp = ros::Time::now();
} else {
mFrameTimestamp = sl_tools::slTime2Ros(mZed.getTimestamp(sl::TIME_REFERENCE_CURRENT));
}
mPrevFrameTimestamp = mFrameTimestamp;
sl::ERROR_CODE grab_status;
mTrackingActivated = false;
// Get the parameters of the ZED images
mCamWidth = mZed.getResolution().width;
mCamHeight = mZed.getResolution().height;
NODELET_DEBUG_STREAM("Camera Frame size : " << mCamWidth << "x" << mCamHeight);
mMatWidth = static_cast<int>(mCamWidth * mCamMatResizeFactor);
mMatHeight = static_cast<int>(mCamHeight * mCamMatResizeFactor);
NODELET_DEBUG_STREAM("Data Mat size : " << mMatWidth << "x" << mMatHeight);
// Create and fill the camera information messages
fillCamInfo(mZed, mLeftCamInfoMsg, mRightCamInfoMsg, mLeftCamOptFrameId,
mRightCamOptFrameId);
fillCamInfo(mZed, mLeftCamInfoRawMsg, mRightCamInfoRawMsg, mLeftCamOptFrameId,
mRightCamOptFrameId, true);
mRgbCamInfoMsg = mDepthCamInfoMsg = mLeftCamInfoMsg; // the reference camera is
// the Left one (next to the
// ZED logo)
mRgbCamInfoRawMsg = mLeftCamInfoRawMsg;
sl::RuntimeParameters runParams;
runParams.sensing_mode = static_cast<sl::SENSING_MODE>(mCamSensingMode);
sl::Mat leftZEDMat, rightZEDMat, depthZEDMat, disparityZEDMat, confImgZEDMat, confMapZEDMat;
// Main loop
while (mNhNs.ok()) {
// Check for subscribers
uint32_t rgbSubnumber = mPubRgb.getNumSubscribers();
uint32_t rgbRawSubnumber = mPubRawRgb.getNumSubscribers();
uint32_t leftSubnumber = mPubLeft.getNumSubscribers();
uint32_t leftRawSubnumber = mPubRawLeft.getNumSubscribers();
uint32_t rightSubnumber = mPubRight.getNumSubscribers();
uint32_t rightRawSubnumber = mPubRawRight.getNumSubscribers();
uint32_t depthSubnumber = mPubDepth.getNumSubscribers();
uint32_t disparitySubnumber = mPubDisparity.getNumSubscribers();
uint32_t cloudSubnumber = mPubCloud.getNumSubscribers();
uint32_t poseSubnumber = mPubPose.getNumSubscribers();
uint32_t poseCovSubnumber = mPubPoseCov.getNumSubscribers();
uint32_t odomSubnumber = mPubOdom.getNumSubscribers();
uint32_t confImgSubnumber = mPubConfImg.getNumSubscribers();
uint32_t confMapSubnumber = mPubConfMap.getNumSubscribers();
uint32_t imuSubnumber = mPubImu.getNumSubscribers();
uint32_t imuRawsubnumber = mPubImuRaw.getNumSubscribers();
uint32_t pathSubNumber = mPubMapPath.getNumSubscribers() + mPubOdomPath.getNumSubscribers();
bool runLoop = ((rgbSubnumber + rgbRawSubnumber + leftSubnumber +
leftRawSubnumber + rightSubnumber + rightRawSubnumber +
depthSubnumber + disparitySubnumber + cloudSubnumber +
poseSubnumber + poseCovSubnumber + odomSubnumber + confImgSubnumber +
confMapSubnumber + imuSubnumber + imuRawsubnumber + pathSubNumber) > 0);
runParams.enable_point_cloud = false;
if (cloudSubnumber > 0) {
runParams.enable_point_cloud = true;
}
// Run the loop only if there is some subscribers
if (runLoop) {
bool startTracking = (mDepthStabilization || poseSubnumber > 0 || poseCovSubnumber > 0 ||
odomSubnumber > 0 || cloudSubnumber > 0 || depthSubnumber > 0 || pathSubNumber > 0);
if ((startTracking) && !mTrackingActivated) { // Start the tracking
start_tracking();
} else if (!mDepthStabilization && poseSubnumber == 0 && poseCovSubnumber == 0 &&
odomSubnumber == 0 &&
mTrackingActivated) { // Stop the tracking
mZed.disableTracking();
mTrackingActivated = false;
}
// Detect if one of the subscriber need to have the depth information
mComputeDepth = ((depthSubnumber + disparitySubnumber + cloudSubnumber +
poseSubnumber + poseCovSubnumber + odomSubnumber + confImgSubnumber +
confMapSubnumber) > 0);
if (mComputeDepth) {
int actual_confidence = mZed.getConfidenceThreshold();
if (actual_confidence != mCamConfidence) {
mZed.setConfidenceThreshold(mCamConfidence);
}
double actual_max_depth = static_cast<double>(mZed.getDepthMaxRangeValue());
if (actual_max_depth != mCamMaxDepth) {
mZed.setDepthMaxRangeValue(static_cast<double>(mCamMaxDepth));
}
runParams.enable_depth = true; // Ask to compute the depth
} else {
runParams.enable_depth = false;
}
grab_status = mZed.grab(runParams); // Ask to not compute the depth
// cout << toString(grab_status) << endl;
if (grab_status != sl::ERROR_CODE::SUCCESS) {
// Detect if a error occurred (for example:
// the zed have been disconnected) and
// re-initialize the ZED
if (grab_status != sl::ERROR_CODE_NOT_A_NEW_FRAME) {
NODELET_INFO_STREAM_ONCE(toString(grab_status));
}
// if ( mSvoMode && mPubClock.getNumSubscribers() > 0) {
// rosgraph_msgs::Clock clkMsg;
// clkMsg.clock = sl_tools::slTime2Ros(mZed.getTimestamp(sl::TIME_REFERENCE_IMAGE));
// mPubClock.publish(clkMsg);
// }
std::this_thread::sleep_for(std::chrono::milliseconds(2));
if ((ros::Time::now() - mPrevFrameTimestamp).toSec() > 5 && !mSvoMode) {
mCloseZedMutex.lock();
mZed.close();
mCloseZedMutex.unlock();
sl::ERROR_CODE err = sl::ERROR_CODE_CAMERA_NOT_DETECTED;
while (err != sl::SUCCESS) {
if (!mNhNs.ok()) {
mStopNode = true;
std::lock_guard<std::mutex> lock(mCloseZedMutex);
NODELET_DEBUG("Closing ZED");
mZed.close();
NODELET_DEBUG("ZED pool thread finished");
return;
}
int id = sl_tools::checkCameraReady(mZedSerialNumber);
if (id >= 0) {
mZedParams.camera_linux_id = id;
err = mZed.open(mZedParams); // Try to initialize the ZED
NODELET_INFO_STREAM(toString(err));
} else {
NODELET_INFO_STREAM("Waiting for the ZED (S/N " << mZedSerialNumber << ") to be re-connected");
}
std::this_thread::sleep_for(std::chrono::milliseconds(2000));
}
mTrackingActivated = false;
startTracking = mDepthStabilization || poseSubnumber > 0 || poseCovSubnumber > 0 ||
odomSubnumber > 0;
if (startTracking) { // Start the tracking
start_tracking();
}
}
continue;
}
mPrevFrameTimestamp = mFrameTimestamp;
// Timestamp
if (mSvoMode) {
mFrameTimestamp = ros::Time::now();
} else {
mFrameTimestamp = sl_tools::slTime2Ros(mZed.getTimestamp(sl::TIME_REFERENCE_IMAGE));
}
if (mCamAutoExposure) {
// getCameraSettings() can't check status of auto exposure
// triggerAutoExposure is used to execute setCameraSettings() only once
if (mTriggerAutoExposure) {
mZed.setCameraSettings(sl::CAMERA_SETTINGS_EXPOSURE, 0, true);
mTriggerAutoExposure = false;
}
} else {
int actual_exposure =
mZed.getCameraSettings(sl::CAMERA_SETTINGS_EXPOSURE);
if (actual_exposure != mCamExposure) {
mZed.setCameraSettings(sl::CAMERA_SETTINGS_EXPOSURE, mCamExposure);
}
int actual_gain = mZed.getCameraSettings(sl::CAMERA_SETTINGS_GAIN);
if (actual_gain != mCamGain) {
mZed.setCameraSettings(sl::CAMERA_SETTINGS_GAIN, mCamGain);
}
}
mCamDataMutex.lock();
// Publish the left == rgb image if someone has subscribed to
if (leftSubnumber > 0 || rgbSubnumber > 0) {
// Retrieve RGBA Left image
mZed.retrieveImage(leftZEDMat, sl::VIEW_LEFT, sl::MEM_CPU, mMatWidth, mMatHeight);
if (leftSubnumber > 0) {
publishCamInfo(mLeftCamInfoMsg, mPubLeftCamInfo, mFrameTimestamp);
publishImage(leftZEDMat, mPubLeft, mLeftCamOptFrameId, mFrameTimestamp);
}
if (rgbSubnumber > 0) {
publishCamInfo(mRgbCamInfoMsg, mPubRgbCamInfo, mFrameTimestamp);
publishImage(leftZEDMat, mPubRgb, mDepthOptFrameId, mFrameTimestamp); // rgb is the left image
}
}
// Publish the left_raw == rgb_raw image if someone has subscribed to
if (leftRawSubnumber > 0 || rgbRawSubnumber > 0) {
// Retrieve RGBA Left image
mZed.retrieveImage(leftZEDMat, sl::VIEW_LEFT_UNRECTIFIED, sl::MEM_CPU, mMatWidth, mMatHeight);
if (leftRawSubnumber > 0) {
publishCamInfo(mLeftCamInfoRawMsg, mPubLeftCamInfoRaw, mFrameTimestamp);
publishImage(leftZEDMat, mPubRawLeft, mLeftCamOptFrameId, mFrameTimestamp);
}
if (rgbRawSubnumber > 0) {
publishCamInfo(mRgbCamInfoRawMsg, mPubRgbCamInfoRaw, mFrameTimestamp);
publishImage(leftZEDMat, mPubRawRgb, mDepthOptFrameId, mFrameTimestamp);
}
}
// Publish the right image if someone has subscribed to
if (rightSubnumber > 0) {
// Retrieve RGBA Right image
mZed.retrieveImage(rightZEDMat, sl::VIEW_RIGHT, sl::MEM_CPU, mMatWidth, mMatHeight);
publishCamInfo(mRightCamInfoMsg, mPubRightCamInfo, mFrameTimestamp);
publishImage(rightZEDMat, mPubRight, mRightCamOptFrameId, mFrameTimestamp);
}
// Publish the right image if someone has subscribed to
if (rightRawSubnumber > 0) {
// Retrieve RGBA Right image
mZed.retrieveImage(rightZEDMat, sl::VIEW_RIGHT_UNRECTIFIED, sl::MEM_CPU, mMatWidth, mMatHeight);
publishCamInfo(mRightCamInfoRawMsg, mPubRightCamInfoRaw, mFrameTimestamp);
publishImage(rightZEDMat, mPubRawRight, mRightCamOptFrameId, mFrameTimestamp);
}
// Publish the depth image if someone has subscribed to
if (depthSubnumber > 0 || disparitySubnumber > 0) {
mZed.retrieveMeasure(depthZEDMat, sl::MEASURE_DEPTH, sl::MEM_CPU, mMatWidth, mMatHeight);
publishCamInfo(mDepthCamInfoMsg, mPubDepthCamInfo, mFrameTimestamp);
publishDepth(depthZEDMat, mFrameTimestamp); // in meters
}
// Publish the disparity image if someone has subscribed to
if (disparitySubnumber > 0) {
mZed.retrieveMeasure(disparityZEDMat, sl::MEASURE_DISPARITY, sl::MEM_CPU, mMatWidth, mMatHeight);
// Need to flip sign, but cause of this is not sure
publishDisparity(disparityZEDMat, mFrameTimestamp);
}
// Publish the confidence image if someone has subscribed to
if (confImgSubnumber > 0) {
mZed.retrieveImage(confImgZEDMat, sl::VIEW_CONFIDENCE, sl::MEM_CPU, mMatWidth, mMatHeight);
publishImage(confImgZEDMat, mPubConfImg, mConfidenceOptFrameId, mFrameTimestamp);
}
// Publish the confidence map if someone has subscribed to
if (confMapSubnumber > 0) {
mZed.retrieveMeasure(confMapZEDMat, sl::MEASURE_CONFIDENCE, sl::MEM_CPU, mMatWidth, mMatHeight);
mPubConfMap.publish(sl_tools::imageToROSmsg(confMapZEDMat, mConfidenceOptFrameId, mFrameTimestamp));
}
// Publish the point cloud if someone has subscribed to
if (cloudSubnumber > 0) {
// Run the point cloud conversion asynchronously to avoid slowing down
// all the program
// Retrieve raw pointCloud data if latest Pointcloud is ready
std::unique_lock<std::mutex> lock(mPcMutex, std::defer_lock);
if (lock.try_lock()) {
mZed.retrieveMeasure(mCloud, sl::MEASURE_XYZBGRA, sl::MEM_CPU, mMatWidth, mMatHeight);
mPointCloudFrameId = mDepthFrameId;
mPointCloudTime = mFrameTimestamp;
// Signal Pointcloud thread that a new pointcloud is ready
mPcDataReadyCondVar.notify_one();
mPcDataReady = true;
}
}
mCamDataMutex.unlock();
// Publish the odometry if someone has subscribed to
if (poseSubnumber > 0 || poseCovSubnumber > 0 || odomSubnumber > 0 || cloudSubnumber > 0 ||
depthSubnumber > 0 || imuSubnumber > 0 || imuRawsubnumber > 0 || pathSubNumber > 0) {
if (!mInitOdomWithPose) {
sl::Pose deltaOdom;
sl::TRACKING_STATE status = mZed.getPosition(deltaOdom, sl::REFERENCE_FRAME_CAMERA);
sl::Translation translation = deltaOdom.getTranslation();
sl::Orientation quat = deltaOdom.getOrientation();
NODELET_DEBUG("delta ODOM [%s] - %.2f,%.2f,%.2f %.2f,%.2f,%.2f,%.2f",
sl::toString(status).c_str(),
translation(mIdxX), translation(mIdxY), translation(mIdxZ),
quat(mIdxX), quat(mIdxY), quat(mIdxZ), quat(3));
if (status == sl::TRACKING_STATE_OK || status == sl::TRACKING_STATE_SEARCHING ||
status == sl::TRACKING_STATE_FPS_TOO_LOW) {
// Transform ZED delta odom pose in TF2 Transformation
geometry_msgs::Transform deltaTransf;
deltaTransf.translation.x = mSignX * translation(mIdxX);
deltaTransf.translation.y = mSignY * translation(mIdxY);
deltaTransf.translation.z = mSignZ * translation(mIdxZ);
deltaTransf.rotation.x = mSignX * quat(mIdxX);
deltaTransf.rotation.y = mSignY * quat(mIdxY);
deltaTransf.rotation.z = mSignZ * quat(mIdxZ);
deltaTransf.rotation.w = quat(3);
tf2::Transform deltaOdomTf;
tf2::fromMsg(deltaTransf, deltaOdomTf);
// delta odom from sensor to base frame
tf2::Transform deltaOdomTf_base =
mSensor2BaseTransf * deltaOdomTf * mSensor2BaseTransf.inverse();
// Propagate Odom transform in time
mBase2OdomTransf = mBase2OdomTransf * deltaOdomTf_base;
// Publish odometry message
publishOdom(mBase2OdomTransf, deltaOdom, mFrameTimestamp);
mTrackingReady = true;
} else {
NODELET_DEBUG_STREAM("ODOM -> Tracking Status: " << sl::toString(status));
}
} else if (mFloorAlignment) {
NODELET_WARN_THROTTLE(5.0, "Odometry will be published as soon as the floor as been detected for the first time");
}
}
// Publish the zed camera pose if someone has subscribed to
if (poseSubnumber > 0 || odomSubnumber > 0 || poseCovSubnumber > 0 || cloudSubnumber > 0 ||
depthSubnumber > 0 || imuSubnumber > 0 || imuRawsubnumber > 0 || pathSubNumber > 0) {
static sl::TRACKING_STATE oldStatus;
sl::TRACKING_STATE status = mZed.getPosition(mLastZedPose, sl::REFERENCE_FRAME_WORLD);
sl::Translation translation = mLastZedPose.getTranslation();
sl::Orientation quat = mLastZedPose.getOrientation();
NODELET_DEBUG("POSE [%s] - %.2f,%.2f,%.2f %.2f,%.2f,%.2f,%.2f",
sl::toString(status).c_str(),
translation(mIdxX), translation(mIdxY), translation(mIdxZ),
quat(mIdxX), quat(mIdxY), quat(mIdxZ), quat(3));
if (status == sl::TRACKING_STATE_OK ||
status == sl::TRACKING_STATE_SEARCHING /*|| status == sl::TRACKING_STATE_FPS_TOO_LOW*/) {
// Transform ZED pose in TF2 Transformation
geometry_msgs::Transform sens2mapTransf;
sens2mapTransf.translation.x = mSignX * translation(mIdxX);
sens2mapTransf.translation.y = mSignY * translation(mIdxY);
sens2mapTransf.translation.z = mSignZ * translation(mIdxZ);
sens2mapTransf.rotation.x = mSignX * quat(mIdxX);
sens2mapTransf.rotation.y = mSignY * quat(mIdxY);
sens2mapTransf.rotation.z = mSignZ * quat(mIdxZ);
sens2mapTransf.rotation.w = quat(3);
tf2::Transform sens_to_map_transf;
tf2::fromMsg(sens2mapTransf, sens_to_map_transf);
// Transformation from camera sensor to base frame
/*tf2::Transform base_to_map_transform =
sensor_to_base_transf * sens_to_map_transf * sensor_to_base_transf.inverse();*/
tf2::Transform base_to_map_transform = (mSensor2BaseTransf * sens_to_map_transf.inverse()).inverse();
bool initOdom = false;
if (!(mFloorAlignment)) {
initOdom = mInitOdomWithPose;
} else {
initOdom = (status == sl::TRACKING_STATE_OK) & mInitOdomWithPose;
}
if (initOdom || mResetOdom) {
ROS_INFO("Odometry aligned to last tracking pose");
// Propagate Odom transform in time
mBase2OdomTransf = base_to_map_transform;
base_to_map_transform.setIdentity();
if (odomSubnumber > 0) {
// Publish odometry message
publishOdom(mBase2OdomTransf, mLastZedPose, mFrameTimestamp);
}
mInitOdomWithPose = false;
mResetOdom = false;
} else {
// Transformation from map to odometry frame
mOdom2MapTransf =
base_to_map_transform * mBase2OdomTransf.inverse();
}
// Publish Pose message
publishPose(mFrameTimestamp);
mTrackingReady = true;
} else {
NODELET_DEBUG_STREAM("MAP -> Tracking Status: " << static_cast<int>(status));
}
oldStatus = status;
}
// Publish pose tf only if enabled
if (mPublishTf) {
// Note, the frame is published, but its values will only change if
// someone has subscribed to odom
publishOdomFrame(mBase2OdomTransf, mFrameTimestamp); // publish the base Frame in odometry frame
if (mPublishMapTf) {
// Note, the frame is published, but its values will only change if
// someone has subscribed to map
publishPoseFrame(mOdom2MapTransf, mFrameTimestamp); // publish the odometry Frame in map frame
}
}
static int rateWarnCount = 0;
if (!loop_rate.sleep()) {
rateWarnCount++;
if (rateWarnCount == 10) {
NODELET_DEBUG_THROTTLE(
1.0,
"Working thread is not synchronized with the Camera frame rate");
NODELET_DEBUG_STREAM_THROTTLE(
1.0, "Expected cycle time: " << loop_rate.expectedCycleTime()
<< " - Real cycle time: "
<< loop_rate.cycleTime());
NODELET_WARN_THROTTLE(10.0, "Elaboration takes longer than requested "
"by the FPS rate. Please consider to "
"lower the 'frame_rate' setting.");
}
} else {
rateWarnCount = 0;
}
} else {
NODELET_DEBUG_THROTTLE(5.0, "No topics subscribed by users");
// Publish odometry tf only if enabled
if (mPublishTf) {
ros::Time t;
if (mSvoMode) {
t = ros::Time::now();
} else {
t = sl_tools::slTime2Ros(mZed.getTimestamp(sl::TIME_REFERENCE_CURRENT));
}
publishOdomFrame(mBase2OdomTransf, mFrameTimestamp); // publish the base Frame in odometry frame
if (mPublishMapTf) {
publishPoseFrame(mOdom2MapTransf, mFrameTimestamp); // publish the odometry Frame in map frame
}
}
std::this_thread::sleep_for(
std::chrono::milliseconds(10)); // No subscribers, we just wait
loop_rate.reset();
}
} // while loop
mStopNode = true; // Stops other threads
std::lock_guard<std::mutex> lock(mCloseZedMutex);
NODELET_DEBUG("Closing ZED");
mZed.close();
NODELET_DEBUG("ZED pool thread finished");
}
} // namespace
|
/*
* Copyright (c) 2017 Sprint
*
* 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 "async_shell_cmd.hpp"
#include "common_defs.h"
#include "itti.hpp"
#include "logger.hpp"
#include "options.hpp"
#include "pgw_app.hpp"
#include "pgw_config.hpp"
#include "pid_file.hpp"
#include "sgwc_app.hpp"
#include "sgwc_config.hpp"
#include <signal.h>
#include <stdint.h>
#include <stdlib.h> // srand
#include <unistd.h> // get_pid(), pause()
#include <iostream>
#include <thread>
using namespace gtpv2c;
using namespace pgwc;
using namespace sgwc;
using namespace util;
using namespace std;
itti_mw* itti_inst = nullptr;
async_shell_cmd* async_shell_cmd_inst = nullptr;
pgw_app* pgw_app_inst = nullptr;
sgwc_app* sgwc_app_inst = nullptr;
pgw_config pgw_cfg;
sgwc_config sgwc_cfg;
void send_heartbeat_to_tasks(const uint32_t sequence);
//------------------------------------------------------------------------------
void send_heartbeat_to_tasks(const uint32_t sequence) {
itti_msg_ping* itti_msg =
new itti_msg_ping(TASK_SGWC_APP, TASK_ALL, sequence);
std::shared_ptr<itti_msg_ping> i = std::shared_ptr<itti_msg_ping>(itti_msg);
int ret = itti_inst->send_broadcast_msg(i);
if (RETURNok != ret) {
Logger::sgwc_app().error(
"Could not send ITTI message %s to task TASK_ALL", i->get_msg_name());
}
}
//------------------------------------------------------------------------------
void my_app_signal_handler(int s) {
std::cout << "Caught signal " << s << std::endl;
Logger::system().startup("exiting");
itti_inst->send_terminate_msg(TASK_SGWC_APP);
itti_inst->wait_tasks_end();
std::cout << "Freeing Allocated memory..." << std::endl;
if (async_shell_cmd_inst) delete async_shell_cmd_inst;
async_shell_cmd_inst = nullptr;
std::cout << "Async Shell CMD memory done." << std::endl;
if (itti_inst) delete itti_inst;
itti_inst = nullptr;
std::cout << "ITTI memory done." << std::endl;
if (sgwc_app_inst) delete sgwc_app_inst;
sgwc_app_inst = nullptr;
std::cout << "SGW APP memory done." << std::endl;
if (pgw_app_inst) delete pgw_app_inst;
pgw_app_inst = nullptr;
std::cout << "PGW APP memory done." << std::endl;
std::cout << "Freeing Allocated memory done" << std::endl;
exit(0);
}
//------------------------------------------------------------------------------
int main(int argc, char** argv) {
srand(time(NULL));
// Command line options
if (!Options::parse(argc, argv)) {
std::cout << "Options::parse() failed" << std::endl;
return 1;
}
// Logger
Logger::init("spgwc", Options::getlogStdout(), Options::getlogRotFilelog());
Logger::sgwc_app().startup("Options parsed");
struct sigaction sigIntHandler;
sigIntHandler.sa_handler = my_app_signal_handler;
sigemptyset(&sigIntHandler.sa_mask);
sigIntHandler.sa_flags = 0;
sigaction(SIGINT, &sigIntHandler, NULL);
// Config
sgwc_cfg.load(Options::getlibconfigConfig());
sgwc_cfg.display();
pgw_cfg.load(Options::getlibconfigConfig());
pgw_cfg.display();
// Inter task Interface
itti_inst = new itti_mw();
itti_inst->start(pgw_cfg.itti.itti_timer_sched_params);
// system command
async_shell_cmd_inst =
new async_shell_cmd(sgwc_cfg.itti.async_cmd_sched_params);
// PGW application layer
pgw_app_inst = new pgw_app(Options::getlibconfigConfig());
// PID file
// Currently hard-coded value. TODO: add as config option.
string pid_file_name = get_exe_absolute_path("/var/run", pgw_cfg.instance);
if (!is_pid_file_lock_success(pid_file_name.c_str())) {
Logger::pgwc_app().error(
"Lock PID file %s failed\n", pid_file_name.c_str());
exit(-EDEADLK);
}
// SGW application layer
sgwc_app_inst = new sgwc_app(Options::getlibconfigConfig());
FILE* fp = NULL;
std::string filename = fmt::format("/tmp/spgwc_{}.status", getpid());
fp = fopen(filename.c_str(), "w+");
fprintf(fp, "STARTED\n");
fflush(fp);
fclose(fp);
pause();
return 0;
}
|
// Copyright (c) 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 "chromeos/attestation/attestation_flow.h"
#include <algorithm>
#include <utility>
#include "base/bind.h"
#include "base/compiler_specific.h"
#include "base/logging.h"
#include "base/memory/ptr_util.h"
#include "base/optional.h"
#include "base/threading/thread_task_runner_handle.h"
#include "base/timer/timer.h"
#include "chromeos/attestation/attestation_flow_utils.h"
#include "chromeos/cryptohome/cryptohome_parameters.h"
#include "chromeos/dbus/attestation/attestation_client.h"
#include "chromeos/dbus/attestation/interface.pb.h"
#include "components/account_id/account_id.h"
namespace chromeos {
namespace attestation {
namespace {
base::Optional<::attestation::CertificateProfile> ProfileToAttestationProtoEnum(
AttestationCertificateProfile p) {
switch (p) {
case PROFILE_ENTERPRISE_MACHINE_CERTIFICATE:
return ::attestation::CertificateProfile::ENTERPRISE_MACHINE_CERTIFICATE;
case PROFILE_ENTERPRISE_USER_CERTIFICATE:
return ::attestation::CertificateProfile::ENTERPRISE_USER_CERTIFICATE;
case PROFILE_CONTENT_PROTECTION_CERTIFICATE:
return ::attestation::CertificateProfile::CONTENT_PROTECTION_CERTIFICATE;
case PROFILE_ENTERPRISE_ENROLLMENT_CERTIFICATE:
return ::attestation::CertificateProfile::
ENTERPRISE_ENROLLMENT_CERTIFICATE;
}
return {};
}
::attestation::ACAType ToAcaType(PrivacyCAType type) {
switch (type) {
case DEFAULT_PCA:
return ::attestation::DEFAULT_ACA;
case TEST_PCA:
return ::attestation::TEST_ACA;
}
LOG(DFATAL) << "Unknown type to convert: " << type;
return ::attestation::DEFAULT_ACA;
}
// A reasonable timeout that gives enough time for attestation to be ready,
// yet does not make the caller wait too long.
constexpr uint16_t kReadyTimeoutInSeconds = 60;
// Delay before checking again whether the TPM has been prepared for
// attestation.
constexpr uint16_t kRetryDelayInMilliseconds = 300;
} // namespace
AttestationKeyType AttestationFlow::GetKeyTypeForProfile(
AttestationCertificateProfile certificate_profile) {
switch (certificate_profile) {
case PROFILE_ENTERPRISE_MACHINE_CERTIFICATE:
case PROFILE_ENTERPRISE_ENROLLMENT_CERTIFICATE:
return KEY_DEVICE;
case PROFILE_ENTERPRISE_USER_CERTIFICATE:
case PROFILE_CONTENT_PROTECTION_CERTIFICATE:
return KEY_USER;
}
NOTREACHED();
return KEY_USER;
}
AttestationFlow::AttestationFlow(std::unique_ptr<ServerProxy> server_proxy,
::attestation::KeyType crypto_key_type)
: attestation_client_(AttestationClient::Get()),
server_proxy_(std::move(server_proxy)),
crypto_key_type_(crypto_key_type),
ready_timeout_(base::TimeDelta::FromSeconds(kReadyTimeoutInSeconds)),
retry_delay_(
base::TimeDelta::FromMilliseconds(kRetryDelayInMilliseconds)) {}
AttestationFlow::AttestationFlow(std::unique_ptr<ServerProxy> server_proxy)
: AttestationFlow(std::move(server_proxy), ::attestation::KEY_TYPE_RSA) {}
AttestationFlow::~AttestationFlow() = default;
void AttestationFlow::GetCertificate(
AttestationCertificateProfile certificate_profile,
const AccountId& account_id,
const std::string& request_origin,
bool force_new_key,
const std::string& key_name,
CertificateCallback callback) {
std::string attestation_key_name =
!key_name.empty()
? key_name
: GetKeyNameForProfile(certificate_profile, request_origin);
base::OnceCallback<void(bool)> start_certificate_request = base::BindOnce(
&AttestationFlow::StartCertificateRequest, weak_factory_.GetWeakPtr(),
certificate_profile, account_id, request_origin, force_new_key,
attestation_key_name, std::move(callback));
// If this device has not enrolled with the Privacy CA, we need to do that
// first. Once enrolled we can proceed with the certificate request.
attestation_client_->GetStatus(
::attestation::GetStatusRequest(),
base::BindOnce(&AttestationFlow::OnEnrollmentCheckComplete,
weak_factory_.GetWeakPtr(),
std::move(start_certificate_request)));
}
void AttestationFlow::OnEnrollmentCheckComplete(
base::OnceCallback<void(bool)> callback,
const ::attestation::GetStatusReply& reply) {
if (reply.status() != ::attestation::STATUS_SUCCESS) {
LOG(ERROR) << "Attestation: Failed to check enrollment state. Status: "
<< reply.status();
std::move(callback).Run(false);
return;
}
if (reply.enrolled()) {
std::move(callback).Run(true);
return;
}
// The device is not enrolled; check if it's enrollment prepared.
base::TimeTicks end_time = base::TimeTicks::Now() + ready_timeout_;
WaitForAttestationPrepared(end_time, std::move(callback));
}
void AttestationFlow::WaitForAttestationPrepared(
base::TimeTicks end_time,
base::OnceCallback<void(bool)> callback) {
::attestation::GetEnrollmentPreparationsRequest request;
attestation_client_->GetEnrollmentPreparations(
request, base::BindOnce(&AttestationFlow::OnPreparedCheckComplete,
weak_factory_.GetWeakPtr(), end_time,
std::move(callback)));
}
void AttestationFlow::OnPreparedCheckComplete(
base::TimeTicks end_time,
base::OnceCallback<void(bool)> callback,
const ::attestation::GetEnrollmentPreparationsReply& reply) {
if (AttestationClient::IsAttestationPrepared(reply)) {
// Get the attestation service to create a Privacy CA enrollment request.
::attestation::CreateEnrollRequestRequest request;
request.set_aca_type(ToAcaType(server_proxy_->GetType()));
AttestationClient::Get()->CreateEnrollRequest(
request,
base::BindOnce(&AttestationFlow::SendEnrollRequestToPCA,
weak_factory_.GetWeakPtr(), std::move(callback)));
return;
}
if (base::TimeTicks::Now() < end_time) {
LOG(WARNING) << "Attestation: Not prepared yet."
<< " Retrying in " << retry_delay_ << ".";
base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
FROM_HERE,
base::BindOnce(&AttestationFlow::WaitForAttestationPrepared,
weak_factory_.GetWeakPtr(), end_time,
std::move(callback)),
retry_delay_);
return;
}
LOG(ERROR) << "Attestation: Not prepared. Giving up on retrying.";
std::move(callback).Run(false);
}
void AttestationFlow::SendEnrollRequestToPCA(
base::OnceCallback<void(bool)> callback,
const ::attestation::CreateEnrollRequestReply& reply) {
if (reply.status() != ::attestation::STATUS_SUCCESS) {
LOG(ERROR) << "Attestation: Failed to create enroll request; status: "
<< reply.status();
std::move(callback).Run(false);
return;
}
// Send the request to the Privacy CA.
server_proxy_->SendEnrollRequest(
reply.pca_request(),
base::BindOnce(&AttestationFlow::SendEnrollResponseToDaemon,
weak_factory_.GetWeakPtr(), std::move(callback)));
}
void AttestationFlow::SendEnrollResponseToDaemon(
base::OnceCallback<void(bool)> callback,
bool success,
const std::string& data) {
if (!success) {
LOG(ERROR) << "Attestation: Enroll request failed.";
std::move(callback).Run(false);
return;
}
// Forward the response to the attestation service to complete enrollment.
::attestation::FinishEnrollRequest request;
request.set_pca_response(data);
request.set_aca_type(ToAcaType(server_proxy_->GetType()));
AttestationClient::Get()->FinishEnroll(
request, base::BindOnce(&AttestationFlow::OnEnrollComplete,
weak_factory_.GetWeakPtr(), std::move(callback)));
}
void AttestationFlow::OnEnrollComplete(
base::OnceCallback<void(bool)> callback,
const ::attestation::FinishEnrollReply& reply) {
if (reply.status() != ::attestation::STATUS_SUCCESS) {
LOG(ERROR) << "Attestation: Failed to complete enrollment; status: "
<< reply.status();
std::move(callback).Run(false);
return;
}
std::move(callback).Run(true);
}
void AttestationFlow::StartCertificateRequest(
AttestationCertificateProfile certificate_profile,
const AccountId& account_id,
const std::string& request_origin,
bool generate_new_key,
const std::string& key_name,
CertificateCallback callback,
bool enrolled) {
if (!enrolled) {
std::move(callback).Run(ATTESTATION_UNSPECIFIED_FAILURE, "");
return;
}
AttestationKeyType key_type = GetKeyTypeForProfile(certificate_profile);
if (generate_new_key) {
// Get the attestation service to create a Privacy CA certificate request.
const base::Optional<::attestation::CertificateProfile>
attestation_profile =
ProfileToAttestationProtoEnum(certificate_profile);
if (!attestation_profile) {
LOG(DFATAL) << "Attestation: Unrecognized profile type: "
<< certificate_profile;
return;
}
::attestation::CreateCertificateRequestRequest request;
if (key_type == KEY_USER) {
request.set_username(cryptohome::Identification(account_id).id());
}
request.set_certificate_profile(*attestation_profile);
request.set_request_origin(request_origin);
request.set_key_type(crypto_key_type_);
attestation_client_->CreateCertificateRequest(
request, base::BindOnce(&AttestationFlow::SendCertificateRequestToPCA,
weak_factory_.GetWeakPtr(), key_type,
account_id, key_name, std::move(callback)));
return;
}
::attestation::GetKeyInfoRequest request;
if (key_type == KEY_USER) {
request.set_username(cryptohome::Identification(account_id).id());
}
request.set_key_label(key_name);
attestation_client_->GetKeyInfo(
request, base::BindOnce(&AttestationFlow::OnGetKeyInfoComplete,
weak_factory_.GetWeakPtr(), certificate_profile,
account_id, request_origin, key_name, key_type,
std::move(callback)));
}
void AttestationFlow::OnGetKeyInfoComplete(
AttestationCertificateProfile certificate_profile,
const AccountId& account_id,
const std::string& request_origin,
const std::string& key_name,
AttestationKeyType key_type,
CertificateCallback callback,
const ::attestation::GetKeyInfoReply& reply) {
// If the key already exists, return the existing certificate.
if (reply.status() == ::attestation::STATUS_SUCCESS) {
std::move(callback).Run(ATTESTATION_SUCCESS, reply.certificate());
return;
}
// If the key does not exist, call this method back with |generate_new_key|
// set to true.
if (reply.status() == ::attestation::STATUS_INVALID_PARAMETER) {
StartCertificateRequest(certificate_profile, account_id, request_origin,
/*generate_new_key=*/true, key_name,
std::move(callback), /*enrolled=*/true);
return;
}
// Otherwise the key info query fails.
LOG(ERROR) << "Attestation: Failed to check for existence of key; status: "
<< reply.status() << ".";
std::move(callback).Run(ATTESTATION_UNSPECIFIED_FAILURE, "");
}
void AttestationFlow::SendCertificateRequestToPCA(
AttestationKeyType key_type,
const AccountId& account_id,
const std::string& key_name,
CertificateCallback callback,
const ::attestation::CreateCertificateRequestReply& reply) {
if (reply.status() != ::attestation::STATUS_SUCCESS) {
LOG(ERROR) << "Attestation: Failed to create certificate request. Status: "
<< reply.status();
std::move(callback).Run(ATTESTATION_UNSPECIFIED_FAILURE, "");
return;
}
// Send the request to the Privacy CA.
server_proxy_->SendCertificateRequest(
reply.pca_request(),
base::BindOnce(&AttestationFlow::SendCertificateResponseToDaemon,
weak_factory_.GetWeakPtr(), key_type, account_id, key_name,
std::move(callback)));
}
void AttestationFlow::SendCertificateResponseToDaemon(
AttestationKeyType key_type,
const AccountId& account_id,
const std::string& key_name,
CertificateCallback callback,
bool success,
const std::string& data) {
if (!success) {
LOG(ERROR) << "Attestation: Certificate request failed.";
std::move(callback).Run(ATTESTATION_UNSPECIFIED_FAILURE, "");
return;
}
::attestation::FinishCertificateRequestRequest request;
if (key_type == KEY_USER) {
request.set_username(cryptohome::Identification(account_id).id());
}
request.set_key_label(key_name);
request.set_pca_response(data);
AttestationClient::Get()->FinishCertificateRequest(
request, base::BindOnce(&AttestationFlow::OnCertRequestFinished,
weak_factory_.GetWeakPtr(), std::move(callback)));
}
void AttestationFlow::OnCertRequestFinished(
CertificateCallback callback,
const ::attestation::FinishCertificateRequestReply& reply) {
if (reply.status() == ::attestation::STATUS_SUCCESS) {
std::move(callback).Run(ATTESTATION_SUCCESS, reply.certificate());
} else {
LOG(ERROR) << "Failed to finish certificate request; status: "
<< reply.status();
std::move(callback).Run(ATTESTATION_SERVER_BAD_REQUEST_FAILURE,
/*pem_certificate_chain=*/"");
}
}
ServerProxy::~ServerProxy() = default;
PrivacyCAType ServerProxy::GetType() {
return DEFAULT_PCA;
}
} // namespace attestation
} // namespace chromeos
|
/*
* Copyright (C) 2012 Apple 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:
* 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 APPLE INC. ``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 APPLE INC. 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 "wtf/DataLog.h"
#if OS(POSIX)
#include <pthread.h>
#include <unistd.h>
#endif
#define DATA_LOG_TO_FILE 0
// Uncomment to force logging to the given file regardless of what the
// environment variable says. Note that we will append ".<pid>.txt" where <pid>
// is the PID.
// This path won't work on Windows, make sure to change to something like
// C:\\Users\\<more path>\\log.txt.
#define DATA_LOG_FILENAME "/tmp/WTFLog"
namespace WTF {
#if OS(POSIX)
static pthread_once_t initializeLogFileOnceKey = PTHREAD_ONCE_INIT;
#endif
static FilePrintStream* file;
static void initializeLogFileOnce() {
#if DATA_LOG_TO_FILE
#ifdef DATA_LOG_FILENAME
const char* filename = DATA_LOG_FILENAME;
#else
const char* filename = getenv("WTF_DATA_LOG_FILENAME");
#endif
char actualFilename[1024];
snprintf(actualFilename, sizeof(actualFilename), "%s.%d.txt", filename,
getpid());
if (filename) {
file = FilePrintStream::open(actualFilename, "w").release();
if (!file)
fprintf(stderr, "Warning: Could not open log file %s for writing.\n",
actualFilename);
}
#endif // DATA_LOG_TO_FILE
if (!file)
file = new FilePrintStream(stderr, FilePrintStream::Borrow);
// Prefer unbuffered output, so that we get a full log upon crash or
// deadlock.
setvbuf(file->file(), 0, _IONBF, 0);
}
static void initializeLogFile() {
#if OS(POSIX)
pthread_once(&initializeLogFileOnceKey, initializeLogFileOnce);
#else
if (!file)
initializeLogFileOnce();
#endif
}
FilePrintStream& dataFile() {
initializeLogFile();
return *file;
}
void dataLogFV(const char* format, va_list argList) {
dataFile().vprintf(format, argList);
}
void dataLogF(const char* format, ...) {
va_list argList;
va_start(argList, format);
dataLogFV(format, argList);
va_end(argList);
}
} // namespace WTF
|
#include <iostream>
class S
{
public:
S() : n_(10) { }
// regardless of whether the members are on the same or different instances
S(const S& other) : n_(other.n_) { } // other.n is accessible in S::S
private:
int n_;
};
class Derived;
class Base
{
public:
void F(Base&, Derived&);
public:
int public_;
protected:
int protected_;
private:
int private_;
};
//class Derived : private Base
//class Derived : protected Base
class Derived : public Base
{
public:
void Access(Derived& d)
{
public_ = 1; // OK
protected_ = 1; // OK,访问从基类继承的 protected 成员
//private_ = 1; // 错,不能访问基类私有成员
d_public_ = 1; // OK
d_protected_ = 1; // OK
d_private_ = 1; // OK
d.public_ = 1; // OK
// regardless of whether the members are on the same or different instances
d.protected_ = 1; // OK
//d.private_ = 1; // 错
d.d_public_ = 1; // OK
// regardless of whether the members are on the same or different instances
d.d_protected_ = 1; // OK
// regardless of whether the members are on the same or different instances
d.d_private_ = 1; // OK
Base f;
f.public_ = 1; // OK
//f.protected_ = 1; // 错,在派生类的成员函数中不能访问普通的基类对象的保护成员
//f.private_ = 1; // 错
}
public:
int d_public_;
protected:
int d_protected_;
private:
int d_private_;
};
void Base::F(Base& b, Derived& d)
{
++protected_;
// regardless of whether the members are on the same or different instances
++b.private_;
++b.protected_;
++b.public_;
++d.public_; // 经过测试发现仅公有继承时才可以访问该成员
++d.protected_; // 经过测试发现仅公有继承时才可以访问该成员
++d.private_; // 经过测试发现仅公有继承时才可以访问该成员
++d.d_public_;
//++d.d_protected_;
//++d.d_private_;
}
// non-member/non-friend
void X(Base& b, Derived& d)
{
//++b.protected_; // error: no access from non-member/non-friend
//++d.protected_; // error: no access from non-member/non-friend
}
int main()
{
Base b;
Derived d;
//int n = b.protected_; // 错,在类的成员函数外部,不能访问基类保护成员
//n = d.private_; // 错,此处不能访问d的私有成员
d.public_ = 10; // 仅公有继承时可以访问
d.d_public_ = 11; // OK
return 0;
}
// Tips:
// 1. 在类的成员函数内部可以访问同类其他对象的全部(私有, 保护, 公有)成员(不含继承的基类的私有成员,其是不可访问的)。
// 2. 需要留意基类Base的成员函数Base::F对普通的派生类对象的成员的访问权限:
// 按理说,基类的成员和友元对于普通的派生类对象,也应该是不具有特殊的访问权限的。
// 但经过测试发现,对于protected或private继承的方式,基类的成员和友元是符合预期地仅可以访问普通派生类对象自定义部分的public成员;
// 但是对于public继承的方式,基类的成员和友元是出乎预期地既可以访问普通派生类对象自定义部分的public成员,还可以访问普通派生类对象继承自基类部分的所有成员。
|
// Copyright 2020 The Fuchsia 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/ui/tools/present_view/testing/fake_view.h"
#include <lib/async/default.h>
#include <lib/ui/scenic/cpp/view_ref_pair.h>
#include <zircon/types.h>
#include <functional>
#include "gtest/gtest.h"
namespace present_view::testing {
FakeView::FakeView() : legacy_binding_(this), binding_(this) {}
FakeView::~FakeView() = default;
void FakeView::CreateView(
zx::eventpair view_token,
fidl::InterfaceRequest<fuchsia::sys::ServiceProvider> /*incoming_services*/,
fidl::InterfaceHandle<fuchsia::sys::ServiceProvider> /*outgoing_services*/) {
auto [view_ref_control, view_ref] = scenic::ViewRefPair::New();
CreateViewWithViewRef(std::move(view_token), std::move(view_ref_control), std::move(view_ref));
}
void FakeView::CreateViewWithViewRef(zx::eventpair view_token,
fuchsia::ui::views::ViewRefControl view_ref_control,
fuchsia::ui::views::ViewRef view_ref) {
// Wait on the passed-in |ViewToken| so we can detect if the peer token is destroyed.
token_.value = std::move(view_token);
token_waiter_ =
std::make_unique<async::Wait>(token_.value.get(), __ZX_OBJECT_PEER_CLOSED, 0,
std::bind([this] { token_peer_disconnected_ = true; }));
zx_status_t wait_status = token_waiter_->Begin(async_get_default_dispatcher());
EXPECT_EQ(wait_status, ZX_OK);
}
void FakeView::Present(fuchsia::ui::views::ViewToken view_token) {
auto [view_ref_control, view_ref] = scenic::ViewRefPair::New();
CreateViewWithViewRef(std::move(view_token.value), std::move(view_ref_control),
std::move(view_ref));
}
void FakeView::NotImplemented_(const std::string& name) {
FAIL() << "Unimplemented -- fuchsia.ui.views.ViewProvider::" << name;
}
void FakeView::BindLegacy(fidl::InterfaceRequest<fuchsia::ui::app::ViewProvider> request) {
ASSERT_FALSE(bound());
legacy_binding_.Bind(std::move(request));
}
void FakeView::Bind(fidl::InterfaceRequest<fuchsia::ui::views::View> request) {
ASSERT_FALSE(bound());
binding_.Bind(std::move(request));
}
void FakeView::OnKill() {
token_waiter_.reset();
token_ = fuchsia::ui::views::ViewToken(); // Must outlive `token_waiter_`.
legacy_binding_.Unbind();
binding_.Unbind();
killed_ = true;
}
} // namespace present_view::testing
|
/* Copyright (c) 2017-2022, Hans Erik Thrane */
#pragma once
#include <fmt/format.h>
#include <cctype>
#include "roq/span.hpp"
namespace roq {
namespace debug {
namespace fix {
struct Message final {
public:
explicit Message(std::span<const std::byte> const &buffer) : buffer_(buffer) {}
Message(std::byte const *data, size_t length) : Message{{data, length}} {}
template <typename Context>
auto format_to(Context &context) const {
using namespace std::literals;
for (auto b : buffer_) {
if (b == std::byte{0x1}) {
fmt::format_to(context.out(), "|"sv);
} else {
char c = static_cast<char>(b);
if (::isprint(c))
fmt::format_to(context.out(), "{}"sv, c);
else
fmt::format_to(context.out(), "."sv);
}
}
return context.out();
}
private:
const std::span<const std::byte> buffer_;
};
} // namespace fix
} // namespace debug
} // namespace roq
template <>
struct fmt::formatter<roq::debug::fix::Message> {
template <typename Context>
constexpr auto parse(Context &context) {
return std::begin(context);
}
template <typename Context>
auto format(roq::debug::fix::Message const &value, Context &context) {
return value.format_to(context);
}
};
|
/*
* 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.
*/
/*!
* Lower TVM related builtin intrinsics such as packed call.
* \file tir/transforms/lower_tvm_buildin.cc
*/
#include <tvm/runtime/registry.h>
#include <tvm/tir/builtin.h>
#include <tvm/tir/expr.h>
#include <tvm/tir/stmt_functor.h>
#include <tvm/tir/transform.h>
#include <unordered_set>
#include "ir_utils.h"
namespace tvm {
namespace tir {
// Calculate the statistics of packed function.
// These information are needed during codegen.
class BuiltinLower : public StmtExprMutator {
public:
struct StackSizes {
// If a tvm_stack_make_shape call has no arguments, it is still
// valid and represents a scalar shape (). Therefore, -1 is used
// to represent "no shape arguments exist", while 0 represents
// "shape arguments exist, all of which are size 0".
int64_t shape_stack{-1};
uint64_t array_stack{0};
uint64_t arg_stack{0};
};
// Record stack frame for existing scope.
struct AllocaScope {
Buffer stack_shape;
Var stack_array = Var("stack_array", DataType::Handle());
Var stack_value = Var("stack_value", DataType::Handle());
Buffer stack_tcode;
StackSizes max_sizes;
StackSizes run_sizes;
void UpdateMax() {
max_sizes.shape_stack = std::max(max_sizes.shape_stack, run_sizes.shape_stack);
max_sizes.array_stack = std::max(max_sizes.array_stack, run_sizes.array_stack);
max_sizes.arg_stack = std::max(max_sizes.arg_stack, run_sizes.arg_stack);
}
void AssertMaxIsValid() const {
ICHECK((max_sizes.shape_stack >= run_sizes.shape_stack) ||
(max_sizes.array_stack >= run_sizes.array_stack) ||
(max_sizes.arg_stack >= run_sizes.arg_stack));
}
};
Stmt Build(Stmt stmt) { return this->VisitBodyAndRealizeAlloca(stmt); }
StackSizes GetMaxStack(Stmt stmt) {
BuiltinLower precheck;
precheck.is_precheck_ = true;
precheck.device_id_ = this->device_id_;
precheck.device_type_ = this->device_type_;
precheck.alloca_scope_.emplace_back();
auto& scope = precheck.alloca_scope_.back();
scope.stack_shape =
decl_buffer({IntImm(DataType::Int(64), 0)}, DataType::Int(64), "stack_shape");
scope.stack_tcode =
decl_buffer({IntImm(DataType::UInt(64), 0)}, DataType::Int(32), "stack_tcode");
precheck.VisitStmt(stmt);
ICHECK_EQ(precheck.alloca_scope_.size(), 1);
return precheck.alloca_scope_[0].max_sizes;
}
// Allcoate stack frames, only at parallel-for or root.
Stmt VisitBodyAndRealizeAlloca(Stmt stmt) {
// Only perform the precheck up to the point where we would add a
// new scope.
if (is_precheck_) {
return stmt;
}
alloca_scope_.emplace_back();
auto& scope = alloca_scope_.back();
// Initial check to identify maximum stack sizes. These are used
// to construct Buffer objects to hold the stack, which are then
// used when mutating.
scope.max_sizes = GetMaxStack(stmt);
if (scope.max_sizes.shape_stack != -1) {
scope.stack_shape = decl_buffer({IntImm(DataType::Int(64), scope.max_sizes.shape_stack)},
DataType::Int(64), "stack_shape");
stmt =
LetStmt(scope.stack_shape->data, StackAlloca("shape", scope.max_sizes.shape_stack), stmt);
}
if (scope.max_sizes.array_stack != 0) {
stmt = LetStmt(scope.stack_array, StackAlloca("array", scope.max_sizes.array_stack), stmt);
}
if (scope.max_sizes.arg_stack != 0) {
scope.stack_tcode = decl_buffer({IntImm(DataType::UInt(64), scope.max_sizes.arg_stack)},
DataType::Int(32), "stack_tcode");
stmt = LetStmt(scope.stack_value, StackAlloca("arg_value", scope.max_sizes.arg_stack), stmt);
stmt = LetStmt(scope.stack_tcode->data, StackAlloca("arg_tcode", scope.max_sizes.arg_stack),
stmt);
}
stmt = this->VisitStmt(stmt);
ICHECK(!alloca_scope_.empty());
alloca_scope_.pop_back();
return stmt;
}
Stmt VisitStmt(const Stmt& s) final {
// allocate space to hold prepare stmts before s
prep_seq_stack_.emplace_back(std::vector<Stmt>());
auto stmt = StmtExprMutator::VisitStmt(s);
auto& scope = alloca_scope_.back();
ICHECK_EQ(scope.run_sizes.shape_stack, -1);
ICHECK_EQ(scope.run_sizes.array_stack, 0);
auto prep_seq = std::move(prep_seq_stack_.back());
prep_seq_stack_.pop_back();
if (prep_seq.size() != 0) {
Stmt ret = SeqStmt::Flatten(prep_seq, stmt);
return ret;
} else {
return stmt;
}
}
Stmt VisitStmt_(const LetStmtNode* op) final {
if (const CallNode* call = op->value.as<CallNode>()) {
if (call->op.same_as(builtin::nd_mem_alloc_with_scope())) {
return StmtExprMutator::VisitStmt(MakeNdMemAllocWithScope(op, call));
}
}
return StmtExprMutator::VisitStmt_(op);
}
Stmt VisitStmt_(const AllocateNode* op) {
// Lower allocate to device allocate when needed.
Stmt stmt = StmtExprMutator::VisitStmt_(op);
op = stmt.as<AllocateNode>();
// Get constant allocation bound.
int64_t nbytes = GetVectorBytes(op->dtype);
// If the buffers are for CPU and have global scope,
// and less than runtime::kMaxStackAlloca heuristic
// they are not serviced with TVMBackendWorkspaceAlloc calls
// to be placed on stack.
if (op->annotations.count(transform::kDisableLowerTVMBuiltin)) {
if (Downcast<Bool>(op->annotations[transform::kDisableLowerTVMBuiltin])) {
return stmt;
}
}
if (device_type_.defined()) {
if (const auto* dev_type = device_type_.as<IntImmNode>()) {
auto storage_scope = Downcast<PointerType>(op->buffer_var->type_annotation)->storage_scope;
if (dev_type->value == kDLCPU && storage_scope == "global") {
size_t constant_size = op->ConstantAllocationSize();
if (constant_size > 0 && constant_size * nbytes < runtime::kMaxStackAlloca) {
return stmt;
}
}
}
}
PrimExpr total_bytes = make_const(op->extents[0].dtype(), nbytes);
for (size_t i = 0; i < op->extents.size(); ++i) {
total_bytes = total_bytes * op->extents[i];
}
ICHECK(device_type_.defined()) << "Unknown device type in current IR";
ICHECK(device_id_.defined()) << "Unknown device id in current IR";
Stmt throw_last_error = Evaluate(Call(DataType::Int(32), builtin::tvm_throw_last_error(), {}));
Stmt body = SeqStmt({IfThenElse(Call(DataType::Bool(1), builtin::isnullptr(), {op->buffer_var}),
throw_last_error),
op->body});
Stmt alloca = LetStmt(
op->buffer_var,
Call(op->buffer_var.dtype(), Op::Get("tir.TVMBackendAllocWorkspace"),
{cast(DataType::Int(32), device_type_), cast(DataType::Int(32), device_id_),
cast(DataType::UInt(64), total_bytes), IntImm(DataType::Int(32), op->dtype.code()),
IntImm(DataType::Int(32), op->dtype.bits())}),
body);
PrimExpr free_op = Call(DataType::Int(32), Op::Get("tir.TVMBackendFreeWorkspace"),
{cast(DataType::Int(32), device_type_),
cast(DataType::Int(32), device_id_), op->buffer_var});
Stmt free_stmt = IfThenElse(free_op != make_zero(DataType::Int(32)), throw_last_error);
body = SeqStmt({alloca, free_stmt});
body = AttrStmt(op->buffer_var, attr::storage_alignment,
make_const(DataType::Int(32), runtime::kTempAllocaAlignment), body);
return body;
}
Stmt VisitStmt_(const AttrStmtNode* op) final {
if (op->attr_key == attr::device_id) {
ICHECK(!device_id_.defined());
device_id_ = op->value;
return this->VisitStmt(op->body);
} else if (op->attr_key == attr::device_type) {
ICHECK(!device_type_.defined());
device_type_ = op->value;
return this->VisitStmt(op->body);
} else {
return StmtExprMutator::VisitStmt_(op);
}
}
Stmt VisitStmt_(const ForNode* op) final {
PrimExpr min = this->VisitExpr(op->min);
PrimExpr extent = this->VisitExpr(op->extent);
Stmt body;
if (op->kind == ForKind::kParallel) {
body = this->VisitBodyAndRealizeAlloca(op->body);
} else {
body = this->VisitStmt(op->body);
}
if (min.same_as(op->min) && extent.same_as(op->extent) && body.same_as(op->body)) {
return GetRef<Stmt>(op);
} else {
auto n = CopyOnWrite(op);
n->min = std::move(min);
n->extent = std::move(extent);
n->body = std::move(body);
return Stmt(n);
}
}
PrimExpr VisitExpr_(const CallNode* op) final {
if (op->op.same_as(builtin::tvm_call_packed())) {
return MakeCallPacked(op, /* use_string_lookup */ true);
} else if (op->op.same_as(builtin::tvm_call_cpacked())) {
return MakeCallPacked(op, /* use_string_lookup */ false);
} else if (op->op.same_as(builtin::tvm_call_trace_packed())) {
return MakeCallTracePacked(op);
} else if (op->op.same_as(builtin::tvm_stack_make_shape())) {
return MakeShape(op);
} else if (op->op.same_as(builtin::tvm_stack_make_array())) {
return MakeArray(op);
} else if (op->op.same_as(builtin::tvm_context_id())) {
return make_zero(op->dtype);
} else if (op->op.same_as(builtin::mem_copy())) {
return MakeMemCopy(op);
} else {
return StmtExprMutator::VisitExpr_(op);
}
}
PrimExpr MakeMemCopy(const CallNode* op) {
PrimExpr dst = op->args[0];
PrimExpr src = op->args[1];
PrimExpr size = op->args[2];
std::string fdevapi_prefix =
"device_api." + std::string(runtime::DeviceName(device_type_.as<IntImmNode>()->value));
Call call_packed = Call(DataType::Int(32), builtin::tvm_call_packed(),
{StringImm(fdevapi_prefix + ".mem_copy"), dst, src, size});
return VisitExpr(call_packed);
}
// call shape
PrimExpr MakeShape(const CallNode* op) {
// if args.size() == 0, it represents a scalar shape ()
ICHECK(!alloca_scope_.empty());
auto& scope = alloca_scope_.back();
auto& prep_seq = prep_seq_stack_.back();
if (scope.run_sizes.shape_stack == -1) {
scope.run_sizes.shape_stack = 0;
}
int64_t stack_begin = scope.run_sizes.shape_stack;
scope.run_sizes.shape_stack += op->args.size();
PrimExpr expr = StmtExprMutator::VisitExpr_(op);
op = expr.as<CallNode>();
// no need to perform any store for a scalar shape
for (size_t i = 0; i < op->args.size(); ++i) {
prep_seq.emplace_back(BufferStore(scope.stack_shape, cast(DataType::Int(64), op->args[i]),
{ConstInt32(stack_begin + i)}));
}
return AddressOffset(scope.stack_shape->data, DataType::Int(64), stack_begin);
}
// make array
PrimExpr MakeArray(const CallNode* op) {
ICHECK(!alloca_scope_.empty());
auto& scope = alloca_scope_.back();
auto& prep_seq = prep_seq_stack_.back();
size_t idx = scope.run_sizes.array_stack;
scope.run_sizes.array_stack += 1;
PrimExpr expr = StmtExprMutator::VisitExpr_(op);
op = expr.as<CallNode>();
prep_seq.emplace_back(TVMStructSet(scope.stack_array, idx, builtin::kArrData, op->args[0]));
prep_seq.emplace_back(TVMStructSet(scope.stack_array, idx, builtin::kArrShape, op->args[1]));
PrimExpr strides = op->args[2];
if (!strides.defined() || is_zero(strides)) {
strides = make_zero(DataType::Handle());
}
prep_seq.emplace_back(TVMStructSet(scope.stack_array, idx, builtin::kArrStrides, strides));
prep_seq.emplace_back(TVMStructSet(scope.stack_array, idx, builtin::kArrNDim, op->args[3]));
DataType dtype = op->args[4].dtype();
prep_seq.emplace_back(
TVMStructSet(scope.stack_array, idx, builtin::kArrTypeCode,
make_const(DataType::UInt(8), static_cast<int>(dtype.code()))));
prep_seq.emplace_back(TVMStructSet(scope.stack_array, idx, builtin::kArrTypeBits,
make_const(DataType::UInt(8), dtype.bits())));
prep_seq.emplace_back(TVMStructSet(scope.stack_array, idx, builtin::kArrTypeLanes,
make_const(DataType::UInt(16), dtype.lanes())));
// set byte offset
int data_bytes = GetVectorBytes(dtype);
PrimExpr byte_offset = op->args[5];
if (!is_zero(byte_offset)) {
byte_offset = byte_offset * make_const(byte_offset.dtype(), data_bytes);
}
prep_seq.emplace_back(TVMStructSet(scope.stack_array, idx, builtin::kArrByteOffset,
cast(DataType::UInt(64), byte_offset)));
ICHECK(device_type_.defined()) << "Unknown device type in current IR";
ICHECK(device_id_.defined()) << "Unknown device id in current IR";
prep_seq.emplace_back(TVMStructSet(scope.stack_array, idx, builtin::kArrDeviceId,
cast(DataType::Int(32), device_id_)));
prep_seq.emplace_back(TVMStructSet(scope.stack_array, idx, builtin::kArrDeviceType,
cast(DataType::Int(32), device_type_)));
return TVMStructGet(DataType::Handle(), scope.stack_array, idx, builtin::kArrAddr);
}
// call packed.
PrimExpr MakeCallPacked(const CallNode* op, bool use_string_lookup) {
auto& scope = alloca_scope_.back();
auto& prep_seq = prep_seq_stack_.back();
int64_t restore_shape_stack = scope.run_sizes.shape_stack;
size_t restore_array_stack = scope.run_sizes.array_stack;
size_t arg_stack_begin = scope.run_sizes.arg_stack;
size_t arg_count = op->args.size();
// cpacked expects a resource_handle parameter
if (!use_string_lookup) {
arg_count--;
}
scope.run_sizes.arg_stack += arg_count;
// Specially handle the buffer packed intrinsic
PrimExpr expr = StmtExprMutator::VisitExpr_(op);
op = expr.as<CallNode>();
for (size_t i = 1; i < arg_count; ++i) {
PrimExpr stack_index = ConstInt32(arg_stack_begin + i - 1);
PrimExpr arg = op->args[i];
DataType t = arg.dtype();
DataType api_type = APIType(t);
if (t != api_type) {
arg = Cast(api_type, arg);
}
prep_seq.emplace_back(TVMStructSet(scope.stack_value,
static_cast<int>(arg_stack_begin + i - 1),
builtin::kTVMValueContent, arg));
int arg_tcode = api_type.code();
if (api_type.is_handle() && arg.as<StringImmNode>()) {
arg_tcode = kTVMStr;
}
if (IsArrayHandle(arg)) arg_tcode = kTVMDLTensorHandle;
prep_seq.emplace_back(BufferStore(scope.stack_tcode, ConstInt32(arg_tcode), {stack_index}));
}
// Verify stack size matches earlier value.
if (is_precheck_) {
scope.UpdateMax();
} else {
scope.AssertMaxIsValid();
}
scope.run_sizes.shape_stack = restore_shape_stack;
scope.run_sizes.array_stack = restore_array_stack;
scope.run_sizes.arg_stack = arg_stack_begin;
Array<PrimExpr> packed_args = {op->args[0], scope.stack_value, scope.stack_tcode->data,
ConstInt32(arg_stack_begin),
ConstInt32(arg_stack_begin + op->args.size() - 1)};
// cpacked call resource_handle
if (!use_string_lookup) {
tir::Var resource_handle = Downcast<Var>(op->args[arg_count]);
packed_args.push_back(StringImm(resource_handle->name_hint));
}
auto builtin_call = use_string_lookup ? builtin::tvm_call_packed_lowered()
: builtin::tvm_call_cpacked_lowered();
return Call(op->dtype, builtin_call, packed_args);
}
PrimExpr MakeCallTracePacked(const CallNode* op) {
ICHECK(!alloca_scope_.empty());
auto& scope = alloca_scope_.back();
auto& prep_seq = prep_seq_stack_.back();
int64_t restore_shape_stack = scope.run_sizes.shape_stack;
size_t restore_array_stack = scope.run_sizes.array_stack;
size_t arg_stack_begin = scope.run_sizes.arg_stack;
scope.run_sizes.arg_stack += op->args.size();
size_t args_size = op->args.size();
ICHECK_GT(args_size, 0);
PrimExpr expr = StmtExprMutator::VisitExpr_(op);
op = expr.as<CallNode>();
for (size_t i = 1; i < op->args.size(); ++i) {
PrimExpr stack_index = ConstInt32(arg_stack_begin + i - 1);
PrimExpr arg = op->args[i];
DataType t = arg.dtype();
DataType api_type = APIType(t);
if (t != api_type) {
arg = Cast(api_type, arg);
}
prep_seq.emplace_back(TVMStructSet(scope.stack_value,
static_cast<int>(arg_stack_begin + i - 1),
builtin::kTVMValueContent, arg));
int arg_tcode = api_type.code();
ICHECK(!IsArrayHandle(arg)) << "Trace does not support Buffers";
prep_seq.emplace_back(BufferStore(scope.stack_tcode, ConstInt32(arg_tcode), {stack_index}));
}
// Verify stack size matches earlier value.
if (is_precheck_) {
scope.UpdateMax();
} else {
scope.AssertMaxIsValid();
}
scope.run_sizes.shape_stack = restore_shape_stack;
scope.run_sizes.array_stack = restore_array_stack;
// Update the top of the stack, so we can use more than one
// packed function's arguments with the one stack.
scope.run_sizes.arg_stack = arg_stack_begin + args_size - 1;
Array<PrimExpr> packed_args = {op->args[0], scope.stack_value, scope.stack_tcode->data,
ConstInt32(arg_stack_begin),
ConstInt32(arg_stack_begin + op->args.size() - 1),
// Pass traced value.
op->args[args_size - 1]};
return Call(op->dtype, builtin::tvm_call_trace_packed_lowered(), packed_args);
}
Stmt MakeNdMemAllocWithScope(const LetStmtNode* let, const CallNode* call) {
ICHECK(device_type_.defined()) << "Unknown device type in current IR";
ICHECK(device_id_.defined()) << "Unknown device id in current IR";
Stmt throw_last_error = Evaluate(Call(DataType::Int(32), builtin::tvm_throw_last_error(), {}));
Stmt body = SeqStmt(
{IfThenElse(Call(DataType::Bool(1), builtin::isnullptr(), {let->var}), throw_last_error),
let->body});
DataType dtype =
let->var->type_annotation.as<PointerTypeNode>()->element_type.as<PrimTypeNode>()->dtype;
std::string fdevapi_prefix = "device_api.";
fdevapi_prefix += runtime::DeviceName(device_type_.as<IntImmNode>()->value);
Array<PrimExpr> args = {
StringImm(fdevapi_prefix + ".alloc_nd"),
device_type_,
device_id_,
IntImm(DataType::Int(32), dtype.code()),
IntImm(DataType::Int(32), dtype.bits()),
};
for (size_t i = 0; i < call->args.size(); ++i) {
args.push_back(call->args[i]);
}
Call call_packed = Call(let->var.dtype(), builtin::tvm_call_packed(), args);
Stmt alloca = LetStmt(let->var, call_packed, body);
PrimExpr storage_scope = call->args[0];
Call free_op = Call(DataType::Int(32), builtin::tvm_call_packed(),
{StringImm(fdevapi_prefix + ".free_nd"), device_type_, device_id_,
storage_scope, let->var});
Stmt free_stmt = IfThenElse(free_op != make_zero(DataType::Int(32)), throw_last_error);
body = SeqStmt({alloca, free_stmt});
return body;
}
private:
bool IsArrayHandle(const PrimExpr& arg) {
// specially set array handle.
if (const CallNode* buf = arg.as<CallNode>()) {
if (buf->op.same_as(builtin::tvm_struct_get()) &&
buf->args[2].as<IntImmNode>()->value == builtin::kArrAddr) {
return true;
}
}
return false;
}
// The prepration sequence to be emitted before the current statement.
std::vector<std::vector<Stmt>> prep_seq_stack_;
PrimExpr device_type_;
PrimExpr device_id_;
bool is_precheck_{false};
// Record all stack frames.
std::vector<AllocaScope> alloca_scope_;
};
namespace transform {
Pass LowerTVMBuiltin() {
auto pass_func = [](PrimFunc f, IRModule m, PassContext ctx) {
auto* n = f.CopyOnWrite();
n->body = BuiltinLower().Build(n->body);
return f;
};
return CreatePrimFuncPass(pass_func, 0, "tir.LowerTVMBuiltin", {});
}
TVM_REGISTER_GLOBAL("tir.transform.LowerTVMBuiltin").set_body_typed(LowerTVMBuiltin);
} // namespace transform
} // namespace tir
} // namespace tvm
|
//
// ModelOverlay.cpp
//
//
// Created by Clement on 6/30/14.
// Copyright 2014 High Fidelity, Inc.
//
// Distributed under the Apache License, Version 2.0.
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
//
#include "ModelOverlay.h"
#include <Rig.h>
#include "Application.h"
QString const ModelOverlay::TYPE = "model";
ModelOverlay::ModelOverlay()
: _model(std::make_shared<Model>(std::make_shared<Rig>())),
_modelTextures(QVariantMap())
{
_model->init();
_isLoaded = false;
}
ModelOverlay::ModelOverlay(const ModelOverlay* modelOverlay) :
Volume3DOverlay(modelOverlay),
_model(std::make_shared<Model>(std::make_shared<Rig>())),
_modelTextures(QVariantMap()),
_url(modelOverlay->_url),
_updateModel(false)
{
_model->init();
if (_url.isValid()) {
_updateModel = true;
_isLoaded = false;
}
}
void ModelOverlay::update(float deltatime) {
if (_updateModel) {
_updateModel = false;
_model->setSnapModelToCenter(true);
if (_scaleToFit) {
_model->setScaleToFit(true, getScale() * getDimensions());
} else {
_model->setScale(getScale());
}
_model->setRotation(getRotation());
_model->setTranslation(getPosition());
_model->setURL(_url);
_model->simulate(deltatime, true);
} else {
_model->simulate(deltatime);
}
_isLoaded = _model->isActive();
}
bool ModelOverlay::addToScene(Overlay::Pointer overlay, std::shared_ptr<render::Scene> scene, render::PendingChanges& pendingChanges) {
Volume3DOverlay::addToScene(overlay, scene, pendingChanges);
_model->addToScene(scene, pendingChanges);
return true;
}
void ModelOverlay::removeFromScene(Overlay::Pointer overlay, std::shared_ptr<render::Scene> scene, render::PendingChanges& pendingChanges) {
Volume3DOverlay::removeFromScene(overlay, scene, pendingChanges);
_model->removeFromScene(scene, pendingChanges);
}
void ModelOverlay::render(RenderArgs* args) {
// check to see if when we added our model to the scene they were ready, if they were not ready, then
// fix them up in the scene
render::ScenePointer scene = qApp->getMain3DScene();
render::PendingChanges pendingChanges;
if (_model->needsFixupInScene()) {
_model->removeFromScene(scene, pendingChanges);
_model->addToScene(scene, pendingChanges);
}
_model->setVisibleInScene(_visible, scene);
_model->setLayeredInFront(getDrawInFront(), scene);
scene->enqueuePendingChanges(pendingChanges);
}
void ModelOverlay::setProperties(const QVariantMap& properties) {
auto origPosition = getPosition();
auto origRotation = getRotation();
auto origDimensions = getDimensions();
auto origScale = getScale();
Base3DOverlay::setProperties(properties);
auto scale = properties["scale"];
if (scale.isValid()) {
setScale(vec3FromVariant(scale));
}
auto dimensions = properties["dimensions"];
if (dimensions.isValid()) {
_scaleToFit = true;
setDimensions(vec3FromVariant(dimensions));
} else if (scale.isValid()) {
// if "scale" property is set but "dimentions" is not.
// do NOT scale to fit.
_scaleToFit = false;
}
if (origPosition != getPosition() || origRotation != getRotation() || origDimensions != getDimensions() || origScale != getScale()) {
_updateModel = true;
}
auto urlValue = properties["url"];
if (urlValue.isValid() && urlValue.canConvert<QString>()) {
_url = urlValue.toString();
_updateModel = true;
_isLoaded = false;
}
auto texturesValue = properties["textures"];
if (texturesValue.isValid() && texturesValue.canConvert(QVariant::Map)) {
QVariantMap textureMap = texturesValue.toMap();
QMetaObject::invokeMethod(_model.get(), "setTextures", Qt::AutoConnection,
Q_ARG(const QVariantMap&, textureMap));
}
}
QVariant ModelOverlay::getProperty(const QString& property) {
if (property == "url") {
return _url.toString();
}
if (property == "dimensions" || property == "size") {
return vec3toVariant(getDimensions());
}
if (property == "scale") {
return vec3toVariant(getScale());
}
if (property == "textures") {
if (_modelTextures.size() > 0) {
QVariantMap textures;
foreach(const QString& key, _modelTextures.keys()) {
textures[key] = _modelTextures[key].toString();
}
return textures;
} else {
return QVariant();
}
}
return Volume3DOverlay::getProperty(property);
}
bool ModelOverlay::findRayIntersection(const glm::vec3& origin, const glm::vec3& direction,
float& distance, BoxFace& face, glm::vec3& surfaceNormal) {
QString subMeshNameTemp;
return _model->findRayIntersectionAgainstSubMeshes(origin, direction, distance, face, surfaceNormal, subMeshNameTemp);
}
bool ModelOverlay::findRayIntersectionExtraInfo(const glm::vec3& origin, const glm::vec3& direction,
float& distance, BoxFace& face, glm::vec3& surfaceNormal, QString& extraInfo) {
return _model->findRayIntersectionAgainstSubMeshes(origin, direction, distance, face, surfaceNormal, extraInfo);
}
ModelOverlay* ModelOverlay::createClone() const {
return new ModelOverlay(this);
}
void ModelOverlay::locationChanged(bool tellPhysics) {
Base3DOverlay::locationChanged(tellPhysics);
if (_model && _model->isActive()) {
_model->setRotation(getRotation());
_model->setTranslation(getPosition());
}
}
|
// dear imgui: Platform Backend for GLFW
// This needs to be used along with a Renderer (e.g. OpenGL3, Vulkan, WebGPU..)
// (Info: GLFW is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan graphics context creation, etc.)
// (Requires: GLFW 3.1+. Prefer GLFW 3.3+ for full feature support.)
// Implemented features:
// [X] Platform: Clipboard support.
// [X] Platform: Gamepad support. Enable with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
// [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange' (note: the resizing cursors requires GLFW 3.4+).
// [X] Platform: Keyboard arrays indexed using GLFW_KEY_* codes, e.g. ImGui::IsKeyPressed(GLFW_KEY_SPACE).
// [X] Platform: Multi-viewport support (multiple windows). Enable with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'.
// Issues:
// [ ] Platform: Multi-viewport support: ParentViewportID not honored, and so io.ConfigViewportsNoDefaultParent has no effect (minor).
// You can copy and use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp.
// Read online: https://github.com/ocornut/imgui/tree/master/docs
// CHANGELOG
// (minor and older changes stripped away, please see git history for details)
// 2021-XX-XX: Platform: Added support for multiple windows via the ImGuiPlatformIO interface.
// 2020-01-17: Inputs: Disable error callback while assigning mouse cursors because some X11 setup don't have them and it generates errors.
// 2019-12-05: Inputs: Added support for new mouse cursors added in GLFW 3.4+ (resizing cursors, not allowed cursor).
// 2019-10-18: Misc: Previously installed user callbacks are now restored on shutdown.
// 2019-07-21: Inputs: Added mapping for ImGuiKey_KeyPadEnter.
// 2019-05-11: Inputs: Don't filter value from character callback before calling AddInputCharacter().
// 2019-03-12: Misc: Preserve DisplayFramebufferScale when main window is minimized.
// 2018-11-30: Misc: Setting up io.BackendPlatformName so it can be displayed in the About Window.
// 2018-11-07: Inputs: When installing our GLFW callbacks, we save user's previously installed ones - if any - and chain call them.
// 2018-08-01: Inputs: Workaround for Emscripten which doesn't seem to handle focus related calls.
// 2018-06-29: Inputs: Added support for the ImGuiMouseCursor_Hand cursor.
// 2018-06-08: Misc: Extracted imgui_impl_glfw.cpp/.h away from the old combined GLFW+OpenGL/Vulkan examples.
// 2018-03-20: Misc: Setup io.BackendFlags ImGuiBackendFlags_HasMouseCursors flag + honor ImGuiConfigFlags_NoMouseCursorChange flag.
// 2018-02-20: Inputs: Added support for mouse cursors (ImGui::GetMouseCursor() value, passed to glfwSetCursor()).
// 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves.
// 2018-02-06: Inputs: Added mapping for ImGuiKey_Space.
// 2018-01-25: Inputs: Added gamepad support if ImGuiConfigFlags_NavEnableGamepad is set.
// 2018-01-25: Inputs: Honoring the io.WantSetMousePos by repositioning the mouse (when using navigation and ImGuiConfigFlags_NavMoveMouse is set).
// 2018-01-20: Inputs: Added Horizontal Mouse Wheel support.
// 2018-01-18: Inputs: Added mapping for ImGuiKey_Insert.
// 2017-08-25: Inputs: MousePos set to -FLT_MAX,-FLT_MAX when mouse is unavailable/missing (instead of -1,-1).
// 2016-10-15: Misc: Added a void* user_data parameter to Clipboard function handlers.
#include "imgui.h"
#include "imgui_impl_glfw.h"
#include <math.h> // isinf
// GLFW
#include <GLFW/glfw3.h>
#ifdef _WIN32
#undef APIENTRY
#define GLFW_EXPOSE_NATIVE_WIN32
#include <GLFW/glfw3native.h> // for glfwGetWin32Window
#endif
#define GLFW_HAS_WINDOW_TOPMOST (GLFW_VERSION_MAJOR * 1000 + GLFW_VERSION_MINOR * 100 >= 3200) // 3.2+ GLFW_FLOATING
#define GLFW_HAS_WINDOW_HOVERED (GLFW_VERSION_MAJOR * 1000 + GLFW_VERSION_MINOR * 100 >= 3300) // 3.3+ GLFW_HOVERED
#define GLFW_HAS_WINDOW_ALPHA (GLFW_VERSION_MAJOR * 1000 + GLFW_VERSION_MINOR * 100 >= 3300) // 3.3+ glfwSetWindowOpacity
#define GLFW_HAS_PER_MONITOR_DPI (GLFW_VERSION_MAJOR * 1000 + GLFW_VERSION_MINOR * 100 >= 3300) // 3.3+ glfwGetMonitorContentScale
#define GLFW_HAS_VULKAN (GLFW_VERSION_MAJOR * 1000 + GLFW_VERSION_MINOR * 100 >= 3200) // 3.2+ glfwCreateWindowSurface
#define GLFW_HAS_FOCUS_WINDOW (GLFW_VERSION_MAJOR * 1000 + GLFW_VERSION_MINOR * 100 >= 3200) // 3.2+ glfwFocusWindow
#define GLFW_HAS_FOCUS_ON_SHOW (GLFW_VERSION_MAJOR * 1000 + GLFW_VERSION_MINOR * 100 >= 3300) // 3.3+ GLFW_FOCUS_ON_SHOW
#define GLFW_HAS_MONITOR_WORK_AREA (GLFW_VERSION_MAJOR * 1000 + GLFW_VERSION_MINOR * 100 >= 3300) // 3.3+ glfwGetMonitorWorkarea
#define GLFW_HAS_OSX_WINDOW_POS_FIX (GLFW_VERSION_MAJOR * 1000 + GLFW_VERSION_MINOR * 100 + GLFW_VERSION_REVISION * 10 >= 3310) // 3.3.1+ Fixed: Resizing window repositions it on MacOS #1553
#ifdef GLFW_RESIZE_NESW_CURSOR // Let's be nice to people who pulled GLFW between 2019-04-16 (3.4 define) and 2019-11-29 (cursors defines) // FIXME: Remove when GLFW 3.4 is released?
#define GLFW_HAS_NEW_CURSORS (GLFW_VERSION_MAJOR * 1000 + GLFW_VERSION_MINOR * 100 >= 3400) // 3.4+ GLFW_RESIZE_ALL_CURSOR, GLFW_RESIZE_NESW_CURSOR, GLFW_RESIZE_NWSE_CURSOR, GLFW_NOT_ALLOWED_CURSOR
#else
#define GLFW_HAS_NEW_CURSORS (0)
#endif
#ifdef GLFW_MOUSE_PASSTHROUGH // Let's be nice to people who pulled GLFW between 2019-04-16 (3.4 define) and 2020-07-17 (passthrough)
#define GLFW_HAS_MOUSE_PASSTHROUGH (GLFW_VERSION_MAJOR * 1000 + GLFW_VERSION_MINOR * 100 >= 3400) // 3.4+ GLFW_MOUSE_PASSTHROUGH
#else
#define GLFW_HAS_MOUSE_PASSTHROUGH (0)
#endif
// Data
enum GlfwClientApi
{
GlfwClientApi_Unknown,
GlfwClientApi_OpenGL,
GlfwClientApi_Vulkan
};
static GLFWwindow* g_Window = NULL; // Main window
static GlfwClientApi g_ClientApi = GlfwClientApi_Unknown;
static double g_Time = 0.0;
static bool g_MouseJustPressed[ImGuiMouseButton_COUNT] = {};
static GLFWcursor* g_MouseCursors[ImGuiMouseCursor_COUNT] = {};
static GLFWwindow* g_KeyOwnerWindows[512] = {};
static bool g_InstalledCallbacks = false;
static bool g_WantUpdateMonitors = true;
// Chain GLFW callbacks for main viewport: our callbacks will call the user's previously installed callbacks, if any.
static GLFWmousebuttonfun g_PrevUserCallbackMousebutton = NULL;
static GLFWscrollfun g_PrevUserCallbackScroll = NULL;
static GLFWcursorposfun g_PrevUserCallbackCursorPos = NULL;
static GLFWkeyfun g_PrevUserCallbackKey = NULL;
static GLFWcharfun g_PrevUserCallbackChar = NULL;
static GLFWmonitorfun g_PrevUserCallbackMonitor = NULL;
// Forward Declarations
static void ImGui_ImplGlfw_UpdateMonitors();
static void ImGui_ImplGlfw_InitPlatformInterface();
static void ImGui_ImplGlfw_ShutdownPlatformInterface();
static const char* ImGui_ImplGlfw_GetClipboardText(void* user_data)
{
return glfwGetClipboardString((GLFWwindow*)user_data);
}
static void ImGui_ImplGlfw_SetClipboardText(void* user_data, const char* text)
{
glfwSetClipboardString((GLFWwindow*)user_data, text);
}
void ImGui_ImplGlfw_MouseButtonCallback(GLFWwindow* window, int button, int action, int mods)
{
if (g_PrevUserCallbackMousebutton != NULL && window == g_Window)
g_PrevUserCallbackMousebutton(window, button, action, mods);
ImGuiIO& io = ImGui::GetIO();
io.FrameCountSinceLastInput = 0;
if (action == GLFW_PRESS && button >= 0 && button < IM_ARRAYSIZE(g_MouseJustPressed))
g_MouseJustPressed[button] = true;
}
void ImGui_ImplGlfw_ScrollCallback(GLFWwindow* window, double xoffset, double yoffset)
{
if (g_PrevUserCallbackScroll != NULL && window == g_Window)
g_PrevUserCallbackScroll(window, xoffset, yoffset);
ImGuiIO& io = ImGui::GetIO();
io.FrameCountSinceLastInput = 0;
io.MouseWheelH += (float)xoffset;
io.MouseWheel += (float)yoffset;
}
void ImGui_ImplGlfw_CursorPosCallback(GLFWwindow* window, double xpos, double ypos)
{
if (g_PrevUserCallbackCursorPos != NULL)
g_PrevUserCallbackCursorPos(window, xpos, ypos);
ImGuiIO& io = ImGui::GetIO();
io.FrameCountSinceLastInput = 0;
// Here, we just take note of the event without actually processing the cursor position.
// This is done in ImGui_ImplGlfw_NewFrame() / ImGui_ImplGlfw_UpdateMousePosAndButtons().
}
void ImGui_ImplGlfw_KeyCallback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
if (g_PrevUserCallbackKey != NULL && window == g_Window)
g_PrevUserCallbackKey(window, key, scancode, action, mods);
ImGuiIO& io = ImGui::GetIO();
io.FrameCountSinceLastInput = 0;
if (action == GLFW_PRESS)
{
io.KeysDown[key] = true;
g_KeyOwnerWindows[key] = window;
}
if (action == GLFW_RELEASE)
{
io.KeysDown[key] = false;
g_KeyOwnerWindows[key] = NULL;
}
// Modifiers are not reliable across systems
io.KeyCtrl = io.KeysDown[GLFW_KEY_LEFT_CONTROL] || io.KeysDown[GLFW_KEY_RIGHT_CONTROL];
io.KeyShift = io.KeysDown[GLFW_KEY_LEFT_SHIFT] || io.KeysDown[GLFW_KEY_RIGHT_SHIFT];
io.KeyAlt = io.KeysDown[GLFW_KEY_LEFT_ALT] || io.KeysDown[GLFW_KEY_RIGHT_ALT];
#ifdef _WIN32
io.KeySuper = false;
#else
io.KeySuper = io.KeysDown[GLFW_KEY_LEFT_SUPER] || io.KeysDown[GLFW_KEY_RIGHT_SUPER];
#endif
}
void ImGui_ImplGlfw_CharCallback(GLFWwindow* window, unsigned int c)
{
if (g_PrevUserCallbackChar != NULL && window == g_Window)
g_PrevUserCallbackChar(window, c);
ImGuiIO& io = ImGui::GetIO();
io.FrameCountSinceLastInput = 0;
io.AddInputCharacter(c);
}
void ImGui_ImplGlfw_MonitorCallback(GLFWmonitor*, int)
{
g_WantUpdateMonitors = true;
}
static bool ImGui_ImplGlfw_Init(GLFWwindow* window, bool install_callbacks, GlfwClientApi client_api)
{
g_Window = window;
g_Time = 0.0;
// Setup backend capabilities flags
ImGuiIO& io = ImGui::GetIO();
io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors; // We can honor GetMouseCursor() values (optional)
io.BackendFlags |= ImGuiBackendFlags_HasSetMousePos; // We can honor io.WantSetMousePos requests (optional, rarely used)
io.BackendFlags |= ImGuiBackendFlags_PlatformHasViewports; // We can create multi-viewports on the Platform side (optional)
#if GLFW_HAS_MOUSE_PASSTHROUGH || (GLFW_HAS_WINDOW_HOVERED && defined(_WIN32))
io.BackendFlags |= ImGuiBackendFlags_HasMouseHoveredViewport; // We can set io.MouseHoveredViewport correctly (optional, not easy)
#endif
io.BackendPlatformName = "imgui_impl_glfw";
// Keyboard mapping. Dear ImGui will use those indices to peek into the io.KeysDown[] array.
io.KeyMap[ImGuiKey_Tab] = GLFW_KEY_TAB;
io.KeyMap[ImGuiKey_LeftArrow] = GLFW_KEY_LEFT;
io.KeyMap[ImGuiKey_RightArrow] = GLFW_KEY_RIGHT;
io.KeyMap[ImGuiKey_UpArrow] = GLFW_KEY_UP;
io.KeyMap[ImGuiKey_DownArrow] = GLFW_KEY_DOWN;
io.KeyMap[ImGuiKey_PageUp] = GLFW_KEY_PAGE_UP;
io.KeyMap[ImGuiKey_PageDown] = GLFW_KEY_PAGE_DOWN;
io.KeyMap[ImGuiKey_Home] = GLFW_KEY_HOME;
io.KeyMap[ImGuiKey_End] = GLFW_KEY_END;
io.KeyMap[ImGuiKey_Insert] = GLFW_KEY_INSERT;
io.KeyMap[ImGuiKey_Delete] = GLFW_KEY_DELETE;
io.KeyMap[ImGuiKey_Backspace] = GLFW_KEY_BACKSPACE;
io.KeyMap[ImGuiKey_Space] = GLFW_KEY_SPACE;
io.KeyMap[ImGuiKey_Enter] = GLFW_KEY_ENTER;
io.KeyMap[ImGuiKey_Escape] = GLFW_KEY_ESCAPE;
io.KeyMap[ImGuiKey_KeyPadEnter] = GLFW_KEY_KP_ENTER;
io.KeyMap[ImGuiKey_A] = GLFW_KEY_A;
io.KeyMap[ImGuiKey_C] = GLFW_KEY_C;
io.KeyMap[ImGuiKey_V] = GLFW_KEY_V;
io.KeyMap[ImGuiKey_X] = GLFW_KEY_X;
io.KeyMap[ImGuiKey_Y] = GLFW_KEY_Y;
io.KeyMap[ImGuiKey_Z] = GLFW_KEY_Z;
io.SetClipboardTextFn = ImGui_ImplGlfw_SetClipboardText;
io.GetClipboardTextFn = ImGui_ImplGlfw_GetClipboardText;
io.ClipboardUserData = g_Window;
// Create mouse cursors
// (By design, on X11 cursors are user configurable and some cursors may be missing. When a cursor doesn't exist,
// GLFW will emit an error which will often be printed by the app, so we temporarily disable error reporting.
// Missing cursors will return NULL and our _UpdateMouseCursor() function will use the Arrow cursor instead.)
GLFWerrorfun prev_error_callback = glfwSetErrorCallback(NULL);
g_MouseCursors[ImGuiMouseCursor_Arrow] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR);
g_MouseCursors[ImGuiMouseCursor_TextInput] = glfwCreateStandardCursor(GLFW_IBEAM_CURSOR);
g_MouseCursors[ImGuiMouseCursor_ResizeNS] = glfwCreateStandardCursor(GLFW_VRESIZE_CURSOR);
g_MouseCursors[ImGuiMouseCursor_ResizeEW] = glfwCreateStandardCursor(GLFW_HRESIZE_CURSOR);
g_MouseCursors[ImGuiMouseCursor_Hand] = glfwCreateStandardCursor(GLFW_HAND_CURSOR);
#if GLFW_HAS_NEW_CURSORS
g_MouseCursors[ImGuiMouseCursor_ResizeAll] = glfwCreateStandardCursor(GLFW_RESIZE_ALL_CURSOR);
g_MouseCursors[ImGuiMouseCursor_ResizeNESW] = glfwCreateStandardCursor(GLFW_RESIZE_NESW_CURSOR);
g_MouseCursors[ImGuiMouseCursor_ResizeNWSE] = glfwCreateStandardCursor(GLFW_RESIZE_NWSE_CURSOR);
g_MouseCursors[ImGuiMouseCursor_NotAllowed] = glfwCreateStandardCursor(GLFW_NOT_ALLOWED_CURSOR);
#else
g_MouseCursors[ImGuiMouseCursor_ResizeAll] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR);
g_MouseCursors[ImGuiMouseCursor_ResizeNESW] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR);
g_MouseCursors[ImGuiMouseCursor_ResizeNWSE] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR);
g_MouseCursors[ImGuiMouseCursor_NotAllowed] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR);
#endif
glfwSetErrorCallback(prev_error_callback);
// Chain GLFW callbacks: our callbacks will call the user's previously installed callbacks, if any.
g_PrevUserCallbackMousebutton = NULL;
g_PrevUserCallbackScroll = NULL;
g_PrevUserCallbackKey = NULL;
g_PrevUserCallbackChar = NULL;
g_PrevUserCallbackMonitor = NULL;
if (install_callbacks)
{
g_InstalledCallbacks = true;
g_PrevUserCallbackMousebutton = glfwSetMouseButtonCallback(window, ImGui_ImplGlfw_MouseButtonCallback);
g_PrevUserCallbackScroll = glfwSetScrollCallback(window, ImGui_ImplGlfw_ScrollCallback);
g_PrevUserCallbackCursorPos = glfwSetCursorPosCallback(window, ImGui_ImplGlfw_CursorPosCallback);
g_PrevUserCallbackKey = glfwSetKeyCallback(window, ImGui_ImplGlfw_KeyCallback);
g_PrevUserCallbackChar = glfwSetCharCallback(window, ImGui_ImplGlfw_CharCallback);
g_PrevUserCallbackMonitor = glfwSetMonitorCallback(ImGui_ImplGlfw_MonitorCallback);
}
// Update monitors the first time (note: monitor callback are broken in GLFW 3.2 and earlier, see github.com/glfw/glfw/issues/784)
ImGui_ImplGlfw_UpdateMonitors();
glfwSetMonitorCallback(ImGui_ImplGlfw_MonitorCallback);
// Our mouse update function expect PlatformHandle to be filled for the main viewport
ImGuiViewport* main_viewport = ImGui::GetMainViewport();
main_viewport->PlatformHandle = (void*)g_Window;
#ifdef _WIN32
main_viewport->PlatformHandleRaw = glfwGetWin32Window(g_Window);
#endif
if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
ImGui_ImplGlfw_InitPlatformInterface();
g_ClientApi = client_api;
return true;
}
bool ImGui_ImplGlfw_InitForOpenGL(GLFWwindow* window, bool install_callbacks)
{
return ImGui_ImplGlfw_Init(window, install_callbacks, GlfwClientApi_OpenGL);
}
bool ImGui_ImplGlfw_InitForVulkan(GLFWwindow* window, bool install_callbacks)
{
return ImGui_ImplGlfw_Init(window, install_callbacks, GlfwClientApi_Vulkan);
}
bool ImGui_ImplGlfw_InitForOther(GLFWwindow* window, bool install_callbacks)
{
return ImGui_ImplGlfw_Init(window, install_callbacks, GlfwClientApi_Unknown);
}
void ImGui_ImplGlfw_Shutdown()
{
ImGui_ImplGlfw_ShutdownPlatformInterface();
if (g_InstalledCallbacks)
{
glfwSetMouseButtonCallback(g_Window, g_PrevUserCallbackMousebutton);
glfwSetScrollCallback(g_Window, g_PrevUserCallbackScroll);
glfwSetKeyCallback(g_Window, g_PrevUserCallbackKey);
glfwSetCharCallback(g_Window, g_PrevUserCallbackChar);
g_InstalledCallbacks = false;
}
for (ImGuiMouseCursor cursor_n = 0; cursor_n < ImGuiMouseCursor_COUNT; cursor_n++)
{
glfwDestroyCursor(g_MouseCursors[cursor_n]);
g_MouseCursors[cursor_n] = NULL;
}
g_ClientApi = GlfwClientApi_Unknown;
}
void ImGui_ImplGlfw_WaitForEvent()
{
if (!(ImGui::GetIO().ConfigFlags & ImGuiConfigFlags_EnablePowerSavingMode))
return;
bool window_is_hidden = false; //!glfwGetWindowAttrib(g_Window, GLFW_VISIBLE) || glfwGetWindowAttrib(g_Window, GLFW_ICONIFIED);
double waiting_time = window_is_hidden ? INFINITY : ImGui::GetEventWaitingTime();
if (waiting_time > 0.0)
{
if (isinf(waiting_time))
glfwWaitEvents();
else
glfwWaitEventsTimeout(waiting_time);
}
}
static void ImGui_ImplGlfw_UpdateMousePosAndButtons()
{
// Update buttons
ImGuiIO& io = ImGui::GetIO();
for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++)
{
// If a mouse press event came, always pass it as "mouse held this frame", so we don't miss click-release events that are shorter than 1 frame.
io.MouseDown[i] = g_MouseJustPressed[i] || glfwGetMouseButton(g_Window, i) != 0;
g_MouseJustPressed[i] = false;
}
// Update mouse position
const ImVec2 mouse_pos_backup = io.MousePos;
io.MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
io.MouseHoveredViewport = 0;
ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
for (int n = 0; n < platform_io.Viewports.Size; n++)
{
ImGuiViewport* viewport = platform_io.Viewports[n];
GLFWwindow* window = (GLFWwindow*)viewport->PlatformHandle;
IM_ASSERT(window != NULL);
#ifdef __EMSCRIPTEN__
const bool focused = true;
IM_ASSERT(platform_io.Viewports.Size == 1);
#else
const bool focused = glfwGetWindowAttrib(window, GLFW_FOCUSED) != 0;
#endif
if (focused)
{
if (io.WantSetMousePos)
{
glfwSetCursorPos(window, (double)(mouse_pos_backup.x - viewport->Pos.x), (double)(mouse_pos_backup.y - viewport->Pos.y));
}
else
{
double mouse_x, mouse_y;
glfwGetCursorPos(window, &mouse_x, &mouse_y);
if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
{
// Multi-viewport mode: mouse position in OS absolute coordinates (io.MousePos is (0,0) when the mouse is on the upper-left of the primary monitor)
int window_x, window_y;
glfwGetWindowPos(window, &window_x, &window_y);
io.MousePos = ImVec2((float)mouse_x + window_x, (float)mouse_y + window_y);
}
else
{
// Single viewport mode: mouse position in client window coordinates (io.MousePos is (0,0) when the mouse is on the upper-left corner of the app window)
io.MousePos = ImVec2((float)mouse_x, (float)mouse_y);
}
}
for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++)
io.MouseDown[i] |= glfwGetMouseButton(window, i) != 0;
}
// (Optional) When using multiple viewports: set io.MouseHoveredViewport to the viewport the OS mouse cursor is hovering.
// Important: this information is not easy to provide and many high-level windowing library won't be able to provide it correctly, because
// - This is _ignoring_ viewports with the ImGuiViewportFlags_NoInputs flag (pass-through windows).
// - This is _regardless_ of whether another viewport is focused or being dragged from.
// If ImGuiBackendFlags_HasMouseHoveredViewport is not set by the backend, imgui will ignore this field and infer the information by relying on the
// rectangles and last focused time of every viewports it knows about. It will be unaware of other windows that may be sitting between or over your windows.
// [GLFW] FIXME: This is currently only correct on Win32. See what we do below with the WM_NCHITTEST, missing an equivalent for other systems.
// See https://github.com/glfw/glfw/issues/1236 if you want to help in making this a GLFW feature.
#if GLFW_HAS_MOUSE_PASSTHROUGH || (GLFW_HAS_WINDOW_HOVERED && defined(_WIN32))
const bool window_no_input = (viewport->Flags & ImGuiViewportFlags_NoInputs) != 0;
#if GLFW_HAS_MOUSE_PASSTHROUGH
glfwSetWindowAttrib(window, GLFW_MOUSE_PASSTHROUGH, window_no_input);
#endif
if (glfwGetWindowAttrib(window, GLFW_HOVERED) && !window_no_input)
io.MouseHoveredViewport = viewport->ID;
#endif
}
}
static void ImGui_ImplGlfw_UpdateMouseCursor()
{
ImGuiIO& io = ImGui::GetIO();
if ((io.ConfigFlags & ImGuiConfigFlags_NoMouseCursorChange) || glfwGetInputMode(g_Window, GLFW_CURSOR) == GLFW_CURSOR_DISABLED)
return;
ImGuiMouseCursor imgui_cursor = ImGui::GetMouseCursor();
ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
for (int n = 0; n < platform_io.Viewports.Size; n++)
{
GLFWwindow* window = (GLFWwindow*)platform_io.Viewports[n]->PlatformHandle;
if (imgui_cursor == ImGuiMouseCursor_None || io.MouseDrawCursor)
{
// Hide OS mouse cursor if imgui is drawing it or if it wants no cursor
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_HIDDEN);
}
else
{
// Show OS mouse cursor
// FIXME-PLATFORM: Unfocused windows seems to fail changing the mouse cursor with GLFW 3.2, but 3.3 works here.
glfwSetCursor(window, g_MouseCursors[imgui_cursor] ? g_MouseCursors[imgui_cursor] : g_MouseCursors[ImGuiMouseCursor_Arrow]);
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL);
}
}
}
static void ImGui_ImplGlfw_UpdateGamepads()
{
ImGuiIO& io = ImGui::GetIO();
memset(io.NavInputs, 0, sizeof(io.NavInputs));
if ((io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) == 0)
return;
// Update gamepad inputs
#define MAP_BUTTON(NAV_NO, BUTTON_NO) { if (buttons_count > BUTTON_NO && buttons[BUTTON_NO] == GLFW_PRESS) io.NavInputs[NAV_NO] = 1.0f; }
#define MAP_ANALOG(NAV_NO, AXIS_NO, V0, V1) { float v = (axes_count > AXIS_NO) ? axes[AXIS_NO] : V0; v = (v - V0) / (V1 - V0); if (v > 1.0f) v = 1.0f; if (io.NavInputs[NAV_NO] < v) io.NavInputs[NAV_NO] = v; }
int axes_count = 0, buttons_count = 0;
const float* axes = glfwGetJoystickAxes(GLFW_JOYSTICK_1, &axes_count);
const unsigned char* buttons = glfwGetJoystickButtons(GLFW_JOYSTICK_1, &buttons_count);
MAP_BUTTON(ImGuiNavInput_Activate, 0); // Cross / A
MAP_BUTTON(ImGuiNavInput_Cancel, 1); // Circle / B
MAP_BUTTON(ImGuiNavInput_Menu, 2); // Square / X
MAP_BUTTON(ImGuiNavInput_Input, 3); // Triangle / Y
MAP_BUTTON(ImGuiNavInput_DpadLeft, 13); // D-Pad Left
MAP_BUTTON(ImGuiNavInput_DpadRight, 11); // D-Pad Right
MAP_BUTTON(ImGuiNavInput_DpadUp, 10); // D-Pad Up
MAP_BUTTON(ImGuiNavInput_DpadDown, 12); // D-Pad Down
MAP_BUTTON(ImGuiNavInput_FocusPrev, 4); // L1 / LB
MAP_BUTTON(ImGuiNavInput_FocusNext, 5); // R1 / RB
MAP_BUTTON(ImGuiNavInput_TweakSlow, 4); // L1 / LB
MAP_BUTTON(ImGuiNavInput_TweakFast, 5); // R1 / RB
MAP_ANALOG(ImGuiNavInput_LStickLeft, 0, -0.3f, -0.9f);
MAP_ANALOG(ImGuiNavInput_LStickRight,0, +0.3f, +0.9f);
MAP_ANALOG(ImGuiNavInput_LStickUp, 1, +0.3f, +0.9f);
MAP_ANALOG(ImGuiNavInput_LStickDown, 1, -0.3f, -0.9f);
#undef MAP_BUTTON
#undef MAP_ANALOG
if (axes_count > 0 && buttons_count > 0)
io.BackendFlags |= ImGuiBackendFlags_HasGamepad;
else
io.BackendFlags &= ~ImGuiBackendFlags_HasGamepad;
}
static void ImGui_ImplGlfw_UpdateMonitors()
{
ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
int monitors_count = 0;
GLFWmonitor** glfw_monitors = glfwGetMonitors(&monitors_count);
platform_io.Monitors.resize(0);
for (int n = 0; n < monitors_count; n++)
{
ImGuiPlatformMonitor monitor;
int x, y;
glfwGetMonitorPos(glfw_monitors[n], &x, &y);
const GLFWvidmode* vid_mode = glfwGetVideoMode(glfw_monitors[n]);
monitor.MainPos = monitor.WorkPos = ImVec2((float)x, (float)y);
monitor.MainSize = monitor.WorkSize = ImVec2((float)vid_mode->width, (float)vid_mode->height);
#if GLFW_HAS_MONITOR_WORK_AREA
int w, h;
glfwGetMonitorWorkarea(glfw_monitors[n], &x, &y, &w, &h);
if (w > 0 && h > 0) // Workaround a small GLFW issue reporting zero on monitor changes: https://github.com/glfw/glfw/pull/1761
{
monitor.WorkPos = ImVec2((float)x, (float)y);
monitor.WorkSize = ImVec2((float)w, (float)h);
}
#endif
#if GLFW_HAS_PER_MONITOR_DPI
// Warning: the validity of monitor DPI information on Windows depends on the application DPI awareness settings, which generally needs to be set in the manifest or at runtime.
float x_scale, y_scale;
glfwGetMonitorContentScale(glfw_monitors[n], &x_scale, &y_scale);
monitor.DpiScale = x_scale;
#endif
platform_io.Monitors.push_back(monitor);
}
g_WantUpdateMonitors = false;
}
void ImGui_ImplGlfw_NewFrame()
{
ImGuiIO& io = ImGui::GetIO();
IM_ASSERT(io.Fonts->IsBuilt() && "Font atlas not built! It is generally built by the renderer backend. Missing call to renderer _NewFrame() function? e.g. ImGui_ImplOpenGL3_NewFrame().");
// Setup display size (every frame to accommodate for window resizing)
int w, h;
int display_w, display_h;
glfwGetWindowSize(g_Window, &w, &h);
glfwGetFramebufferSize(g_Window, &display_w, &display_h);
io.DisplaySize = ImVec2((float)w, (float)h);
if (w > 0 && h > 0)
io.DisplayFramebufferScale = ImVec2((float)display_w / w, (float)display_h / h);
if (g_WantUpdateMonitors)
ImGui_ImplGlfw_UpdateMonitors();
// Setup time step
double current_time = glfwGetTime();
io.DeltaTime = g_Time > 0.0 ? (float)(current_time - g_Time) : (float)(1.0f / 60.0f);
g_Time = current_time;
ImGui_ImplGlfw_UpdateMousePosAndButtons();
ImGui_ImplGlfw_UpdateMouseCursor();
// Update game controllers (if enabled and available)
ImGui_ImplGlfw_UpdateGamepads();
}
//--------------------------------------------------------------------------------------------------------
// MULTI-VIEWPORT / PLATFORM INTERFACE SUPPORT
// This is an _advanced_ and _optional_ feature, allowing the backend to create and handle multiple viewports simultaneously.
// If you are new to dear imgui or creating a new binding for dear imgui, it is recommended that you completely ignore this section first..
//--------------------------------------------------------------------------------------------------------
// Helper structure we store in the void* RenderUserData field of each ImGuiViewport to easily retrieve our backend data.
struct ImGuiViewportDataGlfw
{
GLFWwindow* Window;
bool WindowOwned;
int IgnoreWindowPosEventFrame;
int IgnoreWindowSizeEventFrame;
ImGuiViewportDataGlfw() { Window = NULL; WindowOwned = false; IgnoreWindowSizeEventFrame = IgnoreWindowPosEventFrame = -1; }
~ImGuiViewportDataGlfw() { IM_ASSERT(Window == NULL); }
};
static void ImGui_ImplGlfw_WindowCloseCallback(GLFWwindow* window)
{
if (ImGuiViewport* viewport = ImGui::FindViewportByPlatformHandle(window))
viewport->PlatformRequestClose = true;
}
// GLFW may dispatch window pos/size events after calling glfwSetWindowPos()/glfwSetWindowSize().
// However: depending on the platform the callback may be invoked at different time:
// - on Windows it appears to be called within the glfwSetWindowPos()/glfwSetWindowSize() call
// - on Linux it is queued and invoked during glfwPollEvents()
// Because the event doesn't always fire on glfwSetWindowXXX() we use a frame counter tag to only
// ignore recent glfwSetWindowXXX() calls.
static void ImGui_ImplGlfw_WindowPosCallback(GLFWwindow* window, int, int)
{
if (ImGuiViewport* viewport = ImGui::FindViewportByPlatformHandle(window))
{
if (ImGuiViewportDataGlfw* data = (ImGuiViewportDataGlfw*)viewport->PlatformUserData)
{
bool ignore_event = (ImGui::GetFrameCount() <= data->IgnoreWindowPosEventFrame + 1);
//data->IgnoreWindowPosEventFrame = -1;
if (ignore_event)
return;
}
viewport->PlatformRequestMove = true;
}
}
static void ImGui_ImplGlfw_WindowSizeCallback(GLFWwindow* window, int, int)
{
if (ImGuiViewport* viewport = ImGui::FindViewportByPlatformHandle(window))
{
if (ImGuiViewportDataGlfw* data = (ImGuiViewportDataGlfw*)viewport->PlatformUserData)
{
bool ignore_event = (ImGui::GetFrameCount() <= data->IgnoreWindowSizeEventFrame + 1);
//data->IgnoreWindowSizeEventFrame = -1;
if (ignore_event)
return;
}
viewport->PlatformRequestResize = true;
}
}
static void ImGui_ImplGlfw_CreateWindow(ImGuiViewport* viewport)
{
ImGuiViewportDataGlfw* data = IM_NEW(ImGuiViewportDataGlfw)();
viewport->PlatformUserData = data;
// GLFW 3.2 unfortunately always set focus on glfwCreateWindow() if GLFW_VISIBLE is set, regardless of GLFW_FOCUSED
// With GLFW 3.3, the hint GLFW_FOCUS_ON_SHOW fixes this problem
glfwWindowHint(GLFW_VISIBLE, false);
glfwWindowHint(GLFW_FOCUSED, false);
#if GLFW_HAS_FOCUS_ON_SHOW
glfwWindowHint(GLFW_FOCUS_ON_SHOW, false);
#endif
glfwWindowHint(GLFW_DECORATED, (viewport->Flags & ImGuiViewportFlags_NoDecoration) ? false : true);
#if GLFW_HAS_WINDOW_TOPMOST
glfwWindowHint(GLFW_FLOATING, (viewport->Flags & ImGuiViewportFlags_TopMost) ? true : false);
#endif
GLFWwindow* share_window = (g_ClientApi == GlfwClientApi_OpenGL) ? g_Window : NULL;
data->Window = glfwCreateWindow((int)viewport->Size.x, (int)viewport->Size.y, "No Title Yet", NULL, share_window);
data->WindowOwned = true;
viewport->PlatformHandle = (void*)data->Window;
#ifdef _WIN32
viewport->PlatformHandleRaw = glfwGetWin32Window(data->Window);
#endif
glfwSetWindowPos(data->Window, (int)viewport->Pos.x, (int)viewport->Pos.y);
// Install GLFW callbacks for secondary viewports
glfwSetMouseButtonCallback(data->Window, ImGui_ImplGlfw_MouseButtonCallback);
glfwSetScrollCallback(data->Window, ImGui_ImplGlfw_ScrollCallback);
glfwSetKeyCallback(data->Window, ImGui_ImplGlfw_KeyCallback);
glfwSetCharCallback(data->Window, ImGui_ImplGlfw_CharCallback);
glfwSetWindowCloseCallback(data->Window, ImGui_ImplGlfw_WindowCloseCallback);
glfwSetWindowPosCallback(data->Window, ImGui_ImplGlfw_WindowPosCallback);
glfwSetWindowSizeCallback(data->Window, ImGui_ImplGlfw_WindowSizeCallback);
if (g_ClientApi == GlfwClientApi_OpenGL)
{
glfwMakeContextCurrent(data->Window);
glfwSwapInterval(0);
}
}
static void ImGui_ImplGlfw_DestroyWindow(ImGuiViewport* viewport)
{
if (ImGuiViewportDataGlfw* data = (ImGuiViewportDataGlfw*)viewport->PlatformUserData)
{
if (data->WindowOwned)
{
#if !GLFW_HAS_MOUSE_PASSTHROUGH && GLFW_HAS_WINDOW_HOVERED && defined(_WIN32)
HWND hwnd = (HWND)viewport->PlatformHandleRaw;
::RemovePropA(hwnd, "IMGUI_VIEWPORT");
#endif
// Release any keys that were pressed in the window being destroyed and are still held down,
// because we will not receive any release events after window is destroyed.
for (int i = 0; i < IM_ARRAYSIZE(g_KeyOwnerWindows); i++)
if (g_KeyOwnerWindows[i] == data->Window)
ImGui_ImplGlfw_KeyCallback(data->Window, i, 0, GLFW_RELEASE, 0); // Later params are only used for main viewport, on which this function is never called.
glfwDestroyWindow(data->Window);
}
data->Window = NULL;
IM_DELETE(data);
}
viewport->PlatformUserData = viewport->PlatformHandle = NULL;
}
// We have submitted https://github.com/glfw/glfw/pull/1568 to allow GLFW to support "transparent inputs".
// In the meanwhile we implement custom per-platform workarounds here (FIXME-VIEWPORT: Implement same work-around for Linux/OSX!)
#if !GLFW_HAS_MOUSE_PASSTHROUGH && GLFW_HAS_WINDOW_HOVERED && defined(_WIN32)
static WNDPROC g_GlfwWndProc = NULL;
static LRESULT CALLBACK WndProcNoInputs(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
if (msg == WM_NCHITTEST)
{
// Let mouse pass-through the window. This will allow the backend to set io.MouseHoveredViewport properly (which is OPTIONAL).
// The ImGuiViewportFlags_NoInputs flag is set while dragging a viewport, as want to detect the window behind the one we are dragging.
// If you cannot easily access those viewport flags from your windowing/event code: you may manually synchronize its state e.g. in
// your main loop after calling UpdatePlatformWindows(). Iterate all viewports/platform windows and pass the flag to your windowing system.
ImGuiViewport* viewport = (ImGuiViewport*)::GetPropA(hWnd, "IMGUI_VIEWPORT");
if (viewport->Flags & ImGuiViewportFlags_NoInputs)
return HTTRANSPARENT;
}
return ::CallWindowProc(g_GlfwWndProc, hWnd, msg, wParam, lParam);
}
#endif
static void ImGui_ImplGlfw_ShowWindow(ImGuiViewport* viewport)
{
ImGuiViewportDataGlfw* data = (ImGuiViewportDataGlfw*)viewport->PlatformUserData;
#if defined(_WIN32)
// GLFW hack: Hide icon from task bar
HWND hwnd = (HWND)viewport->PlatformHandleRaw;
if (viewport->Flags & ImGuiViewportFlags_NoTaskBarIcon)
{
LONG ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE);
ex_style &= ~WS_EX_APPWINDOW;
ex_style |= WS_EX_TOOLWINDOW;
::SetWindowLong(hwnd, GWL_EXSTYLE, ex_style);
}
// GLFW hack: install hook for WM_NCHITTEST message handler
#if !GLFW_HAS_MOUSE_PASSTHROUGH && GLFW_HAS_WINDOW_HOVERED && defined(_WIN32)
::SetPropA(hwnd, "IMGUI_VIEWPORT", viewport);
if (g_GlfwWndProc == NULL)
g_GlfwWndProc = (WNDPROC)::GetWindowLongPtr(hwnd, GWLP_WNDPROC);
::SetWindowLongPtr(hwnd, GWLP_WNDPROC, (LONG_PTR)WndProcNoInputs);
#endif
#if !GLFW_HAS_FOCUS_ON_SHOW
// GLFW hack: GLFW 3.2 has a bug where glfwShowWindow() also activates/focus the window.
// The fix was pushed to GLFW repository on 2018/01/09 and should be included in GLFW 3.3 via a GLFW_FOCUS_ON_SHOW window attribute.
// See https://github.com/glfw/glfw/issues/1189
// FIXME-VIEWPORT: Implement same work-around for Linux/OSX in the meanwhile.
if (viewport->Flags & ImGuiViewportFlags_NoFocusOnAppearing)
{
::ShowWindow(hwnd, SW_SHOWNA);
return;
}
#endif
#endif
glfwShowWindow(data->Window);
}
static ImVec2 ImGui_ImplGlfw_GetWindowPos(ImGuiViewport* viewport)
{
ImGuiViewportDataGlfw* data = (ImGuiViewportDataGlfw*)viewport->PlatformUserData;
int x = 0, y = 0;
glfwGetWindowPos(data->Window, &x, &y);
return ImVec2((float)x, (float)y);
}
static void ImGui_ImplGlfw_SetWindowPos(ImGuiViewport* viewport, ImVec2 pos)
{
ImGuiViewportDataGlfw* data = (ImGuiViewportDataGlfw*)viewport->PlatformUserData;
data->IgnoreWindowPosEventFrame = ImGui::GetFrameCount();
glfwSetWindowPos(data->Window, (int)pos.x, (int)pos.y);
}
static ImVec2 ImGui_ImplGlfw_GetWindowSize(ImGuiViewport* viewport)
{
ImGuiViewportDataGlfw* data = (ImGuiViewportDataGlfw*)viewport->PlatformUserData;
int w = 0, h = 0;
glfwGetWindowSize(data->Window, &w, &h);
return ImVec2((float)w, (float)h);
}
static void ImGui_ImplGlfw_SetWindowSize(ImGuiViewport* viewport, ImVec2 size)
{
ImGuiViewportDataGlfw* data = (ImGuiViewportDataGlfw*)viewport->PlatformUserData;
#if __APPLE__ && !GLFW_HAS_OSX_WINDOW_POS_FIX
// Native OS windows are positioned from the bottom-left corner on macOS, whereas on other platforms they are
// positioned from the upper-left corner. GLFW makes an effort to convert macOS style coordinates, however it
// doesn't handle it when changing size. We are manually moving the window in order for changes of size to be based
// on the upper-left corner.
int x, y, width, height;
glfwGetWindowPos(data->Window, &x, &y);
glfwGetWindowSize(data->Window, &width, &height);
glfwSetWindowPos(data->Window, x, y - height + size.y);
#endif
data->IgnoreWindowSizeEventFrame = ImGui::GetFrameCount();
glfwSetWindowSize(data->Window, (int)size.x, (int)size.y);
}
static void ImGui_ImplGlfw_SetWindowTitle(ImGuiViewport* viewport, const char* title)
{
ImGuiViewportDataGlfw* data = (ImGuiViewportDataGlfw*)viewport->PlatformUserData;
glfwSetWindowTitle(data->Window, title);
}
static void ImGui_ImplGlfw_SetWindowFocus(ImGuiViewport* viewport)
{
#if GLFW_HAS_FOCUS_WINDOW
ImGuiViewportDataGlfw* data = (ImGuiViewportDataGlfw*)viewport->PlatformUserData;
glfwFocusWindow(data->Window);
#else
// FIXME: What are the effect of not having this function? At the moment imgui doesn't actually call SetWindowFocus - we set that up ahead, will answer that question later.
(void)viewport;
#endif
}
static bool ImGui_ImplGlfw_GetWindowFocus(ImGuiViewport* viewport)
{
ImGuiViewportDataGlfw* data = (ImGuiViewportDataGlfw*)viewport->PlatformUserData;
return glfwGetWindowAttrib(data->Window, GLFW_FOCUSED) != 0;
}
static bool ImGui_ImplGlfw_GetWindowMinimized(ImGuiViewport* viewport)
{
ImGuiViewportDataGlfw* data = (ImGuiViewportDataGlfw*)viewport->PlatformUserData;
return glfwGetWindowAttrib(data->Window, GLFW_ICONIFIED) != 0;
}
#if GLFW_HAS_WINDOW_ALPHA
static void ImGui_ImplGlfw_SetWindowAlpha(ImGuiViewport* viewport, float alpha)
{
ImGuiViewportDataGlfw* data = (ImGuiViewportDataGlfw*)viewport->PlatformUserData;
glfwSetWindowOpacity(data->Window, alpha);
}
#endif
static void ImGui_ImplGlfw_RenderWindow(ImGuiViewport* viewport, void*)
{
ImGuiViewportDataGlfw* data = (ImGuiViewportDataGlfw*)viewport->PlatformUserData;
if (g_ClientApi == GlfwClientApi_OpenGL)
glfwMakeContextCurrent(data->Window);
}
static void ImGui_ImplGlfw_SwapBuffers(ImGuiViewport* viewport, void*)
{
ImGuiViewportDataGlfw* data = (ImGuiViewportDataGlfw*)viewport->PlatformUserData;
if (g_ClientApi == GlfwClientApi_OpenGL)
{
glfwMakeContextCurrent(data->Window);
glfwSwapBuffers(data->Window);
}
}
//--------------------------------------------------------------------------------------------------------
// IME (Input Method Editor) basic support for e.g. Asian language users
//--------------------------------------------------------------------------------------------------------
// We provide a Win32 implementation because this is such a common issue for IME users
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS)
#define HAS_WIN32_IME 1
#include <imm.h>
#ifdef _MSC_VER
#pragma comment(lib, "imm32")
#endif
static void ImGui_ImplWin32_SetImeInputPos(ImGuiViewport* viewport, ImVec2 pos)
{
COMPOSITIONFORM cf = { CFS_FORCE_POSITION, { (LONG)(pos.x - viewport->Pos.x), (LONG)(pos.y - viewport->Pos.y) }, { 0, 0, 0, 0 } };
if (HWND hwnd = (HWND)viewport->PlatformHandleRaw)
if (HIMC himc = ::ImmGetContext(hwnd))
{
::ImmSetCompositionWindow(himc, &cf);
::ImmReleaseContext(hwnd, himc);
}
}
#else
#define HAS_WIN32_IME 0
#endif
//--------------------------------------------------------------------------------------------------------
// Vulkan support (the Vulkan renderer needs to call a platform-side support function to create the surface)
//--------------------------------------------------------------------------------------------------------
// Avoid including <vulkan.h> so we can build without it
#if GLFW_HAS_VULKAN
#ifndef VULKAN_H_
#define VK_DEFINE_HANDLE(object) typedef struct object##_T* object;
#if defined(__LP64__) || defined(_WIN64) || defined(__x86_64__) || defined(_M_X64) || defined(__ia64) || defined (_M_IA64) || defined(__aarch64__) || defined(__powerpc64__)
#define VK_DEFINE_NON_DISPATCHABLE_HANDLE(object) typedef struct object##_T *object;
#else
#define VK_DEFINE_NON_DISPATCHABLE_HANDLE(object) typedef uint64_t object;
#endif
VK_DEFINE_HANDLE(VkInstance)
VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkSurfaceKHR)
struct VkAllocationCallbacks;
enum VkResult { VK_RESULT_MAX_ENUM = 0x7FFFFFFF };
#endif // VULKAN_H_
extern "C" { extern GLFWAPI VkResult glfwCreateWindowSurface(VkInstance instance, GLFWwindow* window, const VkAllocationCallbacks* allocator, VkSurfaceKHR* surface); }
static int ImGui_ImplGlfw_CreateVkSurface(ImGuiViewport* viewport, ImU64 vk_instance, const void* vk_allocator, ImU64* out_vk_surface)
{
ImGuiViewportDataGlfw* data = (ImGuiViewportDataGlfw*)viewport->PlatformUserData;
IM_ASSERT(g_ClientApi == GlfwClientApi_Vulkan);
VkResult err = glfwCreateWindowSurface((VkInstance)vk_instance, data->Window, (const VkAllocationCallbacks*)vk_allocator, (VkSurfaceKHR*)out_vk_surface);
return (int)err;
}
#endif // GLFW_HAS_VULKAN
static void ImGui_ImplGlfw_InitPlatformInterface()
{
// Register platform interface (will be coupled with a renderer interface)
ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
platform_io.Platform_CreateWindow = ImGui_ImplGlfw_CreateWindow;
platform_io.Platform_DestroyWindow = ImGui_ImplGlfw_DestroyWindow;
platform_io.Platform_ShowWindow = ImGui_ImplGlfw_ShowWindow;
platform_io.Platform_SetWindowPos = ImGui_ImplGlfw_SetWindowPos;
platform_io.Platform_GetWindowPos = ImGui_ImplGlfw_GetWindowPos;
platform_io.Platform_SetWindowSize = ImGui_ImplGlfw_SetWindowSize;
platform_io.Platform_GetWindowSize = ImGui_ImplGlfw_GetWindowSize;
platform_io.Platform_SetWindowFocus = ImGui_ImplGlfw_SetWindowFocus;
platform_io.Platform_GetWindowFocus = ImGui_ImplGlfw_GetWindowFocus;
platform_io.Platform_GetWindowMinimized = ImGui_ImplGlfw_GetWindowMinimized;
platform_io.Platform_SetWindowTitle = ImGui_ImplGlfw_SetWindowTitle;
platform_io.Platform_RenderWindow = ImGui_ImplGlfw_RenderWindow;
platform_io.Platform_SwapBuffers = ImGui_ImplGlfw_SwapBuffers;
#if GLFW_HAS_WINDOW_ALPHA
platform_io.Platform_SetWindowAlpha = ImGui_ImplGlfw_SetWindowAlpha;
#endif
#if GLFW_HAS_VULKAN
platform_io.Platform_CreateVkSurface = ImGui_ImplGlfw_CreateVkSurface;
#endif
#if HAS_WIN32_IME
platform_io.Platform_SetImeInputPos = ImGui_ImplWin32_SetImeInputPos;
#endif
// Register main window handle (which is owned by the main application, not by us)
// This is mostly for simplicity and consistency, so that our code (e.g. mouse handling etc.) can use same logic for main and secondary viewports.
ImGuiViewport* main_viewport = ImGui::GetMainViewport();
ImGuiViewportDataGlfw* data = IM_NEW(ImGuiViewportDataGlfw)();
data->Window = g_Window;
data->WindowOwned = false;
main_viewport->PlatformUserData = data;
main_viewport->PlatformHandle = (void*)g_Window;
}
static void ImGui_ImplGlfw_ShutdownPlatformInterface()
{
}
|
/**
* The MIT License (MIT)
*
* Copyright (c) 2013-2020 Winlin
*
* 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 <srs_service_utility.hpp>
#include <unistd.h>
#include <arpa/inet.h>
#include <net/if.h>
#include <ifaddrs.h>
#include <netdb.h>
#include <math.h>
#include <stdlib.h>
#include <map>
#include <sstream>
using namespace std;
#include <srs_service_st.hpp>
#include <srs_kernel_error.hpp>
#include <srs_kernel_consts.hpp>
#include <srs_kernel_log.hpp>
#include <srs_kernel_utility.hpp>
#include <srs_http_stack.hpp>
bool srs_string_is_http(string url)
{
return srs_string_starts_with(url, "http://", "https://");
}
bool srs_string_is_rtmp(string url)
{
return srs_string_starts_with(url, "rtmp://");
}
bool srs_is_digit_number(string str)
{
if (str.empty()) {
return false;
}
const char* p = str.c_str();
const char* p_end = str.data() + str.length();
for (; p < p_end; p++) {
if (*p != '0') {
break;
}
}
if (p == p_end) {
return true;
}
int64_t v = ::atoll(p);
int64_t powv = (int64_t)pow(10, p_end - p - 1);
return v / powv >= 1 && v / powv <= 9;
}
// we detect all network device as internet or intranet device, by its ip address.
// key is device name, for instance, eth0
// value is whether internet, for instance, true.
static std::map<std::string, bool> _srs_device_ifs;
bool srs_net_device_is_internet(string ifname)
{
srs_info("check ifname=%s", ifname.c_str());
if (_srs_device_ifs.find(ifname) == _srs_device_ifs.end()) {
return false;
}
return _srs_device_ifs[ifname];
}
bool srs_net_device_is_internet(const sockaddr* addr)
{
if(addr->sa_family == AF_INET) {
const in_addr inaddr = ((sockaddr_in*)addr)->sin_addr;
const uint32_t addr_h = ntohl(inaddr.s_addr);
// lo, 127.0.0.0-127.0.0.1
if (addr_h >= 0x7f000000 && addr_h <= 0x7f000001) {
return false;
}
// Class A 10.0.0.0-10.255.255.255
if (addr_h >= 0x0a000000 && addr_h <= 0x0affffff) {
return false;
}
// Class B 172.16.0.0-172.31.255.255
if (addr_h >= 0xac100000 && addr_h <= 0xac1fffff) {
return false;
}
// Class C 192.168.0.0-192.168.255.255
if (addr_h >= 0xc0a80000 && addr_h <= 0xc0a8ffff) {
return false;
}
} else if(addr->sa_family == AF_INET6) {
const sockaddr_in6* a6 = (const sockaddr_in6*)addr;
// IPv6 loopback is ::1
if (IN6_IS_ADDR_LOOPBACK(&a6->sin6_addr)) {
return false;
}
// IPv6 unspecified is ::
if (IN6_IS_ADDR_UNSPECIFIED(&a6->sin6_addr)) {
return false;
}
// From IPv4, you might know APIPA (Automatic Private IP Addressing) or AutoNet.
// Whenever automatic IP configuration through DHCP fails.
// The prefix of a site-local address is FE80::/10.
if (IN6_IS_ADDR_LINKLOCAL(&a6->sin6_addr)) {
return false;
}
// Site-local addresses are equivalent to private IP addresses in IPv4.
// The prefix of a site-local address is FEC0::/10.
// https://4sysops.com/archives/ipv6-tutorial-part-6-site-local-addresses-and-link-local-addresses/
if (IN6_IS_ADDR_SITELOCAL(&a6->sin6_addr)) {
return false;
}
}
return true;
}
vector<string> _srs_system_ips;
void discover_network_iface(ifaddrs* cur, vector<string>& ips, stringstream& ss0, stringstream& ss1, bool ipv6)
{
char saddr[64];
char* h = (char*)saddr;
socklen_t nbh = (socklen_t)sizeof(saddr);
const int r0 = getnameinfo(cur->ifa_addr, sizeof(sockaddr_storage), h, nbh, NULL, 0, NI_NUMERICHOST);
if(r0) {
srs_warn("convert local ip failed: %s", gai_strerror(r0));
return;
}
std::string ip(saddr, strlen(saddr));
ss0 << ", iface[" << (int)ips.size() << "] " << cur->ifa_name << " " << (ipv6? "ipv6":"ipv4")
<< " 0x" << std::hex << cur->ifa_flags << std::dec << " " << ip;
ips.push_back(ip);
// set the device internet status.
if (!srs_net_device_is_internet(cur->ifa_addr)) {
ss1 << ", intranet ";
_srs_device_ifs[cur->ifa_name] = false;
} else {
ss1 << ", internet ";
_srs_device_ifs[cur->ifa_name] = true;
}
ss1 << cur->ifa_name << " " << ip;
}
void retrieve_local_ips()
{
vector<string>& ips = _srs_system_ips;
ips.clear();
ifaddrs* ifap;
if (getifaddrs(&ifap) == -1) {
srs_warn("retrieve local ips, getifaddrs failed.");
return;
}
stringstream ss0;
ss0 << "ips";
stringstream ss1;
ss1 << "devices";
// Discover IPv4 first.
for (ifaddrs* p = ifap; p ; p = p->ifa_next) {
ifaddrs* cur = p;
// Ignore if no address for this interface.
// @see https://github.com/ossrs/srs/issues/1087#issuecomment-408847115
if (!cur->ifa_addr) {
continue;
}
// retrieve IP address, ignore the tun0 network device, whose addr is NULL.
// @see: https://github.com/ossrs/srs/issues/141
bool ipv4 = (cur->ifa_addr->sa_family == AF_INET);
bool ready = (cur->ifa_flags & IFF_UP) && (cur->ifa_flags & IFF_RUNNING);
bool ignored = (!cur->ifa_addr) || (cur->ifa_flags & IFF_POINTOPOINT) || (cur->ifa_flags & IFF_PROMISC) || (cur->ifa_flags & IFF_LOOPBACK);
if (ipv4 && ready && !ignored) {
discover_network_iface(cur, ips, ss0, ss1, false);
}
}
// Then, discover IPv6 addresses.
for (ifaddrs* p = ifap; p ; p = p->ifa_next) {
ifaddrs* cur = p;
// Ignore if no address for this interface.
// @see https://github.com/ossrs/srs/issues/1087#issuecomment-408847115
if (!cur->ifa_addr) {
continue;
}
// retrieve IP address, ignore the tun0 network device, whose addr is NULL.
// @see: https://github.com/ossrs/srs/issues/141
bool ipv6 = (cur->ifa_addr->sa_family == AF_INET6);
bool ready = (cur->ifa_flags & IFF_UP) && (cur->ifa_flags & IFF_RUNNING);
bool ignored = (!cur->ifa_addr) || (cur->ifa_flags & IFF_POINTOPOINT) || (cur->ifa_flags & IFF_PROMISC) || (cur->ifa_flags & IFF_LOOPBACK);
if (ipv6 && ready && !ignored) {
discover_network_iface(cur, ips, ss0, ss1, true);
}
}
// If empty, disover IPv4 loopback.
if (ips.empty()) {
for (ifaddrs* p = ifap; p ; p = p->ifa_next) {
ifaddrs* cur = p;
// Ignore if no address for this interface.
// @see https://github.com/ossrs/srs/issues/1087#issuecomment-408847115
if (!cur->ifa_addr) {
continue;
}
// retrieve IP address, ignore the tun0 network device, whose addr is NULL.
// @see: https://github.com/ossrs/srs/issues/141
bool ipv4 = (cur->ifa_addr->sa_family == AF_INET);
bool ready = (cur->ifa_flags & IFF_UP) && (cur->ifa_flags & IFF_RUNNING);
bool ignored = (!cur->ifa_addr) || (cur->ifa_flags & IFF_POINTOPOINT) || (cur->ifa_flags & IFF_PROMISC);
if (ipv4 && ready && !ignored) {
discover_network_iface(cur, ips, ss0, ss1, false);
}
}
}
srs_trace(ss0.str().c_str());
srs_trace(ss1.str().c_str());
freeifaddrs(ifap);
}
vector<string>& srs_get_local_ips()
{
if (_srs_system_ips.empty()) {
retrieve_local_ips();
}
return _srs_system_ips;
}
std::string _public_internet_address;
string srs_get_public_internet_address()
{
if (!_public_internet_address.empty()) {
return _public_internet_address;
}
std::vector<std::string>& ips = srs_get_local_ips();
// find the best match public address.
for (int i = 0; i < (int)ips.size(); i++) {
std::string ip = ips[i];
// TODO: FIXME: Support ipv6.
if (ip.find(".") == string::npos) {
continue;
}
in_addr_t addr = inet_addr(ip.c_str());
uint32_t addr_h = ntohl(addr);
// lo, 127.0.0.0-127.0.0.1
if (addr_h >= 0x7f000000 && addr_h <= 0x7f000001) {
srs_trace("ignore private address: %s", ip.c_str());
continue;
}
// Class A 10.0.0.0-10.255.255.255
if (addr_h >= 0x0a000000 && addr_h <= 0x0affffff) {
srs_trace("ignore private address: %s", ip.c_str());
continue;
}
// Class B 172.16.0.0-172.31.255.255
if (addr_h >= 0xac100000 && addr_h <= 0xac1fffff) {
srs_trace("ignore private address: %s", ip.c_str());
continue;
}
// Class C 192.168.0.0-192.168.255.255
if (addr_h >= 0xc0a80000 && addr_h <= 0xc0a8ffff) {
srs_trace("ignore private address: %s", ip.c_str());
continue;
}
srs_warn("use public address as ip: %s", ip.c_str());
// _public_internet_address = ip;
// return ip;
}
// no public address, use private address.
for (int i = 0; i < (int)ips.size(); i++) {
std::string ip = ips[i];
// TODO: FIXME: Support ipv6.
if (ip.find(".") == string::npos) {
continue;
}
in_addr_t addr = inet_addr(ip.c_str());
uint32_t addr_h = ntohl(addr);
// lo, 127.0.0.0-127.0.0.1
if (addr_h >= 0x7f000000 && addr_h <= 0x7f000001) {
srs_trace("ignore private address: %s", ip.c_str());
continue;
}
srs_warn("use private address as ip: %s", ip.c_str());
_public_internet_address = ip;
return ip;
}
// Finally, use first whatever kind of address.
if (!ips.empty() && _public_internet_address.empty()) {
string ip = ips.at(0);
srs_warn("use first address as ip: %s", ip.c_str());
_public_internet_address = ip;
return ip;
}
return "";
}
string srs_get_original_ip(ISrsHttpMessage* r)
{
SrsHttpHeader* h = r->header();
string x_forwarded_for = h->get("X-Forwarded-For");
if (!x_forwarded_for.empty()) {
size_t pos = string::npos;
if ((pos = x_forwarded_for.find(",")) == string::npos) {
return x_forwarded_for;
}
return x_forwarded_for.substr(0, pos);
}
string x_real_ip = h->get("X-Real-IP");
if (!x_real_ip.empty()) {
size_t pos = string::npos;
if ((pos = x_real_ip.find(":")) == string::npos) {
return x_real_ip;
}
return x_real_ip.substr(0, pos);
}
return "";
}
|
/* Димитър Валериев Трифонов, КН, 50Б, 146518 */
/*
14. Зададен е едномерен масив от цели числа А0, А1,...,Аn-1.
Да се състави програма, която създава нов масив а0, а1,...,аn-1,
като стойността на аi е равна на първата цифра на Аi.
*/
#include "stdafx.h"
using namespace std;
#include <iostream>
#include <stdlib.h>
#include <conio.h>
#include <math.h>
void main(){
system("chcp 1251");
int A[30], n, i;
int a[30];
int c[60];
cout << "Enter n: "; cin >> n;
for (i = 0; i < n; i++)
{
cout << "A[" << i << "]: "; cin >> A[i];
while (A[i] > 0)
{
c[i] = A[i] % 10;
a[i] = c[i];
A[i] = A[i] / 10;
}
}
cout << endl;
for (i = 0; i < n; i++)
{
cout << "a[" << i << "]: " << a[i] << endl;
}
_getch();
}
|
// generated from
// rosidl_typesupport_fastrtps_cpp/resource/msg__rosidl_typesupport_fastrtps_cpp.hpp.em
// generated code does not contain a copyright notice
#ifndef SENSOR_MSGS__MSG__BATTERY_STATE__ROSIDL_TYPESUPPORT_FASTRTPS_CPP_HPP_
#define SENSOR_MSGS__MSG__BATTERY_STATE__ROSIDL_TYPESUPPORT_FASTRTPS_CPP_HPP_
#include "rosidl_generator_c/message_type_support_struct.h"
#include "rosidl_typesupport_interface/macros.h"
#include "sensor_msgs/msg/rosidl_typesupport_fastrtps_cpp__visibility_control.h"
#include "sensor_msgs/msg/battery_state__struct.hpp"
#ifndef _WIN32
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wunused-parameter"
# ifdef __clang__
# pragma clang diagnostic ignored "-Wdeprecated-register"
# pragma clang diagnostic ignored "-Wreturn-type-c-linkage"
# endif
#endif
#ifndef _WIN32
# pragma GCC diagnostic pop
#endif
#include "fastcdr/Cdr.h"
namespace sensor_msgs
{
namespace msg
{
namespace typesupport_fastrtps_cpp
{
bool
ROSIDL_TYPESUPPORT_FASTRTPS_CPP_PUBLIC_sensor_msgs
cdr_serialize(
const sensor_msgs::msg::BatteryState & ros_message,
eprosima::fastcdr::Cdr & cdr);
bool
ROSIDL_TYPESUPPORT_FASTRTPS_CPP_PUBLIC_sensor_msgs
cdr_deserialize(
eprosima::fastcdr::Cdr & cdr,
sensor_msgs::msg::BatteryState & ros_message);
size_t
ROSIDL_TYPESUPPORT_FASTRTPS_CPP_PUBLIC_sensor_msgs
get_serialized_size(
const sensor_msgs::msg::BatteryState & ros_message,
size_t current_alignment);
size_t
ROSIDL_TYPESUPPORT_FASTRTPS_CPP_PUBLIC_sensor_msgs
max_serialized_size_BatteryState(
bool & full_bounded,
size_t current_alignment);
} // namespace typesupport_fastrtps_cpp
} // namespace msg
} // namespace sensor_msgs
#ifdef __cplusplus
extern "C"
{
#endif
ROSIDL_TYPESUPPORT_FASTRTPS_CPP_PUBLIC_sensor_msgs
const rosidl_message_type_support_t *
ROSIDL_TYPESUPPORT_INTERFACE__MESSAGE_SYMBOL_NAME(rosidl_typesupport_fastrtps_cpp, sensor_msgs, msg, BatteryState)();
#ifdef __cplusplus
}
#endif
#endif // SENSOR_MSGS__MSG__BATTERY_STATE__ROSIDL_TYPESUPPORT_FASTRTPS_CPP_HPP_
|
#UNION
#include<bits/stdc++.h>
using namespace std;
int main()
{
//code
int t,n,m;
cin>>t;
while(t--)
{
cin>>n>>m;
int a[n], b[m];
unordered_set <int> s;
for(int i=0;i<n;i++)
{
cin>>a[i];
s.insert(a[i]);
}
for(int i=0;i<m;i++)
{
cin>>b[i];
s.insert(b[i]);
}
cout<<s.size()<<endl;
}
return 0;
}
#Intersection
#include<bits/stdc++.h>
using namespace std;
int main()
{
//code
int t,n,m;
cin>>t;
while(t--)
{
cin>>n>>m;
int a[n], b[m];
set <int> s;
for(int i=0;i<n;i++)
{
cin>>a[i];
s.insert(a[i]);
}
for(int i=0;i<m;i++)
{
cin>>b[i];
//s.insert(b[i]);
}
for(int j = 0; j<m; j++)
{
if(s.find(b[j])!= s.end())
cout<<b[j]<<" ";
}
//cout<<s.size()<<endl;
// for(auto it = s.begin(); it!= s.end(); it++)
// {
// cout<<*it<<" ";
// }
cout<<endl;
}
return 0;
}
|
/*
* Copyright 2011 The LibYuv 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 "libyuv/row.h"
#ifdef __cplusplus
namespace libyuv {
extern "C" {
#endif
// This module is for GCC x86 and x64.
#if !defined(LIBYUV_DISABLE_X86) && \
(defined(__x86_64__) || (defined(__i386__) && !defined(_MSC_VER)))
#if defined(HAS_ARGBTOYROW_SSSE3) || defined(HAS_ARGBGRAYROW_SSSE3)
// Constants for ARGB
static const uvec8 kARGBToY = {25u, 129u, 66u, 0u, 25u, 129u, 66u, 0u,
25u, 129u, 66u, 0u, 25u, 129u, 66u, 0u};
// JPeg full range.
static const uvec8 kARGBToYJ = {29u, 150u, 77u, 0u, 29u, 150u, 77u, 0u,
29u, 150u, 77u, 0u, 29u, 150u, 77u, 0u};
static const uvec8 kRGBAToYJ = {0u, 29u, 150u, 77u, 0u, 29u, 150u, 77u,
0u, 29u, 150u, 77u, 0u, 29u, 150u, 77u};
#endif // defined(HAS_ARGBTOYROW_SSSE3) || defined(HAS_ARGBGRAYROW_SSSE3)
#if defined(HAS_ARGBTOYROW_SSSE3) || defined(HAS_I422TOARGBROW_SSSE3)
static const vec8 kARGBToU = {112, -74, -38, 0, 112, -74, -38, 0,
112, -74, -38, 0, 112, -74, -38, 0};
static const vec8 kARGBToUJ = {127, -84, -43, 0, 127, -84, -43, 0,
127, -84, -43, 0, 127, -84, -43, 0};
static const vec8 kARGBToV = {-18, -94, 112, 0, -18, -94, 112, 0,
-18, -94, 112, 0, -18, -94, 112, 0};
static const vec8 kARGBToVJ = {-20, -107, 127, 0, -20, -107, 127, 0,
-20, -107, 127, 0, -20, -107, 127, 0};
// Constants for BGRA
static const uvec8 kBGRAToY = {0u, 66u, 129u, 25u, 0u, 66u, 129u, 25u,
0u, 66u, 129u, 25u, 0u, 66u, 129u, 25u};
static const vec8 kBGRAToU = {0, -38, -74, 112, 0, -38, -74, 112,
0, -38, -74, 112, 0, -38, -74, 112};
static const vec8 kBGRAToV = {0, 112, -94, -18, 0, 112, -94, -18,
0, 112, -94, -18, 0, 112, -94, -18};
// Constants for ABGR
static const uvec8 kABGRToY = {66u, 129u, 25u, 0u, 66u, 129u, 25u, 0u,
66u, 129u, 25u, 0u, 66u, 129u, 25u, 0u};
static const vec8 kABGRToU = {-38, -74, 112, 0, -38, -74, 112, 0,
-38, -74, 112, 0, -38, -74, 112, 0};
static const vec8 kABGRToV = {112, -94, -18, 0, 112, -94, -18, 0,
112, -94, -18, 0, 112, -94, -18, 0};
// Constants for RGBA.
static const uvec8 kRGBAToY = {0u, 25u, 129u, 66u, 0u, 25u, 129u, 66u,
0u, 25u, 129u, 66u, 0u, 25u, 129u, 66u};
static const vec8 kRGBAToU = {0, 112, -74, -38, 0, 112, -74, -38,
0, 112, -74, -38, 0, 112, -74, -38};
static const vec8 kRGBAToV = {0, -18, -94, 112, 0, -18, -94, 112,
0, -18, -94, 112, 0, -18, -94, 112};
static const uvec16 kAddY16 = {0x7e80u, 0x7e80u, 0x7e80u, 0x7e80u,
0x7e80u, 0x7e80u, 0x7e80u, 0x7e80u};
static const uvec8 kAddUV128 = {128u, 128u, 128u, 128u, 128u, 128u, 128u, 128u,
128u, 128u, 128u, 128u, 128u, 128u, 128u, 128u};
static const uvec16 kSub128 = {0x8080u, 0x8080u, 0x8080u, 0x8080u,
0x8080u, 0x8080u, 0x8080u, 0x8080u};
#endif // defined(HAS_ARGBTOYROW_SSSE3) || defined(HAS_I422TOARGBROW_SSSE3)
#ifdef HAS_RGB24TOARGBROW_SSSE3
// Shuffle table for converting RGB24 to ARGB.
static const uvec8 kShuffleMaskRGB24ToARGB = {
0u, 1u, 2u, 12u, 3u, 4u, 5u, 13u, 6u, 7u, 8u, 14u, 9u, 10u, 11u, 15u};
// Shuffle table for converting RAW to ARGB.
static const uvec8 kShuffleMaskRAWToARGB = {2u, 1u, 0u, 12u, 5u, 4u, 3u, 13u,
8u, 7u, 6u, 14u, 11u, 10u, 9u, 15u};
// Shuffle table for converting RAW to RGBA.
static const uvec8 kShuffleMaskRAWToRGBA = {12u, 2u, 1u, 0u, 13u, 5u, 4u, 3u,
14u, 8u, 7u, 6u, 15u, 11u, 10u, 9u};
// Shuffle table for converting RAW to RGB24. First 8.
static const uvec8 kShuffleMaskRAWToRGB24_0 = {
2u, 1u, 0u, 5u, 4u, 3u, 8u, 7u,
128u, 128u, 128u, 128u, 128u, 128u, 128u, 128u};
// Shuffle table for converting RAW to RGB24. Middle 8.
static const uvec8 kShuffleMaskRAWToRGB24_1 = {
2u, 7u, 6u, 5u, 10u, 9u, 8u, 13u,
128u, 128u, 128u, 128u, 128u, 128u, 128u, 128u};
// Shuffle table for converting RAW to RGB24. Last 8.
static const uvec8 kShuffleMaskRAWToRGB24_2 = {
8u, 7u, 12u, 11u, 10u, 15u, 14u, 13u,
128u, 128u, 128u, 128u, 128u, 128u, 128u, 128u};
// Shuffle table for converting ARGB to RGB24.
static const uvec8 kShuffleMaskARGBToRGB24 = {
0u, 1u, 2u, 4u, 5u, 6u, 8u, 9u, 10u, 12u, 13u, 14u, 128u, 128u, 128u, 128u};
// Shuffle table for converting ARGB to RAW.
static const uvec8 kShuffleMaskARGBToRAW = {
2u, 1u, 0u, 6u, 5u, 4u, 10u, 9u, 8u, 14u, 13u, 12u, 128u, 128u, 128u, 128u};
// Shuffle table for converting ARGBToRGB24 for I422ToRGB24. First 8 + next 4
static const uvec8 kShuffleMaskARGBToRGB24_0 = {
0u, 1u, 2u, 4u, 5u, 6u, 8u, 9u, 128u, 128u, 128u, 128u, 10u, 12u, 13u, 14u};
// YUY2 shuf 16 Y to 32 Y.
static const lvec8 kShuffleYUY2Y = {0, 0, 2, 2, 4, 4, 6, 6, 8, 8, 10,
10, 12, 12, 14, 14, 0, 0, 2, 2, 4, 4,
6, 6, 8, 8, 10, 10, 12, 12, 14, 14};
// YUY2 shuf 8 UV to 16 UV.
static const lvec8 kShuffleYUY2UV = {1, 3, 1, 3, 5, 7, 5, 7, 9, 11, 9,
11, 13, 15, 13, 15, 1, 3, 1, 3, 5, 7,
5, 7, 9, 11, 9, 11, 13, 15, 13, 15};
// UYVY shuf 16 Y to 32 Y.
static const lvec8 kShuffleUYVYY = {1, 1, 3, 3, 5, 5, 7, 7, 9, 9, 11,
11, 13, 13, 15, 15, 1, 1, 3, 3, 5, 5,
7, 7, 9, 9, 11, 11, 13, 13, 15, 15};
// UYVY shuf 8 UV to 16 UV.
static const lvec8 kShuffleUYVYUV = {0, 2, 0, 2, 4, 6, 4, 6, 8, 10, 8,
10, 12, 14, 12, 14, 0, 2, 0, 2, 4, 6,
4, 6, 8, 10, 8, 10, 12, 14, 12, 14};
// NV21 shuf 8 VU to 16 UV.
static const lvec8 kShuffleNV21 = {
1, 0, 1, 0, 3, 2, 3, 2, 5, 4, 5, 4, 7, 6, 7, 6,
1, 0, 1, 0, 3, 2, 3, 2, 5, 4, 5, 4, 7, 6, 7, 6,
};
#endif // HAS_RGB24TOARGBROW_SSSE3
#ifdef HAS_J400TOARGBROW_SSE2
void J400ToARGBRow_SSE2(const uint8_t* src_y, uint8_t* dst_argb, int width) {
asm volatile(
"pcmpeqb %%xmm5,%%xmm5 \n"
"pslld $0x18,%%xmm5 \n"
LABELALIGN
"1: \n"
"movq (%0),%%xmm0 \n"
"lea 0x8(%0),%0 \n"
"punpcklbw %%xmm0,%%xmm0 \n"
"movdqa %%xmm0,%%xmm1 \n"
"punpcklwd %%xmm0,%%xmm0 \n"
"punpckhwd %%xmm1,%%xmm1 \n"
"por %%xmm5,%%xmm0 \n"
"por %%xmm5,%%xmm1 \n"
"movdqu %%xmm0,(%1) \n"
"movdqu %%xmm1,0x10(%1) \n"
"lea 0x20(%1),%1 \n"
"sub $0x8,%2 \n"
"jg 1b \n"
: "+r"(src_y), // %0
"+r"(dst_argb), // %1
"+r"(width) // %2
::"memory",
"cc", "xmm0", "xmm1", "xmm5");
}
#endif // HAS_J400TOARGBROW_SSE2
#ifdef HAS_RGB24TOARGBROW_SSSE3
void RGB24ToARGBRow_SSSE3(const uint8_t* src_rgb24,
uint8_t* dst_argb,
int width) {
asm volatile(
"pcmpeqb %%xmm5,%%xmm5 \n" // 0xff000000
"pslld $0x18,%%xmm5 \n"
"movdqa %3,%%xmm4 \n"
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"movdqu 0x10(%0),%%xmm1 \n"
"movdqu 0x20(%0),%%xmm3 \n"
"lea 0x30(%0),%0 \n"
"movdqa %%xmm3,%%xmm2 \n"
"palignr $0x8,%%xmm1,%%xmm2 \n"
"pshufb %%xmm4,%%xmm2 \n"
"por %%xmm5,%%xmm2 \n"
"palignr $0xc,%%xmm0,%%xmm1 \n"
"pshufb %%xmm4,%%xmm0 \n"
"movdqu %%xmm2,0x20(%1) \n"
"por %%xmm5,%%xmm0 \n"
"pshufb %%xmm4,%%xmm1 \n"
"movdqu %%xmm0,(%1) \n"
"por %%xmm5,%%xmm1 \n"
"palignr $0x4,%%xmm3,%%xmm3 \n"
"pshufb %%xmm4,%%xmm3 \n"
"movdqu %%xmm1,0x10(%1) \n"
"por %%xmm5,%%xmm3 \n"
"movdqu %%xmm3,0x30(%1) \n"
"lea 0x40(%1),%1 \n"
"sub $0x10,%2 \n"
"jg 1b \n"
: "+r"(src_rgb24), // %0
"+r"(dst_argb), // %1
"+r"(width) // %2
: "m"(kShuffleMaskRGB24ToARGB) // %3
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5");
}
void RAWToARGBRow_SSSE3(const uint8_t* src_raw, uint8_t* dst_argb, int width) {
asm volatile(
"pcmpeqb %%xmm5,%%xmm5 \n" // 0xff000000
"pslld $0x18,%%xmm5 \n"
"movdqa %3,%%xmm4 \n"
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"movdqu 0x10(%0),%%xmm1 \n"
"movdqu 0x20(%0),%%xmm3 \n"
"lea 0x30(%0),%0 \n"
"movdqa %%xmm3,%%xmm2 \n"
"palignr $0x8,%%xmm1,%%xmm2 \n"
"pshufb %%xmm4,%%xmm2 \n"
"por %%xmm5,%%xmm2 \n"
"palignr $0xc,%%xmm0,%%xmm1 \n"
"pshufb %%xmm4,%%xmm0 \n"
"movdqu %%xmm2,0x20(%1) \n"
"por %%xmm5,%%xmm0 \n"
"pshufb %%xmm4,%%xmm1 \n"
"movdqu %%xmm0,(%1) \n"
"por %%xmm5,%%xmm1 \n"
"palignr $0x4,%%xmm3,%%xmm3 \n"
"pshufb %%xmm4,%%xmm3 \n"
"movdqu %%xmm1,0x10(%1) \n"
"por %%xmm5,%%xmm3 \n"
"movdqu %%xmm3,0x30(%1) \n"
"lea 0x40(%1),%1 \n"
"sub $0x10,%2 \n"
"jg 1b \n"
: "+r"(src_raw), // %0
"+r"(dst_argb), // %1
"+r"(width) // %2
: "m"(kShuffleMaskRAWToARGB) // %3
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5");
}
// Same code as RAWToARGB with different shuffler and A in low bits
void RAWToRGBARow_SSSE3(const uint8_t* src_raw, uint8_t* dst_rgba, int width) {
asm volatile(
"pcmpeqb %%xmm5,%%xmm5 \n" // 0x000000ff
"psrld $0x18,%%xmm5 \n"
"movdqa %3,%%xmm4 \n"
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"movdqu 0x10(%0),%%xmm1 \n"
"movdqu 0x20(%0),%%xmm3 \n"
"lea 0x30(%0),%0 \n"
"movdqa %%xmm3,%%xmm2 \n"
"palignr $0x8,%%xmm1,%%xmm2 \n"
"pshufb %%xmm4,%%xmm2 \n"
"por %%xmm5,%%xmm2 \n"
"palignr $0xc,%%xmm0,%%xmm1 \n"
"pshufb %%xmm4,%%xmm0 \n"
"movdqu %%xmm2,0x20(%1) \n"
"por %%xmm5,%%xmm0 \n"
"pshufb %%xmm4,%%xmm1 \n"
"movdqu %%xmm0,(%1) \n"
"por %%xmm5,%%xmm1 \n"
"palignr $0x4,%%xmm3,%%xmm3 \n"
"pshufb %%xmm4,%%xmm3 \n"
"movdqu %%xmm1,0x10(%1) \n"
"por %%xmm5,%%xmm3 \n"
"movdqu %%xmm3,0x30(%1) \n"
"lea 0x40(%1),%1 \n"
"sub $0x10,%2 \n"
"jg 1b \n"
: "+r"(src_raw), // %0
"+r"(dst_rgba), // %1
"+r"(width) // %2
: "m"(kShuffleMaskRAWToRGBA) // %3
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5");
}
void RAWToRGB24Row_SSSE3(const uint8_t* src_raw,
uint8_t* dst_rgb24,
int width) {
asm volatile(
"movdqa %3,%%xmm3 \n"
"movdqa %4,%%xmm4 \n"
"movdqa %5,%%xmm5 \n"
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"movdqu 0x4(%0),%%xmm1 \n"
"movdqu 0x8(%0),%%xmm2 \n"
"lea 0x18(%0),%0 \n"
"pshufb %%xmm3,%%xmm0 \n"
"pshufb %%xmm4,%%xmm1 \n"
"pshufb %%xmm5,%%xmm2 \n"
"movq %%xmm0,(%1) \n"
"movq %%xmm1,0x8(%1) \n"
"movq %%xmm2,0x10(%1) \n"
"lea 0x18(%1),%1 \n"
"sub $0x8,%2 \n"
"jg 1b \n"
: "+r"(src_raw), // %0
"+r"(dst_rgb24), // %1
"+r"(width) // %2
: "m"(kShuffleMaskRAWToRGB24_0), // %3
"m"(kShuffleMaskRAWToRGB24_1), // %4
"m"(kShuffleMaskRAWToRGB24_2) // %5
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5");
}
void RGB565ToARGBRow_SSE2(const uint8_t* src, uint8_t* dst, int width) {
asm volatile(
"mov $0x1080108,%%eax \n"
"movd %%eax,%%xmm5 \n"
"pshufd $0x0,%%xmm5,%%xmm5 \n"
"mov $0x20802080,%%eax \n"
"movd %%eax,%%xmm6 \n"
"pshufd $0x0,%%xmm6,%%xmm6 \n"
"pcmpeqb %%xmm3,%%xmm3 \n"
"psllw $0xb,%%xmm3 \n"
"pcmpeqb %%xmm4,%%xmm4 \n"
"psllw $0xa,%%xmm4 \n"
"psrlw $0x5,%%xmm4 \n"
"pcmpeqb %%xmm7,%%xmm7 \n"
"psllw $0x8,%%xmm7 \n"
"sub %0,%1 \n"
"sub %0,%1 \n"
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"movdqa %%xmm0,%%xmm1 \n"
"movdqa %%xmm0,%%xmm2 \n"
"pand %%xmm3,%%xmm1 \n"
"psllw $0xb,%%xmm2 \n"
"pmulhuw %%xmm5,%%xmm1 \n"
"pmulhuw %%xmm5,%%xmm2 \n"
"psllw $0x8,%%xmm1 \n"
"por %%xmm2,%%xmm1 \n"
"pand %%xmm4,%%xmm0 \n"
"pmulhuw %%xmm6,%%xmm0 \n"
"por %%xmm7,%%xmm0 \n"
"movdqa %%xmm1,%%xmm2 \n"
"punpcklbw %%xmm0,%%xmm1 \n"
"punpckhbw %%xmm0,%%xmm2 \n"
"movdqu %%xmm1,0x00(%1,%0,2) \n"
"movdqu %%xmm2,0x10(%1,%0,2) \n"
"lea 0x10(%0),%0 \n"
"sub $0x8,%2 \n"
"jg 1b \n"
: "+r"(src), // %0
"+r"(dst), // %1
"+r"(width) // %2
:
: "memory", "cc", "eax", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5",
"xmm6", "xmm7");
}
void ARGB1555ToARGBRow_SSE2(const uint8_t* src, uint8_t* dst, int width) {
asm volatile(
"mov $0x1080108,%%eax \n"
"movd %%eax,%%xmm5 \n"
"pshufd $0x0,%%xmm5,%%xmm5 \n"
"mov $0x42004200,%%eax \n"
"movd %%eax,%%xmm6 \n"
"pshufd $0x0,%%xmm6,%%xmm6 \n"
"pcmpeqb %%xmm3,%%xmm3 \n"
"psllw $0xb,%%xmm3 \n"
"movdqa %%xmm3,%%xmm4 \n"
"psrlw $0x6,%%xmm4 \n"
"pcmpeqb %%xmm7,%%xmm7 \n"
"psllw $0x8,%%xmm7 \n"
"sub %0,%1 \n"
"sub %0,%1 \n"
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"movdqa %%xmm0,%%xmm1 \n"
"movdqa %%xmm0,%%xmm2 \n"
"psllw $0x1,%%xmm1 \n"
"psllw $0xb,%%xmm2 \n"
"pand %%xmm3,%%xmm1 \n"
"pmulhuw %%xmm5,%%xmm2 \n"
"pmulhuw %%xmm5,%%xmm1 \n"
"psllw $0x8,%%xmm1 \n"
"por %%xmm2,%%xmm1 \n"
"movdqa %%xmm0,%%xmm2 \n"
"pand %%xmm4,%%xmm0 \n"
"psraw $0x8,%%xmm2 \n"
"pmulhuw %%xmm6,%%xmm0 \n"
"pand %%xmm7,%%xmm2 \n"
"por %%xmm2,%%xmm0 \n"
"movdqa %%xmm1,%%xmm2 \n"
"punpcklbw %%xmm0,%%xmm1 \n"
"punpckhbw %%xmm0,%%xmm2 \n"
"movdqu %%xmm1,0x00(%1,%0,2) \n"
"movdqu %%xmm2,0x10(%1,%0,2) \n"
"lea 0x10(%0),%0 \n"
"sub $0x8,%2 \n"
"jg 1b \n"
: "+r"(src), // %0
"+r"(dst), // %1
"+r"(width) // %2
:
: "memory", "cc", "eax", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5",
"xmm6", "xmm7");
}
void ARGB4444ToARGBRow_SSE2(const uint8_t* src, uint8_t* dst, int width) {
asm volatile(
"mov $0xf0f0f0f,%%eax \n"
"movd %%eax,%%xmm4 \n"
"pshufd $0x0,%%xmm4,%%xmm4 \n"
"movdqa %%xmm4,%%xmm5 \n"
"pslld $0x4,%%xmm5 \n"
"sub %0,%1 \n"
"sub %0,%1 \n"
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"movdqa %%xmm0,%%xmm2 \n"
"pand %%xmm4,%%xmm0 \n"
"pand %%xmm5,%%xmm2 \n"
"movdqa %%xmm0,%%xmm1 \n"
"movdqa %%xmm2,%%xmm3 \n"
"psllw $0x4,%%xmm1 \n"
"psrlw $0x4,%%xmm3 \n"
"por %%xmm1,%%xmm0 \n"
"por %%xmm3,%%xmm2 \n"
"movdqa %%xmm0,%%xmm1 \n"
"punpcklbw %%xmm2,%%xmm0 \n"
"punpckhbw %%xmm2,%%xmm1 \n"
"movdqu %%xmm0,0x00(%1,%0,2) \n"
"movdqu %%xmm1,0x10(%1,%0,2) \n"
"lea 0x10(%0),%0 \n"
"sub $0x8,%2 \n"
"jg 1b \n"
: "+r"(src), // %0
"+r"(dst), // %1
"+r"(width) // %2
:
: "memory", "cc", "eax", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5");
}
void ARGBToRGB24Row_SSSE3(const uint8_t* src, uint8_t* dst, int width) {
asm volatile(
"movdqa %3,%%xmm6 \n"
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"movdqu 0x10(%0),%%xmm1 \n"
"movdqu 0x20(%0),%%xmm2 \n"
"movdqu 0x30(%0),%%xmm3 \n"
"lea 0x40(%0),%0 \n"
"pshufb %%xmm6,%%xmm0 \n"
"pshufb %%xmm6,%%xmm1 \n"
"pshufb %%xmm6,%%xmm2 \n"
"pshufb %%xmm6,%%xmm3 \n"
"movdqa %%xmm1,%%xmm4 \n"
"psrldq $0x4,%%xmm1 \n"
"pslldq $0xc,%%xmm4 \n"
"movdqa %%xmm2,%%xmm5 \n"
"por %%xmm4,%%xmm0 \n"
"pslldq $0x8,%%xmm5 \n"
"movdqu %%xmm0,(%1) \n"
"por %%xmm5,%%xmm1 \n"
"psrldq $0x8,%%xmm2 \n"
"pslldq $0x4,%%xmm3 \n"
"por %%xmm3,%%xmm2 \n"
"movdqu %%xmm1,0x10(%1) \n"
"movdqu %%xmm2,0x20(%1) \n"
"lea 0x30(%1),%1 \n"
"sub $0x10,%2 \n"
"jg 1b \n"
: "+r"(src), // %0
"+r"(dst), // %1
"+r"(width) // %2
: "m"(kShuffleMaskARGBToRGB24) // %3
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6");
}
void ARGBToRAWRow_SSSE3(const uint8_t* src, uint8_t* dst, int width) {
asm volatile(
"movdqa %3,%%xmm6 \n"
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"movdqu 0x10(%0),%%xmm1 \n"
"movdqu 0x20(%0),%%xmm2 \n"
"movdqu 0x30(%0),%%xmm3 \n"
"lea 0x40(%0),%0 \n"
"pshufb %%xmm6,%%xmm0 \n"
"pshufb %%xmm6,%%xmm1 \n"
"pshufb %%xmm6,%%xmm2 \n"
"pshufb %%xmm6,%%xmm3 \n"
"movdqa %%xmm1,%%xmm4 \n"
"psrldq $0x4,%%xmm1 \n"
"pslldq $0xc,%%xmm4 \n"
"movdqa %%xmm2,%%xmm5 \n"
"por %%xmm4,%%xmm0 \n"
"pslldq $0x8,%%xmm5 \n"
"movdqu %%xmm0,(%1) \n"
"por %%xmm5,%%xmm1 \n"
"psrldq $0x8,%%xmm2 \n"
"pslldq $0x4,%%xmm3 \n"
"por %%xmm3,%%xmm2 \n"
"movdqu %%xmm1,0x10(%1) \n"
"movdqu %%xmm2,0x20(%1) \n"
"lea 0x30(%1),%1 \n"
"sub $0x10,%2 \n"
"jg 1b \n"
: "+r"(src), // %0
"+r"(dst), // %1
"+r"(width) // %2
: "m"(kShuffleMaskARGBToRAW) // %3
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6");
}
#ifdef HAS_ARGBTORGB24ROW_AVX2
// vpermd for 12+12 to 24
static const lvec32 kPermdRGB24_AVX = {0, 1, 2, 4, 5, 6, 3, 7};
void ARGBToRGB24Row_AVX2(const uint8_t* src, uint8_t* dst, int width) {
asm volatile(
"vbroadcastf128 %3,%%ymm6 \n"
"vmovdqa %4,%%ymm7 \n"
LABELALIGN
"1: \n"
"vmovdqu (%0),%%ymm0 \n"
"vmovdqu 0x20(%0),%%ymm1 \n"
"vmovdqu 0x40(%0),%%ymm2 \n"
"vmovdqu 0x60(%0),%%ymm3 \n"
"lea 0x80(%0),%0 \n"
"vpshufb %%ymm6,%%ymm0,%%ymm0 \n" // xxx0yyy0
"vpshufb %%ymm6,%%ymm1,%%ymm1 \n"
"vpshufb %%ymm6,%%ymm2,%%ymm2 \n"
"vpshufb %%ymm6,%%ymm3,%%ymm3 \n"
"vpermd %%ymm0,%%ymm7,%%ymm0 \n" // pack to 24 bytes
"vpermd %%ymm1,%%ymm7,%%ymm1 \n"
"vpermd %%ymm2,%%ymm7,%%ymm2 \n"
"vpermd %%ymm3,%%ymm7,%%ymm3 \n"
"vpermq $0x3f,%%ymm1,%%ymm4 \n" // combine 24 + 8
"vpor %%ymm4,%%ymm0,%%ymm0 \n"
"vmovdqu %%ymm0,(%1) \n"
"vpermq $0xf9,%%ymm1,%%ymm1 \n" // combine 16 + 16
"vpermq $0x4f,%%ymm2,%%ymm4 \n"
"vpor %%ymm4,%%ymm1,%%ymm1 \n"
"vmovdqu %%ymm1,0x20(%1) \n"
"vpermq $0xfe,%%ymm2,%%ymm2 \n" // combine 8 + 24
"vpermq $0x93,%%ymm3,%%ymm3 \n"
"vpor %%ymm3,%%ymm2,%%ymm2 \n"
"vmovdqu %%ymm2,0x40(%1) \n"
"lea 0x60(%1),%1 \n"
"sub $0x20,%2 \n"
"jg 1b \n"
"vzeroupper \n"
: "+r"(src), // %0
"+r"(dst), // %1
"+r"(width) // %2
: "m"(kShuffleMaskARGBToRGB24), // %3
"m"(kPermdRGB24_AVX) // %4
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6",
"xmm7");
}
#endif
#ifdef HAS_ARGBTORGB24ROW_AVX512VBMI
// Shuffle table for converting ARGBToRGB24
static const ulvec8 kPermARGBToRGB24_0 = {
0u, 1u, 2u, 4u, 5u, 6u, 8u, 9u, 10u, 12u, 13u,
14u, 16u, 17u, 18u, 20u, 21u, 22u, 24u, 25u, 26u, 28u,
29u, 30u, 32u, 33u, 34u, 36u, 37u, 38u, 40u, 41u};
static const ulvec8 kPermARGBToRGB24_1 = {
10u, 12u, 13u, 14u, 16u, 17u, 18u, 20u, 21u, 22u, 24u,
25u, 26u, 28u, 29u, 30u, 32u, 33u, 34u, 36u, 37u, 38u,
40u, 41u, 42u, 44u, 45u, 46u, 48u, 49u, 50u, 52u};
static const ulvec8 kPermARGBToRGB24_2 = {
21u, 22u, 24u, 25u, 26u, 28u, 29u, 30u, 32u, 33u, 34u,
36u, 37u, 38u, 40u, 41u, 42u, 44u, 45u, 46u, 48u, 49u,
50u, 52u, 53u, 54u, 56u, 57u, 58u, 60u, 61u, 62u};
void ARGBToRGB24Row_AVX512VBMI(const uint8_t* src, uint8_t* dst, int width) {
asm volatile(
"vmovdqa %3,%%ymm5 \n"
"vmovdqa %4,%%ymm6 \n"
"vmovdqa %5,%%ymm7 \n"
LABELALIGN
"1: \n"
"vmovdqu (%0),%%ymm0 \n"
"vmovdqu 0x20(%0),%%ymm1 \n"
"vmovdqu 0x40(%0),%%ymm2 \n"
"vmovdqu 0x60(%0),%%ymm3 \n"
"lea 0x80(%0),%0 \n"
"vpermt2b %%ymm1,%%ymm5,%%ymm0 \n"
"vpermt2b %%ymm2,%%ymm6,%%ymm1 \n"
"vpermt2b %%ymm3,%%ymm7,%%ymm2 \n"
"vmovdqu %%ymm0,(%1) \n"
"vmovdqu %%ymm1,0x20(%1) \n"
"vmovdqu %%ymm2,0x40(%1) \n"
"lea 0x60(%1),%1 \n"
"sub $0x20,%2 \n"
"jg 1b \n"
"vzeroupper \n"
: "+r"(src), // %0
"+r"(dst), // %1
"+r"(width) // %2
: "m"(kPermARGBToRGB24_0), // %3
"m"(kPermARGBToRGB24_1), // %4
"m"(kPermARGBToRGB24_2) // %5
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm5", "xmm6", "xmm7");
}
#endif
#ifdef HAS_ARGBTORAWROW_AVX2
void ARGBToRAWRow_AVX2(const uint8_t* src, uint8_t* dst, int width) {
asm volatile(
"vbroadcastf128 %3,%%ymm6 \n"
"vmovdqa %4,%%ymm7 \n"
LABELALIGN
"1: \n"
"vmovdqu (%0),%%ymm0 \n"
"vmovdqu 0x20(%0),%%ymm1 \n"
"vmovdqu 0x40(%0),%%ymm2 \n"
"vmovdqu 0x60(%0),%%ymm3 \n"
"lea 0x80(%0),%0 \n"
"vpshufb %%ymm6,%%ymm0,%%ymm0 \n" // xxx0yyy0
"vpshufb %%ymm6,%%ymm1,%%ymm1 \n"
"vpshufb %%ymm6,%%ymm2,%%ymm2 \n"
"vpshufb %%ymm6,%%ymm3,%%ymm3 \n"
"vpermd %%ymm0,%%ymm7,%%ymm0 \n" // pack to 24 bytes
"vpermd %%ymm1,%%ymm7,%%ymm1 \n"
"vpermd %%ymm2,%%ymm7,%%ymm2 \n"
"vpermd %%ymm3,%%ymm7,%%ymm3 \n"
"vpermq $0x3f,%%ymm1,%%ymm4 \n" // combine 24 + 8
"vpor %%ymm4,%%ymm0,%%ymm0 \n"
"vmovdqu %%ymm0,(%1) \n"
"vpermq $0xf9,%%ymm1,%%ymm1 \n" // combine 16 + 16
"vpermq $0x4f,%%ymm2,%%ymm4 \n"
"vpor %%ymm4,%%ymm1,%%ymm1 \n"
"vmovdqu %%ymm1,0x20(%1) \n"
"vpermq $0xfe,%%ymm2,%%ymm2 \n" // combine 8 + 24
"vpermq $0x93,%%ymm3,%%ymm3 \n"
"vpor %%ymm3,%%ymm2,%%ymm2 \n"
"vmovdqu %%ymm2,0x40(%1) \n"
"lea 0x60(%1),%1 \n"
"sub $0x20,%2 \n"
"jg 1b \n"
"vzeroupper \n"
: "+r"(src), // %0
"+r"(dst), // %1
"+r"(width) // %2
: "m"(kShuffleMaskARGBToRAW), // %3
"m"(kPermdRGB24_AVX) // %4
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6",
"xmm7");
}
#endif
void ARGBToRGB565Row_SSE2(const uint8_t* src, uint8_t* dst, int width) {
asm volatile(
"pcmpeqb %%xmm3,%%xmm3 \n"
"psrld $0x1b,%%xmm3 \n"
"pcmpeqb %%xmm4,%%xmm4 \n"
"psrld $0x1a,%%xmm4 \n"
"pslld $0x5,%%xmm4 \n"
"pcmpeqb %%xmm5,%%xmm5 \n"
"pslld $0xb,%%xmm5 \n"
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"movdqa %%xmm0,%%xmm1 \n"
"movdqa %%xmm0,%%xmm2 \n"
"pslld $0x8,%%xmm0 \n"
"psrld $0x3,%%xmm1 \n"
"psrld $0x5,%%xmm2 \n"
"psrad $0x10,%%xmm0 \n"
"pand %%xmm3,%%xmm1 \n"
"pand %%xmm4,%%xmm2 \n"
"pand %%xmm5,%%xmm0 \n"
"por %%xmm2,%%xmm1 \n"
"por %%xmm1,%%xmm0 \n"
"packssdw %%xmm0,%%xmm0 \n"
"lea 0x10(%0),%0 \n"
"movq %%xmm0,(%1) \n"
"lea 0x8(%1),%1 \n"
"sub $0x4,%2 \n"
"jg 1b \n"
: "+r"(src), // %0
"+r"(dst), // %1
"+r"(width) // %2
::"memory",
"cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5");
}
void ARGBToRGB565DitherRow_SSE2(const uint8_t* src,
uint8_t* dst,
const uint32_t dither4,
int width) {
asm volatile(
"movd %3,%%xmm6 \n"
"punpcklbw %%xmm6,%%xmm6 \n"
"movdqa %%xmm6,%%xmm7 \n"
"punpcklwd %%xmm6,%%xmm6 \n"
"punpckhwd %%xmm7,%%xmm7 \n"
"pcmpeqb %%xmm3,%%xmm3 \n"
"psrld $0x1b,%%xmm3 \n"
"pcmpeqb %%xmm4,%%xmm4 \n"
"psrld $0x1a,%%xmm4 \n"
"pslld $0x5,%%xmm4 \n"
"pcmpeqb %%xmm5,%%xmm5 \n"
"pslld $0xb,%%xmm5 \n"
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"paddusb %%xmm6,%%xmm0 \n"
"movdqa %%xmm0,%%xmm1 \n"
"movdqa %%xmm0,%%xmm2 \n"
"pslld $0x8,%%xmm0 \n"
"psrld $0x3,%%xmm1 \n"
"psrld $0x5,%%xmm2 \n"
"psrad $0x10,%%xmm0 \n"
"pand %%xmm3,%%xmm1 \n"
"pand %%xmm4,%%xmm2 \n"
"pand %%xmm5,%%xmm0 \n"
"por %%xmm2,%%xmm1 \n"
"por %%xmm1,%%xmm0 \n"
"packssdw %%xmm0,%%xmm0 \n"
"lea 0x10(%0),%0 \n"
"movq %%xmm0,(%1) \n"
"lea 0x8(%1),%1 \n"
"sub $0x4,%2 \n"
"jg 1b \n"
: "+r"(src), // %0
"+r"(dst), // %1
"+r"(width) // %2
: "m"(dither4) // %3
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6",
"xmm7");
}
#ifdef HAS_ARGBTORGB565DITHERROW_AVX2
void ARGBToRGB565DitherRow_AVX2(const uint8_t* src,
uint8_t* dst,
const uint32_t dither4,
int width) {
asm volatile(
"vbroadcastss %3,%%xmm6 \n"
"vpunpcklbw %%xmm6,%%xmm6,%%xmm6 \n"
"vpermq $0xd8,%%ymm6,%%ymm6 \n"
"vpunpcklwd %%ymm6,%%ymm6,%%ymm6 \n"
"vpcmpeqb %%ymm3,%%ymm3,%%ymm3 \n"
"vpsrld $0x1b,%%ymm3,%%ymm3 \n"
"vpcmpeqb %%ymm4,%%ymm4,%%ymm4 \n"
"vpsrld $0x1a,%%ymm4,%%ymm4 \n"
"vpslld $0x5,%%ymm4,%%ymm4 \n"
"vpslld $0xb,%%ymm3,%%ymm5 \n"
LABELALIGN
"1: \n"
"vmovdqu (%0),%%ymm0 \n"
"vpaddusb %%ymm6,%%ymm0,%%ymm0 \n"
"vpsrld $0x5,%%ymm0,%%ymm2 \n"
"vpsrld $0x3,%%ymm0,%%ymm1 \n"
"vpsrld $0x8,%%ymm0,%%ymm0 \n"
"vpand %%ymm4,%%ymm2,%%ymm2 \n"
"vpand %%ymm3,%%ymm1,%%ymm1 \n"
"vpand %%ymm5,%%ymm0,%%ymm0 \n"
"vpor %%ymm2,%%ymm1,%%ymm1 \n"
"vpor %%ymm1,%%ymm0,%%ymm0 \n"
"vpackusdw %%ymm0,%%ymm0,%%ymm0 \n"
"vpermq $0xd8,%%ymm0,%%ymm0 \n"
"lea 0x20(%0),%0 \n"
"vmovdqu %%xmm0,(%1) \n"
"lea 0x10(%1),%1 \n"
"sub $0x8,%2 \n"
"jg 1b \n"
"vzeroupper \n"
: "+r"(src), // %0
"+r"(dst), // %1
"+r"(width) // %2
: "m"(dither4) // %3
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6",
"xmm7");
}
#endif // HAS_ARGBTORGB565DITHERROW_AVX2
void ARGBToARGB1555Row_SSE2(const uint8_t* src, uint8_t* dst, int width) {
asm volatile(
"pcmpeqb %%xmm4,%%xmm4 \n"
"psrld $0x1b,%%xmm4 \n"
"movdqa %%xmm4,%%xmm5 \n"
"pslld $0x5,%%xmm5 \n"
"movdqa %%xmm4,%%xmm6 \n"
"pslld $0xa,%%xmm6 \n"
"pcmpeqb %%xmm7,%%xmm7 \n"
"pslld $0xf,%%xmm7 \n"
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"movdqa %%xmm0,%%xmm1 \n"
"movdqa %%xmm0,%%xmm2 \n"
"movdqa %%xmm0,%%xmm3 \n"
"psrad $0x10,%%xmm0 \n"
"psrld $0x3,%%xmm1 \n"
"psrld $0x6,%%xmm2 \n"
"psrld $0x9,%%xmm3 \n"
"pand %%xmm7,%%xmm0 \n"
"pand %%xmm4,%%xmm1 \n"
"pand %%xmm5,%%xmm2 \n"
"pand %%xmm6,%%xmm3 \n"
"por %%xmm1,%%xmm0 \n"
"por %%xmm3,%%xmm2 \n"
"por %%xmm2,%%xmm0 \n"
"packssdw %%xmm0,%%xmm0 \n"
"lea 0x10(%0),%0 \n"
"movq %%xmm0,(%1) \n"
"lea 0x8(%1),%1 \n"
"sub $0x4,%2 \n"
"jg 1b \n"
: "+r"(src), // %0
"+r"(dst), // %1
"+r"(width) // %2
::"memory",
"cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6", "xmm7");
}
void ARGBToARGB4444Row_SSE2(const uint8_t* src, uint8_t* dst, int width) {
asm volatile(
"pcmpeqb %%xmm4,%%xmm4 \n"
"psllw $0xc,%%xmm4 \n"
"movdqa %%xmm4,%%xmm3 \n"
"psrlw $0x8,%%xmm3 \n"
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"movdqa %%xmm0,%%xmm1 \n"
"pand %%xmm3,%%xmm0 \n"
"pand %%xmm4,%%xmm1 \n"
"psrlq $0x4,%%xmm0 \n"
"psrlq $0x8,%%xmm1 \n"
"por %%xmm1,%%xmm0 \n"
"packuswb %%xmm0,%%xmm0 \n"
"lea 0x10(%0),%0 \n"
"movq %%xmm0,(%1) \n"
"lea 0x8(%1),%1 \n"
"sub $0x4,%2 \n"
"jg 1b \n"
: "+r"(src), // %0
"+r"(dst), // %1
"+r"(width) // %2
::"memory",
"cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4");
}
#endif // HAS_RGB24TOARGBROW_SSSE3
/*
ARGBToAR30Row:
Red Blue
With the 8 bit value in the upper bits of a short, vpmulhuw by (1024+4) will
produce a 10 bit value in the low 10 bits of each 16 bit value. This is whats
wanted for the blue channel. The red needs to be shifted 4 left, so multiply by
(1024+4)*16 for red.
Alpha Green
Alpha and Green are already in the high bits so vpand can zero out the other
bits, keeping just 2 upper bits of alpha and 8 bit green. The same multiplier
could be used for Green - (1024+4) putting the 10 bit green in the lsb. Alpha
would be a simple multiplier to shift it into position. It wants a gap of 10
above the green. Green is 10 bits, so there are 6 bits in the low short. 4
more are needed, so a multiplier of 4 gets the 2 bits into the upper 16 bits,
and then a shift of 4 is a multiply of 16, so (4*16) = 64. Then shift the
result left 10 to position the A and G channels.
*/
// Shuffle table for converting RAW to RGB24. Last 8.
static const uvec8 kShuffleRB30 = {128u, 0u, 128u, 2u, 128u, 4u, 128u, 6u,
128u, 8u, 128u, 10u, 128u, 12u, 128u, 14u};
static const uvec8 kShuffleBR30 = {128u, 2u, 128u, 0u, 128u, 6u, 128u, 4u,
128u, 10u, 128u, 8u, 128u, 14u, 128u, 12u};
static const uint32_t kMulRB10 = 1028 * 16 * 65536 + 1028;
static const uint32_t kMaskRB10 = 0x3ff003ff;
static const uint32_t kMaskAG10 = 0xc000ff00;
static const uint32_t kMulAG10 = 64 * 65536 + 1028;
void ARGBToAR30Row_SSSE3(const uint8_t* src, uint8_t* dst, int width) {
asm volatile(
"movdqa %3,%%xmm2 \n" // shuffler for RB
"movd %4,%%xmm3 \n" // multipler for RB
"movd %5,%%xmm4 \n" // mask for R10 B10
"movd %6,%%xmm5 \n" // mask for AG
"movd %7,%%xmm6 \n" // multipler for AG
"pshufd $0x0,%%xmm3,%%xmm3 \n"
"pshufd $0x0,%%xmm4,%%xmm4 \n"
"pshufd $0x0,%%xmm5,%%xmm5 \n"
"pshufd $0x0,%%xmm6,%%xmm6 \n"
"sub %0,%1 \n"
"1: \n"
"movdqu (%0),%%xmm0 \n" // fetch 4 ARGB pixels
"movdqa %%xmm0,%%xmm1 \n"
"pshufb %%xmm2,%%xmm1 \n" // R0B0
"pand %%xmm5,%%xmm0 \n" // A0G0
"pmulhuw %%xmm3,%%xmm1 \n" // X2 R16 X4 B10
"pmulhuw %%xmm6,%%xmm0 \n" // X10 A2 X10 G10
"pand %%xmm4,%%xmm1 \n" // X2 R10 X10 B10
"pslld $10,%%xmm0 \n" // A2 x10 G10 x10
"por %%xmm1,%%xmm0 \n" // A2 R10 G10 B10
"movdqu %%xmm0,(%1,%0) \n" // store 4 AR30 pixels
"add $0x10,%0 \n"
"sub $0x4,%2 \n"
"jg 1b \n"
: "+r"(src), // %0
"+r"(dst), // %1
"+r"(width) // %2
: "m"(kShuffleRB30), // %3
"m"(kMulRB10), // %4
"m"(kMaskRB10), // %5
"m"(kMaskAG10), // %6
"m"(kMulAG10) // %7
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6");
}
void ABGRToAR30Row_SSSE3(const uint8_t* src, uint8_t* dst, int width) {
asm volatile(
"movdqa %3,%%xmm2 \n" // shuffler for RB
"movd %4,%%xmm3 \n" // multipler for RB
"movd %5,%%xmm4 \n" // mask for R10 B10
"movd %6,%%xmm5 \n" // mask for AG
"movd %7,%%xmm6 \n" // multipler for AG
"pshufd $0x0,%%xmm3,%%xmm3 \n"
"pshufd $0x0,%%xmm4,%%xmm4 \n"
"pshufd $0x0,%%xmm5,%%xmm5 \n"
"pshufd $0x0,%%xmm6,%%xmm6 \n"
"sub %0,%1 \n"
"1: \n"
"movdqu (%0),%%xmm0 \n" // fetch 4 ABGR pixels
"movdqa %%xmm0,%%xmm1 \n"
"pshufb %%xmm2,%%xmm1 \n" // R0B0
"pand %%xmm5,%%xmm0 \n" // A0G0
"pmulhuw %%xmm3,%%xmm1 \n" // X2 R16 X4 B10
"pmulhuw %%xmm6,%%xmm0 \n" // X10 A2 X10 G10
"pand %%xmm4,%%xmm1 \n" // X2 R10 X10 B10
"pslld $10,%%xmm0 \n" // A2 x10 G10 x10
"por %%xmm1,%%xmm0 \n" // A2 R10 G10 B10
"movdqu %%xmm0,(%1,%0) \n" // store 4 AR30 pixels
"add $0x10,%0 \n"
"sub $0x4,%2 \n"
"jg 1b \n"
: "+r"(src), // %0
"+r"(dst), // %1
"+r"(width) // %2
: "m"(kShuffleBR30), // %3 reversed shuffler
"m"(kMulRB10), // %4
"m"(kMaskRB10), // %5
"m"(kMaskAG10), // %6
"m"(kMulAG10) // %7
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6");
}
#ifdef HAS_ARGBTOAR30ROW_AVX2
void ARGBToAR30Row_AVX2(const uint8_t* src, uint8_t* dst, int width) {
asm volatile(
"vbroadcastf128 %3,%%ymm2 \n" // shuffler for RB
"vbroadcastss %4,%%ymm3 \n" // multipler for RB
"vbroadcastss %5,%%ymm4 \n" // mask for R10 B10
"vbroadcastss %6,%%ymm5 \n" // mask for AG
"vbroadcastss %7,%%ymm6 \n" // multipler for AG
"sub %0,%1 \n"
"1: \n"
"vmovdqu (%0),%%ymm0 \n" // fetch 8 ARGB pixels
"vpshufb %%ymm2,%%ymm0,%%ymm1 \n" // R0B0
"vpand %%ymm5,%%ymm0,%%ymm0 \n" // A0G0
"vpmulhuw %%ymm3,%%ymm1,%%ymm1 \n" // X2 R16 X4 B10
"vpmulhuw %%ymm6,%%ymm0,%%ymm0 \n" // X10 A2 X10 G10
"vpand %%ymm4,%%ymm1,%%ymm1 \n" // X2 R10 X10 B10
"vpslld $10,%%ymm0,%%ymm0 \n" // A2 x10 G10 x10
"vpor %%ymm1,%%ymm0,%%ymm0 \n" // A2 R10 G10 B10
"vmovdqu %%ymm0,(%1,%0) \n" // store 8 AR30 pixels
"add $0x20,%0 \n"
"sub $0x8,%2 \n"
"jg 1b \n"
"vzeroupper \n"
: "+r"(src), // %0
"+r"(dst), // %1
"+r"(width) // %2
: "m"(kShuffleRB30), // %3
"m"(kMulRB10), // %4
"m"(kMaskRB10), // %5
"m"(kMaskAG10), // %6
"m"(kMulAG10) // %7
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6");
}
#endif
#ifdef HAS_ABGRTOAR30ROW_AVX2
void ABGRToAR30Row_AVX2(const uint8_t* src, uint8_t* dst, int width) {
asm volatile(
"vbroadcastf128 %3,%%ymm2 \n" // shuffler for RB
"vbroadcastss %4,%%ymm3 \n" // multipler for RB
"vbroadcastss %5,%%ymm4 \n" // mask for R10 B10
"vbroadcastss %6,%%ymm5 \n" // mask for AG
"vbroadcastss %7,%%ymm6 \n" // multipler for AG
"sub %0,%1 \n"
"1: \n"
"vmovdqu (%0),%%ymm0 \n" // fetch 8 ABGR pixels
"vpshufb %%ymm2,%%ymm0,%%ymm1 \n" // R0B0
"vpand %%ymm5,%%ymm0,%%ymm0 \n" // A0G0
"vpmulhuw %%ymm3,%%ymm1,%%ymm1 \n" // X2 R16 X4 B10
"vpmulhuw %%ymm6,%%ymm0,%%ymm0 \n" // X10 A2 X10 G10
"vpand %%ymm4,%%ymm1,%%ymm1 \n" // X2 R10 X10 B10
"vpslld $10,%%ymm0,%%ymm0 \n" // A2 x10 G10 x10
"vpor %%ymm1,%%ymm0,%%ymm0 \n" // A2 R10 G10 B10
"vmovdqu %%ymm0,(%1,%0) \n" // store 8 AR30 pixels
"add $0x20,%0 \n"
"sub $0x8,%2 \n"
"jg 1b \n"
"vzeroupper \n"
: "+r"(src), // %0
"+r"(dst), // %1
"+r"(width) // %2
: "m"(kShuffleBR30), // %3 reversed shuffler
"m"(kMulRB10), // %4
"m"(kMaskRB10), // %5
"m"(kMaskAG10), // %6
"m"(kMulAG10) // %7
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6");
}
#endif
// clang-format off
// TODO(mraptis): Consider passing R, G, B multipliers as parameter.
// round parameter is register containing value to add before shift.
#define RGBTOY(round) \
"1: \n" \
"movdqu (%0),%%xmm0 \n" \
"movdqu 0x10(%0),%%xmm1 \n" \
"movdqu 0x20(%0),%%xmm2 \n" \
"movdqu 0x30(%0),%%xmm3 \n" \
"psubb %%xmm5,%%xmm0 \n" \
"psubb %%xmm5,%%xmm1 \n" \
"psubb %%xmm5,%%xmm2 \n" \
"psubb %%xmm5,%%xmm3 \n" \
"movdqu %%xmm4,%%xmm6 \n" \
"pmaddubsw %%xmm0,%%xmm6 \n" \
"movdqu %%xmm4,%%xmm0 \n" \
"pmaddubsw %%xmm1,%%xmm0 \n" \
"movdqu %%xmm4,%%xmm1 \n" \
"pmaddubsw %%xmm2,%%xmm1 \n" \
"movdqu %%xmm4,%%xmm2 \n" \
"pmaddubsw %%xmm3,%%xmm2 \n" \
"lea 0x40(%0),%0 \n" \
"phaddw %%xmm0,%%xmm6 \n" \
"phaddw %%xmm2,%%xmm1 \n" \
"prefetcht0 1280(%0) \n" \
"paddw %%" #round ",%%xmm6 \n" \
"paddw %%" #round ",%%xmm1 \n" \
"psrlw $0x8,%%xmm6 \n" \
"psrlw $0x8,%%xmm1 \n" \
"packuswb %%xmm1,%%xmm6 \n" \
"movdqu %%xmm6,(%1) \n" \
"lea 0x10(%1),%1 \n" \
"sub $0x10,%2 \n" \
"jg 1b \n"
#define RGBTOY_AVX2(round) \
"1: \n" \
"vmovdqu (%0),%%ymm0 \n" \
"vmovdqu 0x20(%0),%%ymm1 \n" \
"vmovdqu 0x40(%0),%%ymm2 \n" \
"vmovdqu 0x60(%0),%%ymm3 \n" \
"vpsubb %%ymm5, %%ymm0, %%ymm0 \n" \
"vpsubb %%ymm5, %%ymm1, %%ymm1 \n" \
"vpsubb %%ymm5, %%ymm2, %%ymm2 \n" \
"vpsubb %%ymm5, %%ymm3, %%ymm3 \n" \
"vpmaddubsw %%ymm0,%%ymm4,%%ymm0 \n" \
"vpmaddubsw %%ymm1,%%ymm4,%%ymm1 \n" \
"vpmaddubsw %%ymm2,%%ymm4,%%ymm2 \n" \
"vpmaddubsw %%ymm3,%%ymm4,%%ymm3 \n" \
"lea 0x80(%0),%0 \n" \
"vphaddw %%ymm1,%%ymm0,%%ymm0 \n" /* mutates. */ \
"vphaddw %%ymm3,%%ymm2,%%ymm2 \n" \
"prefetcht0 1280(%0) \n" \
"vpaddw %%" #round ",%%ymm0,%%ymm0 \n" /* Add .5 for rounding. */ \
"vpaddw %%" #round ",%%ymm2,%%ymm2 \n" \
"vpsrlw $0x8,%%ymm0,%%ymm0 \n" \
"vpsrlw $0x8,%%ymm2,%%ymm2 \n" \
"vpackuswb %%ymm2,%%ymm0,%%ymm0 \n" /* mutates. */ \
"vpermd %%ymm0,%%ymm6,%%ymm0 \n" /* unmutate. */ \
"vmovdqu %%ymm0,(%1) \n" \
"lea 0x20(%1),%1 \n" \
"sub $0x20,%2 \n" \
"jg 1b \n" \
"vzeroupper \n"
// clang-format on
#ifdef HAS_ARGBTOYROW_SSSE3
// Convert 16 ARGB pixels (64 bytes) to 16 Y values.
void ARGBToYRow_SSSE3(const uint8_t* src_argb, uint8_t* dst_y, int width) {
asm volatile(
"movdqa %3,%%xmm4 \n"
"movdqa %4,%%xmm5 \n"
"movdqa %5,%%xmm7 \n"
LABELALIGN RGBTOY(xmm7)
: "+r"(src_argb), // %0
"+r"(dst_y), // %1
"+r"(width) // %2
: "m"(kARGBToY), // %3
"m"(kSub128), // %4
"m"(kAddY16) // %5
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6",
"xmm7");
}
#endif // HAS_ARGBTOYROW_SSSE3
#ifdef HAS_ARGBTOYJROW_SSSE3
// Convert 16 ARGB pixels (64 bytes) to 16 YJ values.
// Same as ARGBToYRow but different coefficients, no add 16.
void ARGBToYJRow_SSSE3(const uint8_t* src_argb, uint8_t* dst_y, int width) {
asm volatile(
"movdqa %3,%%xmm4 \n"
"movdqa %4,%%xmm5 \n"
LABELALIGN RGBTOY(xmm5)
: "+r"(src_argb), // %0
"+r"(dst_y), // %1
"+r"(width) // %2
: "m"(kARGBToYJ), // %3
"m"(kSub128) // %4
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6");
}
#endif // HAS_ARGBTOYJROW_SSSE3
#ifdef HAS_RGBATOYJROW_SSSE3
// Convert 16 ARGB pixels (64 bytes) to 16 YJ values.
// Same as ARGBToYRow but different coefficients, no add 16.
void RGBAToYJRow_SSSE3(const uint8_t* src_rgba, uint8_t* dst_y, int width) {
asm volatile(
"movdqa %3,%%xmm4 \n"
"movdqa %4,%%xmm5 \n"
LABELALIGN RGBTOY(xmm5)
: "+r"(src_rgba), // %0
"+r"(dst_y), // %1
"+r"(width) // %2
: "m"(kRGBAToYJ), // %3
"m"(kSub128) // %4
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6");
}
#endif // HAS_RGBATOYJROW_SSSE3
#ifdef HAS_ARGBTOYROW_AVX2
// vpermd for vphaddw + vpackuswb vpermd.
static const lvec32 kPermdARGBToY_AVX = {0, 4, 1, 5, 2, 6, 3, 7};
// Convert 32 ARGB pixels (128 bytes) to 32 Y values.
void ARGBToYRow_AVX2(const uint8_t* src_argb, uint8_t* dst_y, int width) {
asm volatile(
"vbroadcastf128 %3,%%ymm4 \n"
"vbroadcastf128 %4,%%ymm5 \n"
"vbroadcastf128 %5,%%ymm7 \n"
"vmovdqu %6,%%ymm6 \n"
LABELALIGN RGBTOY_AVX2(ymm7)
: "+r"(src_argb), // %0
"+r"(dst_y), // %1
"+r"(width) // %2
: "m"(kARGBToY), // %3
"m"(kSub128), // %4
"m"(kAddY16), // %5
"m"(kPermdARGBToY_AVX) // %6
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6",
"xmm7");
}
#endif // HAS_ARGBTOYROW_AVX2
#ifdef HAS_ABGRTOYROW_AVX2
// Convert 32 ABGR pixels (128 bytes) to 32 Y values.
void ABGRToYRow_AVX2(const uint8_t* src_abgr, uint8_t* dst_y, int width) {
asm volatile(
"vbroadcastf128 %3,%%ymm4 \n"
"vbroadcastf128 %4,%%ymm5 \n"
"vbroadcastf128 %5,%%ymm7 \n"
"vmovdqu %6,%%ymm6 \n"
LABELALIGN RGBTOY_AVX2(ymm7)
: "+r"(src_abgr), // %0
"+r"(dst_y), // %1
"+r"(width) // %2
: "m"(kABGRToY), // %3
"m"(kSub128), // %4
"m"(kAddY16), // %5
"m"(kPermdARGBToY_AVX) // %6
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6",
"xmm7");
}
#endif // HAS_ABGRTOYROW_AVX2
#ifdef HAS_ARGBTOYJROW_AVX2
// Convert 32 ARGB pixels (128 bytes) to 32 Y values.
void ARGBToYJRow_AVX2(const uint8_t* src_argb, uint8_t* dst_y, int width) {
asm volatile(
"vbroadcastf128 %3,%%ymm4 \n"
"vbroadcastf128 %4,%%ymm5 \n"
"vmovdqu %5,%%ymm6 \n"
LABELALIGN RGBTOY_AVX2(ymm5)
: "+r"(src_argb), // %0
"+r"(dst_y), // %1
"+r"(width) // %2
: "m"(kARGBToYJ), // %3
"m"(kSub128), // %4
"m"(kPermdARGBToY_AVX) // %5
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6",
"xmm7");
}
#endif // HAS_ARGBTOYJROW_AVX2
#ifdef HAS_RGBATOYJROW_AVX2
// Convert 32 ARGB pixels (128 bytes) to 32 Y values.
void RGBAToYJRow_AVX2(const uint8_t* src_rgba, uint8_t* dst_y, int width) {
asm volatile(
"vbroadcastf128 %3,%%ymm4 \n"
"vbroadcastf128 %4,%%ymm5 \n"
"vmovdqu %5,%%ymm6 \n"
LABELALIGN RGBTOY_AVX2(
ymm5) "vzeroupper \n"
: "+r"(src_rgba), // %0
"+r"(dst_y), // %1
"+r"(width) // %2
: "m"(kRGBAToYJ), // %3
"m"(kSub128), // %4
"m"(kPermdARGBToY_AVX) // %5
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6");
}
#endif // HAS_RGBATOYJROW_AVX2
#ifdef HAS_ARGBTOUVROW_SSSE3
void ARGBToUVRow_SSSE3(const uint8_t* src_argb0,
int src_stride_argb,
uint8_t* dst_u,
uint8_t* dst_v,
int width) {
asm volatile(
"movdqa %5,%%xmm3 \n"
"movdqa %6,%%xmm4 \n"
"movdqa %7,%%xmm5 \n"
"sub %1,%2 \n"
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"movdqu 0x00(%0,%4,1),%%xmm7 \n"
"pavgb %%xmm7,%%xmm0 \n"
"movdqu 0x10(%0),%%xmm1 \n"
"movdqu 0x10(%0,%4,1),%%xmm7 \n"
"pavgb %%xmm7,%%xmm1 \n"
"movdqu 0x20(%0),%%xmm2 \n"
"movdqu 0x20(%0,%4,1),%%xmm7 \n"
"pavgb %%xmm7,%%xmm2 \n"
"movdqu 0x30(%0),%%xmm6 \n"
"movdqu 0x30(%0,%4,1),%%xmm7 \n"
"pavgb %%xmm7,%%xmm6 \n"
"lea 0x40(%0),%0 \n"
"movdqa %%xmm0,%%xmm7 \n"
"shufps $0x88,%%xmm1,%%xmm0 \n"
"shufps $0xdd,%%xmm1,%%xmm7 \n"
"pavgb %%xmm7,%%xmm0 \n"
"movdqa %%xmm2,%%xmm7 \n"
"shufps $0x88,%%xmm6,%%xmm2 \n"
"shufps $0xdd,%%xmm6,%%xmm7 \n"
"pavgb %%xmm7,%%xmm2 \n"
"movdqa %%xmm0,%%xmm1 \n"
"movdqa %%xmm2,%%xmm6 \n"
"pmaddubsw %%xmm4,%%xmm0 \n"
"pmaddubsw %%xmm4,%%xmm2 \n"
"pmaddubsw %%xmm3,%%xmm1 \n"
"pmaddubsw %%xmm3,%%xmm6 \n"
"phaddw %%xmm2,%%xmm0 \n"
"phaddw %%xmm6,%%xmm1 \n"
"psraw $0x8,%%xmm0 \n"
"psraw $0x8,%%xmm1 \n"
"packsswb %%xmm1,%%xmm0 \n"
"paddb %%xmm5,%%xmm0 \n"
"movlps %%xmm0,(%1) \n"
"movhps %%xmm0,0x00(%1,%2,1) \n"
"lea 0x8(%1),%1 \n"
"sub $0x10,%3 \n"
"jg 1b \n"
: "+r"(src_argb0), // %0
"+r"(dst_u), // %1
"+r"(dst_v), // %2
"+rm"(width) // %3
: "r"((intptr_t)(src_stride_argb)), // %4
"m"(kARGBToV), // %5
"m"(kARGBToU), // %6
"m"(kAddUV128) // %7
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm6", "xmm7");
}
#endif // HAS_ARGBTOUVROW_SSSE3
#ifdef HAS_ARGBTOUVROW_AVX2
// vpshufb for vphaddw + vpackuswb packed to shorts.
static const lvec8 kShufARGBToUV_AVX = {
0, 1, 8, 9, 2, 3, 10, 11, 4, 5, 12, 13, 6, 7, 14, 15,
0, 1, 8, 9, 2, 3, 10, 11, 4, 5, 12, 13, 6, 7, 14, 15};
void ARGBToUVRow_AVX2(const uint8_t* src_argb0,
int src_stride_argb,
uint8_t* dst_u,
uint8_t* dst_v,
int width) {
asm volatile(
"vbroadcastf128 %5,%%ymm5 \n"
"vbroadcastf128 %6,%%ymm6 \n"
"vbroadcastf128 %7,%%ymm7 \n"
"sub %1,%2 \n"
LABELALIGN
"1: \n"
"vmovdqu (%0),%%ymm0 \n"
"vmovdqu 0x20(%0),%%ymm1 \n"
"vmovdqu 0x40(%0),%%ymm2 \n"
"vmovdqu 0x60(%0),%%ymm3 \n"
"vpavgb 0x00(%0,%4,1),%%ymm0,%%ymm0 \n"
"vpavgb 0x20(%0,%4,1),%%ymm1,%%ymm1 \n"
"vpavgb 0x40(%0,%4,1),%%ymm2,%%ymm2 \n"
"vpavgb 0x60(%0,%4,1),%%ymm3,%%ymm3 \n"
"lea 0x80(%0),%0 \n"
"vshufps $0x88,%%ymm1,%%ymm0,%%ymm4 \n"
"vshufps $0xdd,%%ymm1,%%ymm0,%%ymm0 \n"
"vpavgb %%ymm4,%%ymm0,%%ymm0 \n"
"vshufps $0x88,%%ymm3,%%ymm2,%%ymm4 \n"
"vshufps $0xdd,%%ymm3,%%ymm2,%%ymm2 \n"
"vpavgb %%ymm4,%%ymm2,%%ymm2 \n"
"vpmaddubsw %%ymm7,%%ymm0,%%ymm1 \n"
"vpmaddubsw %%ymm7,%%ymm2,%%ymm3 \n"
"vpmaddubsw %%ymm6,%%ymm0,%%ymm0 \n"
"vpmaddubsw %%ymm6,%%ymm2,%%ymm2 \n"
"vphaddw %%ymm3,%%ymm1,%%ymm1 \n"
"vphaddw %%ymm2,%%ymm0,%%ymm0 \n"
"vpsraw $0x8,%%ymm1,%%ymm1 \n"
"vpsraw $0x8,%%ymm0,%%ymm0 \n"
"vpacksswb %%ymm0,%%ymm1,%%ymm0 \n"
"vpermq $0xd8,%%ymm0,%%ymm0 \n"
"vpshufb %8,%%ymm0,%%ymm0 \n"
"vpaddb %%ymm5,%%ymm0,%%ymm0 \n"
"vextractf128 $0x0,%%ymm0,(%1) \n"
"vextractf128 $0x1,%%ymm0,0x0(%1,%2,1) \n"
"lea 0x10(%1),%1 \n"
"sub $0x20,%3 \n"
"jg 1b \n"
"vzeroupper \n"
: "+r"(src_argb0), // %0
"+r"(dst_u), // %1
"+r"(dst_v), // %2
"+rm"(width) // %3
: "r"((intptr_t)(src_stride_argb)), // %4
"m"(kAddUV128), // %5
"m"(kARGBToV), // %6
"m"(kARGBToU), // %7
"m"(kShufARGBToUV_AVX) // %8
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6",
"xmm7");
}
#endif // HAS_ARGBTOUVROW_AVX2
#ifdef HAS_ABGRTOUVROW_AVX2
void ABGRToUVRow_AVX2(const uint8_t* src_abgr0,
int src_stride_abgr,
uint8_t* dst_u,
uint8_t* dst_v,
int width) {
asm volatile(
"vbroadcastf128 %5,%%ymm5 \n"
"vbroadcastf128 %6,%%ymm6 \n"
"vbroadcastf128 %7,%%ymm7 \n"
"sub %1,%2 \n"
LABELALIGN
"1: \n"
"vmovdqu (%0),%%ymm0 \n"
"vmovdqu 0x20(%0),%%ymm1 \n"
"vmovdqu 0x40(%0),%%ymm2 \n"
"vmovdqu 0x60(%0),%%ymm3 \n"
"vpavgb 0x00(%0,%4,1),%%ymm0,%%ymm0 \n"
"vpavgb 0x20(%0,%4,1),%%ymm1,%%ymm1 \n"
"vpavgb 0x40(%0,%4,1),%%ymm2,%%ymm2 \n"
"vpavgb 0x60(%0,%4,1),%%ymm3,%%ymm3 \n"
"lea 0x80(%0),%0 \n"
"vshufps $0x88,%%ymm1,%%ymm0,%%ymm4 \n"
"vshufps $0xdd,%%ymm1,%%ymm0,%%ymm0 \n"
"vpavgb %%ymm4,%%ymm0,%%ymm0 \n"
"vshufps $0x88,%%ymm3,%%ymm2,%%ymm4 \n"
"vshufps $0xdd,%%ymm3,%%ymm2,%%ymm2 \n"
"vpavgb %%ymm4,%%ymm2,%%ymm2 \n"
"vpmaddubsw %%ymm7,%%ymm0,%%ymm1 \n"
"vpmaddubsw %%ymm7,%%ymm2,%%ymm3 \n"
"vpmaddubsw %%ymm6,%%ymm0,%%ymm0 \n"
"vpmaddubsw %%ymm6,%%ymm2,%%ymm2 \n"
"vphaddw %%ymm3,%%ymm1,%%ymm1 \n"
"vphaddw %%ymm2,%%ymm0,%%ymm0 \n"
"vpsraw $0x8,%%ymm1,%%ymm1 \n"
"vpsraw $0x8,%%ymm0,%%ymm0 \n"
"vpacksswb %%ymm0,%%ymm1,%%ymm0 \n"
"vpermq $0xd8,%%ymm0,%%ymm0 \n"
"vpshufb %8,%%ymm0,%%ymm0 \n"
"vpaddb %%ymm5,%%ymm0,%%ymm0 \n"
"vextractf128 $0x0,%%ymm0,(%1) \n"
"vextractf128 $0x1,%%ymm0,0x0(%1,%2,1) \n"
"lea 0x10(%1),%1 \n"
"sub $0x20,%3 \n"
"jg 1b \n"
"vzeroupper \n"
: "+r"(src_abgr0), // %0
"+r"(dst_u), // %1
"+r"(dst_v), // %2
"+rm"(width) // %3
: "r"((intptr_t)(src_stride_abgr)), // %4
"m"(kAddUV128), // %5
"m"(kABGRToV), // %6
"m"(kABGRToU), // %7
"m"(kShufARGBToUV_AVX) // %8
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6",
"xmm7");
}
#endif // HAS_ABGRTOUVROW_AVX2
#ifdef HAS_ARGBTOUVJROW_AVX2
void ARGBToUVJRow_AVX2(const uint8_t* src_argb0,
int src_stride_argb,
uint8_t* dst_u,
uint8_t* dst_v,
int width) {
asm volatile(
"vbroadcastf128 %5,%%ymm5 \n"
"vbroadcastf128 %6,%%ymm6 \n"
"vbroadcastf128 %7,%%ymm7 \n"
"sub %1,%2 \n"
LABELALIGN
"1: \n"
"vmovdqu (%0),%%ymm0 \n"
"vmovdqu 0x20(%0),%%ymm1 \n"
"vmovdqu 0x40(%0),%%ymm2 \n"
"vmovdqu 0x60(%0),%%ymm3 \n"
"vpavgb 0x00(%0,%4,1),%%ymm0,%%ymm0 \n"
"vpavgb 0x20(%0,%4,1),%%ymm1,%%ymm1 \n"
"vpavgb 0x40(%0,%4,1),%%ymm2,%%ymm2 \n"
"vpavgb 0x60(%0,%4,1),%%ymm3,%%ymm3 \n"
"lea 0x80(%0),%0 \n"
"vshufps $0x88,%%ymm1,%%ymm0,%%ymm4 \n"
"vshufps $0xdd,%%ymm1,%%ymm0,%%ymm0 \n"
"vpavgb %%ymm4,%%ymm0,%%ymm0 \n"
"vshufps $0x88,%%ymm3,%%ymm2,%%ymm4 \n"
"vshufps $0xdd,%%ymm3,%%ymm2,%%ymm2 \n"
"vpavgb %%ymm4,%%ymm2,%%ymm2 \n"
"vpmaddubsw %%ymm7,%%ymm0,%%ymm1 \n"
"vpmaddubsw %%ymm7,%%ymm2,%%ymm3 \n"
"vpmaddubsw %%ymm6,%%ymm0,%%ymm0 \n"
"vpmaddubsw %%ymm6,%%ymm2,%%ymm2 \n"
"vphaddw %%ymm3,%%ymm1,%%ymm1 \n"
"vphaddw %%ymm2,%%ymm0,%%ymm0 \n"
"vpaddw %%ymm5,%%ymm0,%%ymm0 \n"
"vpaddw %%ymm5,%%ymm1,%%ymm1 \n"
"vpsraw $0x8,%%ymm1,%%ymm1 \n"
"vpsraw $0x8,%%ymm0,%%ymm0 \n"
"vpacksswb %%ymm0,%%ymm1,%%ymm0 \n"
"vpermq $0xd8,%%ymm0,%%ymm0 \n"
"vpshufb %8,%%ymm0,%%ymm0 \n"
"vextractf128 $0x0,%%ymm0,(%1) \n"
"vextractf128 $0x1,%%ymm0,0x0(%1,%2,1) \n"
"lea 0x10(%1),%1 \n"
"sub $0x20,%3 \n"
"jg 1b \n"
"vzeroupper \n"
: "+r"(src_argb0), // %0
"+r"(dst_u), // %1
"+r"(dst_v), // %2
"+rm"(width) // %3
: "r"((intptr_t)(src_stride_argb)), // %4
"m"(kSub128), // %5
"m"(kARGBToVJ), // %6
"m"(kARGBToUJ), // %7
"m"(kShufARGBToUV_AVX) // %8
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6",
"xmm7");
}
#endif // HAS_ARGBTOUVJROW_AVX2
#ifdef HAS_ARGBTOUVJROW_SSSE3
void ARGBToUVJRow_SSSE3(const uint8_t* src_argb0,
int src_stride_argb,
uint8_t* dst_u,
uint8_t* dst_v,
int width) {
asm volatile(
"movdqa %5,%%xmm3 \n"
"movdqa %6,%%xmm4 \n"
"movdqa %7,%%xmm5 \n"
"sub %1,%2 \n"
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"movdqu 0x00(%0,%4,1),%%xmm7 \n"
"pavgb %%xmm7,%%xmm0 \n"
"movdqu 0x10(%0),%%xmm1 \n"
"movdqu 0x10(%0,%4,1),%%xmm7 \n"
"pavgb %%xmm7,%%xmm1 \n"
"movdqu 0x20(%0),%%xmm2 \n"
"movdqu 0x20(%0,%4,1),%%xmm7 \n"
"pavgb %%xmm7,%%xmm2 \n"
"movdqu 0x30(%0),%%xmm6 \n"
"movdqu 0x30(%0,%4,1),%%xmm7 \n"
"pavgb %%xmm7,%%xmm6 \n"
"lea 0x40(%0),%0 \n"
"movdqa %%xmm0,%%xmm7 \n"
"shufps $0x88,%%xmm1,%%xmm0 \n"
"shufps $0xdd,%%xmm1,%%xmm7 \n"
"pavgb %%xmm7,%%xmm0 \n"
"movdqa %%xmm2,%%xmm7 \n"
"shufps $0x88,%%xmm6,%%xmm2 \n"
"shufps $0xdd,%%xmm6,%%xmm7 \n"
"pavgb %%xmm7,%%xmm2 \n"
"movdqa %%xmm0,%%xmm1 \n"
"movdqa %%xmm2,%%xmm6 \n"
"pmaddubsw %%xmm4,%%xmm0 \n"
"pmaddubsw %%xmm4,%%xmm2 \n"
"pmaddubsw %%xmm3,%%xmm1 \n"
"pmaddubsw %%xmm3,%%xmm6 \n"
"phaddw %%xmm2,%%xmm0 \n"
"phaddw %%xmm6,%%xmm1 \n"
"paddw %%xmm5,%%xmm0 \n"
"paddw %%xmm5,%%xmm1 \n"
"psraw $0x8,%%xmm0 \n"
"psraw $0x8,%%xmm1 \n"
"packsswb %%xmm1,%%xmm0 \n"
"movlps %%xmm0,(%1) \n"
"movhps %%xmm0,0x00(%1,%2,1) \n"
"lea 0x8(%1),%1 \n"
"sub $0x10,%3 \n"
"jg 1b \n"
: "+r"(src_argb0), // %0
"+r"(dst_u), // %1
"+r"(dst_v), // %2
"+rm"(width) // %3
: "r"((intptr_t)(src_stride_argb)), // %4
"m"(kARGBToVJ), // %5
"m"(kARGBToUJ), // %6
"m"(kSub128) // %7
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm6", "xmm7");
}
#endif // HAS_ARGBTOUVJROW_SSSE3
#ifdef HAS_ARGBTOUV444ROW_SSSE3
void ARGBToUV444Row_SSSE3(const uint8_t* src_argb,
uint8_t* dst_u,
uint8_t* dst_v,
int width) {
asm volatile(
"movdqa %4,%%xmm3 \n"
"movdqa %5,%%xmm4 \n"
"movdqa %6,%%xmm5 \n"
"sub %1,%2 \n"
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"movdqu 0x10(%0),%%xmm1 \n"
"movdqu 0x20(%0),%%xmm2 \n"
"movdqu 0x30(%0),%%xmm6 \n"
"pmaddubsw %%xmm4,%%xmm0 \n"
"pmaddubsw %%xmm4,%%xmm1 \n"
"pmaddubsw %%xmm4,%%xmm2 \n"
"pmaddubsw %%xmm4,%%xmm6 \n"
"phaddw %%xmm1,%%xmm0 \n"
"phaddw %%xmm6,%%xmm2 \n"
"psraw $0x8,%%xmm0 \n"
"psraw $0x8,%%xmm2 \n"
"packsswb %%xmm2,%%xmm0 \n"
"paddb %%xmm5,%%xmm0 \n"
"movdqu %%xmm0,(%1) \n"
"movdqu (%0),%%xmm0 \n"
"movdqu 0x10(%0),%%xmm1 \n"
"movdqu 0x20(%0),%%xmm2 \n"
"movdqu 0x30(%0),%%xmm6 \n"
"pmaddubsw %%xmm3,%%xmm0 \n"
"pmaddubsw %%xmm3,%%xmm1 \n"
"pmaddubsw %%xmm3,%%xmm2 \n"
"pmaddubsw %%xmm3,%%xmm6 \n"
"phaddw %%xmm1,%%xmm0 \n"
"phaddw %%xmm6,%%xmm2 \n"
"psraw $0x8,%%xmm0 \n"
"psraw $0x8,%%xmm2 \n"
"packsswb %%xmm2,%%xmm0 \n"
"paddb %%xmm5,%%xmm0 \n"
"lea 0x40(%0),%0 \n"
"movdqu %%xmm0,0x00(%1,%2,1) \n"
"lea 0x10(%1),%1 \n"
"sub $0x10,%3 \n"
"jg 1b \n"
: "+r"(src_argb), // %0
"+r"(dst_u), // %1
"+r"(dst_v), // %2
"+rm"(width) // %3
: "m"(kARGBToV), // %4
"m"(kARGBToU), // %5
"m"(kAddUV128) // %6
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm6");
}
#endif // HAS_ARGBTOUV444ROW_SSSE3
void BGRAToYRow_SSSE3(const uint8_t* src_bgra, uint8_t* dst_y, int width) {
asm volatile(
"movdqa %3,%%xmm4 \n"
"movdqa %4,%%xmm5 \n"
"movdqa %5,%%xmm7 \n"
LABELALIGN RGBTOY(xmm7)
: "+r"(src_bgra), // %0
"+r"(dst_y), // %1
"+r"(width) // %2
: "m"(kBGRAToY), // %3
"m"(kSub128), // %4
"m"(kAddY16) // %5
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6",
"xmm7");
}
void BGRAToUVRow_SSSE3(const uint8_t* src_bgra0,
int src_stride_bgra,
uint8_t* dst_u,
uint8_t* dst_v,
int width) {
asm volatile(
"movdqa %5,%%xmm3 \n"
"movdqa %6,%%xmm4 \n"
"movdqa %7,%%xmm5 \n"
"sub %1,%2 \n"
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"movdqu 0x00(%0,%4,1),%%xmm7 \n"
"pavgb %%xmm7,%%xmm0 \n"
"movdqu 0x10(%0),%%xmm1 \n"
"movdqu 0x10(%0,%4,1),%%xmm7 \n"
"pavgb %%xmm7,%%xmm1 \n"
"movdqu 0x20(%0),%%xmm2 \n"
"movdqu 0x20(%0,%4,1),%%xmm7 \n"
"pavgb %%xmm7,%%xmm2 \n"
"movdqu 0x30(%0),%%xmm6 \n"
"movdqu 0x30(%0,%4,1),%%xmm7 \n"
"pavgb %%xmm7,%%xmm6 \n"
"lea 0x40(%0),%0 \n"
"movdqa %%xmm0,%%xmm7 \n"
"shufps $0x88,%%xmm1,%%xmm0 \n"
"shufps $0xdd,%%xmm1,%%xmm7 \n"
"pavgb %%xmm7,%%xmm0 \n"
"movdqa %%xmm2,%%xmm7 \n"
"shufps $0x88,%%xmm6,%%xmm2 \n"
"shufps $0xdd,%%xmm6,%%xmm7 \n"
"pavgb %%xmm7,%%xmm2 \n"
"movdqa %%xmm0,%%xmm1 \n"
"movdqa %%xmm2,%%xmm6 \n"
"pmaddubsw %%xmm4,%%xmm0 \n"
"pmaddubsw %%xmm4,%%xmm2 \n"
"pmaddubsw %%xmm3,%%xmm1 \n"
"pmaddubsw %%xmm3,%%xmm6 \n"
"phaddw %%xmm2,%%xmm0 \n"
"phaddw %%xmm6,%%xmm1 \n"
"psraw $0x8,%%xmm0 \n"
"psraw $0x8,%%xmm1 \n"
"packsswb %%xmm1,%%xmm0 \n"
"paddb %%xmm5,%%xmm0 \n"
"movlps %%xmm0,(%1) \n"
"movhps %%xmm0,0x00(%1,%2,1) \n"
"lea 0x8(%1),%1 \n"
"sub $0x10,%3 \n"
"jg 1b \n"
: "+r"(src_bgra0), // %0
"+r"(dst_u), // %1
"+r"(dst_v), // %2
"+rm"(width) // %3
: "r"((intptr_t)(src_stride_bgra)), // %4
"m"(kBGRAToV), // %5
"m"(kBGRAToU), // %6
"m"(kAddUV128) // %7
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm6", "xmm7");
}
void ABGRToYRow_SSSE3(const uint8_t* src_abgr, uint8_t* dst_y, int width) {
asm volatile(
"movdqa %3,%%xmm4 \n"
"movdqa %4,%%xmm5 \n"
"movdqa %5,%%xmm7 \n"
LABELALIGN RGBTOY(xmm7)
: "+r"(src_abgr), // %0
"+r"(dst_y), // %1
"+r"(width) // %2
: "m"(kABGRToY), // %3
"m"(kSub128), // %4
"m"(kAddY16) // %5
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6",
"xmm7");
}
void RGBAToYRow_SSSE3(const uint8_t* src_rgba, uint8_t* dst_y, int width) {
asm volatile(
"movdqa %3,%%xmm4 \n"
"movdqa %4,%%xmm5 \n"
"movdqa %5,%%xmm7 \n"
LABELALIGN RGBTOY(xmm7)
: "+r"(src_rgba), // %0
"+r"(dst_y), // %1
"+r"(width) // %2
: "m"(kRGBAToY), // %3
"m"(kSub128), // %4
"m"(kAddY16) // %5
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6",
"xmm7");
}
void ABGRToUVRow_SSSE3(const uint8_t* src_abgr0,
int src_stride_abgr,
uint8_t* dst_u,
uint8_t* dst_v,
int width) {
asm volatile(
"movdqa %5,%%xmm3 \n"
"movdqa %6,%%xmm4 \n"
"movdqa %7,%%xmm5 \n"
"sub %1,%2 \n"
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"movdqu 0x00(%0,%4,1),%%xmm7 \n"
"pavgb %%xmm7,%%xmm0 \n"
"movdqu 0x10(%0),%%xmm1 \n"
"movdqu 0x10(%0,%4,1),%%xmm7 \n"
"pavgb %%xmm7,%%xmm1 \n"
"movdqu 0x20(%0),%%xmm2 \n"
"movdqu 0x20(%0,%4,1),%%xmm7 \n"
"pavgb %%xmm7,%%xmm2 \n"
"movdqu 0x30(%0),%%xmm6 \n"
"movdqu 0x30(%0,%4,1),%%xmm7 \n"
"pavgb %%xmm7,%%xmm6 \n"
"lea 0x40(%0),%0 \n"
"movdqa %%xmm0,%%xmm7 \n"
"shufps $0x88,%%xmm1,%%xmm0 \n"
"shufps $0xdd,%%xmm1,%%xmm7 \n"
"pavgb %%xmm7,%%xmm0 \n"
"movdqa %%xmm2,%%xmm7 \n"
"shufps $0x88,%%xmm6,%%xmm2 \n"
"shufps $0xdd,%%xmm6,%%xmm7 \n"
"pavgb %%xmm7,%%xmm2 \n"
"movdqa %%xmm0,%%xmm1 \n"
"movdqa %%xmm2,%%xmm6 \n"
"pmaddubsw %%xmm4,%%xmm0 \n"
"pmaddubsw %%xmm4,%%xmm2 \n"
"pmaddubsw %%xmm3,%%xmm1 \n"
"pmaddubsw %%xmm3,%%xmm6 \n"
"phaddw %%xmm2,%%xmm0 \n"
"phaddw %%xmm6,%%xmm1 \n"
"psraw $0x8,%%xmm0 \n"
"psraw $0x8,%%xmm1 \n"
"packsswb %%xmm1,%%xmm0 \n"
"paddb %%xmm5,%%xmm0 \n"
"movlps %%xmm0,(%1) \n"
"movhps %%xmm0,0x00(%1,%2,1) \n"
"lea 0x8(%1),%1 \n"
"sub $0x10,%3 \n"
"jg 1b \n"
: "+r"(src_abgr0), // %0
"+r"(dst_u), // %1
"+r"(dst_v), // %2
"+rm"(width) // %3
: "r"((intptr_t)(src_stride_abgr)), // %4
"m"(kABGRToV), // %5
"m"(kABGRToU), // %6
"m"(kAddUV128) // %7
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm6", "xmm7");
}
void RGBAToUVRow_SSSE3(const uint8_t* src_rgba0,
int src_stride_rgba,
uint8_t* dst_u,
uint8_t* dst_v,
int width) {
asm volatile(
"movdqa %5,%%xmm3 \n"
"movdqa %6,%%xmm4 \n"
"movdqa %7,%%xmm5 \n"
"sub %1,%2 \n"
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"movdqu 0x00(%0,%4,1),%%xmm7 \n"
"pavgb %%xmm7,%%xmm0 \n"
"movdqu 0x10(%0),%%xmm1 \n"
"movdqu 0x10(%0,%4,1),%%xmm7 \n"
"pavgb %%xmm7,%%xmm1 \n"
"movdqu 0x20(%0),%%xmm2 \n"
"movdqu 0x20(%0,%4,1),%%xmm7 \n"
"pavgb %%xmm7,%%xmm2 \n"
"movdqu 0x30(%0),%%xmm6 \n"
"movdqu 0x30(%0,%4,1),%%xmm7 \n"
"pavgb %%xmm7,%%xmm6 \n"
"lea 0x40(%0),%0 \n"
"movdqa %%xmm0,%%xmm7 \n"
"shufps $0x88,%%xmm1,%%xmm0 \n"
"shufps $0xdd,%%xmm1,%%xmm7 \n"
"pavgb %%xmm7,%%xmm0 \n"
"movdqa %%xmm2,%%xmm7 \n"
"shufps $0x88,%%xmm6,%%xmm2 \n"
"shufps $0xdd,%%xmm6,%%xmm7 \n"
"pavgb %%xmm7,%%xmm2 \n"
"movdqa %%xmm0,%%xmm1 \n"
"movdqa %%xmm2,%%xmm6 \n"
"pmaddubsw %%xmm4,%%xmm0 \n"
"pmaddubsw %%xmm4,%%xmm2 \n"
"pmaddubsw %%xmm3,%%xmm1 \n"
"pmaddubsw %%xmm3,%%xmm6 \n"
"phaddw %%xmm2,%%xmm0 \n"
"phaddw %%xmm6,%%xmm1 \n"
"psraw $0x8,%%xmm0 \n"
"psraw $0x8,%%xmm1 \n"
"packsswb %%xmm1,%%xmm0 \n"
"paddb %%xmm5,%%xmm0 \n"
"movlps %%xmm0,(%1) \n"
"movhps %%xmm0,0x00(%1,%2,1) \n"
"lea 0x8(%1),%1 \n"
"sub $0x10,%3 \n"
"jg 1b \n"
: "+r"(src_rgba0), // %0
"+r"(dst_u), // %1
"+r"(dst_v), // %2
"+rm"(width) // %3
: "r"((intptr_t)(src_stride_rgba)), // %4
"m"(kRGBAToV), // %5
"m"(kRGBAToU), // %6
"m"(kAddUV128) // %7
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm6", "xmm7");
}
#if defined(HAS_I422TOARGBROW_SSSE3) || defined(HAS_I422TOARGBROW_AVX2)
// Read 8 UV from 444
#define READYUV444 \
"movq (%[u_buf]),%%xmm0 \n" \
"movq 0x00(%[u_buf],%[v_buf],1),%%xmm1 \n" \
"lea 0x8(%[u_buf]),%[u_buf] \n" \
"punpcklbw %%xmm1,%%xmm0 \n" \
"movq (%[y_buf]),%%xmm4 \n" \
"punpcklbw %%xmm4,%%xmm4 \n" \
"lea 0x8(%[y_buf]),%[y_buf] \n"
// Read 4 UV from 422, upsample to 8 UV
#define READYUV422 \
"movd (%[u_buf]),%%xmm0 \n" \
"movd 0x00(%[u_buf],%[v_buf],1),%%xmm1 \n" \
"lea 0x4(%[u_buf]),%[u_buf] \n" \
"punpcklbw %%xmm1,%%xmm0 \n" \
"punpcklwd %%xmm0,%%xmm0 \n" \
"movq (%[y_buf]),%%xmm4 \n" \
"punpcklbw %%xmm4,%%xmm4 \n" \
"lea 0x8(%[y_buf]),%[y_buf] \n"
// Read 4 UV from 422 10 bit, upsample to 8 UV
// TODO(fbarchard): Consider shufb to replace pack/unpack
// TODO(fbarchard): Consider pmulhuw to replace psraw
// TODO(fbarchard): Consider pmullw to replace psllw and allow different bits.
#define READYUV210 \
"movq (%[u_buf]),%%xmm0 \n" \
"movq 0x00(%[u_buf],%[v_buf],1),%%xmm1 \n" \
"lea 0x8(%[u_buf]),%[u_buf] \n" \
"punpcklwd %%xmm1,%%xmm0 \n" \
"psraw $0x2,%%xmm0 \n" \
"packuswb %%xmm0,%%xmm0 \n" \
"punpcklwd %%xmm0,%%xmm0 \n" \
"movdqu (%[y_buf]),%%xmm4 \n" \
"psllw $0x6,%%xmm4 \n" \
"lea 0x10(%[y_buf]),%[y_buf] \n"
// Read 4 UV from 422, upsample to 8 UV. With 8 Alpha.
#define READYUVA422 \
"movd (%[u_buf]),%%xmm0 \n" \
"movd 0x00(%[u_buf],%[v_buf],1),%%xmm1 \n" \
"lea 0x4(%[u_buf]),%[u_buf] \n" \
"punpcklbw %%xmm1,%%xmm0 \n" \
"punpcklwd %%xmm0,%%xmm0 \n" \
"movq (%[y_buf]),%%xmm4 \n" \
"punpcklbw %%xmm4,%%xmm4 \n" \
"lea 0x8(%[y_buf]),%[y_buf] \n" \
"movq (%[a_buf]),%%xmm5 \n" \
"lea 0x8(%[a_buf]),%[a_buf] \n"
// Read 4 UV from NV12, upsample to 8 UV
#define READNV12 \
"movq (%[uv_buf]),%%xmm0 \n" \
"lea 0x8(%[uv_buf]),%[uv_buf] \n" \
"punpcklwd %%xmm0,%%xmm0 \n" \
"movq (%[y_buf]),%%xmm4 \n" \
"punpcklbw %%xmm4,%%xmm4 \n" \
"lea 0x8(%[y_buf]),%[y_buf] \n"
// Read 4 VU from NV21, upsample to 8 UV
#define READNV21 \
"movq (%[vu_buf]),%%xmm0 \n" \
"lea 0x8(%[vu_buf]),%[vu_buf] \n" \
"pshufb %[kShuffleNV21], %%xmm0 \n" \
"movq (%[y_buf]),%%xmm4 \n" \
"punpcklbw %%xmm4,%%xmm4 \n" \
"lea 0x8(%[y_buf]),%[y_buf] \n"
// Read 4 YUY2 with 8 Y and update 4 UV to 8 UV.
#define READYUY2 \
"movdqu (%[yuy2_buf]),%%xmm4 \n" \
"pshufb %[kShuffleYUY2Y], %%xmm4 \n" \
"movdqu (%[yuy2_buf]),%%xmm0 \n" \
"pshufb %[kShuffleYUY2UV], %%xmm0 \n" \
"lea 0x10(%[yuy2_buf]),%[yuy2_buf] \n"
// Read 4 UYVY with 8 Y and update 4 UV to 8 UV.
#define READUYVY \
"movdqu (%[uyvy_buf]),%%xmm4 \n" \
"pshufb %[kShuffleUYVYY], %%xmm4 \n" \
"movdqu (%[uyvy_buf]),%%xmm0 \n" \
"pshufb %[kShuffleUYVYUV], %%xmm0 \n" \
"lea 0x10(%[uyvy_buf]),%[uyvy_buf] \n"
#if defined(__x86_64__)
#define YUVTORGB_SETUP(yuvconstants) \
"movdqa (%[yuvconstants]),%%xmm8 \n" \
"movdqa 32(%[yuvconstants]),%%xmm9 \n" \
"movdqa 64(%[yuvconstants]),%%xmm10 \n" \
"movdqa 96(%[yuvconstants]),%%xmm11 \n" \
"movdqa 128(%[yuvconstants]),%%xmm12 \n" \
"movdqa 160(%[yuvconstants]),%%xmm13 \n" \
"movdqa 192(%[yuvconstants]),%%xmm14 \n"
// Convert 8 pixels: 8 UV and 8 Y
#define YUVTORGB16(yuvconstants) \
"movdqa %%xmm0,%%xmm1 \n" \
"movdqa %%xmm0,%%xmm2 \n" \
"movdqa %%xmm0,%%xmm3 \n" \
"movdqa %%xmm11,%%xmm0 \n" \
"pmaddubsw %%xmm8,%%xmm1 \n" \
"psubw %%xmm1,%%xmm0 \n" \
"movdqa %%xmm12,%%xmm1 \n" \
"pmaddubsw %%xmm9,%%xmm2 \n" \
"psubw %%xmm2,%%xmm1 \n" \
"movdqa %%xmm13,%%xmm2 \n" \
"pmaddubsw %%xmm10,%%xmm3 \n" \
"psubw %%xmm3,%%xmm2 \n" \
"pmulhuw %%xmm14,%%xmm4 \n" \
"paddsw %%xmm4,%%xmm0 \n" \
"paddsw %%xmm4,%%xmm1 \n" \
"paddsw %%xmm4,%%xmm2 \n"
#define YUVTORGB_REGS \
"xmm8", "xmm9", "xmm10", "xmm11", "xmm12", "xmm13", "xmm14",
#else
#define YUVTORGB_SETUP(yuvconstants)
// Convert 8 pixels: 8 UV and 8 Y
#define YUVTORGB16(yuvconstants) \
"movdqa %%xmm0,%%xmm1 \n" \
"movdqa %%xmm0,%%xmm2 \n" \
"movdqa %%xmm0,%%xmm3 \n" \
"movdqa 96(%[yuvconstants]),%%xmm0 \n" \
"pmaddubsw (%[yuvconstants]),%%xmm1 \n" \
"psubw %%xmm1,%%xmm0 \n" \
"movdqa 128(%[yuvconstants]),%%xmm1 \n" \
"pmaddubsw 32(%[yuvconstants]),%%xmm2 \n" \
"psubw %%xmm2,%%xmm1 \n" \
"movdqa 160(%[yuvconstants]),%%xmm2 \n" \
"pmaddubsw 64(%[yuvconstants]),%%xmm3 \n" \
"psubw %%xmm3,%%xmm2 \n" \
"pmulhuw 192(%[yuvconstants]),%%xmm4 \n" \
"paddsw %%xmm4,%%xmm0 \n" \
"paddsw %%xmm4,%%xmm1 \n" \
"paddsw %%xmm4,%%xmm2 \n"
#define YUVTORGB_REGS
#endif
#define YUVTORGB(yuvconstants) \
YUVTORGB16(yuvconstants) \
"psraw $0x6,%%xmm0 \n" \
"psraw $0x6,%%xmm1 \n" \
"psraw $0x6,%%xmm2 \n" \
"packuswb %%xmm0,%%xmm0 \n" \
"packuswb %%xmm1,%%xmm1 \n" \
"packuswb %%xmm2,%%xmm2 \n"
// Store 8 ARGB values.
#define STOREARGB \
"punpcklbw %%xmm1,%%xmm0 \n" \
"punpcklbw %%xmm5,%%xmm2 \n" \
"movdqa %%xmm0,%%xmm1 \n" \
"punpcklwd %%xmm2,%%xmm0 \n" \
"punpckhwd %%xmm2,%%xmm1 \n" \
"movdqu %%xmm0,(%[dst_argb]) \n" \
"movdqu %%xmm1,0x10(%[dst_argb]) \n" \
"lea 0x20(%[dst_argb]), %[dst_argb] \n"
// Store 8 RGBA values.
#define STORERGBA \
"pcmpeqb %%xmm5,%%xmm5 \n" \
"punpcklbw %%xmm2,%%xmm1 \n" \
"punpcklbw %%xmm0,%%xmm5 \n" \
"movdqa %%xmm5,%%xmm0 \n" \
"punpcklwd %%xmm1,%%xmm5 \n" \
"punpckhwd %%xmm1,%%xmm0 \n" \
"movdqu %%xmm5,(%[dst_rgba]) \n" \
"movdqu %%xmm0,0x10(%[dst_rgba]) \n" \
"lea 0x20(%[dst_rgba]),%[dst_rgba] \n"
// Store 8 AR30 values.
#define STOREAR30 \
"psraw $0x4,%%xmm0 \n" \
"psraw $0x4,%%xmm1 \n" \
"psraw $0x4,%%xmm2 \n" \
"pminsw %%xmm7,%%xmm0 \n" \
"pminsw %%xmm7,%%xmm1 \n" \
"pminsw %%xmm7,%%xmm2 \n" \
"pmaxsw %%xmm6,%%xmm0 \n" \
"pmaxsw %%xmm6,%%xmm1 \n" \
"pmaxsw %%xmm6,%%xmm2 \n" \
"psllw $0x4,%%xmm2 \n" \
"movdqa %%xmm0,%%xmm3 \n" \
"punpcklwd %%xmm2,%%xmm0 \n" \
"punpckhwd %%xmm2,%%xmm3 \n" \
"movdqa %%xmm1,%%xmm2 \n" \
"punpcklwd %%xmm5,%%xmm1 \n" \
"punpckhwd %%xmm5,%%xmm2 \n" \
"pslld $0xa,%%xmm1 \n" \
"pslld $0xa,%%xmm2 \n" \
"por %%xmm1,%%xmm0 \n" \
"por %%xmm2,%%xmm3 \n" \
"movdqu %%xmm0,(%[dst_ar30]) \n" \
"movdqu %%xmm3,0x10(%[dst_ar30]) \n" \
"lea 0x20(%[dst_ar30]), %[dst_ar30] \n"
void OMITFP I444ToARGBRow_SSSE3(const uint8_t* y_buf,
const uint8_t* u_buf,
const uint8_t* v_buf,
uint8_t* dst_argb,
const struct YuvConstants* yuvconstants,
int width) {
asm volatile (
YUVTORGB_SETUP(yuvconstants)
"sub %[u_buf],%[v_buf] \n"
"pcmpeqb %%xmm5,%%xmm5 \n"
LABELALIGN
"1: \n"
READYUV444
YUVTORGB(yuvconstants)
STOREARGB
"sub $0x8,%[width] \n"
"jg 1b \n"
: [y_buf]"+r"(y_buf), // %[y_buf]
[u_buf]"+r"(u_buf), // %[u_buf]
[v_buf]"+r"(v_buf), // %[v_buf]
[dst_argb]"+r"(dst_argb), // %[dst_argb]
[width]"+rm"(width) // %[width]
: [yuvconstants]"r"(yuvconstants) // %[yuvconstants]
: "memory", "cc", YUVTORGB_REGS
"xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5"
);
}
void OMITFP I422ToRGB24Row_SSSE3(const uint8_t* y_buf,
const uint8_t* u_buf,
const uint8_t* v_buf,
uint8_t* dst_rgb24,
const struct YuvConstants* yuvconstants,
int width) {
asm volatile (
YUVTORGB_SETUP(yuvconstants)
"movdqa %[kShuffleMaskARGBToRGB24_0],%%xmm5 \n"
"movdqa %[kShuffleMaskARGBToRGB24],%%xmm6 \n"
"sub %[u_buf],%[v_buf] \n"
LABELALIGN
"1: \n"
READYUV422
YUVTORGB(yuvconstants)
"punpcklbw %%xmm1,%%xmm0 \n"
"punpcklbw %%xmm2,%%xmm2 \n"
"movdqa %%xmm0,%%xmm1 \n"
"punpcklwd %%xmm2,%%xmm0 \n"
"punpckhwd %%xmm2,%%xmm1 \n"
"pshufb %%xmm5,%%xmm0 \n"
"pshufb %%xmm6,%%xmm1 \n"
"palignr $0xc,%%xmm0,%%xmm1 \n"
"movq %%xmm0,(%[dst_rgb24]) \n"
"movdqu %%xmm1,0x8(%[dst_rgb24]) \n"
"lea 0x18(%[dst_rgb24]),%[dst_rgb24] \n"
"subl $0x8,%[width] \n"
"jg 1b \n"
: [y_buf]"+r"(y_buf), // %[y_buf]
[u_buf]"+r"(u_buf), // %[u_buf]
[v_buf]"+r"(v_buf), // %[v_buf]
[dst_rgb24]"+r"(dst_rgb24), // %[dst_rgb24]
#if defined(__i386__)
[width]"+m"(width) // %[width]
#else
[width]"+rm"(width) // %[width]
#endif
: [yuvconstants]"r"(yuvconstants), // %[yuvconstants]
[kShuffleMaskARGBToRGB24_0]"m"(kShuffleMaskARGBToRGB24_0),
[kShuffleMaskARGBToRGB24]"m"(kShuffleMaskARGBToRGB24)
: "memory", "cc", YUVTORGB_REGS
"xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6"
);
}
void OMITFP I422ToARGBRow_SSSE3(const uint8_t* y_buf,
const uint8_t* u_buf,
const uint8_t* v_buf,
uint8_t* dst_argb,
const struct YuvConstants* yuvconstants,
int width) {
asm volatile (
YUVTORGB_SETUP(yuvconstants)
"sub %[u_buf],%[v_buf] \n"
"pcmpeqb %%xmm5,%%xmm5 \n"
LABELALIGN
"1: \n"
READYUV422
YUVTORGB(yuvconstants)
STOREARGB
"sub $0x8,%[width] \n"
"jg 1b \n"
: [y_buf]"+r"(y_buf), // %[y_buf]
[u_buf]"+r"(u_buf), // %[u_buf]
[v_buf]"+r"(v_buf), // %[v_buf]
[dst_argb]"+r"(dst_argb), // %[dst_argb]
[width]"+rm"(width) // %[width]
: [yuvconstants]"r"(yuvconstants) // %[yuvconstants]
: "memory", "cc", YUVTORGB_REGS
"xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5"
);
}
void OMITFP I422ToAR30Row_SSSE3(const uint8_t* y_buf,
const uint8_t* u_buf,
const uint8_t* v_buf,
uint8_t* dst_ar30,
const struct YuvConstants* yuvconstants,
int width) {
asm volatile (
YUVTORGB_SETUP(yuvconstants)
"sub %[u_buf],%[v_buf] \n"
"pcmpeqb %%xmm5,%%xmm5 \n" // AR30 constants
"psrlw $14,%%xmm5 \n"
"psllw $4,%%xmm5 \n" // 2 alpha bits
"pxor %%xmm6,%%xmm6 \n"
"pcmpeqb %%xmm7,%%xmm7 \n" // 0 for min
"psrlw $6,%%xmm7 \n" // 1023 for max
LABELALIGN
"1: \n"
READYUV422
YUVTORGB16(yuvconstants)
STOREAR30
"sub $0x8,%[width] \n"
"jg 1b \n"
: [y_buf]"+r"(y_buf), // %[y_buf]
[u_buf]"+r"(u_buf), // %[u_buf]
[v_buf]"+r"(v_buf), // %[v_buf]
[dst_ar30]"+r"(dst_ar30), // %[dst_ar30]
[width]"+rm"(width) // %[width]
: [yuvconstants]"r"(yuvconstants) // %[yuvconstants]
: "memory", "cc", YUVTORGB_REGS
"xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6", "xmm7"
);
}
// 10 bit YUV to ARGB
void OMITFP I210ToARGBRow_SSSE3(const uint16_t* y_buf,
const uint16_t* u_buf,
const uint16_t* v_buf,
uint8_t* dst_argb,
const struct YuvConstants* yuvconstants,
int width) {
asm volatile (
YUVTORGB_SETUP(yuvconstants)
"sub %[u_buf],%[v_buf] \n"
"pcmpeqb %%xmm5,%%xmm5 \n"
LABELALIGN
"1: \n"
READYUV210
YUVTORGB(yuvconstants)
STOREARGB
"sub $0x8,%[width] \n"
"jg 1b \n"
: [y_buf]"+r"(y_buf), // %[y_buf]
[u_buf]"+r"(u_buf), // %[u_buf]
[v_buf]"+r"(v_buf), // %[v_buf]
[dst_argb]"+r"(dst_argb), // %[dst_argb]
[width]"+rm"(width) // %[width]
: [yuvconstants]"r"(yuvconstants) // %[yuvconstants]
: "memory", "cc", YUVTORGB_REGS
"xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5"
);
}
// 10 bit YUV to AR30
void OMITFP I210ToAR30Row_SSSE3(const uint16_t* y_buf,
const uint16_t* u_buf,
const uint16_t* v_buf,
uint8_t* dst_ar30,
const struct YuvConstants* yuvconstants,
int width) {
asm volatile (
YUVTORGB_SETUP(yuvconstants)
"sub %[u_buf],%[v_buf] \n"
"pcmpeqb %%xmm5,%%xmm5 \n"
"psrlw $14,%%xmm5 \n"
"psllw $4,%%xmm5 \n" // 2 alpha bits
"pxor %%xmm6,%%xmm6 \n"
"pcmpeqb %%xmm7,%%xmm7 \n" // 0 for min
"psrlw $6,%%xmm7 \n" // 1023 for max
LABELALIGN
"1: \n"
READYUV210
YUVTORGB16(yuvconstants)
STOREAR30
"sub $0x8,%[width] \n"
"jg 1b \n"
: [y_buf]"+r"(y_buf), // %[y_buf]
[u_buf]"+r"(u_buf), // %[u_buf]
[v_buf]"+r"(v_buf), // %[v_buf]
[dst_ar30]"+r"(dst_ar30), // %[dst_ar30]
[width]"+rm"(width) // %[width]
: [yuvconstants]"r"(yuvconstants) // %[yuvconstants]
: "memory", "cc", YUVTORGB_REGS
"xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6", "xmm7"
);
}
#ifdef HAS_I422ALPHATOARGBROW_SSSE3
void OMITFP I422AlphaToARGBRow_SSSE3(const uint8_t* y_buf,
const uint8_t* u_buf,
const uint8_t* v_buf,
const uint8_t* a_buf,
uint8_t* dst_argb,
const struct YuvConstants* yuvconstants,
int width) {
// clang-format off
asm volatile (
YUVTORGB_SETUP(yuvconstants)
"sub %[u_buf],%[v_buf] \n"
LABELALIGN
"1: \n"
READYUVA422
YUVTORGB(yuvconstants)
STOREARGB
"subl $0x8,%[width] \n"
"jg 1b \n"
: [y_buf]"+r"(y_buf), // %[y_buf]
[u_buf]"+r"(u_buf), // %[u_buf]
[v_buf]"+r"(v_buf), // %[v_buf]
[a_buf]"+r"(a_buf), // %[a_buf]
[dst_argb]"+r"(dst_argb), // %[dst_argb]
#if defined(__i386__)
[width]"+m"(width) // %[width]
#else
[width]"+rm"(width) // %[width]
#endif
: [yuvconstants]"r"(yuvconstants) // %[yuvconstants]
: "memory", "cc", YUVTORGB_REGS
"xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5"
);
// clang-format on
}
#endif // HAS_I422ALPHATOARGBROW_SSSE3
void OMITFP NV12ToARGBRow_SSSE3(const uint8_t* y_buf,
const uint8_t* uv_buf,
uint8_t* dst_argb,
const struct YuvConstants* yuvconstants,
int width) {
// clang-format off
asm volatile (
YUVTORGB_SETUP(yuvconstants)
"pcmpeqb %%xmm5,%%xmm5 \n"
LABELALIGN
"1: \n"
READNV12
YUVTORGB(yuvconstants)
STOREARGB
"sub $0x8,%[width] \n"
"jg 1b \n"
: [y_buf]"+r"(y_buf), // %[y_buf]
[uv_buf]"+r"(uv_buf), // %[uv_buf]
[dst_argb]"+r"(dst_argb), // %[dst_argb]
[width]"+rm"(width) // %[width]
: [yuvconstants]"r"(yuvconstants) // %[yuvconstants]
: "memory", "cc", YUVTORGB_REGS
"xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5"
);
// clang-format on
}
void OMITFP NV21ToARGBRow_SSSE3(const uint8_t* y_buf,
const uint8_t* vu_buf,
uint8_t* dst_argb,
const struct YuvConstants* yuvconstants,
int width) {
// clang-format off
asm volatile (
YUVTORGB_SETUP(yuvconstants)
"pcmpeqb %%xmm5,%%xmm5 \n"
LABELALIGN
"1: \n"
READNV21
YUVTORGB(yuvconstants)
STOREARGB
"sub $0x8,%[width] \n"
"jg 1b \n"
: [y_buf]"+r"(y_buf), // %[y_buf]
[vu_buf]"+r"(vu_buf), // %[vu_buf]
[dst_argb]"+r"(dst_argb), // %[dst_argb]
[width]"+rm"(width) // %[width]
: [yuvconstants]"r"(yuvconstants), // %[yuvconstants]
[kShuffleNV21]"m"(kShuffleNV21)
: "memory", "cc", YUVTORGB_REGS
"xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5"
);
// clang-format on
}
void OMITFP YUY2ToARGBRow_SSSE3(const uint8_t* yuy2_buf,
uint8_t* dst_argb,
const struct YuvConstants* yuvconstants,
int width) {
// clang-format off
asm volatile (
YUVTORGB_SETUP(yuvconstants)
"pcmpeqb %%xmm5,%%xmm5 \n"
LABELALIGN
"1: \n"
READYUY2
YUVTORGB(yuvconstants)
STOREARGB
"sub $0x8,%[width] \n"
"jg 1b \n"
: [yuy2_buf]"+r"(yuy2_buf), // %[yuy2_buf]
[dst_argb]"+r"(dst_argb), // %[dst_argb]
[width]"+rm"(width) // %[width]
: [yuvconstants]"r"(yuvconstants), // %[yuvconstants]
[kShuffleYUY2Y]"m"(kShuffleYUY2Y),
[kShuffleYUY2UV]"m"(kShuffleYUY2UV)
: "memory", "cc", YUVTORGB_REGS
"xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5"
);
// clang-format on
}
void OMITFP UYVYToARGBRow_SSSE3(const uint8_t* uyvy_buf,
uint8_t* dst_argb,
const struct YuvConstants* yuvconstants,
int width) {
// clang-format off
asm volatile (
YUVTORGB_SETUP(yuvconstants)
"pcmpeqb %%xmm5,%%xmm5 \n"
LABELALIGN
"1: \n"
READUYVY
YUVTORGB(yuvconstants)
STOREARGB
"sub $0x8,%[width] \n"
"jg 1b \n"
: [uyvy_buf]"+r"(uyvy_buf), // %[uyvy_buf]
[dst_argb]"+r"(dst_argb), // %[dst_argb]
[width]"+rm"(width) // %[width]
: [yuvconstants]"r"(yuvconstants), // %[yuvconstants]
[kShuffleUYVYY]"m"(kShuffleUYVYY),
[kShuffleUYVYUV]"m"(kShuffleUYVYUV)
: "memory", "cc", YUVTORGB_REGS
"xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5"
);
// clang-format on
}
void OMITFP I422ToRGBARow_SSSE3(const uint8_t* y_buf,
const uint8_t* u_buf,
const uint8_t* v_buf,
uint8_t* dst_rgba,
const struct YuvConstants* yuvconstants,
int width) {
asm volatile (
YUVTORGB_SETUP(yuvconstants)
"sub %[u_buf],%[v_buf] \n"
"pcmpeqb %%xmm5,%%xmm5 \n"
LABELALIGN
"1: \n"
READYUV422
YUVTORGB(yuvconstants)
STORERGBA
"sub $0x8,%[width] \n"
"jg 1b \n"
: [y_buf]"+r"(y_buf), // %[y_buf]
[u_buf]"+r"(u_buf), // %[u_buf]
[v_buf]"+r"(v_buf), // %[v_buf]
[dst_rgba]"+r"(dst_rgba), // %[dst_rgba]
[width]"+rm"(width) // %[width]
: [yuvconstants]"r"(yuvconstants) // %[yuvconstants]
: "memory", "cc", YUVTORGB_REGS
"xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5"
);
}
#endif // HAS_I422TOARGBROW_SSSE3
// Read 16 UV from 444
#define READYUV444_AVX2 \
"vmovdqu (%[u_buf]),%%xmm0 \n" \
"vmovdqu 0x00(%[u_buf],%[v_buf],1),%%xmm1 \n" \
"lea 0x10(%[u_buf]),%[u_buf] \n" \
"vpermq $0xd8,%%ymm0,%%ymm0 \n" \
"vpermq $0xd8,%%ymm1,%%ymm1 \n" \
"vpunpcklbw %%ymm1,%%ymm0,%%ymm0 \n" \
"vmovdqu (%[y_buf]),%%xmm4 \n" \
"vpermq $0xd8,%%ymm4,%%ymm4 \n" \
"vpunpcklbw %%ymm4,%%ymm4,%%ymm4 \n" \
"lea 0x10(%[y_buf]),%[y_buf] \n"
// Read 8 UV from 422, upsample to 16 UV.
#define READYUV422_AVX2 \
"vmovq (%[u_buf]),%%xmm0 \n" \
"vmovq 0x00(%[u_buf],%[v_buf],1),%%xmm1 \n" \
"lea 0x8(%[u_buf]),%[u_buf] \n" \
"vpunpcklbw %%ymm1,%%ymm0,%%ymm0 \n" \
"vpermq $0xd8,%%ymm0,%%ymm0 \n" \
"vpunpcklwd %%ymm0,%%ymm0,%%ymm0 \n" \
"vmovdqu (%[y_buf]),%%xmm4 \n" \
"vpermq $0xd8,%%ymm4,%%ymm4 \n" \
"vpunpcklbw %%ymm4,%%ymm4,%%ymm4 \n" \
"lea 0x10(%[y_buf]),%[y_buf] \n"
// Read 8 UV from 210 10 bit, upsample to 16 UV
// TODO(fbarchard): Consider vshufb to replace pack/unpack
// TODO(fbarchard): Consider vunpcklpd to combine the 2 registers into 1.
#define READYUV210_AVX2 \
"vmovdqu (%[u_buf]),%%xmm0 \n" \
"vmovdqu 0x00(%[u_buf],%[v_buf],1),%%xmm1 \n" \
"lea 0x10(%[u_buf]),%[u_buf] \n" \
"vpermq $0xd8,%%ymm0,%%ymm0 \n" \
"vpermq $0xd8,%%ymm1,%%ymm1 \n" \
"vpunpcklwd %%ymm1,%%ymm0,%%ymm0 \n" \
"vpsraw $0x2,%%ymm0,%%ymm0 \n" \
"vpackuswb %%ymm0,%%ymm0,%%ymm0 \n" \
"vpunpcklwd %%ymm0,%%ymm0,%%ymm0 \n" \
"vmovdqu (%[y_buf]),%%ymm4 \n" \
"vpsllw $0x6,%%ymm4,%%ymm4 \n" \
"lea 0x20(%[y_buf]),%[y_buf] \n"
// Read 8 UV from 422, upsample to 16 UV. With 16 Alpha.
#define READYUVA422_AVX2 \
"vmovq (%[u_buf]),%%xmm0 \n" \
"vmovq 0x00(%[u_buf],%[v_buf],1),%%xmm1 \n" \
"lea 0x8(%[u_buf]),%[u_buf] \n" \
"vpunpcklbw %%ymm1,%%ymm0,%%ymm0 \n" \
"vpermq $0xd8,%%ymm0,%%ymm0 \n" \
"vpunpcklwd %%ymm0,%%ymm0,%%ymm0 \n" \
"vmovdqu (%[y_buf]),%%xmm4 \n" \
"vpermq $0xd8,%%ymm4,%%ymm4 \n" \
"vpunpcklbw %%ymm4,%%ymm4,%%ymm4 \n" \
"lea 0x10(%[y_buf]),%[y_buf] \n" \
"vmovdqu (%[a_buf]),%%xmm5 \n" \
"vpermq $0xd8,%%ymm5,%%ymm5 \n" \
"lea 0x10(%[a_buf]),%[a_buf] \n"
// Read 8 UV from NV12, upsample to 16 UV.
#define READNV12_AVX2 \
"vmovdqu (%[uv_buf]),%%xmm0 \n" \
"lea 0x10(%[uv_buf]),%[uv_buf] \n" \
"vpermq $0xd8,%%ymm0,%%ymm0 \n" \
"vpunpcklwd %%ymm0,%%ymm0,%%ymm0 \n" \
"vmovdqu (%[y_buf]),%%xmm4 \n" \
"vpermq $0xd8,%%ymm4,%%ymm4 \n" \
"vpunpcklbw %%ymm4,%%ymm4,%%ymm4 \n" \
"lea 0x10(%[y_buf]),%[y_buf] \n"
// Read 8 VU from NV21, upsample to 16 UV.
#define READNV21_AVX2 \
"vmovdqu (%[vu_buf]),%%xmm0 \n" \
"lea 0x10(%[vu_buf]),%[vu_buf] \n" \
"vpermq $0xd8,%%ymm0,%%ymm0 \n" \
"vpshufb %[kShuffleNV21], %%ymm0, %%ymm0 \n" \
"vmovdqu (%[y_buf]),%%xmm4 \n" \
"vpermq $0xd8,%%ymm4,%%ymm4 \n" \
"vpunpcklbw %%ymm4,%%ymm4,%%ymm4 \n" \
"lea 0x10(%[y_buf]),%[y_buf] \n"
// Read 8 YUY2 with 16 Y and upsample 8 UV to 16 UV.
#define READYUY2_AVX2 \
"vmovdqu (%[yuy2_buf]),%%ymm4 \n" \
"vpshufb %[kShuffleYUY2Y], %%ymm4, %%ymm4 \n" \
"vmovdqu (%[yuy2_buf]),%%ymm0 \n" \
"vpshufb %[kShuffleYUY2UV], %%ymm0, %%ymm0 \n" \
"lea 0x20(%[yuy2_buf]),%[yuy2_buf] \n"
// Read 8 UYVY with 16 Y and upsample 8 UV to 16 UV.
#define READUYVY_AVX2 \
"vmovdqu (%[uyvy_buf]),%%ymm4 \n" \
"vpshufb %[kShuffleUYVYY], %%ymm4, %%ymm4 \n" \
"vmovdqu (%[uyvy_buf]),%%ymm0 \n" \
"vpshufb %[kShuffleUYVYUV], %%ymm0, %%ymm0 \n" \
"lea 0x20(%[uyvy_buf]),%[uyvy_buf] \n"
#if defined(__x86_64__)
#define YUVTORGB_SETUP_AVX2(yuvconstants) \
"vmovdqa (%[yuvconstants]),%%ymm8 \n" \
"vmovdqa 32(%[yuvconstants]),%%ymm9 \n" \
"vmovdqa 64(%[yuvconstants]),%%ymm10 \n" \
"vmovdqa 96(%[yuvconstants]),%%ymm11 \n" \
"vmovdqa 128(%[yuvconstants]),%%ymm12 \n" \
"vmovdqa 160(%[yuvconstants]),%%ymm13 \n" \
"vmovdqa 192(%[yuvconstants]),%%ymm14 \n"
#define YUVTORGB16_AVX2(yuvconstants) \
"vpmaddubsw %%ymm10,%%ymm0,%%ymm2 \n" \
"vpmaddubsw %%ymm9,%%ymm0,%%ymm1 \n" \
"vpmaddubsw %%ymm8,%%ymm0,%%ymm0 \n" \
"vpsubw %%ymm2,%%ymm13,%%ymm2 \n" \
"vpsubw %%ymm1,%%ymm12,%%ymm1 \n" \
"vpsubw %%ymm0,%%ymm11,%%ymm0 \n" \
"vpmulhuw %%ymm14,%%ymm4,%%ymm4 \n" \
"vpaddsw %%ymm4,%%ymm0,%%ymm0 \n" \
"vpaddsw %%ymm4,%%ymm1,%%ymm1 \n" \
"vpaddsw %%ymm4,%%ymm2,%%ymm2 \n"
#define YUVTORGB_REGS_AVX2 \
"xmm8", "xmm9", "xmm10", "xmm11", "xmm12", "xmm13", "xmm14",
#else // Convert 16 pixels: 16 UV and 16 Y.
#define YUVTORGB_SETUP_AVX2(yuvconstants)
#define YUVTORGB16_AVX2(yuvconstants) \
"vpmaddubsw 64(%[yuvconstants]),%%ymm0,%%ymm2 \n" \
"vpmaddubsw 32(%[yuvconstants]),%%ymm0,%%ymm1 \n" \
"vpmaddubsw (%[yuvconstants]),%%ymm0,%%ymm0 \n" \
"vmovdqu 160(%[yuvconstants]),%%ymm3 \n" \
"vpsubw %%ymm2,%%ymm3,%%ymm2 \n" \
"vmovdqu 128(%[yuvconstants]),%%ymm3 \n" \
"vpsubw %%ymm1,%%ymm3,%%ymm1 \n" \
"vmovdqu 96(%[yuvconstants]),%%ymm3 \n" \
"vpsubw %%ymm0,%%ymm3,%%ymm0 \n" \
"vpmulhuw 192(%[yuvconstants]),%%ymm4,%%ymm4 \n" \
"vpaddsw %%ymm4,%%ymm0,%%ymm0 \n" \
"vpaddsw %%ymm4,%%ymm1,%%ymm1 \n" \
"vpaddsw %%ymm4,%%ymm2,%%ymm2 \n"
#define YUVTORGB_REGS_AVX2
#endif
#define YUVTORGB_AVX2(yuvconstants) \
YUVTORGB16_AVX2(yuvconstants) \
"vpsraw $0x6,%%ymm0,%%ymm0 \n" \
"vpsraw $0x6,%%ymm1,%%ymm1 \n" \
"vpsraw $0x6,%%ymm2,%%ymm2 \n" \
"vpackuswb %%ymm0,%%ymm0,%%ymm0 \n" \
"vpackuswb %%ymm1,%%ymm1,%%ymm1 \n" \
"vpackuswb %%ymm2,%%ymm2,%%ymm2 \n"
// Store 16 ARGB values.
#define STOREARGB_AVX2 \
"vpunpcklbw %%ymm1,%%ymm0,%%ymm0 \n" \
"vpermq $0xd8,%%ymm0,%%ymm0 \n" \
"vpunpcklbw %%ymm5,%%ymm2,%%ymm2 \n" \
"vpermq $0xd8,%%ymm2,%%ymm2 \n" \
"vpunpcklwd %%ymm2,%%ymm0,%%ymm1 \n" \
"vpunpckhwd %%ymm2,%%ymm0,%%ymm0 \n" \
"vmovdqu %%ymm1,(%[dst_argb]) \n" \
"vmovdqu %%ymm0,0x20(%[dst_argb]) \n" \
"lea 0x40(%[dst_argb]), %[dst_argb] \n"
// Store 16 AR30 values.
#define STOREAR30_AVX2 \
"vpsraw $0x4,%%ymm0,%%ymm0 \n" \
"vpsraw $0x4,%%ymm1,%%ymm1 \n" \
"vpsraw $0x4,%%ymm2,%%ymm2 \n" \
"vpminsw %%ymm7,%%ymm0,%%ymm0 \n" \
"vpminsw %%ymm7,%%ymm1,%%ymm1 \n" \
"vpminsw %%ymm7,%%ymm2,%%ymm2 \n" \
"vpmaxsw %%ymm6,%%ymm0,%%ymm0 \n" \
"vpmaxsw %%ymm6,%%ymm1,%%ymm1 \n" \
"vpmaxsw %%ymm6,%%ymm2,%%ymm2 \n" \
"vpsllw $0x4,%%ymm2,%%ymm2 \n" \
"vpermq $0xd8,%%ymm0,%%ymm0 \n" \
"vpermq $0xd8,%%ymm1,%%ymm1 \n" \
"vpermq $0xd8,%%ymm2,%%ymm2 \n" \
"vpunpckhwd %%ymm2,%%ymm0,%%ymm3 \n" \
"vpunpcklwd %%ymm2,%%ymm0,%%ymm0 \n" \
"vpunpckhwd %%ymm5,%%ymm1,%%ymm2 \n" \
"vpunpcklwd %%ymm5,%%ymm1,%%ymm1 \n" \
"vpslld $0xa,%%ymm1,%%ymm1 \n" \
"vpslld $0xa,%%ymm2,%%ymm2 \n" \
"vpor %%ymm1,%%ymm0,%%ymm0 \n" \
"vpor %%ymm2,%%ymm3,%%ymm3 \n" \
"vmovdqu %%ymm0,(%[dst_ar30]) \n" \
"vmovdqu %%ymm3,0x20(%[dst_ar30]) \n" \
"lea 0x40(%[dst_ar30]), %[dst_ar30] \n"
#ifdef HAS_I444TOARGBROW_AVX2
// 16 pixels
// 16 UV values with 16 Y producing 16 ARGB (64 bytes).
void OMITFP I444ToARGBRow_AVX2(const uint8_t* y_buf,
const uint8_t* u_buf,
const uint8_t* v_buf,
uint8_t* dst_argb,
const struct YuvConstants* yuvconstants,
int width) {
asm volatile (
YUVTORGB_SETUP_AVX2(yuvconstants)
"sub %[u_buf],%[v_buf] \n"
"vpcmpeqb %%ymm5,%%ymm5,%%ymm5 \n"
LABELALIGN
"1: \n"
READYUV444_AVX2
YUVTORGB_AVX2(yuvconstants)
STOREARGB_AVX2
"sub $0x10,%[width] \n"
"jg 1b \n"
"vzeroupper \n"
: [y_buf]"+r"(y_buf), // %[y_buf]
[u_buf]"+r"(u_buf), // %[u_buf]
[v_buf]"+r"(v_buf), // %[v_buf]
[dst_argb]"+r"(dst_argb), // %[dst_argb]
[width]"+rm"(width) // %[width]
: [yuvconstants]"r"(yuvconstants) // %[yuvconstants]
: "memory", "cc", YUVTORGB_REGS_AVX2
"xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5"
);
}
#endif // HAS_I444TOARGBROW_AVX2
#if defined(HAS_I422TOARGBROW_AVX2)
// 16 pixels
// 8 UV values upsampled to 16 UV, mixed with 16 Y producing 16 ARGB (64 bytes).
void OMITFP I422ToARGBRow_AVX2(const uint8_t* y_buf,
const uint8_t* u_buf,
const uint8_t* v_buf,
uint8_t* dst_argb,
const struct YuvConstants* yuvconstants,
int width) {
asm volatile (
YUVTORGB_SETUP_AVX2(yuvconstants)
"sub %[u_buf],%[v_buf] \n"
"vpcmpeqb %%ymm5,%%ymm5,%%ymm5 \n"
LABELALIGN
"1: \n"
READYUV422_AVX2
YUVTORGB_AVX2(yuvconstants)
STOREARGB_AVX2
"sub $0x10,%[width] \n"
"jg 1b \n"
"vzeroupper \n"
: [y_buf]"+r"(y_buf), // %[y_buf]
[u_buf]"+r"(u_buf), // %[u_buf]
[v_buf]"+r"(v_buf), // %[v_buf]
[dst_argb]"+r"(dst_argb), // %[dst_argb]
[width]"+rm"(width) // %[width]
: [yuvconstants]"r"(yuvconstants) // %[yuvconstants]
: "memory", "cc", YUVTORGB_REGS_AVX2
"xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5"
);
}
#endif // HAS_I422TOARGBROW_AVX2
#if defined(HAS_I422TOAR30ROW_AVX2)
// 16 pixels
// 8 UV values upsampled to 16 UV, mixed with 16 Y producing 16 AR30 (64 bytes).
void OMITFP I422ToAR30Row_AVX2(const uint8_t* y_buf,
const uint8_t* u_buf,
const uint8_t* v_buf,
uint8_t* dst_ar30,
const struct YuvConstants* yuvconstants,
int width) {
asm volatile (
YUVTORGB_SETUP_AVX2(yuvconstants)
"sub %[u_buf],%[v_buf] \n"
"vpcmpeqb %%ymm5,%%ymm5,%%ymm5 \n" // AR30 constants
"vpsrlw $14,%%ymm5,%%ymm5 \n"
"vpsllw $4,%%ymm5,%%ymm5 \n" // 2 alpha bits
"vpxor %%ymm6,%%ymm6,%%ymm6 \n" // 0 for min
"vpcmpeqb %%ymm7,%%ymm7,%%ymm7 \n" // 1023 for max
"vpsrlw $6,%%ymm7,%%ymm7 \n"
LABELALIGN
"1: \n"
READYUV422_AVX2
YUVTORGB16_AVX2(yuvconstants)
STOREAR30_AVX2
"sub $0x10,%[width] \n"
"jg 1b \n"
"vzeroupper \n"
: [y_buf]"+r"(y_buf), // %[y_buf]
[u_buf]"+r"(u_buf), // %[u_buf]
[v_buf]"+r"(v_buf), // %[v_buf]
[dst_ar30]"+r"(dst_ar30), // %[dst_ar30]
[width]"+rm"(width) // %[width]
: [yuvconstants]"r"(yuvconstants) // %[yuvconstants]
: "memory", "cc", YUVTORGB_REGS_AVX2
"xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6", "xmm7"
);
}
#endif // HAS_I422TOAR30ROW_AVX2
#if defined(HAS_I210TOARGBROW_AVX2)
// 16 pixels
// 8 UV values upsampled to 16 UV, mixed with 16 Y producing 16 ARGB (64 bytes).
void OMITFP I210ToARGBRow_AVX2(const uint16_t* y_buf,
const uint16_t* u_buf,
const uint16_t* v_buf,
uint8_t* dst_argb,
const struct YuvConstants* yuvconstants,
int width) {
asm volatile (
YUVTORGB_SETUP_AVX2(yuvconstants)
"sub %[u_buf],%[v_buf] \n"
"vpcmpeqb %%ymm5,%%ymm5,%%ymm5 \n"
LABELALIGN
"1: \n"
READYUV210_AVX2
YUVTORGB_AVX2(yuvconstants)
STOREARGB_AVX2
"sub $0x10,%[width] \n"
"jg 1b \n"
"vzeroupper \n"
: [y_buf]"+r"(y_buf), // %[y_buf]
[u_buf]"+r"(u_buf), // %[u_buf]
[v_buf]"+r"(v_buf), // %[v_buf]
[dst_argb]"+r"(dst_argb), // %[dst_argb]
[width]"+rm"(width) // %[width]
: [yuvconstants]"r"(yuvconstants) // %[yuvconstants]
: "memory", "cc", YUVTORGB_REGS_AVX2
"xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5"
);
}
#endif // HAS_I210TOARGBROW_AVX2
#if defined(HAS_I210TOAR30ROW_AVX2)
// 16 pixels
// 8 UV values upsampled to 16 UV, mixed with 16 Y producing 16 AR30 (64 bytes).
void OMITFP I210ToAR30Row_AVX2(const uint16_t* y_buf,
const uint16_t* u_buf,
const uint16_t* v_buf,
uint8_t* dst_ar30,
const struct YuvConstants* yuvconstants,
int width) {
asm volatile (
YUVTORGB_SETUP_AVX2(yuvconstants)
"sub %[u_buf],%[v_buf] \n"
"vpcmpeqb %%ymm5,%%ymm5,%%ymm5 \n" // AR30 constants
"vpsrlw $14,%%ymm5,%%ymm5 \n"
"vpsllw $4,%%ymm5,%%ymm5 \n" // 2 alpha bits
"vpxor %%ymm6,%%ymm6,%%ymm6 \n" // 0 for min
"vpcmpeqb %%ymm7,%%ymm7,%%ymm7 \n" // 1023 for max
"vpsrlw $6,%%ymm7,%%ymm7 \n"
LABELALIGN
"1: \n"
READYUV210_AVX2
YUVTORGB16_AVX2(yuvconstants)
STOREAR30_AVX2
"sub $0x10,%[width] \n"
"jg 1b \n"
"vzeroupper \n"
: [y_buf]"+r"(y_buf), // %[y_buf]
[u_buf]"+r"(u_buf), // %[u_buf]
[v_buf]"+r"(v_buf), // %[v_buf]
[dst_ar30]"+r"(dst_ar30), // %[dst_ar30]
[width]"+rm"(width) // %[width]
: [yuvconstants]"r"(yuvconstants) // %[yuvconstants]
: "memory", "cc", YUVTORGB_REGS_AVX2
"xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5"
);
}
#endif // HAS_I210TOAR30ROW_AVX2
#if defined(HAS_I422ALPHATOARGBROW_AVX2)
// 16 pixels
// 8 UV values upsampled to 16 UV, mixed with 16 Y and 16 A producing 16 ARGB.
void OMITFP I422AlphaToARGBRow_AVX2(const uint8_t* y_buf,
const uint8_t* u_buf,
const uint8_t* v_buf,
const uint8_t* a_buf,
uint8_t* dst_argb,
const struct YuvConstants* yuvconstants,
int width) {
// clang-format off
asm volatile (
YUVTORGB_SETUP_AVX2(yuvconstants)
"sub %[u_buf],%[v_buf] \n"
LABELALIGN
"1: \n"
READYUVA422_AVX2
YUVTORGB_AVX2(yuvconstants)
STOREARGB_AVX2
"subl $0x10,%[width] \n"
"jg 1b \n"
"vzeroupper \n"
: [y_buf]"+r"(y_buf), // %[y_buf]
[u_buf]"+r"(u_buf), // %[u_buf]
[v_buf]"+r"(v_buf), // %[v_buf]
[a_buf]"+r"(a_buf), // %[a_buf]
[dst_argb]"+r"(dst_argb), // %[dst_argb]
#if defined(__i386__)
[width]"+m"(width) // %[width]
#else
[width]"+rm"(width) // %[width]
#endif
: [yuvconstants]"r"(yuvconstants) // %[yuvconstants]
: "memory", "cc", YUVTORGB_REGS_AVX2
"xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5"
);
// clang-format on
}
#endif // HAS_I422ALPHATOARGBROW_AVX2
#if defined(HAS_I422TORGBAROW_AVX2)
// 16 pixels
// 8 UV values upsampled to 16 UV, mixed with 16 Y producing 16 RGBA (64 bytes).
void OMITFP I422ToRGBARow_AVX2(const uint8_t* y_buf,
const uint8_t* u_buf,
const uint8_t* v_buf,
uint8_t* dst_argb,
const struct YuvConstants* yuvconstants,
int width) {
asm volatile (
YUVTORGB_SETUP_AVX2(yuvconstants)
"sub %[u_buf],%[v_buf] \n"
"vpcmpeqb %%ymm5,%%ymm5,%%ymm5 \n"
LABELALIGN
"1: \n"
READYUV422_AVX2
YUVTORGB_AVX2(yuvconstants)
// Step 3: Weave into RGBA
"vpunpcklbw %%ymm2,%%ymm1,%%ymm1 \n"
"vpermq $0xd8,%%ymm1,%%ymm1 \n"
"vpunpcklbw %%ymm0,%%ymm5,%%ymm2 \n"
"vpermq $0xd8,%%ymm2,%%ymm2 \n"
"vpunpcklwd %%ymm1,%%ymm2,%%ymm0 \n"
"vpunpckhwd %%ymm1,%%ymm2,%%ymm1 \n"
"vmovdqu %%ymm0,(%[dst_argb]) \n"
"vmovdqu %%ymm1,0x20(%[dst_argb]) \n"
"lea 0x40(%[dst_argb]),%[dst_argb] \n"
"sub $0x10,%[width] \n"
"jg 1b \n"
"vzeroupper \n"
: [y_buf]"+r"(y_buf), // %[y_buf]
[u_buf]"+r"(u_buf), // %[u_buf]
[v_buf]"+r"(v_buf), // %[v_buf]
[dst_argb]"+r"(dst_argb), // %[dst_argb]
[width]"+rm"(width) // %[width]
: [yuvconstants]"r"(yuvconstants) // %[yuvconstants]
: "memory", "cc", YUVTORGB_REGS_AVX2
"xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5"
);
}
#endif // HAS_I422TORGBAROW_AVX2
#if defined(HAS_NV12TOARGBROW_AVX2)
// 16 pixels.
// 8 UV values upsampled to 16 UV, mixed with 16 Y producing 16 ARGB (64 bytes).
void OMITFP NV12ToARGBRow_AVX2(const uint8_t* y_buf,
const uint8_t* uv_buf,
uint8_t* dst_argb,
const struct YuvConstants* yuvconstants,
int width) {
// clang-format off
asm volatile (
YUVTORGB_SETUP_AVX2(yuvconstants)
"vpcmpeqb %%ymm5,%%ymm5,%%ymm5 \n"
LABELALIGN
"1: \n"
READNV12_AVX2
YUVTORGB_AVX2(yuvconstants)
STOREARGB_AVX2
"sub $0x10,%[width] \n"
"jg 1b \n"
"vzeroupper \n"
: [y_buf]"+r"(y_buf), // %[y_buf]
[uv_buf]"+r"(uv_buf), // %[uv_buf]
[dst_argb]"+r"(dst_argb), // %[dst_argb]
[width]"+rm"(width) // %[width]
: [yuvconstants]"r"(yuvconstants) // %[yuvconstants]
: "memory", "cc", YUVTORGB_REGS_AVX2
"xmm0", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5"
);
// clang-format on
}
#endif // HAS_NV12TOARGBROW_AVX2
#if defined(HAS_NV21TOARGBROW_AVX2)
// 16 pixels.
// 8 VU values upsampled to 16 UV, mixed with 16 Y producing 16 ARGB (64 bytes).
void OMITFP NV21ToARGBRow_AVX2(const uint8_t* y_buf,
const uint8_t* vu_buf,
uint8_t* dst_argb,
const struct YuvConstants* yuvconstants,
int width) {
// clang-format off
asm volatile (
YUVTORGB_SETUP_AVX2(yuvconstants)
"vpcmpeqb %%ymm5,%%ymm5,%%ymm5 \n"
LABELALIGN
"1: \n"
READNV21_AVX2
YUVTORGB_AVX2(yuvconstants)
STOREARGB_AVX2
"sub $0x10,%[width] \n"
"jg 1b \n"
"vzeroupper \n"
: [y_buf]"+r"(y_buf), // %[y_buf]
[vu_buf]"+r"(vu_buf), // %[vu_buf]
[dst_argb]"+r"(dst_argb), // %[dst_argb]
[width]"+rm"(width) // %[width]
: [yuvconstants]"r"(yuvconstants), // %[yuvconstants]
[kShuffleNV21]"m"(kShuffleNV21)
: "memory", "cc", YUVTORGB_REGS_AVX2
"xmm0", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5"
);
// clang-format on
}
#endif // HAS_NV21TOARGBROW_AVX2
#if defined(HAS_YUY2TOARGBROW_AVX2)
// 16 pixels.
// 8 YUY2 values with 16 Y and 8 UV producing 16 ARGB (64 bytes).
void OMITFP YUY2ToARGBRow_AVX2(const uint8_t* yuy2_buf,
uint8_t* dst_argb,
const struct YuvConstants* yuvconstants,
int width) {
// clang-format off
asm volatile (
YUVTORGB_SETUP_AVX2(yuvconstants)
"vpcmpeqb %%ymm5,%%ymm5,%%ymm5 \n"
LABELALIGN
"1: \n"
READYUY2_AVX2
YUVTORGB_AVX2(yuvconstants)
STOREARGB_AVX2
"sub $0x10,%[width] \n"
"jg 1b \n"
"vzeroupper \n"
: [yuy2_buf]"+r"(yuy2_buf), // %[yuy2_buf]
[dst_argb]"+r"(dst_argb), // %[dst_argb]
[width]"+rm"(width) // %[width]
: [yuvconstants]"r"(yuvconstants), // %[yuvconstants]
[kShuffleYUY2Y]"m"(kShuffleYUY2Y),
[kShuffleYUY2UV]"m"(kShuffleYUY2UV)
: "memory", "cc", YUVTORGB_REGS_AVX2
"xmm0", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5"
);
// clang-format on
}
#endif // HAS_YUY2TOARGBROW_AVX2
#if defined(HAS_UYVYTOARGBROW_AVX2)
// 16 pixels.
// 8 UYVY values with 16 Y and 8 UV producing 16 ARGB (64 bytes).
void OMITFP UYVYToARGBRow_AVX2(const uint8_t* uyvy_buf,
uint8_t* dst_argb,
const struct YuvConstants* yuvconstants,
int width) {
// clang-format off
asm volatile (
YUVTORGB_SETUP_AVX2(yuvconstants)
"vpcmpeqb %%ymm5,%%ymm5,%%ymm5 \n"
LABELALIGN
"1: \n"
READUYVY_AVX2
YUVTORGB_AVX2(yuvconstants)
STOREARGB_AVX2
"sub $0x10,%[width] \n"
"jg 1b \n"
"vzeroupper \n"
: [uyvy_buf]"+r"(uyvy_buf), // %[uyvy_buf]
[dst_argb]"+r"(dst_argb), // %[dst_argb]
[width]"+rm"(width) // %[width]
: [yuvconstants]"r"(yuvconstants), // %[yuvconstants]
[kShuffleUYVYY]"m"(kShuffleUYVYY),
[kShuffleUYVYUV]"m"(kShuffleUYVYUV)
: "memory", "cc", YUVTORGB_REGS_AVX2
"xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5"
);
// clang-format on
}
#endif // HAS_UYVYTOARGBROW_AVX2
#ifdef HAS_I400TOARGBROW_SSE2
void I400ToARGBRow_SSE2(const uint8_t* y_buf,
uint8_t* dst_argb,
const struct YuvConstants* yuvconstants,
int width) {
asm volatile(
"movdqa 192(%3),%%xmm2 \n" // yg = 18997 = 1.164
"movdqa 224(%3),%%xmm3 \n" // ygb = 1160 = 1.164 * 16
"pcmpeqb %%xmm4,%%xmm4 \n" // 0xff000000
"pslld $0x18,%%xmm4 \n"
LABELALIGN
"1: \n"
// Step 1: Scale Y contribution to 8 G values. G = (y - 16) * 1.164
"movq (%0),%%xmm0 \n"
"lea 0x8(%0),%0 \n"
"punpcklbw %%xmm0,%%xmm0 \n"
"pmulhuw %%xmm2,%%xmm0 \n"
"paddsw %%xmm3,%%xmm0 \n"
"psraw $6, %%xmm0 \n"
"packuswb %%xmm0,%%xmm0 \n"
// Step 2: Weave into ARGB
"punpcklbw %%xmm0,%%xmm0 \n"
"movdqa %%xmm0,%%xmm1 \n"
"punpcklwd %%xmm0,%%xmm0 \n"
"punpckhwd %%xmm1,%%xmm1 \n"
"por %%xmm4,%%xmm0 \n"
"por %%xmm4,%%xmm1 \n"
"movdqu %%xmm0,(%1) \n"
"movdqu %%xmm1,0x10(%1) \n"
"lea 0x20(%1),%1 \n"
"sub $0x8,%2 \n"
"jg 1b \n"
: "+r"(y_buf), // %0
"+r"(dst_argb), // %1
"+rm"(width) // %2
: "r"(yuvconstants) // %3
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4");
}
#endif // HAS_I400TOARGBROW_SSE2
#ifdef HAS_I400TOARGBROW_AVX2
// 16 pixels of Y converted to 16 pixels of ARGB (64 bytes).
// note: vpunpcklbw mutates and vpackuswb unmutates.
void I400ToARGBRow_AVX2(const uint8_t* y_buf,
uint8_t* dst_argb,
const struct YuvConstants* yuvconstants,
int width) {
asm volatile(
"vmovdqa 192(%3),%%ymm2 \n" // yg = 18997 = 1.164
"vmovdqa 224(%3),%%ymm3 \n" // ygb = -1160 = 1.164*16
"vpcmpeqb %%ymm4,%%ymm4,%%ymm4 \n" // 0xff000000
"vpslld $0x18,%%ymm4,%%ymm4 \n"
LABELALIGN
"1: \n"
// Step 1: Scale Y contribution to 16 G values. G = (y - 16) * 1.164
"vmovdqu (%0),%%xmm0 \n"
"lea 0x10(%0),%0 \n"
"vpermq $0xd8,%%ymm0,%%ymm0 \n"
"vpunpcklbw %%ymm0,%%ymm0,%%ymm0 \n"
"vpmulhuw %%ymm2,%%ymm0,%%ymm0 \n"
"vpaddsw %%ymm3,%%ymm0,%%ymm0 \n"
"vpsraw $0x6,%%ymm0,%%ymm0 \n"
"vpackuswb %%ymm0,%%ymm0,%%ymm0 \n"
"vpunpcklbw %%ymm0,%%ymm0,%%ymm1 \n"
"vpermq $0xd8,%%ymm1,%%ymm1 \n"
"vpunpcklwd %%ymm1,%%ymm1,%%ymm0 \n"
"vpunpckhwd %%ymm1,%%ymm1,%%ymm1 \n"
"vpor %%ymm4,%%ymm0,%%ymm0 \n"
"vpor %%ymm4,%%ymm1,%%ymm1 \n"
"vmovdqu %%ymm0,(%1) \n"
"vmovdqu %%ymm1,0x20(%1) \n"
"lea 0x40(%1),%1 \n"
"sub $0x10,%2 \n"
"jg 1b \n"
"vzeroupper \n"
: "+r"(y_buf), // %0
"+r"(dst_argb), // %1
"+rm"(width) // %2
: "r"(yuvconstants) // %3
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4");
}
#endif // HAS_I400TOARGBROW_AVX2
#ifdef HAS_MIRRORROW_SSSE3
// Shuffle table for reversing the bytes.
static const uvec8 kShuffleMirror = {15u, 14u, 13u, 12u, 11u, 10u, 9u, 8u,
7u, 6u, 5u, 4u, 3u, 2u, 1u, 0u};
void MirrorRow_SSSE3(const uint8_t* src, uint8_t* dst, int width) {
intptr_t temp_width = (intptr_t)(width);
asm volatile(
"movdqa %3,%%xmm5 \n"
LABELALIGN
"1: \n"
"movdqu -0x10(%0,%2,1),%%xmm0 \n"
"pshufb %%xmm5,%%xmm0 \n"
"movdqu %%xmm0,(%1) \n"
"lea 0x10(%1),%1 \n"
"sub $0x10,%2 \n"
"jg 1b \n"
: "+r"(src), // %0
"+r"(dst), // %1
"+r"(temp_width) // %2
: "m"(kShuffleMirror) // %3
: "memory", "cc", "xmm0", "xmm5");
}
#endif // HAS_MIRRORROW_SSSE3
#ifdef HAS_MIRRORROW_AVX2
void MirrorRow_AVX2(const uint8_t* src, uint8_t* dst, int width) {
intptr_t temp_width = (intptr_t)(width);
asm volatile(
"vbroadcastf128 %3,%%ymm5 \n"
LABELALIGN
"1: \n"
"vmovdqu -0x20(%0,%2,1),%%ymm0 \n"
"vpshufb %%ymm5,%%ymm0,%%ymm0 \n"
"vpermq $0x4e,%%ymm0,%%ymm0 \n"
"vmovdqu %%ymm0,(%1) \n"
"lea 0x20(%1),%1 \n"
"sub $0x20,%2 \n"
"jg 1b \n"
"vzeroupper \n"
: "+r"(src), // %0
"+r"(dst), // %1
"+r"(temp_width) // %2
: "m"(kShuffleMirror) // %3
: "memory", "cc", "xmm0", "xmm5");
}
#endif // HAS_MIRRORROW_AVX2
#ifdef HAS_MIRRORUVROW_SSSE3
// Shuffle table for reversing the UV.
static const uvec8 kShuffleMirrorUV = {14u, 15u, 12u, 13u, 10u, 11u, 8u, 9u,
6u, 7u, 4u, 5u, 2u, 3u, 0u, 1u};
void MirrorUVRow_SSSE3(const uint8_t* src_uv, uint8_t* dst_uv, int width) {
intptr_t temp_width = (intptr_t)(width);
asm volatile(
"movdqa %3,%%xmm5 \n"
LABELALIGN
"1: \n"
"movdqu -0x10(%0,%2,2),%%xmm0 \n"
"pshufb %%xmm5,%%xmm0 \n"
"movdqu %%xmm0,(%1) \n"
"lea 0x10(%1),%1 \n"
"sub $0x8,%2 \n"
"jg 1b \n"
: "+r"(src_uv), // %0
"+r"(dst_uv), // %1
"+r"(temp_width) // %2
: "m"(kShuffleMirrorUV) // %3
: "memory", "cc", "xmm0", "xmm5");
}
#endif // HAS_MIRRORUVROW_SSSE3
#ifdef HAS_MIRRORUVROW_AVX2
void MirrorUVRow_AVX2(const uint8_t* src_uv, uint8_t* dst_uv, int width) {
intptr_t temp_width = (intptr_t)(width);
asm volatile(
"vbroadcastf128 %3,%%ymm5 \n"
LABELALIGN
"1: \n"
"vmovdqu -0x20(%0,%2,2),%%ymm0 \n"
"vpshufb %%ymm5,%%ymm0,%%ymm0 \n"
"vpermq $0x4e,%%ymm0,%%ymm0 \n"
"vmovdqu %%ymm0,(%1) \n"
"lea 0x20(%1),%1 \n"
"sub $0x10,%2 \n"
"jg 1b \n"
"vzeroupper \n"
: "+r"(src_uv), // %0
"+r"(dst_uv), // %1
"+r"(temp_width) // %2
: "m"(kShuffleMirrorUV) // %3
: "memory", "cc", "xmm0", "xmm5");
}
#endif // HAS_MIRRORUVROW_AVX2
#ifdef HAS_MIRRORSPLITUVROW_SSSE3
// Shuffle table for reversing the bytes of UV channels.
static const uvec8 kShuffleMirrorSplitUV = {14u, 12u, 10u, 8u, 6u, 4u, 2u, 0u,
15u, 13u, 11u, 9u, 7u, 5u, 3u, 1u};
void MirrorSplitUVRow_SSSE3(const uint8_t* src,
uint8_t* dst_u,
uint8_t* dst_v,
int width) {
intptr_t temp_width = (intptr_t)(width);
asm volatile(
"movdqa %4,%%xmm1 \n"
"lea -0x10(%0,%3,2),%0 \n"
"sub %1,%2 \n"
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"lea -0x10(%0),%0 \n"
"pshufb %%xmm1,%%xmm0 \n"
"movlpd %%xmm0,(%1) \n"
"movhpd %%xmm0,0x00(%1,%2,1) \n"
"lea 0x8(%1),%1 \n"
"sub $8,%3 \n"
"jg 1b \n"
: "+r"(src), // %0
"+r"(dst_u), // %1
"+r"(dst_v), // %2
"+r"(temp_width) // %3
: "m"(kShuffleMirrorSplitUV) // %4
: "memory", "cc", "xmm0", "xmm1");
}
#endif // HAS_MIRRORSPLITUVROW_SSSE3
#ifdef HAS_RGB24MIRRORROW_SSSE3
// Shuffle first 5 pixels to last 5 mirrored. first byte zero
static const uvec8 kShuffleMirrorRGB0 = {128u, 12u, 13u, 14u, 9u, 10u, 11u, 6u,
7u, 8u, 3u, 4u, 5u, 0u, 1u, 2u};
// Shuffle last 5 pixels to first 5 mirrored. last byte zero
static const uvec8 kShuffleMirrorRGB1 = {
13u, 14u, 15u, 10u, 11u, 12u, 7u, 8u, 9u, 4u, 5u, 6u, 1u, 2u, 3u, 128u};
// Shuffle 5 pixels at a time (15 bytes)
void RGB24MirrorRow_SSSE3(const uint8_t* src_rgb24,
uint8_t* dst_rgb24,
int width) {
intptr_t temp_width = (intptr_t)(width);
src_rgb24 += width * 3 - 48;
asm volatile(
"movdqa %3,%%xmm4 \n"
"movdqa %4,%%xmm5 \n"
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n" // first 5
"movdqu 15(%0),%%xmm1 \n" // next 5
"movdqu 30(%0),%%xmm2 \n" // next 5
"movdqu 32(%0),%%xmm3 \n" // last 1 special
"pshufb %%xmm4,%%xmm0 \n"
"pshufb %%xmm4,%%xmm1 \n"
"pshufb %%xmm4,%%xmm2 \n"
"pshufb %%xmm5,%%xmm3 \n"
"lea -0x30(%0),%0 \n"
"movdqu %%xmm0,32(%1) \n" // last 5
"movdqu %%xmm1,17(%1) \n" // next 5
"movdqu %%xmm2,2(%1) \n" // next 5
"movlpd %%xmm3,0(%1) \n" // first 1
"lea 0x30(%1),%1 \n"
"sub $0x10,%2 \n"
"jg 1b \n"
: "+r"(src_rgb24), // %0
"+r"(dst_rgb24), // %1
"+r"(temp_width) // %2
: "m"(kShuffleMirrorRGB0), // %3
"m"(kShuffleMirrorRGB1) // %4
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5");
}
#endif // HAS_RGB24MIRRORROW_SSSE3
#ifdef HAS_ARGBMIRRORROW_SSE2
void ARGBMirrorRow_SSE2(const uint8_t* src, uint8_t* dst, int width) {
intptr_t temp_width = (intptr_t)(width);
asm volatile(
"lea -0x10(%0,%2,4),%0 \n"
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"pshufd $0x1b,%%xmm0,%%xmm0 \n"
"lea -0x10(%0),%0 \n"
"movdqu %%xmm0,(%1) \n"
"lea 0x10(%1),%1 \n"
"sub $0x4,%2 \n"
"jg 1b \n"
: "+r"(src), // %0
"+r"(dst), // %1
"+r"(temp_width) // %2
:
: "memory", "cc", "xmm0");
}
#endif // HAS_ARGBMIRRORROW_SSE2
#ifdef HAS_ARGBMIRRORROW_AVX2
// Shuffle table for reversing the bytes.
static const ulvec32 kARGBShuffleMirror_AVX2 = {7u, 6u, 5u, 4u, 3u, 2u, 1u, 0u};
void ARGBMirrorRow_AVX2(const uint8_t* src, uint8_t* dst, int width) {
intptr_t temp_width = (intptr_t)(width);
asm volatile(
"vmovdqu %3,%%ymm5 \n"
LABELALIGN
"1: \n"
"vpermd -0x20(%0,%2,4),%%ymm5,%%ymm0 \n"
"vmovdqu %%ymm0,(%1) \n"
"lea 0x20(%1),%1 \n"
"sub $0x8,%2 \n"
"jg 1b \n"
"vzeroupper \n"
: "+r"(src), // %0
"+r"(dst), // %1
"+r"(temp_width) // %2
: "m"(kARGBShuffleMirror_AVX2) // %3
: "memory", "cc", "xmm0", "xmm5");
}
#endif // HAS_ARGBMIRRORROW_AVX2
#ifdef HAS_SPLITUVROW_AVX2
void SplitUVRow_AVX2(const uint8_t* src_uv,
uint8_t* dst_u,
uint8_t* dst_v,
int width) {
asm volatile(
"vpcmpeqb %%ymm5,%%ymm5,%%ymm5 \n"
"vpsrlw $0x8,%%ymm5,%%ymm5 \n"
"sub %1,%2 \n"
LABELALIGN
"1: \n"
"vmovdqu (%0),%%ymm0 \n"
"vmovdqu 0x20(%0),%%ymm1 \n"
"lea 0x40(%0),%0 \n"
"vpsrlw $0x8,%%ymm0,%%ymm2 \n"
"vpsrlw $0x8,%%ymm1,%%ymm3 \n"
"vpand %%ymm5,%%ymm0,%%ymm0 \n"
"vpand %%ymm5,%%ymm1,%%ymm1 \n"
"vpackuswb %%ymm1,%%ymm0,%%ymm0 \n"
"vpackuswb %%ymm3,%%ymm2,%%ymm2 \n"
"vpermq $0xd8,%%ymm0,%%ymm0 \n"
"vpermq $0xd8,%%ymm2,%%ymm2 \n"
"vmovdqu %%ymm0,(%1) \n"
"vmovdqu %%ymm2,0x00(%1,%2,1) \n"
"lea 0x20(%1),%1 \n"
"sub $0x20,%3 \n"
"jg 1b \n"
"vzeroupper \n"
: "+r"(src_uv), // %0
"+r"(dst_u), // %1
"+r"(dst_v), // %2
"+r"(width) // %3
:
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm5");
}
#endif // HAS_SPLITUVROW_AVX2
#ifdef HAS_SPLITUVROW_SSE2
void SplitUVRow_SSE2(const uint8_t* src_uv,
uint8_t* dst_u,
uint8_t* dst_v,
int width) {
asm volatile(
"pcmpeqb %%xmm5,%%xmm5 \n"
"psrlw $0x8,%%xmm5 \n"
"sub %1,%2 \n"
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"movdqu 0x10(%0),%%xmm1 \n"
"lea 0x20(%0),%0 \n"
"movdqa %%xmm0,%%xmm2 \n"
"movdqa %%xmm1,%%xmm3 \n"
"pand %%xmm5,%%xmm0 \n"
"pand %%xmm5,%%xmm1 \n"
"packuswb %%xmm1,%%xmm0 \n"
"psrlw $0x8,%%xmm2 \n"
"psrlw $0x8,%%xmm3 \n"
"packuswb %%xmm3,%%xmm2 \n"
"movdqu %%xmm0,(%1) \n"
"movdqu %%xmm2,0x00(%1,%2,1) \n"
"lea 0x10(%1),%1 \n"
"sub $0x10,%3 \n"
"jg 1b \n"
: "+r"(src_uv), // %0
"+r"(dst_u), // %1
"+r"(dst_v), // %2
"+r"(width) // %3
:
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm5");
}
#endif // HAS_SPLITUVROW_SSE2
#ifdef HAS_MERGEUVROW_AVX2
void MergeUVRow_AVX2(const uint8_t* src_u,
const uint8_t* src_v,
uint8_t* dst_uv,
int width) {
asm volatile(
"sub %0,%1 \n"
LABELALIGN
"1: \n"
"vmovdqu (%0),%%ymm0 \n"
"vmovdqu 0x00(%0,%1,1),%%ymm1 \n"
"lea 0x20(%0),%0 \n"
"vpunpcklbw %%ymm1,%%ymm0,%%ymm2 \n"
"vpunpckhbw %%ymm1,%%ymm0,%%ymm0 \n"
"vextractf128 $0x0,%%ymm2,(%2) \n"
"vextractf128 $0x0,%%ymm0,0x10(%2) \n"
"vextractf128 $0x1,%%ymm2,0x20(%2) \n"
"vextractf128 $0x1,%%ymm0,0x30(%2) \n"
"lea 0x40(%2),%2 \n"
"sub $0x20,%3 \n"
"jg 1b \n"
"vzeroupper \n"
: "+r"(src_u), // %0
"+r"(src_v), // %1
"+r"(dst_uv), // %2
"+r"(width) // %3
:
: "memory", "cc", "xmm0", "xmm1", "xmm2");
}
#endif // HAS_MERGEUVROW_AVX2
#ifdef HAS_MERGEUVROW_SSE2
void MergeUVRow_SSE2(const uint8_t* src_u,
const uint8_t* src_v,
uint8_t* dst_uv,
int width) {
asm volatile(
"sub %0,%1 \n"
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"movdqu 0x00(%0,%1,1),%%xmm1 \n"
"lea 0x10(%0),%0 \n"
"movdqa %%xmm0,%%xmm2 \n"
"punpcklbw %%xmm1,%%xmm0 \n"
"punpckhbw %%xmm1,%%xmm2 \n"
"movdqu %%xmm0,(%2) \n"
"movdqu %%xmm2,0x10(%2) \n"
"lea 0x20(%2),%2 \n"
"sub $0x10,%3 \n"
"jg 1b \n"
: "+r"(src_u), // %0
"+r"(src_v), // %1
"+r"(dst_uv), // %2
"+r"(width) // %3
:
: "memory", "cc", "xmm0", "xmm1", "xmm2");
}
#endif // HAS_MERGEUVROW_SSE2
// Use scale to convert lsb formats to msb, depending how many bits there are:
// 128 = 9 bits
// 64 = 10 bits
// 16 = 12 bits
// 1 = 16 bits
#ifdef HAS_MERGEUVROW_16_AVX2
void MergeUVRow_16_AVX2(const uint16_t* src_u,
const uint16_t* src_v,
uint16_t* dst_uv,
int scale,
int width) {
// clang-format off
asm volatile (
"vmovd %4,%%xmm3 \n"
"vpunpcklwd %%xmm3,%%xmm3,%%xmm3 \n"
"vbroadcastss %%xmm3,%%ymm3 \n"
"sub %0,%1 \n"
// 16 pixels per loop.
LABELALIGN
"1: \n"
"vmovdqu (%0),%%ymm0 \n"
"vmovdqu (%0,%1,1),%%ymm1 \n"
"add $0x20,%0 \n"
"vpmullw %%ymm3,%%ymm0,%%ymm0 \n"
"vpmullw %%ymm3,%%ymm1,%%ymm1 \n"
"vpunpcklwd %%ymm1,%%ymm0,%%ymm2 \n" // mutates
"vpunpckhwd %%ymm1,%%ymm0,%%ymm0 \n"
"vextractf128 $0x0,%%ymm2,(%2) \n"
"vextractf128 $0x0,%%ymm0,0x10(%2) \n"
"vextractf128 $0x1,%%ymm2,0x20(%2) \n"
"vextractf128 $0x1,%%ymm0,0x30(%2) \n"
"add $0x40,%2 \n"
"sub $0x10,%3 \n"
"jg 1b \n"
"vzeroupper \n"
: "+r"(src_u), // %0
"+r"(src_v), // %1
"+r"(dst_uv), // %2
"+r"(width) // %3
: "r"(scale) // %4
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3");
// clang-format on
}
#endif // HAS_MERGEUVROW_AVX2
// Use scale to convert lsb formats to msb, depending how many bits there are:
// 128 = 9 bits
// 64 = 10 bits
// 16 = 12 bits
// 1 = 16 bits
#ifdef HAS_MULTIPLYROW_16_AVX2
void MultiplyRow_16_AVX2(const uint16_t* src_y,
uint16_t* dst_y,
int scale,
int width) {
// clang-format off
asm volatile (
"vmovd %3,%%xmm3 \n"
"vpunpcklwd %%xmm3,%%xmm3,%%xmm3 \n"
"vbroadcastss %%xmm3,%%ymm3 \n"
"sub %0,%1 \n"
// 16 pixels per loop.
LABELALIGN
"1: \n"
"vmovdqu (%0),%%ymm0 \n"
"vmovdqu 0x20(%0),%%ymm1 \n"
"vpmullw %%ymm3,%%ymm0,%%ymm0 \n"
"vpmullw %%ymm3,%%ymm1,%%ymm1 \n"
"vmovdqu %%ymm0,(%0,%1) \n"
"vmovdqu %%ymm1,0x20(%0,%1) \n"
"add $0x40,%0 \n"
"sub $0x20,%2 \n"
"jg 1b \n"
"vzeroupper \n"
: "+r"(src_y), // %0
"+r"(dst_y), // %1
"+r"(width) // %2
: "r"(scale) // %3
: "memory", "cc", "xmm0", "xmm1", "xmm3");
// clang-format on
}
#endif // HAS_MULTIPLYROW_16_AVX2
// Use scale to convert lsb formats to msb, depending how many bits there are:
// 32768 = 9 bits
// 16384 = 10 bits
// 4096 = 12 bits
// 256 = 16 bits
void Convert16To8Row_SSSE3(const uint16_t* src_y,
uint8_t* dst_y,
int scale,
int width) {
// clang-format off
asm volatile (
"movd %3,%%xmm2 \n"
"punpcklwd %%xmm2,%%xmm2 \n"
"pshufd $0x0,%%xmm2,%%xmm2 \n"
// 32 pixels per loop.
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"movdqu 0x10(%0),%%xmm1 \n"
"add $0x20,%0 \n"
"pmulhuw %%xmm2,%%xmm0 \n"
"pmulhuw %%xmm2,%%xmm1 \n"
"packuswb %%xmm1,%%xmm0 \n"
"movdqu %%xmm0,(%1) \n"
"add $0x10,%1 \n"
"sub $0x10,%2 \n"
"jg 1b \n"
: "+r"(src_y), // %0
"+r"(dst_y), // %1
"+r"(width) // %2
: "r"(scale) // %3
: "memory", "cc", "xmm0", "xmm1", "xmm2");
// clang-format on
}
#ifdef HAS_CONVERT16TO8ROW_AVX2
void Convert16To8Row_AVX2(const uint16_t* src_y,
uint8_t* dst_y,
int scale,
int width) {
// clang-format off
asm volatile (
"vmovd %3,%%xmm2 \n"
"vpunpcklwd %%xmm2,%%xmm2,%%xmm2 \n"
"vbroadcastss %%xmm2,%%ymm2 \n"
// 32 pixels per loop.
LABELALIGN
"1: \n"
"vmovdqu (%0),%%ymm0 \n"
"vmovdqu 0x20(%0),%%ymm1 \n"
"add $0x40,%0 \n"
"vpmulhuw %%ymm2,%%ymm0,%%ymm0 \n"
"vpmulhuw %%ymm2,%%ymm1,%%ymm1 \n"
"vpackuswb %%ymm1,%%ymm0,%%ymm0 \n" // mutates
"vpermq $0xd8,%%ymm0,%%ymm0 \n"
"vmovdqu %%ymm0,(%1) \n"
"add $0x20,%1 \n"
"sub $0x20,%2 \n"
"jg 1b \n"
"vzeroupper \n"
: "+r"(src_y), // %0
"+r"(dst_y), // %1
"+r"(width) // %2
: "r"(scale) // %3
: "memory", "cc", "xmm0", "xmm1", "xmm2");
// clang-format on
}
#endif // HAS_CONVERT16TO8ROW_AVX2
// Use scale to convert to lsb formats depending how many bits there are:
// 512 = 9 bits
// 1024 = 10 bits
// 4096 = 12 bits
// TODO(fbarchard): reduce to SSE2
void Convert8To16Row_SSE2(const uint8_t* src_y,
uint16_t* dst_y,
int scale,
int width) {
// clang-format off
asm volatile (
"movd %3,%%xmm2 \n"
"punpcklwd %%xmm2,%%xmm2 \n"
"pshufd $0x0,%%xmm2,%%xmm2 \n"
// 32 pixels per loop.
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"movdqa %%xmm0,%%xmm1 \n"
"punpcklbw %%xmm0,%%xmm0 \n"
"punpckhbw %%xmm1,%%xmm1 \n"
"add $0x10,%0 \n"
"pmulhuw %%xmm2,%%xmm0 \n"
"pmulhuw %%xmm2,%%xmm1 \n"
"movdqu %%xmm0,(%1) \n"
"movdqu %%xmm1,0x10(%1) \n"
"add $0x20,%1 \n"
"sub $0x10,%2 \n"
"jg 1b \n"
: "+r"(src_y), // %0
"+r"(dst_y), // %1
"+r"(width) // %2
: "r"(scale) // %3
: "memory", "cc", "xmm0", "xmm1", "xmm2");
// clang-format on
}
#ifdef HAS_CONVERT8TO16ROW_AVX2
void Convert8To16Row_AVX2(const uint8_t* src_y,
uint16_t* dst_y,
int scale,
int width) {
// clang-format off
asm volatile (
"vmovd %3,%%xmm2 \n"
"vpunpcklwd %%xmm2,%%xmm2,%%xmm2 \n"
"vbroadcastss %%xmm2,%%ymm2 \n"
// 32 pixels per loop.
LABELALIGN
"1: \n"
"vmovdqu (%0),%%ymm0 \n"
"vpermq $0xd8,%%ymm0,%%ymm0 \n"
"add $0x20,%0 \n"
"vpunpckhbw %%ymm0,%%ymm0,%%ymm1 \n"
"vpunpcklbw %%ymm0,%%ymm0,%%ymm0 \n"
"vpmulhuw %%ymm2,%%ymm0,%%ymm0 \n"
"vpmulhuw %%ymm2,%%ymm1,%%ymm1 \n"
"vmovdqu %%ymm0,(%1) \n"
"vmovdqu %%ymm1,0x20(%1) \n"
"add $0x40,%1 \n"
"sub $0x20,%2 \n"
"jg 1b \n"
"vzeroupper \n"
: "+r"(src_y), // %0
"+r"(dst_y), // %1
"+r"(width) // %2
: "r"(scale) // %3
: "memory", "cc", "xmm0", "xmm1", "xmm2");
// clang-format on
}
#endif // HAS_CONVERT8TO16ROW_AVX2
#ifdef HAS_SPLITRGBROW_SSSE3
// Shuffle table for converting RGB to Planar.
static const uvec8 kShuffleMaskRGBToR0 = {0u, 3u, 6u, 9u, 12u, 15u,
128u, 128u, 128u, 128u, 128u, 128u,
128u, 128u, 128u, 128u};
static const uvec8 kShuffleMaskRGBToR1 = {128u, 128u, 128u, 128u, 128u, 128u,
2u, 5u, 8u, 11u, 14u, 128u,
128u, 128u, 128u, 128u};
static const uvec8 kShuffleMaskRGBToR2 = {128u, 128u, 128u, 128u, 128u, 128u,
128u, 128u, 128u, 128u, 128u, 1u,
4u, 7u, 10u, 13u};
static const uvec8 kShuffleMaskRGBToG0 = {1u, 4u, 7u, 10u, 13u, 128u,
128u, 128u, 128u, 128u, 128u, 128u,
128u, 128u, 128u, 128u};
static const uvec8 kShuffleMaskRGBToG1 = {128u, 128u, 128u, 128u, 128u, 0u,
3u, 6u, 9u, 12u, 15u, 128u,
128u, 128u, 128u, 128u};
static const uvec8 kShuffleMaskRGBToG2 = {128u, 128u, 128u, 128u, 128u, 128u,
128u, 128u, 128u, 128u, 128u, 2u,
5u, 8u, 11u, 14u};
static const uvec8 kShuffleMaskRGBToB0 = {2u, 5u, 8u, 11u, 14u, 128u,
128u, 128u, 128u, 128u, 128u, 128u,
128u, 128u, 128u, 128u};
static const uvec8 kShuffleMaskRGBToB1 = {128u, 128u, 128u, 128u, 128u, 1u,
4u, 7u, 10u, 13u, 128u, 128u,
128u, 128u, 128u, 128u};
static const uvec8 kShuffleMaskRGBToB2 = {128u, 128u, 128u, 128u, 128u, 128u,
128u, 128u, 128u, 128u, 0u, 3u,
6u, 9u, 12u, 15u};
void SplitRGBRow_SSSE3(const uint8_t* src_rgb,
uint8_t* dst_r,
uint8_t* dst_g,
uint8_t* dst_b,
int width) {
asm volatile(
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"movdqu 0x10(%0),%%xmm1 \n"
"movdqu 0x20(%0),%%xmm2 \n"
"pshufb %5, %%xmm0 \n"
"pshufb %6, %%xmm1 \n"
"pshufb %7, %%xmm2 \n"
"por %%xmm1,%%xmm0 \n"
"por %%xmm2,%%xmm0 \n"
"movdqu %%xmm0,(%1) \n"
"lea 0x10(%1),%1 \n"
"movdqu (%0),%%xmm0 \n"
"movdqu 0x10(%0),%%xmm1 \n"
"movdqu 0x20(%0),%%xmm2 \n"
"pshufb %8, %%xmm0 \n"
"pshufb %9, %%xmm1 \n"
"pshufb %10, %%xmm2 \n"
"por %%xmm1,%%xmm0 \n"
"por %%xmm2,%%xmm0 \n"
"movdqu %%xmm0,(%2) \n"
"lea 0x10(%2),%2 \n"
"movdqu (%0),%%xmm0 \n"
"movdqu 0x10(%0),%%xmm1 \n"
"movdqu 0x20(%0),%%xmm2 \n"
"pshufb %11, %%xmm0 \n"
"pshufb %12, %%xmm1 \n"
"pshufb %13, %%xmm2 \n"
"por %%xmm1,%%xmm0 \n"
"por %%xmm2,%%xmm0 \n"
"movdqu %%xmm0,(%3) \n"
"lea 0x10(%3),%3 \n"
"lea 0x30(%0),%0 \n"
"sub $0x10,%4 \n"
"jg 1b \n"
: "+r"(src_rgb), // %0
"+r"(dst_r), // %1
"+r"(dst_g), // %2
"+r"(dst_b), // %3
"+r"(width) // %4
: "m"(kShuffleMaskRGBToR0), // %5
"m"(kShuffleMaskRGBToR1), // %6
"m"(kShuffleMaskRGBToR2), // %7
"m"(kShuffleMaskRGBToG0), // %8
"m"(kShuffleMaskRGBToG1), // %9
"m"(kShuffleMaskRGBToG2), // %10
"m"(kShuffleMaskRGBToB0), // %11
"m"(kShuffleMaskRGBToB1), // %12
"m"(kShuffleMaskRGBToB2) // %13
: "memory", "cc", "xmm0", "xmm1", "xmm2");
}
#endif // HAS_SPLITRGBROW_SSSE3
#ifdef HAS_MERGERGBROW_SSSE3
// Shuffle table for converting RGB to Planar.
static const uvec8 kShuffleMaskRToRGB0 = {0u, 128u, 128u, 1u, 128u, 128u,
2u, 128u, 128u, 3u, 128u, 128u,
4u, 128u, 128u, 5u};
static const uvec8 kShuffleMaskGToRGB0 = {128u, 0u, 128u, 128u, 1u, 128u,
128u, 2u, 128u, 128u, 3u, 128u,
128u, 4u, 128u, 128u};
static const uvec8 kShuffleMaskBToRGB0 = {128u, 128u, 0u, 128u, 128u, 1u,
128u, 128u, 2u, 128u, 128u, 3u,
128u, 128u, 4u, 128u};
static const uvec8 kShuffleMaskGToRGB1 = {5u, 128u, 128u, 6u, 128u, 128u,
7u, 128u, 128u, 8u, 128u, 128u,
9u, 128u, 128u, 10u};
static const uvec8 kShuffleMaskBToRGB1 = {128u, 5u, 128u, 128u, 6u, 128u,
128u, 7u, 128u, 128u, 8u, 128u,
128u, 9u, 128u, 128u};
static const uvec8 kShuffleMaskRToRGB1 = {128u, 128u, 6u, 128u, 128u, 7u,
128u, 128u, 8u, 128u, 128u, 9u,
128u, 128u, 10u, 128u};
static const uvec8 kShuffleMaskBToRGB2 = {10u, 128u, 128u, 11u, 128u, 128u,
12u, 128u, 128u, 13u, 128u, 128u,
14u, 128u, 128u, 15u};
static const uvec8 kShuffleMaskRToRGB2 = {128u, 11u, 128u, 128u, 12u, 128u,
128u, 13u, 128u, 128u, 14u, 128u,
128u, 15u, 128u, 128u};
static const uvec8 kShuffleMaskGToRGB2 = {128u, 128u, 11u, 128u, 128u, 12u,
128u, 128u, 13u, 128u, 128u, 14u,
128u, 128u, 15u, 128u};
void MergeRGBRow_SSSE3(const uint8_t* src_r,
const uint8_t* src_g,
const uint8_t* src_b,
uint8_t* dst_rgb,
int width) {
asm volatile(
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"movdqu (%1),%%xmm1 \n"
"movdqu (%2),%%xmm2 \n"
"pshufb %5, %%xmm0 \n"
"pshufb %6, %%xmm1 \n"
"pshufb %7, %%xmm2 \n"
"por %%xmm1,%%xmm0 \n"
"por %%xmm2,%%xmm0 \n"
"movdqu %%xmm0,(%3) \n"
"movdqu (%0),%%xmm0 \n"
"movdqu (%1),%%xmm1 \n"
"movdqu (%2),%%xmm2 \n"
"pshufb %8, %%xmm0 \n"
"pshufb %9, %%xmm1 \n"
"pshufb %10, %%xmm2 \n"
"por %%xmm1,%%xmm0 \n"
"por %%xmm2,%%xmm0 \n"
"movdqu %%xmm0,16(%3) \n"
"movdqu (%0),%%xmm0 \n"
"movdqu (%1),%%xmm1 \n"
"movdqu (%2),%%xmm2 \n"
"pshufb %11, %%xmm0 \n"
"pshufb %12, %%xmm1 \n"
"pshufb %13, %%xmm2 \n"
"por %%xmm1,%%xmm0 \n"
"por %%xmm2,%%xmm0 \n"
"movdqu %%xmm0,32(%3) \n"
"lea 0x10(%0),%0 \n"
"lea 0x10(%1),%1 \n"
"lea 0x10(%2),%2 \n"
"lea 0x30(%3),%3 \n"
"sub $0x10,%4 \n"
"jg 1b \n"
: "+r"(src_r), // %0
"+r"(src_g), // %1
"+r"(src_b), // %2
"+r"(dst_rgb), // %3
"+r"(width) // %4
: "m"(kShuffleMaskRToRGB0), // %5
"m"(kShuffleMaskGToRGB0), // %6
"m"(kShuffleMaskBToRGB0), // %7
"m"(kShuffleMaskRToRGB1), // %8
"m"(kShuffleMaskGToRGB1), // %9
"m"(kShuffleMaskBToRGB1), // %10
"m"(kShuffleMaskRToRGB2), // %11
"m"(kShuffleMaskGToRGB2), // %12
"m"(kShuffleMaskBToRGB2) // %13
: "memory", "cc", "xmm0", "xmm1", "xmm2");
}
#endif // HAS_MERGERGBROW_SSSE3
#ifdef HAS_COPYROW_SSE2
void CopyRow_SSE2(const uint8_t* src, uint8_t* dst, int width) {
asm volatile(
"test $0xf,%0 \n"
"jne 2f \n"
"test $0xf,%1 \n"
"jne 2f \n"
LABELALIGN
"1: \n"
"movdqa (%0),%%xmm0 \n"
"movdqa 0x10(%0),%%xmm1 \n"
"lea 0x20(%0),%0 \n"
"movdqa %%xmm0,(%1) \n"
"movdqa %%xmm1,0x10(%1) \n"
"lea 0x20(%1),%1 \n"
"sub $0x20,%2 \n"
"jg 1b \n"
"jmp 9f \n"
LABELALIGN
"2: \n"
"movdqu (%0),%%xmm0 \n"
"movdqu 0x10(%0),%%xmm1 \n"
"lea 0x20(%0),%0 \n"
"movdqu %%xmm0,(%1) \n"
"movdqu %%xmm1,0x10(%1) \n"
"lea 0x20(%1),%1 \n"
"sub $0x20,%2 \n"
"jg 2b \n"
LABELALIGN "9: \n"
: "+r"(src), // %0
"+r"(dst), // %1
"+r"(width) // %2
:
: "memory", "cc", "xmm0", "xmm1");
}
#endif // HAS_COPYROW_SSE2
#ifdef HAS_COPYROW_AVX
void CopyRow_AVX(const uint8_t* src, uint8_t* dst, int width) {
asm volatile(
LABELALIGN
"1: \n"
"vmovdqu (%0),%%ymm0 \n"
"vmovdqu 0x20(%0),%%ymm1 \n"
"lea 0x40(%0),%0 \n"
"vmovdqu %%ymm0,(%1) \n"
"vmovdqu %%ymm1,0x20(%1) \n"
"lea 0x40(%1),%1 \n"
"sub $0x40,%2 \n"
"jg 1b \n"
: "+r"(src), // %0
"+r"(dst), // %1
"+r"(width) // %2
:
: "memory", "cc", "xmm0", "xmm1");
}
#endif // HAS_COPYROW_AVX
#ifdef HAS_COPYROW_ERMS
// Multiple of 1.
void CopyRow_ERMS(const uint8_t* src, uint8_t* dst, int width) {
size_t width_tmp = (size_t)(width);
asm volatile(
"rep movsb \n"
: "+S"(src), // %0
"+D"(dst), // %1
"+c"(width_tmp) // %2
:
: "memory", "cc");
}
#endif // HAS_COPYROW_ERMS
#ifdef HAS_ARGBCOPYALPHAROW_SSE2
// width in pixels
void ARGBCopyAlphaRow_SSE2(const uint8_t* src, uint8_t* dst, int width) {
asm volatile(
"pcmpeqb %%xmm0,%%xmm0 \n"
"pslld $0x18,%%xmm0 \n"
"pcmpeqb %%xmm1,%%xmm1 \n"
"psrld $0x8,%%xmm1 \n"
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm2 \n"
"movdqu 0x10(%0),%%xmm3 \n"
"lea 0x20(%0),%0 \n"
"movdqu (%1),%%xmm4 \n"
"movdqu 0x10(%1),%%xmm5 \n"
"pand %%xmm0,%%xmm2 \n"
"pand %%xmm0,%%xmm3 \n"
"pand %%xmm1,%%xmm4 \n"
"pand %%xmm1,%%xmm5 \n"
"por %%xmm4,%%xmm2 \n"
"por %%xmm5,%%xmm3 \n"
"movdqu %%xmm2,(%1) \n"
"movdqu %%xmm3,0x10(%1) \n"
"lea 0x20(%1),%1 \n"
"sub $0x8,%2 \n"
"jg 1b \n"
: "+r"(src), // %0
"+r"(dst), // %1
"+r"(width) // %2
:
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5");
}
#endif // HAS_ARGBCOPYALPHAROW_SSE2
#ifdef HAS_ARGBCOPYALPHAROW_AVX2
// width in pixels
void ARGBCopyAlphaRow_AVX2(const uint8_t* src, uint8_t* dst, int width) {
asm volatile(
"vpcmpeqb %%ymm0,%%ymm0,%%ymm0 \n"
"vpsrld $0x8,%%ymm0,%%ymm0 \n"
LABELALIGN
"1: \n"
"vmovdqu (%0),%%ymm1 \n"
"vmovdqu 0x20(%0),%%ymm2 \n"
"lea 0x40(%0),%0 \n"
"vpblendvb %%ymm0,(%1),%%ymm1,%%ymm1 \n"
"vpblendvb %%ymm0,0x20(%1),%%ymm2,%%ymm2 \n"
"vmovdqu %%ymm1,(%1) \n"
"vmovdqu %%ymm2,0x20(%1) \n"
"lea 0x40(%1),%1 \n"
"sub $0x10,%2 \n"
"jg 1b \n"
"vzeroupper \n"
: "+r"(src), // %0
"+r"(dst), // %1
"+r"(width) // %2
:
: "memory", "cc", "xmm0", "xmm1", "xmm2");
}
#endif // HAS_ARGBCOPYALPHAROW_AVX2
#ifdef HAS_ARGBEXTRACTALPHAROW_SSE2
// width in pixels
void ARGBExtractAlphaRow_SSE2(const uint8_t* src_argb,
uint8_t* dst_a,
int width) {
asm volatile(
LABELALIGN
"1: \n"
"movdqu (%0), %%xmm0 \n"
"movdqu 0x10(%0), %%xmm1 \n"
"lea 0x20(%0), %0 \n"
"psrld $0x18, %%xmm0 \n"
"psrld $0x18, %%xmm1 \n"
"packssdw %%xmm1, %%xmm0 \n"
"packuswb %%xmm0, %%xmm0 \n"
"movq %%xmm0,(%1) \n"
"lea 0x8(%1), %1 \n"
"sub $0x8, %2 \n"
"jg 1b \n"
: "+r"(src_argb), // %0
"+r"(dst_a), // %1
"+rm"(width) // %2
:
: "memory", "cc", "xmm0", "xmm1");
}
#endif // HAS_ARGBEXTRACTALPHAROW_SSE2
#ifdef HAS_ARGBEXTRACTALPHAROW_AVX2
static const uvec8 kShuffleAlphaShort_AVX2 = {
3u, 128u, 128u, 128u, 7u, 128u, 128u, 128u,
11u, 128u, 128u, 128u, 15u, 128u, 128u, 128u};
void ARGBExtractAlphaRow_AVX2(const uint8_t* src_argb,
uint8_t* dst_a,
int width) {
asm volatile(
"vmovdqa %3,%%ymm4 \n"
"vbroadcastf128 %4,%%ymm5 \n"
LABELALIGN
"1: \n"
"vmovdqu (%0), %%ymm0 \n"
"vmovdqu 0x20(%0), %%ymm1 \n"
"vpshufb %%ymm5,%%ymm0,%%ymm0 \n" // vpsrld $0x18, %%ymm0
"vpshufb %%ymm5,%%ymm1,%%ymm1 \n"
"vmovdqu 0x40(%0), %%ymm2 \n"
"vmovdqu 0x60(%0), %%ymm3 \n"
"lea 0x80(%0), %0 \n"
"vpackssdw %%ymm1, %%ymm0, %%ymm0 \n" // mutates
"vpshufb %%ymm5,%%ymm2,%%ymm2 \n"
"vpshufb %%ymm5,%%ymm3,%%ymm3 \n"
"vpackssdw %%ymm3, %%ymm2, %%ymm2 \n" // mutates
"vpackuswb %%ymm2,%%ymm0,%%ymm0 \n" // mutates.
"vpermd %%ymm0,%%ymm4,%%ymm0 \n" // unmutate.
"vmovdqu %%ymm0,(%1) \n"
"lea 0x20(%1),%1 \n"
"sub $0x20, %2 \n"
"jg 1b \n"
"vzeroupper \n"
: "+r"(src_argb), // %0
"+r"(dst_a), // %1
"+rm"(width) // %2
: "m"(kPermdARGBToY_AVX), // %3
"m"(kShuffleAlphaShort_AVX2) // %4
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5");
}
#endif // HAS_ARGBEXTRACTALPHAROW_AVX2
#ifdef HAS_ARGBCOPYYTOALPHAROW_SSE2
// width in pixels
void ARGBCopyYToAlphaRow_SSE2(const uint8_t* src, uint8_t* dst, int width) {
asm volatile(
"pcmpeqb %%xmm0,%%xmm0 \n"
"pslld $0x18,%%xmm0 \n"
"pcmpeqb %%xmm1,%%xmm1 \n"
"psrld $0x8,%%xmm1 \n"
LABELALIGN
"1: \n"
"movq (%0),%%xmm2 \n"
"lea 0x8(%0),%0 \n"
"punpcklbw %%xmm2,%%xmm2 \n"
"punpckhwd %%xmm2,%%xmm3 \n"
"punpcklwd %%xmm2,%%xmm2 \n"
"movdqu (%1),%%xmm4 \n"
"movdqu 0x10(%1),%%xmm5 \n"
"pand %%xmm0,%%xmm2 \n"
"pand %%xmm0,%%xmm3 \n"
"pand %%xmm1,%%xmm4 \n"
"pand %%xmm1,%%xmm5 \n"
"por %%xmm4,%%xmm2 \n"
"por %%xmm5,%%xmm3 \n"
"movdqu %%xmm2,(%1) \n"
"movdqu %%xmm3,0x10(%1) \n"
"lea 0x20(%1),%1 \n"
"sub $0x8,%2 \n"
"jg 1b \n"
: "+r"(src), // %0
"+r"(dst), // %1
"+r"(width) // %2
:
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5");
}
#endif // HAS_ARGBCOPYYTOALPHAROW_SSE2
#ifdef HAS_ARGBCOPYYTOALPHAROW_AVX2
// width in pixels
void ARGBCopyYToAlphaRow_AVX2(const uint8_t* src, uint8_t* dst, int width) {
asm volatile(
"vpcmpeqb %%ymm0,%%ymm0,%%ymm0 \n"
"vpsrld $0x8,%%ymm0,%%ymm0 \n"
LABELALIGN
"1: \n"
"vpmovzxbd (%0),%%ymm1 \n"
"vpmovzxbd 0x8(%0),%%ymm2 \n"
"lea 0x10(%0),%0 \n"
"vpslld $0x18,%%ymm1,%%ymm1 \n"
"vpslld $0x18,%%ymm2,%%ymm2 \n"
"vpblendvb %%ymm0,(%1),%%ymm1,%%ymm1 \n"
"vpblendvb %%ymm0,0x20(%1),%%ymm2,%%ymm2 \n"
"vmovdqu %%ymm1,(%1) \n"
"vmovdqu %%ymm2,0x20(%1) \n"
"lea 0x40(%1),%1 \n"
"sub $0x10,%2 \n"
"jg 1b \n"
"vzeroupper \n"
: "+r"(src), // %0
"+r"(dst), // %1
"+r"(width) // %2
:
: "memory", "cc", "xmm0", "xmm1", "xmm2");
}
#endif // HAS_ARGBCOPYYTOALPHAROW_AVX2
#ifdef HAS_SETROW_X86
void SetRow_X86(uint8_t* dst, uint8_t v8, int width) {
size_t width_tmp = (size_t)(width >> 2);
const uint32_t v32 = v8 * 0x01010101u; // Duplicate byte to all bytes.
asm volatile(
"rep stosl \n"
: "+D"(dst), // %0
"+c"(width_tmp) // %1
: "a"(v32) // %2
: "memory", "cc");
}
void SetRow_ERMS(uint8_t* dst, uint8_t v8, int width) {
size_t width_tmp = (size_t)(width);
asm volatile(
"rep stosb \n"
: "+D"(dst), // %0
"+c"(width_tmp) // %1
: "a"(v8) // %2
: "memory", "cc");
}
void ARGBSetRow_X86(uint8_t* dst_argb, uint32_t v32, int width) {
size_t width_tmp = (size_t)(width);
asm volatile(
"rep stosl \n"
: "+D"(dst_argb), // %0
"+c"(width_tmp) // %1
: "a"(v32) // %2
: "memory", "cc");
}
#endif // HAS_SETROW_X86
#ifdef HAS_YUY2TOYROW_SSE2
void YUY2ToYRow_SSE2(const uint8_t* src_yuy2, uint8_t* dst_y, int width) {
asm volatile(
"pcmpeqb %%xmm5,%%xmm5 \n"
"psrlw $0x8,%%xmm5 \n"
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"movdqu 0x10(%0),%%xmm1 \n"
"lea 0x20(%0),%0 \n"
"pand %%xmm5,%%xmm0 \n"
"pand %%xmm5,%%xmm1 \n"
"packuswb %%xmm1,%%xmm0 \n"
"movdqu %%xmm0,(%1) \n"
"lea 0x10(%1),%1 \n"
"sub $0x10,%2 \n"
"jg 1b \n"
: "+r"(src_yuy2), // %0
"+r"(dst_y), // %1
"+r"(width) // %2
:
: "memory", "cc", "xmm0", "xmm1", "xmm5");
}
void YUY2ToUVRow_SSE2(const uint8_t* src_yuy2,
int stride_yuy2,
uint8_t* dst_u,
uint8_t* dst_v,
int width) {
asm volatile(
"pcmpeqb %%xmm5,%%xmm5 \n"
"psrlw $0x8,%%xmm5 \n"
"sub %1,%2 \n"
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"movdqu 0x10(%0),%%xmm1 \n"
"movdqu 0x00(%0,%4,1),%%xmm2 \n"
"movdqu 0x10(%0,%4,1),%%xmm3 \n"
"lea 0x20(%0),%0 \n"
"pavgb %%xmm2,%%xmm0 \n"
"pavgb %%xmm3,%%xmm1 \n"
"psrlw $0x8,%%xmm0 \n"
"psrlw $0x8,%%xmm1 \n"
"packuswb %%xmm1,%%xmm0 \n"
"movdqa %%xmm0,%%xmm1 \n"
"pand %%xmm5,%%xmm0 \n"
"packuswb %%xmm0,%%xmm0 \n"
"psrlw $0x8,%%xmm1 \n"
"packuswb %%xmm1,%%xmm1 \n"
"movq %%xmm0,(%1) \n"
"movq %%xmm1,0x00(%1,%2,1) \n"
"lea 0x8(%1),%1 \n"
"sub $0x10,%3 \n"
"jg 1b \n"
: "+r"(src_yuy2), // %0
"+r"(dst_u), // %1
"+r"(dst_v), // %2
"+r"(width) // %3
: "r"((intptr_t)(stride_yuy2)) // %4
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm5");
}
void YUY2ToUV422Row_SSE2(const uint8_t* src_yuy2,
uint8_t* dst_u,
uint8_t* dst_v,
int width) {
asm volatile(
"pcmpeqb %%xmm5,%%xmm5 \n"
"psrlw $0x8,%%xmm5 \n"
"sub %1,%2 \n"
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"movdqu 0x10(%0),%%xmm1 \n"
"lea 0x20(%0),%0 \n"
"psrlw $0x8,%%xmm0 \n"
"psrlw $0x8,%%xmm1 \n"
"packuswb %%xmm1,%%xmm0 \n"
"movdqa %%xmm0,%%xmm1 \n"
"pand %%xmm5,%%xmm0 \n"
"packuswb %%xmm0,%%xmm0 \n"
"psrlw $0x8,%%xmm1 \n"
"packuswb %%xmm1,%%xmm1 \n"
"movq %%xmm0,(%1) \n"
"movq %%xmm1,0x00(%1,%2,1) \n"
"lea 0x8(%1),%1 \n"
"sub $0x10,%3 \n"
"jg 1b \n"
: "+r"(src_yuy2), // %0
"+r"(dst_u), // %1
"+r"(dst_v), // %2
"+r"(width) // %3
:
: "memory", "cc", "xmm0", "xmm1", "xmm5");
}
void UYVYToYRow_SSE2(const uint8_t* src_uyvy, uint8_t* dst_y, int width) {
asm volatile(
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"movdqu 0x10(%0),%%xmm1 \n"
"lea 0x20(%0),%0 \n"
"psrlw $0x8,%%xmm0 \n"
"psrlw $0x8,%%xmm1 \n"
"packuswb %%xmm1,%%xmm0 \n"
"movdqu %%xmm0,(%1) \n"
"lea 0x10(%1),%1 \n"
"sub $0x10,%2 \n"
"jg 1b \n"
: "+r"(src_uyvy), // %0
"+r"(dst_y), // %1
"+r"(width) // %2
:
: "memory", "cc", "xmm0", "xmm1");
}
void UYVYToUVRow_SSE2(const uint8_t* src_uyvy,
int stride_uyvy,
uint8_t* dst_u,
uint8_t* dst_v,
int width) {
asm volatile(
"pcmpeqb %%xmm5,%%xmm5 \n"
"psrlw $0x8,%%xmm5 \n"
"sub %1,%2 \n"
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"movdqu 0x10(%0),%%xmm1 \n"
"movdqu 0x00(%0,%4,1),%%xmm2 \n"
"movdqu 0x10(%0,%4,1),%%xmm3 \n"
"lea 0x20(%0),%0 \n"
"pavgb %%xmm2,%%xmm0 \n"
"pavgb %%xmm3,%%xmm1 \n"
"pand %%xmm5,%%xmm0 \n"
"pand %%xmm5,%%xmm1 \n"
"packuswb %%xmm1,%%xmm0 \n"
"movdqa %%xmm0,%%xmm1 \n"
"pand %%xmm5,%%xmm0 \n"
"packuswb %%xmm0,%%xmm0 \n"
"psrlw $0x8,%%xmm1 \n"
"packuswb %%xmm1,%%xmm1 \n"
"movq %%xmm0,(%1) \n"
"movq %%xmm1,0x00(%1,%2,1) \n"
"lea 0x8(%1),%1 \n"
"sub $0x10,%3 \n"
"jg 1b \n"
: "+r"(src_uyvy), // %0
"+r"(dst_u), // %1
"+r"(dst_v), // %2
"+r"(width) // %3
: "r"((intptr_t)(stride_uyvy)) // %4
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm5");
}
void UYVYToUV422Row_SSE2(const uint8_t* src_uyvy,
uint8_t* dst_u,
uint8_t* dst_v,
int width) {
asm volatile(
"pcmpeqb %%xmm5,%%xmm5 \n"
"psrlw $0x8,%%xmm5 \n"
"sub %1,%2 \n"
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"movdqu 0x10(%0),%%xmm1 \n"
"lea 0x20(%0),%0 \n"
"pand %%xmm5,%%xmm0 \n"
"pand %%xmm5,%%xmm1 \n"
"packuswb %%xmm1,%%xmm0 \n"
"movdqa %%xmm0,%%xmm1 \n"
"pand %%xmm5,%%xmm0 \n"
"packuswb %%xmm0,%%xmm0 \n"
"psrlw $0x8,%%xmm1 \n"
"packuswb %%xmm1,%%xmm1 \n"
"movq %%xmm0,(%1) \n"
"movq %%xmm1,0x00(%1,%2,1) \n"
"lea 0x8(%1),%1 \n"
"sub $0x10,%3 \n"
"jg 1b \n"
: "+r"(src_uyvy), // %0
"+r"(dst_u), // %1
"+r"(dst_v), // %2
"+r"(width) // %3
:
: "memory", "cc", "xmm0", "xmm1", "xmm5");
}
#endif // HAS_YUY2TOYROW_SSE2
#ifdef HAS_YUY2TOYROW_AVX2
void YUY2ToYRow_AVX2(const uint8_t* src_yuy2, uint8_t* dst_y, int width) {
asm volatile(
"vpcmpeqb %%ymm5,%%ymm5,%%ymm5 \n"
"vpsrlw $0x8,%%ymm5,%%ymm5 \n"
LABELALIGN
"1: \n"
"vmovdqu (%0),%%ymm0 \n"
"vmovdqu 0x20(%0),%%ymm1 \n"
"lea 0x40(%0),%0 \n"
"vpand %%ymm5,%%ymm0,%%ymm0 \n"
"vpand %%ymm5,%%ymm1,%%ymm1 \n"
"vpackuswb %%ymm1,%%ymm0,%%ymm0 \n"
"vpermq $0xd8,%%ymm0,%%ymm0 \n"
"vmovdqu %%ymm0,(%1) \n"
"lea 0x20(%1),%1 \n"
"sub $0x20,%2 \n"
"jg 1b \n"
"vzeroupper \n"
: "+r"(src_yuy2), // %0
"+r"(dst_y), // %1
"+r"(width) // %2
:
: "memory", "cc", "xmm0", "xmm1", "xmm5");
}
void YUY2ToUVRow_AVX2(const uint8_t* src_yuy2,
int stride_yuy2,
uint8_t* dst_u,
uint8_t* dst_v,
int width) {
asm volatile(
"vpcmpeqb %%ymm5,%%ymm5,%%ymm5 \n"
"vpsrlw $0x8,%%ymm5,%%ymm5 \n"
"sub %1,%2 \n"
LABELALIGN
"1: \n"
"vmovdqu (%0),%%ymm0 \n"
"vmovdqu 0x20(%0),%%ymm1 \n"
"vpavgb 0x00(%0,%4,1),%%ymm0,%%ymm0 \n"
"vpavgb 0x20(%0,%4,1),%%ymm1,%%ymm1 \n"
"lea 0x40(%0),%0 \n"
"vpsrlw $0x8,%%ymm0,%%ymm0 \n"
"vpsrlw $0x8,%%ymm1,%%ymm1 \n"
"vpackuswb %%ymm1,%%ymm0,%%ymm0 \n"
"vpermq $0xd8,%%ymm0,%%ymm0 \n"
"vpand %%ymm5,%%ymm0,%%ymm1 \n"
"vpsrlw $0x8,%%ymm0,%%ymm0 \n"
"vpackuswb %%ymm1,%%ymm1,%%ymm1 \n"
"vpackuswb %%ymm0,%%ymm0,%%ymm0 \n"
"vpermq $0xd8,%%ymm1,%%ymm1 \n"
"vpermq $0xd8,%%ymm0,%%ymm0 \n"
"vextractf128 $0x0,%%ymm1,(%1) \n"
"vextractf128 $0x0,%%ymm0,0x00(%1,%2,1) \n"
"lea 0x10(%1),%1 \n"
"sub $0x20,%3 \n"
"jg 1b \n"
"vzeroupper \n"
: "+r"(src_yuy2), // %0
"+r"(dst_u), // %1
"+r"(dst_v), // %2
"+r"(width) // %3
: "r"((intptr_t)(stride_yuy2)) // %4
: "memory", "cc", "xmm0", "xmm1", "xmm5");
}
void YUY2ToUV422Row_AVX2(const uint8_t* src_yuy2,
uint8_t* dst_u,
uint8_t* dst_v,
int width) {
asm volatile(
"vpcmpeqb %%ymm5,%%ymm5,%%ymm5 \n"
"vpsrlw $0x8,%%ymm5,%%ymm5 \n"
"sub %1,%2 \n"
LABELALIGN
"1: \n"
"vmovdqu (%0),%%ymm0 \n"
"vmovdqu 0x20(%0),%%ymm1 \n"
"lea 0x40(%0),%0 \n"
"vpsrlw $0x8,%%ymm0,%%ymm0 \n"
"vpsrlw $0x8,%%ymm1,%%ymm1 \n"
"vpackuswb %%ymm1,%%ymm0,%%ymm0 \n"
"vpermq $0xd8,%%ymm0,%%ymm0 \n"
"vpand %%ymm5,%%ymm0,%%ymm1 \n"
"vpsrlw $0x8,%%ymm0,%%ymm0 \n"
"vpackuswb %%ymm1,%%ymm1,%%ymm1 \n"
"vpackuswb %%ymm0,%%ymm0,%%ymm0 \n"
"vpermq $0xd8,%%ymm1,%%ymm1 \n"
"vpermq $0xd8,%%ymm0,%%ymm0 \n"
"vextractf128 $0x0,%%ymm1,(%1) \n"
"vextractf128 $0x0,%%ymm0,0x00(%1,%2,1) \n"
"lea 0x10(%1),%1 \n"
"sub $0x20,%3 \n"
"jg 1b \n"
"vzeroupper \n"
: "+r"(src_yuy2), // %0
"+r"(dst_u), // %1
"+r"(dst_v), // %2
"+r"(width) // %3
:
: "memory", "cc", "xmm0", "xmm1", "xmm5");
}
void UYVYToYRow_AVX2(const uint8_t* src_uyvy, uint8_t* dst_y, int width) {
asm volatile(
LABELALIGN
"1: \n"
"vmovdqu (%0),%%ymm0 \n"
"vmovdqu 0x20(%0),%%ymm1 \n"
"lea 0x40(%0),%0 \n"
"vpsrlw $0x8,%%ymm0,%%ymm0 \n"
"vpsrlw $0x8,%%ymm1,%%ymm1 \n"
"vpackuswb %%ymm1,%%ymm0,%%ymm0 \n"
"vpermq $0xd8,%%ymm0,%%ymm0 \n"
"vmovdqu %%ymm0,(%1) \n"
"lea 0x20(%1),%1 \n"
"sub $0x20,%2 \n"
"jg 1b \n"
"vzeroupper \n"
: "+r"(src_uyvy), // %0
"+r"(dst_y), // %1
"+r"(width) // %2
:
: "memory", "cc", "xmm0", "xmm1", "xmm5");
}
void UYVYToUVRow_AVX2(const uint8_t* src_uyvy,
int stride_uyvy,
uint8_t* dst_u,
uint8_t* dst_v,
int width) {
asm volatile(
"vpcmpeqb %%ymm5,%%ymm5,%%ymm5 \n"
"vpsrlw $0x8,%%ymm5,%%ymm5 \n"
"sub %1,%2 \n"
LABELALIGN
"1: \n"
"vmovdqu (%0),%%ymm0 \n"
"vmovdqu 0x20(%0),%%ymm1 \n"
"vpavgb 0x00(%0,%4,1),%%ymm0,%%ymm0 \n"
"vpavgb 0x20(%0,%4,1),%%ymm1,%%ymm1 \n"
"lea 0x40(%0),%0 \n"
"vpand %%ymm5,%%ymm0,%%ymm0 \n"
"vpand %%ymm5,%%ymm1,%%ymm1 \n"
"vpackuswb %%ymm1,%%ymm0,%%ymm0 \n"
"vpermq $0xd8,%%ymm0,%%ymm0 \n"
"vpand %%ymm5,%%ymm0,%%ymm1 \n"
"vpsrlw $0x8,%%ymm0,%%ymm0 \n"
"vpackuswb %%ymm1,%%ymm1,%%ymm1 \n"
"vpackuswb %%ymm0,%%ymm0,%%ymm0 \n"
"vpermq $0xd8,%%ymm1,%%ymm1 \n"
"vpermq $0xd8,%%ymm0,%%ymm0 \n"
"vextractf128 $0x0,%%ymm1,(%1) \n"
"vextractf128 $0x0,%%ymm0,0x00(%1,%2,1) \n"
"lea 0x10(%1),%1 \n"
"sub $0x20,%3 \n"
"jg 1b \n"
"vzeroupper \n"
: "+r"(src_uyvy), // %0
"+r"(dst_u), // %1
"+r"(dst_v), // %2
"+r"(width) // %3
: "r"((intptr_t)(stride_uyvy)) // %4
: "memory", "cc", "xmm0", "xmm1", "xmm5");
}
void UYVYToUV422Row_AVX2(const uint8_t* src_uyvy,
uint8_t* dst_u,
uint8_t* dst_v,
int width) {
asm volatile(
"vpcmpeqb %%ymm5,%%ymm5,%%ymm5 \n"
"vpsrlw $0x8,%%ymm5,%%ymm5 \n"
"sub %1,%2 \n"
LABELALIGN
"1: \n"
"vmovdqu (%0),%%ymm0 \n"
"vmovdqu 0x20(%0),%%ymm1 \n"
"lea 0x40(%0),%0 \n"
"vpand %%ymm5,%%ymm0,%%ymm0 \n"
"vpand %%ymm5,%%ymm1,%%ymm1 \n"
"vpackuswb %%ymm1,%%ymm0,%%ymm0 \n"
"vpermq $0xd8,%%ymm0,%%ymm0 \n"
"vpand %%ymm5,%%ymm0,%%ymm1 \n"
"vpsrlw $0x8,%%ymm0,%%ymm0 \n"
"vpackuswb %%ymm1,%%ymm1,%%ymm1 \n"
"vpackuswb %%ymm0,%%ymm0,%%ymm0 \n"
"vpermq $0xd8,%%ymm1,%%ymm1 \n"
"vpermq $0xd8,%%ymm0,%%ymm0 \n"
"vextractf128 $0x0,%%ymm1,(%1) \n"
"vextractf128 $0x0,%%ymm0,0x00(%1,%2,1) \n"
"lea 0x10(%1),%1 \n"
"sub $0x20,%3 \n"
"jg 1b \n"
"vzeroupper \n"
: "+r"(src_uyvy), // %0
"+r"(dst_u), // %1
"+r"(dst_v), // %2
"+r"(width) // %3
:
: "memory", "cc", "xmm0", "xmm1", "xmm5");
}
#endif // HAS_YUY2TOYROW_AVX2
#ifdef HAS_ARGBBLENDROW_SSSE3
// Shuffle table for isolating alpha.
static const uvec8 kShuffleAlpha = {3u, 0x80, 3u, 0x80, 7u, 0x80, 7u, 0x80,
11u, 0x80, 11u, 0x80, 15u, 0x80, 15u, 0x80};
// Blend 8 pixels at a time
void ARGBBlendRow_SSSE3(const uint8_t* src_argb0,
const uint8_t* src_argb1,
uint8_t* dst_argb,
int width) {
asm volatile(
"pcmpeqb %%xmm7,%%xmm7 \n"
"psrlw $0xf,%%xmm7 \n"
"pcmpeqb %%xmm6,%%xmm6 \n"
"psrlw $0x8,%%xmm6 \n"
"pcmpeqb %%xmm5,%%xmm5 \n"
"psllw $0x8,%%xmm5 \n"
"pcmpeqb %%xmm4,%%xmm4 \n"
"pslld $0x18,%%xmm4 \n"
"sub $0x4,%3 \n"
"jl 49f \n"
// 4 pixel loop.
LABELALIGN
"40: \n"
"movdqu (%0),%%xmm3 \n"
"lea 0x10(%0),%0 \n"
"movdqa %%xmm3,%%xmm0 \n"
"pxor %%xmm4,%%xmm3 \n"
"movdqu (%1),%%xmm2 \n"
"pshufb %4,%%xmm3 \n"
"pand %%xmm6,%%xmm2 \n"
"paddw %%xmm7,%%xmm3 \n"
"pmullw %%xmm3,%%xmm2 \n"
"movdqu (%1),%%xmm1 \n"
"lea 0x10(%1),%1 \n"
"psrlw $0x8,%%xmm1 \n"
"por %%xmm4,%%xmm0 \n"
"pmullw %%xmm3,%%xmm1 \n"
"psrlw $0x8,%%xmm2 \n"
"paddusb %%xmm2,%%xmm0 \n"
"pand %%xmm5,%%xmm1 \n"
"paddusb %%xmm1,%%xmm0 \n"
"movdqu %%xmm0,(%2) \n"
"lea 0x10(%2),%2 \n"
"sub $0x4,%3 \n"
"jge 40b \n"
"49: \n"
"add $0x3,%3 \n"
"jl 99f \n"
// 1 pixel loop.
"91: \n"
"movd (%0),%%xmm3 \n"
"lea 0x4(%0),%0 \n"
"movdqa %%xmm3,%%xmm0 \n"
"pxor %%xmm4,%%xmm3 \n"
"movd (%1),%%xmm2 \n"
"pshufb %4,%%xmm3 \n"
"pand %%xmm6,%%xmm2 \n"
"paddw %%xmm7,%%xmm3 \n"
"pmullw %%xmm3,%%xmm2 \n"
"movd (%1),%%xmm1 \n"
"lea 0x4(%1),%1 \n"
"psrlw $0x8,%%xmm1 \n"
"por %%xmm4,%%xmm0 \n"
"pmullw %%xmm3,%%xmm1 \n"
"psrlw $0x8,%%xmm2 \n"
"paddusb %%xmm2,%%xmm0 \n"
"pand %%xmm5,%%xmm1 \n"
"paddusb %%xmm1,%%xmm0 \n"
"movd %%xmm0,(%2) \n"
"lea 0x4(%2),%2 \n"
"sub $0x1,%3 \n"
"jge 91b \n"
"99: \n"
: "+r"(src_argb0), // %0
"+r"(src_argb1), // %1
"+r"(dst_argb), // %2
"+r"(width) // %3
: "m"(kShuffleAlpha) // %4
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6",
"xmm7");
}
#endif // HAS_ARGBBLENDROW_SSSE3
#ifdef HAS_BLENDPLANEROW_SSSE3
// Blend 8 pixels at a time.
// unsigned version of math
// =((A2*C2)+(B2*(255-C2))+255)/256
// signed version of math
// =(((A2-128)*C2)+((B2-128)*(255-C2))+32768+127)/256
void BlendPlaneRow_SSSE3(const uint8_t* src0,
const uint8_t* src1,
const uint8_t* alpha,
uint8_t* dst,
int width) {
asm volatile(
"pcmpeqb %%xmm5,%%xmm5 \n"
"psllw $0x8,%%xmm5 \n"
"mov $0x80808080,%%eax \n"
"movd %%eax,%%xmm6 \n"
"pshufd $0x0,%%xmm6,%%xmm6 \n"
"mov $0x807f807f,%%eax \n"
"movd %%eax,%%xmm7 \n"
"pshufd $0x0,%%xmm7,%%xmm7 \n"
"sub %2,%0 \n"
"sub %2,%1 \n"
"sub %2,%3 \n"
// 8 pixel loop.
LABELALIGN
"1: \n"
"movq (%2),%%xmm0 \n"
"punpcklbw %%xmm0,%%xmm0 \n"
"pxor %%xmm5,%%xmm0 \n"
"movq (%0,%2,1),%%xmm1 \n"
"movq (%1,%2,1),%%xmm2 \n"
"punpcklbw %%xmm2,%%xmm1 \n"
"psubb %%xmm6,%%xmm1 \n"
"pmaddubsw %%xmm1,%%xmm0 \n"
"paddw %%xmm7,%%xmm0 \n"
"psrlw $0x8,%%xmm0 \n"
"packuswb %%xmm0,%%xmm0 \n"
"movq %%xmm0,(%3,%2,1) \n"
"lea 0x8(%2),%2 \n"
"sub $0x8,%4 \n"
"jg 1b \n"
: "+r"(src0), // %0
"+r"(src1), // %1
"+r"(alpha), // %2
"+r"(dst), // %3
"+rm"(width) // %4
::"memory",
"cc", "eax", "xmm0", "xmm1", "xmm2", "xmm5", "xmm6", "xmm7");
}
#endif // HAS_BLENDPLANEROW_SSSE3
#ifdef HAS_BLENDPLANEROW_AVX2
// Blend 32 pixels at a time.
// unsigned version of math
// =((A2*C2)+(B2*(255-C2))+255)/256
// signed version of math
// =(((A2-128)*C2)+((B2-128)*(255-C2))+32768+127)/256
void BlendPlaneRow_AVX2(const uint8_t* src0,
const uint8_t* src1,
const uint8_t* alpha,
uint8_t* dst,
int width) {
asm volatile(
"vpcmpeqb %%ymm5,%%ymm5,%%ymm5 \n"
"vpsllw $0x8,%%ymm5,%%ymm5 \n"
"mov $0x80808080,%%eax \n"
"vmovd %%eax,%%xmm6 \n"
"vbroadcastss %%xmm6,%%ymm6 \n"
"mov $0x807f807f,%%eax \n"
"vmovd %%eax,%%xmm7 \n"
"vbroadcastss %%xmm7,%%ymm7 \n"
"sub %2,%0 \n"
"sub %2,%1 \n"
"sub %2,%3 \n"
// 32 pixel loop.
LABELALIGN
"1: \n"
"vmovdqu (%2),%%ymm0 \n"
"vpunpckhbw %%ymm0,%%ymm0,%%ymm3 \n"
"vpunpcklbw %%ymm0,%%ymm0,%%ymm0 \n"
"vpxor %%ymm5,%%ymm3,%%ymm3 \n"
"vpxor %%ymm5,%%ymm0,%%ymm0 \n"
"vmovdqu (%0,%2,1),%%ymm1 \n"
"vmovdqu (%1,%2,1),%%ymm2 \n"
"vpunpckhbw %%ymm2,%%ymm1,%%ymm4 \n"
"vpunpcklbw %%ymm2,%%ymm1,%%ymm1 \n"
"vpsubb %%ymm6,%%ymm4,%%ymm4 \n"
"vpsubb %%ymm6,%%ymm1,%%ymm1 \n"
"vpmaddubsw %%ymm4,%%ymm3,%%ymm3 \n"
"vpmaddubsw %%ymm1,%%ymm0,%%ymm0 \n"
"vpaddw %%ymm7,%%ymm3,%%ymm3 \n"
"vpaddw %%ymm7,%%ymm0,%%ymm0 \n"
"vpsrlw $0x8,%%ymm3,%%ymm3 \n"
"vpsrlw $0x8,%%ymm0,%%ymm0 \n"
"vpackuswb %%ymm3,%%ymm0,%%ymm0 \n"
"vmovdqu %%ymm0,(%3,%2,1) \n"
"lea 0x20(%2),%2 \n"
"sub $0x20,%4 \n"
"jg 1b \n"
"vzeroupper \n"
: "+r"(src0), // %0
"+r"(src1), // %1
"+r"(alpha), // %2
"+r"(dst), // %3
"+rm"(width) // %4
::"memory",
"cc", "eax", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6",
"xmm7");
}
#endif // HAS_BLENDPLANEROW_AVX2
#ifdef HAS_ARGBATTENUATEROW_SSSE3
// Shuffle table duplicating alpha.
static const uvec8 kAttenShuffle = {6u, 7u, 6u, 7u, 6u, 7u, 128u, 128u,
14u, 15u, 14u, 15u, 14u, 15u, 128u, 128u};
// Attenuate 4 pixels at a time.
void ARGBAttenuateRow_SSSE3(const uint8_t* src_argb,
uint8_t* dst_argb,
int width) {
asm volatile(
"movdqu %3,%%xmm6 \n" // alpha shuffler
"pcmpeqb %%xmm7,%%xmm7 \n" // 0x0080
"psllw $0xf,%%xmm7 \n"
"psrlw $0x8,%%xmm7 \n"
"pcmpeqb %%xmm0,%%xmm0 \n" // 0xff000000
"pslld $0x18,%%xmm0 \n"
"sub %0,%1 \n"
// 4 pixel loop.
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm1 \n"
"pxor %%xmm4,%%xmm4 \n"
"movdqa %%xmm1,%%xmm2 \n"
"movdqa %%xmm1,%%xmm3 \n"
"punpcklbw %%xmm4,%%xmm2 \n"
"punpckhbw %%xmm4,%%xmm3 \n"
"movdqa %%xmm2,%%xmm4 \n"
"movdqa %%xmm3,%%xmm5 \n"
"pshufb %%xmm6,%%xmm4 \n"
"pshufb %%xmm6,%%xmm5 \n"
"pmullw %%xmm4,%%xmm2 \n"
"pmullw %%xmm5,%%xmm3 \n"
"pand %%xmm0,%%xmm1 \n"
"paddw %%xmm7,%%xmm2 \n"
"paddw %%xmm7,%%xmm3 \n"
"psrlw $0x8,%%xmm2 \n"
"psrlw $0x8,%%xmm3 \n"
"packuswb %%xmm3,%%xmm2 \n"
"por %%xmm1,%%xmm2 \n"
"movdqu %%xmm2,(%0,%1,1) \n"
"lea 0x10(%0),%0 \n"
"sub $0x4,%2 \n"
"jg 1b \n"
: "+r"(src_argb), // %0
"+r"(dst_argb), // %1
"+r"(width) // %2
: "m"(kAttenShuffle) // %3
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6",
"xmm7");
}
#endif // HAS_ARGBATTENUATEROW_SSSE3
#ifdef HAS_ARGBATTENUATEROW_AVX2
// Attenuate 8 pixels at a time.
void ARGBAttenuateRow_AVX2(const uint8_t* src_argb,
uint8_t* dst_argb,
int width) {
asm volatile(
"vbroadcastf128 %3,%%ymm6 \n" // alpha shuffler
"vpcmpeqb %%ymm0,%%ymm0,%%ymm0 \n" // 0xff000000
"vpsllw $0xf,%%ymm0,%%ymm7 \n" // 0x0080
"vpslld $0x18,%%ymm0,%%ymm0 \n"
"vpsrlw $0x8,%%ymm7,%%ymm7 \n"
"sub %0,%1 \n"
// 8 pixel loop.
LABELALIGN
"1: \n"
"vmovdqu (%0),%%ymm1 \n"
"vpxor %%ymm3,%%ymm3,%%ymm3 \n"
"vpunpcklbw %%ymm3,%%ymm1,%%ymm2 \n"
"vpunpckhbw %%ymm3,%%ymm1,%%ymm3 \n"
"vpshufb %%ymm6,%%ymm2,%%ymm4 \n"
"vpshufb %%ymm6,%%ymm3,%%ymm5 \n"
"vpmullw %%ymm4,%%ymm2,%%ymm2 \n"
"vpmullw %%ymm5,%%ymm3,%%ymm3 \n"
"vpaddw %%ymm7,%%ymm2,%%ymm2 \n"
"vpaddw %%ymm7,%%ymm3,%%ymm3 \n"
"vpsrlw $0x8,%%ymm2,%%ymm2 \n"
"vpsrlw $0x8,%%ymm3,%%ymm3 \n"
"vpackuswb %%ymm3,%%ymm2,%%ymm2 \n"
"vpblendvb %%ymm0,%%ymm1,%%ymm2,%%ymm2 \n"
"vmovdqu %%ymm2,(%0,%1,1) \n"
"lea 0x20(%0),%0 \n"
"sub $0x8,%2 \n"
"jg 1b \n"
"vzeroupper \n"
: "+r"(src_argb), // %0
"+r"(dst_argb), // %1
"+r"(width) // %2
: "m"(kAttenShuffle) // %3
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6",
"xmm7");
}
#endif // HAS_ARGBATTENUATEROW_AVX2
#ifdef HAS_ARGBUNATTENUATEROW_SSE2
// Unattenuate 4 pixels at a time.
void ARGBUnattenuateRow_SSE2(const uint8_t* src_argb,
uint8_t* dst_argb,
int width) {
uintptr_t alpha;
asm volatile(
// 4 pixel loop.
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"movzb 0x03(%0),%3 \n"
"punpcklbw %%xmm0,%%xmm0 \n"
"movd 0x00(%4,%3,4),%%xmm2 \n"
"movzb 0x07(%0),%3 \n"
"movd 0x00(%4,%3,4),%%xmm3 \n"
"pshuflw $0x40,%%xmm2,%%xmm2 \n"
"pshuflw $0x40,%%xmm3,%%xmm3 \n"
"movlhps %%xmm3,%%xmm2 \n"
"pmulhuw %%xmm2,%%xmm0 \n"
"movdqu (%0),%%xmm1 \n"
"movzb 0x0b(%0),%3 \n"
"punpckhbw %%xmm1,%%xmm1 \n"
"movd 0x00(%4,%3,4),%%xmm2 \n"
"movzb 0x0f(%0),%3 \n"
"movd 0x00(%4,%3,4),%%xmm3 \n"
"pshuflw $0x40,%%xmm2,%%xmm2 \n"
"pshuflw $0x40,%%xmm3,%%xmm3 \n"
"movlhps %%xmm3,%%xmm2 \n"
"pmulhuw %%xmm2,%%xmm1 \n"
"lea 0x10(%0),%0 \n"
"packuswb %%xmm1,%%xmm0 \n"
"movdqu %%xmm0,(%1) \n"
"lea 0x10(%1),%1 \n"
"sub $0x4,%2 \n"
"jg 1b \n"
: "+r"(src_argb), // %0
"+r"(dst_argb), // %1
"+r"(width), // %2
"=&r"(alpha) // %3
: "r"(fixed_invtbl8) // %4
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5");
}
#endif // HAS_ARGBUNATTENUATEROW_SSE2
#ifdef HAS_ARGBUNATTENUATEROW_AVX2
// Shuffle table duplicating alpha.
static const uvec8 kUnattenShuffleAlpha_AVX2 = {
0u, 1u, 0u, 1u, 0u, 1u, 6u, 7u, 8u, 9u, 8u, 9u, 8u, 9u, 14u, 15u};
// Unattenuate 8 pixels at a time.
void ARGBUnattenuateRow_AVX2(const uint8_t* src_argb,
uint8_t* dst_argb,
int width) {
uintptr_t alpha;
asm volatile(
"sub %0,%1 \n"
"vbroadcastf128 %5,%%ymm5 \n"
// 8 pixel loop.
LABELALIGN
"1: \n"
// replace VPGATHER
"movzb 0x03(%0),%3 \n"
"vmovd 0x00(%4,%3,4),%%xmm0 \n"
"movzb 0x07(%0),%3 \n"
"vmovd 0x00(%4,%3,4),%%xmm1 \n"
"movzb 0x0b(%0),%3 \n"
"vpunpckldq %%xmm1,%%xmm0,%%xmm6 \n"
"vmovd 0x00(%4,%3,4),%%xmm2 \n"
"movzb 0x0f(%0),%3 \n"
"vmovd 0x00(%4,%3,4),%%xmm3 \n"
"movzb 0x13(%0),%3 \n"
"vpunpckldq %%xmm3,%%xmm2,%%xmm7 \n"
"vmovd 0x00(%4,%3,4),%%xmm0 \n"
"movzb 0x17(%0),%3 \n"
"vmovd 0x00(%4,%3,4),%%xmm1 \n"
"movzb 0x1b(%0),%3 \n"
"vpunpckldq %%xmm1,%%xmm0,%%xmm0 \n"
"vmovd 0x00(%4,%3,4),%%xmm2 \n"
"movzb 0x1f(%0),%3 \n"
"vmovd 0x00(%4,%3,4),%%xmm3 \n"
"vpunpckldq %%xmm3,%%xmm2,%%xmm2 \n"
"vpunpcklqdq %%xmm7,%%xmm6,%%xmm3 \n"
"vpunpcklqdq %%xmm2,%%xmm0,%%xmm0 \n"
"vinserti128 $0x1,%%xmm0,%%ymm3,%%ymm3 \n"
// end of VPGATHER
"vmovdqu (%0),%%ymm6 \n"
"vpunpcklbw %%ymm6,%%ymm6,%%ymm0 \n"
"vpunpckhbw %%ymm6,%%ymm6,%%ymm1 \n"
"vpunpcklwd %%ymm3,%%ymm3,%%ymm2 \n"
"vpunpckhwd %%ymm3,%%ymm3,%%ymm3 \n"
"vpshufb %%ymm5,%%ymm2,%%ymm2 \n"
"vpshufb %%ymm5,%%ymm3,%%ymm3 \n"
"vpmulhuw %%ymm2,%%ymm0,%%ymm0 \n"
"vpmulhuw %%ymm3,%%ymm1,%%ymm1 \n"
"vpackuswb %%ymm1,%%ymm0,%%ymm0 \n"
"vmovdqu %%ymm0,0x00(%0,%1,1) \n"
"lea 0x20(%0),%0 \n"
"sub $0x8,%2 \n"
"jg 1b \n"
"vzeroupper \n"
: "+r"(src_argb), // %0
"+r"(dst_argb), // %1
"+r"(width), // %2
"=&r"(alpha) // %3
: "r"(fixed_invtbl8), // %4
"m"(kUnattenShuffleAlpha_AVX2) // %5
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6",
"xmm7");
}
#endif // HAS_ARGBUNATTENUATEROW_AVX2
#ifdef HAS_ARGBGRAYROW_SSSE3
// Convert 8 ARGB pixels (64 bytes) to 8 Gray ARGB pixels
void ARGBGrayRow_SSSE3(const uint8_t* src_argb, uint8_t* dst_argb, int width) {
asm volatile(
"movdqa %3,%%xmm4 \n"
"movdqa %4,%%xmm5 \n"
// 8 pixel loop.
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"movdqu 0x10(%0),%%xmm1 \n"
"psubb %%xmm5,%%xmm0 \n"
"psubb %%xmm5,%%xmm1 \n"
"movdqu %%xmm4,%%xmm6 \n"
"pmaddubsw %%xmm0,%%xmm6 \n"
"movdqu %%xmm4,%%xmm0 \n"
"pmaddubsw %%xmm1,%%xmm0 \n"
"phaddw %%xmm0,%%xmm6 \n"
"paddw %%xmm5,%%xmm6 \n"
"psrlw $0x8,%%xmm6 \n"
"packuswb %%xmm6,%%xmm6 \n"
"movdqu (%0),%%xmm2 \n"
"movdqu 0x10(%0),%%xmm3 \n"
"lea 0x20(%0),%0 \n"
"psrld $0x18,%%xmm2 \n"
"psrld $0x18,%%xmm3 \n"
"packuswb %%xmm3,%%xmm2 \n"
"packuswb %%xmm2,%%xmm2 \n"
"movdqa %%xmm6,%%xmm3 \n"
"punpcklbw %%xmm6,%%xmm6 \n"
"punpcklbw %%xmm2,%%xmm3 \n"
"movdqa %%xmm6,%%xmm1 \n"
"punpcklwd %%xmm3,%%xmm6 \n"
"punpckhwd %%xmm3,%%xmm1 \n"
"movdqu %%xmm6,(%1) \n"
"movdqu %%xmm1,0x10(%1) \n"
"lea 0x20(%1),%1 \n"
"sub $0x8,%2 \n"
"jg 1b \n"
: "+r"(src_argb), // %0
"+r"(dst_argb), // %1
"+r"(width) // %2
: "m"(kARGBToYJ), // %3
"m"(kSub128) // %4
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6");
}
#endif // HAS_ARGBGRAYROW_SSSE3
#ifdef HAS_ARGBSEPIAROW_SSSE3
// b = (r * 35 + g * 68 + b * 17) >> 7
// g = (r * 45 + g * 88 + b * 22) >> 7
// r = (r * 50 + g * 98 + b * 24) >> 7
// Constant for ARGB color to sepia tone
static const vec8 kARGBToSepiaB = {17, 68, 35, 0, 17, 68, 35, 0,
17, 68, 35, 0, 17, 68, 35, 0};
static const vec8 kARGBToSepiaG = {22, 88, 45, 0, 22, 88, 45, 0,
22, 88, 45, 0, 22, 88, 45, 0};
static const vec8 kARGBToSepiaR = {24, 98, 50, 0, 24, 98, 50, 0,
24, 98, 50, 0, 24, 98, 50, 0};
// Convert 8 ARGB pixels (32 bytes) to 8 Sepia ARGB pixels.
void ARGBSepiaRow_SSSE3(uint8_t* dst_argb, int width) {
asm volatile(
"movdqa %2,%%xmm2 \n"
"movdqa %3,%%xmm3 \n"
"movdqa %4,%%xmm4 \n"
// 8 pixel loop.
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"movdqu 0x10(%0),%%xmm6 \n"
"pmaddubsw %%xmm2,%%xmm0 \n"
"pmaddubsw %%xmm2,%%xmm6 \n"
"phaddw %%xmm6,%%xmm0 \n"
"psrlw $0x7,%%xmm0 \n"
"packuswb %%xmm0,%%xmm0 \n"
"movdqu (%0),%%xmm5 \n"
"movdqu 0x10(%0),%%xmm1 \n"
"pmaddubsw %%xmm3,%%xmm5 \n"
"pmaddubsw %%xmm3,%%xmm1 \n"
"phaddw %%xmm1,%%xmm5 \n"
"psrlw $0x7,%%xmm5 \n"
"packuswb %%xmm5,%%xmm5 \n"
"punpcklbw %%xmm5,%%xmm0 \n"
"movdqu (%0),%%xmm5 \n"
"movdqu 0x10(%0),%%xmm1 \n"
"pmaddubsw %%xmm4,%%xmm5 \n"
"pmaddubsw %%xmm4,%%xmm1 \n"
"phaddw %%xmm1,%%xmm5 \n"
"psrlw $0x7,%%xmm5 \n"
"packuswb %%xmm5,%%xmm5 \n"
"movdqu (%0),%%xmm6 \n"
"movdqu 0x10(%0),%%xmm1 \n"
"psrld $0x18,%%xmm6 \n"
"psrld $0x18,%%xmm1 \n"
"packuswb %%xmm1,%%xmm6 \n"
"packuswb %%xmm6,%%xmm6 \n"
"punpcklbw %%xmm6,%%xmm5 \n"
"movdqa %%xmm0,%%xmm1 \n"
"punpcklwd %%xmm5,%%xmm0 \n"
"punpckhwd %%xmm5,%%xmm1 \n"
"movdqu %%xmm0,(%0) \n"
"movdqu %%xmm1,0x10(%0) \n"
"lea 0x20(%0),%0 \n"
"sub $0x8,%1 \n"
"jg 1b \n"
: "+r"(dst_argb), // %0
"+r"(width) // %1
: "m"(kARGBToSepiaB), // %2
"m"(kARGBToSepiaG), // %3
"m"(kARGBToSepiaR) // %4
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6");
}
#endif // HAS_ARGBSEPIAROW_SSSE3
#ifdef HAS_ARGBCOLORMATRIXROW_SSSE3
// Tranform 8 ARGB pixels (32 bytes) with color matrix.
// Same as Sepia except matrix is provided.
void ARGBColorMatrixRow_SSSE3(const uint8_t* src_argb,
uint8_t* dst_argb,
const int8_t* matrix_argb,
int width) {
asm volatile(
"movdqu (%3),%%xmm5 \n"
"pshufd $0x00,%%xmm5,%%xmm2 \n"
"pshufd $0x55,%%xmm5,%%xmm3 \n"
"pshufd $0xaa,%%xmm5,%%xmm4 \n"
"pshufd $0xff,%%xmm5,%%xmm5 \n"
// 8 pixel loop.
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"movdqu 0x10(%0),%%xmm7 \n"
"pmaddubsw %%xmm2,%%xmm0 \n"
"pmaddubsw %%xmm2,%%xmm7 \n"
"movdqu (%0),%%xmm6 \n"
"movdqu 0x10(%0),%%xmm1 \n"
"pmaddubsw %%xmm3,%%xmm6 \n"
"pmaddubsw %%xmm3,%%xmm1 \n"
"phaddsw %%xmm7,%%xmm0 \n"
"phaddsw %%xmm1,%%xmm6 \n"
"psraw $0x6,%%xmm0 \n"
"psraw $0x6,%%xmm6 \n"
"packuswb %%xmm0,%%xmm0 \n"
"packuswb %%xmm6,%%xmm6 \n"
"punpcklbw %%xmm6,%%xmm0 \n"
"movdqu (%0),%%xmm1 \n"
"movdqu 0x10(%0),%%xmm7 \n"
"pmaddubsw %%xmm4,%%xmm1 \n"
"pmaddubsw %%xmm4,%%xmm7 \n"
"phaddsw %%xmm7,%%xmm1 \n"
"movdqu (%0),%%xmm6 \n"
"movdqu 0x10(%0),%%xmm7 \n"
"pmaddubsw %%xmm5,%%xmm6 \n"
"pmaddubsw %%xmm5,%%xmm7 \n"
"phaddsw %%xmm7,%%xmm6 \n"
"psraw $0x6,%%xmm1 \n"
"psraw $0x6,%%xmm6 \n"
"packuswb %%xmm1,%%xmm1 \n"
"packuswb %%xmm6,%%xmm6 \n"
"punpcklbw %%xmm6,%%xmm1 \n"
"movdqa %%xmm0,%%xmm6 \n"
"punpcklwd %%xmm1,%%xmm0 \n"
"punpckhwd %%xmm1,%%xmm6 \n"
"movdqu %%xmm0,(%1) \n"
"movdqu %%xmm6,0x10(%1) \n"
"lea 0x20(%0),%0 \n"
"lea 0x20(%1),%1 \n"
"sub $0x8,%2 \n"
"jg 1b \n"
: "+r"(src_argb), // %0
"+r"(dst_argb), // %1
"+r"(width) // %2
: "r"(matrix_argb) // %3
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6",
"xmm7");
}
#endif // HAS_ARGBCOLORMATRIXROW_SSSE3
#ifdef HAS_ARGBQUANTIZEROW_SSE2
// Quantize 4 ARGB pixels (16 bytes).
void ARGBQuantizeRow_SSE2(uint8_t* dst_argb,
int scale,
int interval_size,
int interval_offset,
int width) {
asm volatile(
"movd %2,%%xmm2 \n"
"movd %3,%%xmm3 \n"
"movd %4,%%xmm4 \n"
"pshuflw $0x40,%%xmm2,%%xmm2 \n"
"pshufd $0x44,%%xmm2,%%xmm2 \n"
"pshuflw $0x40,%%xmm3,%%xmm3 \n"
"pshufd $0x44,%%xmm3,%%xmm3 \n"
"pshuflw $0x40,%%xmm4,%%xmm4 \n"
"pshufd $0x44,%%xmm4,%%xmm4 \n"
"pxor %%xmm5,%%xmm5 \n"
"pcmpeqb %%xmm6,%%xmm6 \n"
"pslld $0x18,%%xmm6 \n"
// 4 pixel loop.
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"punpcklbw %%xmm5,%%xmm0 \n"
"pmulhuw %%xmm2,%%xmm0 \n"
"movdqu (%0),%%xmm1 \n"
"punpckhbw %%xmm5,%%xmm1 \n"
"pmulhuw %%xmm2,%%xmm1 \n"
"pmullw %%xmm3,%%xmm0 \n"
"movdqu (%0),%%xmm7 \n"
"pmullw %%xmm3,%%xmm1 \n"
"pand %%xmm6,%%xmm7 \n"
"paddw %%xmm4,%%xmm0 \n"
"paddw %%xmm4,%%xmm1 \n"
"packuswb %%xmm1,%%xmm0 \n"
"por %%xmm7,%%xmm0 \n"
"movdqu %%xmm0,(%0) \n"
"lea 0x10(%0),%0 \n"
"sub $0x4,%1 \n"
"jg 1b \n"
: "+r"(dst_argb), // %0
"+r"(width) // %1
: "r"(scale), // %2
"r"(interval_size), // %3
"r"(interval_offset) // %4
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6",
"xmm7");
}
#endif // HAS_ARGBQUANTIZEROW_SSE2
#ifdef HAS_ARGBSHADEROW_SSE2
// Shade 4 pixels at a time by specified value.
void ARGBShadeRow_SSE2(const uint8_t* src_argb,
uint8_t* dst_argb,
int width,
uint32_t value) {
asm volatile(
"movd %3,%%xmm2 \n"
"punpcklbw %%xmm2,%%xmm2 \n"
"punpcklqdq %%xmm2,%%xmm2 \n"
// 4 pixel loop.
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"lea 0x10(%0),%0 \n"
"movdqa %%xmm0,%%xmm1 \n"
"punpcklbw %%xmm0,%%xmm0 \n"
"punpckhbw %%xmm1,%%xmm1 \n"
"pmulhuw %%xmm2,%%xmm0 \n"
"pmulhuw %%xmm2,%%xmm1 \n"
"psrlw $0x8,%%xmm0 \n"
"psrlw $0x8,%%xmm1 \n"
"packuswb %%xmm1,%%xmm0 \n"
"movdqu %%xmm0,(%1) \n"
"lea 0x10(%1),%1 \n"
"sub $0x4,%2 \n"
"jg 1b \n"
: "+r"(src_argb), // %0
"+r"(dst_argb), // %1
"+r"(width) // %2
: "r"(value) // %3
: "memory", "cc", "xmm0", "xmm1", "xmm2");
}
#endif // HAS_ARGBSHADEROW_SSE2
#ifdef HAS_ARGBMULTIPLYROW_SSE2
// Multiply 2 rows of ARGB pixels together, 4 pixels at a time.
void ARGBMultiplyRow_SSE2(const uint8_t* src_argb0,
const uint8_t* src_argb1,
uint8_t* dst_argb,
int width) {
asm volatile(
"pxor %%xmm5,%%xmm5 \n"
// 4 pixel loop.
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"lea 0x10(%0),%0 \n"
"movdqu (%1),%%xmm2 \n"
"lea 0x10(%1),%1 \n"
"movdqu %%xmm0,%%xmm1 \n"
"movdqu %%xmm2,%%xmm3 \n"
"punpcklbw %%xmm0,%%xmm0 \n"
"punpckhbw %%xmm1,%%xmm1 \n"
"punpcklbw %%xmm5,%%xmm2 \n"
"punpckhbw %%xmm5,%%xmm3 \n"
"pmulhuw %%xmm2,%%xmm0 \n"
"pmulhuw %%xmm3,%%xmm1 \n"
"packuswb %%xmm1,%%xmm0 \n"
"movdqu %%xmm0,(%2) \n"
"lea 0x10(%2),%2 \n"
"sub $0x4,%3 \n"
"jg 1b \n"
: "+r"(src_argb0), // %0
"+r"(src_argb1), // %1
"+r"(dst_argb), // %2
"+r"(width) // %3
:
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm5");
}
#endif // HAS_ARGBMULTIPLYROW_SSE2
#ifdef HAS_ARGBMULTIPLYROW_AVX2
// Multiply 2 rows of ARGB pixels together, 8 pixels at a time.
void ARGBMultiplyRow_AVX2(const uint8_t* src_argb0,
const uint8_t* src_argb1,
uint8_t* dst_argb,
int width) {
asm volatile(
"vpxor %%ymm5,%%ymm5,%%ymm5 \n"
// 4 pixel loop.
LABELALIGN
"1: \n"
"vmovdqu (%0),%%ymm1 \n"
"lea 0x20(%0),%0 \n"
"vmovdqu (%1),%%ymm3 \n"
"lea 0x20(%1),%1 \n"
"vpunpcklbw %%ymm1,%%ymm1,%%ymm0 \n"
"vpunpckhbw %%ymm1,%%ymm1,%%ymm1 \n"
"vpunpcklbw %%ymm5,%%ymm3,%%ymm2 \n"
"vpunpckhbw %%ymm5,%%ymm3,%%ymm3 \n"
"vpmulhuw %%ymm2,%%ymm0,%%ymm0 \n"
"vpmulhuw %%ymm3,%%ymm1,%%ymm1 \n"
"vpackuswb %%ymm1,%%ymm0,%%ymm0 \n"
"vmovdqu %%ymm0,(%2) \n"
"lea 0x20(%2),%2 \n"
"sub $0x8,%3 \n"
"jg 1b \n"
"vzeroupper \n"
: "+r"(src_argb0), // %0
"+r"(src_argb1), // %1
"+r"(dst_argb), // %2
"+r"(width) // %3
:
: "memory", "cc"
#if defined(__AVX2__)
,
"xmm0", "xmm1", "xmm2", "xmm3", "xmm5"
#endif
);
}
#endif // HAS_ARGBMULTIPLYROW_AVX2
#ifdef HAS_ARGBADDROW_SSE2
// Add 2 rows of ARGB pixels together, 4 pixels at a time.
void ARGBAddRow_SSE2(const uint8_t* src_argb0,
const uint8_t* src_argb1,
uint8_t* dst_argb,
int width) {
asm volatile(
// 4 pixel loop.
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"lea 0x10(%0),%0 \n"
"movdqu (%1),%%xmm1 \n"
"lea 0x10(%1),%1 \n"
"paddusb %%xmm1,%%xmm0 \n"
"movdqu %%xmm0,(%2) \n"
"lea 0x10(%2),%2 \n"
"sub $0x4,%3 \n"
"jg 1b \n"
: "+r"(src_argb0), // %0
"+r"(src_argb1), // %1
"+r"(dst_argb), // %2
"+r"(width) // %3
:
: "memory", "cc", "xmm0", "xmm1");
}
#endif // HAS_ARGBADDROW_SSE2
#ifdef HAS_ARGBADDROW_AVX2
// Add 2 rows of ARGB pixels together, 4 pixels at a time.
void ARGBAddRow_AVX2(const uint8_t* src_argb0,
const uint8_t* src_argb1,
uint8_t* dst_argb,
int width) {
asm volatile(
// 4 pixel loop.
LABELALIGN
"1: \n"
"vmovdqu (%0),%%ymm0 \n"
"lea 0x20(%0),%0 \n"
"vpaddusb (%1),%%ymm0,%%ymm0 \n"
"lea 0x20(%1),%1 \n"
"vmovdqu %%ymm0,(%2) \n"
"lea 0x20(%2),%2 \n"
"sub $0x8,%3 \n"
"jg 1b \n"
"vzeroupper \n"
: "+r"(src_argb0), // %0
"+r"(src_argb1), // %1
"+r"(dst_argb), // %2
"+r"(width) // %3
:
: "memory", "cc", "xmm0");
}
#endif // HAS_ARGBADDROW_AVX2
#ifdef HAS_ARGBSUBTRACTROW_SSE2
// Subtract 2 rows of ARGB pixels, 4 pixels at a time.
void ARGBSubtractRow_SSE2(const uint8_t* src_argb0,
const uint8_t* src_argb1,
uint8_t* dst_argb,
int width) {
asm volatile(
// 4 pixel loop.
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"lea 0x10(%0),%0 \n"
"movdqu (%1),%%xmm1 \n"
"lea 0x10(%1),%1 \n"
"psubusb %%xmm1,%%xmm0 \n"
"movdqu %%xmm0,(%2) \n"
"lea 0x10(%2),%2 \n"
"sub $0x4,%3 \n"
"jg 1b \n"
: "+r"(src_argb0), // %0
"+r"(src_argb1), // %1
"+r"(dst_argb), // %2
"+r"(width) // %3
:
: "memory", "cc", "xmm0", "xmm1");
}
#endif // HAS_ARGBSUBTRACTROW_SSE2
#ifdef HAS_ARGBSUBTRACTROW_AVX2
// Subtract 2 rows of ARGB pixels, 8 pixels at a time.
void ARGBSubtractRow_AVX2(const uint8_t* src_argb0,
const uint8_t* src_argb1,
uint8_t* dst_argb,
int width) {
asm volatile(
// 4 pixel loop.
LABELALIGN
"1: \n"
"vmovdqu (%0),%%ymm0 \n"
"lea 0x20(%0),%0 \n"
"vpsubusb (%1),%%ymm0,%%ymm0 \n"
"lea 0x20(%1),%1 \n"
"vmovdqu %%ymm0,(%2) \n"
"lea 0x20(%2),%2 \n"
"sub $0x8,%3 \n"
"jg 1b \n"
"vzeroupper \n"
: "+r"(src_argb0), // %0
"+r"(src_argb1), // %1
"+r"(dst_argb), // %2
"+r"(width) // %3
:
: "memory", "cc", "xmm0");
}
#endif // HAS_ARGBSUBTRACTROW_AVX2
#ifdef HAS_SOBELXROW_SSE2
// SobelX as a matrix is
// -1 0 1
// -2 0 2
// -1 0 1
void SobelXRow_SSE2(const uint8_t* src_y0,
const uint8_t* src_y1,
const uint8_t* src_y2,
uint8_t* dst_sobelx,
int width) {
asm volatile(
"sub %0,%1 \n"
"sub %0,%2 \n"
"sub %0,%3 \n"
"pxor %%xmm5,%%xmm5 \n"
// 8 pixel loop.
LABELALIGN
"1: \n"
"movq (%0),%%xmm0 \n"
"movq 0x2(%0),%%xmm1 \n"
"punpcklbw %%xmm5,%%xmm0 \n"
"punpcklbw %%xmm5,%%xmm1 \n"
"psubw %%xmm1,%%xmm0 \n"
"movq 0x00(%0,%1,1),%%xmm1 \n"
"movq 0x02(%0,%1,1),%%xmm2 \n"
"punpcklbw %%xmm5,%%xmm1 \n"
"punpcklbw %%xmm5,%%xmm2 \n"
"psubw %%xmm2,%%xmm1 \n"
"movq 0x00(%0,%2,1),%%xmm2 \n"
"movq 0x02(%0,%2,1),%%xmm3 \n"
"punpcklbw %%xmm5,%%xmm2 \n"
"punpcklbw %%xmm5,%%xmm3 \n"
"psubw %%xmm3,%%xmm2 \n"
"paddw %%xmm2,%%xmm0 \n"
"paddw %%xmm1,%%xmm0 \n"
"paddw %%xmm1,%%xmm0 \n"
"pxor %%xmm1,%%xmm1 \n"
"psubw %%xmm0,%%xmm1 \n"
"pmaxsw %%xmm1,%%xmm0 \n"
"packuswb %%xmm0,%%xmm0 \n"
"movq %%xmm0,0x00(%0,%3,1) \n"
"lea 0x8(%0),%0 \n"
"sub $0x8,%4 \n"
"jg 1b \n"
: "+r"(src_y0), // %0
"+r"(src_y1), // %1
"+r"(src_y2), // %2
"+r"(dst_sobelx), // %3
"+r"(width) // %4
:
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm5");
}
#endif // HAS_SOBELXROW_SSE2
#ifdef HAS_SOBELYROW_SSE2
// SobelY as a matrix is
// -1 -2 -1
// 0 0 0
// 1 2 1
void SobelYRow_SSE2(const uint8_t* src_y0,
const uint8_t* src_y1,
uint8_t* dst_sobely,
int width) {
asm volatile(
"sub %0,%1 \n"
"sub %0,%2 \n"
"pxor %%xmm5,%%xmm5 \n"
// 8 pixel loop.
LABELALIGN
"1: \n"
"movq (%0),%%xmm0 \n"
"movq 0x00(%0,%1,1),%%xmm1 \n"
"punpcklbw %%xmm5,%%xmm0 \n"
"punpcklbw %%xmm5,%%xmm1 \n"
"psubw %%xmm1,%%xmm0 \n"
"movq 0x1(%0),%%xmm1 \n"
"movq 0x01(%0,%1,1),%%xmm2 \n"
"punpcklbw %%xmm5,%%xmm1 \n"
"punpcklbw %%xmm5,%%xmm2 \n"
"psubw %%xmm2,%%xmm1 \n"
"movq 0x2(%0),%%xmm2 \n"
"movq 0x02(%0,%1,1),%%xmm3 \n"
"punpcklbw %%xmm5,%%xmm2 \n"
"punpcklbw %%xmm5,%%xmm3 \n"
"psubw %%xmm3,%%xmm2 \n"
"paddw %%xmm2,%%xmm0 \n"
"paddw %%xmm1,%%xmm0 \n"
"paddw %%xmm1,%%xmm0 \n"
"pxor %%xmm1,%%xmm1 \n"
"psubw %%xmm0,%%xmm1 \n"
"pmaxsw %%xmm1,%%xmm0 \n"
"packuswb %%xmm0,%%xmm0 \n"
"movq %%xmm0,0x00(%0,%2,1) \n"
"lea 0x8(%0),%0 \n"
"sub $0x8,%3 \n"
"jg 1b \n"
: "+r"(src_y0), // %0
"+r"(src_y1), // %1
"+r"(dst_sobely), // %2
"+r"(width) // %3
:
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm5");
}
#endif // HAS_SOBELYROW_SSE2
#ifdef HAS_SOBELROW_SSE2
// Adds Sobel X and Sobel Y and stores Sobel into ARGB.
// A = 255
// R = Sobel
// G = Sobel
// B = Sobel
void SobelRow_SSE2(const uint8_t* src_sobelx,
const uint8_t* src_sobely,
uint8_t* dst_argb,
int width) {
asm volatile(
"sub %0,%1 \n"
"pcmpeqb %%xmm5,%%xmm5 \n"
"pslld $0x18,%%xmm5 \n"
// 8 pixel loop.
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"movdqu 0x00(%0,%1,1),%%xmm1 \n"
"lea 0x10(%0),%0 \n"
"paddusb %%xmm1,%%xmm0 \n"
"movdqa %%xmm0,%%xmm2 \n"
"punpcklbw %%xmm0,%%xmm2 \n"
"punpckhbw %%xmm0,%%xmm0 \n"
"movdqa %%xmm2,%%xmm1 \n"
"punpcklwd %%xmm2,%%xmm1 \n"
"punpckhwd %%xmm2,%%xmm2 \n"
"por %%xmm5,%%xmm1 \n"
"por %%xmm5,%%xmm2 \n"
"movdqa %%xmm0,%%xmm3 \n"
"punpcklwd %%xmm0,%%xmm3 \n"
"punpckhwd %%xmm0,%%xmm0 \n"
"por %%xmm5,%%xmm3 \n"
"por %%xmm5,%%xmm0 \n"
"movdqu %%xmm1,(%2) \n"
"movdqu %%xmm2,0x10(%2) \n"
"movdqu %%xmm3,0x20(%2) \n"
"movdqu %%xmm0,0x30(%2) \n"
"lea 0x40(%2),%2 \n"
"sub $0x10,%3 \n"
"jg 1b \n"
: "+r"(src_sobelx), // %0
"+r"(src_sobely), // %1
"+r"(dst_argb), // %2
"+r"(width) // %3
:
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm5");
}
#endif // HAS_SOBELROW_SSE2
#ifdef HAS_SOBELTOPLANEROW_SSE2
// Adds Sobel X and Sobel Y and stores Sobel into a plane.
void SobelToPlaneRow_SSE2(const uint8_t* src_sobelx,
const uint8_t* src_sobely,
uint8_t* dst_y,
int width) {
asm volatile(
"sub %0,%1 \n"
"pcmpeqb %%xmm5,%%xmm5 \n"
"pslld $0x18,%%xmm5 \n"
// 8 pixel loop.
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"movdqu 0x00(%0,%1,1),%%xmm1 \n"
"lea 0x10(%0),%0 \n"
"paddusb %%xmm1,%%xmm0 \n"
"movdqu %%xmm0,(%2) \n"
"lea 0x10(%2),%2 \n"
"sub $0x10,%3 \n"
"jg 1b \n"
: "+r"(src_sobelx), // %0
"+r"(src_sobely), // %1
"+r"(dst_y), // %2
"+r"(width) // %3
:
: "memory", "cc", "xmm0", "xmm1");
}
#endif // HAS_SOBELTOPLANEROW_SSE2
#ifdef HAS_SOBELXYROW_SSE2
// Mixes Sobel X, Sobel Y and Sobel into ARGB.
// A = 255
// R = Sobel X
// G = Sobel
// B = Sobel Y
void SobelXYRow_SSE2(const uint8_t* src_sobelx,
const uint8_t* src_sobely,
uint8_t* dst_argb,
int width) {
asm volatile(
"sub %0,%1 \n"
"pcmpeqb %%xmm5,%%xmm5 \n"
// 8 pixel loop.
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"movdqu 0x00(%0,%1,1),%%xmm1 \n"
"lea 0x10(%0),%0 \n"
"movdqa %%xmm0,%%xmm2 \n"
"paddusb %%xmm1,%%xmm2 \n"
"movdqa %%xmm0,%%xmm3 \n"
"punpcklbw %%xmm5,%%xmm3 \n"
"punpckhbw %%xmm5,%%xmm0 \n"
"movdqa %%xmm1,%%xmm4 \n"
"punpcklbw %%xmm2,%%xmm4 \n"
"punpckhbw %%xmm2,%%xmm1 \n"
"movdqa %%xmm4,%%xmm6 \n"
"punpcklwd %%xmm3,%%xmm6 \n"
"punpckhwd %%xmm3,%%xmm4 \n"
"movdqa %%xmm1,%%xmm7 \n"
"punpcklwd %%xmm0,%%xmm7 \n"
"punpckhwd %%xmm0,%%xmm1 \n"
"movdqu %%xmm6,(%2) \n"
"movdqu %%xmm4,0x10(%2) \n"
"movdqu %%xmm7,0x20(%2) \n"
"movdqu %%xmm1,0x30(%2) \n"
"lea 0x40(%2),%2 \n"
"sub $0x10,%3 \n"
"jg 1b \n"
: "+r"(src_sobelx), // %0
"+r"(src_sobely), // %1
"+r"(dst_argb), // %2
"+r"(width) // %3
:
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6",
"xmm7");
}
#endif // HAS_SOBELXYROW_SSE2
#ifdef HAS_COMPUTECUMULATIVESUMROW_SSE2
// Creates a table of cumulative sums where each value is a sum of all values
// above and to the left of the value, inclusive of the value.
void ComputeCumulativeSumRow_SSE2(const uint8_t* row,
int32_t* cumsum,
const int32_t* previous_cumsum,
int width) {
asm volatile(
"pxor %%xmm0,%%xmm0 \n"
"pxor %%xmm1,%%xmm1 \n"
"sub $0x4,%3 \n"
"jl 49f \n"
"test $0xf,%1 \n"
"jne 49f \n"
// 4 pixel loop.
LABELALIGN
"40: \n"
"movdqu (%0),%%xmm2 \n"
"lea 0x10(%0),%0 \n"
"movdqa %%xmm2,%%xmm4 \n"
"punpcklbw %%xmm1,%%xmm2 \n"
"movdqa %%xmm2,%%xmm3 \n"
"punpcklwd %%xmm1,%%xmm2 \n"
"punpckhwd %%xmm1,%%xmm3 \n"
"punpckhbw %%xmm1,%%xmm4 \n"
"movdqa %%xmm4,%%xmm5 \n"
"punpcklwd %%xmm1,%%xmm4 \n"
"punpckhwd %%xmm1,%%xmm5 \n"
"paddd %%xmm2,%%xmm0 \n"
"movdqu (%2),%%xmm2 \n"
"paddd %%xmm0,%%xmm2 \n"
"paddd %%xmm3,%%xmm0 \n"
"movdqu 0x10(%2),%%xmm3 \n"
"paddd %%xmm0,%%xmm3 \n"
"paddd %%xmm4,%%xmm0 \n"
"movdqu 0x20(%2),%%xmm4 \n"
"paddd %%xmm0,%%xmm4 \n"
"paddd %%xmm5,%%xmm0 \n"
"movdqu 0x30(%2),%%xmm5 \n"
"lea 0x40(%2),%2 \n"
"paddd %%xmm0,%%xmm5 \n"
"movdqu %%xmm2,(%1) \n"
"movdqu %%xmm3,0x10(%1) \n"
"movdqu %%xmm4,0x20(%1) \n"
"movdqu %%xmm5,0x30(%1) \n"
"lea 0x40(%1),%1 \n"
"sub $0x4,%3 \n"
"jge 40b \n"
"49: \n"
"add $0x3,%3 \n"
"jl 19f \n"
// 1 pixel loop.
LABELALIGN
"10: \n"
"movd (%0),%%xmm2 \n"
"lea 0x4(%0),%0 \n"
"punpcklbw %%xmm1,%%xmm2 \n"
"punpcklwd %%xmm1,%%xmm2 \n"
"paddd %%xmm2,%%xmm0 \n"
"movdqu (%2),%%xmm2 \n"
"lea 0x10(%2),%2 \n"
"paddd %%xmm0,%%xmm2 \n"
"movdqu %%xmm2,(%1) \n"
"lea 0x10(%1),%1 \n"
"sub $0x1,%3 \n"
"jge 10b \n"
"19: \n"
: "+r"(row), // %0
"+r"(cumsum), // %1
"+r"(previous_cumsum), // %2
"+r"(width) // %3
:
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5");
}
#endif // HAS_COMPUTECUMULATIVESUMROW_SSE2
#ifdef HAS_CUMULATIVESUMTOAVERAGEROW_SSE2
void CumulativeSumToAverageRow_SSE2(const int32_t* topleft,
const int32_t* botleft,
int width,
int area,
uint8_t* dst,
int count) {
asm volatile(
"movd %5,%%xmm5 \n"
"cvtdq2ps %%xmm5,%%xmm5 \n"
"rcpss %%xmm5,%%xmm4 \n"
"pshufd $0x0,%%xmm4,%%xmm4 \n"
"sub $0x4,%3 \n"
"jl 49f \n"
"cmpl $0x80,%5 \n"
"ja 40f \n"
"pshufd $0x0,%%xmm5,%%xmm5 \n"
"pcmpeqb %%xmm6,%%xmm6 \n"
"psrld $0x10,%%xmm6 \n"
"cvtdq2ps %%xmm6,%%xmm6 \n"
"addps %%xmm6,%%xmm5 \n"
"mulps %%xmm4,%%xmm5 \n"
"cvtps2dq %%xmm5,%%xmm5 \n"
"packssdw %%xmm5,%%xmm5 \n"
// 4 pixel small loop.
LABELALIGN
"4: \n"
"movdqu (%0),%%xmm0 \n"
"movdqu 0x10(%0),%%xmm1 \n"
"movdqu 0x20(%0),%%xmm2 \n"
"movdqu 0x30(%0),%%xmm3 \n"
"psubd 0x00(%0,%4,4),%%xmm0 \n"
"psubd 0x10(%0,%4,4),%%xmm1 \n"
"psubd 0x20(%0,%4,4),%%xmm2 \n"
"psubd 0x30(%0,%4,4),%%xmm3 \n"
"lea 0x40(%0),%0 \n"
"psubd (%1),%%xmm0 \n"
"psubd 0x10(%1),%%xmm1 \n"
"psubd 0x20(%1),%%xmm2 \n"
"psubd 0x30(%1),%%xmm3 \n"
"paddd 0x00(%1,%4,4),%%xmm0 \n"
"paddd 0x10(%1,%4,4),%%xmm1 \n"
"paddd 0x20(%1,%4,4),%%xmm2 \n"
"paddd 0x30(%1,%4,4),%%xmm3 \n"
"lea 0x40(%1),%1 \n"
"packssdw %%xmm1,%%xmm0 \n"
"packssdw %%xmm3,%%xmm2 \n"
"pmulhuw %%xmm5,%%xmm0 \n"
"pmulhuw %%xmm5,%%xmm2 \n"
"packuswb %%xmm2,%%xmm0 \n"
"movdqu %%xmm0,(%2) \n"
"lea 0x10(%2),%2 \n"
"sub $0x4,%3 \n"
"jge 4b \n"
"jmp 49f \n"
// 4 pixel loop
LABELALIGN
"40: \n"
"movdqu (%0),%%xmm0 \n"
"movdqu 0x10(%0),%%xmm1 \n"
"movdqu 0x20(%0),%%xmm2 \n"
"movdqu 0x30(%0),%%xmm3 \n"
"psubd 0x00(%0,%4,4),%%xmm0 \n"
"psubd 0x10(%0,%4,4),%%xmm1 \n"
"psubd 0x20(%0,%4,4),%%xmm2 \n"
"psubd 0x30(%0,%4,4),%%xmm3 \n"
"lea 0x40(%0),%0 \n"
"psubd (%1),%%xmm0 \n"
"psubd 0x10(%1),%%xmm1 \n"
"psubd 0x20(%1),%%xmm2 \n"
"psubd 0x30(%1),%%xmm3 \n"
"paddd 0x00(%1,%4,4),%%xmm0 \n"
"paddd 0x10(%1,%4,4),%%xmm1 \n"
"paddd 0x20(%1,%4,4),%%xmm2 \n"
"paddd 0x30(%1,%4,4),%%xmm3 \n"
"lea 0x40(%1),%1 \n"
"cvtdq2ps %%xmm0,%%xmm0 \n"
"cvtdq2ps %%xmm1,%%xmm1 \n"
"mulps %%xmm4,%%xmm0 \n"
"mulps %%xmm4,%%xmm1 \n"
"cvtdq2ps %%xmm2,%%xmm2 \n"
"cvtdq2ps %%xmm3,%%xmm3 \n"
"mulps %%xmm4,%%xmm2 \n"
"mulps %%xmm4,%%xmm3 \n"
"cvtps2dq %%xmm0,%%xmm0 \n"
"cvtps2dq %%xmm1,%%xmm1 \n"
"cvtps2dq %%xmm2,%%xmm2 \n"
"cvtps2dq %%xmm3,%%xmm3 \n"
"packssdw %%xmm1,%%xmm0 \n"
"packssdw %%xmm3,%%xmm2 \n"
"packuswb %%xmm2,%%xmm0 \n"
"movdqu %%xmm0,(%2) \n"
"lea 0x10(%2),%2 \n"
"sub $0x4,%3 \n"
"jge 40b \n"
"49: \n"
"add $0x3,%3 \n"
"jl 19f \n"
// 1 pixel loop
LABELALIGN
"10: \n"
"movdqu (%0),%%xmm0 \n"
"psubd 0x00(%0,%4,4),%%xmm0 \n"
"lea 0x10(%0),%0 \n"
"psubd (%1),%%xmm0 \n"
"paddd 0x00(%1,%4,4),%%xmm0 \n"
"lea 0x10(%1),%1 \n"
"cvtdq2ps %%xmm0,%%xmm0 \n"
"mulps %%xmm4,%%xmm0 \n"
"cvtps2dq %%xmm0,%%xmm0 \n"
"packssdw %%xmm0,%%xmm0 \n"
"packuswb %%xmm0,%%xmm0 \n"
"movd %%xmm0,(%2) \n"
"lea 0x4(%2),%2 \n"
"sub $0x1,%3 \n"
"jge 10b \n"
"19: \n"
: "+r"(topleft), // %0
"+r"(botleft), // %1
"+r"(dst), // %2
"+rm"(count) // %3
: "r"((intptr_t)(width)), // %4
"rm"(area) // %5
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6");
}
#endif // HAS_CUMULATIVESUMTOAVERAGEROW_SSE2
#ifdef HAS_ARGBAFFINEROW_SSE2
// Copy ARGB pixels from source image with slope to a row of destination.
LIBYUV_API
void ARGBAffineRow_SSE2(const uint8_t* src_argb,
int src_argb_stride,
uint8_t* dst_argb,
const float* src_dudv,
int width) {
intptr_t src_argb_stride_temp = src_argb_stride;
intptr_t temp;
asm volatile(
"movq (%3),%%xmm2 \n"
"movq 0x08(%3),%%xmm7 \n"
"shl $0x10,%1 \n"
"add $0x4,%1 \n"
"movd %1,%%xmm5 \n"
"sub $0x4,%4 \n"
"jl 49f \n"
"pshufd $0x44,%%xmm7,%%xmm7 \n"
"pshufd $0x0,%%xmm5,%%xmm5 \n"
"movdqa %%xmm2,%%xmm0 \n"
"addps %%xmm7,%%xmm0 \n"
"movlhps %%xmm0,%%xmm2 \n"
"movdqa %%xmm7,%%xmm4 \n"
"addps %%xmm4,%%xmm4 \n"
"movdqa %%xmm2,%%xmm3 \n"
"addps %%xmm4,%%xmm3 \n"
"addps %%xmm4,%%xmm4 \n"
// 4 pixel loop
LABELALIGN
"40: \n"
"cvttps2dq %%xmm2,%%xmm0 \n" // x,y float->int first 2
"cvttps2dq %%xmm3,%%xmm1 \n" // x,y float->int next 2
"packssdw %%xmm1,%%xmm0 \n" // x, y as 8 shorts
"pmaddwd %%xmm5,%%xmm0 \n" // off = x*4 + y*stride
"movd %%xmm0,%k1 \n"
"pshufd $0x39,%%xmm0,%%xmm0 \n"
"movd %%xmm0,%k5 \n"
"pshufd $0x39,%%xmm0,%%xmm0 \n"
"movd 0x00(%0,%1,1),%%xmm1 \n"
"movd 0x00(%0,%5,1),%%xmm6 \n"
"punpckldq %%xmm6,%%xmm1 \n"
"addps %%xmm4,%%xmm2 \n"
"movq %%xmm1,(%2) \n"
"movd %%xmm0,%k1 \n"
"pshufd $0x39,%%xmm0,%%xmm0 \n"
"movd %%xmm0,%k5 \n"
"movd 0x00(%0,%1,1),%%xmm0 \n"
"movd 0x00(%0,%5,1),%%xmm6 \n"
"punpckldq %%xmm6,%%xmm0 \n"
"addps %%xmm4,%%xmm3 \n"
"movq %%xmm0,0x08(%2) \n"
"lea 0x10(%2),%2 \n"
"sub $0x4,%4 \n"
"jge 40b \n"
"49: \n"
"add $0x3,%4 \n"
"jl 19f \n"
// 1 pixel loop
LABELALIGN
"10: \n"
"cvttps2dq %%xmm2,%%xmm0 \n"
"packssdw %%xmm0,%%xmm0 \n"
"pmaddwd %%xmm5,%%xmm0 \n"
"addps %%xmm7,%%xmm2 \n"
"movd %%xmm0,%k1 \n"
"movd 0x00(%0,%1,1),%%xmm0 \n"
"movd %%xmm0,(%2) \n"
"lea 0x04(%2),%2 \n"
"sub $0x1,%4 \n"
"jge 10b \n"
"19: \n"
: "+r"(src_argb), // %0
"+r"(src_argb_stride_temp), // %1
"+r"(dst_argb), // %2
"+r"(src_dudv), // %3
"+rm"(width), // %4
"=&r"(temp) // %5
:
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6",
"xmm7");
}
#endif // HAS_ARGBAFFINEROW_SSE2
#ifdef HAS_INTERPOLATEROW_SSSE3
// Bilinear filter 16x2 -> 16x1
void InterpolateRow_SSSE3(uint8_t* dst_ptr,
const uint8_t* src_ptr,
ptrdiff_t src_stride,
int dst_width,
int source_y_fraction) {
asm volatile(
"sub %1,%0 \n"
"cmp $0x0,%3 \n"
"je 100f \n"
"cmp $0x80,%3 \n"
"je 50f \n"
"movd %3,%%xmm0 \n"
"neg %3 \n"
"add $0x100,%3 \n"
"movd %3,%%xmm5 \n"
"punpcklbw %%xmm0,%%xmm5 \n"
"punpcklwd %%xmm5,%%xmm5 \n"
"pshufd $0x0,%%xmm5,%%xmm5 \n"
"mov $0x80808080,%%eax \n"
"movd %%eax,%%xmm4 \n"
"pshufd $0x0,%%xmm4,%%xmm4 \n"
// General purpose row blend.
LABELALIGN
"1: \n"
"movdqu (%1),%%xmm0 \n"
"movdqu 0x00(%1,%4,1),%%xmm2 \n"
"movdqa %%xmm0,%%xmm1 \n"
"punpcklbw %%xmm2,%%xmm0 \n"
"punpckhbw %%xmm2,%%xmm1 \n"
"psubb %%xmm4,%%xmm0 \n"
"psubb %%xmm4,%%xmm1 \n"
"movdqa %%xmm5,%%xmm2 \n"
"movdqa %%xmm5,%%xmm3 \n"
"pmaddubsw %%xmm0,%%xmm2 \n"
"pmaddubsw %%xmm1,%%xmm3 \n"
"paddw %%xmm4,%%xmm2 \n"
"paddw %%xmm4,%%xmm3 \n"
"psrlw $0x8,%%xmm2 \n"
"psrlw $0x8,%%xmm3 \n"
"packuswb %%xmm3,%%xmm2 \n"
"movdqu %%xmm2,0x00(%1,%0,1) \n"
"lea 0x10(%1),%1 \n"
"sub $0x10,%2 \n"
"jg 1b \n"
"jmp 99f \n"
// Blend 50 / 50.
LABELALIGN
"50: \n"
"movdqu (%1),%%xmm0 \n"
"movdqu 0x00(%1,%4,1),%%xmm1 \n"
"pavgb %%xmm1,%%xmm0 \n"
"movdqu %%xmm0,0x00(%1,%0,1) \n"
"lea 0x10(%1),%1 \n"
"sub $0x10,%2 \n"
"jg 50b \n"
"jmp 99f \n"
// Blend 100 / 0 - Copy row unchanged.
LABELALIGN
"100: \n"
"movdqu (%1),%%xmm0 \n"
"movdqu %%xmm0,0x00(%1,%0,1) \n"
"lea 0x10(%1),%1 \n"
"sub $0x10,%2 \n"
"jg 100b \n"
"99: \n"
: "+r"(dst_ptr), // %0
"+r"(src_ptr), // %1
"+rm"(dst_width), // %2
"+r"(source_y_fraction) // %3
: "r"((intptr_t)(src_stride)) // %4
: "memory", "cc", "eax", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5");
}
#endif // HAS_INTERPOLATEROW_SSSE3
#ifdef HAS_INTERPOLATEROW_AVX2
// Bilinear filter 32x2 -> 32x1
void InterpolateRow_AVX2(uint8_t* dst_ptr,
const uint8_t* src_ptr,
ptrdiff_t src_stride,
int dst_width,
int source_y_fraction) {
asm volatile(
"cmp $0x0,%3 \n"
"je 100f \n"
"sub %1,%0 \n"
"cmp $0x80,%3 \n"
"je 50f \n"
"vmovd %3,%%xmm0 \n"
"neg %3 \n"
"add $0x100,%3 \n"
"vmovd %3,%%xmm5 \n"
"vpunpcklbw %%xmm0,%%xmm5,%%xmm5 \n"
"vpunpcklwd %%xmm5,%%xmm5,%%xmm5 \n"
"vbroadcastss %%xmm5,%%ymm5 \n"
"mov $0x80808080,%%eax \n"
"vmovd %%eax,%%xmm4 \n"
"vbroadcastss %%xmm4,%%ymm4 \n"
// General purpose row blend.
LABELALIGN
"1: \n"
"vmovdqu (%1),%%ymm0 \n"
"vmovdqu 0x00(%1,%4,1),%%ymm2 \n"
"vpunpckhbw %%ymm2,%%ymm0,%%ymm1 \n"
"vpunpcklbw %%ymm2,%%ymm0,%%ymm0 \n"
"vpsubb %%ymm4,%%ymm1,%%ymm1 \n"
"vpsubb %%ymm4,%%ymm0,%%ymm0 \n"
"vpmaddubsw %%ymm1,%%ymm5,%%ymm1 \n"
"vpmaddubsw %%ymm0,%%ymm5,%%ymm0 \n"
"vpaddw %%ymm4,%%ymm1,%%ymm1 \n"
"vpaddw %%ymm4,%%ymm0,%%ymm0 \n"
"vpsrlw $0x8,%%ymm1,%%ymm1 \n"
"vpsrlw $0x8,%%ymm0,%%ymm0 \n"
"vpackuswb %%ymm1,%%ymm0,%%ymm0 \n"
"vmovdqu %%ymm0,0x00(%1,%0,1) \n"
"lea 0x20(%1),%1 \n"
"sub $0x20,%2 \n"
"jg 1b \n"
"jmp 99f \n"
// Blend 50 / 50.
LABELALIGN
"50: \n"
"vmovdqu (%1),%%ymm0 \n"
"vpavgb 0x00(%1,%4,1),%%ymm0,%%ymm0 \n"
"vmovdqu %%ymm0,0x00(%1,%0,1) \n"
"lea 0x20(%1),%1 \n"
"sub $0x20,%2 \n"
"jg 50b \n"
"jmp 99f \n"
// Blend 100 / 0 - Copy row unchanged.
LABELALIGN
"100: \n"
"rep movsb \n"
"jmp 999f \n"
"99: \n"
"vzeroupper \n"
"999: \n"
: "+D"(dst_ptr), // %0
"+S"(src_ptr), // %1
"+cm"(dst_width), // %2
"+r"(source_y_fraction) // %3
: "r"((intptr_t)(src_stride)) // %4
: "memory", "cc", "eax", "xmm0", "xmm1", "xmm2", "xmm4", "xmm5");
}
#endif // HAS_INTERPOLATEROW_AVX2
#ifdef HAS_ARGBSHUFFLEROW_SSSE3
// For BGRAToARGB, ABGRToARGB, RGBAToARGB, and ARGBToRGBA.
void ARGBShuffleRow_SSSE3(const uint8_t* src_argb,
uint8_t* dst_argb,
const uint8_t* shuffler,
int width) {
asm volatile(
"movdqu (%3),%%xmm5 \n"
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"movdqu 0x10(%0),%%xmm1 \n"
"lea 0x20(%0),%0 \n"
"pshufb %%xmm5,%%xmm0 \n"
"pshufb %%xmm5,%%xmm1 \n"
"movdqu %%xmm0,(%1) \n"
"movdqu %%xmm1,0x10(%1) \n"
"lea 0x20(%1),%1 \n"
"sub $0x8,%2 \n"
"jg 1b \n"
: "+r"(src_argb), // %0
"+r"(dst_argb), // %1
"+r"(width) // %2
: "r"(shuffler) // %3
: "memory", "cc", "xmm0", "xmm1", "xmm5");
}
#endif // HAS_ARGBSHUFFLEROW_SSSE3
#ifdef HAS_ARGBSHUFFLEROW_AVX2
// For BGRAToARGB, ABGRToARGB, RGBAToARGB, and ARGBToRGBA.
void ARGBShuffleRow_AVX2(const uint8_t* src_argb,
uint8_t* dst_argb,
const uint8_t* shuffler,
int width) {
asm volatile(
"vbroadcastf128 (%3),%%ymm5 \n"
LABELALIGN
"1: \n"
"vmovdqu (%0),%%ymm0 \n"
"vmovdqu 0x20(%0),%%ymm1 \n"
"lea 0x40(%0),%0 \n"
"vpshufb %%ymm5,%%ymm0,%%ymm0 \n"
"vpshufb %%ymm5,%%ymm1,%%ymm1 \n"
"vmovdqu %%ymm0,(%1) \n"
"vmovdqu %%ymm1,0x20(%1) \n"
"lea 0x40(%1),%1 \n"
"sub $0x10,%2 \n"
"jg 1b \n"
"vzeroupper \n"
: "+r"(src_argb), // %0
"+r"(dst_argb), // %1
"+r"(width) // %2
: "r"(shuffler) // %3
: "memory", "cc", "xmm0", "xmm1", "xmm5");
}
#endif // HAS_ARGBSHUFFLEROW_AVX2
#ifdef HAS_I422TOYUY2ROW_SSE2
void I422ToYUY2Row_SSE2(const uint8_t* src_y,
const uint8_t* src_u,
const uint8_t* src_v,
uint8_t* dst_yuy2,
int width) {
asm volatile(
"sub %1,%2 \n"
LABELALIGN
"1: \n"
"movq (%1),%%xmm2 \n"
"movq 0x00(%1,%2,1),%%xmm1 \n"
"add $0x8,%1 \n"
"punpcklbw %%xmm1,%%xmm2 \n"
"movdqu (%0),%%xmm0 \n"
"add $0x10,%0 \n"
"movdqa %%xmm0,%%xmm1 \n"
"punpcklbw %%xmm2,%%xmm0 \n"
"punpckhbw %%xmm2,%%xmm1 \n"
"movdqu %%xmm0,(%3) \n"
"movdqu %%xmm1,0x10(%3) \n"
"lea 0x20(%3),%3 \n"
"sub $0x10,%4 \n"
"jg 1b \n"
: "+r"(src_y), // %0
"+r"(src_u), // %1
"+r"(src_v), // %2
"+r"(dst_yuy2), // %3
"+rm"(width) // %4
:
: "memory", "cc", "xmm0", "xmm1", "xmm2");
}
#endif // HAS_I422TOYUY2ROW_SSE2
#ifdef HAS_I422TOUYVYROW_SSE2
void I422ToUYVYRow_SSE2(const uint8_t* src_y,
const uint8_t* src_u,
const uint8_t* src_v,
uint8_t* dst_uyvy,
int width) {
asm volatile(
"sub %1,%2 \n"
LABELALIGN
"1: \n"
"movq (%1),%%xmm2 \n"
"movq 0x00(%1,%2,1),%%xmm1 \n"
"add $0x8,%1 \n"
"punpcklbw %%xmm1,%%xmm2 \n"
"movdqu (%0),%%xmm0 \n"
"movdqa %%xmm2,%%xmm1 \n"
"add $0x10,%0 \n"
"punpcklbw %%xmm0,%%xmm1 \n"
"punpckhbw %%xmm0,%%xmm2 \n"
"movdqu %%xmm1,(%3) \n"
"movdqu %%xmm2,0x10(%3) \n"
"lea 0x20(%3),%3 \n"
"sub $0x10,%4 \n"
"jg 1b \n"
: "+r"(src_y), // %0
"+r"(src_u), // %1
"+r"(src_v), // %2
"+r"(dst_uyvy), // %3
"+rm"(width) // %4
:
: "memory", "cc", "xmm0", "xmm1", "xmm2");
}
#endif // HAS_I422TOUYVYROW_SSE2
#ifdef HAS_I422TOYUY2ROW_AVX2
void I422ToYUY2Row_AVX2(const uint8_t* src_y,
const uint8_t* src_u,
const uint8_t* src_v,
uint8_t* dst_yuy2,
int width) {
asm volatile(
"sub %1,%2 \n"
LABELALIGN
"1: \n"
"vpmovzxbw (%1),%%ymm1 \n"
"vpmovzxbw 0x00(%1,%2,1),%%ymm2 \n"
"add $0x10,%1 \n"
"vpsllw $0x8,%%ymm2,%%ymm2 \n"
"vpor %%ymm1,%%ymm2,%%ymm2 \n"
"vmovdqu (%0),%%ymm0 \n"
"add $0x20,%0 \n"
"vpunpcklbw %%ymm2,%%ymm0,%%ymm1 \n"
"vpunpckhbw %%ymm2,%%ymm0,%%ymm2 \n"
"vextractf128 $0x0,%%ymm1,(%3) \n"
"vextractf128 $0x0,%%ymm2,0x10(%3) \n"
"vextractf128 $0x1,%%ymm1,0x20(%3) \n"
"vextractf128 $0x1,%%ymm2,0x30(%3) \n"
"lea 0x40(%3),%3 \n"
"sub $0x20,%4 \n"
"jg 1b \n"
"vzeroupper \n"
: "+r"(src_y), // %0
"+r"(src_u), // %1
"+r"(src_v), // %2
"+r"(dst_yuy2), // %3
"+rm"(width) // %4
:
: "memory", "cc", "xmm0", "xmm1", "xmm2");
}
#endif // HAS_I422TOYUY2ROW_AVX2
#ifdef HAS_I422TOUYVYROW_AVX2
void I422ToUYVYRow_AVX2(const uint8_t* src_y,
const uint8_t* src_u,
const uint8_t* src_v,
uint8_t* dst_uyvy,
int width) {
asm volatile(
"sub %1,%2 \n"
LABELALIGN
"1: \n"
"vpmovzxbw (%1),%%ymm1 \n"
"vpmovzxbw 0x00(%1,%2,1),%%ymm2 \n"
"add $0x10,%1 \n"
"vpsllw $0x8,%%ymm2,%%ymm2 \n"
"vpor %%ymm1,%%ymm2,%%ymm2 \n"
"vmovdqu (%0),%%ymm0 \n"
"add $0x20,%0 \n"
"vpunpcklbw %%ymm0,%%ymm2,%%ymm1 \n"
"vpunpckhbw %%ymm0,%%ymm2,%%ymm2 \n"
"vextractf128 $0x0,%%ymm1,(%3) \n"
"vextractf128 $0x0,%%ymm2,0x10(%3) \n"
"vextractf128 $0x1,%%ymm1,0x20(%3) \n"
"vextractf128 $0x1,%%ymm2,0x30(%3) \n"
"lea 0x40(%3),%3 \n"
"sub $0x20,%4 \n"
"jg 1b \n"
"vzeroupper \n"
: "+r"(src_y), // %0
"+r"(src_u), // %1
"+r"(src_v), // %2
"+r"(dst_uyvy), // %3
"+rm"(width) // %4
:
: "memory", "cc", "xmm0", "xmm1", "xmm2");
}
#endif // HAS_I422TOUYVYROW_AVX2
#ifdef HAS_ARGBPOLYNOMIALROW_SSE2
void ARGBPolynomialRow_SSE2(const uint8_t* src_argb,
uint8_t* dst_argb,
const float* poly,
int width) {
asm volatile(
"pxor %%xmm3,%%xmm3 \n"
// 2 pixel loop.
LABELALIGN
"1: \n"
"movq (%0),%%xmm0 \n"
"lea 0x8(%0),%0 \n"
"punpcklbw %%xmm3,%%xmm0 \n"
"movdqa %%xmm0,%%xmm4 \n"
"punpcklwd %%xmm3,%%xmm0 \n"
"punpckhwd %%xmm3,%%xmm4 \n"
"cvtdq2ps %%xmm0,%%xmm0 \n"
"cvtdq2ps %%xmm4,%%xmm4 \n"
"movdqa %%xmm0,%%xmm1 \n"
"movdqa %%xmm4,%%xmm5 \n"
"mulps 0x10(%3),%%xmm0 \n"
"mulps 0x10(%3),%%xmm4 \n"
"addps (%3),%%xmm0 \n"
"addps (%3),%%xmm4 \n"
"movdqa %%xmm1,%%xmm2 \n"
"movdqa %%xmm5,%%xmm6 \n"
"mulps %%xmm1,%%xmm2 \n"
"mulps %%xmm5,%%xmm6 \n"
"mulps %%xmm2,%%xmm1 \n"
"mulps %%xmm6,%%xmm5 \n"
"mulps 0x20(%3),%%xmm2 \n"
"mulps 0x20(%3),%%xmm6 \n"
"mulps 0x30(%3),%%xmm1 \n"
"mulps 0x30(%3),%%xmm5 \n"
"addps %%xmm2,%%xmm0 \n"
"addps %%xmm6,%%xmm4 \n"
"addps %%xmm1,%%xmm0 \n"
"addps %%xmm5,%%xmm4 \n"
"cvttps2dq %%xmm0,%%xmm0 \n"
"cvttps2dq %%xmm4,%%xmm4 \n"
"packuswb %%xmm4,%%xmm0 \n"
"packuswb %%xmm0,%%xmm0 \n"
"movq %%xmm0,(%1) \n"
"lea 0x8(%1),%1 \n"
"sub $0x2,%2 \n"
"jg 1b \n"
: "+r"(src_argb), // %0
"+r"(dst_argb), // %1
"+r"(width) // %2
: "r"(poly) // %3
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6");
}
#endif // HAS_ARGBPOLYNOMIALROW_SSE2
#ifdef HAS_ARGBPOLYNOMIALROW_AVX2
void ARGBPolynomialRow_AVX2(const uint8_t* src_argb,
uint8_t* dst_argb,
const float* poly,
int width) {
asm volatile(
"vbroadcastf128 (%3),%%ymm4 \n"
"vbroadcastf128 0x10(%3),%%ymm5 \n"
"vbroadcastf128 0x20(%3),%%ymm6 \n"
"vbroadcastf128 0x30(%3),%%ymm7 \n"
// 2 pixel loop.
LABELALIGN
"1: \n"
"vpmovzxbd (%0),%%ymm0 \n" // 2 ARGB pixels
"lea 0x8(%0),%0 \n"
"vcvtdq2ps %%ymm0,%%ymm0 \n" // X 8 floats
"vmulps %%ymm0,%%ymm0,%%ymm2 \n" // X * X
"vmulps %%ymm7,%%ymm0,%%ymm3 \n" // C3 * X
"vfmadd132ps %%ymm5,%%ymm4,%%ymm0 \n" // result = C0 + C1 * X
"vfmadd231ps %%ymm6,%%ymm2,%%ymm0 \n" // result += C2 * X * X
"vfmadd231ps %%ymm3,%%ymm2,%%ymm0 \n" // result += C3 * X * X *
// X
"vcvttps2dq %%ymm0,%%ymm0 \n"
"vpackusdw %%ymm0,%%ymm0,%%ymm0 \n"
"vpermq $0xd8,%%ymm0,%%ymm0 \n"
"vpackuswb %%xmm0,%%xmm0,%%xmm0 \n"
"vmovq %%xmm0,(%1) \n"
"lea 0x8(%1),%1 \n"
"sub $0x2,%2 \n"
"jg 1b \n"
"vzeroupper \n"
: "+r"(src_argb), // %0
"+r"(dst_argb), // %1
"+r"(width) // %2
: "r"(poly) // %3
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6",
"xmm7");
}
#endif // HAS_ARGBPOLYNOMIALROW_AVX2
#ifdef HAS_HALFFLOATROW_SSE2
static float kScaleBias = 1.9259299444e-34f;
void HalfFloatRow_SSE2(const uint16_t* src,
uint16_t* dst,
float scale,
int width) {
scale *= kScaleBias;
asm volatile(
"movd %3,%%xmm4 \n"
"pshufd $0x0,%%xmm4,%%xmm4 \n"
"pxor %%xmm5,%%xmm5 \n"
"sub %0,%1 \n"
// 16 pixel loop.
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm2 \n" // 8 shorts
"add $0x10,%0 \n"
"movdqa %%xmm2,%%xmm3 \n"
"punpcklwd %%xmm5,%%xmm2 \n" // 8 ints in xmm2/1
"cvtdq2ps %%xmm2,%%xmm2 \n" // 8 floats
"punpckhwd %%xmm5,%%xmm3 \n"
"cvtdq2ps %%xmm3,%%xmm3 \n"
"mulps %%xmm4,%%xmm2 \n"
"mulps %%xmm4,%%xmm3 \n"
"psrld $0xd,%%xmm2 \n"
"psrld $0xd,%%xmm3 \n"
"packssdw %%xmm3,%%xmm2 \n"
"movdqu %%xmm2,-0x10(%0,%1,1) \n"
"sub $0x8,%2 \n"
"jg 1b \n"
: "+r"(src), // %0
"+r"(dst), // %1
"+r"(width) // %2
: "m"(scale) // %3
: "memory", "cc", "xmm2", "xmm3", "xmm4", "xmm5");
}
#endif // HAS_HALFFLOATROW_SSE2
#ifdef HAS_HALFFLOATROW_AVX2
void HalfFloatRow_AVX2(const uint16_t* src,
uint16_t* dst,
float scale,
int width) {
scale *= kScaleBias;
asm volatile(
"vbroadcastss %3, %%ymm4 \n"
"vpxor %%ymm5,%%ymm5,%%ymm5 \n"
"sub %0,%1 \n"
// 16 pixel loop.
LABELALIGN
"1: \n"
"vmovdqu (%0),%%ymm2 \n" // 16 shorts
"add $0x20,%0 \n"
"vpunpckhwd %%ymm5,%%ymm2,%%ymm3 \n" // mutates
"vpunpcklwd %%ymm5,%%ymm2,%%ymm2 \n"
"vcvtdq2ps %%ymm3,%%ymm3 \n"
"vcvtdq2ps %%ymm2,%%ymm2 \n"
"vmulps %%ymm3,%%ymm4,%%ymm3 \n"
"vmulps %%ymm2,%%ymm4,%%ymm2 \n"
"vpsrld $0xd,%%ymm3,%%ymm3 \n"
"vpsrld $0xd,%%ymm2,%%ymm2 \n"
"vpackssdw %%ymm3, %%ymm2, %%ymm2 \n" // unmutates
"vmovdqu %%ymm2,-0x20(%0,%1,1) \n"
"sub $0x10,%2 \n"
"jg 1b \n"
"vzeroupper \n"
: "+r"(src), // %0
"+r"(dst), // %1
"+r"(width) // %2
#if defined(__x86_64__)
: "x"(scale) // %3
#else
: "m"(scale) // %3
#endif
: "memory", "cc", "xmm2", "xmm3", "xmm4", "xmm5");
}
#endif // HAS_HALFFLOATROW_AVX2
#ifdef HAS_HALFFLOATROW_F16C
void HalfFloatRow_F16C(const uint16_t* src,
uint16_t* dst,
float scale,
int width) {
asm volatile(
"vbroadcastss %3, %%ymm4 \n"
"sub %0,%1 \n"
// 16 pixel loop.
LABELALIGN
"1: \n"
"vpmovzxwd (%0),%%ymm2 \n" // 16 shorts -> 16 ints
"vpmovzxwd 0x10(%0),%%ymm3 \n"
"vcvtdq2ps %%ymm2,%%ymm2 \n"
"vcvtdq2ps %%ymm3,%%ymm3 \n"
"vmulps %%ymm2,%%ymm4,%%ymm2 \n"
"vmulps %%ymm3,%%ymm4,%%ymm3 \n"
"vcvtps2ph $3, %%ymm2, %%xmm2 \n"
"vcvtps2ph $3, %%ymm3, %%xmm3 \n"
"vmovdqu %%xmm2,0x00(%0,%1,1) \n"
"vmovdqu %%xmm3,0x10(%0,%1,1) \n"
"add $0x20,%0 \n"
"sub $0x10,%2 \n"
"jg 1b \n"
"vzeroupper \n"
: "+r"(src), // %0
"+r"(dst), // %1
"+r"(width) // %2
#if defined(__x86_64__)
: "x"(scale) // %3
#else
: "m"(scale) // %3
#endif
: "memory", "cc", "xmm2", "xmm3", "xmm4");
}
#endif // HAS_HALFFLOATROW_F16C
#ifdef HAS_HALFFLOATROW_F16C
void HalfFloat1Row_F16C(const uint16_t* src, uint16_t* dst, float, int width) {
asm volatile(
"sub %0,%1 \n"
// 16 pixel loop.
LABELALIGN
"1: \n"
"vpmovzxwd (%0),%%ymm2 \n" // 16 shorts -> 16 ints
"vpmovzxwd 0x10(%0),%%ymm3 \n"
"vcvtdq2ps %%ymm2,%%ymm2 \n"
"vcvtdq2ps %%ymm3,%%ymm3 \n"
"vcvtps2ph $3, %%ymm2, %%xmm2 \n"
"vcvtps2ph $3, %%ymm3, %%xmm3 \n"
"vmovdqu %%xmm2,0x00(%0,%1,1) \n"
"vmovdqu %%xmm3,0x10(%0,%1,1) \n"
"add $0x20,%0 \n"
"sub $0x10,%2 \n"
"jg 1b \n"
"vzeroupper \n"
: "+r"(src), // %0
"+r"(dst), // %1
"+r"(width) // %2
:
: "memory", "cc", "xmm2", "xmm3");
}
#endif // HAS_HALFFLOATROW_F16C
#ifdef HAS_ARGBCOLORTABLEROW_X86
// Tranform ARGB pixels with color table.
void ARGBColorTableRow_X86(uint8_t* dst_argb,
const uint8_t* table_argb,
int width) {
uintptr_t pixel_temp;
asm volatile(
// 1 pixel loop.
LABELALIGN
"1: \n"
"movzb (%0),%1 \n"
"lea 0x4(%0),%0 \n"
"movzb 0x00(%3,%1,4),%1 \n"
"mov %b1,-0x4(%0) \n"
"movzb -0x3(%0),%1 \n"
"movzb 0x01(%3,%1,4),%1 \n"
"mov %b1,-0x3(%0) \n"
"movzb -0x2(%0),%1 \n"
"movzb 0x02(%3,%1,4),%1 \n"
"mov %b1,-0x2(%0) \n"
"movzb -0x1(%0),%1 \n"
"movzb 0x03(%3,%1,4),%1 \n"
"mov %b1,-0x1(%0) \n"
"dec %2 \n"
"jg 1b \n"
: "+r"(dst_argb), // %0
"=&d"(pixel_temp), // %1
"+r"(width) // %2
: "r"(table_argb) // %3
: "memory", "cc");
}
#endif // HAS_ARGBCOLORTABLEROW_X86
#ifdef HAS_RGBCOLORTABLEROW_X86
// Tranform RGB pixels with color table.
void RGBColorTableRow_X86(uint8_t* dst_argb,
const uint8_t* table_argb,
int width) {
uintptr_t pixel_temp;
asm volatile(
// 1 pixel loop.
LABELALIGN
"1: \n"
"movzb (%0),%1 \n"
"lea 0x4(%0),%0 \n"
"movzb 0x00(%3,%1,4),%1 \n"
"mov %b1,-0x4(%0) \n"
"movzb -0x3(%0),%1 \n"
"movzb 0x01(%3,%1,4),%1 \n"
"mov %b1,-0x3(%0) \n"
"movzb -0x2(%0),%1 \n"
"movzb 0x02(%3,%1,4),%1 \n"
"mov %b1,-0x2(%0) \n"
"dec %2 \n"
"jg 1b \n"
: "+r"(dst_argb), // %0
"=&d"(pixel_temp), // %1
"+r"(width) // %2
: "r"(table_argb) // %3
: "memory", "cc");
}
#endif // HAS_RGBCOLORTABLEROW_X86
#ifdef HAS_ARGBLUMACOLORTABLEROW_SSSE3
// Tranform RGB pixels with luma table.
void ARGBLumaColorTableRow_SSSE3(const uint8_t* src_argb,
uint8_t* dst_argb,
int width,
const uint8_t* luma,
uint32_t lumacoeff) {
uintptr_t pixel_temp;
uintptr_t table_temp;
asm volatile(
"movd %6,%%xmm3 \n"
"pshufd $0x0,%%xmm3,%%xmm3 \n"
"pcmpeqb %%xmm4,%%xmm4 \n"
"psllw $0x8,%%xmm4 \n"
"pxor %%xmm5,%%xmm5 \n"
// 4 pixel loop.
LABELALIGN
"1: \n"
"movdqu (%2),%%xmm0 \n"
"pmaddubsw %%xmm3,%%xmm0 \n"
"phaddw %%xmm0,%%xmm0 \n"
"pand %%xmm4,%%xmm0 \n"
"punpcklwd %%xmm5,%%xmm0 \n"
"movd %%xmm0,%k1 \n" // 32 bit offset
"add %5,%1 \n"
"pshufd $0x39,%%xmm0,%%xmm0 \n"
"movzb (%2),%0 \n"
"movzb 0x00(%1,%0,1),%0 \n"
"mov %b0,(%3) \n"
"movzb 0x1(%2),%0 \n"
"movzb 0x00(%1,%0,1),%0 \n"
"mov %b0,0x1(%3) \n"
"movzb 0x2(%2),%0 \n"
"movzb 0x00(%1,%0,1),%0 \n"
"mov %b0,0x2(%3) \n"
"movzb 0x3(%2),%0 \n"
"mov %b0,0x3(%3) \n"
"movd %%xmm0,%k1 \n" // 32 bit offset
"add %5,%1 \n"
"pshufd $0x39,%%xmm0,%%xmm0 \n"
"movzb 0x4(%2),%0 \n"
"movzb 0x00(%1,%0,1),%0 \n"
"mov %b0,0x4(%3) \n"
"movzb 0x5(%2),%0 \n"
"movzb 0x00(%1,%0,1),%0 \n"
"mov %b0,0x5(%3) \n"
"movzb 0x6(%2),%0 \n"
"movzb 0x00(%1,%0,1),%0 \n"
"mov %b0,0x6(%3) \n"
"movzb 0x7(%2),%0 \n"
"mov %b0,0x7(%3) \n"
"movd %%xmm0,%k1 \n" // 32 bit offset
"add %5,%1 \n"
"pshufd $0x39,%%xmm0,%%xmm0 \n"
"movzb 0x8(%2),%0 \n"
"movzb 0x00(%1,%0,1),%0 \n"
"mov %b0,0x8(%3) \n"
"movzb 0x9(%2),%0 \n"
"movzb 0x00(%1,%0,1),%0 \n"
"mov %b0,0x9(%3) \n"
"movzb 0xa(%2),%0 \n"
"movzb 0x00(%1,%0,1),%0 \n"
"mov %b0,0xa(%3) \n"
"movzb 0xb(%2),%0 \n"
"mov %b0,0xb(%3) \n"
"movd %%xmm0,%k1 \n" // 32 bit offset
"add %5,%1 \n"
"movzb 0xc(%2),%0 \n"
"movzb 0x00(%1,%0,1),%0 \n"
"mov %b0,0xc(%3) \n"
"movzb 0xd(%2),%0 \n"
"movzb 0x00(%1,%0,1),%0 \n"
"mov %b0,0xd(%3) \n"
"movzb 0xe(%2),%0 \n"
"movzb 0x00(%1,%0,1),%0 \n"
"mov %b0,0xe(%3) \n"
"movzb 0xf(%2),%0 \n"
"mov %b0,0xf(%3) \n"
"lea 0x10(%2),%2 \n"
"lea 0x10(%3),%3 \n"
"sub $0x4,%4 \n"
"jg 1b \n"
: "=&d"(pixel_temp), // %0
"=&a"(table_temp), // %1
"+r"(src_argb), // %2
"+r"(dst_argb), // %3
"+rm"(width) // %4
: "r"(luma), // %5
"rm"(lumacoeff) // %6
: "memory", "cc", "xmm0", "xmm3", "xmm4", "xmm5");
}
#endif // HAS_ARGBLUMACOLORTABLEROW_SSSE3
#ifdef HAS_NV21TOYUV24ROW_AVX2
// begin NV21ToYUV24Row_C avx2 constants
static const ulvec8 kBLEND0 = {0x80, 0x00, 0x80, 0x80, 0x00, 0x80, 0x80, 0x00,
0x80, 0x80, 0x00, 0x80, 0x80, 0x00, 0x80, 0x80,
0x00, 0x80, 0x00, 0x00, 0x80, 0x00, 0x00, 0x80,
0x00, 0x00, 0x80, 0x00, 0x00, 0x80, 0x00, 0x00};
static const ulvec8 kBLEND1 = {0x00, 0x00, 0x80, 0x00, 0x00, 0x80, 0x00, 0x00,
0x80, 0x00, 0x00, 0x80, 0x00, 0x00, 0x80, 0x00,
0x80, 0x00, 0x00, 0x80, 0x00, 0x00, 0x80, 0x00,
0x00, 0x80, 0x00, 0x00, 0x80, 0x00, 0x00, 0x80};
static const ulvec8 kBLEND2 = {0x80, 0x00, 0x00, 0x80, 0x00, 0x00, 0x80, 0x00,
0x00, 0x80, 0x00, 0x00, 0x80, 0x00, 0x00, 0x80,
0x00, 0x00, 0x80, 0x00, 0x00, 0x80, 0x00, 0x00,
0x80, 0x00, 0x00, 0x80, 0x00, 0x00, 0x80, 0x00};
static const ulvec8 kSHUF0 = {0x00, 0x0b, 0x80, 0x01, 0x0c, 0x80, 0x02, 0x0d,
0x80, 0x03, 0x0e, 0x80, 0x04, 0x0f, 0x80, 0x05,
0x00, 0x0b, 0x80, 0x01, 0x0c, 0x80, 0x02, 0x0d,
0x80, 0x03, 0x0e, 0x80, 0x04, 0x0f, 0x80, 0x05};
static const ulvec8 kSHUF1 = {0x80, 0x00, 0x0b, 0x80, 0x01, 0x0c, 0x80, 0x02,
0x0d, 0x80, 0x03, 0x0e, 0x80, 0x04, 0x0f, 0x80,
0x80, 0x00, 0x0b, 0x80, 0x01, 0x0c, 0x80, 0x02,
0x0d, 0x80, 0x03, 0x0e, 0x80, 0x04, 0x0f, 0x80};
static const ulvec8 kSHUF2 = {0x0a, 0x80, 0x00, 0x0b, 0x80, 0x01, 0x0c, 0x80,
0x02, 0x0d, 0x80, 0x03, 0x0e, 0x80, 0x04, 0x0f,
0x0a, 0x80, 0x00, 0x0b, 0x80, 0x01, 0x0c, 0x80,
0x02, 0x0d, 0x80, 0x03, 0x0e, 0x80, 0x04, 0x0f};
static const ulvec8 kSHUF3 = {0x80, 0x80, 0x06, 0x80, 0x80, 0x07, 0x80, 0x80,
0x08, 0x80, 0x80, 0x09, 0x80, 0x80, 0x0a, 0x80,
0x80, 0x80, 0x06, 0x80, 0x80, 0x07, 0x80, 0x80,
0x08, 0x80, 0x80, 0x09, 0x80, 0x80, 0x0a, 0x80};
static const ulvec8 kSHUF4 = {0x05, 0x80, 0x80, 0x06, 0x80, 0x80, 0x07, 0x80,
0x80, 0x08, 0x80, 0x80, 0x09, 0x80, 0x80, 0x0a,
0x05, 0x80, 0x80, 0x06, 0x80, 0x80, 0x07, 0x80,
0x80, 0x08, 0x80, 0x80, 0x09, 0x80, 0x80, 0x0a};
static const ulvec8 kSHUF5 = {0x80, 0x05, 0x80, 0x80, 0x06, 0x80, 0x80, 0x07,
0x80, 0x80, 0x08, 0x80, 0x80, 0x09, 0x80, 0x80,
0x80, 0x05, 0x80, 0x80, 0x06, 0x80, 0x80, 0x07,
0x80, 0x80, 0x08, 0x80, 0x80, 0x09, 0x80, 0x80};
// NV21ToYUV24Row_AVX2
void NV21ToYUV24Row_AVX2(const uint8_t* src_y,
const uint8_t* src_vu,
uint8_t* dst_yuv24,
int width) {
uint8_t* src_y_ptr;
uint64_t src_offset = 0;
uint64_t width64;
width64 = width;
src_y_ptr = (uint8_t*)src_y;
asm volatile(
"vmovdqu %5, %%ymm0 \n" // init blend value
"vmovdqu %6, %%ymm1 \n" // init blend value
"vmovdqu %7, %%ymm2 \n" // init blend value
// "sub $0x20, %3 \n" //sub 32 from width for final loop
LABELALIGN
"1: \n" // label 1
"vmovdqu (%0,%4), %%ymm3 \n" // src_y
"vmovdqu 1(%1,%4), %%ymm4 \n" // src_uv+1
"vmovdqu (%1), %%ymm5 \n" // src_uv
"vpshufb %8, %%ymm3, %%ymm13 \n" // y, kSHUF0 for shuf
"vpshufb %9, %%ymm4, %%ymm14 \n" // uv+1, kSHUF1 for
// shuf
"vpshufb %10, %%ymm5, %%ymm15 \n" // uv, kSHUF2 for
// shuf
"vpshufb %11, %%ymm3, %%ymm3 \n" // y kSHUF3 for shuf
"vpshufb %12, %%ymm4, %%ymm4 \n" // uv+1 kSHUF4 for
// shuf
"vpblendvb %%ymm0, %%ymm14, %%ymm13, %%ymm12 \n" // blend 0
"vpblendvb %%ymm0, %%ymm13, %%ymm14, %%ymm14 \n" // blend 0
"vpblendvb %%ymm2, %%ymm15, %%ymm12, %%ymm12 \n" // blend 2
"vpblendvb %%ymm1, %%ymm15, %%ymm14, %%ymm13 \n" // blend 1
"vpshufb %13, %%ymm5, %%ymm15 \n" // shuffle const
"vpor %%ymm4, %%ymm3, %%ymm5 \n" // get results
"vmovdqu %%ymm12, 0x20(%2) \n" // store dst_yuv+20h
"vpor %%ymm15, %%ymm5, %%ymm3 \n" // get results
"add $0x20, %4 \n" // add to src buffer
// ptr
"vinserti128 $0x1, %%xmm3, %%ymm13, %%ymm4 \n" // insert
"vperm2i128 $0x31, %%ymm13, %%ymm3, %%ymm5 \n" // insert
"vmovdqu %%ymm4, (%2) \n" // store dst_yuv
"vmovdqu %%ymm5, 0x40(%2) \n" // store dst_yuv+40h
"add $0x60,%2 \n" // add to dst buffer
// ptr
// "cmp %3, %4 \n" //(width64 -
// 32 bytes) and src_offset
"sub $0x20,%3 \n" // 32 pixels per loop
"jg 1b \n"
"vzeroupper \n" // sse-avx2
// transistions
: "+r"(src_y), //%0
"+r"(src_vu), //%1
"+r"(dst_yuv24), //%2
"+r"(width64), //%3
"+r"(src_offset) //%4
: "m"(kBLEND0), //%5
"m"(kBLEND1), //%6
"m"(kBLEND2), //%7
"m"(kSHUF0), //%8
"m"(kSHUF1), //%9
"m"(kSHUF2), //%10
"m"(kSHUF3), //%11
"m"(kSHUF4), //%12
"m"(kSHUF5) //%13
: "memory", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm12",
"xmm13", "xmm14", "xmm15");
}
#endif // HAS_NV21TOYUV24ROW_AVX2
#ifdef HAS_SWAPUVROW_SSSE3
// Shuffle table for reversing the bytes.
static const uvec8 kShuffleUVToVU = {1u, 0u, 3u, 2u, 5u, 4u, 7u, 6u,
9u, 8u, 11u, 10u, 13u, 12u, 15u, 14u};
// Convert UV plane of NV12 to VU of NV21.
void SwapUVRow_SSSE3(const uint8_t* src_uv, uint8_t* dst_vu, int width) {
asm volatile(
"movdqu %3,%%xmm5 \n"
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n"
"movdqu 0x10(%0),%%xmm1 \n"
"lea 0x20(%0),%0 \n"
"pshufb %%xmm5,%%xmm0 \n"
"pshufb %%xmm5,%%xmm1 \n"
"movdqu %%xmm0,(%1) \n"
"movdqu %%xmm1,0x10(%1) \n"
"lea 0x20(%1),%1 \n"
"sub $0x10,%2 \n"
"jg 1b \n"
: "+r"(src_uv), // %0
"+r"(dst_vu), // %1
"+r"(width) // %2
: "m"(kShuffleUVToVU) // %3
: "memory", "cc", "xmm0", "xmm1", "xmm5");
}
#endif // HAS_SWAPUVROW_SSSE3
#ifdef HAS_SWAPUVROW_AVX2
void SwapUVRow_AVX2(const uint8_t* src_uv, uint8_t* dst_vu, int width) {
asm volatile(
"vbroadcastf128 %3,%%ymm5 \n"
LABELALIGN
"1: \n"
"vmovdqu (%0),%%ymm0 \n"
"vmovdqu 0x20(%0),%%ymm1 \n"
"lea 0x40(%0),%0 \n"
"vpshufb %%ymm5,%%ymm0,%%ymm0 \n"
"vpshufb %%ymm5,%%ymm1,%%ymm1 \n"
"vmovdqu %%ymm0,(%1) \n"
"vmovdqu %%ymm1,0x20(%1) \n"
"lea 0x40(%1),%1 \n"
"sub $0x20,%2 \n"
"jg 1b \n"
"vzeroupper \n"
: "+r"(src_uv), // %0
"+r"(dst_vu), // %1
"+r"(width) // %2
: "m"(kShuffleUVToVU) // %3
: "memory", "cc", "xmm0", "xmm1", "xmm5");
}
#endif // HAS_SWAPUVROW_AVX2
void HalfMergeUVRow_SSSE3(const uint8_t* src_u,
int src_stride_u,
const uint8_t* src_v,
int src_stride_v,
uint8_t* dst_uv,
int width) {
asm volatile(
"pcmpeqb %%xmm4,%%xmm4 \n"
"psrlw $0xf,%%xmm4 \n"
"packuswb %%xmm4,%%xmm4 \n"
"pxor %%xmm5,%%xmm5 \n"
LABELALIGN
"1: \n"
"movdqu (%0),%%xmm0 \n" // load 16 U values
"movdqu (%1),%%xmm1 \n" // load 16 V values
"movdqu 0(%0,%4,1),%%xmm2 \n" // 16 from next row
"movdqu 0(%1,%5,1),%%xmm3 \n"
"lea 0x10(%0),%0 \n"
"pmaddubsw %%xmm4,%%xmm0 \n" // half size
"pmaddubsw %%xmm4,%%xmm1 \n"
"pmaddubsw %%xmm4,%%xmm2 \n"
"pmaddubsw %%xmm4,%%xmm3 \n"
"lea 0x10(%1),%1 \n"
"paddw %%xmm2,%%xmm0 \n"
"paddw %%xmm3,%%xmm1 \n"
"psrlw $0x1,%%xmm0 \n"
"psrlw $0x1,%%xmm1 \n"
"pavgw %%xmm5,%%xmm0 \n"
"pavgw %%xmm5,%%xmm1 \n"
"packuswb %%xmm0,%%xmm0 \n"
"packuswb %%xmm1,%%xmm1 \n"
"punpcklbw %%xmm1,%%xmm0 \n"
"movdqu %%xmm0,(%2) \n" // store 8 UV pixels
"lea 0x10(%2),%2 \n"
"sub $0x10,%3 \n" // 16 src pixels per loop
"jg 1b \n"
: "+r"(src_u), // %0
"+r"(src_v), // %1
"+r"(dst_uv), // %2
"+r"(width) // %3
: "r"((intptr_t)(src_stride_u)), // %4
"r"((intptr_t)(src_stride_v)) // %5
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5");
}
void HalfMergeUVRow_AVX2(const uint8_t* src_u,
int src_stride_u,
const uint8_t* src_v,
int src_stride_v,
uint8_t* dst_uv,
int width) {
asm volatile(
"vpcmpeqb %%ymm4,%%ymm4,%%ymm4 \n" // 0x0101
"vpsrlw $0xf,%%ymm4,%%ymm4 \n"
"vpackuswb %%ymm4,%%ymm4,%%ymm4 \n"
"vpxor %%ymm5,%%ymm5,%%ymm5 \n"
LABELALIGN
"1: \n"
"vmovdqu (%0),%%ymm0 \n" // load 32 U values
"vmovdqu (%1),%%ymm1 \n" // load 32 V values
"vmovdqu 0(%0,%4,1),%%ymm2 \n" // 32 from next row
"vmovdqu 0(%1,%5,1),%%ymm3 \n"
"lea 0x20(%0),%0 \n"
"vpmaddubsw %%ymm4,%%ymm0,%%ymm0 \n" // half size
"vpmaddubsw %%ymm4,%%ymm1,%%ymm1 \n"
"vpmaddubsw %%ymm4,%%ymm2,%%ymm2 \n"
"vpmaddubsw %%ymm4,%%ymm3,%%ymm3 \n"
"lea 0x20(%1),%1 \n"
"vpaddw %%ymm2,%%ymm0,%%ymm0 \n"
"vpaddw %%ymm3,%%ymm1,%%ymm1 \n"
"vpsrlw $0x1,%%ymm0,%%ymm0 \n"
"vpsrlw $0x1,%%ymm1,%%ymm1 \n"
"vpavgw %%ymm5,%%ymm0,%%ymm0 \n"
"vpavgw %%ymm5,%%ymm1,%%ymm1 \n"
"vpackuswb %%ymm0,%%ymm0,%%ymm0 \n"
"vpackuswb %%ymm1,%%ymm1,%%ymm1 \n"
"vpunpcklbw %%ymm1,%%ymm0,%%ymm0 \n"
"vmovdqu %%ymm0,(%2) \n" // store 16 UV pixels
"lea 0x20(%2),%2 \n"
"sub $0x20,%3 \n" // 32 src pixels per loop
"jg 1b \n"
"vzeroupper \n"
: "+r"(src_u), // %0
"+r"(src_v), // %1
"+r"(dst_uv), // %2
"+r"(width) // %3
: "r"((intptr_t)(src_stride_u)), // %4
"r"((intptr_t)(src_stride_v)) // %5
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5");
}
#endif // defined(__x86_64__) || defined(__i386__)
#ifdef __cplusplus
} // extern "C"
} // namespace libyuv
#endif
|
/**
* this is an extra step in classes
*/
// importing iostream header file :)
#include <iostream>
/**
* creating a class named myClass
*/
class myClass {
public:
void helloworld()
{
std::cout << "hello world\n";
};
};
/**
* calling it in another void function
* for imporiving code clean
*/
void callbackfunction()
{
myClass myObj;
myObj.helloworld();
}
/**
* calling the callbackfunction using a simple if loop
*/
int main()
{
int x = 10;
if (x == 10) {
callbackfunction();
} else {
std::cout << "oops i cant get the class ;(\n";
}
return 0;
}
|
/**
* @file nystroem_method_test.cpp
* @author Ryan Curtin
*
* Test the NystroemMethod class and ensure that the reconstructed kernel matrix
* errors are comparable with those in the literature.
*/
#include <mlpack/core.hpp>
#include <boost/test/unit_test.hpp>
#include "old_boost_test_definitions.hpp"
#include <mlpack/methods/nystroem_method/ordered_selection.hpp>
#include <mlpack/methods/nystroem_method/random_selection.hpp>
#include <mlpack/methods/nystroem_method/kmeans_selection.hpp>
#include <mlpack/methods/nystroem_method/nystroem_method.hpp>
using namespace mlpack;
using namespace mlpack::kernel;
BOOST_AUTO_TEST_SUITE(NystroemMethodTest);
/**
* Make sure that if the rank is the same and we do a full-rank approximation,
* the result is virtually identical (a little bit of tolerance for floating
* point error).
*/
BOOST_AUTO_TEST_CASE(FullRankTest)
{
// Run several trials.
for (size_t trial = 0; trial < 5; ++trial)
{
arma::mat data;
data.randu(5, trial * 200);
GaussianKernel gk;
NystroemMethod<GaussianKernel, OrderedSelection> nm(data, gk, trial * 200);
arma::mat g;
nm.Apply(g);
// Construct exact kernel matrix.
arma::mat kernel(trial * 200, trial * 200);
for (size_t i = 0; i < trial * 200; ++i)
for (size_t j = 0; j < trial * 200; ++j)
kernel(i, j) = gk.Evaluate(data.col(i), data.col(j));
// Reconstruct approximation.
arma::mat approximation = g * g.t();
// Check closeness.
for (size_t i = 0; i < trial * 200; ++i)
{
for (size_t j = 0; j < trial * 200; ++j)
{
if (kernel(i, j) < 1e-5)
BOOST_REQUIRE_SMALL(approximation(i, j), 1e-4);
else
BOOST_REQUIRE_CLOSE(kernel(i, j), approximation(i, j), 1e-5);
}
}
}
}
/**
* Can we accurately represent a rank-10 matrix?
*/
BOOST_AUTO_TEST_CASE(Rank10Test)
{
arma::mat data;
data.randu(500, 500); // Just so it's square.
// Use SVD and only keep the first ten singular vectors.
arma::mat U;
arma::vec s;
arma::mat V;
arma::svd(U, s, V, data);
// Don't set completely to 0; the hope is that K is still positive definite.
s.subvec(0, 9) += 1.0; // Make sure the first 10 singular vectors are large.
s.subvec(10, s.n_elem - 1).fill(1e-6);
arma::mat dataMod = U * arma::diagmat(s) * V.t();
// Add some noise.
dataMod += 1e-5 * arma::randu<arma::mat>(dataMod.n_rows, dataMod.n_cols);
// Calculate the true kernel matrix.
LinearKernel lk;
arma::mat kernel = dataMod.t() * dataMod;
// Now use the linear kernel to get a Nystroem approximation; try this several
// times.
double normalizedFroAverage = 0.0;
for (size_t trial = 0; trial < 20; ++trial)
{
LinearKernel lk;
NystroemMethod<LinearKernel, RandomSelection> nm(dataMod, lk, 10);
arma::mat g;
nm.Apply(g);
arma::mat approximation = g * g.t();
// Check the normalized Frobenius norm.
const double normalizedFro = arma::norm(kernel - approximation, "fro") /
arma::norm(kernel, "fro");
normalizedFroAverage += normalizedFro;
}
normalizedFroAverage /= 20;
BOOST_REQUIRE_SMALL(normalizedFroAverage, 1e-3);
}
/**
* Can we reproduce the results in Zhang, Tsang, and Kwok (2008)?
* They provide the following test points (approximately) in their experiments
* in Section 4.1, for the german dataset:
*
* rank = 0.02n; approximation error: ~27
* rank = 0.04n; approximation error: ~15
* rank = 0.06n; approximation error: ~10
* rank = 0.08n; approximation error: ~7
* rank = 0.10n; approximation error: ~3
*/
BOOST_AUTO_TEST_CASE(GermanTest)
{
// Load the dataset.
arma::mat dataset;
data::Load("german.csv", dataset, true);
// These are our tolerance bounds.
double results[5] = { 32.0, 20.0, 15.0, 12.0, 9.0 };
// The bandwidth of the kernel is selected to be the half the average
// distance between each point and the mean of the dataset. This isn't
// _exactly_ what the paper says, but I've modified what it said because our
// formulation of what the Gaussian kernel is is different.
GaussianKernel gk(16.461);
// Calculate the true kernel matrix.
arma::mat kernel(dataset.n_cols, dataset.n_cols);
for (size_t i = 0; i < dataset.n_cols; ++i)
for (size_t j = 0; j < dataset.n_cols; ++j)
kernel(i, j) = gk.Evaluate(dataset.col(i), dataset.col(j));
for (size_t trial = 0; trial < 5; ++trial)
{
// We will repeat each trial 20 times.
double avgError = 0.0;
for (size_t z = 0; z < 20; ++z)
{
NystroemMethod<GaussianKernel, KMeansSelection<> > nm(dataset, gk,
size_t((double((trial + 1) * 2) / 100.0) * dataset.n_cols));
arma::mat g;
nm.Apply(g);
// Reconstruct kernel matrix.
arma::mat approximation = g * g.t();
const double error = arma::norm(kernel - approximation, "fro");
if (error != error)
{
// Sometimes K' is singular. Unlucky.
--z;
continue;
}
else
{
Log::Debug << "Trial " << trial << ": error " << error << ".\n";
avgError += arma::norm(kernel - approximation, "fro");
}
}
avgError /= 20;
// Ensure that this is within tolerance, which is at least as good as the
// paper's results (plus a little bit for noise).
BOOST_REQUIRE_SMALL(avgError, results[trial]);
}
}
BOOST_AUTO_TEST_SUITE_END();
|
#include <Urho3D/Urho3DAll.h>
#include "NavigationMesh.h"
#include <Globals.h>
static const char* typeNames[] =
{
"Dynamic",
"Static",
nullptr
};
static const NavMeshType DEFAULT_NAVMESHTYPE = NAV_Static;
static const int DEFAULT_TILESIZE=32;
static const float DEFAULT_AGENT_HEIGHT=0.5f;
static const float DEFAULT_AGENT_MAXCLIMB=0.25f;
static const float DEFAULT_CELL_HEIGHT=0.05;
CNavigationMesh::CNavigationMesh(Context* context)
: LogicComponent(context)
,activateNavigation(false)
,showNavmesh(true)
,navmeshType(DEFAULT_NAVMESHTYPE)
,tileSize(DEFAULT_TILESIZE)
,agentHeight(DEFAULT_AGENT_HEIGHT)
,agentMaxClimb(DEFAULT_AGENT_MAXCLIMB)
,cellHeight(DEFAULT_CELL_HEIGHT)
{
SetUpdateEventMask(USE_UPDATE);
}
void CNavigationMesh::RegisterObject(Context* context) {
context->RegisterFactory<CNavigationMesh>("Sample Component");
//URHO3D_ACCESSOR_ATTRIBUTE("Speed", GetSpeed, SetSpeed, float,1.5f,AM_DEFAULT);
URHO3D_ENUM_ACCESSOR_ATTRIBUTE("Navmesh Type",GetNavmeshType,SetNavmeshType,NavMeshType,typeNames,DEFAULT_NAVMESHTYPE,AM_DEFAULT);
URHO3D_ATTRIBUTE("activateNavigation", bool, activateNavigation, false, AM_DEFAULT);
URHO3D_ATTRIBUTE("showNavmesh", bool, showNavmesh, true, AM_DEFAULT);
URHO3D_ATTRIBUTE("tileSize", int, tileSize, DEFAULT_TILESIZE, AM_DEFAULT);
URHO3D_ATTRIBUTE("agent height", float, agentHeight, DEFAULT_AGENT_HEIGHT, AM_DEFAULT);
URHO3D_ATTRIBUTE("agent max climb", float, agentMaxClimb, DEFAULT_AGENT_MAXCLIMB, AM_DEFAULT);
URHO3D_ATTRIBUTE("cell height", float, cellHeight, DEFAULT_CELL_HEIGHT, AM_DEFAULT);
}
void CNavigationMesh::SetNavmeshType(NavMeshType type)
{
navmeshType = type;
}
void CNavigationMesh::Start(){
SubscribeToEvent(E_POSTRENDERUPDATE, URHO3D_HANDLER(CNavigationMesh, HandlePostRenderUpdate));
}
void CNavigationMesh::SetupNavigation()
{
Scene* m_scene = Globals::instance()->scene;
auto crowdManager_ = m_scene->CreateComponent<CrowdManager>();
context_->RegisterSubsystem(crowdManager_);
CrowdObstacleAvoidanceParams params = crowdManager_->GetObstacleAvoidanceParams(0);
// Set the params to "High (66)" setting
params.velBias = 0.5f;
params.adaptiveDivs = 7;
params.adaptiveRings = 3;
params.adaptiveDepth = 3;
crowdManager_->SetObstacleAvoidanceParams(0, params);
// Create a DynamicNavigationMesh component to the scene root
NavigationMesh* navMesh_ = navmeshType==NAV_Static?
m_scene->CreateComponent<DynamicNavigationMesh>()
:m_scene->CreateComponent<NavigationMesh>();
// Set small tiles to show navigation mesh streaming
navMesh_->SetTileSize(tileSize);
navMesh_->SetDrawOffMeshConnections(true);
// Set the agent height large enough to exclude the layers under boxes
navMesh_->SetAgentHeight(agentHeight);
navMesh_->SetAgentMaxClimb(agentMaxClimb);
// Set nav mesh cell height to minimum (allows agents to be grounded)
navMesh_->SetCellHeight(cellHeight);
// Create a Navigable component to the scene root. This tags all of the geometry in the scene as being part of the
// navigation mesh. By default this is recursive, but the recursion could be turned off from Navigable
//m_scene->CreateComponent<Navigable>();
// Add padding to the navigation mesh in Y-direction so that we can add objects on top of the tallest boxes
// in the scene and still update the mesh correctly
navMesh_->SetPadding(Vector3(0.0f, 10.0f, 0.0f));
// Now build the navigation geometry. This will take some time. Note that the navigation mesh will prefer to use
// physics geometry from the scene nodes, as it often is simpler, but if it can not find any (like in this example)
// it will use renderable geometry instead
navMesh_->SetAreaCost(1,2.0f);
// Enable drawing debug geometry for obstacles and off-mesh connections
if (navmeshType == NAV_Dynamic){
DynamicNavigationMesh* dynNav = static_cast<DynamicNavigationMesh*>(navMesh_);
dynNav->SetDrawObstacles(true);
}
navMesh_->Build();
context_->RegisterSubsystem(navMesh_);
crowdManager_->SetNavigationMesh(navMesh_);
/*
// Create a NavigationMesh component to the scene root
auto* navMesh = m_scene->CreateComponent<NavigationMesh>();
context_->RegisterSubsystem(navMesh);
// Set small tiles to show navigation mesh streaming
navMesh->SetTileSize(32);
// Create a Navigable component to the scene root. This tags all of the geometry in the scene as being part of the
// navigation mesh. By default this is recursive, but the recursion could be turned off from Navigable
m_scene->CreateComponent<Navigable>();
// Add padding to the navigation mesh in Y-direction so that we can add objects on top of the tallest boxes
// in the scene and still update the mesh correctly
navMesh->SetPadding(Vector3(0.0f, 10.0f, 0.0f));
// Now build the navigation geometry. This will take some time. Note that the navigation mesh will prefer to use
// physics geometry from the scene nodes, as it often is simpler, but if it can not find any (like in this example)
// it will use renderable geometry instead
navMesh->Build();*/
}
void CNavigationMesh::HandlePostRenderUpdate(StringHash eventType, VariantMap &eventData)
{
if (!showNavmesh)
return;
DebugRenderer* dR = Globals::instance()->scene->GetComponent<DebugRenderer>();
if (dR){
DynamicNavigationMesh* navMesh_ = GetSubsystem<DynamicNavigationMesh>();
navMesh_->DrawDebugGeometry(dR,true);
dR->AddCircle(Vector3(0,0,0),Vector3::UP,2,Color::CYAN);
}
}
void CNavigationMesh::Update(float timestep){
}
void CNavigationMesh::DelayedStart(){
if (activateNavigation){
SetupNavigation();
}
}
|
#include "../include/public/bigintegercpp/BigInteger.h"
#include "gtest/gtest.h"
#include "Random.h"
#include "stack_calc.h"
#include "utils.h"
static void VerifyOrString(std::string opstring)
{
StackCalc sc(opstring);
while (sc.DoNextOperation())
{
ASSERT_EQ(sc.snCalc.top().to_string(), sc.myCalc.top().to_string());
}
}
static byte_array GetRandomByteArray(Random random, int size)
{
return MyBigIntImp::GetRandomByteArray(random, size);
}
static byte_array GetRandomByteArray(Random random)
{
return GetRandomByteArray(random, random.Next(0, 1024));
}
static std::string Print(byte_array bytes)
{
return MyBigIntImp::Print(bytes);
}
TEST(operator_tests, op_or) {
int s_samples = 10;
Random s_random(100);
byte_array tempByteArray1;
byte_array tempByteArray2;
// Or Method - Two Large BigIntegers
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomByteArray(s_random);
tempByteArray2 = GetRandomByteArray(s_random);
VerifyOrString(Print(tempByteArray1) + Print(tempByteArray2) + "b|");
}
// Or Method - Two Small BigIntegers
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomByteArray(s_random, 2);
tempByteArray2 = GetRandomByteArray(s_random, 2);
VerifyOrString(Print(tempByteArray1) + Print(tempByteArray2) + "b|");
}
// Or Method - one large and one small BigIntegers
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomByteArray(s_random);
tempByteArray2 = GetRandomByteArray(s_random, 2);
VerifyOrString(Print(tempByteArray1) + Print(tempByteArray2) + "b|");
tempByteArray1 = GetRandomByteArray(s_random, 2);
tempByteArray2 = GetRandomByteArray(s_random);
VerifyOrString(Print(tempByteArray1) + Print(tempByteArray2) + "b|");
}
// Or Method - one large BigIntegers and zero
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomByteArray(s_random);
tempByteArray2 = byte_array{ 0 };
VerifyOrString(Print(tempByteArray1) + Print(tempByteArray2) + "b|");
tempByteArray1 = byte_array{ 0 };
tempByteArray2 = GetRandomByteArray(s_random);
VerifyOrString(Print(tempByteArray1) + Print(tempByteArray2) + "b|");
}
// Or Method - one small BigIntegers and zero
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomByteArray(s_random, 2);
tempByteArray2 = byte_array{ 0 };
VerifyOrString(Print(tempByteArray1) + Print(tempByteArray2) + "b|");
tempByteArray1 = byte_array{ 0 };
tempByteArray2 = GetRandomByteArray(s_random, 2);
VerifyOrString(Print(tempByteArray1) + Print(tempByteArray2) + "b|");
}
// Or Method - one large BigIntegers and -1
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomByteArray(s_random);
tempByteArray2 = byte_array{ 0xFF };
VerifyOrString(Print(tempByteArray1) + Print(tempByteArray2) + "b|");
tempByteArray1 = byte_array{ 0xFF };
tempByteArray2 = GetRandomByteArray(s_random);
VerifyOrString(Print(tempByteArray1) + Print(tempByteArray2) + "b|");
}
// Or Method - one small BigIntegers and -1
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomByteArray(s_random, 2);
tempByteArray2 = byte_array{ 0xFF };
VerifyOrString(Print(tempByteArray1) + Print(tempByteArray2) + "b|");
tempByteArray1 = byte_array{ 0xFF };
tempByteArray2 = GetRandomByteArray(s_random, 2);
VerifyOrString(Print(tempByteArray1) + Print(tempByteArray2) + "b|");
}
// Or Method - one large BigIntegers and Int.MaxValue+1
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomByteArray(s_random);
tempByteArray2 = byte_array{ 0x00, 0x00, 0x00, 0x80, 0x00 };
VerifyOrString(Print(tempByteArray1) + Print(tempByteArray2) + "b|");
tempByteArray1 = byte_array{ 0x00, 0x00, 0x00, 0x80, 0x00 };
tempByteArray2 = GetRandomByteArray(s_random);
VerifyOrString(Print(tempByteArray1) + Print(tempByteArray2) + "b|");
}
// Or Method - one small BigIntegers and Int.MaxValue+1
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomByteArray(s_random, 2);
tempByteArray2 = byte_array{ 0x00, 0x00, 0x00, 0x80, 0x00 };
VerifyOrString(Print(tempByteArray1) + Print(tempByteArray2) + "b|");
tempByteArray1 = byte_array{ 0x00, 0x00, 0x00, 0x80, 0x00 };
tempByteArray2 = GetRandomByteArray(s_random, 2);
VerifyOrString(Print(tempByteArray1) + Print(tempByteArray2) + "b|");
}
}
|
/****************************************************************************
** Meta object code from reading C++ file 'bitcoingui.h'
**
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "qt/bitcoingui.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'bitcoingui.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.5.1. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
struct qt_meta_stringdata_BitcoinGUI_t {
QByteArrayData data[57];
char stringdata0[758];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_BitcoinGUI_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_BitcoinGUI_t qt_meta_stringdata_BitcoinGUI = {
{
QT_MOC_LITERAL(0, 0, 10), // "BitcoinGUI"
QT_MOC_LITERAL(1, 11, 11), // "receivedURI"
QT_MOC_LITERAL(2, 23, 0), // ""
QT_MOC_LITERAL(3, 24, 3), // "uri"
QT_MOC_LITERAL(4, 28, 17), // "setNumConnections"
QT_MOC_LITERAL(5, 46, 5), // "count"
QT_MOC_LITERAL(6, 52, 16), // "setNetworkActive"
QT_MOC_LITERAL(7, 69, 13), // "networkActive"
QT_MOC_LITERAL(8, 83, 12), // "setNumBlocks"
QT_MOC_LITERAL(9, 96, 9), // "blockDate"
QT_MOC_LITERAL(10, 106, 21), // "nVerificationProgress"
QT_MOC_LITERAL(11, 128, 7), // "headers"
QT_MOC_LITERAL(12, 136, 7), // "message"
QT_MOC_LITERAL(13, 144, 5), // "title"
QT_MOC_LITERAL(14, 150, 5), // "style"
QT_MOC_LITERAL(15, 156, 5), // "bool*"
QT_MOC_LITERAL(16, 162, 3), // "ret"
QT_MOC_LITERAL(17, 166, 19), // "setEncryptionStatus"
QT_MOC_LITERAL(18, 186, 6), // "status"
QT_MOC_LITERAL(19, 193, 11), // "setHDStatus"
QT_MOC_LITERAL(20, 205, 9), // "hdEnabled"
QT_MOC_LITERAL(21, 215, 20), // "handlePaymentRequest"
QT_MOC_LITERAL(22, 236, 18), // "SendCoinsRecipient"
QT_MOC_LITERAL(23, 255, 9), // "recipient"
QT_MOC_LITERAL(24, 265, 19), // "incomingTransaction"
QT_MOC_LITERAL(25, 285, 4), // "date"
QT_MOC_LITERAL(26, 290, 4), // "unit"
QT_MOC_LITERAL(27, 295, 7), // "CAmount"
QT_MOC_LITERAL(28, 303, 6), // "amount"
QT_MOC_LITERAL(29, 310, 4), // "type"
QT_MOC_LITERAL(30, 315, 7), // "address"
QT_MOC_LITERAL(31, 323, 5), // "label"
QT_MOC_LITERAL(32, 329, 16), // "gotoOverviewPage"
QT_MOC_LITERAL(33, 346, 15), // "gotoHistoryPage"
QT_MOC_LITERAL(34, 362, 20), // "gotoReceiveCoinsPage"
QT_MOC_LITERAL(35, 383, 17), // "gotoSendCoinsPage"
QT_MOC_LITERAL(36, 401, 4), // "addr"
QT_MOC_LITERAL(37, 406, 18), // "gotoSignMessageTab"
QT_MOC_LITERAL(38, 425, 20), // "gotoVerifyMessageTab"
QT_MOC_LITERAL(39, 446, 11), // "openClicked"
QT_MOC_LITERAL(40, 458, 14), // "optionsClicked"
QT_MOC_LITERAL(41, 473, 12), // "aboutClicked"
QT_MOC_LITERAL(42, 486, 15), // "showDebugWindow"
QT_MOC_LITERAL(43, 502, 30), // "showDebugWindowActivateConsole"
QT_MOC_LITERAL(44, 533, 22), // "showHelpMessageClicked"
QT_MOC_LITERAL(45, 556, 17), // "trayIconActivated"
QT_MOC_LITERAL(46, 574, 33), // "QSystemTrayIcon::ActivationRe..."
QT_MOC_LITERAL(47, 608, 6), // "reason"
QT_MOC_LITERAL(48, 615, 21), // "showNormalIfMinimized"
QT_MOC_LITERAL(49, 637, 13), // "fToggleHidden"
QT_MOC_LITERAL(50, 651, 12), // "toggleHidden"
QT_MOC_LITERAL(51, 664, 14), // "detectShutdown"
QT_MOC_LITERAL(52, 679, 12), // "showProgress"
QT_MOC_LITERAL(53, 692, 9), // "nProgress"
QT_MOC_LITERAL(54, 702, 18), // "setTrayIconVisible"
QT_MOC_LITERAL(55, 721, 19), // "toggleNetworkActive"
QT_MOC_LITERAL(56, 741, 16) // "showModalOverlay"
},
"BitcoinGUI\0receivedURI\0\0uri\0"
"setNumConnections\0count\0setNetworkActive\0"
"networkActive\0setNumBlocks\0blockDate\0"
"nVerificationProgress\0headers\0message\0"
"title\0style\0bool*\0ret\0setEncryptionStatus\0"
"status\0setHDStatus\0hdEnabled\0"
"handlePaymentRequest\0SendCoinsRecipient\0"
"recipient\0incomingTransaction\0date\0"
"unit\0CAmount\0amount\0type\0address\0label\0"
"gotoOverviewPage\0gotoHistoryPage\0"
"gotoReceiveCoinsPage\0gotoSendCoinsPage\0"
"addr\0gotoSignMessageTab\0gotoVerifyMessageTab\0"
"openClicked\0optionsClicked\0aboutClicked\0"
"showDebugWindow\0showDebugWindowActivateConsole\0"
"showHelpMessageClicked\0trayIconActivated\0"
"QSystemTrayIcon::ActivationReason\0"
"reason\0showNormalIfMinimized\0fToggleHidden\0"
"toggleHidden\0detectShutdown\0showProgress\0"
"nProgress\0setTrayIconVisible\0"
"toggleNetworkActive\0showModalOverlay"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_BitcoinGUI[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
34, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
1, // signalCount
// signals: name, argc, parameters, tag, flags
1, 1, 184, 2, 0x06 /* Public */,
// slots: name, argc, parameters, tag, flags
4, 1, 187, 2, 0x0a /* Public */,
6, 1, 190, 2, 0x0a /* Public */,
8, 4, 193, 2, 0x0a /* Public */,
12, 4, 202, 2, 0x0a /* Public */,
12, 3, 211, 2, 0x2a /* Public | MethodCloned */,
17, 1, 218, 2, 0x0a /* Public */,
19, 1, 221, 2, 0x0a /* Public */,
21, 1, 224, 2, 0x0a /* Public */,
24, 6, 227, 2, 0x0a /* Public */,
32, 0, 240, 2, 0x08 /* Private */,
33, 0, 241, 2, 0x08 /* Private */,
34, 0, 242, 2, 0x08 /* Private */,
35, 1, 243, 2, 0x08 /* Private */,
35, 0, 246, 2, 0x28 /* Private | MethodCloned */,
37, 1, 247, 2, 0x08 /* Private */,
37, 0, 250, 2, 0x28 /* Private | MethodCloned */,
38, 1, 251, 2, 0x08 /* Private */,
38, 0, 254, 2, 0x28 /* Private | MethodCloned */,
39, 0, 255, 2, 0x08 /* Private */,
40, 0, 256, 2, 0x08 /* Private */,
41, 0, 257, 2, 0x08 /* Private */,
42, 0, 258, 2, 0x08 /* Private */,
43, 0, 259, 2, 0x08 /* Private */,
44, 0, 260, 2, 0x08 /* Private */,
45, 1, 261, 2, 0x08 /* Private */,
48, 1, 264, 2, 0x08 /* Private */,
48, 0, 267, 2, 0x28 /* Private | MethodCloned */,
50, 0, 268, 2, 0x08 /* Private */,
51, 0, 269, 2, 0x08 /* Private */,
52, 2, 270, 2, 0x08 /* Private */,
54, 1, 275, 2, 0x08 /* Private */,
55, 0, 278, 2, 0x08 /* Private */,
56, 0, 279, 2, 0x08 /* Private */,
// signals: parameters
QMetaType::Void, QMetaType::QString, 3,
// slots: parameters
QMetaType::Void, QMetaType::Int, 5,
QMetaType::Void, QMetaType::Bool, 7,
QMetaType::Void, QMetaType::Int, QMetaType::QDateTime, QMetaType::Double, QMetaType::Bool, 5, 9, 10, 11,
QMetaType::Void, QMetaType::QString, QMetaType::QString, QMetaType::UInt, 0x80000000 | 15, 13, 12, 14, 16,
QMetaType::Void, QMetaType::QString, QMetaType::QString, QMetaType::UInt, 13, 12, 14,
QMetaType::Void, QMetaType::Int, 18,
QMetaType::Void, QMetaType::Int, 20,
QMetaType::Bool, 0x80000000 | 22, 23,
QMetaType::Void, QMetaType::QString, QMetaType::Int, 0x80000000 | 27, QMetaType::QString, QMetaType::QString, QMetaType::QString, 25, 26, 28, 29, 30, 31,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void, QMetaType::QString, 36,
QMetaType::Void,
QMetaType::Void, QMetaType::QString, 36,
QMetaType::Void,
QMetaType::Void, QMetaType::QString, 36,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void, 0x80000000 | 46, 47,
QMetaType::Void, QMetaType::Bool, 49,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void, QMetaType::QString, QMetaType::Int, 13, 53,
QMetaType::Void, QMetaType::Bool, 2,
QMetaType::Void,
QMetaType::Void,
0 // eod
};
void BitcoinGUI::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
BitcoinGUI *_t = static_cast<BitcoinGUI *>(_o);
Q_UNUSED(_t)
switch (_id) {
case 0: _t->receivedURI((*reinterpret_cast< const QString(*)>(_a[1]))); break;
case 1: _t->setNumConnections((*reinterpret_cast< int(*)>(_a[1]))); break;
case 2: _t->setNetworkActive((*reinterpret_cast< bool(*)>(_a[1]))); break;
case 3: _t->setNumBlocks((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< const QDateTime(*)>(_a[2])),(*reinterpret_cast< double(*)>(_a[3])),(*reinterpret_cast< bool(*)>(_a[4]))); break;
case 4: _t->message((*reinterpret_cast< const QString(*)>(_a[1])),(*reinterpret_cast< const QString(*)>(_a[2])),(*reinterpret_cast< uint(*)>(_a[3])),(*reinterpret_cast< bool*(*)>(_a[4]))); break;
case 5: _t->message((*reinterpret_cast< const QString(*)>(_a[1])),(*reinterpret_cast< const QString(*)>(_a[2])),(*reinterpret_cast< uint(*)>(_a[3]))); break;
case 6: _t->setEncryptionStatus((*reinterpret_cast< int(*)>(_a[1]))); break;
case 7: _t->setHDStatus((*reinterpret_cast< int(*)>(_a[1]))); break;
case 8: { bool _r = _t->handlePaymentRequest((*reinterpret_cast< const SendCoinsRecipient(*)>(_a[1])));
if (_a[0]) *reinterpret_cast< bool*>(_a[0]) = _r; } break;
case 9: _t->incomingTransaction((*reinterpret_cast< const QString(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2])),(*reinterpret_cast< const CAmount(*)>(_a[3])),(*reinterpret_cast< const QString(*)>(_a[4])),(*reinterpret_cast< const QString(*)>(_a[5])),(*reinterpret_cast< const QString(*)>(_a[6]))); break;
case 10: _t->gotoOverviewPage(); break;
case 11: _t->gotoHistoryPage(); break;
case 12: _t->gotoReceiveCoinsPage(); break;
case 13: _t->gotoSendCoinsPage((*reinterpret_cast< QString(*)>(_a[1]))); break;
case 14: _t->gotoSendCoinsPage(); break;
case 15: _t->gotoSignMessageTab((*reinterpret_cast< QString(*)>(_a[1]))); break;
case 16: _t->gotoSignMessageTab(); break;
case 17: _t->gotoVerifyMessageTab((*reinterpret_cast< QString(*)>(_a[1]))); break;
case 18: _t->gotoVerifyMessageTab(); break;
case 19: _t->openClicked(); break;
case 20: _t->optionsClicked(); break;
case 21: _t->aboutClicked(); break;
case 22: _t->showDebugWindow(); break;
case 23: _t->showDebugWindowActivateConsole(); break;
case 24: _t->showHelpMessageClicked(); break;
case 25: _t->trayIconActivated((*reinterpret_cast< QSystemTrayIcon::ActivationReason(*)>(_a[1]))); break;
case 26: _t->showNormalIfMinimized((*reinterpret_cast< bool(*)>(_a[1]))); break;
case 27: _t->showNormalIfMinimized(); break;
case 28: _t->toggleHidden(); break;
case 29: _t->detectShutdown(); break;
case 30: _t->showProgress((*reinterpret_cast< const QString(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2]))); break;
case 31: _t->setTrayIconVisible((*reinterpret_cast< bool(*)>(_a[1]))); break;
case 32: _t->toggleNetworkActive(); break;
case 33: _t->showModalOverlay(); break;
default: ;
}
} else if (_c == QMetaObject::IndexOfMethod) {
int *result = reinterpret_cast<int *>(_a[0]);
void **func = reinterpret_cast<void **>(_a[1]);
{
typedef void (BitcoinGUI::*_t)(const QString & );
if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&BitcoinGUI::receivedURI)) {
*result = 0;
}
}
}
}
const QMetaObject BitcoinGUI::staticMetaObject = {
{ &QMainWindow::staticMetaObject, qt_meta_stringdata_BitcoinGUI.data,
qt_meta_data_BitcoinGUI, qt_static_metacall, Q_NULLPTR, Q_NULLPTR}
};
const QMetaObject *BitcoinGUI::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *BitcoinGUI::qt_metacast(const char *_clname)
{
if (!_clname) return Q_NULLPTR;
if (!strcmp(_clname, qt_meta_stringdata_BitcoinGUI.stringdata0))
return static_cast<void*>(const_cast< BitcoinGUI*>(this));
return QMainWindow::qt_metacast(_clname);
}
int BitcoinGUI::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QMainWindow::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 34)
qt_static_metacall(this, _c, _id, _a);
_id -= 34;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 34)
*reinterpret_cast<int*>(_a[0]) = -1;
_id -= 34;
}
return _id;
}
// SIGNAL 0
void BitcoinGUI::receivedURI(const QString & _t1)
{
void *_a[] = { Q_NULLPTR, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) };
QMetaObject::activate(this, &staticMetaObject, 0, _a);
}
struct qt_meta_stringdata_UnitDisplayStatusBarControl_t {
QByteArrayData data[7];
char stringdata0[88];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_UnitDisplayStatusBarControl_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_UnitDisplayStatusBarControl_t qt_meta_stringdata_UnitDisplayStatusBarControl = {
{
QT_MOC_LITERAL(0, 0, 27), // "UnitDisplayStatusBarControl"
QT_MOC_LITERAL(1, 28, 17), // "updateDisplayUnit"
QT_MOC_LITERAL(2, 46, 0), // ""
QT_MOC_LITERAL(3, 47, 8), // "newUnits"
QT_MOC_LITERAL(4, 56, 15), // "onMenuSelection"
QT_MOC_LITERAL(5, 72, 8), // "QAction*"
QT_MOC_LITERAL(6, 81, 6) // "action"
},
"UnitDisplayStatusBarControl\0"
"updateDisplayUnit\0\0newUnits\0onMenuSelection\0"
"QAction*\0action"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_UnitDisplayStatusBarControl[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
2, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
// slots: name, argc, parameters, tag, flags
1, 1, 24, 2, 0x08 /* Private */,
4, 1, 27, 2, 0x08 /* Private */,
// slots: parameters
QMetaType::Void, QMetaType::Int, 3,
QMetaType::Void, 0x80000000 | 5, 6,
0 // eod
};
void UnitDisplayStatusBarControl::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
UnitDisplayStatusBarControl *_t = static_cast<UnitDisplayStatusBarControl *>(_o);
Q_UNUSED(_t)
switch (_id) {
case 0: _t->updateDisplayUnit((*reinterpret_cast< int(*)>(_a[1]))); break;
case 1: _t->onMenuSelection((*reinterpret_cast< QAction*(*)>(_a[1]))); break;
default: ;
}
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
switch (_id) {
default: *reinterpret_cast<int*>(_a[0]) = -1; break;
case 1:
switch (*reinterpret_cast<int*>(_a[1])) {
default: *reinterpret_cast<int*>(_a[0]) = -1; break;
case 0:
*reinterpret_cast<int*>(_a[0]) = qRegisterMetaType< QAction* >(); break;
}
break;
}
}
}
const QMetaObject UnitDisplayStatusBarControl::staticMetaObject = {
{ &QLabel::staticMetaObject, qt_meta_stringdata_UnitDisplayStatusBarControl.data,
qt_meta_data_UnitDisplayStatusBarControl, qt_static_metacall, Q_NULLPTR, Q_NULLPTR}
};
const QMetaObject *UnitDisplayStatusBarControl::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *UnitDisplayStatusBarControl::qt_metacast(const char *_clname)
{
if (!_clname) return Q_NULLPTR;
if (!strcmp(_clname, qt_meta_stringdata_UnitDisplayStatusBarControl.stringdata0))
return static_cast<void*>(const_cast< UnitDisplayStatusBarControl*>(this));
return QLabel::qt_metacast(_clname);
}
int UnitDisplayStatusBarControl::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QLabel::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 2)
qt_static_metacall(this, _c, _id, _a);
_id -= 2;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 2)
qt_static_metacall(this, _c, _id, _a);
_id -= 2;
}
return _id;
}
QT_END_MOC_NAMESPACE
|
//===-- MCAsmInfoDarwin.cpp - Darwin asm properties -------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines target asm properties related what form asm statements
// should take in general on Darwin-based targets
//
//===----------------------------------------------------------------------===//
#include "llvm/MC/MCAsmInfoDarwin.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCExpr.h"
#include "llvm/MC/MCSectionMachO.h"
#include "llvm/MC/MCStreamer.h"
using namespace llvm;
bool MCAsmInfoDarwin::isSectionAtomizableBySymbols(
const MCSection &Section) const {
const MCSectionMachO &SMO = static_cast<const MCSectionMachO &>(Section);
// Sections holding 1 byte strings are atomized based on the data they
// contain.
// Sections holding 2 byte strings require symbols in order to be atomized.
// There is no dedicated section for 4 byte strings.
if (SMO.getType() == MachO::S_CSTRING_LITERALS)
return false;
if (SMO.getSegmentName() == "__DATA" && SMO.getSectionName() == "__cfstring")
return false;
switch (SMO.getType()) {
default:
return true;
// These sections are atomized at the element boundaries without using
// symbols.
case MachO::S_4BYTE_LITERALS:
case MachO::S_8BYTE_LITERALS:
case MachO::S_16BYTE_LITERALS:
case MachO::S_LITERAL_POINTERS:
case MachO::S_NON_LAZY_SYMBOL_POINTERS:
case MachO::S_LAZY_SYMBOL_POINTERS:
case MachO::S_MOD_INIT_FUNC_POINTERS:
case MachO::S_MOD_TERM_FUNC_POINTERS:
case MachO::S_INTERPOSING:
return false;
}
}
MCAsmInfoDarwin::MCAsmInfoDarwin() {
// Common settings for all Darwin targets.
// Syntax:
LinkerPrivateGlobalPrefix = "l";
HasSingleParameterDotFile = false;
HasSubsectionsViaSymbols = true;
AlignmentIsInBytes = false;
COMMDirectiveAlignmentIsInBytes = false;
LCOMMDirectiveAlignmentType = LCOMM::Log2Alignment;
InlineAsmStart = " InlineAsm Start";
InlineAsmEnd = " InlineAsm End";
// Directives:
HasWeakDefDirective = true;
HasWeakDefCanBeHiddenDirective = true;
WeakRefDirective = "\t.weak_reference ";
ZeroDirective = "\t.space\t"; // ".space N" emits N zeros.
HasMachoZeroFillDirective = true; // Uses .zerofill
HasMachoTBSSDirective = true; // Uses .tbss
HasStaticCtorDtorReferenceInStaticMode = true;
// FIXME: Change this once MC is the system assembler.
HasAggressiveSymbolFolding = false;
HiddenVisibilityAttr = MCSA_PrivateExtern;
HiddenDeclarationVisibilityAttr = MCSA_Invalid;
// Doesn't support protected visibility.
ProtectedVisibilityAttr = MCSA_Invalid;
HasDotTypeDotSizeDirective = false;
HasNoDeadStrip = true;
DwarfUsesRelocationsAcrossSections = false;
UseIntegratedAssembler = true;
SetDirectiveSuppressesReloc = true;
}
|
// ==============
// common/crc.cpp
// ==============
#include "crc.h"
uint64 ReverseBits64(uint64 a)
{
{ const uint64 mask = 0x5555555555555555ULL; a = ((a >> 0x01) & mask) | ((a & mask) << 0x01); }
{ const uint64 mask = 0x3333333333333333ULL; a = ((a >> 0x02) & mask) | ((a & mask) << 0x02); }
{ const uint64 mask = 0x0F0F0F0F0F0F0F0FULL; a = ((a >> 0x04) & mask) | ((a & mask) << 0x04); }
{ const uint64 mask = 0x00FF00FF00FF00FFULL; a = ((a >> 0x08) & mask) | ((a & mask) << 0x08); }
{ const uint64 mask = 0x0000FFFF0000FFFFULL; a = ((a >> 0x10) & mask) | ((a & mask) << 0x10); }
return (a >> 0x20) | (a << 0x20);
}
uint64 Crc64(const void* ptr, size_t numBytes, uint64 crc)
{
static uint64 table[256] = {0};
if (table[0] == 0) {
const uint64 polynomial = ReverseBits64(0x42F0E1EBA9EA3693ULL); // CRC-64-ECMA-182
for (int i = 0; i < 256; i++) {
uint64 x = (uint64)i;
for (int j = 0; j < 8; j++) {
if (x & 1) { x = (x >> 1) ^ polynomial; }
else { x = (x >> 1); }
}
table[i] = x;
}
}
const uint8* src = (const uint8*)ptr;
const uint8* end = &src[numBytes];
while (src < end)
crc = table[(uint8)crc ^ *(src++)] ^ (crc >> 8);
return crc;
}
uint64 GetFileCrc64(const char* path, uint64 crc, size_t* accumsize)
{
FILE* file = fopen(path, "rb");
if (file) {
fseek(file, 0, SEEK_END);
const size_t size = ftell(file);
fseek(file, 0, SEEK_SET);
uint8* data = new uint8[size];
fread(data, size, 1, file);
fclose(file);
crc = Crc64(data, size, crc);
delete[] data;
if (accumsize)
(*accumsize) += size;
}
return crc;
}
|
/* ************************************************************************
* Copyright 2016 Advanced Micro Devices, Inc.
* ************************************************************************ */
#include <hip/hip_runtime.h>
#include "rocblas.h"
#include "status.h"
#include "definitions.h"
#include "reduction.h"
#include "fetch_template.h"
#include "rocblas_unique_ptr.hpp"
#include "handle.h"
#include "logging.h"
#include "utility.h"
namespace {
template <class To>
struct rocblas_fetch_nrm2
{
template <class Ti>
__forceinline__ __device__ To operator()(Ti x, ssize_t tid)
{
return {fetch_abs2(x)};
}
};
struct rocblas_finalize_nrm2
{
template <class To>
__forceinline__ __host__ __device__ To operator()(To x)
{
return sqrt(x);
}
};
template <typename>
constexpr char rocblas_nrm2_name[] = "unknown";
template <>
constexpr char rocblas_nrm2_name<float>[] = "rocblas_snrm2";
template <>
constexpr char rocblas_nrm2_name<double>[] = "rocblas_dnrm2";
template <>
constexpr char rocblas_nrm2_name<rocblas_half>[] = "rocblas_hnrm2";
template <>
constexpr char rocblas_nrm2_name<rocblas_float_complex>[] = "rocblas_scnrm2";
template <>
constexpr char rocblas_nrm2_name<rocblas_double_complex>[] = "rocblas_dznrm2";
/* ============================================================================================ */
/*! \brief BLAS Level 1 API
\details
nrm2 computes the euclidean norm of a real or complex vector
:= sqrt( x'*x ) for real vector
:= sqrt( x**H*x ) for complex vector
@param[in]
handle rocblas_handle.
handle to the rocblas library context queue.
@param[in]
n rocblas_int.
@param[in]
x pointer storing vector x on the GPU.
@param[in]
incx rocblas_int
specifies the increment for the elements of y.
@param[inout]
result
store the nrm2 product. either on the host CPU or device GPU.
return is 0 if n <= 0 or incx <= 0.
********************************************************************/
// allocate workspace inside this API
template <typename Ti, typename To>
rocblas_status
rocblas_nrm2(rocblas_handle handle, rocblas_int n, const Ti* x, rocblas_int incx, To* result)
{
if(!handle)
return rocblas_status_invalid_handle;
auto layer_mode = handle->layer_mode;
if(layer_mode & rocblas_layer_mode_log_trace)
log_trace(handle, rocblas_nrm2_name<Ti>, n, x, incx);
if(layer_mode & rocblas_layer_mode_log_bench)
log_bench(handle,
"./rocblas-bench -f nrm2 -r",
rocblas_precision_string<Ti>,
"-n",
n,
"--incx",
incx);
if(layer_mode & rocblas_layer_mode_log_profile)
log_profile(handle, rocblas_nrm2_name<Ti>, "N", n, "incx", incx);
if(!x || !result)
return rocblas_status_invalid_pointer;
/*
* Quick return if possible.
*/
if(n <= 0 || incx <= 0)
{
if(rocblas_pointer_mode_device == handle->pointer_mode)
RETURN_IF_HIP_ERROR(hipMemset(result, 0, sizeof(*result)));
else
*result = 0;
return rocblas_status_success;
}
// HIP support up to 1024 threads/work itmes per thread block/work group
static constexpr int NB = 512;
rocblas_int blocks = (n - 1) / NB + 1;
auto workspace =
rocblas_unique_ptr{rocblas::device_malloc(sizeof(To) * blocks), rocblas::device_free};
if(!workspace)
return rocblas_status_memory_error;
auto status = rocblas_reduction_kernel<NB,
rocblas_fetch_nrm2<To>,
rocblas_reduce_sum,
rocblas_finalize_nrm2>(
handle, n, x, incx, result, (To*)workspace.get(), blocks);
return status;
}
} // namespace
/* ============================================================================================ */
/*
* ===========================================================================
* C wrapper
* ===========================================================================
*/
extern "C" {
rocblas_status
rocblas_snrm2(rocblas_handle handle, rocblas_int n, const float* x, rocblas_int incx, float* result)
{
return rocblas_nrm2(handle, n, x, incx, result);
}
rocblas_status rocblas_dnrm2(
rocblas_handle handle, rocblas_int n, const double* x, rocblas_int incx, double* result)
{
return rocblas_nrm2(handle, n, x, incx, result);
}
#if 0 // complex not supported
rocblas_status rocblas_scnrm2(rocblas_handle handle,
rocblas_int n,
const rocblas_float_complex* x,
rocblas_int incx,
float* result)
{
return rocblas_nrm2(handle, n, x, incx, result);
}
rocblas_status rocblas_dznrm2(rocblas_handle handle,
rocblas_int n,
const rocblas_double_complex* x,
rocblas_int incx,
double* result)
{
return rocblas_nrm2(handle, n, x, incx, result);
}
#endif
} // extern "C"
|
#include <mbgl/programs/line_program.hpp>
#include <mbgl/style/layers/line_layer_properties.hpp>
#include <mbgl/renderer/render_tile.hpp>
#include <mbgl/map/transform_state.hpp>
#include <mbgl/util/mat2.hpp>
#include <mbgl/sprite/sprite_atlas.hpp>
#include <mbgl/geometry/line_atlas.hpp>
namespace mbgl {
using namespace style;
static_assert(sizeof(LineAttributes::Vertex) == 8, "expected LineVertex size");
template <class Values, class...Args>
Values makeValues(const LinePaintProperties::Evaluated& properties,
const RenderTile& tile,
const TransformState& state,
const std::array<float, 2>& pixelsToGLUnits,
Args&&... args) {
return Values {
uniforms::u_matrix::Value{
tile.translatedMatrix(properties.get<LineTranslate>(),
properties.get<LineTranslateAnchor>(),
state)
},
uniforms::u_opacity::Value{ properties.get<LineOpacity>() },
uniforms::u_width::Value{ properties.get<LineWidth>() },
uniforms::u_gapwidth::Value{ properties.get<LineGapWidth>() },
uniforms::u_blur::Value{ properties.get<LineBlur>() },
uniforms::u_offset::Value{ properties.get<LineOffset>() },
uniforms::u_ratio::Value{ 1.0f / tile.id.pixelsToTileUnits(1.0, state.getZoom()) },
uniforms::u_gl_units_to_pixels::Value{{{ 1.0f / pixelsToGLUnits[0], 1.0f / pixelsToGLUnits[1] }}},
std::forward<Args>(args)...
};
}
LineProgram::UniformValues
LineProgram::uniformValues(const LinePaintProperties::Evaluated& properties,
const RenderTile& tile,
const TransformState& state,
const std::array<float, 2>& pixelsToGLUnits) {
return makeValues<LineProgram::UniformValues>(
properties,
tile,
state,
pixelsToGLUnits,
uniforms::u_color::Value{ properties.get<LineColor>() }
);
}
LineSDFProgram::UniformValues
LineSDFProgram::uniformValues(const LinePaintProperties::Evaluated& properties,
float pixelRatio,
const RenderTile& tile,
const TransformState& state,
const std::array<float, 2>& pixelsToGLUnits,
const LinePatternPos& posA,
const LinePatternPos& posB,
float dashLineWidth,
float atlasWidth) {
const float widthA = posA.width * properties.get<LineDasharray>().fromScale * dashLineWidth;
const float widthB = posB.width * properties.get<LineDasharray>().toScale * dashLineWidth;
std::array<float, 2> scaleA {{
1.0f / tile.id.pixelsToTileUnits(widthA, state.getIntegerZoom()),
-posA.height / 2.0f
}};
std::array<float, 2> scaleB {{
1.0f / tile.id.pixelsToTileUnits(widthB, state.getIntegerZoom()),
-posB.height / 2.0f
}};
return makeValues<LineSDFProgram::UniformValues>(
properties,
tile,
state,
pixelsToGLUnits,
uniforms::u_color::Value{ properties.get<LineColor>() },
uniforms::u_patternscale_a::Value{ scaleA },
uniforms::u_patternscale_b::Value{ scaleB },
uniforms::u_tex_y_a::Value{ posA.y },
uniforms::u_tex_y_b::Value{ posB.y },
uniforms::u_mix::Value{ properties.get<LineDasharray>().t },
uniforms::u_sdfgamma::Value{ atlasWidth / (std::min(widthA, widthB) * 256.0f * pixelRatio) / 2.0f },
uniforms::u_image::Value{ 0 }
);
}
LinePatternProgram::UniformValues
LinePatternProgram::uniformValues(const LinePaintProperties::Evaluated& properties,
const RenderTile& tile,
const TransformState& state,
const std::array<float, 2>& pixelsToGLUnits,
const SpriteAtlasPosition& posA,
const SpriteAtlasPosition& posB) {
std::array<float, 2> sizeA {{
tile.id.pixelsToTileUnits(posA.size[0] * properties.get<LinePattern>().fromScale, state.getIntegerZoom()),
posA.size[1]
}};
std::array<float, 2> sizeB {{
tile.id.pixelsToTileUnits(posB.size[0] * properties.get<LinePattern>().toScale, state.getIntegerZoom()),
posB.size[1]
}};
return makeValues<LinePatternProgram::UniformValues>(
properties,
tile,
state,
pixelsToGLUnits,
uniforms::u_pattern_tl_a::Value{ posA.tl },
uniforms::u_pattern_br_a::Value{ posA.br },
uniforms::u_pattern_tl_b::Value{ posB.tl },
uniforms::u_pattern_br_b::Value{ posB.br },
uniforms::u_pattern_size_a::Value{ sizeA },
uniforms::u_pattern_size_b::Value{ sizeB },
uniforms::u_fade::Value{ properties.get<LinePattern>().t },
uniforms::u_image::Value{ 0 }
);
}
} // namespace mbgl
|
// Autogenerated from KST: please remove this line if doing any edits by hand!
#include <boost/test/unit_test.hpp>
#include "expr_bytes_ops.h"
#include <iostream>
#include <fstream>
#include <vector>
BOOST_AUTO_TEST_CASE(test_expr_bytes_ops) {
std::ifstream ifs("src/nav_parent_switch.bin", std::ifstream::binary);
kaitai::kstream ks(&ifs);
expr_bytes_ops_t* r = new expr_bytes_ops_t(&ks);
BOOST_CHECK_EQUAL(r->one_size(), 3);
BOOST_CHECK_EQUAL(r->one_first(), 1);
BOOST_CHECK_EQUAL(r->one_mid(), 66);
BOOST_CHECK_EQUAL(r->one_last(), 255);
BOOST_CHECK_EQUAL(kaitai::kstream::to_string(r->one_last()), std::string("255"));
BOOST_CHECK_EQUAL(r->one_min(), 1);
BOOST_CHECK_EQUAL(r->one_max(), 255);
BOOST_CHECK_EQUAL(kaitai::kstream::to_string(r->one_max()), std::string("255"));
BOOST_CHECK_EQUAL(r->two_size(), 3);
BOOST_CHECK_EQUAL(r->two_first(), 65);
BOOST_CHECK_EQUAL(r->two_mid(), 255);
BOOST_CHECK_EQUAL(kaitai::kstream::to_string(r->two_mid()), std::string("255"));
BOOST_CHECK_EQUAL(r->two_last(), 75);
BOOST_CHECK_EQUAL(r->two_min(), 65);
BOOST_CHECK_EQUAL(r->two_max(), 255);
BOOST_CHECK_EQUAL(kaitai::kstream::to_string(r->two_max()), std::string("255"));
delete r;
}
|
//=========================================================================
// Copyright (C) 2012 The Elastos Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//=========================================================================
#include "SSLSocketFactory.h"
#include "CDefaultSSLSocketFactory.h"
#include "AutoLock.h"
#include "Thread.h"
#include "CSecurity.h"
#include "SSLContext.h"
#include "org/apache/harmony/security/fortress/Services.h"
using Elastos::Core::AutoLock;
using Elastos::Core::Thread;
using Elastos::Core::IThread;
using Elastos::Core::IClassLoader;
using Elastos::Security::CSecurity;
using Elastos::Security::ISecurity;
using Elastosx::Net::Ssl::CDefaultSSLSocketFactory;
using Org::Apache::Harmony::Security::Fortress::Services;
namespace Elastosx {
namespace Net {
namespace Ssl {
INIT_PROI_6 AutoPtr<ISocketFactory> SSLSocketFactory::sDefaultSocketFactory;
Int32 SSLSocketFactory::sLastCacheVersion = -1;
INIT_PROI_6 Object SSLSocketFactory::sLock;
CAR_INTERFACE_IMPL(SSLSocketFactory, SocketFactory, ISSLSocketFactory)
SSLSocketFactory::SSLSocketFactory()
{}
SSLSocketFactory::~SSLSocketFactory()
{}
ECode SSLSocketFactory::GetDefault(
/* [out] */ ISocketFactory** factory)
{
VALIDATE_NOT_NULL(factory)
{ AutoLock syncLock(sLock);
assert(sLastCacheVersion == -1);
Int32 newCacheVersion;
FAIL_RETURN(Services::GetCacheVersion(&newCacheVersion));
if (sDefaultSocketFactory != NULL && sLastCacheVersion == newCacheVersion) {
*factory = sDefaultSocketFactory;
REFCOUNT_ADD(*factory);
return NOERROR;
}
sLastCacheVersion = newCacheVersion;
String newName;
AutoPtr<ISecurity> security;
CSecurity::AcquireSingleton((ISecurity**)&security);
FAIL_RETURN(security->GetProperty(String("ssl.SocketFactory.provider"), &newName));
if (!newName.IsNull()) {
/* The cache could have been invalidated, but the provider name didn't change. This
* will be the most common state, so check for it early without resetting the default
* SocketFactory.
*/
if (sDefaultSocketFactory != NULL) {
assert(0 && "TODO");
if (0/*newName.Equals(sDefaultSocketFactory.getClass().getName())*/) {
*factory = sDefaultSocketFactory;
REFCOUNT_ADD(*factory);
return NOERROR;
}
else {
sDefaultSocketFactory = NULL;
}
}
AutoPtr<IThread> thread = Thread::GetCurrentThread();
AutoPtr<IClassLoader> cl;
FAIL_RETURN(thread->GetContextClassLoader((IClassLoader**)&cl))
assert(0 && "TODO");
// if (cl == NULL) {
// cl = ClassLoader.getSystemClassLoader();
// }
// try {
// final Class<?> sfc = Class.forName(newName, true, cl);
// sDefaultSocketFactory = (SocketFactory) sfc.newInstance();
// } catch (Exception e) {
// System.logW("Could not create " + newName + " with ClassLoader "
// + cl.toString() + ": " + e.getMessage());
// }
} else {
sDefaultSocketFactory = NULL;
}
if (sDefaultSocketFactory == NULL) {
AutoPtr<ISSLContext> context;
ECode ec = NOERROR;
//try {
ec = SSLContext::GetDefault((ISSLContext**)&context);
//} catch (NoSuchAlgorithmException e) {
if (!SUCCEEDED(ec)) {
context = NULL;
}
//}
if (context != NULL) {
AutoPtr<ISSLServerSocketFactory> _factory;
FAIL_RETURN(context->GetServerSocketFactory((ISSLServerSocketFactory**)&_factory))
sDefaultSocketFactory = ISocketFactory::Probe(_factory);
}
}
if (sDefaultSocketFactory == NULL) {
// Use internal implementation
CDefaultSSLSocketFactory::New(String("No SSLSocketFactory installed"), (ISocketFactory**)&sDefaultSocketFactory);
}
*factory = sDefaultSocketFactory;
REFCOUNT_ADD(*factory);
return NOERROR;
}
}
} // namespace Ssl
} // namespace Net
} // namespace Elastosx
|
#include <array>
#include <seastar/core/byteorder.hh>
#include <CQLDriver/Common/Exceptions/DecodeException.hpp>
#include <CQLDriver/Common/CommonDefinitions.hpp>
#include "./ProtocolVariableIntegerBase.hpp"
namespace cql {
namespace {
/** The first byte use to indicate how many extra bytes followed */
static const std::array<std::uint8_t, 9> ExtraBytesHeaders({
0b00000000,
0b10000000,
0b11000000,
0b11100000,
0b11110000,
0b11111000,
0b11111100,
0b11111110,
0b11111111
});
}
/** Encode to binary data */
void ProtocolVariableIntegerBase::encode(std::string& data) const {
std::uint64_t valueBe = seastar::cpu_to_be(value_);
const char* ptr = reinterpret_cast<const char*>(&valueBe);
const char* end = ptr + sizeof(valueBe);
// trim empty bytes and calculate total bytes
while (ptr < end && *ptr == 0) {
++ptr;
}
std::size_t totalBytes = end - ptr;
if (totalBytes == 0) {
// value is 0
data.append("\x00", 1);
} else {
// check the header can embed to the first byte
std::uint8_t header = ExtraBytesHeaders[totalBytes];
if ((header & static_cast<std::uint8_t>(*ptr)) != 0) {
data.append(reinterpret_cast<const char*>(&header), 1);
data.append(ptr, totalBytes);
} else {
header = *ptr | ExtraBytesHeaders[totalBytes-1];
data.append(reinterpret_cast<const char*>(&header), 1);
data.append(ptr+1, totalBytes-1);
}
}
}
/** Decode from binary data */
void ProtocolVariableIntegerBase::decode(const char*& ptr, const char* end) {
if (CQL_UNLIKELY(ptr + sizeof(char) > end)) {
throw DecodeException(CQL_CODEINFO, "length not enough");
}
// read header
std::uint8_t header = static_cast<std::uint8_t>(*ptr);
std::size_t extraBytes = 0;
#if defined(__i386__) || defined(__amd64__)
static const constexpr std::size_t bitsDistance = (sizeof(unsigned int) - 1) * 8;
static_assert(bitsDistance > 0, "ensure ~(header << bitsDistance) != 0");
extraBytes = __builtin_clz(~(static_cast<unsigned int>(header) << bitsDistance));
header = static_cast<uint8_t>(header << extraBytes) >> extraBytes;
#else
while (header & 0b10000000) {
++extraBytes;
header <<= 1;
}
header >>= extraBytes;
#endif
++ptr;
// read extra bytes
if (CQL_UNLIKELY(ptr + extraBytes > end)) {
throw DecodeException(CQL_CODEINFO, "length not enough");
}
value_ = header;
for (std::size_t i = 0; i < extraBytes; ++i) {
value_ = (value_ << 8) | static_cast<std::uint8_t>(ptr[i]);
}
ptr += extraBytes;
}
}
|
/*
* SPDX-License-Identifier: Apache-2.0
*/
#include "include/onnx-mlir/Runtime/OMInstrument.h"
#include <chrono>
#include <thread>
int main(int argc, char *argv[]) {
const char opstart[8] = "TOpStar";
const char op2[8] = "TOp2";
const char op3[8] = "TOp3";
const char op4[8] = "TOp4";
const char opfinal[8] = "TOpFin";
OMInstrumentInit();
OMInstrumentPoint(*(const int64_t*)opstart, 13);
OMInstrumentPoint(*(const int64_t*)op2, 1);
OMInstrumentPoint(*(const int64_t*)op3, 4);
OMInstrumentPoint(*(const int64_t*)op4, 9);
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
OMInstrumentPoint(*(const int64_t*)opfinal, 12);
return 0;
}
|
// Copyright 2021 Tangent Animation
//
// 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,
// including without limitation, as related to merchantability and fitness
// for a particular purpose.
//
// In no event shall any copyright holder be liable for any damages of any kind
// arising from the use of this software, whether in contract, tort or otherwise.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "objectSource.h"
#include <pxr/imaging/hd/tokens.h>
#include <graph/node.h>
#include <render/geometry.h>
#include <render/object.h>
PXR_NAMESPACE_USING_DIRECTIVE
HdCyclesObjectSource::HdCyclesObjectSource(ccl::Object* object, const SdfPath& id, bool isReference)
: m_object { object }
, m_id { id }
, m_isReference { isReference }
{
m_object->name = ccl::ustring { m_id.GetToken().GetText(), m_id.GetToken().size() };
}
HdCyclesObjectSource::~HdCyclesObjectSource()
{
if (!m_isReference) {
assert(m_object != nullptr);
delete m_object->geometry;
delete m_object;
}
}
bool
HdCyclesObjectSource::Resolve()
{
if (!_TryLock()) {
return false;
}
// TODO bind ot the scene?
// marked as finished
_SetResolved();
return true;
}
HdBbbObjectPropertiesSource*
HdCyclesObjectSource::AddObjectPropertiesSource(HdBbbObjectPropertiesSourceSharedPtr source)
{
const TfToken& name = source->GetName();
m_pending_properties[name] = std::move(source);
return m_pending_properties[name].get();
}
HdBbAttributeSource*
HdCyclesObjectSource::AddAttributeSource(HdBbAttributeSourceSharedPtr source)
{
const TfToken& name = source->GetName();
m_pending_attributes[name] = std::move(source);
return m_pending_attributes[name].get();
}
const TfToken&
HdCyclesObjectSource::GetName() const
{
return m_id.GetToken();
}
size_t
HdCyclesObjectSource::ResolvePendingSources()
{
size_t num_resolved_sources = 0;
for (auto& source : m_pending_properties) {
if (!source.second->IsValid()) {
continue;
}
if(source.second->IsResolved()) {
continue;
}
source.second->Resolve();
++num_resolved_sources;
}
// resolve pending sources
for (auto& source : m_pending_attributes) {
if (!source.second->IsValid()) {
continue;
}
if(source.second->IsResolved()) {
continue;
}
source.second->Resolve();
++num_resolved_sources;
}
// cleanup sources right after the resolve
m_pending_properties.clear();
m_pending_attributes.clear();
return num_resolved_sources;
}
|
#ifndef BONJOUR_ADDRESS_RESOLVER_HPP__
#define BONJOUR_ADDRESS_RESOLVER_HPP__
#include <boost/noncopyable.hpp>
#include <boost/asio.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <ddnspp/bonjourpp/dnsd_callback.hpp> /// callback func def
#include <ddnspp/bonjourpp/dnsdapi.hpp>
#include <ddnspp/bonjourpp/core.hpp>
#include <ddnspp/bonjourpp/bonjourerror.hpp>
#include <ddnspp/bonjourpp/servicetype.hpp>
#include <ddnspp/logv/logv.hpp>
namespace air
{
namespace bonjour
{
class ServiceFactory;
/// AddressResolver
/// Queries for the IP address of a hostname by using either Multicast or Unicast DNS
class AddressResolver:boost::noncopyable,public boost::enable_shared_from_this<AddressResolver>
{
friend class ServiceFactory;
private:
CoreContextPtr core;
AddressResolverEvtCallback evtCallback;
public:
AddressResolver(boost::asio::io_service& ios,const DNSDApi &dll,const AddressResolverEvtCallback& func)
:core(new CoreContext(ios,dll)),evtCallback(func)
{
}
~AddressResolver()
{
//LOG_DEBUG<<"AddressResolver dead";
}
CoreContextPtr getCoreContext()
{
return core;
}
void close()
{
core->close();
}
/// return old one
AddressResolverEvtCallback setEvtCallback(const AddressResolverEvtCallback& func)
{
AddressResolverEvtCallback old=evtCallback;
evtCallback=func;
return old;
}
private:
static void DNSSD_API DNSServiceGetAddrInfoReplyCallback(
DNSServiceRef sdRef,
DNSServiceFlags flags,
uint32_t interfaceIndex,
DNSServiceErrorType errorCode,
const char *hostname,
const struct sockaddr *address,
uint32_t ttl,
void *context
)
{
AddressResolver* thisService=NULL;
if(context != NULL) {
thisService=(AddressResolver*)context;
thisService->evtHanler(sdRef,flags,interfaceIndex,errorCode,hostname,address,ttl,context);
}
}
//Possible values are kDNSServiceFlagsMoreComing and kDNSServiceFlagsAdd.
void evtHanler(
DNSServiceRef sdRef,
DNSServiceFlags flags,
uint32_t interfaceIndex,
DNSServiceErrorType errorCode,
const char *hostname,
const struct sockaddr *address,
uint32_t ttl,
void *context)
{
air::bonjour::BonjourError err(errorCode);
/*
bool moreData=(flags & kDNSServiceFlagsMoreComing);
if (moreData) return;
*/
boost::asio::ip::address warped_address;
if(!err && NULL != address) {
if (AF_INET == address->sa_family ) {
boost::uint32_t be32=air::common::as_be32(reinterpret_cast<const struct sockaddr_in*>(address)->sin_addr.s_addr);
warped_address = boost::asio::ip::address_v4(be32);
} else if (AF_INET6 == address->sa_family) {
boost::asio::ip::address_v6::bytes_type addr_bytes;
for (int i=0; i< 16; i++) {
addr_bytes[i] = reinterpret_cast<const struct sockaddr_in6*>(address)->sin6_addr.s6_addr[i];
}
warped_address=boost::asio::ip::address_v6 (
addr_bytes,
reinterpret_cast<const struct sockaddr_in6*>(address)->sin6_scope_id);
} else {
//bug here!
}
}
if(err) {
LOG_ERR<<err.getErrorCode()<<"," <<err.getMessage();
} else {
if (flags & kDNSServiceFlagsAdd) {
LOG_TRACE<<"Addres added";
} else {
LOG_TRACE<<"Addres removed";
}
LOG_TRACE<<"flags:"<< flags;
LOG_TRACE<<"interfaceIndex:"<< interfaceIndex;
LOG_TRACE<<"hostname:"<< hostname;
LOG_TRACE<<"address:"<<warped_address;
LOG_TRACE<<"ttl:"<<ttl;
}
if(evtCallback) {
air::bonjour::AddressResolveData data;
data.addr = warped_address;
data.error = err;
data.flags = flags;
data.hostName = hostname;
data.interfaceIndex = interfaceIndex;
data.ttl = ttl;
data.owner = shared_from_this();
evtCallback(data);
}
}
};
typedef boost::shared_ptr<AddressResolver> AddressResolverPtr;
}
}
#endif // BONJOUR_ADDRESS_RESOLVER_HPP__
|
////////////////////////////////////////////////////////////////////////
// Avni Utility functions
////////////////////////////////////////////////////////////////////////
// Includes
#include "AvniInterfaces.h"
#include <stdio.h>
#include <stdarg.h>
#include <Windows.h>
namespace Avni
{
void Log(char* str, int numarg , ... ) // supports only float and integer, maximum 10 nos
{
static char string[512];
if(numarg)
{
va_list arglist;
va_start(arglist, numarg);
sprintf_s(str, strlen(str), string, arglist);
va_end(arglist);
}
else
{
strcpy_s(string,(const char*)str);
}
// Write to the console
OutputDebugStringA(string);
}
}
|
#include "mock_bitcoinRPCFacade.h"
MockBitcoinRPCFacade::~MockBitcoinRPCFacade() = default;
|
/*
Copyright (c) 2019 - 2022 Advanced Micro Devices, Inc. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include <device_manager.h>
#include "ring_buffer.h"
RingBuffer::RingBuffer(unsigned buffer_depth):
BUFF_DEPTH(buffer_depth),
_dev_sub_buffer(buffer_depth),
_host_master_buffers(BUFF_DEPTH)
{
reset();
}
void RingBuffer::block_if_empty()
{
std::unique_lock<std::mutex> lock(_lock);
if(empty())
{ // if the current read buffer is being written wait on it
if(_dont_block)
return;
_wait_for_load.wait(lock);
}
}
void RingBuffer:: block_if_full()
{
std::unique_lock<std::mutex> lock(_lock);
// Write the whole buffer except for the last spot which is being read by the reader thread
if(full())
{
if(_dont_block)
return;
_wait_for_unload.wait(lock);
}
}
std::vector<void*> RingBuffer::get_read_buffers()
{
block_if_empty();
if((_mem_type == RaliMemType::OCL) || (_mem_type == RaliMemType::HIP))
return _dev_sub_buffer[_read_ptr];
return _host_sub_buffers[_read_ptr];
}
void *RingBuffer::get_host_master_read_buffer() {
block_if_empty();
if((_mem_type == RaliMemType::OCL) || (_mem_type == RaliMemType::HIP))
return nullptr;
return _host_master_buffers[_read_ptr];
}
std::vector<void*> RingBuffer::get_write_buffers()
{
block_if_full();
if((_mem_type == RaliMemType::OCL) || (_mem_type == RaliMemType::HIP))
return _dev_sub_buffer[_write_ptr];
return _host_sub_buffers[_write_ptr];
}
void RingBuffer::unblock_reader()
{
// Wake up the reader thread in case it's waiting for a load
_wait_for_load.notify_all();
}
void RingBuffer::release_all_blocked_calls()
{
_dont_block = true;
unblock_reader();
unblock_writer();
}
void RingBuffer::release_if_empty()
{
if (empty()) unblock_reader();
}
void RingBuffer::unblock_writer()
{
// Wake up the writer thread in case it's waiting for an unload
_wait_for_unload.notify_all();
}
#if !ENABLE_HIP
void RingBuffer::init(RaliMemType mem_type, DeviceResources dev, unsigned sub_buffer_size, unsigned sub_buffer_count)
{
_mem_type = mem_type;
_dev = dev;
_sub_buffer_size = sub_buffer_size;
_sub_buffer_count = sub_buffer_count;
if(BUFF_DEPTH < 2)
THROW ("Error internal buffer size for the ring buffer should be greater than one")
// Allocating buffers
if(mem_type== RaliMemType::OCL)
{
if(_dev.cmd_queue == nullptr || _dev.device_id == nullptr || _dev.context == nullptr)
THROW("Error ocl structure needed since memory type is OCL");
cl_int err = CL_SUCCESS;
for(size_t buffIdx = 0; buffIdx < BUFF_DEPTH; buffIdx++)
{
cl_mem_flags flags = CL_MEM_READ_ONLY;
_dev_sub_buffer[buffIdx].resize(_sub_buffer_count);
for(unsigned sub_idx = 0; sub_idx < _sub_buffer_count; sub_idx++)
{
_dev_sub_buffer[buffIdx][sub_idx] = clCreateBuffer(_dev.context, flags, sub_buffer_size, NULL, &err);
if(err)
{
_dev_sub_buffer.clear();
THROW("clCreateBuffer of size " + TOSTR(sub_buffer_size) + " index " + TOSTR(sub_idx) +
" failed " + TOSTR(err));
}
clRetainMemObject((cl_mem)_dev_sub_buffer[buffIdx][sub_idx]);
}
}
}
else
{
_host_sub_buffers.resize(BUFF_DEPTH);
for(size_t buffIdx = 0; buffIdx < BUFF_DEPTH; buffIdx++)
{
const size_t master_buffer_size = sub_buffer_size * sub_buffer_count;
// a minimum of extra MEM_ALIGNMENT is allocated
_host_master_buffers[buffIdx] = aligned_alloc(MEM_ALIGNMENT, MEM_ALIGNMENT * (master_buffer_size / MEM_ALIGNMENT + 1));
_host_sub_buffers[buffIdx].resize(_sub_buffer_count);
for(size_t sub_buff_idx = 0; sub_buff_idx < _sub_buffer_count; sub_buff_idx++)
_host_sub_buffers[buffIdx][sub_buff_idx] = (unsigned char*)_host_master_buffers[buffIdx] + _sub_buffer_size * sub_buff_idx;
}
}
}
#else
void RingBuffer::initHip(RaliMemType mem_type, DeviceResourcesHip dev, unsigned sub_buffer_size, unsigned sub_buffer_count)
{
_mem_type = mem_type;
_devhip = dev;
_sub_buffer_size = sub_buffer_size;
_sub_buffer_count = sub_buffer_count;
if(BUFF_DEPTH < 2)
THROW ("Error internal buffer size for the ring buffer should be greater than one")
// Allocating buffers
if(_mem_type == RaliMemType::HIP)
{
if(_devhip.hip_stream == nullptr || _devhip.device_id == -1 )
THROW("Error Hip Device is not initialzed");
for(size_t buffIdx = 0; buffIdx < BUFF_DEPTH; buffIdx++)
{
_dev_sub_buffer[buffIdx].resize(_sub_buffer_count);
for(unsigned sub_idx = 0; sub_idx < _sub_buffer_count; sub_idx++)
{
hipError_t err = hipMalloc(&_dev_sub_buffer[buffIdx][sub_idx], sub_buffer_size);
//printf("allocated HIP device buffer <%d, %d, %d, %p>\n", buffIdx, sub_idx, sub_buffer_size, _dev_sub_buffer[buffIdx][sub_idx]);
if(err != hipSuccess)
{
_dev_sub_buffer.clear();
THROW("hipMalloc of size " + TOSTR(sub_buffer_size) + " index " + TOSTR(sub_idx) +
" failed " + TOSTR(err));
}
}
}
}
else
{
_host_sub_buffers.resize(BUFF_DEPTH);
for(size_t buffIdx = 0; buffIdx < BUFF_DEPTH; buffIdx++)
{
const size_t master_buffer_size = sub_buffer_size * sub_buffer_count;
// a minimum of extra MEM_ALIGNMENT is allocated
_host_master_buffers[buffIdx] = aligned_alloc(MEM_ALIGNMENT, MEM_ALIGNMENT * (master_buffer_size / MEM_ALIGNMENT + 1));
_host_sub_buffers[buffIdx].resize(_sub_buffer_count);
for(size_t sub_buff_idx = 0; sub_buff_idx < _sub_buffer_count; sub_buff_idx++)
_host_sub_buffers[buffIdx][sub_buff_idx] = (unsigned char*)_host_master_buffers[buffIdx] + _sub_buffer_size * sub_buff_idx;
}
}
}
#endif
void RingBuffer::push()
{
// pushing and popping to and from image and metadata buffer should be atomic so that their level stays the same at all times
std::unique_lock<std::mutex> lock(_names_buff_lock);
_meta_ring_buffer.push(_last_image_meta_data);
increment_write_ptr();
}
void RingBuffer::pop()
{
if(empty())
return;
// pushing and popping to and from image and metadata buffer should be atomic so that their level stays the same at all times
std::unique_lock<std::mutex> lock(_names_buff_lock);
increment_read_ptr();
_meta_ring_buffer.pop();
}
void RingBuffer::reset()
{
_write_ptr = 0;
_read_ptr = 0;
_level = 0;
_dont_block = false;
while(!_meta_ring_buffer.empty())
_meta_ring_buffer.pop();
}
void RingBuffer::release_gpu_res()
{
#if ENABLE_HIP
if (_mem_type == RaliMemType::HIP) {
for (size_t buffIdx = 0; buffIdx < _dev_sub_buffer.size(); buffIdx++){
for (unsigned sub_buf_idx = 0; sub_buf_idx < _dev_sub_buffer[buffIdx].size(); sub_buf_idx++){
if (_dev_sub_buffer[buffIdx][sub_buf_idx])
if ( hipFree((void *)_dev_sub_buffer[buffIdx][sub_buf_idx]) != hipSuccess ) {
//printf("Error Freeing device buffer <%d, %d, %p>\n", buffIdx, sub_buf_idx, _dev_sub_buffer[buffIdx][sub_buf_idx]);
ERR("Could not release hip memory in the ring buffer")
}
}
}
_dev_sub_buffer.clear();
}
#elif ENABLE_OPENCL
if (_mem_type == RaliMemType::OCL) {
for (size_t buffIdx = 0; buffIdx < _dev_sub_buffer.size(); buffIdx++)
for (unsigned sub_buf_idx = 0; sub_buf_idx < _dev_sub_buffer[buffIdx].size(); sub_buf_idx++)
if (_dev_sub_buffer[buffIdx][sub_buf_idx])
if (clReleaseMemObject((cl_mem) _dev_sub_buffer[buffIdx][sub_buf_idx]) != CL_SUCCESS)
ERR("Could not release ocl memory in the ring buffer")
_dev_sub_buffer.clear();
}
#endif
}
RingBuffer::~RingBuffer()
{
if (_mem_type == RaliMemType::HOST) {
for (unsigned idx = 0; idx < _host_master_buffers.size(); idx++)
if (_host_master_buffers[idx]) {
free(_host_master_buffers[idx]);
}
_host_master_buffers.clear();
_host_sub_buffers.clear();
}
}
bool RingBuffer::empty()
{
return (_level <= 0);
}
bool RingBuffer::full()
{
return (_level >= BUFF_DEPTH - 1);
}
size_t RingBuffer::level()
{
return _level;
}
void RingBuffer::increment_read_ptr()
{
std::unique_lock<std::mutex> lock(_lock);
_read_ptr = (_read_ptr+1)%BUFF_DEPTH;
_level--;
lock.unlock();
// Wake up the writer thread (in case waiting) since there is an empty spot to write to,
_wait_for_unload.notify_all();
}
void RingBuffer::increment_write_ptr()
{
std::unique_lock<std::mutex> lock(_lock);
_write_ptr = (_write_ptr+1)%BUFF_DEPTH;
_level++;
lock.unlock();
// Wake up the reader thread (in case waiting) since there is a new load to be read
_wait_for_load.notify_all();
}
void RingBuffer::set_meta_data( ImageNameBatch names, pMetaDataBatch meta_data)
{
_last_image_meta_data = std::move(std::make_pair(std::move(names), meta_data));
}
MetaDataNamePair& RingBuffer::get_meta_data()
{
block_if_empty();
std::unique_lock<std::mutex> lock(_names_buff_lock);
if(_level != _meta_ring_buffer.size())
THROW("ring buffer internals error, image and metadata sizes not the same "+TOSTR(_level) + " != "+TOSTR(_meta_ring_buffer.size()))
return _meta_ring_buffer.front();
}
|
/* This file is part of the Gudhi Library. The Gudhi library
* (Geometric Understanding in Higher Dimensions) is a generic C++
* library for computational topology.
*
* Author(s): Pawel Dlotko
*
* Copyright (C) 2015 INRIA Saclay (France)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
// for persistence algorithm
#include <gudhi/reader_utils.h>
#include <gudhi/Bitmap_cubical_complex.h>
#include <gudhi/Persistent_cohomology.h>
// standard stuff
#include <iostream>
#include <sstream>
#include <vector>
int main(int argc, char** argv) {
srand(time(0));
std::cout
<< "This program computes persistent homology, by using bitmap_cubical_complex class, of cubical "
<< "complexes. The first parameter of the program is the dimension D of the bitmap. The next D parameters are "
<< "number of top dimensional cubes in each dimension of the bitmap. The program will create random cubical "
<< "complex of that sizes and compute persistent homology of it." << std::endl;
int p = 2;
double min_persistence = 0;
if (argc < 3) {
std::cerr << "Wrong number of parameters, the program will now terminate\n";
return 1;
}
size_t dimensionOfBitmap = (size_t)atoi(argv[1]);
std::vector<unsigned> sizes;
size_t multipliers = 1;
for (size_t dim = 0; dim != dimensionOfBitmap; ++dim) {
unsigned sizeInThisDimension = (unsigned)atoi(argv[2 + dim]);
sizes.push_back(sizeInThisDimension);
multipliers *= sizeInThisDimension;
}
std::vector<double> data;
for (size_t i = 0; i != multipliers; ++i) {
data.push_back(rand() / static_cast<double>(RAND_MAX));
}
typedef Gudhi::cubical_complex::Bitmap_cubical_complex_base<double> Bitmap_cubical_complex_base;
typedef Gudhi::cubical_complex::Bitmap_cubical_complex<Bitmap_cubical_complex_base> Bitmap_cubical_complex;
Bitmap_cubical_complex b(sizes, data);
// Compute the persistence diagram of the complex
typedef Gudhi::persistent_cohomology::Field_Zp Field_Zp;
typedef Gudhi::persistent_cohomology::Persistent_cohomology<Bitmap_cubical_complex, Field_Zp> Persistent_cohomology;
Persistent_cohomology pcoh(b);
pcoh.init_coefficients(p); // initializes the coefficient field for homology
pcoh.compute_persistent_cohomology(min_persistence);
std::stringstream ss;
ss << "randomComplex_persistence";
std::ofstream out(ss.str().c_str());
pcoh.output_diagram(out);
out.close();
return 0;
}
|
#include "IMU_MPU6050.h"
struct accel_data
{
int XAxis;
int YAxis;
int ZAxis;
}raw_accel;
struct gyro_data
{
int XAxis;
int YAxis;
int ZAxis;
}raw_gyro;
void MPU6050::initialize()
{
raw_accel.XAxis=raw_accel.YAxis=raw_accel.ZAxis=0;
raw_gyro.XAxis=raw_gyro.YAxis=raw_gyro.ZAxis=0;
accel_roll=0;
accel_pitch=0;
gyro_rateX=0;
gyro_rateY=0;
gyro_rateZ=0;
temperature=0;
gyro_sensitivity=131;
i2c_init();
setSampleRateDivider(0x07);
i2c_start(MPU6050_WRITE);
i2c_write(MPU6050_INT_PIN_CFG); //set pointer to interrupt enable register
i2c_write(0x00); //set interrupt enable
i2c_stop();
i2c_start(MPU6050_WRITE);
i2c_write(MPU6050_INT_ENABLE); //set pointer to interrupt sources enable register
i2c_write(0x00); //set data ready interrupt
i2c_stop();
i2c_start(MPU6050_WRITE);
i2c_write(MPU6050_PWR_MGMT_1); //set pointer to power management register 1
i2c_write(MPU6050_CLOCK_PLL_XGYRO); //set clock to gyro clock reference
i2c_stop();
}
unsigned char MPU6050::MPU6050_readRegister(unsigned char register_addr)
{
char tempdata;
i2c_start(MPU6050_WRITE);
i2c_write(register_addr);
i2c_stop();
i2c_rep_start(MPU6050_READ);
tempdata=i2c_read();
i2c_stop();
return tempdata;
}
void MPU6050::MPU6050_writeRegister(unsigned char register_addr,unsigned char data)
{
i2c_start(MPU6050_WRITE);
i2c_write(register_addr);
i2c_write(data);
i2c_stop();
}
void MPU6050::SetAccelRange(unsigned char acrange)
{
i2c_start(MPU6050_WRITE);
i2c_write(MPU6050_ACCEL_CONFIG); //set pointer to accelerometer configuration register
i2c_write(acrange); //set accelerometer scale to 2g
i2c_stop();
}
void MPU6050::SetGyroRange(unsigned char gyrange)
{
i2c_start(MPU6050_WRITE);
i2c_write(MPU6050_GYRO_CONFIG); //set pointer to gyro configuration register
i2c_write(gyrange); //set gyro scale to 500 degree/second
i2c_stop();
switch (gyrange)
{
case 0x00: gyro_sensitivity=131;
break;
case 0x01: gyro_sensitivity=65.5;
break;
case 0x02: gyro_sensitivity=32.8;
break;
case 0x03: gyro_sensitivity=16.4;
break;
}
}
void MPU6050::setSampleRateDivider(unsigned char rate)
{
i2c_start(MPU6050_WRITE);
i2c_write(MPU6050_SMPLRT_DIV); // set pointer to sample rate divider
i2c_write(rate); //e.g.when divider=7, sample rate becomes 8000/(1+7)=1000HZ
i2c_stop();
}
void MPU6050::Calibrate_accel()
{
}
void MPU6050::Calibrate_gyro()
{
}
void MPU6050::Read_raw_accel_angle()
{
raw_accel.XAxis=(MPU6050_readRegister(MPU6050_ACCEL_XOUT_H))<<8;
raw_accel.XAxis |=(MPU6050_readRegister(MPU6050_ACCEL_XOUT_L));
raw_accel.YAxis=(MPU6050_readRegister(MPU6050_ACCEL_YOUT_H))<<8;
raw_accel.YAxis |=(MPU6050_readRegister(MPU6050_ACCEL_YOUT_L));
raw_accel.ZAxis=(MPU6050_readRegister(MPU6050_ACCEL_ZOUT_H))<<8;
raw_accel.ZAxis |=(MPU6050_readRegister(MPU6050_ACCEL_ZOUT_L));
}
void MPU6050::Read_raw_gyro_rate()
{
raw_gyro.XAxis = (MPU6050_readRegister(MPU6050_GYRO_XOUT_H))<<8;
raw_gyro.XAxis |=(MPU6050_readRegister(MPU6050_GYRO_XOUT_L));
raw_gyro.YAxis = (MPU6050_readRegister(MPU6050_GYRO_YOUT_H))<<8;
raw_gyro.YAxis |= (MPU6050_readRegister(MPU6050_GYRO_YOUT_L));
raw_gyro.ZAxis = (MPU6050_readRegister(MPU6050_GYRO_ZOUT_H))<<8;
raw_gyro.ZAxis |= (MPU6050_readRegister(MPU6050_GYRO_ZOUT_L));
}
float MPU6050::readTemperature()
{
float temp;
temperature = (MPU6050_readRegister(MPU6050_TEMP_OUT_H))<<8;
temperature |= (MPU6050_readRegister(MPU6050_TEMP_OUT_L));
temp=(float)temperature/340+36.53;
return temp;
}
void MPU6050::setDLPF_bandwidth()
{
}
void MPU6050::Read_MPU6050()
{
Read_raw_accel_angle();
Read_raw_gyro_rate();
// accel_roll= 57.295*atan((float)raw_accel.YAxis/ sqrt(pow((float)raw_accel.ZAxis,2)+pow((float)raw_accel.XAxis,2))); //180/PI =57.295
// accel_pitch = 57.295*atan((float)-raw_accel.XAxis/ sqrt(pow((float)raw_accel.ZAxis,2)+pow((float)raw_accel.YAxis,2)));
accel_roll= 57.295*atan2((float)raw_accel.YAxis,(float)raw_accel.ZAxis); //180/PI =57.295
accel_pitch = 57.295*atan2((float)-raw_accel.XAxis,(float)raw_accel.ZAxis);
gyro_rateX = (float)raw_gyro.XAxis/gyro_sensitivity;
gyro_rateY = (float)raw_gyro.YAxis/gyro_sensitivity;
gyro_rateZ = (float)raw_gyro.ZAxis/gyro_sensitivity;
}
float MPU6050::get_pitch()
{
return accel_pitch;
}
float MPU6050::get_pitchrate()
{
return gyro_rateY;
}
void MPU6050::get_roll_pitch(float *roll,float *pitch)
{
*roll=accel_roll;
*pitch=accel_pitch;
}
void MPU6050::get_gyrorateXYZ(float *rx,float *ry,float *rz)
{
*rx=gyro_rateX;
*ry=gyro_rateY;
*rz=gyro_rateZ;
}
int MPU6050::accel_getZaxis()
{
return raw_accel.ZAxis;
}
int MPU6050::accel_getXaxis()
{
return raw_accel.XAxis;
}
|
#include "ssloader_sspj.h"
#include "ssloader_ssae.h"
#include "ssloader_ssce.h"
#include "ssloader_ssee.h"
#include "ssstring_uty.h"
#include "../Helper/DebugPrint.h"
namespace spritestudio6
{
SsEffectFile* ssloader_ssee::Load(const std::string& filename )
{
SsString _basepath = "";
SsEffectFile* effectFile = new SsEffectFile();
libXML::XMLDocument xml;
if ( libXML::XML_SUCCESS == xml.LoadFile( filename.c_str() ) )
{
SsXmlIArchiver ar( xml.GetDocument() , "SpriteStudioEffect" );
effectFile->__Serialize( &ar );
}else{
delete effectFile;
effectFile = 0;
}
return effectFile;
}
void ssloader_ssee::loadPostProcessing( SsEffectFile* file , SsProject* pj )
{
for ( size_t i = 0 ; i < file->effectData.nodeList.size(); i++)
{
SsEffectBehavior* beh = &file->effectData.nodeList[i]->behavior;
beh->refCell = 0;
if ( beh->CellMapName == "" )continue;
SsCellMap* map =pj->findCellMap( beh->CellMapName );
if ( map )
{
for ( size_t n = 0 ; n < map->cells.size() ; n++ )
{
if ( map->cells[n]->name == beh->CellName )
{
beh->refCell = map->cells[n];
}
}
if ( beh->refCell == 0 )
{
DEBUG_PRINTF("not fount cell : %s , %s", beh->CellMapName.c_str(), beh->CellName.c_str());
}
}
}
}
} // namespace spritestudio6
|
// itsy.bitsy
//
// Copyright ⓒ 2019-present ThePhD.
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// See https://github.com/ThePhD/itsy_bitsy#using-the-library for documentation.
#include <itsy/algorithm.hpp>
|
///////////////////////////////////////////////////////////////////////////////
// Name: tests/streams/socketstream.cpp
// Purpose: Test wxSocketInputStream/wxSocketOutputStream
// Author: Vadim Zeitlin
// Copyright: (c) 2008 Vadim Zeitlin
// Licence: wxWindows licence
///////////////////////////////////////////////////////////////////////////////
// For compilers that support precompilation, includes "wx/wx.h".
// and "wx/cppunit.h"
#include "testprec.h"
// for all others, include the necessary headers
#ifndef WX_PRECOMP
#include "wx/log.h"
#endif
#include "wx/socket.h"
#include "wx/sckstrm.h"
#include "wx/thread.h"
#include "bstream.h"
namespace
{
const int TEST_PORT_READ = 0x7778; // arbitrary, chosen because == "wx"
const int TEST_PORT_WRITE = 0x7779; // well, "wy"
// these cond and mutex are used to minimize the risk of the main thread
// Connect()-ing before this thread starts Accept()-ing connections but
// unfortunately we can't make this truly safe, see comment in
// SocketServerThread::Entry()
wxMutex gs_mutex;
wxCondition gs_cond(gs_mutex);
} // anonymous namespace
// return address for the given port on local host
static inline wxIPV4address LocalAddress(int port)
{
wxIPV4address addr;
addr.LocalHost();
addr.Service(port);
return addr;
}
// A thread which creates a listening socket on the specified port and executes
// the given function with each socket which connects to it
class SocketServerThread : public wxThread
{
public:
// port is the port to listen on and function will be called on each
// accepted socket
SocketServerThread(int port, void (*accept)(wxSocketBase&))
: wxThread(wxTHREAD_JOINABLE),
m_port(port),
m_accept(accept)
{
Create();
Run();
}
protected:
virtual void *Entry() wxOVERRIDE
{
wxSocketServer srv(LocalAddress(m_port), wxSOCKET_REUSEADDR);
CPPUNIT_ASSERT( srv.IsOk() );
// FIXME: this is still not atomic, of course and the main thread could
// call Connect() before we have time to Accept() but there is
// no way to fix it with current API
{
wxMutexLocker lock(gs_mutex);
gs_cond.Signal();
}
wxSocketBase *socket = srv.Accept();
if ( socket )
{
(*m_accept)(*socket);
delete socket;
}
return NULL;
}
int m_port;
void (*m_accept)(wxSocketBase&);
wxDECLARE_NO_COPY_CLASS(SocketServerThread);
};
// The test case for socket streams
class socketStream :
public BaseStreamTestCase<wxSocketInputStream, wxSocketOutputStream>
{
public:
socketStream();
virtual ~socketStream();
virtual void setUp() wxOVERRIDE;
virtual void tearDown() wxOVERRIDE;
// repeat all socket tests several times with different socket flags, so we
// define this macro which is used several times in the test suite
//
// there must be some more elegant way to do this but I didn't find it...
#define ALL_SOCKET_TESTS() \
CPPUNIT_TEST(Input_GetC); \
CPPUNIT_TEST(Input_Eof); \
CPPUNIT_TEST(Input_Read); \
CPPUNIT_TEST(Input_LastRead); \
CPPUNIT_TEST(Input_CanRead); \
CPPUNIT_TEST(Input_Peek); \
CPPUNIT_TEST(Input_Ungetch); \
\
CPPUNIT_TEST(Output_PutC); \
CPPUNIT_TEST(Output_Write); \
CPPUNIT_TEST(Output_LastWrite)
CPPUNIT_TEST_SUITE(socketStream);
ALL_SOCKET_TESTS();
// some tests don't pass with NOWAIT flag but this is probably not a
// bug (TODO: check this)
#if 0
CPPUNIT_TEST( PseudoTest_SetNoWait );
ALL_SOCKET_TESTS();
#endif
CPPUNIT_TEST( PseudoTest_SetWaitAll );
ALL_SOCKET_TESTS();
CPPUNIT_TEST_SUITE_END();
private:
// Implement base class functions.
virtual wxSocketInputStream *DoCreateInStream() wxOVERRIDE;
virtual wxSocketOutputStream *DoCreateOutStream() wxOVERRIDE;
virtual void DoCheckInputStream(wxSocketInputStream& stream_in) wxOVERRIDE;
// socket thread functions
static void WriteSocket(wxSocketBase& socket)
{
socket.Write("hello, world!", 13);
}
static void ReadSocket(wxSocketBase& socket)
{
char ch;
while ( socket.Read(&ch, 1).LastCount() == 1 )
;
}
void PseudoTest_SetNoWait() { ms_flags = wxSOCKET_NOWAIT; }
void PseudoTest_SetWaitAll() { ms_flags = wxSOCKET_WAITALL; }
wxSocketClient *m_readSocket,
*m_writeSocket;
wxThread *m_writeThread,
*m_readThread;
static wxSocketFlags ms_flags;
};
wxSocketFlags socketStream::ms_flags = wxSOCKET_NONE;
socketStream::socketStream()
{
m_readSocket =
m_writeSocket = NULL;
m_writeThread =
m_readThread = NULL;
wxSocketBase::Initialize();
}
socketStream::~socketStream()
{
wxSocketBase::Shutdown();
}
void socketStream::setUp()
{
// create the socket threads and wait until they are ready to accept
// connections (if we called Connect() before this happens, it would fail)
{
wxMutexLocker lock(gs_mutex);
m_writeThread =
new SocketServerThread(TEST_PORT_READ, &socketStream::WriteSocket);
CPPUNIT_ASSERT_EQUAL( wxCOND_NO_ERROR, gs_cond.Wait() );
m_readThread =
new SocketServerThread(TEST_PORT_WRITE, &socketStream::ReadSocket);
CPPUNIT_ASSERT_EQUAL( wxCOND_NO_ERROR, gs_cond.Wait() );
}
m_readSocket = new wxSocketClient(ms_flags);
CPPUNIT_ASSERT( m_readSocket->Connect(LocalAddress(TEST_PORT_READ)) );
m_writeSocket = new wxSocketClient(ms_flags);
CPPUNIT_ASSERT( m_writeSocket->Connect(LocalAddress(TEST_PORT_WRITE)) );
}
void socketStream::tearDown()
{
wxDELETE(m_readSocket);
wxDELETE(m_writeSocket);
m_writeThread->Wait();
wxDELETE(m_writeThread);
m_readThread->Wait();
wxDELETE(m_readThread);
}
wxSocketInputStream *socketStream::DoCreateInStream()
{
wxSocketInputStream *pStrInStream = new wxSocketInputStream(*m_readSocket);
CPPUNIT_ASSERT(pStrInStream->IsOk());
return pStrInStream;
}
wxSocketOutputStream *socketStream::DoCreateOutStream()
{
wxSocketOutputStream *pStrOutStream = new wxSocketOutputStream(*m_writeSocket);
CPPUNIT_ASSERT(pStrOutStream->IsOk());
return pStrOutStream;
}
void socketStream::DoCheckInputStream(wxSocketInputStream& stream_in)
{
// This check sometimes fails in the AppVeyor CI environment for unknown
// reason, so just log it there but don't fail the entire test suite run.
if ( wxGetEnv("APPVEYOR", NULL) )
{
if ( !stream_in.IsOk() )
{
WARN("Socket input stream test failed.\n"
<< "Socket error = " << m_readSocket->Error()
<< ", last count = " << m_readSocket->LastCount());
return;
}
}
CPPUNIT_ASSERT(stream_in.IsOk());
}
// Register the stream sub suite, by using some stream helper macro.
STREAM_TEST_SUBSUITE_NAMED_REGISTRATION(socketStream)
|
#ifndef _WINDOWEVENTS_H
#define _WINDOWEVENTS_H
#include "Delegate.hpp"
namespace ar
{
/*
* Provides an abstraction between incoming window input events and
* objects which need to consume them
*/
class WindowEvents
{
public:
// Calls all subscribed handlers for the corresponding events
void NotifyMouseButtonCallback(int button, int action, int mods);
void NotifyMouseMoveCallback(double xpos, double ypos);
void NotifyMouseEnterExitCallback(int entered);
void NotifyScrollCallback(double xoffset, double yoffset);
void NotifyKeyboardKeyCallback(int key, int scancode, int action, int mods);
void NotifyKeyboardCharCallback(unsigned int codepoint);
void NotifyWindowSizeCallback(int width, int height);
void NotifyFrameBufferSizeCallback(int width, int height);
void NotifyWindowCloseCallback();
// Don't know if it's useful to keep these getters around...
Delegate<void(int,int,int)>& GetMouseButtonDelegate() { return _mouseButtonDelegate; }
Delegate<void(int)>& GetMouseEnterExitDelegate() { return _mouseEnterExitDelegate; }
Delegate<void(double,double)>& GetMouseMoveDelegate() { return _mouseMoveDelegate; }
Delegate<void(int,int)>& GetWindowResizedDelegate() { return _windowResizedDelegate; }
Delegate<void(int,int)>& GetFrameBufferResizedDelegate() { return _frameBufferResizedDelegate; }
Delegate<void(int,int,int,int)>& GetKeyboardKeyDelegate() { return _keyboardKeyDelegate; }
Delegate<void(unsigned int)>& GetKeyboardCharDelegate() { return _keyboardCharDelegate; }
Delegate<void(double,double)>& GetScrollDelegate() { return _scrollDelegate; }
Delegate<void()>& GetWindowCloseDelegate() { return _windowCloseDelegate; }
private:
Delegate<void(int,int,int)> _mouseButtonDelegate;
Delegate<void(int)> _mouseEnterExitDelegate;
Delegate<void(double,double)> _mouseMoveDelegate;
Delegate<void(int,int)> _windowResizedDelegate;
Delegate<void(int,int)> _frameBufferResizedDelegate;
Delegate<void(int,int,int,int)> _keyboardKeyDelegate;
Delegate<void(unsigned int)> _keyboardCharDelegate;
Delegate<void(double,double)> _scrollDelegate;
Delegate<void()> _windowCloseDelegate;
};
} // namespace ar
#endif // _WINDOWEVENTS_H
|
/*
* Copyright (C) 2017-2019 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "runtime/command_stream/command_stream_receiver.h"
#include "runtime/helpers/options.h"
#include "runtime/helpers/ptr_math.h"
#include "runtime/mem_obj/buffer.h"
#include "test.h"
#include "unit_tests/aub_tests/command_queue/command_enqueue_fixture.h"
#include "unit_tests/mocks/mock_context.h"
#include <algorithm>
using namespace NEO;
struct CopyBufferRectHw
: public CommandEnqueueAUBFixture,
public ::testing::TestWithParam<std::tuple<size_t, size_t, size_t, size_t, size_t, size_t, bool>> {
void SetUp() override {
CommandEnqueueAUBFixture::SetUp();
std::tie(srcOrigin0, srcOrigin1, srcOrigin2, dstOrigin0, dstOrigin1, dstOrigin2, copy3D) = GetParam();
}
void TearDown() override {
CommandEnqueueAUBFixture::TearDown();
}
size_t srcOrigin0;
size_t srcOrigin1;
size_t srcOrigin2;
size_t dstOrigin0;
size_t dstOrigin1;
size_t dstOrigin2;
bool copy3D;
};
typedef CopyBufferRectHw AUBCopyBufferRect;
HWTEST_P(AUBCopyBufferRect, simple) {
//3D UINT8 buffer 20x20x20
static const size_t rowPitch = 20;
static const size_t slicePitch = rowPitch * rowPitch;
static const size_t elementCount = slicePitch * rowPitch;
MockContext context(this->pDevice);
cl_uchar *srcMemory = new uint8_t[elementCount + 8];
cl_uchar *dstMemory = new uint8_t[elementCount + 8];
for (size_t i = 0; i < elementCount; i++) {
srcMemory[i] = static_cast<cl_uchar>(i + 1);
dstMemory[i] = 0;
}
auto retVal = CL_INVALID_VALUE;
auto srcBuffer = Buffer::create(
&context,
CL_MEM_USE_HOST_PTR,
elementCount * sizeof(uint8_t),
srcMemory,
retVal);
ASSERT_NE(nullptr, srcBuffer);
auto dstBuffer = Buffer::create(
&context,
CL_MEM_USE_HOST_PTR,
elementCount * sizeof(uint8_t),
dstMemory,
retVal);
ASSERT_NE(nullptr, dstBuffer);
auto pSrcMemory = &srcMemory[0];
auto pDestMemory = (cl_uchar *)(dstBuffer->getGraphicsAllocation()->getGpuAddress());
size_t regionX = std::min(rowPitch / 2, rowPitch - std::max(srcOrigin0, dstOrigin0));
size_t regionY = std::min(rowPitch / 2, rowPitch - std::max(srcOrigin1, dstOrigin1));
size_t regionZ = copy3D ? std::min(rowPitch / 2, rowPitch - std::max(srcOrigin2, dstOrigin2)) : 1;
size_t srcOrigin[] = {srcOrigin0, srcOrigin1, srcOrigin2};
size_t dstOrigin[] = {dstOrigin0, dstOrigin1, dstOrigin2};
size_t region[] = {regionX, regionY, regionZ};
retVal = pCmdQ->enqueueCopyBufferRect(
srcBuffer,
dstBuffer,
srcOrigin,
dstOrigin,
region,
rowPitch,
slicePitch,
rowPitch,
slicePitch,
0,
nullptr,
nullptr);
EXPECT_EQ(CL_SUCCESS, retVal);
pCmdQ->flush();
// Verify Output, line by line
uint8_t src[rowPitch * slicePitch];
memset(src, 0, sizeof(src));
auto tDst = pDestMemory;
auto tSrc = ptrOffset(pSrcMemory, srcOrigin[0] + srcOrigin[1] * rowPitch + srcOrigin[2] * slicePitch);
auto tRef = ptrOffset(src, dstOrigin[0] + dstOrigin[1] * rowPitch + dstOrigin[2] * slicePitch);
for (unsigned int z = 0; z < regionZ; z++) {
auto pDst = tDst;
auto pSrc = tSrc;
auto pRef = tRef;
for (unsigned int y = 0; y < regionY; y++) {
memcpy(pRef, pSrc, region[0]);
pDst += rowPitch;
pSrc += rowPitch;
pRef += rowPitch;
}
tDst += slicePitch;
tSrc += slicePitch;
tRef += slicePitch;
}
AUBCommandStreamFixture::expectMemory<FamilyType>(pDestMemory, src, rowPitch * slicePitch);
delete srcBuffer;
delete dstBuffer;
delete[] srcMemory;
delete[] dstMemory;
}
static size_t zero[] = {0};
INSTANTIATE_TEST_CASE_P(AUBCopyBufferRect,
AUBCopyBufferRect,
::testing::Combine(
::testing::Values(0, 3), //srcOrigin
::testing::ValuesIn(zero),
::testing::Values(0, 7),
::testing::Values(0, 3), //dstPrigin
::testing::ValuesIn(zero),
::testing::Values(0, 7),
::testing::Values(true, false)));
|
// Dinic - O(V^2 * E)
// Bipartite graph or unit flow - O(sqrt(V) * E)
// Small flow - O(F * (V + E))
// USE INF = 1e9!
/**********************************************************************************
* DINIC (FIND MAX FLOW / BIPARTITE MATCHING) *
* Time complexity: O(EV^2) *
* Usage: dinic() *
* add_edge(from, to, capacity) *
* Testcase: *
* add_edge(src, 1, 1); add_edge(1, snk, 1); add_edge(2, 3, INF); *
* add_edge(src, 2, 1); add_edge(2, snk, 1); add_edge(3, 4, INF); *
* add_edge(src, 2, 1); add_edge(3, snk, 1); *
* add_edge(src, 2, 1); add_edge(4, snk, 1); => dinic() = 4 *
**********************************************************************************/
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5+1, INF = 1e9;
struct edge {int v, c, f;};
int n, src, snk, h[N], ptr[N];
vector<edge> edgs;
vector<int> g[N];
void add_edge (int u, int v, int c) {
int k = edgs.size();
edgs.push_back({v, c, 0});
edgs.push_back({u, 0, 0});
g[u].push_back(k);
g[v].push_back(k+1);
}
void clear() {
memset(h, 0, sizeof h);
memset(ptr, 0, sizeof ptr);
edgs.clear();
for (int i = 0; i < N; i++) g[i].clear();
src = 0;
snk = N-1;
}
bool bfs() {
memset(h, 0, sizeof h);
queue<int> q;
h[src] = 1;
q.push(src);
while(!q.empty()) {
int u = q.front(); q.pop();
for(int i : g[u]) {
int v = edgs[i].v;
if (!h[v] and edgs[i].f < edgs[i].c)
q.push(v), h[v] = h[u] + 1;
}
}
return h[snk];
}
int dfs (int u, int flow) {
if (!flow or u == snk) return flow;
for (int &i = ptr[u]; i < g[u].size(); ++i) {
edge &dir = edgs[g[u][i]], &rev = edgs[g[u][i]^1];
int v = dir.v;
if (h[v] != h[u] + 1) continue;
int inc = min(flow, dir.c - dir.f);
inc = dfs(v, inc);
if (inc) {
dir.f += inc, rev.f -= inc;
return inc;
}
}
return 0;
}
int dinic() {
int flow = 0;
while (bfs()) {
memset(ptr, 0, sizeof ptr);
while (int inc = dfs(src, INF)) flow += inc;
}
return flow;
}
int main () {
clear();
return 0;
}
|
// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2013 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "rpcprotocol.h"
#include "util.h"
#include <stdint.h>
#include <boost/algorithm/string.hpp>
#include <boost/asio.hpp>
#include <boost/asio/ssl.hpp>
#include <boost/bind.hpp>
#include <boost/filesystem.hpp>
#include <boost/foreach.hpp>
#include <boost/iostreams/concepts.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/shared_ptr.hpp>
#include "json/json_spirit_writer_template.h"
using namespace std;
using namespace boost;
using namespace boost::asio;
using namespace json_spirit;
//
// HTTP protocol
//
// This ain't Apache. We're just using HTTP header for the length field
// and to be compatible with other JSON-RPC implementations.
//
string HTTPPost(const string& strMsg, const map<string,string>& mapRequestHeaders)
{
ostringstream s;
s << "POST / HTTP/1.1\r\n"
<< "User-Agent: bcca-json-rpc/" << FormatFullVersion() << "\r\n"
<< "Host: 127.0.0.1\r\n"
<< "Content-Type: application/json\r\n"
<< "Content-Length: " << strMsg.size() << "\r\n"
<< "Connection: close\r\n"
<< "Accept: application/json\r\n";
BOOST_FOREACH(const PAIRTYPE(string, string)& item, mapRequestHeaders)
s << item.first << ": " << item.second << "\r\n";
s << "\r\n" << strMsg;
return s.str();
}
static string rfc1123Time()
{
return DateTimeStrFormat("%a, %d %b %Y %H:%M:%S +0000", GetTime());
}
string HTTPReply(int nStatus, const string& strMsg, bool keepalive)
{
if (nStatus == HTTP_UNAUTHORIZED)
return strprintf("HTTP/1.0 401 Authorization Required\r\n"
"Date: %s\r\n"
"Server: bcca-json-rpc/%s\r\n"
"WWW-Authenticate: Basic realm=\"jsonrpc\"\r\n"
"Content-Type: text/html\r\n"
"Content-Length: 296\r\n"
"\r\n"
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\r\n"
"\"http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd\">\r\n"
"<HTML>\r\n"
"<HEAD>\r\n"
"<TITLE>Error</TITLE>\r\n"
"<META HTTP-EQUIV='Content-Type' CONTENT='text/html; charset=ISO-8859-1'>\r\n"
"</HEAD>\r\n"
"<BODY><H1>401 Unauthorized.</H1></BODY>\r\n"
"</HTML>\r\n", rfc1123Time(), FormatFullVersion());
const char *cStatus;
if (nStatus == HTTP_OK) cStatus = "OK";
else if (nStatus == HTTP_BAD_REQUEST) cStatus = "Bad Request";
else if (nStatus == HTTP_FORBIDDEN) cStatus = "Forbidden";
else if (nStatus == HTTP_NOT_FOUND) cStatus = "Not Found";
else if (nStatus == HTTP_INTERNAL_SERVER_ERROR) cStatus = "Internal Server Error";
else cStatus = "";
return strprintf(
"HTTP/1.1 %d %s\r\n"
"Date: %s\r\n"
"Connection: %s\r\n"
"Content-Length: %u\r\n"
"Content-Type: application/json\r\n"
"Server: bcca-json-rpc/%s\r\n"
"\r\n"
"%s",
nStatus,
cStatus,
rfc1123Time(),
keepalive ? "keep-alive" : "close",
strMsg.size(),
FormatFullVersion(),
strMsg);
}
bool ReadHTTPRequestLine(std::basic_istream<char>& stream, int &proto,
string& http_method, string& http_uri)
{
string str;
getline(stream, str);
// HTTP request line is space-delimited
vector<string> vWords;
boost::split(vWords, str, boost::is_any_of(" "));
if (vWords.size() < 2)
return false;
// HTTP methods permitted: GET, POST
http_method = vWords[0];
if (http_method != "GET" && http_method != "POST")
return false;
// HTTP URI must be an absolute path, relative to current host
http_uri = vWords[1];
if (http_uri.size() == 0 || http_uri[0] != '/')
return false;
// parse proto, if present
string strProto = "";
if (vWords.size() > 2)
strProto = vWords[2];
proto = 0;
const char *ver = strstr(strProto.c_str(), "HTTP/1.");
if (ver != NULL)
proto = atoi(ver+7);
return true;
}
int ReadHTTPStatus(std::basic_istream<char>& stream, int &proto)
{
string str;
getline(stream, str);
vector<string> vWords;
boost::split(vWords, str, boost::is_any_of(" "));
if (vWords.size() < 2)
return HTTP_INTERNAL_SERVER_ERROR;
proto = 0;
const char *ver = strstr(str.c_str(), "HTTP/1.");
if (ver != NULL)
proto = atoi(ver+7);
return atoi(vWords[1].c_str());
}
int ReadHTTPHeaders(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet)
{
int nLen = 0;
while (true)
{
string str;
std::getline(stream, str);
if (str.empty() || str == "\r")
break;
string::size_type nColon = str.find(":");
if (nColon != string::npos)
{
string strHeader = str.substr(0, nColon);
boost::trim(strHeader);
boost::to_lower(strHeader);
string strValue = str.substr(nColon+1);
boost::trim(strValue);
mapHeadersRet[strHeader] = strValue;
if (strHeader == "content-length")
nLen = atoi(strValue.c_str());
}
}
return nLen;
}
int ReadHTTPMessage(std::basic_istream<char>& stream, map<string,
string>& mapHeadersRet, string& strMessageRet,
int nProto)
{
mapHeadersRet.clear();
strMessageRet = "";
// Read header
int nLen = ReadHTTPHeaders(stream, mapHeadersRet);
if (nLen < 0 || nLen > (int)MAX_SIZE)
return HTTP_INTERNAL_SERVER_ERROR;
// Read message
if (nLen > 0)
{
vector<char> vch(nLen);
stream.read(&vch[0], nLen);
strMessageRet = string(vch.begin(), vch.end());
}
string sConHdr = mapHeadersRet["connection"];
if ((sConHdr != "close") && (sConHdr != "keep-alive"))
{
if (nProto >= 1)
mapHeadersRet["connection"] = "keep-alive";
else
mapHeadersRet["connection"] = "close";
}
return HTTP_OK;
}
//
// JSON-RPC protocol. Bitcoin speaks version 1.0 for maximum compatibility,
// but uses JSON-RPC 1.1/2.0 standards for parts of the 1.0 standard that were
// unspecified (HTTP errors and contents of 'error').
//
// 1.0 spec: http://json-rpc.org/wiki/specification
// 1.2 spec: http://groups.google.com/group/json-rpc/web/json-rpc-over-http
// http://www.codeproject.com/KB/recipes/JSON_Spirit.aspx
//
string JSONRPCRequest(const string& strMethod, const Array& params, const Value& id)
{
Object request;
request.push_back(Pair("method", strMethod));
request.push_back(Pair("params", params));
request.push_back(Pair("id", id));
return write_string(Value(request), false) + "\n";
}
Object JSONRPCReplyObj(const Value& result, const Value& error, const Value& id)
{
Object reply;
if (error.type() != null_type)
reply.push_back(Pair("result", Value::null));
else
reply.push_back(Pair("result", result));
reply.push_back(Pair("error", error));
reply.push_back(Pair("id", id));
return reply;
}
string JSONRPCReply(const Value& result, const Value& error, const Value& id)
{
Object reply = JSONRPCReplyObj(result, error, id);
return write_string(Value(reply), false) + "\n";
}
Object JSONRPCError(int code, const string& message)
{
Object error;
error.push_back(Pair("code", code));
error.push_back(Pair("message", message));
return error;
}
|
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
// Copyright (c) 2013, Facebook, Inc. All rights reserved.
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree. An additional grant
// of patent rights can be found in the PATENTS file in the same directory.
//
// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
#include <algorithm>
#include <set>
#include "rocksdb/db.h"
#include "rocksdb/filter_policy.h"
#include "db/db_impl.h"
#include "db/filename.h"
#include "db/version_set.h"
#include "db/write_batch_internal.h"
#include "db/db_statistics.h"
#include "rocksdb/cache.h"
#include "rocksdb/compaction_filter.h"
#include "rocksdb/env.h"
#include "rocksdb/table.h"
#include "util/hash.h"
#include "util/logging.h"
#include "util/mutexlock.h"
#include "util/testharness.h"
#include "util/testutil.h"
#include "utilities/merge_operators.h"
using std::unique_ptr;
namespace rocksdb {
// SimpleTable is a simple table format for UNIT TEST ONLY. It is not built
// as production quality.
// SimpleTable requires the input key size to be fixed 16 bytes, value cannot
// be longer than 150000 bytes and stored data on disk in this format:
// +--------------------------------------------+ <= key1 offset
// | key1 | value_size (4 bytes) | |
// +----------------------------------------+ |
// | value1 |
// | |
// +----------------------------------------+---+ <= key2 offset
// | key2 | value_size (4 bytes) | |
// +----------------------------------------+ |
// | value2 |
// | |
// | ...... |
// +-----------------+--------------------------+ <= index_block_offset
// | key1 | key1 offset (8 bytes) |
// +-----------------+--------------------------+
// | key2 | key2 offset (8 bytes) |
// +-----------------+--------------------------+
// | key3 | key3 offset (8 bytes) |
// +-----------------+--------------------------+
// | ...... |
// +-----------------+------------+-------------+
// | index_block_offset (8 bytes) |
// +------------------------------+
// SimpleTable is a simple table format for UNIT TEST ONLY. It is not built
// as production quality.
class SimpleTableReader: public TableReader {
public:
// Attempt to open the table that is stored in bytes [0..file_size)
// of "file", and read the metadata entries necessary to allow
// retrieving data from the table.
//
// If successful, returns ok and sets "*table" to the newly opened
// table. The client should delete "*table" when no longer needed.
// If there was an error while initializing the table, sets "*table"
// to nullptr and returns a non-ok status. Does not take ownership of
// "*source", but the client must ensure that "source" remains live
// for the duration of the returned table's lifetime.
//
// *file must remain live while this Table is in use.
static Status Open(const Options& options, const EnvOptions& soptions,
unique_ptr<RandomAccessFile> && file, uint64_t file_size,
unique_ptr<TableReader>* table_reader);
bool PrefixMayMatch(const Slice& internal_prefix) override;
Iterator* NewIterator(const ReadOptions&) override;
Status Get(
const ReadOptions&, const Slice& key, void* arg,
bool (*handle_result)(void* arg, const Slice& k, const Slice& v, bool),
void (*mark_key_may_exist)(void*) = nullptr) override;
uint64_t ApproximateOffsetOf(const Slice& key) override;
bool TEST_KeyInCache(const ReadOptions& options, const Slice& key) override;
void SetupForCompaction() override;
TableStats& GetTableStats() override;
~SimpleTableReader();
private:
struct Rep;
Rep* rep_;
explicit SimpleTableReader(Rep* rep) {
rep_ = rep;
}
friend class TableCache;
friend class SimpleTableIterator;
Status GetOffset(const Slice& target, uint64_t* offset);
// No copying allowed
explicit SimpleTableReader(const TableReader&) = delete;
void operator=(const TableReader&) = delete;
};
// Iterator to iterate SimpleTable
class SimpleTableIterator: public Iterator {
public:
explicit SimpleTableIterator(SimpleTableReader* table);
~SimpleTableIterator();
bool Valid() const;
void SeekToFirst();
void SeekToLast();
void Seek(const Slice& target);
void Next();
void Prev();
Slice key() const;
Slice value() const;
Status status() const;
private:
SimpleTableReader* table_;
uint64_t offset_;
uint64_t next_offset_;
Slice key_;
Slice value_;
char tmp_str_[4];
char* key_str_;
char* value_str_;
int value_str_len_;
Status status_;
// No copying allowed
SimpleTableIterator(const SimpleTableIterator&) = delete;
void operator=(const Iterator&) = delete;
};
struct SimpleTableReader::Rep {
~Rep() {
}
Rep(const EnvOptions& storage_options, uint64_t index_start_offset,
int num_entries) :
soptions(storage_options), index_start_offset(index_start_offset),
num_entries(num_entries) {
}
Options options;
const EnvOptions& soptions;
Status status;
unique_ptr<RandomAccessFile> file;
uint64_t index_start_offset;
int num_entries;
TableStats table_stats;
const static int user_key_size = 16;
const static int offset_length = 8;
const static int key_footer_len = 8;
static int GetInternalKeyLength() {
return user_key_size + key_footer_len;
}
};
SimpleTableReader::~SimpleTableReader() {
delete rep_;
}
Status SimpleTableReader::Open(const Options& options,
const EnvOptions& soptions,
unique_ptr<RandomAccessFile> && file,
uint64_t size,
unique_ptr<TableReader>* table_reader) {
char footer_space[Rep::offset_length];
Slice footer_input;
Status s = file->Read(size - Rep::offset_length, Rep::offset_length,
&footer_input, footer_space);
if (s.ok()) {
uint64_t index_start_offset = DecodeFixed64(footer_space);
int num_entries = (size - Rep::offset_length - index_start_offset)
/ (Rep::GetInternalKeyLength() + Rep::offset_length);
SimpleTableReader::Rep* rep = new SimpleTableReader::Rep(soptions,
index_start_offset,
num_entries);
rep->file = std::move(file);
rep->options = options;
table_reader->reset(new SimpleTableReader(rep));
}
return s;
}
void SimpleTableReader::SetupForCompaction() {
}
TableStats& SimpleTableReader::GetTableStats() {
return rep_->table_stats;
}
bool SimpleTableReader::PrefixMayMatch(const Slice& internal_prefix) {
return true;
}
Iterator* SimpleTableReader::NewIterator(const ReadOptions& options) {
return new SimpleTableIterator(this);
}
Status SimpleTableReader::GetOffset(const Slice& target, uint64_t* offset) {
uint32_t left = 0;
uint32_t right = rep_->num_entries - 1;
char key_chars[Rep::GetInternalKeyLength()];
Slice tmp_slice;
uint32_t target_offset = 0;
while (left <= right) {
uint32_t mid = (left + right + 1) / 2;
uint64_t offset_to_read = rep_->index_start_offset
+ (Rep::GetInternalKeyLength() + Rep::offset_length) * mid;
Status s = rep_->file->Read(offset_to_read, Rep::GetInternalKeyLength(),
&tmp_slice, key_chars);
if (!s.ok()) {
return s;
}
int compare_result = rep_->options.comparator->Compare(tmp_slice, target);
if (compare_result < 0) {
if (left == right) {
target_offset = right + 1;
break;
}
left = mid;
} else {
if (left == right) {
target_offset = left;
break;
}
right = mid - 1;
}
}
if (target_offset >= (uint32_t) rep_->num_entries) {
*offset = rep_->index_start_offset;
return Status::OK();
}
char value_offset_chars[Rep::offset_length];
int64_t offset_for_value_offset = rep_->index_start_offset
+ (Rep::GetInternalKeyLength() + Rep::offset_length) * target_offset
+ Rep::GetInternalKeyLength();
Status s = rep_->file->Read(offset_for_value_offset, Rep::offset_length,
&tmp_slice, value_offset_chars);
if (s.ok()) {
*offset = DecodeFixed64(value_offset_chars);
}
return s;
}
Status SimpleTableReader::Get(
const ReadOptions& options, const Slice& k, void* arg,
bool (*saver)(void*, const Slice&, const Slice&, bool),
void (*mark_key_may_exist)(void*)) {
Status s;
SimpleTableIterator* iter = new SimpleTableIterator(this);
for (iter->Seek(k); iter->Valid(); iter->Next()) {
if (!(*saver)(arg, iter->key(), iter->value(), true)) {
break;
}
}
s = iter->status();
delete iter;
return s;
}
bool SimpleTableReader::TEST_KeyInCache(const ReadOptions& options,
const Slice& key) {
return false;
}
uint64_t SimpleTableReader::ApproximateOffsetOf(const Slice& key) {
return 0;
}
SimpleTableIterator::SimpleTableIterator(SimpleTableReader* table) :
table_(table) {
key_str_ = new char[SimpleTableReader::Rep::GetInternalKeyLength()];
value_str_len_ = -1;
SeekToFirst();
}
SimpleTableIterator::~SimpleTableIterator() {
delete[] key_str_;
if (value_str_len_ >= 0) {
delete[] value_str_;
}
}
bool SimpleTableIterator::Valid() const {
return offset_ < table_->rep_->index_start_offset;
}
void SimpleTableIterator::SeekToFirst() {
next_offset_ = 0;
Next();
}
void SimpleTableIterator::SeekToLast() {
assert(false);
}
void SimpleTableIterator::Seek(const Slice& target) {
Status s = table_->GetOffset(target, &next_offset_);
if (!s.ok()) {
status_ = s;
}
Next();
}
void SimpleTableIterator::Next() {
offset_ = next_offset_;
if (offset_ >= table_->rep_->index_start_offset) {
return;
}
Slice result;
int internal_key_size = SimpleTableReader::Rep::GetInternalKeyLength();
Status s = table_->rep_->file->Read(next_offset_, internal_key_size, &result,
key_str_);
next_offset_ += internal_key_size;
key_ = result;
Slice value_size_slice;
s = table_->rep_->file->Read(next_offset_, 4, &value_size_slice, tmp_str_);
next_offset_ += 4;
uint32_t value_size = DecodeFixed32(tmp_str_);
Slice value_slice;
if ((int) value_size > value_str_len_) {
if (value_str_len_ >= 0) {
delete[] value_str_;
}
value_str_ = new char[value_size];
value_str_len_ = value_size;
}
s = table_->rep_->file->Read(next_offset_, value_size, &value_slice,
value_str_);
next_offset_ += value_size;
value_ = value_slice;
}
void SimpleTableIterator::Prev() {
assert(false);
}
Slice SimpleTableIterator::key() const {
Log(table_->rep_->options.info_log, "key!!!!");
return key_;
}
Slice SimpleTableIterator::value() const {
return value_;
}
Status SimpleTableIterator::status() const {
return status_;
}
class SimpleTableBuilder: public TableBuilder {
public:
// Create a builder that will store the contents of the table it is
// building in *file. Does not close the file. It is up to the
// caller to close the file after calling Finish(). The output file
// will be part of level specified by 'level'. A value of -1 means
// that the caller does not know which level the output file will reside.
SimpleTableBuilder(const Options& options, WritableFile* file,
CompressionType compression_type);
// REQUIRES: Either Finish() or Abandon() has been called.
~SimpleTableBuilder();
// Add key,value to the table being constructed.
// REQUIRES: key is after any previously added key according to comparator.
// REQUIRES: Finish(), Abandon() have not been called
void Add(const Slice& key, const Slice& value) override;
// Return non-ok iff some error has been detected.
Status status() const override;
// Finish building the table. Stops using the file passed to the
// constructor after this function returns.
// REQUIRES: Finish(), Abandon() have not been called
Status Finish() override;
// Indicate that the contents of this builder should be abandoned. Stops
// using the file passed to the constructor after this function returns.
// If the caller is not going to call Finish(), it must call Abandon()
// before destroying this builder.
// REQUIRES: Finish(), Abandon() have not been called
void Abandon() override;
// Number of calls to Add() so far.
uint64_t NumEntries() const override;
// Size of the file generated so far. If invoked after a successful
// Finish() call, returns the size of the final generated file.
uint64_t FileSize() const override;
private:
struct Rep;
Rep* rep_;
// No copying allowed
SimpleTableBuilder(const SimpleTableBuilder&) = delete;
void operator=(const SimpleTableBuilder&) = delete;
};
struct SimpleTableBuilder::Rep {
Options options;
WritableFile* file;
uint64_t offset = 0;
Status status;
uint64_t num_entries = 0;
bool closed = false; // Either Finish() or Abandon() has been called.
const static int user_key_size = 16;
const static int offset_length = 8;
const static int key_footer_len = 8;
static int GetInternalKeyLength() {
return user_key_size + key_footer_len;
}
std::string index;
Rep(const Options& opt, WritableFile* f) :
options(opt), file(f) {
}
~Rep() {
}
};
SimpleTableBuilder::SimpleTableBuilder(const Options& options,
WritableFile* file,
CompressionType compression_type) :
rep_(new SimpleTableBuilder::Rep(options, file)) {
}
SimpleTableBuilder::~SimpleTableBuilder() {
delete (rep_);
}
void SimpleTableBuilder::Add(const Slice& key, const Slice& value) {
assert((int ) key.size() == Rep::GetInternalKeyLength());
// Update index
rep_->index.append(key.data(), key.size());
PutFixed64(&(rep_->index), rep_->offset);
// Write key-value pair
rep_->file->Append(key);
rep_->offset += Rep::GetInternalKeyLength();
std::string size;
int value_size = value.size();
PutFixed32(&size, value_size);
Slice sizeSlice(size);
rep_->file->Append(sizeSlice);
rep_->file->Append(value);
rep_->offset += value_size + 4;
rep_->num_entries++;
}
Status SimpleTableBuilder::status() const {
return Status::OK();
}
Status SimpleTableBuilder::Finish() {
Rep* r = rep_;
assert(!r->closed);
r->closed = true;
uint64_t index_offset = rep_->offset;
Slice index_slice(rep_->index);
rep_->file->Append(index_slice);
rep_->offset += index_slice.size();
std::string index_offset_str;
PutFixed64(&index_offset_str, index_offset);
Slice foot_slice(index_offset_str);
rep_->file->Append(foot_slice);
rep_->offset += foot_slice.size();
return Status::OK();
}
void SimpleTableBuilder::Abandon() {
rep_->closed = true;
}
uint64_t SimpleTableBuilder::NumEntries() const {
return rep_->num_entries;
}
uint64_t SimpleTableBuilder::FileSize() const {
return rep_->offset;
}
class SimpleTableFactory: public TableFactory {
public:
~SimpleTableFactory() {
}
SimpleTableFactory() {
}
const char* Name() const override {
return "SimpleTable";
}
Status GetTableReader(const Options& options, const EnvOptions& soptions,
unique_ptr<RandomAccessFile> && file,
uint64_t file_size,
unique_ptr<TableReader>* table_reader) const;
TableBuilder* GetTableBuilder(const Options& options, WritableFile* file,
CompressionType compression_type) const;
};
Status SimpleTableFactory::GetTableReader(
const Options& options, const EnvOptions& soptions,
unique_ptr<RandomAccessFile> && file, uint64_t file_size,
unique_ptr<TableReader>* table_reader) const {
return SimpleTableReader::Open(options, soptions, std::move(file), file_size,
table_reader);
}
TableBuilder* SimpleTableFactory::GetTableBuilder(
const Options& options, WritableFile* file,
CompressionType compression_type) const {
return new SimpleTableBuilder(options, file, compression_type);
}
class SimpleTableDBTest {
protected:
public:
std::string dbname_;
Env* env_;
DB* db_;
Options last_options_;
SimpleTableDBTest() :
env_(Env::Default()) {
dbname_ = test::TmpDir() + "/simple_table_db_test";
ASSERT_OK(DestroyDB(dbname_, Options()));
db_ = nullptr;
Reopen();
}
~SimpleTableDBTest() {
delete db_;
ASSERT_OK(DestroyDB(dbname_, Options()));
}
// Return the current option configuration.
Options CurrentOptions() {
Options options;
options.table_factory.reset(new SimpleTableFactory());
return options;
}
DBImpl* dbfull() {
return reinterpret_cast<DBImpl*>(db_);
}
void Reopen(Options* options = nullptr) {
ASSERT_OK(TryReopen(options));
}
void Close() {
delete db_;
db_ = nullptr;
}
void DestroyAndReopen(Options* options = nullptr) {
//Destroy using last options
Destroy(&last_options_);
ASSERT_OK(TryReopen(options));
}
void Destroy(Options* options) {
delete db_;
db_ = nullptr;
ASSERT_OK(DestroyDB(dbname_, *options));
}
Status PureReopen(Options* options, DB** db) {
return DB::Open(*options, dbname_, db);
}
Status TryReopen(Options* options = nullptr) {
delete db_;
db_ = nullptr;
Options opts;
if (options != nullptr) {
opts = *options;
} else {
opts = CurrentOptions();
opts.create_if_missing = true;
}
last_options_ = opts;
return DB::Open(opts, dbname_, &db_);
}
Status Put(const Slice& k, const Slice& v) {
return db_->Put(WriteOptions(), k, v);
}
Status Delete(const std::string& k) {
return db_->Delete(WriteOptions(), k);
}
std::string Get(const std::string& k, const Snapshot* snapshot = nullptr) {
ReadOptions options;
options.snapshot = snapshot;
std::string result;
Status s = db_->Get(options, k, &result);
if (s.IsNotFound()) {
result = "NOT_FOUND";
} else if (!s.ok()) {
result = s.ToString();
}
return result;
}
int NumTableFilesAtLevel(int level) {
std::string property;
ASSERT_TRUE(
db_->GetProperty("rocksdb.num-files-at-level" + NumberToString(level),
&property));
return atoi(property.c_str());
}
// Return spread of files per level
std::string FilesPerLevel() {
std::string result;
int last_non_zero_offset = 0;
for (int level = 0; level < db_->NumberLevels(); level++) {
int f = NumTableFilesAtLevel(level);
char buf[100];
snprintf(buf, sizeof(buf), "%s%d", (level ? "," : ""), f);
result += buf;
if (f > 0) {
last_non_zero_offset = result.size();
}
}
result.resize(last_non_zero_offset);
return result;
}
std::string IterStatus(Iterator* iter) {
std::string result;
if (iter->Valid()) {
result = iter->key().ToString() + "->" + iter->value().ToString();
} else {
result = "(invalid)";
}
return result;
}
};
TEST(SimpleTableDBTest, Empty) {
ASSERT_TRUE(db_ != nullptr);
ASSERT_EQ("NOT_FOUND", Get("0000000000000foo"));
}
TEST(SimpleTableDBTest, ReadWrite) {
ASSERT_OK(Put("0000000000000foo", "v1"));
ASSERT_EQ("v1", Get("0000000000000foo"));
ASSERT_OK(Put("0000000000000bar", "v2"));
ASSERT_OK(Put("0000000000000foo", "v3"));
ASSERT_EQ("v3", Get("0000000000000foo"));
ASSERT_EQ("v2", Get("0000000000000bar"));
}
TEST(SimpleTableDBTest, Flush) {
ASSERT_OK(Put("0000000000000foo", "v1"));
ASSERT_OK(Put("0000000000000bar", "v2"));
ASSERT_OK(Put("0000000000000foo", "v3"));
dbfull()->TEST_FlushMemTable();
ASSERT_EQ("v3", Get("0000000000000foo"));
ASSERT_EQ("v2", Get("0000000000000bar"));
}
TEST(SimpleTableDBTest, Flush2) {
ASSERT_OK(Put("0000000000000bar", "b"));
ASSERT_OK(Put("0000000000000foo", "v1"));
dbfull()->TEST_FlushMemTable();
ASSERT_OK(Put("0000000000000foo", "v2"));
dbfull()->TEST_FlushMemTable();
ASSERT_EQ("v2", Get("0000000000000foo"));
ASSERT_OK(Put("0000000000000eee", "v3"));
dbfull()->TEST_FlushMemTable();
ASSERT_EQ("v3", Get("0000000000000eee"));
ASSERT_OK(Delete("0000000000000bar"));
dbfull()->TEST_FlushMemTable();
ASSERT_EQ("NOT_FOUND", Get("0000000000000bar"));
ASSERT_OK(Put("0000000000000eee", "v5"));
dbfull()->TEST_FlushMemTable();
ASSERT_EQ("v5", Get("0000000000000eee"));
}
static std::string Key(int i) {
char buf[100];
snprintf(buf, sizeof(buf), "key_______%06d", i);
return std::string(buf);
}
static std::string RandomString(Random* rnd, int len) {
std::string r;
test::RandomString(rnd, len, &r);
return r;
}
TEST(SimpleTableDBTest, CompactionTrigger) {
Options options = CurrentOptions();
options.write_buffer_size = 100 << 10; //100KB
options.num_levels = 3;
options.max_mem_compaction_level = 0;
options.level0_file_num_compaction_trigger = 3;
Reopen(&options);
Random rnd(301);
for (int num = 0; num < options.level0_file_num_compaction_trigger - 1;
num++) {
std::vector<std::string> values;
// Write 120KB (12 values, each 10K)
for (int i = 0; i < 12; i++) {
values.push_back(RandomString(&rnd, 10000));
ASSERT_OK(Put(Key(i), values[i]));
}
dbfull()->TEST_WaitForFlushMemTable();
ASSERT_EQ(NumTableFilesAtLevel(0), num + 1);
}
//generate one more file in level-0, and should trigger level-0 compaction
std::vector<std::string> values;
for (int i = 0; i < 12; i++) {
values.push_back(RandomString(&rnd, 10000));
ASSERT_OK(Put(Key(i), values[i]));
}
dbfull()->TEST_WaitForCompact();
ASSERT_EQ(NumTableFilesAtLevel(0), 0);
ASSERT_EQ(NumTableFilesAtLevel(1), 1);
}
} // namespace rocksdb
int main(int argc, char** argv) {
return rocksdb::test::RunAllTests();
}
|
/*
* Copyright (C) 2012 Open Source Robotics 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
*
* 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.
*
*/
#ifdef _WIN32
// Ensure that Winsock2.h is included before Windows.h, which can get
// pulled in by anybody (e.g., Boost).
#include <Winsock2.h>
#endif
#include <tbb/parallel_for.h>
#include <tbb/blocked_range.h>
#include <sdf/sdf.hh>
#include <algorithm>
#include <map>
#include <string>
#include <utility>
#include <vector>
#include <ignition/math/Rand.hh>
#include <ignition/math/Vector3.hh>
#include "gazebo/util/Diagnostics.hh"
#include "gazebo/common/Assert.hh"
#include "gazebo/common/Console.hh"
#include "gazebo/common/Exception.hh"
#include "gazebo/common/Time.hh"
#include "gazebo/common/Timer.hh"
#include "gazebo/transport/Publisher.hh"
#include "gazebo/physics/PhysicsTypes.hh"
#include "gazebo/physics/PhysicsFactory.hh"
#include "gazebo/physics/World.hh"
#include "gazebo/physics/Entity.hh"
#include "gazebo/physics/Model.hh"
#include "gazebo/physics/SurfaceParams.hh"
#include "gazebo/physics/Collision.hh"
#include "gazebo/physics/MapShape.hh"
#include "gazebo/physics/ContactManager.hh"
#include "gazebo/physics/ode/ODECollision.hh"
#include "gazebo/physics/ode/ODELink.hh"
#include "gazebo/physics/ode/ODEScrewJoint.hh"
#include "gazebo/physics/ode/ODEHingeJoint.hh"
#include "gazebo/physics/ode/ODEGearboxJoint.hh"
#include "gazebo/physics/ode/ODEHinge2Joint.hh"
#include "gazebo/physics/ode/ODESliderJoint.hh"
#include "gazebo/physics/ode/ODEBallJoint.hh"
#include "gazebo/physics/ode/ODEUniversalJoint.hh"
#include "gazebo/physics/ode/ODEFixedJoint.hh"
#include "gazebo/physics/ode/ODERayShape.hh"
#include "gazebo/physics/ode/ODEBoxShape.hh"
#include "gazebo/physics/ode/ODESphereShape.hh"
#include "gazebo/physics/ode/ODECylinderShape.hh"
#include "gazebo/physics/ode/ODEPlaneShape.hh"
#include "gazebo/physics/ode/ODEMeshShape.hh"
#include "gazebo/physics/ode/ODEMultiRayShape.hh"
#include "gazebo/physics/ode/ODEHeightmapShape.hh"
#include "gazebo/physics/ode/ODEPolylineShape.hh"
#include "gazebo/physics/ode/ODEPhysics.hh"
#include "gazebo/physics/ode/ODESurfaceParams.hh"
#include "gazebo/physics/ode/ODEPhysicsPrivate.hh"
using namespace gazebo;
using namespace physics;
GZ_REGISTER_PHYSICS_ENGINE("ode", ODEPhysics)
/*
class ContactUpdate_TBB
{
public: ContactUpdate_TBB(tbb::concurrent_vector<ContactFeedback> *_contacts)
: contacts(contacts) {}
public: void operator() (const tbb::blocked_range<size_t> &_r) const
{
for (size_t i = _r.begin(); i != _r.end(); i++)
{
this->engine->ProcessContactFeedback((*this->contacts)[i]);
}
}
private: tbb::concurrent_vector<ContactFeedback> *contacts;
private: ODEPhysics *engine;
};
*/
class Colliders_TBB
{
public: Colliders_TBB(
std::vector<std::pair<ODECollision*, ODECollision*> > *_colliders,
ODEPhysics *_engine,
dContactGeom* _contactCollisions) :
colliders(_colliders),
engine(_engine), contactCollisions(_contactCollisions)
{
// dAllocateODEDataForThread(dAllocateMaskAll);
}
public: void operator() (const tbb::blocked_range<size_t> &_r) const
{
for (size_t i = _r.begin(); i != _r.end(); i++)
{
ODECollision *collision1 = (*this->colliders)[i].first;
ODECollision *collision2 = (*this->colliders)[i].second;
this->engine->Collide(collision1, collision2, contactCollisions);
}
}
private: std::vector< std::pair<ODECollision*, ODECollision*> > *colliders;
private: ODEPhysics *engine;
private: dContactGeom* contactCollisions;
};
//////////////////////////////////////////////////
extern "C" void dMessageQuiet(int, const char *, va_list)
{
}
//////////////////////////////////////////////////
ODEPhysics::ODEPhysics(WorldPtr _world)
: PhysicsEngine(_world), dataPtr(new ODEPhysicsPrivate)
{
this->dataPtr->physicsStepFunc = nullptr;
this->dataPtr->maxContacts = 0;
// Collision detection init
dInitODE2(0);
dAllocateODEDataForThread(dAllocateMaskAll);
this->dataPtr->worldId = dWorldCreate();
this->dataPtr->spaceId = dHashSpaceCreate(0);
dHashSpaceSetLevels(this->dataPtr->spaceId, -2, 8);
this->dataPtr->contactGroup = dJointGroupCreate(0);
this->dataPtr->colliders.resize(100);
// Set random seed for physics engine based on gazebo's random seed.
// Note: this was moved from physics::PhysicsEngine constructor.
this->SetSeed(ignition::math::Rand::Seed());
}
//////////////////////////////////////////////////
ODEPhysics::~ODEPhysics()
{
this->Fini();
delete this->dataPtr;
this->dataPtr = nullptr;
}
//////////////////////////////////////////////////
void ODEPhysics::Load(sdf::ElementPtr _sdf)
{
PhysicsEngine::Load(_sdf);
this->dataPtr->maxContacts = _sdf->Get<unsigned int>("max_contacts");
this->SetMaxContacts(this->dataPtr->maxContacts);
sdf::ElementPtr odeElem = this->sdf->GetElement("ode");
sdf::ElementPtr solverElem = odeElem->GetElement("solver");
this->dataPtr->stepType = solverElem->Get<std::string>("type");
if (solverElem->HasElement("use_dynamic_moi_rescaling"))
{
dWorldSetQuickStepInertiaRatioReduction(this->dataPtr->worldId,
solverElem->Get<bool>("use_dynamic_moi_rescaling"));
}
else
{
dWorldSetQuickStepInertiaRatioReduction(this->dataPtr->worldId, true);
}
/// \TODO: defaultvelocity decay!? This is BAD if it's true.
dWorldSetDamping(this->dataPtr->worldId, 0.0001, 0.0001);
// Help prevent "popping of deeply embedded object
dWorldSetContactMaxCorrectingVel(this->dataPtr->worldId,
odeElem->GetElement("constraints")->Get<double>(
"contact_max_correcting_vel"));
// This helps prevent jittering problems.
dWorldSetContactSurfaceLayer(this->dataPtr->worldId,
odeElem->GetElement("constraints")->Get<double>(
"contact_surface_layer"));
// Enable auto-disable by default. Models with joints are excluded from
// auto-disable
dWorldSetAutoDisableFlag(this->dataPtr->worldId, 1);
dWorldSetAutoDisableTime(this->dataPtr->worldId, 1);
dWorldSetAutoDisableLinearThreshold(this->dataPtr->worldId, 0.1);
dWorldSetAutoDisableAngularThreshold(this->dataPtr->worldId, 0.1);
dWorldSetAutoDisableSteps(this->dataPtr->worldId, 5);
auto g = this->world->Gravity();
if (g == ignition::math::Vector3d::Zero)
gzwarn << "Gravity vector is (0, 0, 0). Objects will float.\n";
dWorldSetGravity(this->dataPtr->worldId, g.X(), g.Y(), g.Z());
if (odeElem->HasElement("constraints"))
{
dWorldSetCFM(this->dataPtr->worldId,
odeElem->GetElement("constraints")->Get<double>("cfm"));
dWorldSetERP(this->dataPtr->worldId,
odeElem->GetElement("constraints")->Get<double>("erp"));
}
else
dWorldSetERP(this->dataPtr->worldId, 0.2);
dWorldSetQuickStepNumIterations(this->dataPtr->worldId,
this->GetSORPGSIters());
dWorldSetQuickStepW(this->dataPtr->worldId, this->GetSORPGSW());
// Set the physics update function
this->SetStepType(this->dataPtr->stepType);
if (this->dataPtr->physicsStepFunc == nullptr)
gzthrow(std::string("Invalid step type[") + this->dataPtr->stepType);
}
/////////////////////////////////////////////////
void ODEPhysics::OnRequest(ConstRequestPtr &_msg)
{
msgs::Response response;
response.set_id(_msg->id());
response.set_request(_msg->request());
response.set_response("success");
std::string *serializedData = response.mutable_serialized_data();
if (_msg->request() == "physics_info")
{
msgs::Physics physicsMsg;
physicsMsg.set_type(msgs::Physics::ODE);
physicsMsg.set_solver_type(this->dataPtr->stepType);
// min_step_size is defined but not yet used
boost::any min_step_size;
try
{
if (this->GetParam("min_step_size", min_step_size))
physicsMsg.set_min_step_size(boost::any_cast<double>(min_step_size));
}
catch(boost::bad_any_cast &_e)
{
gzerr << "Failed boost::any_cast in ODEPhysics.cc: " << _e.what();
}
physicsMsg.set_precon_iters(this->GetSORPGSPreconIters());
physicsMsg.set_iters(this->GetSORPGSIters());
physicsMsg.set_enable_physics(this->world->PhysicsEnabled());
physicsMsg.set_sor(this->GetSORPGSW());
physicsMsg.set_cfm(this->GetWorldCFM());
physicsMsg.set_erp(this->GetWorldERP());
physicsMsg.set_contact_max_correcting_vel(
this->GetContactMaxCorrectingVel());
physicsMsg.set_contact_surface_layer(
this->GetContactSurfaceLayer());
physicsMsg.mutable_gravity()->CopyFrom(
msgs::Convert(this->world->Gravity()));
physicsMsg.mutable_magnetic_field()->CopyFrom(
msgs::Convert(this->world->MagneticField()));
physicsMsg.set_real_time_update_rate(this->realTimeUpdateRate);
physicsMsg.set_real_time_factor(this->targetRealTimeFactor);
physicsMsg.set_max_step_size(this->maxStepSize);
response.set_type(physicsMsg.GetTypeName());
physicsMsg.SerializeToString(serializedData);
this->responsePub->Publish(response);
}
}
/////////////////////////////////////////////////
void ODEPhysics::OnPhysicsMsg(ConstPhysicsPtr &_msg)
{
// Parent class handles many generic parameters
// This should be done first so that the profile settings
// can be over-ridden by other message parameters.
PhysicsEngine::OnPhysicsMsg(_msg);
if (_msg->has_solver_type())
this->SetStepType(_msg->solver_type());
if (_msg->has_min_step_size())
this->SetParam("min_step_size", _msg->min_step_size());
if (_msg->has_precon_iters())
this->SetSORPGSPreconIters(_msg->precon_iters());
if (_msg->has_iters())
this->SetSORPGSIters(_msg->iters());
if (_msg->has_sor())
this->SetSORPGSW(_msg->sor());
if (_msg->has_cfm())
this->SetWorldCFM(_msg->cfm());
if (_msg->has_erp())
this->SetWorldERP(_msg->erp());
if (_msg->has_enable_physics())
this->world->SetPhysicsEnabled(_msg->enable_physics());
if (_msg->has_contact_max_correcting_vel())
this->SetContactMaxCorrectingVel(_msg->contact_max_correcting_vel());
if (_msg->has_contact_surface_layer())
this->SetContactSurfaceLayer(_msg->contact_surface_layer());
if (_msg->has_gravity())
this->SetGravity(msgs::ConvertIgn(_msg->gravity()));
if (_msg->has_real_time_factor())
this->SetTargetRealTimeFactor(_msg->real_time_factor());
if (_msg->has_real_time_update_rate())
{
this->SetRealTimeUpdateRate(_msg->real_time_update_rate());
}
if (_msg->has_max_step_size())
{
this->SetMaxStepSize(_msg->max_step_size());
}
/// Make sure all models get at least on update cycle.
this->world->EnableAllModels();
}
//////////////////////////////////////////////////
void ODEPhysics::Init()
{
}
//////////////////////////////////////////////////
void ODEPhysics::InitForThread()
{
dAllocateODEDataForThread(dAllocateMaskAll);
}
//////////////////////////////////////////////////
void ODEPhysics::UpdateCollision()
{
DIAG_TIMER_START("ODEPhysics::UpdateCollision");
boost::recursive_mutex::scoped_lock lock(*this->physicsUpdateMutex);
dJointGroupEmpty(this->dataPtr->contactGroup);
unsigned int i = 0;
this->dataPtr->collidersCount = 0;
this->dataPtr->trimeshCollidersCount = 0;
this->dataPtr->jointFeedbackIndex = 0;
// Reset the contact count
this->contactManager->ResetCount();
// Do collision detection; this will add contacts to the contact group
dSpaceCollide(this->dataPtr->spaceId, this, CollisionCallback);
DIAG_TIMER_LAP("ODEPhysics::UpdateCollision", "dSpaceCollide");
// Generate non-trimesh collisions.
for (i = 0; i < this->dataPtr->collidersCount; ++i)
{
this->Collide(this->dataPtr->colliders[i].first,
this->dataPtr->colliders[i].second, this->dataPtr->contactCollisions);
}
DIAG_TIMER_LAP("ODEPhysics::UpdateCollision", "collideShapes");
// Generate trimesh collision.
// This must happen in this thread sequentially
for (i = 0; i < this->dataPtr->trimeshCollidersCount; ++i)
{
ODECollision *collision1 = this->dataPtr->trimeshColliders[i].first;
ODECollision *collision2 = this->dataPtr->trimeshColliders[i].second;
this->Collide(collision1, collision2, this->dataPtr->contactCollisions);
}
DIAG_TIMER_LAP("ODEPhysics::UpdateCollision", "collideTrimeshes");
DIAG_TIMER_STOP("ODEPhysics::UpdateCollision");
}
//////////////////////////////////////////////////
void ODEPhysics::UpdatePhysics()
{
DIAG_TIMER_START("ODEPhysics::UpdatePhysics");
// need to lock, otherwise might conflict with world resetting
{
boost::recursive_mutex::scoped_lock lock(*this->physicsUpdateMutex);
// Update the dynamical model
(*(this->dataPtr->physicsStepFunc))
(this->dataPtr->worldId, this->maxStepSize);
ignition::math::Vector3d f1, f2, t1, t2;
// Set the joint contact feedback for each contact.
for (unsigned int i = 0; i < this->dataPtr->jointFeedbackIndex; ++i)
{
Contact *contactFeedback = this->dataPtr->jointFeedbacks[i]->contact;
Collision *col1 = contactFeedback->collision1;
Collision *col2 = contactFeedback->collision2;
GZ_ASSERT(col1 != nullptr, "Collision 1 is null");
GZ_ASSERT(col2 != nullptr, "Collision 2 is null");
for (int j = 0; j < this->dataPtr->jointFeedbacks[i]->count; ++j)
{
dJointFeedback fb = this->dataPtr->jointFeedbacks[i]->feedbacks[j];
f1.Set(fb.f1[0], fb.f1[1], fb.f1[2]);
f2.Set(fb.f2[0], fb.f2[1], fb.f2[2]);
t1.Set(fb.t1[0], fb.t1[1], fb.t1[2]);
t2.Set(fb.t2[0], fb.t2[1], fb.t2[2]);
// set force torque in link frame
this->dataPtr->jointFeedbacks[i]->contact->wrench[j].body1Force =
col1->GetLink()->WorldPose().Rot().RotateVectorReverse(f1);
this->dataPtr->jointFeedbacks[i]->contact->wrench[j].body2Force =
col2->GetLink()->WorldPose().Rot().RotateVectorReverse(f2);
this->dataPtr->jointFeedbacks[i]->contact->wrench[j].body1Torque =
col1->GetLink()->WorldPose().Rot().RotateVectorReverse(t1);
this->dataPtr->jointFeedbacks[i]->contact->wrench[j].body2Torque =
col2->GetLink()->WorldPose().Rot().RotateVectorReverse(t2);
}
}
}
DIAG_TIMER_STOP("ODEPhysics::UpdatePhysics");
}
//////////////////////////////////////////////////
void ODEPhysics::Fini()
{
dCloseODE();
dJointGroupDestroy(this->dataPtr->contactGroup);
// Delete all the joint feedbacks.
for (auto iter = this->dataPtr->jointFeedbacks.begin();
iter != this->dataPtr->jointFeedbacks.end(); ++iter)
{
delete *iter;
}
this->dataPtr->jointFeedbacks.clear();
if (this->dataPtr->spaceId)
{
dSpaceSetCleanup(this->dataPtr->spaceId, 0);
dSpaceDestroy(this->dataPtr->spaceId);
}
if (this->dataPtr->worldId)
dWorldDestroy(this->dataPtr->worldId);
this->dataPtr->worldId = nullptr;
this->dataPtr->spaceId = nullptr;
PhysicsEngine::Fini();
}
//////////////////////////////////////////////////
void ODEPhysics::Reset()
{
boost::recursive_mutex::scoped_lock lock(*this->physicsUpdateMutex);
// Very important to clear out the contact group
dJointGroupEmpty(this->dataPtr->contactGroup);
}
//////////////////////////////////////////////////
LinkPtr ODEPhysics::CreateLink(ModelPtr _parent)
{
if (_parent == nullptr)
gzthrow("Link must have a parent\n");
std::map<std::string, dSpaceID>::iterator iter;
iter = this->dataPtr->spaces.find(_parent->GetName());
if (iter == this->dataPtr->spaces.end())
this->dataPtr->spaces[_parent->GetName()] =
dSimpleSpaceCreate(this->dataPtr->spaceId);
ODELinkPtr link(new ODELink(_parent));
link->SetSpaceId(this->dataPtr->spaces[_parent->GetName()]);
link->SetWorld(_parent->GetWorld());
return link;
}
//////////////////////////////////////////////////
CollisionPtr ODEPhysics::CreateCollision(const std::string &_type,
LinkPtr _body)
{
ODECollisionPtr collision(new ODECollision(_body));
ShapePtr shape = this->CreateShape(_type, collision);
collision->SetShape(shape);
shape->SetWorld(_body->GetWorld());
return collision;
}
//////////////////////////////////////////////////
ShapePtr ODEPhysics::CreateShape(const std::string &_type,
CollisionPtr _collision)
{
ShapePtr shape;
ODECollisionPtr collision =
boost::dynamic_pointer_cast<ODECollision>(_collision);
if (_type == "sphere")
shape.reset(new ODESphereShape(collision));
else if (_type == "plane")
shape.reset(new ODEPlaneShape(collision));
else if (_type == "box")
shape.reset(new ODEBoxShape(collision));
else if (_type == "cylinder")
shape.reset(new ODECylinderShape(collision));
else if (_type == "polyline")
shape.reset(new ODEPolylineShape(collision));
else if (_type == "multiray")
{
if (_collision)
shape.reset(new ODEMultiRayShape(collision));
else
shape.reset(new ODEMultiRayShape(this->world->Physics()));
}
else if (_type == "mesh" || _type == "trimesh")
shape.reset(new ODEMeshShape(collision));
else if (_type == "heightmap")
shape.reset(new ODEHeightmapShape(collision));
else if (_type == "map" || _type == "image")
shape.reset(new MapShape(collision));
else if (_type == "ray")
{
if (_collision)
shape.reset(new ODERayShape(collision));
else
shape.reset(new ODERayShape(this->world->Physics()));
}
else
gzerr << "Unable to create collision of type[" << _type << "]\n";
return shape;
}
//////////////////////////////////////////////////
dWorldID ODEPhysics::GetWorldId()
{
return this->dataPtr->worldId;
}
//////////////////////////////////////////////////
void ODEPhysics::ConvertMass(InertialPtr _inertial, void *_engineMass)
{
dMass *odeMass = static_cast<dMass*>(_engineMass);
_inertial->SetMass(odeMass->mass);
_inertial->SetCoG(odeMass->c[0], odeMass->c[1], odeMass->c[2]);
_inertial->SetInertiaMatrix(odeMass->I[0*4+0], odeMass->I[1*4+1],
odeMass->I[2*4+2], odeMass->I[0*4+1],
odeMass->I[0*4+2], odeMass->I[1*4+2]);
}
//////////////////////////////////////////////////
Friction_Model ODEPhysics::ConvertFrictionModel(const std::string &_fricModel)
{
Friction_Model result = pyramid_friction;
if (_fricModel.compare("pyramid_model") == 0)
result = pyramid_friction;
else if (_fricModel.compare("cone_model") == 0)
result = cone_friction;
else if (_fricModel.compare("box_model") == 0)
result = box_friction;
else
gzerr << "Unrecognized friction model ["
<< _fricModel
<< "], returning pyramid friction"
<< std::endl;
return result;
}
//////////////////////////////////////////////////
std::string ODEPhysics::ConvertFrictionModel(const Friction_Model _fricModel)
{
std::string result;
switch (_fricModel)
{
case pyramid_friction:
{
result = "pyramid_model";
break;
}
case cone_friction:
{
result = "cone_model";
break;
}
case box_friction:
{
result = "box_model";
break;
}
default:
{
result = "unknown";
gzerr << "Unrecognized friction model [" << _fricModel << "]"
<< std::endl;
}
}
return result;
}
//////////////////////////////////////////////////
World_Solver_Type
ODEPhysics::ConvertWorldStepSolverType(const std::string &_solverType)
{
World_Solver_Type result = ODE_DEFAULT;
if (_solverType.compare("ODE_DANTZIG") == 0)
result = ODE_DEFAULT;
else if (_solverType.compare("DART_PGS") == 0)
result = DART_PGS;
else if (_solverType.compare("BULLET_LEMKE") == 0)
result = BULLET_LEMKE;
else if (_solverType.compare("BULLET_PGS") == 0)
result = BULLET_PGS;
else
{
gzerr << "Unrecognized world step solver ["
<< _solverType
<< "], returning ODE_DANTZIG"
<< std::endl;
}
return result;
}
//////////////////////////////////////////////////
std::string
ODEPhysics::ConvertWorldStepSolverType(const World_Solver_Type _solverType)
{
std::string result;
switch (_solverType)
{
case ODE_DEFAULT:
{
result = "ODE_DANTZIG";
break;
}
case DART_PGS:
{
result = "DART_PGS";
break;
}
case BULLET_LEMKE:
{
result = "BULLET_LEMKE";
break;
}
case BULLET_PGS:
{
result = "BULLET_PGS";
break;
}
default:
{
result = "unknown";
gzerr << "Unrecognized world step solver [" << _solverType << "]"
<< std::endl;
}
}
return result;
}
//////////////////////////////////////////////////
void ODEPhysics::SetSORPGSPreconIters(unsigned int _iters)
{
this->sdf->GetElement("ode")->GetElement("solver")->
GetElement("precon_iters")->Set(_iters);
dWorldSetQuickStepPreconIterations(this->dataPtr->worldId, _iters);
}
//////////////////////////////////////////////////
void ODEPhysics::SetSORPGSIters(unsigned int _iters)
{
this->sdf->GetElement("ode")->GetElement(
"solver")->GetElement("iters")->Set(_iters);
dWorldSetQuickStepNumIterations(this->dataPtr->worldId, _iters);
}
//////////////////////////////////////////////////
void ODEPhysics::SetSORPGSW(double _w)
{
this->sdf->GetElement("ode")->GetElement(
"solver")->GetElement("sor")->Set(_w);
dWorldSetQuickStepW(this->dataPtr->worldId, _w);
}
//////////////////////////////////////////////////
void ODEPhysics::SetFrictionModel(const std::string &_fricModel)
{
/// Uncomment this until sdformat changes (sdformat repo issue #96)
///
/// this->sdf->GetElement("ode")->GetElement(
/// "solver")->GetElement("friction_model")->Set(_fricModel);
dWorldSetQuickStepFrictionModel(this->dataPtr->worldId,
ConvertFrictionModel(_fricModel));
}
//////////////////////////////////////////////////
void ODEPhysics::SetWorldCFM(double _cfm)
{
sdf::ElementPtr elem = this->sdf->GetElement("ode");
elem = elem->GetElement("constraints");
elem->GetElement("cfm")->Set(_cfm);
dWorldSetCFM(this->dataPtr->worldId, _cfm);
}
//////////////////////////////////////////////////
void ODEPhysics::SetWorldERP(double _erp)
{
sdf::ElementPtr elem = this->sdf->GetElement("ode");
elem = elem->GetElement("constraints");
elem->GetElement("erp")->Set(_erp);
dWorldSetERP(this->dataPtr->worldId, _erp);
}
//////////////////////////////////////////////////
void ODEPhysics::SetContactMaxCorrectingVel(double _vel)
{
this->sdf->GetElement("ode")->GetElement(
"constraints")->GetElement(
"contact_max_correcting_vel")->Set(_vel);
dWorldSetContactMaxCorrectingVel(this->dataPtr->worldId, _vel);
}
//////////////////////////////////////////////////
void ODEPhysics::SetContactSurfaceLayer(double _depth)
{
this->sdf->GetElement("ode")->GetElement(
"constraints")->GetElement("contact_surface_layer")->Set(_depth);
dWorldSetContactSurfaceLayer(this->dataPtr->worldId, _depth);
}
//////////////////////////////////////////////////
void ODEPhysics::SetMaxContacts(unsigned int _maxContacts)
{
this->dataPtr->maxContacts = _maxContacts;
this->sdf->GetElement("max_contacts")->GetValue()->Set(_maxContacts);
}
//////////////////////////////////////////////////
void ODEPhysics::SetWorldStepSolverType(const std::string &_worldSolverType)
{
dWorldSetWorldStepSolverType(this->dataPtr->worldId,
ConvertWorldStepSolverType(_worldSolverType));
}
//////////////////////////////////////////////////
int ODEPhysics::GetSORPGSPreconIters()
{
return this->sdf->GetElement("ode")->GetElement(
"solver")->Get<int>("precon_iters");
}
//////////////////////////////////////////////////
int ODEPhysics::GetSORPGSIters()
{
return this->sdf->GetElement("ode")->GetElement(
"solver")->Get<int>("iters");
}
//////////////////////////////////////////////////
double ODEPhysics::GetSORPGSW()
{
return this->sdf->GetElement("ode")->GetElement(
"solver")->Get<double>("sor");
}
//////////////////////////////////////////////////
std::string ODEPhysics::GetFrictionModel() const
{
return ConvertFrictionModel(
dWorldGetQuickStepFrictionModel(this->dataPtr->worldId));
}
//////////////////////////////////////////////////
std::string ODEPhysics::GetWorldStepSolverType() const
{
return ConvertWorldStepSolverType(
dWorldGetWorldStepSolverType(this->dataPtr->worldId));
}
//////////////////////////////////////////////////
double ODEPhysics::GetWorldCFM()
{
sdf::ElementPtr elem = this->sdf->GetElement("ode");
elem = elem->GetElement("constraints");
return elem->Get<double>("cfm");
}
//////////////////////////////////////////////////
double ODEPhysics::GetWorldERP()
{
sdf::ElementPtr elem = this->sdf->GetElement("ode");
elem = elem->GetElement("constraints");
return elem->Get<double>("erp");
}
//////////////////////////////////////////////////
double ODEPhysics::GetContactMaxCorrectingVel()
{
return this->sdf->GetElement("ode")->GetElement(
"constraints")->Get<double>("contact_max_correcting_vel");
}
//////////////////////////////////////////////////
double ODEPhysics::GetContactSurfaceLayer()
{
return this->sdf->GetElement("ode")->GetElement(
"constraints")->Get<double>("contact_surface_layer");
}
//////////////////////////////////////////////////
unsigned int ODEPhysics::GetMaxContacts()
{
return this->dataPtr->maxContacts;
}
//////////////////////////////////////////////////
void ODEPhysics::ConvertMass(void *_engineMass, InertialPtr _inertial)
{
dMass *odeMass = static_cast<dMass*>(_engineMass);
odeMass->mass = _inertial->Mass();
odeMass->c[0] = _inertial->CoG()[0];
odeMass->c[1] = _inertial->CoG()[1];
odeMass->c[2] = _inertial->CoG()[2];
odeMass->I[0*4+0] = _inertial->PrincipalMoments()[0];
odeMass->I[1*4+1] = _inertial->PrincipalMoments()[1];
odeMass->I[2*4+2] = _inertial->PrincipalMoments()[2];
odeMass->I[0*4+1] = _inertial->ProductsOfInertia()[0];
odeMass->I[1*4+0] = _inertial->ProductsOfInertia()[0];
odeMass->I[0*4+2] = _inertial->ProductsOfInertia()[1];
odeMass->I[1*4+0] = _inertial->ProductsOfInertia()[1];
odeMass->I[1*4+2] = _inertial->ProductsOfInertia()[2];
odeMass->I[2*4+1] = _inertial->ProductsOfInertia()[2];
}
//////////////////////////////////////////////////
JointPtr ODEPhysics::CreateJoint(const std::string &_type, ModelPtr _parent)
{
JointPtr joint;
if (_type == "prismatic")
joint.reset(new ODESliderJoint(this->dataPtr->worldId, _parent));
else if (_type == "screw")
joint.reset(new ODEScrewJoint(this->dataPtr->worldId, _parent));
else if (_type == "revolute")
joint.reset(new ODEHingeJoint(this->dataPtr->worldId, _parent));
else if (_type == "gearbox")
joint.reset(new ODEGearboxJoint(this->dataPtr->worldId, _parent));
else if (_type == "revolute2")
joint.reset(new ODEHinge2Joint(this->dataPtr->worldId, _parent));
else if (_type == "ball")
joint.reset(new ODEBallJoint(this->dataPtr->worldId, _parent));
else if (_type == "universal")
joint.reset(new ODEUniversalJoint(this->dataPtr->worldId, _parent));
else if (_type == "fixed")
joint.reset(new ODEFixedJoint(this->dataPtr->worldId, _parent));
else
gzthrow("Unable to create joint of type[" << _type << "]");
return joint;
}
//////////////////////////////////////////////////
dSpaceID ODEPhysics::GetSpaceId() const
{
return this->dataPtr->spaceId;
}
//////////////////////////////////////////////////
std::string ODEPhysics::GetStepType() const
{
sdf::ElementPtr elem = this->sdf->GetElement("ode")->GetElement("solver");
return elem->Get<std::string>("type");
}
//////////////////////////////////////////////////
void ODEPhysics::SetStepType(const std::string &_type)
{
sdf::ElementPtr elem = this->sdf->GetElement("ode")->GetElement("solver");
elem->GetElement("type")->Set(_type);
this->dataPtr->stepType = _type;
// Set the physics update function
if (this->dataPtr->stepType == "quick")
this->dataPtr->physicsStepFunc = &dWorldQuickStep;
else if (this->dataPtr->stepType == "world")
this->dataPtr->physicsStepFunc = &dWorldStep;
else
gzerr << "Invalid step type[" << this->dataPtr->stepType
<< "]" << std::endl;
}
//////////////////////////////////////////////////
void ODEPhysics::SetGravity(const ignition::math::Vector3d &_gravity)
{
this->world->SetGravitySDF(_gravity);
dWorldSetGravity(this->dataPtr->worldId, _gravity.X(), _gravity.Y(),
_gravity.Z());
}
//////////////////////////////////////////////////
void ODEPhysics::CollisionCallback(void *_data, dGeomID _o1, dGeomID _o2)
{
dBodyID b1 = dGeomGetBody(_o1);
dBodyID b2 = dGeomGetBody(_o2);
// exit without doing anything if the two bodies are connected by a joint
if (b1 && b2 && dAreConnectedExcluding(b1, b2, dJointTypeContact))
return;
// Get a pointer to the physics engine
ODEPhysics *self = static_cast<ODEPhysics*>(_data);
// Check if either are spaces
if (dGeomIsSpace(_o1) || dGeomIsSpace(_o2))
{
dSpaceCollide2(_o1, _o2, self, &CollisionCallback);
}
else
{
ODECollision *collision1 = nullptr;
ODECollision *collision2 = nullptr;
// Exit if both bodies are not enabled
if (dGeomGetCategoryBits(_o1) != GZ_SENSOR_COLLIDE &&
dGeomGetCategoryBits(_o2) != GZ_SENSOR_COLLIDE &&
((b1 && b2 && !dBodyIsEnabled(b1) && !dBodyIsEnabled(b2)) ||
(!b2 && b1 && !dBodyIsEnabled(b1)) ||
(!b1 && b2 && !dBodyIsEnabled(b2))))
{
return;
}
// Get pointers to the underlying collisions
if (dGeomGetClass(_o1) == dGeomTransformClass)
collision1 =
static_cast<ODECollision*>(dGeomGetData(dGeomTransformGetGeom(_o1)));
else
collision1 = static_cast<ODECollision*>(dGeomGetData(_o1));
if (dGeomGetClass(_o2) == dGeomTransformClass)
collision2 =
static_cast<ODECollision*>(dGeomGetData(dGeomTransformGetGeom(_o2)));
else
collision2 = static_cast<ODECollision*>(dGeomGetData(_o2));
// Make sure both collision pointers are valid.
if (collision1 && collision2)
{
// Add either a tri-mesh collider or a regular collider.
if (collision1->HasType(Base::MESH_SHAPE) ||
collision2->HasType(Base::MESH_SHAPE))
self->AddTrimeshCollider(collision1, collision2);
else
{
self->AddCollider(collision1, collision2);
}
}
}
}
//////////////////////////////////////////////////
void ODEPhysics::Collide(ODECollision *_collision1, ODECollision *_collision2,
dContactGeom *_contactCollisions)
{
// Filter collisions based on collide bitmask.
if ((_collision1->GetSurface()->collideBitmask &
_collision2->GetSurface()->collideBitmask) == 0)
return;
// Filter collisions based on contact bitmask if collide_without_contact is
// on.The bitmask is set mainly for speed improvements otherwise a collision
// with collide_without_contact may potentially generate a large number of
// contacts.
if (_collision1->GetSurface()->collideWithoutContact ||
_collision2->GetSurface()->collideWithoutContact)
{
if ((_collision1->GetSurface()->collideWithoutContactBitmask &
_collision2->GetSurface()->collideWithoutContactBitmask) == 0)
{
return;
}
}
/*
if (_collision1->GetCollisionId() && _collision2->GetCollisionId())
{
const dVector3 *pos1 =
(const dVector3*)dGeomGetPosition(_collision1->GetCollisionId());
const dVector3 *pos2 =
(const dVector3*)dGeomGetPosition(_collision2->GetCollisionId());
std::cout << "1[" << (*pos1)[0]<< " " << (*pos1)[1] << " "
<< (*pos1)[2] << "] "
<< "2[" << (*pos2)[0]<< " " << (*pos2)[1] << " " << (*pos2)[2] << "]\n";
}*/
unsigned int numc = 0;
dContact contact;
// maxCollide must less than the size of this->dataPtr->indices
// Check the header
unsigned int maxCollide = MAX_CONTACT_JOINTS;
// max_contacts specified globally
if (this->GetMaxContacts() > 0 && this->GetMaxContacts() < MAX_CONTACT_JOINTS)
maxCollide = this->GetMaxContacts();
// over-ride with minimum of max_contacts from both collisions
if (_collision1->GetMaxContacts() < maxCollide)
maxCollide = _collision1->GetMaxContacts();
if (_collision2->GetMaxContacts() < maxCollide)
maxCollide = _collision2->GetMaxContacts();
// Generate the contacts
numc = dCollide(_collision1->GetCollisionId(), _collision2->GetCollisionId(),
MAX_COLLIDE_RETURNS, _contactCollisions, sizeof(_contactCollisions[0]));
// Return if no contacts.
if (numc == 0)
return;
// Store the indices of the contacts.
for (int i = 0; i < MAX_CONTACT_JOINTS; i++)
this->dataPtr->indices[i] = i;
// Choose only the best contacts if too many were generated.
if (maxCollide > 0 && numc > maxCollide)
{
double max = _contactCollisions[maxCollide-1].depth;
for (unsigned int i = maxCollide; i < numc; ++i)
{
if (_contactCollisions[i].depth > max)
{
max = _contactCollisions[i].depth;
this->dataPtr->indices[maxCollide-1] = i;
}
}
// Make sure numc has the valid number of contacts.
numc = maxCollide;
}
// Set the contact surface parameter flags.
contact.surface.mode = dContactBounce |
dContactMu2 |
dContactSoftERP |
dContactSoftCFM |
dContactApprox1 |
dContactApprox3 |
dContactSlip1 |
dContactSlip2;
ODESurfaceParamsPtr surf1 = _collision1->GetODESurface();
ODESurfaceParamsPtr surf2 = _collision2->GetODESurface();
// Compute the CFM and ERP by assuming the two bodies form a
// spring-damper system.
double kp = 1.0 / (1.0 / surf1->kp + 1.0 / surf2->kp);
double kd = surf1->kd + surf2->kd;
contact.surface.soft_erp = (this->maxStepSize * kp) /
(this->maxStepSize * kp + kd);
contact.surface.soft_cfm = 1.0 / (this->maxStepSize * kp + kd);
// contact.surface.soft_erp = 0.5*(_collision1->surface->softERP +
// _collision2->surface->softERP);
// contact.surface.soft_cfm = 0.5*(_collision1->surface->softCFM +
// _collision2->surface->softCFM);
// assign fdir1 if not set as 0
ignition::math::Vector3d fd = surf1->FrictionPyramid()->direction1;
if (fd != ignition::math::Vector3d::Zero)
{
// fdir1 is in body local frame, rotate it into world frame
fd = _collision1->WorldPose().Rot().RotateVector(fd);
}
/// \TODO: Better treatment when both surfaces have fdir1 specified.
/// Ideally, we want to use fdir1 specified by surface with
/// a smaller friction coefficient, but it's not clear how
/// that can be determined with friction pyramid approximations.
/// As a hack, we'll simply compare mu1 from
/// both surfaces for now, and use fdir1 specified by
/// surface with smaller mu1.
ignition::math::Vector3d fd2 = surf2->FrictionPyramid()->direction1;
if (fd2 != ignition::math::Vector3d::Zero &&
(fd == ignition::math::Vector3d::Zero ||
surf1->FrictionPyramid()->MuPrimary() >
surf2->FrictionPyramid()->MuPrimary()))
{
// fdir1 is in body local frame, rotate it into world frame
fd2 = _collision2->WorldPose().Rot().RotateVector(fd2);
/// \TODO: uncomment gzlog below once we confirm it does not affect
/// performance
/// if (fd2 != ignition::math::Vector3d::Zero &&
/// fd != ignition::math::Vector3d::Zero &&
/// _collision1->surface->mu1 > _collision2->surface->mu1)
/// gzlog << "both contact surfaces have non-zero fdir1, comparing"
/// << " comparing mu1 from both surfaces, and use fdir1"
/// << " from surface with smaller mu1\n";
}
if (fd != ignition::math::Vector3d::Zero)
{
contact.surface.mode |= dContactFDir1;
contact.fdir1[0] = fd.X();
contact.fdir1[1] = fd.Y();
contact.fdir1[2] = fd.Z();
}
// Set the friction coefficients.
contact.surface.mu = std::min(surf1->FrictionPyramid()->MuPrimary(),
surf2->FrictionPyramid()->MuPrimary());
contact.surface.mu2 = std::min(surf1->FrictionPyramid()->MuSecondary(),
surf2->FrictionPyramid()->MuSecondary());
contact.surface.mu3 = std::min(surf1->FrictionPyramid()->MuTorsion(),
surf2->FrictionPyramid()->MuTorsion());
// Combine the slip values
// The slip is equivalent to the inverse of a viscous damping term
// To combine dampers in series, the inverse of damping is summed
// So the sum of slip parameters is used to combine them
contact.surface.slip1 = surf1->slip1 + surf2->slip1;
contact.surface.slip2 = surf1->slip2 + surf2->slip2;
contact.surface.slip3 = surf1->slipTorsion + surf2->slipTorsion;
// Combine torsional friction patch radius values
contact.surface.patch_radius =
std::max(surf1->FrictionPyramid()->PatchRadius(),
surf2->FrictionPyramid()->PatchRadius());
// For torsional friction, the curvature is combined using
// 1/R = 1/R1 + 1/R2
// we can consider doing the same for the patch radius
double curv1 = 0;
if (surf1->FrictionPyramid()->SurfaceRadius() > 0)
curv1 = 1 / surf1->FrictionPyramid()->SurfaceRadius();
double curv2 = 0;
if (surf2->FrictionPyramid()->SurfaceRadius() > 0)
curv2 = 1 / surf2->FrictionPyramid()->SurfaceRadius();
double curvSum = curv1 + curv2;
contact.surface.surface_radius = 0;
if (curvSum > 0)
contact.surface.surface_radius = 1 / curvSum;
/// \todo Not sure how to combine these logic flags
/// If user wanted to use patch radius, but got settings
/// overwritten by the logic combination, how do we make sure the
/// the surface radius is specified or makes sense?
contact.surface.use_patch_radius =
surf1->FrictionPyramid()->UsePatchRadius() &&
surf2->FrictionPyramid()->UsePatchRadius();
if (contact.surface.mu3 > 0)
{
// Patch radius
if ((contact.surface.use_patch_radius &&
contact.surface.patch_radius > 0) ||
// Surface radius
(!contact.surface.use_patch_radius &&
contact.surface.surface_radius > 0))
{
contact.surface.mode |= dContactMu3;
if (contact.surface.slip3 > 0)
{
contact.surface.mode |= dContactSlip3;
}
}
}
// Set the elastic modulus
// Using Hertzian contact
// equation 5.26 from Contact Mechanics and Friction by Popov
double nu1 = surf1->FrictionPyramid()->PoissonsRatio();
double nu2 = surf2->FrictionPyramid()->PoissonsRatio();
double e1 = surf1->FrictionPyramid()->ElasticModulus();
double e2 = surf2->FrictionPyramid()->ElasticModulus();
if (e1 > 0 && e2 > 0)
{
contact.surface.elastic_modulus = 1.0 /
((1.0 - nu1*nu1)/e1 + (1.0 - nu2*nu2)/e2);
// Turn on Contact Elastic Modulus model if elastic modulus > 0
if (contact.surface.elastic_modulus > 0.0)
{
contact.surface.mode |= dContactEM;
}
}
// Set the bounce values
contact.surface.bounce = std::min(surf1->bounce,
surf2->bounce);
contact.surface.bounce_vel =
std::min(surf1->bounceThreshold,
surf2->bounceThreshold);
// Get the ODE body IDs
dBodyID b1 = dGeomGetBody(_collision1->GetCollisionId());
dBodyID b2 = dGeomGetBody(_collision2->GetCollisionId());
// Add a new contact to the manager. This will return nullptr if no one is
// listening for contact information.
Contact *contactFeedback = this->contactManager->NewContact(_collision1,
_collision2, this->world->SimTime());
ODEJointFeedback *jointFeedback = nullptr;
// Create a joint feedback mechanism
if (contactFeedback)
{
if (this->dataPtr->jointFeedbackIndex <
this->dataPtr->jointFeedbacks.size())
jointFeedback =
this->dataPtr->jointFeedbacks[this->dataPtr->jointFeedbackIndex];
else
{
jointFeedback = new ODEJointFeedback();
this->dataPtr->jointFeedbacks.push_back(jointFeedback);
}
this->dataPtr->jointFeedbackIndex++;
jointFeedback->count = 0;
jointFeedback->contact = contactFeedback;
}
// Create a joint for each contact
for (unsigned int j = 0; j < numc; ++j)
{
contact.geom = _contactCollisions[this->dataPtr->indices[j]];
// Create the contact joint. This introduces the contact constraint to
// ODE
dJointID contactJoint = dJointCreateContact(this->dataPtr->worldId,
this->dataPtr->contactGroup, &contact);
// Store contact information.
if (contactFeedback && jointFeedback)
{
// Store the contact depth
contactFeedback->depths[j] =
_contactCollisions[this->dataPtr->indices[j]].depth;
// Store the contact position
contactFeedback->positions[j].Set(
_contactCollisions[this->dataPtr->indices[j]].pos[0],
_contactCollisions[this->dataPtr->indices[j]].pos[1],
_contactCollisions[this->dataPtr->indices[j]].pos[2]);
// Store the contact normal
contactFeedback->normals[j].Set(
_contactCollisions[this->dataPtr->indices[j]].normal[0],
_contactCollisions[this->dataPtr->indices[j]].normal[1],
_contactCollisions[this->dataPtr->indices[j]].normal[2]);
// Set the joint feedback.
dJointSetFeedback(contactJoint, &(jointFeedback->feedbacks[j]));
// Increase the counters
contactFeedback->count++;
jointFeedback->count++;
}
// Attach the contact joint if collideWithoutContact flags aren't set.
if (!_collision1->GetSurface()->collideWithoutContact &&
!_collision2->GetSurface()->collideWithoutContact)
dJointAttach(contactJoint, b1, b2);
}
}
/////////////////////////////////////////////////
void ODEPhysics::AddTrimeshCollider(ODECollision *_collision1,
ODECollision *_collision2)
{
if (this->dataPtr->trimeshCollidersCount >=
this->dataPtr->trimeshColliders.size())
this->dataPtr->trimeshColliders.resize(
this->dataPtr->trimeshColliders.size() + 100);
this->dataPtr->trimeshColliders[this->dataPtr->trimeshCollidersCount].first =
_collision1;
this->dataPtr->trimeshColliders[this->dataPtr->trimeshCollidersCount].second =
_collision2;
this->dataPtr->trimeshCollidersCount++;
}
/////////////////////////////////////////////////
void ODEPhysics::AddCollider(ODECollision *_collision1,
ODECollision *_collision2)
{
if (this->dataPtr->collidersCount >= this->dataPtr->colliders.size())
this->dataPtr->colliders.resize(this->dataPtr->colliders.size() + 100);
this->dataPtr->colliders[this->dataPtr->collidersCount].first = _collision1;
this->dataPtr->colliders[this->dataPtr->collidersCount].second = _collision2;
this->dataPtr->collidersCount++;
}
/////////////////////////////////////////////////
void ODEPhysics::DebugPrint() const
{
dBodyID b;
std::cout << "Debug Print[" <<
dWorldGetBodyCount(this->dataPtr->worldId) << "]\n";
for (int i = 0; i < dWorldGetBodyCount(this->dataPtr->worldId); ++i)
{
b = dWorldGetBody(this->dataPtr->worldId, i);
ODELink *link = static_cast<ODELink*>(dBodyGetData(b));
ignition::math::Pose3d pose = link->WorldPose();
const dReal *pos = dBodyGetPosition(b);
const dReal *rot = dBodyGetRotation(b);
ignition::math::Vector3d dpos(pos[0], pos[1], pos[2]);
ignition::math::Quaterniond drot(rot[0], rot[1], rot[2], rot[3]);
std::cout << "Body[" << link->GetScopedName() << "]\n";
std::cout << " World: Pos[" << dpos << "] Rot[" << drot << "]\n";
if (pose.Pos() != dpos)
std::cout << " Incorrect world pos[" << pose.Pos() << "]\n";
if (pose.Rot() != drot)
std::cout << " Incorrect world rot[" << pose.Rot() << "]\n";
dMass mass;
dBodyGetMass(b, &mass);
std::cout << " Mass[" << mass.mass << "] COG[" << mass.c[0]
<< " " << mass.c[1] << " " << mass.c[2] << "]\n";
dGeomID g = dBodyGetFirstGeom(b);
while (g)
{
ODECollision *coll = static_cast<ODECollision*>(dGeomGetData(g));
pose = coll->WorldPose();
const dReal *gpos = dGeomGetPosition(g);
const dReal *grot = dGeomGetRotation(g);
dpos.Set(gpos[0], gpos[1], gpos[2]);
drot.Set(grot[0], grot[1], grot[2], grot[3]);
std::cout << " Geom[" << coll->GetScopedName() << "]\n";
std::cout << " World: Pos[" << dpos << "] Rot[" << drot << "]\n";
if (pose.Pos() != dpos)
std::cout << " Incorrect world pos[" << pose.Pos() << "]\n";
if (pose.Rot() != drot)
std::cout << " Incorrect world rot[" << pose.Rot() << "]\n";
g = dBodyGetNextGeom(g);
}
}
}
/////////////////////////////////////////////////
void ODEPhysics::SetSeed(uint32_t _seed)
{
dRandSetSeed(_seed);
}
//////////////////////////////////////////////////
bool ODEPhysics::SetParam(const std::string &_key, const boost::any &_value)
{
sdf::ElementPtr odeElem = this->sdf->GetElement("ode");
GZ_ASSERT(odeElem != nullptr, "ODE SDF element does not exist");
try
{
if (_key == "solver_type")
{
this->SetStepType(boost::any_cast<std::string>(_value));
}
else if (_key == "cfm")
{
double value = boost::any_cast<double>(_value);
odeElem->GetElement("constraints")->GetElement("cfm")->Set(value);
dWorldSetCFM(this->dataPtr->worldId, value);
}
else if (_key == "erp")
{
double value = boost::any_cast<double>(_value);
odeElem->GetElement("constraints")->GetElement("erp")->Set(value);
dWorldSetERP(this->dataPtr->worldId, value);
}
else if (_key == "precon_iters")
{
int value = boost::any_cast<int>(_value);
odeElem->GetElement("solver")->GetElement("precon_iters")->Set(value);
dWorldSetQuickStepPreconIterations(this->dataPtr->worldId, value);
}
else if (_key == "iters")
{
int value = boost::any_cast<int>(_value);
odeElem->GetElement("solver")->GetElement("iters")->Set(value);
dWorldSetQuickStepNumIterations(this->dataPtr->worldId, value);
}
else if (_key == "sor")
{
double value = boost::any_cast<double>(_value);
odeElem->GetElement("solver")->GetElement("sor")->Set(value);
dWorldSetQuickStepW(this->dataPtr->worldId, value);
}
else if (_key == "friction_model")
this->SetFrictionModel(boost::any_cast<std::string>(_value));
else if (_key == "world_step_solver")
this->SetWorldStepSolverType(boost::any_cast<std::string>(_value));
else if (_key == "contact_max_correcting_vel")
{
double value = boost::any_cast<double>(_value);
odeElem->GetElement("constraints")->GetElement(
"contact_max_correcting_vel")->Set(value);
dWorldSetContactMaxCorrectingVel(this->dataPtr->worldId, value);
}
else if (_key == "contact_surface_layer")
{
double value = boost::any_cast<double>(_value);
odeElem->GetElement("constraints")->GetElement(
"contact_surface_layer")->Set(value);
dWorldSetContactSurfaceLayer(this->dataPtr->worldId, value);
}
else if (_key == "max_contacts")
{
int value = boost::any_cast<int>(_value);
this->sdf->GetElement("max_contacts")->GetValue()->Set(value);
}
else if (_key == "min_step_size")
{
/// TODO: Implement min step size param
double value = boost::any_cast<double>(_value);
odeElem->GetElement("solver")->GetElement("min_step_size")->Set(value);
}
else if (_key == "sor_lcp_tolerance")
{
dWorldSetQuickStepTolerance(this->dataPtr->worldId,
boost::any_cast<double>(_value));
}
else if (_key == "rms_error_tolerance")
{
gzwarn << "please use sor_lcp_tolerance in the future.\n";
dWorldSetQuickStepTolerance(this->dataPtr->worldId,
boost::any_cast<double>(_value));
}
else if (_key == "inertia_ratio_reduction" ||
_key == "use_dynamic_moi_rescaling")
{
bool value = boost::any_cast<bool>(_value);
dWorldSetQuickStepInertiaRatioReduction(this->dataPtr->worldId, value);
if (odeElem->GetElement("solver")->HasElement(
"use_dynamic_moi_rescaling"))
{
odeElem->GetElement("solver")->GetElement(
"use_dynamic_moi_rescaling")->Set(value);
}
}
else if (_key == "contact_residual_smoothing")
{
dWorldSetQuickStepContactResidualSmoothing(this->dataPtr->worldId,
boost::any_cast<double>(_value));
}
else if (_key == "contact_sor_scale")
{
dWorldSetQuickStepContactSORScalingFactor(this->dataPtr->worldId,
boost::any_cast<double>(_value));
}
else if (_key == "thread_position_correction")
{
dWorldSetQuickStepThreadPositionCorrection(this->dataPtr->worldId,
boost::any_cast<bool>(_value));
}
else if (_key == "experimental_row_reordering")
{
dWorldSetQuickStepExperimentalRowReordering(this->dataPtr->worldId,
boost::any_cast<bool>(_value));
}
else if (_key == "warm_start_factor")
{
dWorldSetQuickStepWarmStartFactor(this->dataPtr->worldId,
boost::any_cast<double>(_value));
}
else if (_key == "extra_friction_iterations")
{
dWorldSetQuickStepExtraFrictionIterations(this->dataPtr->worldId,
boost::any_cast<int>(_value));
}
else if (_key == "ode_quiet")
{
bool odeQuiet = boost::any_cast<bool>(_value);
if (odeQuiet)
{
dSetMessageHandler(&dMessageQuiet);
}
else
{
dSetMessageHandler(0);
}
}
else
{
return PhysicsEngine::SetParam(_key, _value);
}
}
catch(boost::bad_any_cast &e)
{
gzerr << "ODEPhysics::SetParam(" << _key << ") boost::any_cast error: "
<< e.what() << std::endl;
return false;
}
return true;
}
//////////////////////////////////////////////////
boost::any ODEPhysics::GetParam(const std::string &_key) const
{
boost::any value;
this->GetParam(_key, value);
return value;
}
//////////////////////////////////////////////////
bool ODEPhysics::GetParam(const std::string &_key, boost::any &_value) const
{
sdf::ElementPtr odeElem = this->sdf->GetElement("ode");
GZ_ASSERT(odeElem != nullptr, "ODE SDF element does not exist");
if (_key == "solver_type")
{
_value = odeElem->GetElement("solver")->Get<std::string>("type");
}
else if (_key == "cfm")
{
_value = odeElem->GetElement("constraints")->Get<double>("cfm");
}
else if (_key == "erp")
_value = odeElem->GetElement("constraints")->Get<double>("erp");
else if (_key == "precon_iters")
_value = odeElem->GetElement("solver")->Get<int>("precon_iters");
else if (_key == "iters")
_value = odeElem->GetElement("solver")->Get<int>("iters");
else if (_key == "sor")
_value = odeElem->GetElement("solver")->Get<double>("sor");
else if (_key == "contact_max_correcting_vel")
_value = odeElem->GetElement("constraints")->Get<double>(
"contact_max_correcting_vel");
else if (_key == "contact_surface_layer")
_value = odeElem->GetElement("constraints")->Get<double>(
"contact_surface_layer");
else if (_key == "max_contacts")
_value = this->sdf->Get<int>("max_contacts");
else if (_key == "min_step_size")
_value = odeElem->GetElement("solver")->Get<double>("min_step_size");
else if (_key == "sor_lcp_tolerance")
_value = dWorldGetQuickStepTolerance(this->dataPtr->worldId);
else if (_key == "rms_error_tolerance")
{
gzwarn << "please use sor_lcp_tolerance in the future.\n";
_value = dWorldGetQuickStepTolerance(this->dataPtr->worldId);
}
else if (_key == "rms_error")
_value = dWorldGetQuickStepRMSDeltaLambda(this->dataPtr->worldId);
else if (_key == "constraint_residual")
_value = dWorldGetQuickStepRMSConstraintResidual(this->dataPtr->worldId);
else if (_key == "num_contacts")
_value = dWorldGetQuickStepNumContacts(this->dataPtr->worldId);
else if (_key == "inertia_ratio_reduction" ||
_key == "use_dynamic_moi_rescaling")
_value = dWorldGetQuickStepInertiaRatioReduction(this->dataPtr->worldId);
else if (_key == "contact_residual_smoothing")
_value = dWorldGetQuickStepContactResidualSmoothing(this->dataPtr->worldId);
else if (_key == "contact_sor_scale")
_value = dWorldGetQuickStepContactSORScalingFactor(this->dataPtr->worldId);
else if (_key == "thread_position_correction")
_value = dWorldGetQuickStepThreadPositionCorrection(this->dataPtr->worldId);
else if (_key == "experimental_row_reordering")
{
_value = dWorldGetQuickStepExperimentalRowReordering
(this->dataPtr->worldId);
}
else if (_key == "warm_start_factor")
_value = dWorldGetQuickStepWarmStartFactor(this->dataPtr->worldId);
else if (_key == "extra_friction_iterations")
_value = dWorldGetQuickStepExtraFrictionIterations(this->dataPtr->worldId);
else if (_key == "friction_model")
_value = this->GetFrictionModel();
else if (_key == "ode_quiet")
_value = dGetMessageHandler() != 0;
else if (_key == "world_step_solver")
_value = this->GetWorldStepSolverType();
else
{
return PhysicsEngine::GetParam(_key, _value);
}
return true;
}
|
/*******************************************************************************
*
* Copyright (c) 2010-2015 Edans Sandes
*
* This file is part of MASA-Core.
*
* MASA-Core is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MASA-Core is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MASA-Core. If not, see <http://www.gnu.org/licenses/>.
*
******************************************************************************/
#ifndef IMANAGER_HPP_
#define IMANAGER_HPP_
#include "libmasaTypes.hpp"
#include "Partition.hpp"
/* Recurrence Functions */
/** NW recurrence function */
#define NEEDLEMAN_WUNSCH (0)
/** SW recurrence function */
#define SMITH_WATERMAN (1)
/* Predefined initialization functions */
/** Init row/column with zeros */
#define INIT_WITH_ZEROES (0)
/** Init row/column with gaps */
#define INIT_WITH_GAPS (1)
/** Init row/column with gaps and without gap opening penalty*/
#define INIT_WITH_GAPS_OPENED (3)
/** Init row/column with custom data */
#define INIT_WITH_CUSTOM_DATA (2)
/* Start type of the partition */
/** Partition starts normally */
#define START_TYPE_MATCH (0)
/** Partition starts with horizontal gap */
#define START_TYPE_GAP_H (1)
/** Partition starts with vertical gap */
#define START_TYPE_GAP_V (2)
/** @brief Interface that manages the MASA extension execution.
*
* The MASA framework has an implementation of the IManager interface, that is
* responsible to receive commands from the Aligner. These commands are
* classified in the following types:
*
* <ul>
* <li><b>getXXX</b> methods: Return information about the desired alignment. For
* example, the get methods returns the coordinates of the partition
* to be aligned; the sequences data; the start type of the alignment
* <li><b>receiveXXX</b> methods: Receives rows or columns from the MASA framework.
* <li><b>dispatchXXX</b> methods: Sends rows or columns to the MASA framework.
* <li><b>mustXXX</b> methods: Returns true if some requirement must be activated.
* </ul>
*
* In order to test these conditional requirements, each aligner is associated
* with an instance of the IManager interface (see setManager() function).
* Besides the conditional requirement tests, the Manager also provides all
* the parameters necessary to customize the alignment, for example
* the sequences, the partitions coordinates.
* The AbstractAligner hides the IManager invocation using some delegate
* methods with protected visibility.
*
* @see The aligner_capabilities_t struct describes all the possible capabilities
* and the requirement necessary to implement it.
* @see The AbstractAligner has many methods that helps the implementation of
* the IAligner interface.
* @see The IManager interface manages the execution of the IAligner.
*/
class IManager {
public:
/* "GET" METHODS */
/**
* @return the recurrence type of the alignment. Possible values are SMITH_WATERMAN and NEEDLEMAN_WUNSCH.
*/
virtual int getRecurrenceType() const = 0;
/**
* @return the minimum distance between two special rows, or 0 if it must
* not save special rows.
*/
virtual int getSpecialRowInterval() const = 0;
/**
* @return the minimum distance between two special columns, or 0 if it must
* not save special columns.
*/
virtual int getSpecialColumnInterval() const = 0;
/**
* Returns the initialization type of the first column. Possible values are
* <ul>
* <li>
* INIT_WITH_CUSTOM_DATA: the first column must be initialized with custom data
* that can only be obtained by the AbstractAligner::receiveFirstColumn method.
* </li>
*
* <li>
* INIT_WITH_GAPS: the first column must be initialized considering gaps.
* The initialization equation is:
* \f{eqnarray*}{H_{0,0} &=& 0 \\ H_{k,0} &=& -k.G_{ext}-G_{open} \\ F_{k,0} &=& -\infty \f}
* </li>
*
* <li>
* INIT_WITH_GAPS_OPENED: the first column must be initialized considering gaps,
* but without gap opening penalty.
* The initialization equation is:
* \f{eqnarray*}{H_{k,0} &=& -k.G_{ext} \\ F_{k,0} &=& -\infty \f}
* </li>
*
* <li>
* INIT_WITH_ZEROES: the first column must be initialized considering zero values.
* The initialization equation is:
* \f{eqnarray*}{H_{k,0} &=& 0 \\ F_{k,0} &=& -\infty \f}
* </li>
*
* The initialization data of all types may be obtained by the AbstractAligner::receiveFirstColumn
* method, but the subclass of AbstractAligner may implement the initialization functions
* using some architectural dependent code (for example, using vectorial hardware instructions).
*
* </ul>
* @return the initialization type.
*/
virtual int getFirstColumnInitType() = 0;
/**
* Returns the initialization type of the first row. Possible values are
* <ul>
* <li>
* INIT_WITH_CUSTOM_DATA: the first row must be initialized with custom data
* that can only be obtained by the AbstractAligner::receiveFirstRow method.
* </li>
*
* <li>
* INIT_WITH_GAPS: the first column must be initialized considering gaps.
* The initialization equation is:
* \f{eqnarray*}{H_{0,0} &=& 0 \\ H_{0,k} &=& -k.G_{ext}-G_{open} \\ F_{0,k} &=& -\infty \f}
* </li>
*
* <li>
* INIT_WITH_GAPS_OPENED: the first column must be initialized considering gaps,
* but without gap opening penalty.
* The initialization equation is:
* \f{eqnarray*}{H_{0,k} &=& -k.G_{ext} \\ F_{0,k} &=& -\infty \f}
* </li>
*
* <li>
* INIT_WITH_ZEROES: the first row must be initialized considering zero values.
* The initialization equation is:
* \f{eqnarray*}{H_{0,k} &=& 0 \\ F_{0,k} &=& -\infty \f}
* </li>
*
* The initialization data of all types may be obtained by the AbstractAligner::receiveFirstRow
* method, but the subclass of AbstractAligner may implement the initialization functions
* using some architectural dependent code (for example, using vectorial hardware instructions).
*
* </ul>
* @return the initialization type.
*/
virtual int getFirstRowInitType() = 0;
/**
* Returns the super partition that includes all sub partitions being aligned.
* This method must be used only by block pruning algorithms in order to
* obtain the corner coordinates of the matrix.
*
* A super partition is a set of many smaller partitions and this occurs
* in two situations. The first is when we are running stage1 in a
* multiprocess environment, where we have one sub partition for each
* process. The second situation happens when the aligner cannot handle
* the full size of the matrix, so the partition is split in parts
* smaller than the max sequence size capability of the aligner.
*
* @return the super partition.
*/
virtual Partition getSuperPartition() = 0;
/* "RECEIVE" METHODS */
/**
* Receives the first row of the partition. This function may block until
* all the requested data is ready. So prefer to read data in chunks instead
* of reading the full first row.
* The data will be stored from 0 to len-1 positions of the vector passed in the parameters.
*
* @param buffer the vector where the first row data will be stored.
* @param len the number of cells that will be read.
*/
virtual void receiveFirstRow(cell_t* buffer, int len) = 0;
/**
* Receives the first column of the partition. This function may block until
* all the requested data is ready. So prefer to read data in chunks instead
* of reading the full first row.
* The data will be stored from 0 to len-1 positions of the vector passed in the parameters.
*
* @param buffer the vector where the first column data will be stored.
* @param len the number of cells that will be read.
*/
virtual void receiveFirstColumn(cell_t* buffer, int len) = 0;
/* "DISPATCH" METHODS */
/**
* Notifies to the MASA framework that some cells of a column has been processed.
* This function must be called serially for each column. For example,
* the invocation of dispatchColumn(50000, vector, 100) will dispatch the
* first 100 cells of the column 50000 to MASA, and the cells are read from
* the vector[0..99] elements. After this, a call to dispatchColumn(50000, vector, 50)
* will dispatch the next 50 cells of the same column 5000, and the cells are read from
* the vector[0..49] elements.
*
* @param j the column to be dispatched.
* @param buffer the vector containing the data (starting from cell 0).
* @param len the number of cells that will be read from the vector.
*/
virtual void dispatchColumn(int j, const cell_t* buffer, int len) = 0;
/**
* Notifies to the MASA framework that some cells of a row has been processed.
* This function must be called serially for each row, analogous to the
* AbstractAligner::dispatchLastColumn method.
*
* @param i the row to be dispatched.
* @param buffer the vector containing the data (starting from cell 0).
* @param len the number of cells that will be read from the vector.
*/
virtual void dispatchRow(int i, const cell_t* buffer, int len) = 0;
/**
* Notifies to the MASA framework that a new score has been computed.
* This method may be called as many times it is necessary, and the
* best score will be calculated among all calls of this method.
*
* If the Aligner supports the aligner_capabilities_t::dispatch_block_scores
* capability, them it must dispatch the score with the bx, by parameters
* set to the block indices and this method must be called only once for
* each block.
*
* @param score the score to be dispatched
* @param bx the block position in the horizontal direction, starting from
* 0 up to AbstractAligner::getGridWidth() minus 1.
* @param by the block position in the vertical direction, starting from
* 0 up to AbstractAligner::getGridHeight() minus 1.
*/
virtual void dispatchScore(score_t score, int bx=-1, int by=-1) = 0;
/* "MUST" METHODS */
/**
* @return true if the execution must continue.
*/
virtual bool mustContinue() = 0;
/**
* @return true if the last cell must be dispatched.
*/
virtual bool mustDispatchLastCell() = 0;
/**
* @return true if the last row must be dispatched.
*/
virtual bool mustDispatchLastRow() = 0;
/**
* @return true if the last column must be dispatched.
*/
virtual bool mustDispatchLastColumn() = 0;
/**
* @return true if special rows must be dispatched.
*/
virtual bool mustDispatchSpecialRows() = 0;
/**
* @return true if special columns must be dispatched.
*/
virtual bool mustDispatchSpecialColumns() = 0;
/**
* @return true if intermediate scores must be dispatched.
*/
virtual bool mustDispatchScores() = 0;
/**
* @return true if block pruning optimization may be used.
*/
virtual bool mustPruneBlocks() = 0;
protected:
/* Avoid the creation/deletion of this interface */
~IManager() {};
IManager() {};
};
#endif /* IMANAGER_HPP_ */
|
// Copyright (C) 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
********************************************************************************
* Copyright (C) 2005-2016, International Business Machines
* Corporation and others. All Rights Reserved.
********************************************************************************
*
* File WINDTTST.CPP
*
********************************************************************************
*/
#include "unicode/utypes.h"
#if U_PLATFORM_HAS_WIN32_API
#if !UCONFIG_NO_FORMATTING
#include "unicode/format.h"
#include "unicode/numfmt.h"
#include "unicode/locid.h"
#include "unicode/ustring.h"
#include "unicode/testlog.h"
#include "unicode/utmscale.h"
#include "windtfmt.h"
#include "winutil.h"
#include "windttst.h"
#include "cmemory.h"
#include "cstring.h"
#include "locmap.h"
#include "wintzimpl.h"
# define WIN32_LEAN_AND_MEAN
# define VC_EXTRALEAN
# define NOUSER
# define NOSERVICE
# define NOIME
# define NOMCX
# include <windows.h>
static const char *getCalendarType(int32_t type)
{
switch (type)
{
case 1:
case 2:
return "@calendar=gregorian";
case 3:
return "@calendar=japanese";
case 6:
return "@calendar=islamic";
case 7:
return "@calendar=buddhist";
case 8:
return "@calendar=hebrew";
default:
return "";
}
}
void Win32DateTimeTest::testLocales(TestLog *log)
{
SYSTEMTIME winNow;
UDate icuNow = 0;
SYSTEMTIME st;
FILETIME ft;
UnicodeString zoneID;
const TimeZone *tz = TimeZone::createDefault();
TIME_ZONE_INFORMATION tzi;
tz->getID(zoneID);
if (! uprv_getWindowsTimeZoneInfo(&tzi, zoneID.getBuffer(), zoneID.length())) {
UBool found = FALSE;
int32_t ec = TimeZone::countEquivalentIDs(zoneID);
for (int z = 0; z < ec; z += 1) {
UnicodeString equiv = TimeZone::getEquivalentID(zoneID, z);
if (found = uprv_getWindowsTimeZoneInfo(&tzi, equiv.getBuffer(), equiv.length())) {
break;
}
}
if (! found) {
GetTimeZoneInformation(&tzi);
}
}
GetSystemTime(&st);
SystemTimeToFileTime(&st, &ft);
SystemTimeToTzSpecificLocalTime(&tzi, &st, &winNow);
int64_t wftNow = ((int64_t) ft.dwHighDateTime << 32) + ft.dwLowDateTime;
UErrorCode status = U_ZERO_ERROR;
int64_t udtsNow = utmscale_fromInt64(wftNow, UDTS_WINDOWS_FILE_TIME, &status);
icuNow = (UDate) utmscale_toInt64(udtsNow, UDTS_ICU4C_TIME, &status);
int32_t lcidCount = 0;
Win32Utilities::LCIDRecord *lcidRecords = Win32Utilities::getLocales(lcidCount);
for(int i = 0; i < lcidCount; i += 1) {
UErrorCode status = U_ZERO_ERROR;
WCHAR longDateFormat[81], longTimeFormat[81], wdBuffer[256], wtBuffer[256];
int32_t calType = 0;
// NULL localeID means ICU didn't recognize this locale
if (lcidRecords[i].localeID == NULL) {
continue;
}
GetLocaleInfoW(lcidRecords[i].lcid, LOCALE_SLONGDATE, longDateFormat, 81);
GetLocaleInfoW(lcidRecords[i].lcid, LOCALE_STIMEFORMAT, longTimeFormat, 81);
GetLocaleInfoW(lcidRecords[i].lcid, LOCALE_RETURN_NUMBER|LOCALE_ICALENDARTYPE, (LPWSTR) calType, sizeof(int32_t));
char localeID[64];
uprv_strcpy(localeID, lcidRecords[i].localeID);
uprv_strcat(localeID, getCalendarType(calType));
UnicodeString ubBuffer, udBuffer, utBuffer;
Locale ulocale(localeID);
int32_t wdLength, wtLength;
wdLength = GetDateFormatW(lcidRecords[i].lcid, DATE_LONGDATE, &winNow, NULL, wdBuffer, UPRV_LENGTHOF(wdBuffer));
wtLength = GetTimeFormatW(lcidRecords[i].lcid, 0, &winNow, NULL, wtBuffer, UPRV_LENGTHOF(wtBuffer));
if (uprv_strchr(localeID, '@') > 0) {
uprv_strcat(localeID, ";");
} else {
uprv_strcat(localeID, "@");
}
uprv_strcat(localeID, "compat=host");
Locale wlocale(localeID);
DateFormat *wbf = DateFormat::createDateTimeInstance(DateFormat::kFull, DateFormat::kFull, wlocale);
DateFormat *wdf = DateFormat::createDateInstance(DateFormat::kFull, wlocale);
DateFormat *wtf = DateFormat::createTimeInstance(DateFormat::kFull, wlocale);
wbf->format(icuNow, ubBuffer);
wdf->format(icuNow, udBuffer);
wtf->format(icuNow, utBuffer);
if (ubBuffer.indexOf((const UChar *)wdBuffer, wdLength - 1, 0) < 0) {
UnicodeString baseName(wlocale.getBaseName());
UnicodeString expected((const UChar *)wdBuffer);
log->errln("DateTime format error for locale " + baseName + ": expected date \"" + expected +
"\" got \"" + ubBuffer + "\"");
}
if (ubBuffer.indexOf((const UChar *)wtBuffer, wtLength - 1, 0) < 0) {
UnicodeString baseName(wlocale.getBaseName());
UnicodeString expected((const UChar *)wtBuffer);
log->errln("DateTime format error for locale " + baseName + ": expected time \"" + expected +
"\" got \"" + ubBuffer + "\"");
}
if (udBuffer.compare((const UChar *)wdBuffer) != 0) {
UnicodeString baseName(wlocale.getBaseName());
UnicodeString expected((const UChar *)wdBuffer);
log->errln("Date format error for locale " + baseName + ": expected \"" + expected +
"\" got \"" + udBuffer + "\"");
}
if (utBuffer.compare((const UChar *)wtBuffer) != 0) {
UnicodeString baseName(wlocale.getBaseName());
UnicodeString expected((const UChar *)wtBuffer);
log->errln("Time format error for locale " + baseName + ": expected \"" + expected +
"\" got \"" + utBuffer + "\"");
}
delete wbf;
delete wdf;
delete wtf;
}
Win32Utilities::freeLocales(lcidRecords);
delete tz;
}
#endif /* #if !UCONFIG_NO_FORMATTING */
#endif /* U_PLATFORM_HAS_WIN32_API */
|
//===----------------------------------------------------------------------===//
// DuckDB
//
// duckdb/planner/tableref/bound_cteref.hpp
//
//
//===----------------------------------------------------------------------===//
#pragma once
#include "duckdb/planner/bound_tableref.hpp"
namespace duckdb {
class BoundCTERef : public BoundTableRef {
public:
BoundCTERef(idx_t bind_index, idx_t cte_index)
: BoundTableRef(TableReferenceType::CTE), bind_index(bind_index), cte_index(cte_index) {
}
//! The set of columns bound to this base table reference
vector<string> bound_columns;
//! The types of the values list
vector<SQLType> types;
//! The index in the bind context
idx_t bind_index;
//! The index of the cte
idx_t cte_index;
};
} // namespace duckdb
|
#include "ExprHelpers.h"
#include <Math/Random.h>
#include <Util/Assert.h>
VarVals_t::VarVals_t(const int n)
{
names.resize(n);
vals.resize(n);
}
bool optimizationGuide(const opInfo& opI, opPrio opP)
{ // Phase 0 == A only; 1 == early; 2 == late opt; 3 == late cleanup
switch (opP) {
case AA: return true; // 0123
case AB: return true; // 0123
case AI: return true; // 0123
case AL: return opI.phase >= 2 || (opI.phase == 1 && chance(1, 4)); // 1p23
case NL: return opI.phase == 3 || (opI.phase == 2 && chance(1, 2)); // 2p3
case NE: return (opI.phase == 1 || opI.phase == 2) && chance(1, 2); // 1p2p
case WE: return (opI.phase == 1 || opI.phase == 2) && chance(1, 3); // 1p2p
case XE: return opI.phase == 1 && chance(1, 3); // 1p
case SE: return (opI.phase == 1 || opI.phase == 2) && chance(1, 2); // 1p2p
case SL: return opI.phase == 3; // 3
case XX: return false;
}
ASSERT_R(0);
return false;
}
|
/*
* Copyright (c) 2011 Paul Tagliamonte <tag@pault.ag>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#ifndef __ANSIENTRY_HH
#define __ANSIENTRY_HH I_CAN_HAS
#include <ansiescape/State.hh>
class ANSIEntry : public State {
public:
virtual void feed ( char c );
virtual void enter();
virtual void exit();
};
extern ANSIEntry ansi_state_ANSIEntry;
#endif
|
#ifndef VECT4D_H
#define VECT4D_H
#ifdef __APPLE__
#include <OpenGL/gl.h>
#else
#include <GL/gl.h>
#endif
#include <cmath>
template <typename T>
class Vect4D
{
public:
T a[4];
Vect4D(T x, T y, T z, T w)
{
a[0] = x;
a[1] = y;
a[2] = z;
a[3] = w;
}
Vect4D(Vect4D<T> const & v)
{
a[0] = v.a[0];
a[1] = v.a[1];
a[2] = v.a[2];
a[3] = v.a[3];
}
~Vect4D(){}
void copy(Vect4D<T> v)
{
a[0] = v.a[0];
a[1] = v.a[1];
a[2] = v.a[2];
a[3] = v.a[3];
}
Vect4D<T> operator+(Vect4D<T> v)
{
Vect4D<T> res;
res.a[0] = a[0] + v.a[0];
res.a[1] = a[1] + v.a[1];
res.a[2] = a[2] + v.a[2];
res.a[3] = a[3] + v.a[3];
return(res);
}
Vect4D<T> operator-(Vect4D<T> v)
{
Vect4D<T> res;
res.a[0] = a[0] - v.a[0];
res.a[1] = a[1] - v.a[1];
res.a[2] = a[2] - v.a[2];
res.a[3] = a[3] - v.a[3];
return(res);
}
Vect4D<T> operator-(void)
{
Vect4D<T> res;
res.a[0] = -a[0];
res.a[1] = -a[1];
res.a[2] = -a[2];
res.a[3] = -a[3];
return(res);
}
Vect4D<T> operator*(T t)
{
Vect4D<T> res;
res.a[0] = a[0] * t;
res.a[1] = a[1] * t;
res.a[2] = a[2] * t;
res.a[3] = a[3] * t;
return (res);
}
Vect4D<T> operator/(T t)
{
Vect4D<T> res;
res.a[0] = a[0] / t;
res.a[1] = a[1] / t;
res.a[2] = a[2] / t;
res.a[3] = a[3] / t;
return (res);
}
T & operator[](int i)
{
return a[i];
}
GLdouble length()
{
return((GLdouble)sqrt(a[0]*a[0] + a[1]*a[1] + a[2]*a[2] + a[3]*a[3]));
}
void normalize()
{
GLdouble len;
len = length();
if (len < 0.001f) {
a[0] /= len;;
a[1] /= len;
a[2] /= len;
a[3] /= len;
}
}
GLdouble innerProduct(Vect4D v)
{
return (a[0] * v.a[0] + a[1] * v.a[1] + a[2] * v.a[2] + a[3] * v.a[3]);
}
void set(T x,T y, T z, T w)
{
a[0] = x;
a[1] = y;
a[2] = z;
a[3] = w;
}
Vect4D scalarMult(T c)
{
Vect4D res;
res.a[0] = a[0] * c;
res.a[1] = a[1] * c;
res.a[2] = a[2] * c;
res.a[3] = a[3] * c;
return res;
}
T * getVector(){return a;}
};
#endif
|
#include "IncludeDefine.h"
#include "Parameters.h"
#include "Transcript.h"
#include "ReadAlign.h"
ReadAlign::ReadAlign (Parameters& Pin, Genome &genomeIn, Transcriptome *TrIn, int iChunk)
: mapGen(genomeIn), genOut(*genomeIn.genomeOut.g), P(Pin), chunkTr(TrIn)
{
readNmates=P.readNmates;
//RNGs
rngMultOrder.seed(P.runRNGseed*(iChunk+1));
rngUniformReal0to1=std::uniform_real_distribution<double> (0.0, 1.0);
//transcriptome
if ( P.quant.trSAM.yes ) {
alignTrAll=new Transcript [P.alignTranscriptsPerReadNmax];
};
if (P.pGe.gType==101) {//SuperTranscriptome
splGraph = new SpliceGraph(*mapGen.superTr, P, this);
} else {//standard map algorithm:
winBin = new uintWinBin* [2];
winBin[0] = new uintWinBin [P.winBinN];
winBin[1] = new uintWinBin [P.winBinN];
memset(winBin[0],255,sizeof(winBin[0][0])*P.winBinN);
memset(winBin[1],255,sizeof(winBin[0][0])*P.winBinN);
//split
splitR=new uint*[3];
splitR[0]=new uint[P.maxNsplit]; splitR[1]=new uint[P.maxNsplit]; splitR[2]=new uint[P.maxNsplit];
//alignments
PC=new uiPC[P.seedPerReadNmax];
WC=new uiWC[P.alignWindowsPerReadNmax];
nWA=new uint[P.alignWindowsPerReadNmax];
nWAP=new uint[P.alignWindowsPerReadNmax];
WALrec=new uint[P.alignWindowsPerReadNmax];
WlastAnchor=new uint[P.alignWindowsPerReadNmax];
WA=new uiWA*[P.alignWindowsPerReadNmax];
for (uint ii=0;ii<P.alignWindowsPerReadNmax;ii++)
WA[ii]=new uiWA[P.seedPerWindowNmax];
WAincl = new bool [P.seedPerWindowNmax];
#ifdef COMPILE_FOR_LONG_READS
swWinCov = new uint[P.alignWindowsPerReadNmax];
scoreSeedToSeed = new intScore [P.seedPerWindowNmax*(P.seedPerWindowNmax+1)/2];
scoreSeedBest = new intScore [P.seedPerWindowNmax];
scoreSeedBestInd = new uint [P.seedPerWindowNmax];
scoreSeedBestMM = new uint [P.seedPerWindowNmax];
seedChain = new uint [P.seedPerWindowNmax];
#endif
};
//aligns a.k.a. transcripts
trAll = new Transcript**[P.alignWindowsPerReadNmax+1];
nWinTr = new uint[P.alignWindowsPerReadNmax];
trArray = new Transcript[P.alignTranscriptsPerReadNmax];
trArrayPointer = new Transcript*[P.alignTranscriptsPerReadNmax];
for (uint ii=0;ii<P.alignTranscriptsPerReadNmax;ii++)
trArrayPointer[ii]= &(trArray[ii]);
trInit = new Transcript;
if (mapGen.genomeOut.convYes) {//allocate output transcripts
trMultOut = new Transcript*[P.outFilterMultimapNmax];
for (uint32 ii=0; ii<P.outFilterMultimapNmax; ii++)
trMultOut[ii]=new Transcript;
};
//read
Read0 = new char*[2];
Read0[0] = new char [DEF_readSeqLengthMax+1];
Read0[1] = new char [DEF_readSeqLengthMax+1];
Qual0 = new char*[2];
Qual0[0] = new char [DEF_readSeqLengthMax+1];
Qual0[1] = new char [DEF_readSeqLengthMax+1];
readNameMates=new char* [P.readNmates];
for (uint ii=0; ii<P.readNmates; ii++) {
readNameMates[ii]=new char [DEF_readNameLengthMax];
};
readNameExtra.resize(P.readNmates);
readName = readNameMates[0];
Read1 = new char*[3];
Read1[0]=new char[DEF_readSeqLengthMax+1]; Read1[1]=new char[DEF_readSeqLengthMax+1]; Read1[2]=new char[DEF_readSeqLengthMax+1];
Qual1=new char*[2]; //modified QSs for scoring
Qual1[0]=new char[DEF_readSeqLengthMax+1]; Qual1[1]=new char[DEF_readSeqLengthMax+1];
//outBAM
outBAMoneAlignNbytes = new uint [P.readNmates+2]; //extra piece for chimeric reads
outBAMoneAlign = new char* [P.readNmates+2]; //extra piece for chimeric reads
for (uint ii=0; ii<P.readNmates+2; ii++) {
outBAMoneAlign[ii]=new char [BAMoutput_oneAlignMaxBytes];
};
resetN();
//chim
chunkOutChimJunction = new fstream;
chimDet = new ChimericDetection(P, trAll, nWinTr, Read1, mapGen, chunkOutChimJunction, this);
//solo
soloRead = new SoloRead (P, iChunk);
};
void ReadAlign::resetN () {//reset resets the counters to 0 for a new read
mapMarker=0;
nA=0;nP=0;nW=0;
nTr=0;nTrMate=0;
nUM[0]=0;nUM[1]=0;
storedLmin=0; uniqLmax=0; uniqLmaxInd=0; multLmax=0; multLmaxN=0; multNminL=0; multNmin=0; multNmax=0; multNmaxL=0;
chimN=0;
for (uint ii=0; ii<P.readNmates; ii++) {
maxScoreMate[ii]=0;
};
};
|
/*
* Copyright (c) 2014-2021, NVIDIA CORPORATION. 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.
*
* SPDX-FileCopyrightText: Copyright (c) 2014-2021 NVIDIA CORPORATION
* SPDX-License-Identifier: Apache-2.0
*/
// ImGui - standalone example application for Glfw + Vulkan, using programmable
// pipeline If you are new to ImGui, see examples/README.txt and documentation
// at the top of imgui.cpp.
#include <array>
#include "backends/imgui_impl_glfw.h"
#include "imgui.h"
#include "hdr_sample.hpp"
#include "imgui/imgui_camera_widget.h"
#include "nvh/cameramanipulator.hpp"
#include "nvh/fileoperations.hpp"
#include "nvpsystem.hpp"
#include "nvvk/commands_vk.hpp"
#include "nvvk/context_vk.hpp"
#include "nvh/inputparser.h"
#include "nvvk/gizmos_vk.hpp"
#include "nvvk/dynamicrendering_vk.hpp"
//////////////////////////////////////////////////////////////////////////
#define UNUSED(x) (void)(x)
//////////////////////////////////////////////////////////////////////////
// Default search path for shaders
std::vector<std::string> defaultSearchPaths;
// GLFW Callback functions
static void onErrorCallback(int error, const char* description)
{
fprintf(stderr, "GLFW Error %d: %s\n", error, description);
}
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
static int const SAMPLE_WIDTH = 1280;
static int const SAMPLE_HEIGHT = 720;
//--------------------------------------------------------------------------------------------------
// Application Entry
//
int main(int argc, char** argv)
{
InputParser parser(argc, argv);
std::string sceneFile = parser.getString("-f", "media/cornellBox.gltf");
std::string hdrFile = parser.getString("-h", "media/spruit_sunrise_1k.hdr");
// Setup GLFW window
glfwSetErrorCallback(onErrorCallback);
if(!glfwInit())
{
return 1;
}
glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
GLFWwindow* window = glfwCreateWindow(SAMPLE_WIDTH, SAMPLE_HEIGHT, PROJECT_NAME, nullptr, nullptr);
// Setup camera
CameraManip.setWindowSize(SAMPLE_WIDTH, SAMPLE_HEIGHT);
CameraManip.setLookat(nvmath::vec3f(0, 0, 15), nvmath::vec3f(0, 0, 0), nvmath::vec3f(0, 1, 0));
// Setup Vulkan
if(!glfwVulkanSupported())
{
printf("GLFW: Vulkan Not Supported\n");
return 1;
}
// setup some basic things for the sample, logging file for example
NVPSystem system(PROJECT_NAME);
// Search path for shaders and other media
defaultSearchPaths = {
NVPSystem::exePath() + PROJECT_RELDIRECTORY,
NVPSystem::exePath() + PROJECT_RELDIRECTORY "..",
std::string(PROJECT_NAME),
};
// Find the files
sceneFile = nvh::findFile(sceneFile, defaultSearchPaths, true);
hdrFile = nvh::findFile(hdrFile, defaultSearchPaths, true);
// Vulkan required extensions
assert(glfwVulkanSupported() == 1);
uint32_t count{0};
auto reqExtensions = glfwGetRequiredInstanceExtensions(&count);
// Requesting Vulkan extensions and layers
nvvk::ContextCreateInfo contextInfo;
contextInfo.setVersion(1, 3); // Using Vulkan 1.3
for(uint32_t ext_id = 0; ext_id < count; ext_id++) // Adding required extensions (surface, win32, linux, ..)
contextInfo.addInstanceExtension(reqExtensions[ext_id]);
contextInfo.addInstanceExtension(VK_EXT_DEBUG_UTILS_EXTENSION_NAME, true); // Allow debug names
contextInfo.addDeviceExtension(VK_KHR_SWAPCHAIN_EXTENSION_NAME); // Enabling ability to present rendering
// #VKRay: Activate the ray tracing extension
VkPhysicalDeviceAccelerationStructureFeaturesKHR accelFeature{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ACCELERATION_STRUCTURE_FEATURES_KHR};
contextInfo.addDeviceExtension(VK_KHR_ACCELERATION_STRUCTURE_EXTENSION_NAME, false, &accelFeature); // To build acceleration structures
VkPhysicalDeviceRayTracingPipelineFeaturesKHR rtPipelineFeature{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_RAY_TRACING_PIPELINE_FEATURES_KHR};
contextInfo.addDeviceExtension(VK_KHR_RAY_TRACING_PIPELINE_EXTENSION_NAME, false, &rtPipelineFeature); // To use vkCmdTraceRaysKHR
VkPhysicalDeviceRayQueryFeaturesKHR rayQueryFeatures{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_RAY_QUERY_FEATURES_KHR};
contextInfo.addDeviceExtension(VK_KHR_RAY_QUERY_EXTENSION_NAME, false, &rayQueryFeatures); // Used for picking
contextInfo.addDeviceExtension(VK_KHR_DEFERRED_HOST_OPERATIONS_EXTENSION_NAME); // Required by ray tracing pipeline
contextInfo.addDeviceExtension(VK_KHR_BUFFER_DEVICE_ADDRESS_EXTENSION_NAME);
// Creating Vulkan base application
nvvk::Context vkctx{};
vkctx.initInstance(contextInfo);
// Find all compatible devices
auto compatibleDevices = vkctx.getCompatibleDevices(contextInfo);
assert(!compatibleDevices.empty());
// Use a compatible device
vkctx.initDevice(compatibleDevices[0], contextInfo);
// Create example
HdrSample vkSample;
// Window need to be opened to get the surface on which to draw
const VkSurfaceKHR surface = vkSample.getVkSurface(vkctx.m_instance, window);
vkctx.setGCTQueueWithPresent(surface);
// Creation of the application
nvvk::AppBaseVkCreateInfo info;
info.instance = vkctx.m_instance;
info.device = vkctx.m_device;
info.physicalDevice = vkctx.m_physicalDevice;
info.size = {SAMPLE_WIDTH, SAMPLE_HEIGHT};
info.surface = surface;
info.window = window;
info.useDynamicRendering = true;
info.queueIndices.push_back(vkctx.m_queueGCT.familyIndex);
vkSample.create(info);
// Loading and creating the scene
vkSample.createHdr(hdrFile);
vkSample.createScene(sceneFile);
nvvk::AxisVK vkAxis;
nvvk::AxisVK::CreateAxisInfo ainfo;
ainfo.colorFormat = {vkSample.getColorFormat()};
ainfo.depthFormat = vkSample.getDepthFormat();
vkAxis.init(vkctx.m_device, ainfo);
// Main loop
while(!glfwWindowShouldClose(window))
{
glfwPollEvents();
if(vkSample.isMinimized())
continue;
// Start the Dear ImGui frame
ImGui_ImplGlfw_NewFrame();
ImGui::NewFrame();
// UI and info
vkSample.titleBar();
vkSample.renderUI();
// Start rendering the scene
vkSample.prepareFrame();
// Start command buffer of this frame
auto curFrame = vkSample.getCurFrame();
const VkCommandBuffer& cmdBuf = vkSample.getCommandBuffers()[curFrame];
VkCommandBufferBeginInfo beginInfo{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO};
beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
vkBeginCommandBuffer(cmdBuf, &beginInfo);
// Updating frame information
vkSample.updateUniformBuffer(cmdBuf);
// Clearing screen
std::array<VkClearValue, 2> clearValues{};
clearValues[0].color = vkSample.clearColor();
clearValues[1].depthStencil = {1.0f, 0};
// Offscreen Rendering Scene
{
if(vkSample.m_renderMode == VulkanSample::RenderMode::eRayTracer)
{
// Ray tracing don't need any rendering pass
vkSample.raytrace(cmdBuf);
}
else
{
vkSample.drawDome(cmdBuf);
// Raster
vkSample.rasterize(cmdBuf);
}
}
// 2nd rendering pass: tone mapper, UI
{
nvvk::createRenderingInfo rInfo({{0, 0}, vkSample.getSize()}, {vkSample.getSwapChain().getActiveImageView()},
vkSample.getDepthView());
// Rendering to the swapchain framebuffer the rendered image and apply a tonemapper
vkCmdBeginRendering(cmdBuf, &rInfo);
vkSample.drawPost(cmdBuf);
// Rendering UI
ImGui::Render();
ImGui_ImplVulkan_RenderDrawData(ImGui::GetDrawData(), cmdBuf);
// Display axis in the lower left corner.
vkAxis.display(cmdBuf, CameraManip.getMatrix(), vkSample.getSize());
vkCmdEndRendering(cmdBuf);
}
// Submit for display
vkEndCommandBuffer(cmdBuf);
vkSample.submitFrame();
}
// Cleanup
vkDeviceWaitIdle(vkSample.getDevice());
vkSample.destroy();
vkAxis.deinit();
vkctx.deinit();
glfwDestroyWindow(window);
glfwTerminate();
return 0;
}
|
#pragma once
#include "constant.hpp"
namespace ntl {
template <typename Stream>
void produce(Stream& out, bool enabled = true)
{
#pragma HLS inline region
typedef typename stream_element<Stream>::type stream_element_t;
constant(stream_element_t(0)).step(out, enabled);
}
}
|
//=============================================================================
//
// Adventure Game Studio (AGS)
//
// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
// The full list of copyright holders can be found in the Copyright.txt
// file, which is part of this source code distribution.
//
// The AGS source code is provided under the Artistic License 2.0.
// A copy of this license can be found in the file License.txt and at
// http://www.opensource.org/licenses/artistic-license-2.0.php
//
//=============================================================================
//
// Engine initialization
//
#include "main/mainheader.h"
#include "ac/asset_helper.h"
#include "ac/common.h"
#include "ac/character.h"
#include "ac/characterextras.h"
#include "ac/characterinfo.h"
#include "ac/draw.h"
#include "ac/game.h"
#include "ac/gamesetup.h"
#include "ac/gamesetupstruct.h"
#include "ac/global_character.h"
#include "ac/global_game.h"
#include "ac/gui.h"
#include "ac/lipsync.h"
#include "ac/objectcache.h"
#include "ac/path_helper.h"
#include "ac/record.h"
#include "ac/roomstatus.h"
#include "ac/speech.h"
#include "ac/translation.h"
#include "ac/viewframe.h"
#include "ac/dynobj/scriptobject.h"
#include "ac/dynobj/scriptsystem.h"
#include "debug/debug_log.h"
#include "debug/debugger.h"
#include "debug/out.h"
#include "font/agsfontrenderer.h"
#include "font/fonts.h"
#include "main/config.h"
#include "main/game_start.h"
#include "main/engine.h"
#include "main/engine_setup.h"
#include "main/graphics_mode.h"
#include "main/main.h"
#include "main/main_allegro.h"
#include "media/audio/sound.h"
#include "ac/spritecache.h"
#include "util/filestream.h"
#include "gfx/graphicsdriver.h"
#include "core/assetmanager.h"
#include "util/misc.h"
#include "platform/util/pe.h"
#include "util/directory.h"
#include "util/path.h"
#include "main/game_file.h"
#include "debug/out.h"
using namespace AGS::Common;
using namespace AGS::Engine;
extern char check_dynamic_sprites_at_exit;
extern int our_eip;
extern volatile char want_exit, abort_engine;
extern bool justRunSetup;
extern GameSetup usetup;
extern GameSetupStruct game;
extern int proper_exit;
extern char pexbuf[STD_BUFFER_SIZE];
extern char saveGameDirectory[260];
extern int spritewidth[MAX_SPRITES],spriteheight[MAX_SPRITES];
extern SpriteCache spriteset;
extern ObjectCache objcache[MAX_INIT_SPR];
extern ScriptObject scrObj[MAX_INIT_SPR];
extern ViewStruct*views;
extern int displayed_room;
extern int eip_guinum;
extern int eip_guiobj;
extern const char *replayTempFile;
extern SpeechLipSyncLine *splipsync;
extern int numLipLines, curLipLine, curLipLinePhoneme;
extern ScriptSystem scsystem;
extern IGraphicsDriver *gfxDriver;
extern Bitmap **actsps;
extern color palette[256];
extern CharacterExtras *charextra;
extern CharacterInfo*playerchar;
extern Bitmap **guibg;
extern IDriverDependantBitmap **guibgbmp;
String music_file;
String speech_file;
t_engine_pre_init_callback engine_pre_init_callback = 0;
#define ALLEGRO_KEYBOARD_HANDLER
// KEYBOARD HANDLER
#if !defined (WINDOWS_VERSION)
int myerrno;
#else
int errno;
#define myerrno errno
#endif
bool engine_init_allegro()
{
Debug::Printf(kDbgMsg_Init, "Initializing allegro");
our_eip = -199;
// Initialize allegro
set_uformat(U_ASCII);
if (install_allegro(SYSTEM_AUTODETECT, &myerrno, atexit))
{
const char *al_err = get_allegro_error();
const char *user_hint = platform->GetAllegroFailUserHint();
platform->DisplayAlert("Unable to initialize Allegro system driver.\n%s\n\n%s",
al_err[0] ? al_err : "Allegro library provided no further information on the problem.",
user_hint);
return false;
}
return true;
}
void engine_setup_allegro()
{
// Setup allegro using constructed config string
const char *al_config_data = "[mouse]\n"
"mouse_accel_factor = 0\n";
override_config_data(al_config_data, ustrsize(al_config_data));
}
void winclosehook() {
want_exit = 1;
abort_engine = 1;
check_dynamic_sprites_at_exit = 0;
}
void engine_setup_window()
{
Debug::Printf(kDbgMsg_Init, "Setting up window");
our_eip = -198;
#if (ALLEGRO_DATE > 19990103)
set_window_title("Adventure Game Studio");
#if (ALLEGRO_DATE > 20021115)
set_close_button_callback (winclosehook);
#else
set_window_close_hook (winclosehook);
#endif
our_eip = -197;
#endif
platform->SetGameWindowIcon();
}
bool engine_check_run_setup(const String &exe_path, ConfigTree &cfg)
{
#if defined (WINDOWS_VERSION)
// check if Setup needs to be run instead
if (justRunSetup)
{
String cfg_file = find_user_cfg_file();
if (cfg_file.IsEmpty())
return false;
Debug::Printf(kDbgMsg_Init, "Running Setup");
// Add information about game resolution and let setup application
// display some properties to the user
INIwriteint(cfg, "misc", "defaultres", game.GetDefaultResolution());
INIwriteint(cfg, "misc", "letterbox", game.options[OPT_LETTERBOX]);
INIwriteint(cfg, "misc", "game_width", game.size.Width);
INIwriteint(cfg, "misc", "game_height", game.size.Height);
INIwriteint(cfg, "misc", "gamecolordepth", game.color_depth * 8);
if (game.options[OPT_RENDERATSCREENRES] != kRenderAtScreenRes_UserDefined)
{
// force enabled/disabled
INIwriteint(cfg, "graphics", "render_at_screenres", game.options[OPT_RENDERATSCREENRES] == kRenderAtScreenRes_Enabled);
INIwriteint(cfg, "disabled", "render_at_screenres", 1);
}
ConfigTree cfg_out;
SetupReturnValue res = platform->RunSetup(cfg, cfg_out);
if (res != kSetup_Cancel)
{
if (!IniUtil::Merge(cfg_file, cfg_out))
{
platform->DisplayAlert("Unable to write to the configuration file (error code 0x%08X).\n%s",
platform->GetLastSystemError(), platform->GetDiskWriteAccessTroubleshootingText());
}
}
if (res != kSetup_RunGame)
return false;
// TODO: investigate if the full program restart may (should) be avoided
// Just re-reading the config file seems to cause a caching
// problem on Win9x, so let's restart the process.
allegro_exit();
char quotedpath[MAX_PATH];
snprintf(quotedpath, MAX_PATH, "\"%s\"", exe_path.GetCStr());
_spawnl (_P_OVERLAY, exe_path, quotedpath, NULL);
}
#endif
return true;
}
void engine_force_window()
{
// Force to run in a window, override the config file
// TODO: actually overwrite config tree instead
if (force_window == 1)
{
usetup.Screen.DisplayMode.Windowed = true;
usetup.Screen.DisplayMode.ScreenSize.SizeDef = kScreenDef_ByGameScaling;
}
else if (force_window == 2)
{
usetup.Screen.DisplayMode.Windowed = false;
usetup.Screen.DisplayMode.ScreenSize.SizeDef = kScreenDef_MaxDisplay;
}
}
void init_game_file_name_from_cmdline()
{
game_file_name.Empty();
#if defined(PSP_VERSION) || defined(ANDROID_VERSION) || defined(IOS_VERSION) || defined(MAC_VERSION)
game_file_name = psp_game_file_name;
#else
game_file_name = GetPathFromCmdArg(datafile_argv);
#endif
}
String find_game_data_in_directory(const String &path)
{
al_ffblk ff;
String test_file;
String first_nonstd_fn;
String pattern = path;
pattern.Append("/*");
if (al_findfirst(pattern, &ff, FA_ALL & ~(FA_DIREC)) != 0)
return "";
// Select first found data file; files with standart names (*.ags) have
// higher priority over files with custom names.
do
{
test_file = ff.name;
// Add a bit of sanity and do not parse contents of the 10k-files-large
// digital sound libraries.
// NOTE: we could certainly benefit from any kind of flag in file lib
// that would tell us this is the main lib without extra parsing.
if (test_file.CompareRightNoCase(".vox") == 0)
continue;
// *.ags is a standart cross-platform file pattern for AGS games,
// ac2game.dat is a legacy file name for very old games,
// *.exe is a MS Win executable; it is included to this case because
// users often run AGS ports with Windows versions of games.
bool is_std_name = test_file.CompareRightNoCase(".ags") == 0 ||
test_file.CompareNoCase("ac2game.dat") == 0 ||
test_file.CompareRightNoCase(".exe") == 0;
if (is_std_name || first_nonstd_fn.IsEmpty())
{
test_file.Format("%s/%s", path.GetCStr(), ff.name);
if (IsMainGameLibrary(test_file))
{
if (is_std_name)
{
al_findclose(&ff);
return test_file;
}
else
first_nonstd_fn = test_file;
}
}
}
while(al_findnext(&ff) == 0);
al_findclose(&ff);
return first_nonstd_fn;
}
bool search_for_game_data_file()
{
Debug::Printf("Looking for the game data file");
// 1. From command line argument
if (datafile_argv > 0)
{
// set game_file_name from cmd arg (do any convertions if needed)
init_game_file_name_from_cmdline();
if (!Path::IsFile(game_file_name))
{
// if it is not a file, assume it is a directory and seek for data file
game_file_name = find_game_data_in_directory(game_file_name);
}
}
// 2. From setup
// 2.1. Use the provided data dir and filename
else if (!usetup.main_data_filename.IsEmpty())
{
if (!usetup.data_files_dir.IsEmpty() && is_relative_filename(usetup.main_data_filename))
{
game_file_name = usetup.data_files_dir;
if (game_file_name.GetLast() != '/' && game_file_name.GetLast() != '\\')
game_file_name.AppendChar('/');
game_file_name.Append(usetup.main_data_filename);
}
else
{
game_file_name = usetup.main_data_filename;
}
}
// 2.2. Search in the provided data dir
else if (!usetup.data_files_dir.IsEmpty())
{
game_file_name = find_game_data_in_directory(usetup.data_files_dir);
}
// 3. Look in known locations
else
{
// 3.1. Look for attachment in the running executable
//
// set game_file_name from cmd arg (do any conversions if needed)
// this will use argument zero, the executable's name
init_game_file_name_from_cmdline();
if (game_file_name.IsEmpty() || !Common::AssetManager::IsDataFile(game_file_name))
{
// 3.2 Look in current directory
String cur_dir = Directory::GetCurrentDirectory();
game_file_name = find_game_data_in_directory(cur_dir);
if (game_file_name.IsEmpty())
{
// 3.3 Look in executable's directory (if it's different from current dir)
if (Path::ComparePaths(appDirectory, cur_dir))
{
game_file_name = find_game_data_in_directory(appDirectory);
}
}
}
}
// Finally, store game file's absolute path, or report error
if (game_file_name.IsEmpty())
{
Debug::Printf(kDbgMsg_Error, "Game data file could not be found");
return false;
}
else
{
game_file_name = Path::MakeAbsolutePath(game_file_name);
Debug::Printf(kDbgMsg_Init, "Located game data file: %s", game_file_name.GetCStr());
return true;
}
}
bool engine_init_game_data()
{
// Search for an available game package in the known locations
AssetError err;
if (search_for_game_data_file())
err = AssetManager::SetDataFile(game_file_name);
else
err = kAssetErrNoLibFile;
if (err != kAssetNoError)
{ // there's a problem
String emsg;
if (err == Common::kAssetErrLibParse)
{
emsg = String::FromFormat("ERROR: The game data is of unsupported format or file is corrupt.\nFile: '%s'", game_file_name.GetCStr());
}
else
{ // file not found, or another problem
if (game_file_name.IsEmpty())
emsg = "ERROR: Unable to find game data files.";
else
emsg = String::FromFormat("ERROR: Unable to find or open '%s'.", game_file_name.GetCStr());
}
platform->DisplayAlert(emsg);
main_print_help();
return false;
}
// Save data file name and data folder
usetup.main_data_filename = get_filename(game_file_name);
// There is a path in the game file name (and the user/ has not specified
// another one) save the path, so that it can load the VOX files, etc
if (usetup.data_files_dir.IsEmpty())
{
size_t ichar = game_file_name.FindCharReverse('/');
if (ichar != -1)
{
usetup.data_files_dir = game_file_name.Left(ichar);
}
}
return true;
}
void engine_init_fonts()
{
Debug::Printf(kDbgMsg_Init, "Initializing TTF renderer");
init_font_renderer();
}
int engine_init_mouse()
{
int res = minstalled();
if (res < 0)
Debug::Printf(kDbgMsg_Init, "Initializing mouse: failed");
else
Debug::Printf(kDbgMsg_Init, "Initializing mouse: number of buttons reported is %d", res);
return RETURN_CONTINUE;
}
int engine_check_memory()
{
Debug::Printf(kDbgMsg_Init, "Checking memory");
char*memcheck=(char*)malloc(4000000);
if (memcheck==NULL) {
platform->DisplayAlert("There is not enough memory available to run this game. You need 4 Mb free\n"
"extended memory to run the game.\n"
"If you are running from Windows, check the 'DPMI memory' setting on the DOS box\n"
"properties.\n");
return EXIT_NORMAL;
}
free(memcheck);
unlink (replayTempFile);
return RETURN_CONTINUE;
}
void engine_init_rooms()
{
// Obsolete now since room statuses are allocated only when needed
}
void engine_init_speech()
{
play.want_speech=-2;
if (!usetup.no_speech_pack) {
speech_file = "speech.vox";
String speech_filepath = find_assetlib(speech_file);
if (!speech_filepath.IsEmpty()) {
Debug::Printf("Initializing speech vox");
if (AssetManager::SetDataFile(speech_filepath)!=Common::kAssetNoError) {
platform->DisplayAlert("Unable to read voice pack, file could be corrupted or of unknown format.\nSpeech voice-over will be disabled.");
AssetManager::SetDataFile(game_file_name); // switch back to the main data pack
return;
}
Stream *speechsync = AssetManager::OpenAsset("syncdata.dat");
if (speechsync != NULL) {
// this game has voice lip sync
int lipsync_fmt = speechsync->ReadInt32();
if (lipsync_fmt != 4)
{
Debug::Printf(kDbgMsg_Init, "Unknown speech lip sync format (%d).\nLip sync disabled.", lipsync_fmt);
}
else {
numLipLines = speechsync->ReadInt32();
splipsync = (SpeechLipSyncLine*)malloc (sizeof(SpeechLipSyncLine) * numLipLines);
for (int ee = 0; ee < numLipLines; ee++)
{
splipsync[ee].numPhonemes = speechsync->ReadInt16();
speechsync->Read(splipsync[ee].filename, 14);
splipsync[ee].endtimeoffs = (int*)malloc(splipsync[ee].numPhonemes * sizeof(int));
speechsync->ReadArrayOfInt32(splipsync[ee].endtimeoffs, splipsync[ee].numPhonemes);
splipsync[ee].frame = (short*)malloc(splipsync[ee].numPhonemes * sizeof(short));
speechsync->ReadArrayOfInt16(splipsync[ee].frame, splipsync[ee].numPhonemes);
}
}
delete speechsync;
}
AssetManager::SetDataFile(game_file_name); // switch back to the main data pack
Debug::Printf(kDbgMsg_Init, "Voice pack found and initialized.");
play.want_speech=1;
}
else if (Path::ComparePaths(usetup.data_files_dir, get_voice_install_dir()) != 0)
{
// If we have custom voice directory set, we will enable voice-over even if speech.vox does not exist
Debug::Printf(kDbgMsg_Init, "Voice pack was not found, but voice installation directory is defined: enabling voice-over.");
play.want_speech=1;
}
}
}
int engine_init_music()
{
play.separate_music_lib = 0;
music_file = "audio.vox";
String music_filepath = find_assetlib(music_file);
if (!music_filepath.IsEmpty()) {
Debug::Printf("Initializing audio vox");
//if (Common::AssetManager::SetDataFile(useloc,"")!=0) {
if (Common::AssetManager::SetDataFile(music_filepath)!=Common::kAssetNoError) {
platform->DisplayAlert("Unable to initialize music library - check for corruption and that\nit belongs to this game.\n");
return EXIT_NORMAL;
}
Common::AssetManager::SetDataFile(game_file_name);
Debug::Printf(kDbgMsg_Init, "Audio vox found and initialized.");
play.separate_music_lib = 1;
}
return RETURN_CONTINUE;
}
void engine_init_keyboard()
{
#ifdef ALLEGRO_KEYBOARD_HANDLER
Debug::Printf(kDbgMsg_Init, "Initializing keyboard");
install_keyboard();
#endif
}
void engine_init_timer()
{
Debug::Printf(kDbgMsg_Init, "Install timer");
install_timer();
}
typedef char AlIDStr[5];
void AlIDToChars(int al_id, AlIDStr &id_str)
{
id_str[0] = (al_id >> 24) & 0xFF;
id_str[1] = (al_id >> 16) & 0xFF;
id_str[2] = (al_id >> 8) & 0xFF;
id_str[3] = (al_id) & 0xFF;
id_str[4] = 0;
}
void AlDigiToChars(int digi_id, AlIDStr &id_str)
{
if (digi_id == DIGI_NONE)
strcpy(id_str, "None");
else if (digi_id == DIGI_AUTODETECT)
strcpy(id_str, "Auto");
else
AlIDToChars(digi_id, id_str);
}
void AlMidiToChars(int midi_id, AlIDStr &id_str)
{
if (midi_id == MIDI_NONE)
strcpy(id_str, "None");
else if (midi_id == MIDI_AUTODETECT)
strcpy(id_str, "Auto");
else
AlIDToChars(midi_id, id_str);
}
bool try_install_sound(int digi_id, int midi_id)
{
if (install_sound(digi_id, midi_id, NULL) == 0)
return true;
// Allegro does not let you try digital and MIDI drivers separately,
// and does not indicate which driver failed by return value.
// Therefore we try to guess.
if (midi_id != MIDI_NONE)
{
Debug::Printf(kDbgMsg_Error, "Failed to init one of the drivers; Error: '%s'.\nWill try to start without MIDI", get_allegro_error());
if (install_sound(digi_id, MIDI_NONE, NULL) == 0)
return true;
}
if (digi_id != DIGI_NONE)
{
Debug::Printf(kDbgMsg_Error, "Failed to init one of the drivers; Error: '%s'.\nWill try to start without DIGI", get_allegro_error());
if (install_sound(DIGI_NONE, midi_id, NULL) == 0)
return true;
}
Debug::Printf(kDbgMsg_Error, "Failed to init sound drivers. Error: %s", get_allegro_error());
return false;
}
void engine_init_sound()
{
if (opts.mod_player)
reserve_voices(16, -1);
#if ALLEGRO_DATE > 19991010
// maybe this line will solve the sound volume?
set_volume_per_voice(1);
#endif
Debug::Printf("Initialize sound drivers");
// TODO: apply those options during config reading instead
if (!psp_audio_enabled)
{
usetup.digicard = DIGI_NONE;
usetup.midicard = MIDI_NONE;
}
if (!psp_midi_enabled)
usetup.midicard = MIDI_NONE;
AlIDStr digi_id;
AlIDStr midi_id;
AlDigiToChars(usetup.digicard, digi_id);
AlMidiToChars(usetup.midicard, midi_id);
Debug::Printf(kDbgMsg_Init, "Sound settings: digital driver ID: '%s' (0x%x), MIDI driver ID: '%s' (0x%x)",
digi_id, usetup.digicard, midi_id, usetup.midicard);
bool sound_res = try_install_sound(usetup.digicard, usetup.midicard);
if (!sound_res && opts.mod_player)
{
Debug::Printf("Resetting to default sound parameters and trying again.");
reserve_voices(-1, -1); // this resets voice number to defaults
opts.mod_player = 0;
sound_res = try_install_sound(usetup.digicard, usetup.midicard);
}
if (!sound_res)
{
// If everything failed, disable sound completely
Debug::Printf("Resetting to zero digital voices and trying again.");
reserve_voices(0,0);
install_sound(DIGI_NONE, MIDI_NONE, NULL);
}
if (usetup.digicard != DIGI_NONE && digi_card == DIGI_NONE ||
usetup.midicard != MIDI_NONE && midi_card == MIDI_NONE)
{
// only flag an error if they wanted a sound card
platform->DisplayAlert("\nUnable to initialize your audio hardware.\n"
"[Problem: %s]\n", get_allegro_error());
}
usetup.digicard = digi_card;
usetup.midicard = midi_card;
AlDigiToChars(usetup.digicard, digi_id);
AlMidiToChars(usetup.midicard, midi_id);
Debug::Printf(kDbgMsg_Init, "Installed digital driver ID: '%s' (0x%x), MIDI driver ID: '%s' (0x%x)",
digi_id, usetup.digicard, midi_id, usetup.midicard);
our_eip = -181;
if (usetup.digicard == DIGI_NONE)
{
// disable speech and music if no digital sound
// therefore the MIDI soundtrack will be used if present,
// and the voice mode should not go to Voice Only
play.want_speech = -2;
play.separate_music_lib = 0;
}
#ifdef WINDOWS_VERSION
if (usetup.digicard == DIGI_DIRECTX(0))
{
// DirectX mixer seems to buffer an extra sample itself
use_extra_sound_offset = 1;
}
#endif
}
void engine_init_debug()
{
//set_volume(255,-1);
if ((debug_flags & (~DBG_DEBUGMODE)) >0) {
platform->DisplayAlert("Engine debugging enabled.\n"
"\nNOTE: You have selected to enable one or more engine debugging options.\n"
"These options cause many parts of the game to behave abnormally, and you\n"
"may not see the game as you are used to it. The point is to test whether\n"
"the engine passes a point where it is crashing on you normally.\n"
"[Debug flags enabled: 0x%02X]\n"
"Press a key to continue.\n",debug_flags);
}
}
void atexit_handler() {
if (proper_exit==0) {
sprintf(pexbuf,"\nError: the program has exited without requesting it.\n"
"Program pointer: %+03d (write this number down), ACI version %s\n"
"If you see a list of numbers above, please write them down and contact\n"
"developers. Otherwise, note down any other information displayed.\n",
our_eip, EngineVersion.LongString.GetCStr());
platform->DisplayAlert(pexbuf);
}
}
void engine_init_exit_handler()
{
Debug::Printf(kDbgMsg_Init, "Install exit handler");
atexit(atexit_handler);
}
void engine_init_rand()
{
play.randseed = time(NULL);
srand (play.randseed);
}
void engine_init_pathfinder()
{
Debug::Printf(kDbgMsg_Init, "Initialize path finder library");
init_pathfinder();
}
void engine_pre_init_gfx()
{
//Debug::Printf("Initialize gfx");
//platform->InitialiseAbufAtStartup();
}
int engine_load_game_data()
{
Debug::Printf("Load game data");
our_eip=-17;
HError err = load_game_file();
if (!err)
{
proper_exit=1;
platform->FinishedUsingGraphicsMode();
display_game_file_error(err);
return EXIT_NORMAL;
}
return RETURN_CONTINUE;
}
int engine_check_register_game()
{
if (justRegisterGame)
{
platform->RegisterGameWithGameExplorer();
proper_exit = 1;
return EXIT_NORMAL;
}
if (justUnRegisterGame)
{
platform->UnRegisterGameWithGameExplorer();
proper_exit = 1;
return EXIT_NORMAL;
}
return RETURN_CONTINUE;
}
void engine_init_title()
{
//platform->DisplayAlert("loaded game");
our_eip=-91;
#if (ALLEGRO_DATE > 19990103)
set_window_title(game.gamename);
#endif
Debug::Printf(kDbgMsg_Init, "Game title: '%s'", game.gamename);
}
void engine_init_directories()
{
Debug::Printf(kDbgMsg_Init, "Data directory: %s", usetup.data_files_dir.GetCStr());
if (!usetup.install_dir.IsEmpty())
Debug::Printf(kDbgMsg_Init, "Optional install directory: %s", usetup.install_dir.GetCStr());
if (!usetup.install_audio_dir.IsEmpty())
Debug::Printf(kDbgMsg_Init, "Optional audio directory: %s", usetup.install_audio_dir.GetCStr());
if (!usetup.install_voice_dir.IsEmpty())
Debug::Printf(kDbgMsg_Init, "Optional voice-over directory: %s", usetup.install_voice_dir.GetCStr());
if (!usetup.user_data_dir.IsEmpty())
Debug::Printf(kDbgMsg_Init, "User data directory: %s", usetup.user_data_dir.GetCStr());
if (!usetup.shared_data_dir.IsEmpty())
Debug::Printf(kDbgMsg_Init, "Shared data directory: %s", usetup.shared_data_dir.GetCStr());
set_install_dir(usetup.install_dir, usetup.install_audio_dir, usetup.install_voice_dir);
if (!usetup.install_dir.IsEmpty())
{
// running in debugger: don't redirect to the game exe folder (_Debug)
// TODO: find out why we need to do this (and do we?)
usetup.data_files_dir = ".";
}
// if end-user specified custom save path, use it
bool res = false;
if (!usetup.user_data_dir.IsEmpty())
{
res = SetCustomSaveParent(usetup.user_data_dir);
if (!res)
{
Debug::Printf(kDbgMsg_Warn, "WARNING: custom user save path failed, using default system paths");
usetup.user_data_dir.Empty();
res = false;
}
}
// if there is no custom path, or if custom path failed, use default system path
if (!res)
{
char newDirBuffer[MAX_PATH];
sprintf(newDirBuffer, "%s/%s", UserSavedgamesRootToken.GetCStr(), game.saveGameFolderName);
SetSaveGameDirectoryPath(newDirBuffer);
}
}
#if defined(ANDROID_VERSION)
extern char android_base_directory[256];
#endif // ANDROID_VERSION
int check_write_access() {
if (platform->GetDiskFreeSpaceMB() < 2)
return 0;
our_eip = -1895;
// The Save Game Dir is the only place that we should write to
char tempPath[MAX_PATH];
sprintf(tempPath, "%s""tmptest.tmp", saveGameDirectory);
Stream *temp_s = Common::File::CreateFile(tempPath);
if (!temp_s)
// TODO: move this somewhere else (Android platform driver init?)
#if defined(ANDROID_VERSION)
{
put_backslash(android_base_directory);
sprintf(tempPath, "%s""tmptest.tmp", android_base_directory);
temp_s = Common::File::CreateFile(tempPath);
if (temp_s == NULL) return 0;
else SetCustomSaveParent(android_base_directory);
}
#else
return 0;
#endif // ANDROID_VERSION
our_eip = -1896;
temp_s->Write("just to test the drive free space", 30);
delete temp_s;
our_eip = -1897;
if (unlink(tempPath))
return 0;
return 1;
}
int engine_check_disk_space()
{
Debug::Printf(kDbgMsg_Init, "Checking for disk space");
if (check_write_access()==0) {
platform->DisplayAlert("Unable to write in the savegame directory.\n%s", platform->GetDiskWriteAccessTroubleshootingText());
proper_exit = 1;
return EXIT_NORMAL;
}
return RETURN_CONTINUE;
}
int engine_check_font_was_loaded()
{
if (!font_first_renderer_loaded())
{
platform->DisplayAlert("No game fonts found. At least one font is required to run the game.");
proper_exit = 1;
return EXIT_NORMAL;
}
return RETURN_CONTINUE;
}
void engine_init_modxm_player()
{
#ifndef PSP_NO_MOD_PLAYBACK
if (game.options[OPT_NOMODMUSIC])
opts.mod_player = 0;
if (opts.mod_player) {
Debug::Printf(kDbgMsg_Init, "Initializing MOD/XM player");
if (init_mod_player(NUM_MOD_DIGI_VOICES) < 0) {
platform->DisplayAlert("Warning: install_mod: MOD player failed to initialize.");
opts.mod_player=0;
}
}
#else
opts.mod_player = 0;
Debug::Printf(kDbgMsg_Init, "Compiled without MOD/XM player");
#endif
}
void show_preload () {
// ** Do the preload graphic if available
color temppal[256];
Bitmap *splashsc = BitmapHelper::CreateRawBitmapOwner( load_pcx("preload.pcx",temppal) );
if (splashsc != NULL) {
if (splashsc->GetColorDepth() == 8)
set_palette_range(temppal, 0, 255, 0);
Bitmap *screen_bmp = BitmapHelper::GetScreenBitmap();
Bitmap *tsc = BitmapHelper::CreateBitmapCopy(splashsc, screen_bmp->GetColorDepth());
screen_bmp->Fill(0);
screen_bmp->StretchBlt(tsc, RectWH(0, 0, play.viewport.GetWidth(),play.viewport.GetHeight()), Common::kBitmap_Transparency);
gfxDriver->ClearDrawList();
if (!gfxDriver->UsesMemoryBackBuffer())
{
IDriverDependantBitmap *ddb = gfxDriver->CreateDDBFromBitmap(screen_bmp, false, true);
gfxDriver->DrawSprite(0, 0, ddb);
render_to_screen(screen_bmp, 0, 0);
gfxDriver->DestroyDDB(ddb);
}
else
render_to_screen(screen_bmp, 0, 0);
delete splashsc;
delete tsc;
platform->Delay(500);
}
}
void engine_show_preload()
{
Debug::Printf("Check for preload image");
show_preload ();
}
int engine_init_sprites()
{
Debug::Printf(kDbgMsg_Init, "Initialize sprites");
if (spriteset.initFile ("acsprset.spr"))
{
platform->FinishedUsingGraphicsMode();
allegro_exit();
proper_exit=1;
platform->DisplayAlert("Could not load sprite set file ACSPRSET.SPR\n"
"This means that the file is missing or there is not enough free\n"
"system memory to load the file.\n");
return EXIT_NORMAL;
}
return RETURN_CONTINUE;
}
void engine_init_game_settings()
{
our_eip=-7;
Debug::Printf("Initialize game settings");
int ee;
for (ee = 0; ee < MAX_INIT_SPR + game.numcharacters; ee++)
actsps[ee] = NULL;
for (ee=0;ee<256;ee++) {
if (game.paluses[ee]!=PAL_BACKGROUND)
palette[ee]=game.defpal[ee];
}
if (game.options[OPT_NOSCALEFNT]) wtext_multiply=1;
for (ee = 0; ee < game.numcursors; ee++)
{
// The cursor graphics are assigned to mousecurs[] and so cannot
// be removed from memory
if (game.mcurs[ee].pic >= 0)
spriteset.precache (game.mcurs[ee].pic);
// just in case they typed an invalid view number in the editor
if (game.mcurs[ee].view >= game.numviews)
game.mcurs[ee].view = -1;
if (game.mcurs[ee].view >= 0)
precache_view (game.mcurs[ee].view);
}
// may as well preload the character gfx
if (playerchar->view >= 0)
precache_view (playerchar->view);
for (ee = 0; ee < MAX_INIT_SPR; ee++)
objcache[ee].image = NULL;
/* dummygui.guiId = -1;
dummyguicontrol.guin = -1;
dummyguicontrol.objn = -1;*/
our_eip=-6;
// game.chars[0].talkview=4;
//init_language_text(game.langcodes[0]);
for (ee = 0; ee < MAX_INIT_SPR; ee++) {
scrObj[ee].id = ee;
// 64 bit: Using the id instead
// scrObj[ee].obj = NULL;
}
for (ee=0;ee<game.numcharacters;ee++) {
memset(&game.chars[ee].inv[0],0,MAX_INV*sizeof(short));
game.chars[ee].activeinv=-1;
game.chars[ee].following=-1;
game.chars[ee].followinfo=97 | (10 << 8);
game.chars[ee].idletime=20; // can be overridden later with SetIdle or summink
game.chars[ee].idleleft=game.chars[ee].idletime;
game.chars[ee].transparency = 0;
game.chars[ee].baseline = -1;
game.chars[ee].walkwaitcounter = 0;
game.chars[ee].z = 0;
charextra[ee].xwas = INVALID_X;
charextra[ee].zoom = 100;
if (game.chars[ee].view >= 0) {
// set initial loop to 0
game.chars[ee].loop = 0;
// or to 1 if they don't have up/down frames
if (views[game.chars[ee].view].loops[0].numFrames < 1)
game.chars[ee].loop = 1;
}
charextra[ee].process_idle_this_time = 0;
charextra[ee].invorder_count = 0;
charextra[ee].slow_move_counter = 0;
charextra[ee].animwait = 0;
}
// multiply up gui positions
guibg = (Bitmap **)malloc(sizeof(Bitmap *) * game.numgui);
guibgbmp = (IDriverDependantBitmap**)malloc(sizeof(IDriverDependantBitmap*) * game.numgui);
for (ee=0;ee<game.numgui;ee++) {
guibg[ee] = NULL;
guibgbmp[ee] = NULL;
}
our_eip=-5;
for (ee=0;ee<game.numinvitems;ee++) {
if (game.invinfo[ee].flags & IFLG_STARTWITH) playerchar->inv[ee]=1;
else playerchar->inv[ee]=0;
}
play.score=0;
play.sierra_inv_color=7;
// copy the value set by the editor
if (game.options[OPT_GLOBALTALKANIMSPD] >= 0)
{
play.talkanim_speed = game.options[OPT_GLOBALTALKANIMSPD];
game.options[OPT_GLOBALTALKANIMSPD] = 1;
}
else
{
play.talkanim_speed = -game.options[OPT_GLOBALTALKANIMSPD] - 1;
game.options[OPT_GLOBALTALKANIMSPD] = 0;
}
play.inv_item_wid = 40;
play.inv_item_hit = 22;
play.messagetime=-1;
play.disabled_user_interface=0;
play.gscript_timer=-1;
play.debug_mode=game.options[OPT_DEBUGMODE];
play.inv_top=0;
play.inv_numdisp=0;
play.obsolete_inv_numorder=0;
play.text_speed=15;
play.text_min_display_time_ms = 1000;
play.ignore_user_input_after_text_timeout_ms = 500;
play.ignore_user_input_until_time = 0;
play.lipsync_speed = 15;
play.close_mouth_speech_time = 10;
play.disable_antialiasing = 0;
play.rtint_enabled = false;
play.rtint_level = 0;
play.rtint_light = 0;
play.text_speed_modifier = 0;
play.text_align = SCALIGN_LEFT;
// Make the default alignment to the right with right-to-left text
if (game.options[OPT_RIGHTLEFTWRITE])
play.text_align = SCALIGN_RIGHT;
play.speech_bubble_width = 100;
play.bg_frame=0;
play.bg_frame_locked=0;
play.bg_anim_delay=0;
play.anim_background_speed = 0;
play.silent_midi = 0;
play.current_music_repeating = 0;
play.skip_until_char_stops = -1;
play.get_loc_name_last_time = -1;
play.get_loc_name_save_cursor = -1;
play.restore_cursor_mode_to = -1;
play.restore_cursor_image_to = -1;
play.ground_level_areas_disabled = 0;
play.next_screen_transition = -1;
play.temporarily_turned_off_character = -1;
play.inv_backwards_compatibility = 0;
play.gamma_adjustment = 100;
play.num_do_once_tokens = 0;
play.do_once_tokens = NULL;
play.music_queue_size = 0;
play.shakesc_length = 0;
play.wait_counter=0;
play.key_skip_wait = 0;
play.cur_music_number=-1;
play.music_repeat=1;
play.music_master_volume=100 + LegacyMusicMasterVolumeAdjustment;
play.digital_master_volume = 100;
play.screen_flipped=0;
play.offsets_locked=0;
play.cant_skip_speech = user_to_internal_skip_speech((SkipSpeechStyle)game.options[OPT_NOSKIPTEXT]);
play.sound_volume = 255;
play.speech_volume = 255;
play.normal_font = 0;
play.speech_font = 1;
play.speech_text_shadow = 16;
play.screen_tint = -1;
play.bad_parsed_word[0] = 0;
play.swap_portrait_side = 0;
play.swap_portrait_lastchar = -1;
play.swap_portrait_lastlastchar = -1;
play.in_conversation = 0;
play.skip_display = 3;
play.no_multiloop_repeat = 0;
play.in_cutscene = 0;
play.fast_forward = 0;
play.totalscore = game.totalscore;
play.roomscript_finished = 0;
play.no_textbg_when_voice = 0;
play.max_dialogoption_width = 180;
play.no_hicolor_fadein = 0;
play.bgspeech_game_speed = 0;
play.bgspeech_stay_on_display = 0;
play.unfactor_speech_from_textlength = 0;
play.mp3_loop_before_end = 70;
play.speech_music_drop = 60;
play.room_changes = 0;
play.check_interaction_only = 0;
play.replay_hotkey = 318; // Alt+R
play.dialog_options_x = 0;
play.dialog_options_y = 0;
play.min_dialogoption_width = 0;
play.disable_dialog_parser = 0;
play.ambient_sounds_persist = 0;
play.screen_is_faded_out = 0;
play.player_on_region = 0;
play.top_bar_backcolor = 8;
play.top_bar_textcolor = 16;
play.top_bar_bordercolor = 8;
play.top_bar_borderwidth = 1;
play.top_bar_ypos = 25;
play.top_bar_font = -1;
play.screenshot_width = 160;
play.screenshot_height = 100;
play.speech_text_align = SCALIGN_CENTRE;
play.auto_use_walkto_points = 1;
play.inventory_greys_out = 0;
play.skip_speech_specific_key = 0;
play.abort_key = 324; // Alt+X
play.fade_to_red = 0;
play.fade_to_green = 0;
play.fade_to_blue = 0;
play.show_single_dialog_option = 0;
play.keep_screen_during_instant_transition = 0;
play.read_dialog_option_colour = -1;
play.speech_portrait_placement = 0;
play.speech_portrait_x = 0;
play.speech_portrait_y = 0;
play.speech_display_post_time_ms = 0;
play.dialog_options_highlight_color = DIALOG_OPTIONS_HIGHLIGHT_COLOR_DEFAULT;
play.speech_in_post_state = false;
play.narrator_speech = game.playercharacter;
play.crossfading_out_channel = 0;
play.speech_textwindow_gui = game.options[OPT_TWCUSTOM];
if (play.speech_textwindow_gui == 0)
play.speech_textwindow_gui = -1;
strcpy(play.game_name, game.gamename);
play.lastParserEntry[0] = 0;
play.follow_change_room_timer = 150;
for (ee = 0; ee < MAX_BSCENE; ee++)
play.raw_modified[ee] = 0;
play.game_speed_modifier = 0;
if (debug_flags & DBG_DEBUGMODE)
play.debug_mode = 1;
gui_disabled_style = convert_gui_disabled_style(game.options[OPT_DISABLEOFF]);
memset(&play.walkable_areas_on[0],1,MAX_WALK_AREAS+1);
memset(&play.script_timers[0],0,MAX_TIMERS * sizeof(int));
memset(&play.default_audio_type_volumes[0], -1, MAX_AUDIO_TYPES * sizeof(int));
// CLNUP check this
// reset graphical script vars (they're still used by some games)
for (ee = 0; ee < MAXGLOBALVARS; ee++)
play.globalvars[ee] = 0;
for (ee = 0; ee < MAXGLOBALSTRINGS; ee++)
play.globalstrings[ee][0] = 0;
for (ee = 0; ee < MAX_SOUND_CHANNELS; ee++)
last_sound_played[ee] = -1;
if (!usetup.translation.IsEmpty())
init_translation (usetup.translation, "", true);
update_invorder();
displayed_room = -10;
currentcursor=0;
our_eip=-4;
mousey=100; // stop icon bar popping up
// We use same variable to read config and be used at runtime for now,
// so update it here with regards to game design option
usetup.RenderAtScreenRes =
(game.options[OPT_RENDERATSCREENRES] == kRenderAtScreenRes_UserDefined && usetup.RenderAtScreenRes) ||
game.options[OPT_RENDERATSCREENRES] == kRenderAtScreenRes_Enabled;
}
void engine_setup_scsystem_auxiliary()
{
if (usetup.override_script_os >= 0)
{
scsystem.os = usetup.override_script_os;
}
else
{
scsystem.os = platform->GetSystemOSID();
}
}
void engine_update_mp3_thread()
{
update_mp3_thread();
platform->Delay(50);
}
void engine_start_multithreaded_audio()
{
// PSP: Initialize the sound cache.
clear_sound_cache();
// Create sound update thread. This is a workaround for sound stuttering.
if (psp_audio_multithreaded)
{
if (!audioThread.CreateAndStart(engine_update_mp3_thread, true))
{
Debug::Printf(kDbgMsg_Init, "Failed to start audio thread, audio will be processed on the main thread");
psp_audio_multithreaded = 0;
}
else
{
Debug::Printf(kDbgMsg_Init, "Audio thread started");
}
}
else
{
Debug::Printf(kDbgMsg_Init, "Audio is processed on the main thread");
}
}
void engine_prepare_to_start_game()
{
Debug::Printf("Prepare to start game");
engine_setup_scsystem_auxiliary();
engine_start_multithreaded_audio();
#if defined(ANDROID_VERSION)
if (psp_load_latest_savegame)
selectLatestSavegame();
#endif
}
// TODO: move to test unit
Bitmap *test_allegro_bitmap;
IDriverDependantBitmap *test_allegro_ddb;
void allegro_bitmap_test_init()
{
test_allegro_bitmap = NULL;
// Switched the test off for now
//test_allegro_bitmap = AllegroBitmap::CreateBitmap(320,200,32);
}
bool engine_init_gamefile(const String &exe_path)
{
Debug::Printf(kDbgMsg_Init, "Initializing game data");
// Read game data location from the default config file.
// This is an optional setting that may instruct which game file to use as a primary asset library.
ConfigTree cfg;
String def_cfg_file = find_default_cfg_file(exe_path);
IniUtil::Read(def_cfg_file, cfg);
read_game_data_location(cfg);
// Deduce the game data file location and initialize assets library.
if (!engine_init_game_data())
return false;
// Pre-load game name and savegame folder names from data file
// TODO: research if that is possible to avoid this step and just
// read the full head game data at this point. This might require
// further changes of the order of initialization.
HError err = preload_game_data();
if (!err)
{
display_game_file_error(err);
return false;
}
return true;
}
void engine_read_config(const String &exe_path, ConfigTree &cfg)
{
// Read default configuration file
String def_cfg_file = find_default_cfg_file(exe_path);
IniUtil::Read(def_cfg_file, cfg);
// Disabled on Windows because people were afraid that this config could be mistakenly
// created by some installer and screw up their games. Until any kind of solution is found.
String user_global_cfg_file;
#if !defined (WINDOWS_VERSION)
// Read user global configuration file
user_global_cfg_file = find_user_global_cfg_file();
if (Path::ComparePaths(user_global_cfg_file, def_cfg_file) != 0)
IniUtil::Read(user_global_cfg_file, cfg);
#endif
// Read user configuration file
String user_cfg_file = find_user_cfg_file();
if (Path::ComparePaths(user_cfg_file, def_cfg_file) != 0 &&
Path::ComparePaths(user_cfg_file, user_global_cfg_file) != 0)
IniUtil::Read(user_cfg_file, cfg);
// Apply overriding options from mobile port settings
// TODO: normally, those should be instead stored in the same config file in a uniform way
// NOTE: the variable is historically called "ignore" but we use it in "override" meaning here
if (psp_ignore_acsetup_cfg_file)
override_config_ext(cfg);
// Apply overriding options from command line
// TODO: override config tree with all the command-line args.
if (disable_log_file)
INIwriteint(cfg, "misc", "log", 0);
else if (enable_log_file)
INIwriteint(cfg, "misc", "log", 1);
}
bool engine_do_config(const String &exe_path)
{
Debug::Printf(kDbgMsg_Init, "Setting up game configuration");
// Init default options
config_defaults();
ConfigTree cfg;
// Read configuration files
engine_read_config(exe_path, cfg);
// Set up game options from user config
apply_config(cfg);
// Fixup configuration if necessary
post_config();
// Test if need to run built-in setup program (where available)
return engine_check_run_setup(exe_path, cfg);
}
int initialize_engine(int argc,char*argv[])
{
if (engine_pre_init_callback) {
engine_pre_init_callback();
}
int res;
if (!engine_init_allegro())
return EXIT_NORMAL;
const String exe_path = argv[0];
if (!engine_init_gamefile(exe_path))
return EXIT_NORMAL;
if (!engine_do_config(exe_path))
return EXIT_NORMAL;
engine_setup_allegro();
engine_setup_window();
our_eip = -196;
engine_force_window();
our_eip = -195;
our_eip = -192;
engine_init_fonts();
our_eip = -188;
res = engine_init_mouse();
if (res != RETURN_CONTINUE) {
return res;
}
our_eip = -187;
res = engine_check_memory();
if (res != RETURN_CONTINUE) {
return res;
}
engine_init_directories();
engine_init_rooms();
our_eip = -186;
engine_init_speech();
our_eip = -185;
res = engine_init_music();
if (res != RETURN_CONTINUE) {
return res;
}
our_eip = -184;
engine_init_keyboard();
our_eip = -183;
engine_init_timer();
our_eip = -182;
engine_init_sound();
engine_init_debug();
our_eip = -10;
engine_init_exit_handler();
// [IKM] I seriously don't get it why do we need to delete warnings.log
// in the middle of procedure; some warnings may have already being
// written there at this point, no?
unlink("warnings.log");
engine_init_rand();
engine_init_pathfinder();
//engine_pre_init_gfx();
LOCK_VARIABLE(timerloop);
LOCK_FUNCTION(dj_timer_handler);
set_game_speed(40);
our_eip=-20;
//thisroom.allocall();
our_eip=-19;
res = engine_load_game_data();
if (res != RETURN_CONTINUE) {
return res;
}
res = engine_check_register_game();
if (res != RETURN_CONTINUE) {
return res;
}
engine_init_title();
our_eip = -189;
res = engine_check_disk_space();
if (res != RETURN_CONTINUE) {
return res;
}
// Make sure that at least one font was loaded in the process of loading
// the game data.
// TODO: Fold this check into engine_load_game_data()
res = engine_check_font_was_loaded();
if (res != RETURN_CONTINUE) {
return res;
}
our_eip = -179;
engine_init_modxm_player();
engine_init_resolution_settings(game.size);
// Attempt to initialize graphics mode
if (!engine_try_set_gfxmode_any(usetup.Screen))
return EXIT_NORMAL;
SetMultitasking(0);
// [ER] 2014-03-13
// Hide the system cursor via allegro
show_os_cursor(MOUSE_CURSOR_NONE);
engine_show_preload();
res = engine_init_sprites();
if (res != RETURN_CONTINUE) {
return res;
}
engine_init_game_settings();
engine_prepare_to_start_game();
allegro_bitmap_test_init();
initialize_start_and_play_game(override_start_room, loadSaveGameOnStartup);
quit("|bye!");
return 0;
}
bool engine_try_set_gfxmode_any(const ScreenSetup &setup)
{
engine_shutdown_gfxmode();
const Size init_desktop = get_desktop_size();
if (!graphics_mode_init_any(game.size, setup, ColorDepthOption(game.GetColorDepth())))
return false;
engine_post_gfxmode_setup(init_desktop);
return true;
}
bool engine_try_switch_windowed_gfxmode()
{
if (!gfxDriver || !gfxDriver->IsModeSet())
return false;
// Keep previous mode in case we need to revert back
DisplayMode old_dm = gfxDriver->GetDisplayMode();
GameFrameSetup old_frame = graphics_mode_get_render_frame();
// Release engine resources that depend on display mode
engine_pre_gfxmode_release();
Size init_desktop = get_desktop_size();
bool switch_to_windowed = !old_dm.Windowed;
ActiveDisplaySetting setting = graphics_mode_get_last_setting(switch_to_windowed);
DisplayMode last_opposite_mode = setting.Dm;
GameFrameSetup use_frame_setup = setting.FrameSetup;
// If there are saved parameters for given mode (fullscreen/windowed)
// then use them, if there are not, get default setup for the new mode.
bool res;
if (last_opposite_mode.IsValid())
{
res = graphics_mode_set_dm(last_opposite_mode);
}
else
{
// we need to clone from initial config, because not every parameter is set by graphics_mode_get_defaults()
DisplayModeSetup dm_setup = usetup.Screen.DisplayMode;
dm_setup.Windowed = !old_dm.Windowed;
graphics_mode_get_defaults(dm_setup.Windowed, dm_setup.ScreenSize, use_frame_setup);
res = graphics_mode_set_dm_any(game.size, dm_setup, old_dm.ColorDepth, use_frame_setup);
}
// Apply corresponding frame render method
if (res)
res = graphics_mode_set_render_frame(use_frame_setup);
if (!res)
{
// If failed, try switching back to previous gfx mode
res = graphics_mode_set_dm(old_dm) &&
graphics_mode_set_render_frame(old_frame);
}
if (res)
{
// If succeeded (with any case), update engine objects that rely on
// active display mode.
if (gfxDriver->GetDisplayMode().Windowed)
init_desktop = get_desktop_size();
engine_post_gfxmode_setup(init_desktop);
}
clear_input_buffer();
return res;
}
void engine_shutdown_gfxmode()
{
if (!gfxDriver)
return;
engine_pre_gfxsystem_shutdown();
graphics_mode_shutdown();
}
#ifdef WINDOWS_VERSION
// in ac_minidump
extern int CustomExceptionHandler (LPEXCEPTION_POINTERS exinfo);
extern EXCEPTION_RECORD excinfo;
extern int miniDumpResultCode;
#endif
// defined in main/main
extern char tempmsg[100];
extern char*printfworkingspace;
int initialize_engine_with_exception_handling(int argc,char*argv[])
{
#ifdef USE_CUSTOM_EXCEPTION_HANDLER
__try
{
Debug::Printf(kDbgMsg_Init, "Installing exception handler");
#endif
return initialize_engine(argc, argv);
#ifdef USE_CUSTOM_EXCEPTION_HANDLER
}
__except (CustomExceptionHandler ( GetExceptionInformation() ))
{
strcpy (tempmsg, "");
sprintf (printfworkingspace, "An exception 0x%X occurred in ACWIN.EXE at EIP = 0x%08X %s; program pointer is %+d, ACI version %s, gtags (%d,%d)\n\n"
"AGS cannot continue, this exception was fatal. Please note down the numbers above, remember what you were doing at the time and post the details on the AGS Technical Forum.\n\n%s\n\n"
"Most versions of Windows allow you to press Ctrl+C now to copy this entire message to the clipboard for easy reporting.\n\n%s (code %d)",
excinfo.ExceptionCode, excinfo.ExceptionAddress, tempmsg, our_eip, EngineVersion.LongString.GetCStr(), eip_guinum, eip_guiobj, get_cur_script(5),
(miniDumpResultCode == 0) ? "An error file CrashInfo.dmp has been created. You may be asked to upload this file when reporting this problem on the AGS Forums." :
"Unable to create an error dump file.", miniDumpResultCode);
MessageBoxA(win_get_window(), printfworkingspace, "Illegal exception", MB_ICONSTOP | MB_OK);
proper_exit = 1;
}
return EXIT_CRASH;
#endif
}
const char *get_engine_version() {
return EngineVersion.LongString.GetCStr();
}
void engine_set_pre_init_callback(t_engine_pre_init_callback callback) {
engine_pre_init_callback = callback;
}
|
/* poppler-document.cc: qt interface to poppler
* Copyright (C) 2005, 2008, 2009, 2012, 2013, Albert Astals Cid <aacid@kde.org>
* Copyright (C) 2005, Brad Hards <bradh@frogmouth.net>
* Copyright (C) 2008, 2011, Pino Toscano <pino@kde.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "poppler-qt4.h"
#include <QtCore/QString>
#include <QtCore/QDateTime>
#include "Object.h"
#include "Stream.h"
#include "Catalog.h"
#include "FileSpec.h"
#include "poppler-private.h"
#include "poppler-embeddedfile-private.h"
namespace Poppler
{
EmbeddedFileData::EmbeddedFileData(FileSpec *fs)
: filespec(fs)
{
}
EmbeddedFileData::~EmbeddedFileData()
{
delete filespec;
}
EmbFile *EmbeddedFileData::embFile() const
{
return filespec->isOk() ? filespec->getEmbeddedFile() : NULL;
}
EmbeddedFile::EmbeddedFile(EmbFile *embfile)
: m_embeddedFile(0)
{
assert(!"You must not use this private constructor!");
}
EmbeddedFile::EmbeddedFile(EmbeddedFileData &dd)
: m_embeddedFile(&dd)
{
}
EmbeddedFile::~EmbeddedFile()
{
delete m_embeddedFile;
}
QString EmbeddedFile::name() const
{
GooString *goo = m_embeddedFile->filespec->getFileName();
return goo ? UnicodeParsedString(goo) : QString();
}
QString EmbeddedFile::description() const
{
GooString *goo = m_embeddedFile->filespec->getDescription();
return goo ? UnicodeParsedString(goo) : QString();
}
int EmbeddedFile::size() const
{
return m_embeddedFile->embFile() ? m_embeddedFile->embFile()->size() : -1;
}
QDateTime EmbeddedFile::modDate() const
{
GooString *goo = m_embeddedFile->embFile() ? m_embeddedFile->embFile()->modDate() : NULL;
return goo ? convertDate(goo->getCString()) : QDateTime();
}
QDateTime EmbeddedFile::createDate() const
{
GooString *goo = m_embeddedFile->embFile() ? m_embeddedFile->embFile()->createDate() : NULL;
return goo ? convertDate(goo->getCString()) : QDateTime();
}
QByteArray EmbeddedFile::checksum() const
{
GooString *goo = m_embeddedFile->embFile() ? m_embeddedFile->embFile()->checksum() : NULL;
return goo ? QByteArray::fromRawData(goo->getCString(), goo->getLength()) : QByteArray();
}
QString EmbeddedFile::mimeType() const
{
GooString *goo = m_embeddedFile->embFile() ? m_embeddedFile->embFile()->mimeType() : NULL;
return goo ? QString(goo->getCString()) : QString();
}
QByteArray EmbeddedFile::data()
{
if (!isValid())
return QByteArray();
Stream *stream = m_embeddedFile->embFile() ? m_embeddedFile->embFile()->stream() : NULL;
if (!stream)
return QByteArray();
stream->reset();
int dataLen = 0;
QByteArray fileArray;
int i;
while ( (i = stream->getChar()) != EOF) {
fileArray[dataLen] = (char)i;
++dataLen;
}
fileArray.resize(dataLen);
return fileArray;
}
bool EmbeddedFile::isValid() const
{
return m_embeddedFile->filespec->isOk();
}
}
|
/*
restinio
*/
/*!
Test upgrade request.
*/
#include <catch2/catch.hpp>
#include <restinio/all.hpp>
#include <restinio/websocket/websocket.hpp>
#include <test/common/utest_logger.hpp>
#include <test/common/pub.hpp>
TEST_CASE( "Upgrade" , "[upgrade]" )
{
using traits_t =
restinio::traits_t<
restinio::asio_timer_manager_t,
utest_logger_t >;
using http_server_t = restinio::http_server_t< traits_t >;
namespace rws = restinio::websocket;
http_server_t http_server{
restinio::own_io_context(),
[]( auto & settings ){
settings
.port( utest_default_port() )
.address( "127.0.0.1" )
.request_handler(
[]( auto req ){
if( restinio::http_connection_header_t::upgrade == req->header().connection() )
{
try
{
namespace rws = restinio::websocket::basic;
auto ws =
rws::upgrade< traits_t >(
*req,
rws::activation_t::immediate,
[]( rws::ws_handle_t,
rws::message_handle_t ){} );
// TODO: write close-message.
ws->kill();
return restinio::request_accepted();
}
catch( const std::exception & ex )
{
std::cout << "UPGRADE FAILED: "
<< ex.what() << std::endl;
}
}
return restinio::request_rejected();
} );
} };
other_work_thread_for_server_t<http_server_t> other_thread{http_server};
other_thread.run();
std::string response;
const char * request_str =
"GET /chat HTTP/1.1\r\n"
"Host: 127.0.0.1\r\n"
"Upgrade: websocket\r\n"
"Connection: Upgrade\r\n"
"Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==\r\n"
"Sec-WebSocket-Protocol: chat\r\n"
"Sec-WebSocket-Version: 1\r\n"
"User-Agent: unit-test\r\n"
"\r\n";
REQUIRE_NOTHROW( response = do_request( request_str ) );
REQUIRE_THAT( response, Catch::StartsWith( "HTTP/1.1 101 Switching Protocols" ) );
REQUIRE_THAT( response, Catch::Contains( "Connection: Upgrade" ) );
REQUIRE_THAT( response, Catch::Contains( "Sec-WebSocket-Accept:" ) );
REQUIRE_THAT( response, Catch::Contains( "Upgrade: websocket" ) );
other_thread.stop_and_join();
}
|
/* Copyright (C) 2010 Ion Torrent Systems, Inc. All Rights Reserved */
/*
* BAMReader.cpp
* SamUtils
*
* Created by Michael Lyons on 12/9/10.
*
*
*/
#include <iostream>
#include <sstream>
#include <string>
#include <cassert>
#include <exception>
#include "Utils.h"
#include "BAMReader.h"
#include "sam_header.h"
using namespace std;
/* constructors */
BAMReader::BAMReader() {
Initialize();
}
BAMReader::BAMReader(const std::string& BAM_file) {
Initialize();
bam_file = BAM_file;
}
BAMReader::BAMReader(const std::string& BAM_file, const std::string& Index_File) {
Initialize();
bam_file = BAM_file;
index_file = Index_File;
}
/* initialization code */
void BAMReader::Initialize() {
file_p = NULL;
bam_index = NULL;
file_open = false;
bam_header = NULL;
//bam_header = bam_header_init();
}
// Destructor closes all open files:
BAMReader::~BAMReader() {
this->close();
}
/* functionality */
void BAMReader::open() {
_open();
}
// Open a bam file or bam/index pair:
void BAMReader::open(const std::string& BAM_file) {
//might as well grab it here
bam_file = BAM_file;
_open();
}
void BAMReader::open(const std::string& mode_stdin, const std::string& type_of_stdin) {
file_p = samopen(mode_stdin.c_str(), type_of_stdin.c_str(), 0);
if (file_p == NULL) {
std::cerr << "[BAMReader] file:"<< bam_file << " doesn't appear to exist" << std::endl;
file_open = false;
} else {
if (file_p->header) {
std::cout << "[BAMReader] file opened" << std::endl;
_init();
} else {
std::cerr << "[BAMReader] invalid input." << std::endl;
}
}
}
void BAMReader::_open() {
//std::cerr << "index_file.capacity(): " << index_file.capacity() << std::endl;
string extension = get_file_extension(bam_file);
//make lower case
std::transform(extension.begin(), extension.end(), extension.begin(), ::tolower);
if (extension == "bam") { //binary sam file (bam)
if (index_file.capacity() > 0) {
file_p = samopen(bam_file.c_str(), "rb", 0);
} else {
file_p = samopen(bam_file.c_str(), "rb", 0);
}
} else { //must be a sam file
if (index_file.capacity() > 0) {
file_p = samopen(bam_file.c_str(), "r", 0);
} else {
file_p = samopen(bam_file.c_str(), "r", 0);
}
}
//error handling
if (file_p == NULL) {
std::cerr << "[BAMReader] file:"<< bam_file << " doesn't appear to exist" << std::endl;
file_open = false;
} else {
std::cout << "[BAMReader] file opened" << std::endl;
_init();
}
}
void BAMReader::_init() {
file_open = true;
bam_header = file_p->header;
bam_header_object.init( bam_header );
for (int n_target = 0; n_target < bam_header->n_targets; n_target++) {
std::string isrt(bam_header->target_name[n_target]);
ref_list.push_back(isrt);
ref_lens.push_back(bam_header->target_len[n_target]);
}
}
void BAMReader::close() {
if (is_open()) {
samclose(file_p);
file_open = false;
}
}
// Was the open successful?
bool BAMReader::is_open() const {
return file_open;
}
BAMReader::operator bool() const {
return is_open();
}
//return number of references
int BAMReader::num_refs() const {
if (bam_header != NULL) {
return bam_header->n_targets;
} else {
return -1;
}
}
//return names strvec(string vector) of names
const strvec& BAMReader::refs() const {
return ref_list;
}
//return lenvec(vector of integers) of lengths of the references
const lenvec& BAMReader::lens() const {
return ref_lens;
}
/**** iterator implementations *****/
/* iterator gets */
BAMReader::iterator BAMReader::get_iterator() {
return BAMReader::iterator(file_p, ref_lens);
}
BAMReader::iterator BAMReader::get_iterator(int ref_index) {
return BAMReader::iterator(file_p, ref_index, bam_file, ref_lens);
}
BAMReader::iterator BAMReader::get_iterator(const std::string& ref_seq_name) {
//couldn't find ref if ref_index == -1
int ref_index = _findRef(ref_seq_name);
if (ref_index > -1) {
return BAMReader::iterator(file_p, ref_index, bam_file, ref_lens);
} else {
//possibly just want to exit here
return BAMReader::iterator(); //basically a null iterator. is_good == false, so you can't do any damage here
}
}
BAMReader::iterator BAMReader::get_iterator(int ref_index, coord_t begin, coord_t end) {
return BAMReader::iterator(file_p, ref_index, bam_file, begin, end, ref_lens);
}
BAMReader::iterator BAMReader::get_iterator(const std::string& ref_seq_name, coord_t begin, coord_t end) {
int ref_index = _findRef(ref_seq_name);
if (ref_index > -1) {
return BAMReader::iterator(file_p, ref_index, bam_file, begin,end, ref_lens);
} else {
return BAMReader::iterator(); //basically a null iterator. is_good == false, so you can't do any damage here
}
}
//gets a ref_index
int BAMReader::_findRef(const std::string& ref_seq_name) const {
int ref_index = -1;
int num_refs = file_p->header->n_targets;
for (int i = 0; i <= num_refs; i++) {
std::string ref(file_p->header->target_name[i]);
if (ref == ref_seq_name) {
ref_index = i;
return ref_index;
}
}
return ref_index;
}
/*iterator ctors/dtors and initialization*/
BAMReader::iterator::iterator() {
_init();
}
BAMReader::iterator::iterator(samfile_t* fp, lenvec& ref_lens) {
_init();
itr_file = fp;
tid_lens = ref_lens;
//std::cerr << "[BAMReader::iterator] itr_file->type: " << itr_file->type << std::endl;
if (itr_file->file->is_bin) {
is_bam = true;
} else {
is_bam = false;
is_good = false;
}
//cerr << "constructed: BAMReader::iterator::iterator(samfile_t* fp)" << endl;
//need to prime iteration to get first record ready:
next();
}
BAMReader::iterator::iterator(samfile_t* fp, int ref_index, const std::string& BAM_file, lenvec& ref_lens ) {
_init(fp, ref_index, BAM_file);
tid_lens = ref_lens;
}
BAMReader::iterator::iterator(samfile_t* fp, int ref_index, const std::string& BAM_file, coord_t begin, coord_t end, lenvec& ref_lens) {
_init(fp, ref_index, BAM_file);
assert(itr_file);
if (itr_file->file->is_bin) {
is_bam = true;
}
tid_lens = ref_lens;
is_good = _set_iter(ref_index, begin, end);
if (is_good) {
cerr << "[BAMReader] iter set: ref[ "<< itr_file->header->target_name[ref_index] << " ] start: "<< begin << " end: "<< end << endl;
} else {
cerr << "[BAMReader] iter not set" << endl;
}
}
void BAMReader::iterator::_init() {
itr_file = NULL;
itr_record = bam_init1();
is_good = false;
bam_iter = NULL; // 12-14 maybe set this to 0
}
void BAMReader::iterator::_init(samfile_t* fp, int ref_index, const std::string& BAM_file) {
_init();
itr_file = fp;
itr_index = bam_index_load(BAM_file.c_str());
if (itr_index != NULL) {
//index loaded
cerr << "[BAMReader] setting iter to ref_index: " << ref_index << ": "
<< itr_file->header->target_name[ref_index] << endl;
int beg = 0;
int end =itr_file->header->target_len[ref_index];
is_good = _set_iter(ref_index, beg, end);
if (is_good) {
cerr << "[BAMReader] iter set" << endl;
} else {
cerr << "[BAMReader] iter not set" << endl;
}
} else {
std::cerr << "[BAMReader] bam not indexed. indexing..." << std::endl;
_index(BAM_file);
itr_index = bam_index_load(BAM_file.c_str());
if (itr_index == NULL) {
std::cerr << "[BAMReader] something serioulsy wrong with indexing: "
<< BAM_file << "\nexiting..." << std::endl;
}
}
}
bool BAMReader::iterator::_set_iter(int tid, int beg, int end) {
if (itr_index == NULL) {
cerr << "[BAMReader] itr_index == null" << endl;
}
cerr << "[BAMReader] bam_iter_query(itr_index, "<< tid << "," << beg << "," << end << ");" << endl;;
bam_iter = bam_iter_query(itr_index, tid, beg, end);
if (bam_iter == NULL) {
cerr << "[BAMReader] bam_iter == NULL" << endl;
}
//prime the iterator to first position
int bytes = bam_iter_read(itr_file->x.bam, bam_iter, itr_record);
if (bytes < 0) {
return false;
} else if (bytes >= 0){
return true;
} else {
return false;
}
}
void BAMReader::iterator::_index(const std::string& BAM_file) {
bam_index_build(BAM_file.c_str());
//documentation says status is always 0 for now.
}
/* iteration */
void BAMReader::iterator::next() {
//if (bam_iter != NULL) {
if (is_bam) { //bamfile
int bytes = bam_iter_read(itr_file->x.bam, bam_iter, itr_record);
//std::cerr << "next() bytes: " << bytes << std::endl;
if (bytes == -1) {
is_good = false;
}
else {
is_good = true;
}
} //end bam_iter != NULL
else if (itr_file != NULL) { //must be sam or non-regional iteration
int bytes = samread(itr_file, itr_record);
//cerr << "bytes read: " << bytes << endl;
if (bytes == -1) {
is_good = false;
}
else {
is_good = true;
}
}
else {
is_good = false;
//return false;
}
}
BAMReader::iterator::~iterator() {
if(NULL != itr_record) {
bam_destroy1(itr_record);
itr_record = NULL;
}
}
/* BAMHeader implementations */
//ctor
BAMReader::BAMHeader::BAMHeader() {
//setup default read group
//maybe?
}
void BAMReader::BAMHeader::init(bam_header_t* header) {
header_ptr = header;
//not sure what this one does, Heng Li's code:
//if (header_ptr->l_text >= 3) {
// if (header_ptr->sdict == 0)
// header_ptr->sdict = sam_header_parse2( header_ptr->text );
//}
int num_entries = 0;
char type[2] = { 'R', 'G' };
char key_tag[2] = { 'I', 'D' };
char **rg_list = NULL;
rg_list = parse_read_group( rg_list, type, key_tag, &num_entries );
if ( rg_list == NULL ) {
/*
I hate doing this. If there's a better way to check
that the ID is or isn't there, I'd like to know
*/
cerr << "[BAMReader::BAMHeader] RG is missing required ID field. Ignoring read groups." << endl;
cerr << "lawlllll" << endl;
read_groups.push_back(BAMReader::BAMHeader::ReadGroup());
return;
} else {
for( int j = 0; j < num_entries; j++ ) {
read_groups.push_back(BAMReader::BAMHeader::ReadGroup());
}
}
//get flow order
key_tag[0] = 'F'; key_tag[1] = 'O';
rg_list = parse_read_group( rg_list, type, key_tag, &num_entries );
for (int j = 0; j < num_entries; j++ ) {
try {
read_groups[j].flow_order = rg_list[j];
read_groups[j].num_flows = read_groups[j].flow_order.length();
} catch ( std::exception& e) {
//defaults are in place for the ReadGroup
}
}
//get key sequence
key_tag[0] = 'K'; key_tag[1] = 'S';
num_entries = 0;
rg_list = parse_read_group( rg_list, type, key_tag, &num_entries );
for (int j = 0; j < num_entries; j++ ) {
try {
read_groups[j].key_sequence = rg_list[j];
read_groups[j].key_length = read_groups[j].key_sequence.length();
} catch ( std::exception& e) {
//defaults are in place for the ReadGroup
}
}
//get ID
key_tag[0] = 'I'; key_tag[1] = 'D';
rg_list = parse_read_group( rg_list, type, key_tag, &num_entries );
for (int j = 0; j < num_entries; j++ ) {
try {
read_groups[j].group_id = rg_list[j];
} catch ( std::exception& e) {
//defaults are in place for the ReadGroup
}
}
//get CN
key_tag[0] = 'C'; key_tag[1] = 'N';
rg_list = parse_read_group( rg_list, type, key_tag, &num_entries );
for (int j = 0; j < num_entries; j++ ) {
try {
read_groups[j].sequencing_center = rg_list[j];
} catch ( std::exception& e) {
//defaults are in place for the ReadGroup
}
}
//get DS
key_tag[0] = 'D'; key_tag[1] = 'S';
rg_list = parse_read_group( rg_list, type, key_tag, &num_entries );
for (int j = 0; j < num_entries; j++ ) {
try {
read_groups[j].description = rg_list[j];
} catch ( std::exception& e) {
//defaults are in place for the ReadGroup
}
}
//get DT
key_tag[0] = 'D'; key_tag[1] = 'T';
rg_list = parse_read_group( rg_list, type, key_tag, &num_entries );
for (int j = 0; j < num_entries; j++ ) {
try {
read_groups[j].date_time = rg_list[j];
} catch ( std::exception& e) {
//defaults are in place for the ReadGroup
}
}
//get LB
key_tag[0] = 'L'; key_tag[1] = 'B';
rg_list = parse_read_group( rg_list, type, key_tag, &num_entries );
for (int j = 0; j < num_entries; j++ ) {
try {
read_groups[j].library = rg_list[j];
} catch ( std::exception& e) {
//defaults are in place for the ReadGroup
}
}
//get PG
key_tag[0] = 'P'; key_tag[1] = 'G';
rg_list = parse_read_group( rg_list, type, key_tag, &num_entries );
for (int j = 0; j < num_entries; j++ ) {
try {
read_groups[j].program = rg_list[j];
} catch ( std::exception& e) {
//defaults are in place for the ReadGroup
}
}
//get PI
key_tag[0] = 'P'; key_tag[1] = 'I';
rg_list = parse_read_group( rg_list, type, key_tag, &num_entries );
for (int j = 0; j < num_entries; j++ ) {
try {
read_groups[j].predicted_median_insert_size = strtol(rg_list[j], NULL, 10);
} catch ( std::exception& e) {
//defaults are in place for the ReadGroup
}
}
//get PL
key_tag[0] = 'P'; key_tag[1] = 'L';
rg_list = parse_read_group( rg_list, type, key_tag, &num_entries );
for (int j = 0; j < num_entries; j++ ) {
try {
read_groups[j].sequencing_platform = rg_list[j];
} catch ( std::exception& e) {
//defaults are in place for the ReadGroup
}
}
//get PU
key_tag[0] = 'P'; key_tag[1] = 'U';
rg_list = parse_read_group( rg_list, type, key_tag, &num_entries );
for (int j = 0; j < num_entries; j++ ) {
try {
read_groups[j].platform_unit = rg_list[j];
} catch ( std::exception& e) {
//defaults are in place for the ReadGroup
}
}
//get SM
key_tag[0] = 'S'; key_tag[1] = 'M';
rg_list = parse_read_group( rg_list, type, key_tag, &num_entries );
for (int j = 0; j < num_entries; j++ ) {
try {
read_groups[j].sample_name = rg_list[j];
}catch ( std::exception& e) {
//defaults are in place for the ReadGroup
}
}
free(rg_list);
}
char** BAMReader::BAMHeader::parse_read_group( char** rg_list, char type[2], char key_tag[2], int* num_entries ) {
if (rg_list != NULL)
free(rg_list);
rg_list = sam_header2list( header_ptr->sdict, type, key_tag, num_entries );
return rg_list;
}
BAMReader::BAMHeader::ReadGroup& BAMReader::BAMHeader::get_read_group(unsigned int id) {
if (read_groups.size() >= id) {
return read_groups[ id ];
} else {
//FIXME: throw an exception instead
return default_group;
}
}
BAMReader::BAMHeader::ReadGroup::ReadGroup()
:
group_id("nothing meaningful"),
sequencing_center("Timbuktu" ),
flow_order("N"),
key_sequence("N"),
description("Default ReadGroup"),
date_time("1/1/12"),
library("not a library"),
num_flows(-1),
key_length(-1)
{
}
std::string BAMReader::BAMHeader::ReadGroup::to_string() {
std::ostringstream strm;
strm << get_read_group_id() <<" "<< get_sequencing_center() <<" "<< get_description() <<" "<< get_date_time()
<<" "<< get_flow_order() <<" "<< get_key_sequence() <<" "<< get_library() <<" "<< get_program()
<<" "<< get_predicted_median_insert_size() <<" "<< get_sequencing_platform() <<" "<< get_platform_unit()
<<" "<< get_sample_name();
return strm.str();
}
|
#include "smart_tuple.hpp"
#include "pa_function.hpp"
#include "lambda.hpp"
#include "struct_tuple.hpp"
#include "type_linker.hpp"
#include "constexpr_counter.hpp"
namespace named_requirements
{
namespace details
{
template<typename U, typename T1, typename T2>
concept same_as_either = std::is_same_v<T1, U> || std::is_same_v<T2, U>;
}
template<typename T>
concept CopyAssignable = std::is_copy_assignable_v<T>;
template<typename T>
concept CopyConstructible = std::is_copy_constructible_v<T>;
template<typename T, typename A>
concept CopyInsertable = requires(A m, T * p, T(*v)())
{
{ std::allocator_traits<A>::construct(m, p, v()) };
};
template<typename T>
concept MoveAssignable = std::is_move_assignable_v<T>;
template<typename T>
concept MoveConstructible = std::is_move_constructible_v<T>;
template<typename T, typename A>
concept MoveInsertable = requires (A m, T * p, T(*v)())
{
{ std::allocator_traits<A>::construct(m, p, v()) };
};
template<typename T>
concept DefaultConstructible = std::is_default_constructible_v<T>;
template<typename T>
concept Destructible = std::is_destructible_v<T>;
template<typename T>
concept EqualityComparable = std::equality_comparable<T>;
template<typename T, typename U>
concept EqualityComparableWith = std::equality_comparable_with<T, U>;
template<typename T, typename A>
concept Erasable = requires(A m, T * p)
{
{ std::allocator_traits<A>::destroy(m, p) };
};
template<typename T>
concept TriviallyCopyable = std::is_trivially_copyable<T>::value;
template<typename T>
concept TrivialType = std::is_trivial<T>::value;
template<typename T>
concept StandardLayoutType = std::is_standard_layout<T>::value;
template<typename T>
concept PODType = std::is_pod<T>::value;
template<typename T>
concept Swappable = std::swappable<T>;
template<typename T, typename U>
concept SwappableWith = std::swappable_with<T, U>;
template<typename T>
concept NullablePointer = requires(T p, T q, std::nullptr_t np)
{
requires EqualityComparable<T>;
requires DefaultConstructible<T>;
requires CopyConstructible<T>;
requires CopyAssignable<T>;
requires Destructible<T>;
{ p = np } -> std::same_as<T&>;
{ p != q } -> std::convertible_to<bool>;
{ p == np } -> std::convertible_to<bool>;
{ np == p } -> std::convertible_to<bool>;
{ p != np } -> std::convertible_to<bool>;
{ np != p } -> std::convertible_to<bool>;
};
template<typename It>
concept LegacyIterator = requires(It r)
{
requires CopyConstructible<It>;
requires CopyAssignable<It>;
requires Destructible<It>;
requires Swappable<It>;
typename std::iterator_traits<It>::value_type;
typename std::iterator_traits<It>::difference_type;
typename std::iterator_traits<It>::reference;
typename std::iterator_traits<It>::pointer;
typename std::iterator_traits<It>::iterator_category;
{ *r };
{ ++r } -> std::same_as<It&>;
};
template<typename It>
concept LegacyInputIterator = requires(It i, It j)
{
requires LegacyIterator<It>;
requires EqualityComparable<It>;
{ i != j } -> std::convertible_to<bool>;
{ *i } -> std::same_as<typename std::iterator_traits<It>::reference>;
{ ++i } -> std::same_as<It&>;
{ *i++ } -> std::convertible_to<typename std::iterator_traits<It>::value_type>;
};
template<typename X>
concept LegacyOutputIterator = requires(X r, typename std::iterator_traits<X>::value_type o)
{
requires LegacyIterator<X>;
requires std::is_class_v<X> || std::is_pointer_v<X>;
{ *r = o };
{ ++r } -> std::same_as<X&>;
{ r++ } -> std::convertible_to<const X&>;
{ *r++ = o };
};
template<typename It>
concept LegacyForwardIterator = requires(It i)
{
requires !LegacyOutputIterator<It>
|| (LegacyOutputIterator<It> && std::same_as<typename std::iterator_traits<It>::value_type&, typename std::iterator_traits<It>::reference>);
{ i++ } -> std::same_as<It>;
{ *i++ } -> std::same_as<typename std::iterator_traits<It>::reference>;
};
template<typename It>
concept LegacyBidirectionalIterator = requires(It a)
{
requires LegacyForwardIterator<It>;
{ --a } -> std::same_as<It&>;
{ a-- } -> std::convertible_to<const It&>;
{ *a-- } -> std::same_as<typename std::iterator_traits<It>::reference>;
};
template<typename It>
concept LegacyContiguousIterator = requires(It a, std::ptrdiff_t n)
{
requires LegacyIterator<It>;
{ a + n } -> std::same_as<It>;
{ *(a + n) } -> std::same_as<typename std::iterator_traits<It>::reference>;
};
template<typename It>
concept LegacyRandomAccessIterator = requires(It i, It a, It b, It & r, typename std::iterator_traits<It>::difference_type n)
{
requires LegacyBidirectionalIterator<It>;
{ r += n } -> std::same_as<It&>;
{ a + n } -> std::same_as<It>;
{ n + a } -> std::same_as<It>;
{ r -= n } -> std::same_as<It&>;
{ i - n } -> std::same_as<It>;
{ b - a } -> std::same_as<typename std::iterator_traits<It>::difference_type>;
{ i[n] } -> std::convertible_to<typename std::iterator_traits<It>::reference>;
{ a < b } -> std::convertible_to<bool>;
{ a > b } -> std::convertible_to<bool>;
{ a >= b } -> std::convertible_to<bool>;
{ a <= b } -> std::convertible_to<bool>;
};
template<typename A>
concept Allocator = requires(A a, A a1, typename A::value_type * p, const typename A::value_type * cp,
typename A::value_type r, typename std::allocator_traits<A>::size_type n)
{
{ *p } -> std::same_as<typename A::value_type&>;
{ *cp } -> std::same_as<const typename A::value_type&>;
{ std::pointer_traits<typename A::value_type*>::pointer_to(r) };
{ a.allocate(n) } -> std::same_as<typename A::value_type*>;
{ a.deallocate(p, n) };
{ a == a1 } -> std::same_as<bool>;
{ a != a1 } -> std::same_as<bool>;
{ A(a) } noexcept;
{ A(std::move(a)) } noexcept;
};
template<typename It>
concept ConstexprIterator = requires(It i)
{
std::is_constant_evaluated();
};
template<typename C>
concept Container = requires(C a, C b, C && rv)
{
requires DefaultConstructible<C>;
requires CopyConstructible<C>;
requires EqualityComparable<C>;
requires Swappable<C>;
requires CopyInsertable<typename C::value_type, std::allocator<typename C::value_type>>;
requires Destructible<typename C::value_type>;
requires Erasable<typename C::value_type, std::allocator<typename C::value_type>>;
typename C::reference;
typename C::const_reference;
typename C::const_iterator;
requires LegacyForwardIterator<typename C::iterator>&& std::convertible_to<typename C::iterator, typename C::const_iterator>;
requires std::signed_integral<typename C::difference_type>;
requires std::unsigned_integral<typename C::size_type>;
{ C() } -> std::same_as<C>;
{ C(a) } -> std::same_as<C>;
{ C(rv) } -> std::same_as<C>;
{ a = b } -> std::same_as<C&>;
{ a = rv } -> std::same_as<C&>;
{ a.~C() } -> std::same_as<void>;
{ a.begin() } -> details::same_as_either<typename C::iterator, typename C::const_iterator>;
{ a.end() } -> details::same_as_either<typename C::iterator, typename C::const_iterator>;
{ a.cbegin() } -> std::same_as<typename C::const_iterator>;
{ a.cend() } -> std::same_as<typename C::const_iterator>;
{ a == b } -> std::convertible_to<bool>;
{ a != b } -> std::convertible_to<bool>;
{ a.swap(b) } -> std::same_as<void>;
{ std::swap(a, b) } -> std::same_as<void>;
{ a.size() } -> std::same_as<typename C::size_type>;
{ a.max_size() } -> std::same_as<typename C::size_type>;
{ a.empty() } -> std::convertible_to<bool>;
};
template<typename C>
concept ReversibleContainer = requires(C a)
{
requires LegacyBidirectionalIterator<typename C::iterator>;
requires LegacyBidirectionalIterator<typename C::const_iterator>;
requires std::same_as<typename C::reverse_iterator, std::reverse_iterator<typename C::iterator>>;
requires std::same_as<typename C::const_reverse_iterator, std::reverse_iterator<typename C::const_iterator>>;
{ a.rbegin() } -> std::same_as<typename C::reverse_iterator>;
{ a.rend() } -> std::same_as<typename C::reverse_iterator>;
{ a.crbegin() } -> std::same_as<typename C::const_reverse_iterator>;
{ a.crend() } -> std::same_as<typename C::const_reverse_iterator>;
};
template<typename X, typename A = typename X::allocator_type>
concept AllocatorAwareContainer = requires(X a, X b, X & t, X && rv, A m)
{
requires std::same_as<typename A::value_type, typename X::value_type>;
requires DefaultConstructible<A>;
requires CopyInsertable<typename X::value_type, X>;
requires MoveInsertable<typename X::value_type, X>;
{ a.get_allocator() } -> std::same_as<A>;
{ X() } -> std::same_as<X>;
{ X(m) } -> std::same_as<X>;
{ X(t, m) } -> std::same_as<X>;
{ X(rv) } -> std::same_as<X>;
{ A(static_cast<A&&>(m)) } noexcept -> std::same_as<A>;
{ X(rv, m) } -> std::same_as<X>;
{ a = t } -> std::same_as<X&>;
{ a = rv } -> std::same_as<X&>;
{ a.swap(b) } -> std::same_as<void>;
};
}
struct A
{
private:
A() {};
A(A&&) {};
A(const A&) {};
};
#include <vector>
#include <intrin.h>
class bowl
{
public:
using value_type = int;
using reference = value_type&;
using const_reference = const value_type&;
using pointer = value_type*;
using const_pointer = const value_type*;
using size_type = std::size_t;
using difference_type = std::ptrdiff_t;
bowl() {
add_bucket();
}
bowl(const bowl& other) {
*this = other;
}
bowl(bowl&& other) {
*this = std::move(other);
}
bowl& operator=(const bowl& other) {
m_Buckets = std::move(other.m_Buckets);
m_Size = std::move(other.m_Size);
m_Index = std::move(other.m_Index);
return *this;
}
bowl& operator=(bowl&& other) {
m_Buckets = std::move(other.m_Buckets);
m_Size = std::move(other.m_Size);
m_Index = std::move(other.m_Index);
other.m_Buckets = nullptr;
other.m_Size = 0;
other.m_Index = 0;
return *this;
}
void add_bucket() {
bucket** _buckets = m_Buckets; // Backup of array
m_Buckets = new bucket * [++m_Size]; // New array
for (size_type i = 0; i < m_Size - 1; i++)
m_Buckets[i] = _buckets[i]; // Move buckets over
m_Buckets[m_Size - 1] = new bucket; // Add new bucket
delete[] _buckets; // Delete old array of buckets
}
void clean() {
if (m_Buckets) { // If buckets
for (size_type i = 0; i < m_Size; i++)
delete m_Buckets[i]; // Delete buckets
delete[] m_Buckets; // And delete array
}
}
size_type size() const {
size_type _size = 0;
for (size_type i = 0; i < m_Size; i++)
_size += m_Buckets[i]->size();
return _size;
}
size_type max_size() const {
return static_cast<size_type>(-1);
}
bool empty() const {
return size() == 0;
}
void swap(bowl& other) {
std::swap(other.m_Buckets, m_Buckets);
std::swap(other.m_Index, m_Index);
std::swap(other.m_Size, m_Size);
}
class bucket;
template<bool Const>
class iterator_type {
public:
using type = std::conditional_t<Const, bowl::bucket* const*, bowl::bucket**>;
using value_type = typename bowl::value_type;
using reference = std::conditional_t<Const, bowl::reference, bowl::const_reference>;
using difference_type = std::ptrdiff_t;
using pointer = std::conditional_t<Const, bowl::pointer, bowl::const_pointer>;
iterator_type() {}
iterator_type(type a, size_type b, size_type i) : m_Buckets(a), m_Bucket(b), m_Index(i) {}
iterator_type(const iterator_type<false>& other) : m_Buckets(other.m_Buckets), m_Bucket(other.m_Bucket), m_Index(other.m_Index) {}
iterator_type& operator++() {
m_Index++;
if (m_Index >= (m_Buckets[m_Bucket])->size())
m_Bucket++, m_Index = 0;
return *this;
}
iterator_type operator++(int) {
iterator_type _backup = *this;
m_Index++;
if (m_Index >= (m_Buckets[m_Bucket])->size())
m_Bucket++, m_Index = 0;
return _backup;
}
reference operator*() { return (m_Buckets[m_Bucket])->operator[](m_Index); }
bool operator==(const iterator_type& other) const { return other.m_Bucket == m_Bucket && other.m_Index == m_Index; }
bool operator!=(const iterator_type& other) const { return !(other == *this); }
private:
type m_Buckets = nullptr;
size_type m_Index = 0;
size_type m_Bucket = 0;
friend class bowl;
};
using iterator = iterator_type<false>;
using const_iterator = iterator_type<true>;
class bucket {
friend class bowl;
friend class bowl::iterator;
friend class bowl::const_iterator;
value_type* m_Data[64];
size_type m_Indices = 0xFFFFFFFFFFFFFFFF;
~bucket() {
const auto _inverted = ~m_Indices;
for (size_type i = 0; i < 64; i++)
if (_inverted & (1ULL << i))
delete m_Data[i];
}
void insert(value_type&& value) {
const size_type _index = first_available_index();
m_Indices &= ~(1ULL << _index);
m_Data[_index] = new value_type{ std::move(value) };
}
void erase(size_type index) {
m_Indices |= 1ULL << index;
delete m_Data[index];
}
value_type& operator[](size_type index) {
const size_type _index = nth_index(index);
return *m_Data[_index];
}
constexpr size_type size() const { return 64ull - std::popcount(m_Indices); }
constexpr bool full() const { return std::popcount(m_Indices) == 0; }
constexpr bool empty() const { return std::popcount(m_Indices) == 64; }
constexpr size_type first_available_index() const { return std::countr_zero(m_Indices); }
size_type nth_index(size_type n) const { return std::countr_zero(_pdep_u64(1ULL << n, ~m_Indices)); }
} **m_Buckets = nullptr;
iterator begin() { return { m_Buckets, 0ull, 0ull }; }
iterator end() { return { m_Buckets, m_Size, 0ull }; }
const_iterator begin() const { return { m_Buckets, 0ull, 0ull }; }
const_iterator end() const { return { m_Buckets, m_Size, 0ull }; }
const_iterator cbegin() const { return { m_Buckets, 0ull, 0ull }; }
const_iterator cend() const { return { m_Buckets, m_Size, 0ull }; }
void insert(value_type&& value) {
m_Buckets[m_Index]->insert(std::move(value));
while (m_Buckets[m_Index]->full())
if (++m_Index >= m_Size)
add_bucket();
}
void erase(const iterator& it) {
(m_Buckets[it.m_Bucket])->erase(it.m_Index);
m_Index = it.m_Bucket;
}
bool operator==(const bowl& other) const {
if (size() != other.size()) return false;
for (const_iterator _b1 = begin(), _b2 = other.begin(); _b1 != end(); ++_b1, ++_b2)
if (*_b1 != *_b2) return false;
return true;
}
bool operator !=(const bowl& other) const {
return !(other == *this);
}
size_type m_Index = 0;
size_type m_Size = 0;
};
void PositiveDivisors(int n, std::vector<int>& divs)
{
divs.push_back(1);
for (int i = 2; i < n / 2 + 1; i++)
if (n % i == 0) divs.push_back(i);
divs.push_back(n);
}
#include <array>
/* y n
x + + + + + + + +
+ 0 1 1 1 1 1 1 \
+ - 0 1 1 1 1 1 |
+ - - 0 1 1 1 1 |
n + - - - 0 1 1 1 }- k=(n-1)*n/2
+ - - - - 0 1 1 | i=max(x,y)*n+min(x,y)
+ - - - - - 0 1 |
+ - - - - - - 0 /
*/
class graph_data {
public:
using size_type = std::size_t;
using value_type = bool;
void resize(std::size_t n) {
const std::size_t _k = std::ceil(0.125 * (n - 1) * n / 2); // Bytes
if (_k < n) {
uint8_t* _newData = new uint8_t[_k];
for (size_type i = 0; i < m_Size; i++)
_newData[i] = m_Data[i];
}
}
size_type size() const { return m_Size; }
private:
std::pair<size_type, size_type> to_pos(size_type index) {
return { index / size(), index % size() };
}
size_type to_index(const std::pair<size_type, size_type>& index) {
return std::max(index.first, index.second) * size() + std::min(index.first, index.second);
}
size_t m_Size;
uint8_t* m_Data;
};
#include <ranges>
namespace g1
{
// 1 2 3 4 5
// 1 . . . . .
// 2 . . . . .
// 3 . . . . .
// 4 . . . . .
// 5 . . . . .
template<class Ty>
class graph {
public:
using value_type = Ty;
using size_type = std::size_t;
class vertex {
public:
template<std::constructible_from<Ty> ...Args>
vertex(graph& graph, Args&&...args)
: graph(graph), m_Value(new value_type{ std::forward<Args>(args)... }) {}
vertex(vertex&& other)
: graph(other.graph), m_Value(other.value()) {
other.m_Value = nullptr;
}
vertex(const vertex& other)
: graph(other.graph), m_Value(new value_type{ *other.m_Value }) {
}
~vertex() { delete m_Value; }
void connect(size_type other) { graph.connect(graph.index_of(*this), other); }
void connect(vertex& other) { graph.connect(*this, other); }
void disconnect(size_type other) { graph.disconnect(graph.index_of(*this), other); }
void disconnect(vertex& other) { graph.disconnect(*this, other); }
bool adjacent(size_type index) const { return graph.adjacent(graph.index_of(*this), index); }
auto neighbourhood() const {
using namespace std::views;
return iota(0ull, graph.size())
| filter([&](size_t index) { return adjacent(index); })
| transform([&](size_type index) { return graph.m_Vertices[index]; });
}
size_type degree() const { return graph.degree(*this); };
value_type& value() { return *m_Value; }
graph& graph;
private:
value_type* m_Value = nullptr;
friend class graph;
};
void disconnect(size_type a, size_type b) { m_BitMap.at(a * size() + b) = false; m_BitMap.at(a * size() + b) = false; }
void disconnect(vertex& a, vertex& b) { connect(index_of(a), index_of(b)); }
void connect(size_type a, size_type b) { m_BitMap.at(a * size() + b) = true; m_BitMap.at(a + b * size()) = true; }
void connect(vertex& a, vertex& b) { connect(index_of(a), index_of(b)); }
bool adjacent(size_type a, size_type b) const { return m_BitMap.at(a * size() + b); }
bool adjacent(vertex& a, vertex& b) const { return adjacent(index_of(a), index_of(b)); }
size_type degree(size_type a) const {
size_type _degree = 0;
for (size_type i = 0; i < size(); i++)
if (i != a && m_BitMap.at(a * size() + i)) _degree++;
return _degree;
}
size_type degree(vertex const& a) const { return degree(index_of(a)); }
size_type index_of(const vertex& a) const { return std::distance(m_Vertices.data(), &a); }
size_type size() const { return m_Vertices.size(); }
std::vector<vertex> const& vertices() const { return m_Vertices; }
template<class ...Args>
vertex& emplace(Args&&...args) { return m_Vertices.emplace_back(*this, std::forward<Args>(args)...); }
private:
std::vector<vertex> m_Vertices;
std::vector<bool> m_BitMap;
friend class vertex;
};
}
#include <bitset>
template<class Ty, std::size_t N>
class graph {
public:
using value_type = Ty;
using size_type = std::size_t;
consteval static auto createEdges(auto es) {
std::bitset<N* N> edges;
for (auto& i : es)
edges.set(i.first * N + i.second), edges.set(i.first + i.second * N);
return edges;
}
consteval graph(const Ty(&vs)[N], std::initializer_list<std::pair<size_type, size_type>> es)
: vertices(), edges(createEdges(es)) {
for (size_type i = 0; i < N; i++)
vertices[i] = vs[i];
}
constexpr graph(std::array<Ty, N> vs)
: vertices(vs), edges()
{}
std::bitset<N* N> edges;
std::array<Ty, N> vertices;
};
template<class Ty, size_t N>
graph(std::array<Ty, N>)->graph<Ty, N>;
namespace woof {
struct IpAddress {
template<size_t N>
consteval IpAddress(const char(&val)[N]) : bytes() {
size_t byte = 0;
int curByte = 0;
for (auto& i : val) {
if (i == '\0')
break;
if (i == '.' || i == '\'') {
bytes[byte] = curByte;
curByte = 0; ++byte;
continue;
}
curByte = curByte * 10 + (i - '0');
if (curByte > 255) throw std::overflow_error("Byte overflow!");
}
bytes[byte] = curByte;
}
uint8_t bytes[4];
};
template<char... Cs>
consteval IpAddress operator""_ipv4() { return IpAddress{ { Cs... } }; }
template<std::size_t Size>
struct name_object {
static constexpr std::size_t size = Size - 1;
char data[Size - 1]{};
constexpr explicit(false) name_object(const char(&str)[Size]) {
std::copy_n(str, Size - 1, data);
}
constexpr explicit(false) operator std::string_view() const {
return { data, Size - 1 };
}
};
template<std::size_t Size>
name_object(const char(&)[Size])->name_object<Size>;
template<name_object Name, class T>
struct arg {
using type = T;
constexpr static std::string_view name = Name;
constexpr arg()
: value() {}
constexpr arg(T&& arg)
: value(std::move(arg)) {}
constexpr arg(const T& arg)
: value(arg) {}
constexpr arg(const arg& other)
: value(other.value) {}
constexpr arg(arg&& other)
: value(std::move(other.value)) {}
T value;
};
template<name_object Name>
struct arg<Name, void> {
using type = void;
constexpr static std::string_view name = Name;
constexpr arg() {}
template<class Ty>
constexpr arg<Name, std::decay_t<Ty>> operator=(Ty&& arg) const {
return { std::forward<Ty>(arg) };
}
template<class Ty>
constexpr explicit(false) operator arg<Name, Ty>() const { return { }; }
};
//template<name_object Name>
//consteval arg<Name, void> operator""_t() { return {}; }
template<name_object Name, class Arg, class ...Args>
struct type_finder {
using type = std::conditional_t<Arg::name == Name, typename Arg::type,
typename type_finder<Name, Args...>::type>;
};
template<name_object Name, class Arg>
struct type_finder<Name, Arg> {
using type = std::conditional_t<Arg::name == Name, typename Arg::type, void>;
};
template<class ...Args>
struct object {
std::tuple<Args...> data;
constexpr object(Args&&...args)
: data(args...) {}
template<name_object Name>
constexpr auto& get() const {
return std::get<arg<Name, typename type_finder<Name, Args...>::type>>(data).value;
}
template<name_object Name>
constexpr auto& operator[](arg<Name, void>) const {
return std::get<arg<Name, typename type_finder<Name, Args...>::type>>(data).value;
}
template<name_object Name>
constexpr auto& get() {
return std::get<arg<Name, typename type_finder<Name, Args...>::type>>(data).value;
}
template<name_object Name>
constexpr auto& operator[](arg<Name, void>) {
return std::get<arg<Name, typename type_finder<Name, Args...>::type>>(data).value;
}
};
struct Email {
std::string email;
Email(auto e) : email(e) {}
void operator=(auto e) { email = e; }
};
}
//namespace aeofamef
//{
//#include "meta_struct.hpp"
//
// using namespace kaixo;
//
// using has_carrot = meta_struct<
// field<"carrot", int&>
// >;
//
// using has_soup = meta_struct<
// field<"soup", float&>
// >;
//
// constexpr auto& get_carrot(has_carrot t) { return t.get<"carrot">(); }
// constexpr auto& get_soup(has_soup t) { return t.get<"soup">(); }
//
// using has_carrot_soup = meta_struct<
// field<"carrot", int&>,
// field<"soup", float&>
// >;
//
// constexpr auto get_carrot_plus_soup(has_carrot_soup t) { return t.get<"carrot">() + t.get<"soup">(); }
// constexpr auto add_carrot_to_soup(has_carrot_soup t) { t.get<"soup">() += t.get<"carrot">(); }
//
//
//
// using has_get = meta_struct<
// virtual_function<"get", double()>
// >;
//
// constexpr auto call_get(has_get t) { return t.run<"get">(); }
//
// using carrot_soup_bowl = meta_struct <
// field<"carrot", int, required>,
// field<"soup", float, required>,
// field < "bowl", double, [](auto& self) { return self.get<"soup">() + 100; } > ,
// function < "addToBowl", [](auto& self, double amount) { self.get<"bowl">() += amount; } > ,
// function < "get", [](auto& self) -> auto& { return self.get<"bowl">(); } >
// > ;
//
// using carrot_has_get = meta_struct<
// field<"carrot", int>,
// virtual_function<"get", double()>
// >;
//
// constexpr auto carrot_plus_call_get(carrot_has_get t) { return t.run<"get">() + t.get<"carrot">(); }
//
// using has_add_to_bowl = meta_struct<
// virtual_function<"addToBowl", void(double)>
// >;
//
// constexpr auto add_2_to_bowl(has_add_to_bowl t) { return t.run<"addToBowl">(2); }
//
//
// using transform = meta_struct <
// field<"value", double>,
// virtual_function<"transform", double(double)>
// >;
//
// using my_transform = meta_struct <
// field<"mult", double>,
// function < "transform", [](auto& self, double v) { return v * self.get<"mult">(); } >
// > ;
//
// constexpr auto transform_value(transform t) {
// return t.run<"transform">((double)t.get<"value">());
// }
//}
namespace kaixo
{
template<class ...Args>
struct constructor {};
template<class Ty, class ...Constructors>
concept link_constructors = kaixo::link_types<kaixo::type_group<Constructors...>, kaixo::type_group<Ty>>;
template<class Ty>
struct try_parse {
static inline Ty parse(std::string_view& args);
};
template<class Ty> requires (std::floating_point<Ty> || std::integral<Ty>)
struct try_parse<Ty> {
static inline Ty parse(std::string_view& args) {
args = args.substr(args.find_first_not_of(" \t"));
std::size_t length;
Ty val = 0;
auto res = std::from_chars(args.data(), args.data() + args.size(), val);
if (res.ec == std::errc()) {
args = { res.ptr, args.size() - (res.ptr - args.data()) };
return val;
}
else
throw nullptr;
}
};
template<class, class > struct decompose_constructor;
template<class Ty, class ...Args>
struct decompose_constructor<Ty, constructor<Args...>> {
static inline bool try_construct(Ty** assign, std::string_view& args) {
try {
*assign = new Ty{ try_parse<Args>::parse(args)... };
return true;
}
catch (...) { return false; }
}
};
template<class, class> struct decompose_type_group;
template<class Ty, class ...Cs>
struct decompose_type_group<Ty, type_group<Cs...>> {
static inline Ty try_construct(std::string_view args) {
Ty* val = nullptr;
(decompose_constructor<Ty, Cs>::try_construct(&val, args) || ...);
if (val == nullptr) throw nullptr;
Ty a = *val;
delete val;
return a;
}
};
template<class> struct decompose_tuple;
template<class ...Tys>
struct decompose_tuple<std::tuple<Tys...>> {
using type = constructor<Tys...>;
};
template<class Ty>
Ty construct(const std::string& args) {
static_assert(link_constructors<Ty, decompose_tuple<struct_info<Ty>::field_types>::type>);
return decompose_type_group<Ty, linked_types<Ty>>::try_construct(args);
}
}
using namespace kaixo;
int Add(int a, int b) { return a + b; }
struct Object { int Add(int a, int b) { return a + b; } };
struct Functor
{
int someValue;
int operator()(int a, int b) { return a + b + someValue; }
};
void pa_function_example()
{
// Functor
pa_function<int(int, int)> functor = Functor{ 5 };
pa_function<int(int)> functor2 = functor(1);
int functorResult = functor2(3);
assert(functorResult == 9);
// Lambda
pa_function<int(int, int)> lambda = [](int a, int b) { return a + b; };
pa_function<int(int)> lambda2 = lambda(1);
int lambdaResult = lambda2(3);
assert(lambdaResult == 4);
// Function Pointer
pa_function<int(int, int)> funPtr = Add;
pa_function<int(int)> funPtr2 = funPtr(1);
int funPtrResult = funPtr2(3);
assert(funPtrResult == 4);
// Member function
Object obj;
pa_function<int(int, int)> memberFun = { &Object::Add, obj };
pa_function<int(int)> memberFun2 = memberFun(1);
int memberFunResult = memberFun2(3);
assert(memberFunResult == 4);
}
void smart_tuple_example()
{
smart_tuple<int, float, double> thing{ 1, 0.5f, 4. };
// By value
int val1 = thing[0];
float val2 = thing[1];
double val3 = thing[2];
assert(val1 == 1);
assert(val2 == 0.5f);
assert(val3 == 4.);
// By reference
int& val4 = thing[0];
val4++;
int val5 = thing[0];
assert(val4 == val5);
}
void lambda_example()
{
//int a = 0;
//double b = 1;
//
//lambda t = [=](int c) -> int { return a + b + c; };
//
//std::cout << typeid(decltype(t)).name() << std::endl;
//
//t.get<0>() += 10;
//t.get<1>() += 10;
//
//std::cout << t(1) << std::endl;
}
class Thing
{
public:
Thing(int a, short b, long long c, double d, float e) {}
};
struct Apple {
short q = 1;
long long d = 2;
int a = 3;
double b = 4;
float c = 5;
};
void struct_tuple_example()
{
//Apple apple;
//
//constexpr size_t fields = struct_info<Apple>::fields;
//using tuple = struct_info<Apple>::field_types;
//std::cout << fields << std::endl;
//std::cout << typeid(tuple).name() << std::endl;
//
//tuple _tuple = as_tuple(apple);
//std::cout << typeid(decltype(_tuple)).name() << std::endl;
//std::cout << std::get<0>(_tuple) << std::endl;
//std::cout << std::get<1>(_tuple) << std::endl;
//std::cout << std::get<2>(_tuple) << std::endl;
//std::cout << std::get<3>(_tuple) << std::endl;
//std::cout << std::get<4>(_tuple) << std::endl;
//
//constexpr size_t args = constructor_info<Thing>::args;
//std::cout << args << std::endl;
//std::cout << typeid(constructor_info<Thing>::arg_types).name() << std::endl;
}
void type_linker_example()
{
//link_types<type_group<double, double>, type_group<int, short>>;
//link_types<type_group<short, long>, type_group<char, float>>;
//
//using type1 = linked_types<int, short>;
//using type2 = linked_types<char, float>;
//
//std::cout << typeid(type1).name() << std::endl;
//std::cout << typeid(type2).name() << std::endl;
}
void constexpr_counter_example()
{
//number<counter(0)::get()> nmr1;
//number<counter(0)::get()> nmr2;
//number<counter(0)::get()> nmr3;
//number<counter(0)::get()> nmr4;
//number<counter(0)::get()> nmr5;
//
//std::cout << typeid(nmr1).name() << std::endl;
//std::cout << typeid(nmr2).name() << std::endl;
//std::cout << typeid(nmr3).name() << std::endl;
//std::cout << typeid(nmr4).name() << std::endl;
//std::cout << typeid(nmr5).name() << std::endl;
//
//number<counter(1)::get()> nmr12;
//number<counter(1)::get()> nmr22;
//number<counter(1)::get()> nmr32;
//number<counter(1)::get()> nmr42;
//number<counter(1)::get()> nmr52;
//
//std::cout << typeid(nmr12).name() << std::endl;
//std::cout << typeid(nmr22).name() << std::endl;
//std::cout << typeid(nmr32).name() << std::endl;
//std::cout << typeid(nmr42).name() << std::endl;
//std::cout << typeid(nmr52).name() << std::endl;
}
//template<class O>
//struct base_converter
//{
// template<class T> requires (!std::same_as<O, T> && (link_types<type_group<T>, type_group<O>>, true))
// operator T();
//
// //template<class T> requires ((link_types<type_group<T>, type_group<O>>, true))
// //operator T();
//};
//
//template<class T>
//concept get_base = requires() {
// new T{ base_converter<T>{} };
//};
//
//template<class T> requires (get_base<T>, true)
//using base_type = nth_type_of_t<0, linked_types<T>>;
//
//template<class>
//struct Pointer;
//
//template<class T> requires (std::same_as<base_type<T>, T>)
//struct Pointer<T> {
// using base = base_type<T>;
// T* ptr;
//};
//
//template<class T> requires (!std::same_as<base_type<T>, T>)
//struct Pointer<T> : public Pointer<base_type<T>> {
// using base = Pointer<base_type<T>>;
// T* ptr;
//};
//
//
//struct Base {
//};
//
//struct Derived : Base {
//};
//
// pe 1
size_t sum_of_multiples(size_t num, size_t max) {
return ((std::ceil(max / (double)num) * num) / 2. * std::floor((max - 1.) / num));
}
size_t sum_of_all_multiples(size_t a, size_t b, size_t max) {
return sum_of_multiples(a, max) + sum_of_multiples(b, max) - sum_of_multiples(a * b, max);
}
void solution1() {
std::cout << sum_of_all_multiples(3, 5, 1000) << std::endl;
}
// pe 2
template<size_t T> constexpr size_t fib = fib<T - 1> +fib<T - 2>;
template<> constexpr size_t fib<0> = 1;
template<> constexpr size_t fib<1> = 2;
template<size_t T> constexpr bool even = !(fib<T> % 2);
template<size_t T, size_t B>
struct fib_below : std::conditional_t<(fib<T> <= B),
fib_below<T + 1, B>, std::integral_constant<size_t, T>> {};
template<size_t T> constexpr size_t fib_below_v = fib_below<0, T>::value;
template<size_t ...Is>
constexpr size_t sum_of_even_fibs(std::index_sequence<Is...>) {
return ((even<Is> ? fib<Is> : 0) + ...);
}
template<size_t T> constexpr size_t sum_of_even_fib_below =
sum_of_even_fibs(std::make_index_sequence<fib_below_v<T>>{});
void solution2() {
std::cout << sum_of_even_fib_below<4000000> << std::endl;
}
// pe 3
#include <vector>
auto get_prime_factors(size_t number) {
size_t n_primes = number / 2;
std::vector<std::pair<size_t, size_t>> primes;
primes.reserve(n_primes);
auto is_prime = [&](size_t v) {
for (auto& prime : primes) {
if (v % prime.first == 0)
return false;
}
return true;
};
primes.push_back({ 2, 0 });
size_t new_prime = 1;
while (primes.size() < n_primes) {
while (!is_prime((new_prime += 2)));
primes.push_back({ new_prime, 0 });
if (new_prime > n_primes)
break;
new_prime = primes.back().first;
}
if (is_prime(number))
primes.push_back({ number, 0 });
while (number != 1) {
for (auto& prime : primes) {
while (number % prime.first == 0) {
number /= prime.first;
prime.second++;
}
}
}
std::vector<std::pair<size_t, size_t>> factors;
for (auto& prime : primes) {
if (prime.second)
factors.push_back(prime);
}
return factors;
}
void solution3() {
size_t number = 600851475143;
auto factors = get_prime_factors(number);
bool first = true;
std::cout << number << " = ";
for (auto& prime : factors) {
if (!first)
std::cout << " + ";
first = false;
std::cout << prime.first << "^" << prime.second;
}
}
// pe 4
auto to_vector(size_t number) {
std::vector<char> numbers;
do {
numbers.push_back(number % 10);
} while ((number /= 10) > 0);
return numbers;
}
bool is_palindromic(size_t number) {
auto nmrs = to_vector(number);
size_t size = nmrs.size();
for (int i = 0; i < size / 2; i++)
if (nmrs[i] != nmrs[size - i - 1])
return false;
return true;
}
void solution4() {
size_t biggest = 0;
for (size_t a = 100; a < 1000; a++) {
for (size_t b = 100; b < 1000; b++) {
size_t product = a * b;
if (product > biggest && is_palindromic(product))
biggest = product;
}
}
std::cout << biggest;
}
// pe 699
#include <set>
size_t sigma(size_t number) {
auto factors = get_prime_factors(number);
std::vector<size_t> divisors;
std::vector<size_t> nmrs;
for (auto& i : factors)
nmrs.push_back(0);
bool done = false;
while (!done) {
size_t product = 1;
for (int i = 0; i < factors.size(); i++) {
product *= std::pow(factors[i].first, nmrs[i]);
}
divisors.push_back(product);
for (int i = 0; i < factors.size(); i++) {
nmrs[i]++;
if (nmrs[i] > factors[i].second) {
nmrs[i] = 0;
if (i == factors.size() - 1)
done = true;
}
else
break;
}
}
size_t sum = 0;
for (auto& d : divisors)
sum += d;
return sum;
}
size_t gcd(size_t a, size_t b) {
while (a != 0 && b != 0) {
if (a > b)
a %= b;
else
b %= a;
}
return std::max(a, b);
}
size_t T(size_t number) {
size_t sum = 0;
auto log3 = std::log(3);
for (size_t n = 2; n <= number; n++) {
size_t s = sigma(n);
size_t g = gcd(s, n);
size_t a = std::log(n / g) / log3;
double b = std::log(n / g) / log3;
if (b == a)
sum += n;
}
return sum;
}
void solution699() {
std::cout << T(1e6) << std::endl;
}
#include <map>
#include <any>
#include <stack>
struct runtime {
using fun_id = std::size_t;
using var_id = std::size_t;
using type_id = std::size_t;
struct type_info {
type_id type_id;
};
struct function_storage {
};
struct variable_storage {
std::any data;
type_info type;
};
std::map<fun_id, function_storage> functions;
std::map<var_id, variable_storage> variables;
struct instruction {
virtual void execute(runtime&) = 0;
};
struct create_variable : instruction {
var_id id;
type_id type;
void execute(runtime& rt) override {
rt.variables.emplace(id, type);
};
};
struct assign_variable : instruction {
var_id var;
var_id value;
void execute(runtime& rt) override {
}
};
std::string code = R"~~(
int entrypoint() {
int b = 100;
int a = 10;
a += b;
return a;
}
)~~";
};
template<class Type>
class my_vector {
public:
using value_type = Type;
using pointer = Type*;
using const_pointer = const Type*;
using reference = Type&;
using const_reference = const Type&;
using size_type = size_t;
using difference_type = ptrdiff_t;
private:
pointer m_Data = nullptr;
size_type m_Size = 0;
size_type m_AllocatedSize = 0;
public:
class const_iterator {
public:
using value_type = Type;
using pointer = Type*;
using const_pointer = const Type*;
using reference = Type&;
using const_reference = const Type&;
using size_type = size_t;
using difference_type = ptrdiff_t;
using iterator_category = std::random_access_iterator_tag;
protected:
pointer m_Ptr;
public:
const_iterator(pointer ptr) : m_Ptr(ptr) {}
const_iterator(const_iterator&& other) = default;
const_iterator(const const_iterator& other) = default;
const_iterator& operator=(const_iterator&&) = default;
const_iterator& operator=(const const_iterator&) = default;
const_iterator& operator++() { m_Ptr++; return *this; }
const_iterator& operator--() { m_Ptr--; return *this; }
const_iterator& operator+=(size_type amt) { this->m_Ptr += amt; return *this; }
const_iterator& operator-=(size_type amt) { this->m_Ptr -= amt; return *this; }
const_iterator operator++(int) { const_iterator _backup = *this; m_Ptr++; return _backup; }
const_iterator operator--(int) { const_iterator _backup = *this; m_Ptr--; return _backup; }
const_iterator operator+(size_type amt) const { const_iterator _new = *this; _new.m_Ptr += amt; return _new; }
const_iterator operator-(size_type amt) const { const_iterator _new = *this; _new.m_Ptr -= amt; return _new; }
difference_type operator-(const const_iterator& other) const { return this->m_Ptr - other.m_Ptr; }
bool operator!=(const const_iterator& other) const { return other.m_Ptr != m_Ptr; }
bool operator==(const const_iterator& other) const { return other.m_Ptr == m_Ptr; }
const_reference operator*() const { return *this->m_Ptr; }
const_pointer operator->() const { return this->m_Ptr; }
friend class my_vector;
};
class iterator : const_iterator {
public:
using value_type = Type;
using pointer = Type*;
using const_pointer = const Type*;
using reference = Type&;
using const_reference = const Type&;
using size_type = size_t;
using difference_type = ptrdiff_t;
using iterator_category = std::random_access_iterator_tag;
using const_iterator::const_iterator;
iterator(iterator&& other) = default;
iterator(const iterator& other) = default;
iterator& operator=(iterator&&) = default;
iterator& operator=(const iterator&) = default;
iterator& operator++() { this->m_Ptr++; return *this; }
iterator& operator--() { this->m_Ptr--; return *this; }
iterator& operator+=(size_type amt) { this->m_Ptr += amt; return *this; }
iterator& operator-=(size_type amt) { this->m_Ptr -= amt; return *this; }
iterator operator++(int) { iterator _backup = *this; this->m_Ptr++; return _backup; }
iterator operator--(int) { iterator _backup = *this; this->m_Ptr--; return _backup; }
iterator operator+(size_type amt) const { iterator _new = *this; _new.m_Ptr += amt; return _new; }
iterator operator-(size_type amt) const { iterator _new = *this; _new.m_Ptr -= amt; return _new; }
difference_type operator-(const iterator& other) const { return this->m_Ptr - other.m_Ptr; }
bool operator!=(const iterator& other) const { return other.m_Ptr != this->m_Ptr; }
bool operator==(const iterator& other) const { return other.m_Ptr == this->m_Ptr; }
reference operator*() { return *this->m_Ptr; }
pointer operator->() { return this->m_Ptr; }
friend class my_vector;
};
my_vector() { allocate(2); }
~my_vector() { clear(); }
bool empty() const { return m_Size == 0; }
size_type size() const { return m_Size; }
size_type capacity() const { return m_AllocatedSize; }
void clear() {
for (size_type _index = 0; _index < m_Size; _index++)
m_Data[_index].~value_type();
delete[] reinterpret_cast<uint8_t*>(m_Data);
m_Data = nullptr;
m_Size = 0;
}
void erase(iterator iter) {
std::move(iter + 1, end(), iter);
end()->~value_type();
m_Size--;
}
void reserve(size_type amount) {
if (amount < m_Size) return; // If already enough memory, return
allocate(amount);
}
void push_back(value_type&& elem) {
check_size();
new (&m_Data[m_Size]) value_type(std::move(elem));
m_Size++;
}
void push_back(const_reference elem) {
check_size();
new (&m_Data[m_Size]) value_type(elem);
m_Size++;
}
template<class ...Args>
reference emplace_back(Args&& ...args) requires std::constructible_from<value_type, Args...> {
check_size();
new (&m_Data[m_Size]) value_type(std::forward<Args>(args)...);
m_Size++;
return m_Data[m_Size - 1];
}
template<class ...Args>
reference emplace(Args&& ...args) requires std::constructible_from<value_type, Args...> {
check_size();
new (&m_Data[m_Size]) value_type(std::forward<Args>(args)...);
m_Size++;
return m_Data[m_Size - 1];
}
reference at(size_type index) { return m_Data[index]; }
const_reference at(size_type index) const { return m_Data[index]; }
reference operator[](size_type index) { return m_Data[index]; }
const_reference operator[](size_type index) const { return m_Data[index]; }
reference front() { return *m_Data[0]; }
reference back() { return *m_Data[m_Size - 1]; }
const_reference front() const { return *m_Data[0]; }
const_reference back() const { return *m_Data[m_Size - 1]; }
pointer data() { return m_Data; }
iterator begin() { return m_Data; }
iterator end() { return m_Data + m_Size; }
const_pointer data() const { return m_Data; }
const_iterator begin() const { return m_Data; }
const_iterator end() const { return m_Data + m_Size; }
const_iterator cbegin() const { return m_Data; }
const_iterator cend() const { return m_Data + m_Size; }
private:
void check_size() {
if (m_Size + 1 > m_AllocatedSize) allocate(m_AllocatedSize * 2);
}
void allocate(size_type amount) {
pointer _new = reinterpret_cast<pointer>(new uint8_t[amount * sizeof value_type]);
for (size_type _index = 0; _index < m_Size; _index++) {
new (&_new[_index]) value_type(std::move(m_Data[_index]));
m_Data[_index].~value_type();
}
delete[] reinterpret_cast<uint8_t*>(m_Data);
m_Data = _new;
m_AllocatedSize = amount;
}
};
struct Woofers {
int val;
Woofers() { puts("construct"); }
Woofers(int val) : val(val) { puts("construct"); }
Woofers(const Woofers& other) : val(other.val) { puts("copy"); }
Woofers(Woofers&& other) : val(other.val) { puts("move"); }
Woofers& operator=(const Woofers& other) { val = other.val; puts("copy assign"); return *this; }
Woofers& operator=(Woofers&& other) { val = other.val; puts("move assign"); return *this; }
~Woofers() { puts("delete"); }
};
#include <algorithm>
#include "vec.hpp"
#include "axial_array.hpp"
template<class Type>
struct ref_or_val {
using type = Type;
enum state : uint8_t { has_ref, has_val, has_null };
constexpr ref_or_val() : m_Null(0), m_State(has_null) {}
constexpr ref_or_val(type& v) : m_Ref(v), m_State(has_ref) {}
constexpr ref_or_val(type&& v) : m_Val(std::move(v)), m_State(has_val) {}
constexpr ref_or_val(const type&& v) : m_Val(std::move(v)), m_State(has_val) {}
constexpr ref_or_val(const type& v) = delete;
constexpr ref_or_val(const ref_or_val& other) { *this = other; }
constexpr ref_or_val(ref_or_val&& other) { *this = std::move(other); }
constexpr ref_or_val& operator=(type& v) { return assign(v), * this; }
constexpr ref_or_val& operator=(type&& v) { return assign(std::move(v)), * this; }
constexpr ref_or_val& operator=(const type&& v) { return assign(std::move(v)), * this; }
constexpr ref_or_val& operator=(const ref_or_val& v) { return assign(v), * this; }
constexpr ref_or_val& operator=(ref_or_val&& v) { return assign(std::move(v)), * this; }
constexpr ref_or_val& operator=(const type& v) = delete;
constexpr type& get() { return m_State == state::has_ref ? m_Ref.get() : m_Val; }
constexpr const type& get() const { return m_State == state::has_ref ? m_Ref.get() : m_Val; }
constexpr operator type& () { return m_State == state::has_ref ? m_Ref.get() : m_Val; }
constexpr operator const type& () const { return m_State == state::has_ref ? m_Ref.get() : m_Val; }
constexpr void assign(type& v) {
cleanup();
new (&m_Ref) std::reference_wrapper<type>(v);
m_State = state::has_ref;
}
constexpr void assign(type&& v) {
cleanup();
new (&m_Val) type{ std::move(v) };
m_State = state::has_val;
}
constexpr void assign(const ref_or_val& v) {
m_State = v.m_State;
m_State == state::has_ref
? assign(v.m_Ref.get())
: assign(type{ v.m_Val });
}
constexpr void assign(ref_or_val&& v) {
m_State = v.m_State;
m_State == state::has_ref
? assign(v.m_Ref.get())
: assign(std::move(v.m_Val));
v.invalidate();
}
constexpr explicit operator bool() const { return m_State != state::has_null; }
private:
union {
std::reference_wrapper<type> m_Ref;
type m_Val;
void* m_Null;
};
state m_State;
constexpr void cleanup() {
if constexpr (!std::is_trivially_destructible_v<type>)
if (m_State == state::has_val) m_Val.~type();
}
constexpr void invalidate() {
new (&m_Null) std::nullptr_t{};
m_State = state::has_null;
}
};
#include <list>
#include <functional>
#include "list_comprehension.hpp"
struct C {
C() = delete;
C(int v) : v(v) { puts("create"); };
C(C&& v) : v(v.v) { puts("move"); }
C(const C& v) : v(v.v) { puts("copy"); }
~C() { puts("destroy"); }
C& operator++() { v++; return *this; }
bool operator==(const C& o) const { return o.v == v; }
int v;
};
struct binary {
using size_type = size_t;
template<std::integral Ty>
binary(Ty data)
: data(reinterpret_cast<uint8_t*>(&data), reinterpret_cast<uint8_t*>(&data) + sizeof Ty)
{}
struct bit {
operator bool() { return (byte >> index) & 1U; }
bit& operator=(bool v) {
byte ^= (-v ^ byte) & (1u << index);
return *this;
}
uint8_t& byte;
uint8_t index;
};
struct iterator {
using value_type = bit;
iterator& operator++() { index++; return *this; }
bit operator*() { return bin->at(index); }
bool operator==(const iterator& o) const { return o.index == index; }
size_type index;
binary* bin;
};
bit operator[](size_t index) {
if (index < size())
resize(index);
return at(index);
}
bit at(size_t index) {
return { data[index / 8], static_cast<uint8_t>(index % 8) };
}
size_type size() const { return data.size() * 8; }
void resize(size_t size) { data.resize((size + 7) / 8); }
iterator begin() { return { 0, this }; }
iterator end() { return { size(), this }; }
private:
std::vector<uint8_t> data;
};
template<class Ty>
class const_array_list_iterator : std::vector<Ty*>::const_iterator {
using m_Base = std::vector<Ty*>::const_iterator;
public:
using iterator_concept = m_Base::iterator_concept;
using iterator_category = m_Base::iterator_category;
using value_type = Ty;
using difference_type = m_Base::difference_type;
using pointer = Ty*;
using reference = Ty&;
auto& operator*() { return *m_Base::operator*(); }
auto operator->() { return *m_Base::operator->(); }
};
template<class Ty>
struct array_list_iterator : std::vector<Ty*>::iterator {
using m_Base = std::vector<Ty*>::iterator;
public:
using iterator_concept = m_Base::iterator_concept;
using iterator_category = m_Base::iterator_category;
using value_type = Ty;
using difference_type = m_Base::difference_type;
using pointer = Ty*;
using reference = Ty&;
auto& operator*() { return *m_Base::operator*(); }
auto operator->() { return *m_Base::operator->(); }
};
template<class Ty>
struct array_list {
using value_type = Ty;
using pointer = Ty*;
using const_pointer = const Ty*;
using reference = Ty&;
using const_reference = const Ty&;
using size_type = std::size_t;
using difference_type = std::ptrdiff_t;
using iterator = array_list_iterator<Ty>;
using const_iterator = const_array_list_iterator<Ty>;
using reverse_iterator = std::reverse_iterator<iterator>;
using const_reverse_iterator = std::reverse_iterator<const_iterator>;
constexpr array_list() {}
constexpr array_list(std::initializer_list<Ty> l) {}
constexpr array_list(const array_list& other) : m_Arr(other.m_Arr) {}
constexpr array_list(array_list&& other) : m_Arr(std::move(other.m_Arr)) {}
array_list& operator=(const array_list& other) { m_Arr = other.m_Arr; }
array_list& operator=(array_list&& other) { m_Arr = std::move(other.m_Arr); }
constexpr reference at(size_type pos) { return *m_Arr.at(pos); }
constexpr const_reference at(size_type pos) const { return *m_Arr.at(pos); }
constexpr reference operator[](size_type pos) { return *m_Arr[pos]; }
constexpr const_reference operator[](size_type pos) const { return *m_Arr[pos]; }
constexpr reference front() { return *m_Arr.front(); }
constexpr const_reference front() const { return *m_Arr.front(); }
constexpr reference back() { return *m_Arr.back(); }
constexpr const_reference back() const { return *m_Arr.back(); }
constexpr iterator begin() { return { m_Arr.begin() }; }
constexpr const_iterator begin() const { return { m_Arr.begin() }; }
constexpr iterator end() { return { m_Arr.end() }; }
constexpr const_iterator end() const { return { m_Arr.end() }; }
constexpr const_iterator cbegin() const { return { m_Arr.cbegin() }; }
constexpr const_iterator cend() const { return { m_Arr.cend() }; }
constexpr iterator rbegin() { return { m_Arr.rbegin() }; }
constexpr const_iterator rbegin() const { return { m_Arr.rbegin() }; }
constexpr iterator rend() { return { m_Arr.rend() }; }
constexpr const_iterator rend() const { return { m_Arr.rend() }; }
constexpr const_iterator crbegin() const { return { m_Arr.crbegin() }; }
constexpr const_iterator crend() const { return { m_Arr.crend() }; }
constexpr bool empty() const { return m_Arr.empty(); }
constexpr size_type size() const { return m_Arr.size(); }
constexpr size_type max_size() const { return m_Arr.max_size(); }
constexpr void reserve(size_type n) { m_Arr.reserve(n); }
constexpr size_type capacity() const { return m_Arr.capacity(); }
constexpr void shrink_to_fit() { m_Arr.shrink_to_fit(); }
constexpr void clear() { m_Arr.clear(); }
constexpr void insert(iterator pos, const Ty& val) { m_Arr.insert(pos, new Ty{ val }); }
constexpr void insert(const_iterator pos, const Ty& val) { m_Arr.insert(pos, new Ty{ val }); }
constexpr void insert(iterator pos, Ty&& val) { m_Arr.insert(pos, new Ty{ std::move(val) }); }
constexpr void insert(const_iterator pos, Ty&& val) { m_Arr.insert(pos, new Ty{ std::move(val) }); }
template<class... Args>
constexpr iterator emplace(const_iterator pos, Args&&... args) {
return m_Arr.emplace(pos, new Ty{ std::forward<Args>(args)... });
}
constexpr iterator erase(const_iterator pos) {
delete* pos;
return m_Arr.erase(pos);
}
constexpr void push_back(const Ty& val) { m_Arr.push_back(new Ty{ val }); }
constexpr void push_back(Ty&& val) { m_Arr.push_back(new Ty{ std::move(val) }); }
template<class... Args>
constexpr reference emplace_back(Args&&... args) {
return m_Arr.emplace_back(new Ty{ std::forward<Args>(args)... });
}
constexpr void pop_back() { delete m_Arr.back(); m_Arr.pop_back(); }
constexpr void swap(array_list& other) { m_Arr.swap(other.m_Arr); }
private:
std::vector<Ty*> m_Arr;
};
#include <map>
#include <variant>
template<class Ty, class ...Tys>
concept OneOf = (std::same_as<Ty, Tys> || ...);
class Json
{
public:
using Floating = double;
using Integral = int64_t;
using Unsigned = uint64_t;
using String = std::string;
using Boolean = bool;
using Array = std::vector<Json>;
using Object = std::map<String, Json, std::less<void>>;
using Null = std::nullptr_t;
private:
using JsonValue = std::variant<Floating, Integral, Unsigned, String, Boolean, Array, Object, Null>;
struct Type { enum { Floating, Integral, Unsigned, String, Boolean, Array, Object, Null }; };
JsonValue m_Value;
template<class Ty> struct Alias { using Type = Ty; };
template<std::signed_integral Ty> struct Alias<Ty> { using Type = Integral; };
template<std::unsigned_integral Ty> struct Alias<Ty> { using Type = Unsigned; };
public:
template<class Ty = Null>
Json(const Ty& ty = {}) : m_Value(static_cast<Alias<Ty>::Type>(ty)) {}
template<class Ty> Ty get() const { return static_cast<Ty>(std::get<Alias<Ty>::Type>(m_Value)); }
template<class Ty> Ty& ref() { return std::get<Ty>(m_Value); }
template<class Ty> const Ty& ref() const { return std::get<Ty>(m_Value); }
Json& operator[](std::string_view index)
{
if (m_Value.index() == Type::Null) m_Value = Object{};
else if (m_Value.index() != Type::Object) throw std::exception("Not an object.");
auto _it = ref<Object>().find(index);
if (_it == ref<Object>().end()) return ref<Object>()[std::string{ index }];
else return _it->second;
}
};
#include <bit>
template<class Ky, class Ty>
class hash_map {
public:
using key_type = Ky;
using mapped_type = Ty;
using value_type = std::pair<const Ky, Ty>;
using size_type = std::size_t;
using difference_type = std::ptrdiff_t;
using reference = value_type&;
using const_reference = const value_type&;
using pointer = value_type*;
using const_pointer = const value_type*;
private:
class node {
public:
node() = default;
node(const Ky& key) : m_Value(new value_type{ key, {} }) {}
node(const value_type& val) : m_Value(new value_type{ val }) {}
value_type* find(const Ky& key) {
if (!m_Value) return nullptr;
if (key == m_Value->first) return m_Value;
if (m_Next) return m_Next->find(key);
return nullptr;
}
void erase(const Ky& key, size_type& size) {
if (!m_Value) return;
if (key == m_Value->first) {
size--;
delete m_Value; // Delete the value
if (m_Next) { // Move the next node over to this one
m_Value = m_Next->m_Value;
m_Next = m_Next->m_Next;
m_Next->m_Value = nullptr;
m_Next->m_Next = nullptr;
delete m_Next; // Delete the next
}
}
else if (!m_Next) return;
else m_Next->erase(key, size);
}
value_type* find_or_insert(const Ky& key, size_type& size) {
if (!m_Value) return size++, m_Value = new value_type{ key, {} };
if (key == m_Value->first) return m_Value;
if (!m_Next) return m_Next = new node{ key }, size++, m_Next->m_Value;
return m_Next->find_or_insert(key, size);
}
value_type* puts(const value_type& val, size_type& size) {
if (!m_Value) return size++, m_Value = new value_type{ val };
if (val.first == m_Value->first) return m_Value->second = val.second, m_Value;
if (!m_Next) return m_Next = new node{ val }, size++, m_Next->m_Value;
return m_Next->puts(val, size);
}
~node() {
if (m_Value) delete m_Value;
if (m_Next) delete m_Next;
}
private:
value_type* m_Value = nullptr;
node* m_Next = nullptr;
friend class hash_map::iterator;
};
public:
class iterator {
public:
using iterator_category = std::forward_iterator_tag;
using value_type = hash_map::value_type;
using difference_type = hash_map::difference_type;
using reference = hash_map::reference;
using pointer = hash_map::pointer;
iterator() : m_Nodes(nullptr), m_Size(0) {};
iterator(node** n, size_type size) : m_Nodes(n), m_Size(size) {
if (!m_Size) m_Base = *m_Nodes; // If no size, we're at the end
else do if ((*m_Nodes)->m_Value) { // if linked list has value
m_Base = (*m_Nodes); // Set base node
break;
} while (++m_Nodes, --m_Size); // Keep incrementing till m_Size == 0
if (!m_Base) m_Base = *m_Nodes; // If no base base set, it's empty
}
iterator& operator++() {
if (m_Base->m_Next) m_Base = m_Base->m_Next; // First try linked list
else while (m_Size--) // Otherwise find next linked list with content
if (!m_Size) m_Base = *++m_Nodes; // If no size left, we're at the end
else if ((*++m_Nodes)->m_Value) { // check if value
m_Base = (*m_Nodes); // Set new base node
break;
}
return *this;
}
iterator operator++(int) {
iterator _next = *this;
++(*this);
return _next;
}
void swap(iterator& other) {
std::swap(other.m_Base, m_Base);
std::swap(other.m_Nodes, m_Nodes);
std::swap(other.m_Size, m_Size);
}
bool operator==(const iterator& other) const { return m_Base == other.m_Base; }
bool operator!=(const iterator& other) const { return m_Base != other.m_Base; }
value_type& operator*() { return *m_Base->m_Value; }
value_type* operator->() { return m_Base->m_Value; }
protected:
node* m_Base = nullptr;
node** m_Nodes;
size_type m_Size;
};
class const_iterator : public iterator {
public:
const value_type& operator*() { return *this->m_Base->m_Value; }
};
hash_map() { resize(16); }
hash_map(std::initializer_list<value_type> il) {
resize(16); // Insert everything from list
for (auto& i : il) puts(i);
}
hash_map(const hash_map& other) {
resize(other.buckets());
for (auto& i : other) puts(i);
}
hash_map(hash_map&& other) : m_Nodes(other.m_Nodes),
m_Buckets(other.m_Buckets), m_Size(other.m_Size) {
other.m_Buckets = 0;
other.m_Size = 0;
other.m_Nodes = nullptr;
}
hash_map& operator=(const hash_map& other) {
cleanup();
resize(other.buckets());
for (auto& i : other) puts(i);
return *this;
}
hash_map& operator=(hash_map&& other) {
cleanup();
m_Nodes = other.m_Nodes;
m_Buckets = other.m_Buckets;
m_Size = other.m_Size;
other.m_Buckets = 0;
other.m_Size = 0;
other.m_Nodes = nullptr;
return *this;
}
~hash_map() { cleanup(); }
bool empty() const { return m_Size != 0; }
size_type size() const { return m_Size; }
size_type buckets() const { return m_Buckets; }
iterator begin() { return iterator{ m_Nodes, m_Buckets }; }
iterator end() { return iterator{ m_Nodes + m_Buckets, 0 }; }
const_iterator begin() const { return const_iterator{ m_Nodes, m_Buckets }; }
const_iterator end() const { return const_iterator{ m_Nodes + m_Buckets, 0 }; }
const_iterator cbegin() const { return const_iterator{ m_Nodes, m_Buckets }; }
const_iterator cend() const { return const_iterator{ m_Nodes + m_Buckets, 0 }; }
Ty& operator[](const Ky& key) { return m_Nodes[hash(key)]->find_or_insert(key, m_Size)->second; }
Ty& puts(const Ky& key, const Ty& val) { return m_Nodes[hash(key)]->puts({ key, val }, m_Size)->second; }
Ty& puts(const value_type& val) { return m_Nodes[hash(val.first)]->puts(val, m_Size)->second; }
Ty& at(const Ky& key) { return m_Nodes[hash(key)]->find(key)->second; }
const Ty& at(const Ky& key) const { return m_Nodes[hash(key)]->find(key)->second; }
void erase(const Ky& key) { m_Nodes[hash(key)]->erase(key, m_Size); }
void resize(size_type buckets) {
if (buckets < m_Buckets) return; // Only resize if specified bigger
buckets = std::bit_ceil(buckets); // Round up to nearest power of 2
node** _new = new node * [buckets]; // Allocated new array
for (size_type i = 0; i < m_Buckets; i++) _new[i] = m_Nodes[i];
for (size_type i = m_Buckets; i < buckets; i++) _new[i] = new node;
delete[] m_Nodes; // Delete the original array
m_Buckets = buckets, m_Nodes = _new;// Update size, assign new array
}
private:
size_type m_Size = 0, m_Buckets = 0;
node** m_Nodes = nullptr;
size_t hash(const Ky& key) const { return std::hash<Ky>{}(key)& (m_Buckets - 1); }
void cleanup() { // Delete array of nodes
for (size_type i = 0; i < m_Buckets; i++) delete m_Nodes[i];
delete[] m_Nodes;
}
};
template<class Ty>
class linked_list {
public:
using value_type = Ty;
using reference = Ty&;
using const_reference = const Ty&;
using pointer = Ty*;
using const_pointer = const Ty*;
using difference_type = std::ptrdiff_t;
using size_type = std::size_t;
struct node {
value_type value;
node* next = nullptr;
~node() { delete next; }
reference push(const_reference val) { return next ? next->push(val) : (next = new node{ val })->value; };
template<class ...Args>
reference emplace(Args&& ...args) {
return next
? next->emplace(std::forward<Args>(args)...)
: (next = new node{ { std::forward<Args>(args)... } })->value;
};
};
class const_iterator {
public:
using iterator_category = std::forward_iterator_tag;
using value_type = typename linked_list::value_type;
using difference_type = typename linked_list::difference_type;
using pointer = typename linked_list::const_pointer;
using reference = const value_type&;
const_iterator() {}
const_iterator(node* n) : m_Node(n) {}
const_iterator& operator++() { m_Node = m_Node->next; return *this; }
const_iterator operator++(int) { const_iterator _t = *this; m_Node = m_Node->next; return _t; }
reference operator*() { return m_Node->value; }
bool operator==(const const_iterator& other) const { return m_Node == other.m_Node; }
private:
node* m_Node = nullptr;
friend class linked_list;
};
class iterator : public const_iterator {
public:
using iterator_category = std::forward_iterator_tag;
using value_type = typename linked_list::value_type;
using difference_type = typename linked_list::difference_type;
using pointer = typename linked_list::const_pointer;
using reference = value_type&;
using const_iterator::const_iterator;
iterator& operator++() { this->m_Node = this->m_Node->next; return *this; }
iterator operator++(int) { iterator _t = *this; this->m_Node = this->m_Node->next; return _t; }
reference operator*() { return this->m_Node->value; }
bool operator==(const iterator& other) const { return this->m_Node == other.m_Node; }
friend class linked_list;
};
iterator begin() { return { m_Start }; }
iterator end() { return { nullptr }; }
const_iterator begin() const { return { m_Start }; }
const_iterator end() const { return { nullptr }; }
const_iterator cbegin() const { return { m_Start }; }
const_iterator cend() const { return { nullptr }; }
reference front() const { return m_Start->value; }
iterator erase_after(const_iterator pos) {
auto _b = pos.m_Node->next;
if (_b) {
pos.m_Node->next = pos.m_Node->next->next;
delete _b;
m_Size--;
}
return { pos.m_Node->next };
}
iterator erase_after(const_iterator first, const_iterator last) {
while (first != last) erase_after(first), ++first;
return last;
}
void push_front(const Ty& val) { m_Size++, m_Start = new node{ val, m_Start }; }
void push_front(Ty&& val) { m_Size++, m_Start = new node{ std::move(val), m_Start }; }
void pop_front() {
auto _b = m_Start;
if (_b) {
m_Start = m_Start->next;
delete _b;
m_Size--;
}
}
template<class ...Args>
reference emplace_front(Args&& ...args) { return (m_Size++, m_Start = new node{ { std::forward<Args>(args)... }, m_Start })->value; }
iterator insert_after(const_iterator pos, const Ty& val) { return m_Insert(pos, val); }
iterator insert_after(const_iterator pos, Ty&& val) { return m_Insert(pos, std::move(val)); }
iterator insert_after(const_iterator pos, size_type count, const Ty& val) {
while (count--) m_Insert(pos, val);
return pos;
}
template<class It>
iterator insert_after(const_iterator pos, It first, It last) {
while (first != last) m_Insert(pos, *first), ++first;
return pos;
}
iterator insert_after(const_iterator pos, std::initializer_list<Ty> il) {
for (auto& i : il) m_Insert(pos, i);
return pos;
}
template<class ...Args>
iterator emplace_after(const_iterator pos, Args&& ...args) { return m_Insert(pos, std::forward<Args>(args)...); }
private:
node* m_Start = nullptr;
size_type m_Size = 0;
template<class ...Args>
iterator m_Insert(const_iterator& pos, Args&& ...args) {
auto _b = pos.m_Node->next;
pos.m_Node->next = new node{ { std::forward<Args>(args)... } };
pos.m_Node->next->next = _b;
pos = pos.m_Node->next;
m_Size++;
return pos.m_Node;
}
};
template<class Symbol = std::uint8_t, class State = std::size_t>
struct TuringMachine {
enum Direction { Left = -1, None = 0, Right = 1 };
constexpr static State HALT = static_cast<State>(-1);
using Instruction = std::tuple<State, Symbol, Direction>;
std::map<std::pair<State, Symbol>, Instruction> instructions;
std::list<Symbol> tape{ 0 };
std::list<Symbol>::iterator head = tape.begin();
State state = 0;
Symbol& Read() { return *head; }
Symbol& Move(Direction d) {
return d == Left ? head == tape.begin() ? *(head = tape.insert(tape.begin(), 0)) : *--head
: d == Right ? ++head == tape.end() ? *(head = tape.insert(tape.end(), 0)) : *head : *head;
}
bool Step() {
auto& [nstate, write, move] = instructions.at({ state, Read() });
return (Read() = write, Move(move), state = nstate) != HALT;
}
};
#include <vector>
#include <iostream>
#include <iomanip>
#include "utils.hpp"
#include <variant>
#include <cassert>
// -- header file --
#include <iostream>
struct override;
template<class = override, class...>
inline auto logger = std::clog;
template<class... Tys, class T>
void log(T t) { logger<override, Tys...> << t; }
// -- cpp file --
#include <fstream>
template<> auto logger<override> = std::ofstream{ "log.txt" };
struct dud {};
template<auto Impl, class A = dud>
struct infix {
A a;
template<class Ty>
constexpr friend auto operator<(Ty&& a, const infix& op) {
return infix<Impl, Ty>{ std::forward<Ty>(a) };
}
template<class Ty> requires (std::invocable<decltype(Impl), A, Ty>)
constexpr friend auto operator>(infix&& op, Ty&& b)
-> decltype(Impl(std::forward<A>(op.a), std::forward<Ty>(b))) {
return Impl(std::forward<A>(op.a), std::forward<Ty>(b));
}
};
#include <array>
#include <map>
constexpr infix < [](auto& a, auto& b) { return a.contains(b); } > contains;
constexpr infix < []<class Ty>(Ty&& val, auto& container) {
return std::find(std::begin(container), std::end(container),
std::forward<Ty>(val)) != std::end(container);
} > in;
constexpr infix < []<class A, class B>(A&& a, B&& b) {
if constexpr (std::integral<A> && std::integral<B>)
return a % b;
else
return std::fmod(std::forward<A>(a), std::forward<B>(b));
} > mod;
#define wrap(x) []<class ...Tys> requires requires(Tys&&...args) { x(std::forward<Tys>(args)...); } (Tys&&...args)\
-> decltype(x(std::forward<Tys>(args)...)) { return x(std::forward<Tys>(args)...); }
template<class ...Tys>
struct overloaded : Tys... {
using Tys::operator()...;
};
template<std::size_t N, std::size_t M>
struct dfa {
struct state {
std::pair<char, std::size_t> fun[M];
bool accept = false;
constexpr std::size_t transition(char c) const {
auto res = std::find_if(std::begin(fun), std::end(fun), [=](auto& v) { return v.first == c; });
return res->second;
}
};
state states[N];
template<std::size_t N>
constexpr bool accepts(const char(&c)[N]) const {
auto q = states;
for (std::size_t i = 0; i < N - 1; i++) {
q = &states[q->transition(c[i])];
}
return q->accept;
}
};
template<class Ty, std::size_t Size, std::size_t Arity = 2, class Pred = std::less<Ty>>
struct heap {
using value_type = Ty;
using size_type = std::size_t;
using reference = Ty&;
using const_reference = const Ty&;
using value_compare = Pred;
constexpr heap() = default;
template<std::size_t N>
constexpr heap(const Ty(&arr)[N])
: m_Size(std::min(N, Size)) {
std::copy_n(arr, N, m_Data);
for (int64_t i = (m_Size - Arity) / Arity; i >= 0; i--)
sink(i); // Sink all layers
}
template<std::same_as<Ty> ...Tys>
constexpr heap(Tys&&...tys)
: m_Size(std::min(sizeof...(Tys), Size)) {
size_type index = 0;
((m_Data[index++] = tys), ...);
for (int64_t i = (m_Size - Arity) / Arity; i >= 0; i--)
sink(i); // Sink all layers
}
template<class ...Tys>
constexpr Ty& emplace(Tys&& ...vals) {
assert(m_Size != Size); // Assert not full
// Put value at end
m_Data[m_Size] = Ty{ std::forward<Tys>(vals)... };
auto me = m_Size, pa = (m_Size - 1) / 2;
while (comp(m_Data[pa], m_Data[me])) { // While parent smaller
std::swap(m_Data[me], m_Data[pa]); // Swap with parent
if (pa == 0) break; // If root node, done
me = pa, pa = (me - 1) / 2; // New parent
}
++m_Size;
return m_Data[me];
}
constexpr void push(Ty&& val) { emplace(std::move(val)); }
constexpr void push(const Ty& val) { emplace(val); }
constexpr bool empty() const { return m_Size == 0; }
constexpr size_type size() const { return m_Size; }
constexpr size_type max_size() const { return Size; }
constexpr size_type arity() const { return Arity; }
constexpr Ty& top() { return m_Data[0]; }
constexpr const Ty& top() const { return m_Data[0]; }
constexpr void pop() {
m_Data[0] = m_Data[m_Size - 1]; // Move last element to top
--m_Size; // Decrease size
sink(0); // Sink the root node down
}
private:
size_type m_Size = 0;
Ty m_Data[Size];
[[no_unique_address]] Pred comp;
constexpr void sink(size_type i) {
size_type max = i; // Find highest value
for (size_type n = Arity * i + 1; n <= Arity * i + Arity; n++)
if (n < m_Size and comp(m_Data[n], m_Data[max])) max = n;
if (max != i) { // If not itself, swap and sink further down
std::swap(m_Data[i], m_Data[max]);
sink(max);
}
}
constexpr friend auto& operator<<(auto& a, const heap& v) {
size_type m = Size, l = 0, k = 1, p = 0;
for (auto& i : v.m_Data) {
for (auto j = 0; j < m * (Arity - 1); j++) a << " ";
a << std::setw(2) << std::setfill(' ') << i, ++p;
if (p >= v.m_Size) break;
for (auto j = 0; j < m * (Arity - 1); j++) a << " ";
if ((++l) % k == 0) l = 0, k *= Arity, a << '\n', m /= Arity;
}
return a;
}
};
template<class ...Tys>
heap(Tys&&...)->heap<std::tuple_element_t<0, std::tuple<Tys...>>, sizeof...(Tys)>;
#include <span>
#include <ranges>
//namespace old {
//
// struct Edge {
// std::size_t vertex = std::numeric_limits<std::size_t>::max();
// double length = std::numeric_limits<double>::max();
// };
//
// template<std::size_t S = 0>
// struct Vertex {
// constexpr static auto size = S;
// Edge edges[S];
// };
//
// template<> struct Vertex<0> {
// constexpr static auto size = 0;
// Edge* edges = nullptr;
// };
//
// template<std::size_t Size, std::size_t Edges>
// struct Graph {
// struct {
// std::size_t offsets[Size + 1]{};
// Edge edges[Edges]{};
//
// constexpr auto from_edge(std::size_t edge) const {
// for (std::size_t i = 0; i < Size + 1; ++i)
// if (offsets[i] > edge) return i - 1;
// return Size;
// }
//
// constexpr auto operator[](std::size_t i) const {
// return std::span{ edges + offsets[i], offsets[i + 1] - offsets[i] };
// }
//
// friend struct Graph;
// } vertices;
//
// constexpr Graph(std::size_t(&a)[Size + 1], Edge(&b)[Edges]) {
// std::copy_n(a, Size + 1, vertices.offsets);
// std::copy_n(b, Edges, vertices.edges);
// }
//
// template<class ...Vertices>
// constexpr Graph(Vertices&& ...vs) {
// std::size_t i1 = 0, i2 = 0;
// vertices.offsets[0] = 0;
// ((std::copy_n(vs.edges, vs.size, vertices.edges + i2),
// vertices.offsets[++i1] = i2 + vs.size, i2 += vs.size), ...);
// }
//
// // Implemented using Dijkstra's Algorithm
// constexpr auto shortest_path(std::size_t a) const {
// constexpr auto infinity = std::numeric_limits<double>::max();
// std::array<double, Size> dist{}; // distances
// dist.fill(infinity), dist[a] = 0; // itself = 0, rest = infinity
//
// bool checked[Size]{}; // Keep track of checked vertices
// checked[a] = true; // No need to check itself
// for (std::size_t _ = 0, u = 0; _ < Size; ++_) {
// double closest = infinity; // Find closest unchecked vertex
// for (std::size_t next = 0; next < Size; ++next)
// if (!checked[next] && dist[next] < closest)
// closest = dist[u], u = next;
// for (auto [v, len] : vertices[u]) // relax vertex u and its neighbours
// dist[v] = std::min(dist[v], dist[u] + len);
// checked[u] = true; // Now we've checked this one
// }
//
// return dist;
// }
//
// constexpr auto minimum_spanning_tree() const {
// struct CompleteEdge {
// std::size_t a, b;
// double length;
// };
//
// std::size_t offsets[Size + 1]{};
// CompleteEdge newEdges[Size - 1]{};
//
// bool in_w[Size]{};
// StackVector<std::size_t, Size> w{};
// w.push_back(0), in_w[0] = true; // Start at v = 0
//
// for (std::size_t i = 0; i < Size - 1; ++i) {
// double len = std::numeric_limits<double>::max();
// std::size_t v = 0, u = 0;
// for (auto vx : w.span()) // Loop over vertices in w
// for (auto [ux, lenx] : vertices[vx]) // Loop over edges of v
// // pick smallest edge who's other vertex is not in w
// if (!in_w[ux] && lenx < len) len = lenx, v = vx, u = ux;
//
// w.push_back(u), in_w[u] = true; // Add connected vertex to choices
// newEdges[i] = CompleteEdge{ v, u, len }; // Add new edge
// ++offsets[u + 1], ++offsets[v + 1]; // Add 1 to offsets
// }
//
// // Calculate offsets
// std::size_t prev = 0;
// for (auto& i : offsets) i += prev, prev = i;
//
// // Order the edges
// Edge finalEdges[2 * Size - 2]{};
// std::size_t cntr[Size]{};
// for (std::size_t i = 0; i < Size - 1; ++i) {
// auto e = newEdges[i];
// finalEdges[offsets[e.a] + cntr[e.a]++] = Edge{ e.b, e.length };
// finalEdges[offsets[e.b] + cntr[e.b]++] = Edge{ e.a, e.length };
// }
//
// return Graph<Size, 2 * Size - 2>{ offsets, finalEdges };
// }
// };
//
// template<class ...Vertices>
// Graph(Vertices&&...)->Graph<sizeof...(Vertices), (Vertices::size + ...)>;
//}
template<class Ty, std::size_t Size> struct StackVector {
constexpr void push_back(Ty&& v) { m_D[m_S] = std::move(v); ++m_S; }
constexpr void push_back(const Ty& v) { m_D[m_S] = v; ++m_S; }
constexpr void pop_back() { --m_S; }
constexpr auto size() const { return m_S; }
constexpr auto data() const { return m_D; }
constexpr auto data() { return m_D; }
constexpr auto begin() const { return m_D; }
constexpr auto end() const { return m_D + m_S; }
constexpr auto cbegin() const { return m_D; }
constexpr auto cend() const { return m_D + m_S; }
constexpr auto begin() { return m_D; }
constexpr auto end() { return m_D + m_S; }
Ty m_D[Size]{};
std::size_t m_S = 0;
};
struct Edge { std::size_t a, b; double length; };
template<std::size_t Vertices, std::size_t Edges>
struct UndirectedGraph {
Edge edges[Edges]{}; // All the edge weights
std::size_t part_of[Edges * 2]{}; // Mapping from vertex to edge
std::size_t offsets[Vertices + 1]{};
// Construct with template pack of edges, creates array
template<class ...Tys> constexpr UndirectedGraph(Tys&& ...es)
: UndirectedGraph(StackVector<Edge, Edges>{
{ std::forward<Tys>(es)... }, sizeof...(Tys) }) {}
// Construct with stack array
constexpr UndirectedGraph(StackVector<Edge, Edges>&& arr) {
// Copy edges and calculate offsets
std::copy_n(arr.data(), arr.size(), edges);
for (auto& [a, b, _] : arr)
++offsets[a + 1], ++offsets[b + 1];
// Convert offsets to be accumulative
std::size_t p = 0;
for (auto& i : offsets) p = i += p;
// Using offsets, get edges that vertices are part of.
std::size_t i1 = 0, now[Vertices + 1]{};
for (auto& [a, b, _] : arr)
part_of[offsets[a] + now[a]++] =
part_of[offsets[b] + now[b]++] = i1++;
}
// View of all incident edges of vertex v
constexpr auto incident_edges(std::size_t v) const {
return std::views::transform(std::span<const std::size_t>{
part_of + offsets[v], offsets[v + 1] - offsets[v] },
[&](auto i) -> const Edge& { return edges[i]; });
}
// Shortest path from vertex a, implemented using Dijkstra's Algorithm
constexpr auto shortest_path(std::size_t a) const {
constexpr auto infinity = std::numeric_limits<double>::max();
std::array<double, Vertices> dist{}; // distances
dist.fill(infinity), dist[a] = 0; // itself = 0, rest = infinity
bool checked[Vertices]{}; // Keep track of checked vertices
checked[a] = true; // No need to check itself
for (std::size_t _ = 0; _ < Vertices; ++_) {
double len = infinity; std::size_t u = 0;
for (std::size_t ux = 0; ux < Vertices; ++ux)
if (!checked[ux] && dist[ux] < len)
len = dist[ux], u = ux; // Find closest
// relax vertex u and its neighbours
for (auto& [vx, ux, len] : incident_edges(u)) {
auto& v = (vx == u ? ux : vx); // Pick other vertex as v
dist[v] = std::min(dist[v], dist[u] + len);
}
checked[u] = true; // Now we've checked this one
} // Return all the distances!
return dist;
}
// Minimum spanning tree using Prim's algorithm
constexpr auto minimum_spanning_tree() const {
constexpr double infinity = std::numeric_limits<double>::max();
StackVector<Edge, Vertices - 1> out;
bool in_w[Vertices]{}; // Keep track of checked vertices
StackVector<std::size_t, Vertices> w{}; // and available ones
w.push_back(0), in_w[0] = true; // Start with v = 0
for (std::size_t _ = 0; _ < Vertices - 1; ++_) {
double len = infinity; std::size_t v = 0, u = 0;
for (auto& vx : w) // Loop over incident edges of vertices in w
for (auto& [a, b, lenx] : incident_edges(vx)) {
auto& ux = (a == vx ? b : a); // Pick other vertex as u
// pick smallest edge whose other vertex is not in w
if (!in_w[ux] && lenx < len) len = lenx, v = vx, u = ux;
}
// Add new vertex to w, and add edge to output
w.push_back(u), in_w[u] = true; // Add connected vertex to choices
out.push_back({ v, u, len }); // Add new edge
} // Finally construct the new graph!
return UndirectedGraph<Vertices, Vertices - 1>{ std::move(out) };
}
};
struct integer {
int value = 0;
constexpr integer() = default;
constexpr integer(int v) : value(v) {};
constexpr integer(const integer&) = default;
constexpr integer(integer&&) = default;
constexpr operator int& () { return value; }
constexpr operator const int& () const { return value; }
constexpr operator int() const { return value; }
};
constexpr bool operator|(integer a, integer b) { return b % a == 0; }
constexpr bool operator|(int a, integer b) { return b % a == 0; }
constexpr bool operator|(integer a, int b) { return b % a == 0; }
constexpr integer operator*(integer a, integer b) { return a.value * b.value; }
constexpr integer operator*(int a, integer b) { return a * b.value; }
constexpr integer operator*(integer a, int b) { return a.value * b; }
constexpr integer operator+(integer a, integer b) { return a.value + b.value; }
constexpr integer operator+(int a, integer b) { return a + b.value; }
constexpr integer operator+(integer a, int b) { return a.value + b; }
template<class Ty>
class object {
public:
using value_type = Ty;
using super = object<Ty>;
protected:
class data : public value_type::data {
public:
using data_type = typename Ty::data;
template<class ...Tys> requires (!std::is_aggregate_v<typename Ty::data>) &&
requires(Tys&&...args) { new typename Ty::data(std::forward<Tys>(args)...); }
constexpr data(Tys&&...args) : Ty::data(std::forward<Tys>(args)...) {}
template<class ...Tys> requires (std::is_aggregate_v<typename Ty::data>) &&
requires(Tys&&...args) { new typename Ty::data{ std::forward<Tys>(args)... }; }
constexpr data(Tys&&...args) : Ty::data{ std::forward<Tys>(args)... } {}
private:
std::size_t ref = 1;
friend class object<value_type>;
} *me = nullptr;
public:
template<class ...Tys> requires
requires(Tys&&...args) { new data(std::forward<Tys>(args)...); }
constexpr object(Tys&&...args) : me(new data(std::forward<Tys>(args)...)) {}
constexpr object(const object& other) : me(other.me) { me->ref++; }
constexpr object(object&& other) : me(other.me) { other.me = nullptr; }
constexpr object& operator=(const object& other) { clean(), me = other.me, ++me->ref; return *this; }
constexpr object& operator=(object&& other) { clean(), me = other.me, other.me = nullptr; return *this; }
constexpr ~object() { clean(); }
constexpr data* operator->() { return me; }
constexpr const data* operator->() const { return me; }
constexpr std::size_t hash_code() const { return std::bit_cast<std::size_t>(me); }
template<class T>
constexpr bool equals(object<T> other) const {
if constexpr (std::same_as<Ty, T>) return other.me == me; else return false;
}
private:
constexpr void clean() {
if (--me->ref == 0) delete me;
}
};
//class MyClass : public object<MyClass> {
// friend class object<MyClass>;
// struct data {
// int a = 1;
// int b = 2;
// };
//public:
// constexpr MyClass() {}
// constexpr MyClass(int a, int b) : super(a, b) {}
//
// constexpr int sum() const {
// return me->a + me->b;
// }
//
// constexpr void add(MyClass other) {
// me->a += other->a;
// me->b += other->b;
// }
//};
//
//constexpr MyClass sum(MyClass a, MyClass b) {
// return { a->a + b->a, a->b + b->b };
//}
//template<typename, std::size_t> concept everything = true;
//template<class ...Tys>
//struct Tuple {
//private:
// constexpr static auto make_offsets() {
// std::size_t offset = 0;
// std::array<std::size_t, sizeof...(Tys)> res{};
// std::size_t* data = res.data();
// ((*(data++) = offset, offset += sizeof(Tys)), ...);
// return res;
// }
// constexpr static auto bytes = (sizeof(Tys) + ...);
// constexpr static std::array<std::size_t, sizeof...(Tys)> offsets = make_offsets();
//public:
// template<std::size_t I>
// using value_type = std::tuple_element_t<I, std::tuple<Tys...>>;
//
// template<class ...Args>
// constexpr Tuple(Args&&...args) {
// std::size_t offset = 0;
// ((std::construct_at(&m_Data[offset], std::forward<Args>(args)), offset += sizeof(args)), ...);
// }
//
// template<std::size_t I>
// constexpr value_type<I>& get() { return *std::bit_cast<value_type<I>*>(&m_Data[offsets[I]]); }
//
// template<std::size_t I>
// constexpr const value_type<I>& get() const { return (const value_type<I>)(m_Data[offsets[I]]); }
//
//private:
// uint8_t m_Data[bytes]{};
//};
struct Color {
float r, g, b, a;
};
//class ColorMap {
//public:
// ColorMap(std::initializer_list<
// std::pair<std::string_view, Color>> values) {
// for (auto& i : values) tree.insert(i.first, i.second);
// }
//
// struct Node {
// ~Node() { if (nodes) delete nodes; }
// std::array<Node, 26>* nodes = nullptr;
// Color value{};
//
// void insert(std::string_view str, const Color& v) {
// if (str.size() == 0) value = v;
// else {
// if (!nodes) nodes = new std::array<Node, 26>{};
// (*nodes)[str[0] - 'a'].insert(str.substr(1), v);
// }
// }
//
// Color& at(std::string_view str) {
// return str.size() == 0 ? value : (*nodes)[str[0] - 'a'].at(str.substr(1));
// }
// };
//
// Color& operator[](const std::string& str) {
// return tree.at(str);
// }
//
// Node tree;
//};
//template<std::size_t N>struct S{char v[N-1]{};constexpr S(const char(&x)[N])
//{std::copy_n(x,N-1,v);}constexpr operator std::string_view()const{return{v,N
//-1};}};template<S K,auto V>struct MapVal{constexpr static auto v=V;constexpr
//static auto k=K;};template<class...V>struct Map{using q=std::tuple_element_t
//<0,std::tuple<decltype(V::v)...>>;constexpr static auto y(std::string_view
//r){auto h=14695981039346656037ULL;for(auto c:r)h=1099511628211ULL*(h^(std::
//size_t)c);return h;}constexpr static auto s=[](){constexpr auto n=[]<auto N,
//auto f>()->std::size_t{constexpr bool c=[](){bool u[N]{};auto i=0ull;return(
//(i=y(V::k)%N,u[i]?1:(u[i]=1,0))||...);}();if constexpr(c)return f.operator()
//<N+1,f>();else return N;};return n.operator()<sizeof...(V),n>();}();constexpr
//static auto d=[](){std::array<const q*,s>res{};return((res[y(V::k)%s]=&V::v
//),...),res;}();constexpr auto&operator[](auto&e)const{return*d[y(e)%s];}};
//template<size_t N>struct S{char v[N-1];constexpr S(const char(&x)[N]){std::
//copy_n(x,N-1,v);}constexpr operator std::string_view()const{return{v,N-1};}};
//template<S K,auto V>struct Val{constexpr static auto v=V;constexpr static auto
//k=K;};template<class...V>struct Map{constexpr static auto y(std::string_view r)
//{auto h=14695981039346656037ULL;for(auto c:r)h=1099511628211ULL*(h^(size_t)c);
//return h;}constexpr static auto s=[]{constexpr auto n=[]<auto N,auto f>(){
//constexpr bool c=[]{bool u[N]{};auto i=0ull;return((i=y(V::k)%N,u[i]?1:(u[i]
//=1,0))||...);}();if constexpr(c)return f.operator()<N+1,f>();else return N;};
//return n.operator()<sizeof...(V),n>();}();constexpr static auto d=[]{std::array
//<std::tuple_element_t<0,std::tuple<decltype(V::v)...>>*,s>res{};return((res[y(V
//::k)%s]=&V::v),...),res;}();constexpr auto&at(auto&e)const{return*d[y(e)%s];}};
#include <numeric>
#include <string_view>
#include <algorithm>
#include <cstddef>
#include <utility>
template<std::size_t N> struct str_t {
char value[N - 1]{};
consteval str_t(const char(&val)[N]) { std::copy_n(val, N - 1, value); }
constexpr operator std::string_view() const { return { value, N - 1 }; }
};
template<str_t Key, auto Val> struct MapVal {
constexpr static auto val = Val;
constexpr static auto key = Key;
};
template<class... Vals> struct Map {
using value_type = std::tuple_element_t<0, std::tuple<decltype(Vals::val)...>>;
constexpr static std::size_t hash(std::string_view val) { // Constexpr str hash
return std::accumulate(val.begin(), val.end(), 14695981039346656037ULL,
[](std::size_t h, char c) { return 1099511628211ULL * (h ^ c); });
}
constexpr static auto size = [] { // Minimal size to prevent collisions
constexpr auto try_n = []<std::size_t N, auto Me>() -> std::size_t {
constexpr bool has_collision = [] { bool u[N]{}; std::size_t i = 0;
return ((i = hash(Vals::key) % N, u[i] ? 1 : (u[i] = 1, 0)) || ...);
}(); // If collision, try 1 more
if constexpr (has_collision) return Me.operator() < N + 1, Me > ();
else return N;
};
return try_n.operator() < sizeof...(Vals), try_n > ();
}();
constexpr static auto data = [] { // Construct the array with values
std::array<std::pair<const value_type*, std::string_view>, size> res{};
return ((res[hash(Vals::key) % size] = { &Vals::val, Vals::key }), ...), res;
}();
constexpr auto& at(auto& val) const {
auto& res = data[hash(val) % size];
if (res.second == val) return res.first; else throw "Value not in Map";
}
};
template<std::size_t N>
struct tag {
constexpr static auto size = N - 1;
char value[N - 1];
constexpr tag(const char(&val)[N]) : value() { std::copy_n(val, N - 1, value); }
constexpr operator std::string_view() const { return { value, N - 1 }; }
constexpr std::string_view str() const { return { value, N - 1 }; }
template<std::size_t A>
constexpr bool operator==(const tag<A>& other) const {
if constexpr (N != A) return false;
else return str() == other.str();
}
};
struct match_result {
bool match;
std::string_view remainder;
};
template<tag Name>
struct non_terminal_t {
constexpr static auto name = Name;
template<class Grammar>
constexpr static match_result match(std::string_view str) {
return Grammar::template non_terminal<non_terminal_t>::template match<Grammar>(str);
}
};
template<tag Name> constexpr auto nt = non_terminal_t<Name>{};
template<tag Name, auto Lambda = 0>
struct terminal_t {
constexpr static auto name = Name;
template<class Grammar>
constexpr static match_result match(std::string_view str) {
if constexpr (std::invocable<decltype(Lambda), std::string_view>) {
return Lambda(str); // if custom parser
}
else {
if (str.starts_with(name.str())) return { true, str.substr(name.size) };
else return { false, str };
}
}
};
template<tag Name, auto Lambda = 0> constexpr auto t = terminal_t<Name, Lambda>{};
template<class ...Tys>
struct and_link {
template<class Grammar>
constexpr static match_result match(std::string_view str) {
match_result res{ true, str };
bool match = ((res = Tys::template match<Grammar>(res.remainder), res.match) && ...);
return { match, res.remainder };
}
};
template<class ...Tys>
struct or_link {
template<class Grammar>
constexpr static match_result match(std::string_view str) {
match_result res{ true, str };
((res = Tys::template match<Grammar>(str), res.match) || ...);
return res;
}
};
template<class A, class B>
constexpr and_link<A, B> operator*(A, B) { return {}; }
template<class A, class ...B>
constexpr and_link<A, B...> operator*(A, and_link<B...>) { return {}; }
template<class A, class ...B>
constexpr and_link<B..., A> operator*(and_link<B...>, A) { return {}; }
template<class A, class B>
constexpr or_link<A, B> operator|(A, B) { return {}; }
template<class A, class ...B>
constexpr or_link<A, B...> operator|(A, or_link<B...>) { return {}; }
template<class A, class ...B>
constexpr or_link<B..., A> operator|(or_link<B...>, A) { return {}; }
template<tag Name, class Ty>
struct non_terminal_link {
constexpr static auto link = Name;
template<class Grammar>
constexpr static match_result match(std::string_view str) {
return Ty::template match<Grammar>(str);
}
};
template<class Nt>
constexpr auto operator<<=(const Nt& b, auto a) {
return non_terminal_link<Nt::name, decltype(a)>{};
}
template<class ...Tys>
struct grammar {
using start = kaixo::head_t<std::tuple<Tys...>>;
template<class Nt, class Ty, class ...Tys> struct find_nt;
template<class Nt, class Ty, class ...Tys> requires (Nt::name == Ty::link)
struct find_nt<Nt, Ty, Tys...> { using type = Ty; };
template<class Nt, class Ty, class ...Tys> requires (!(Nt::name == Ty::link))
struct find_nt<Nt, Ty, Tys...> : find_nt<Nt, Tys...> {};
template<class Nt>
using non_terminal = typename find_nt<Nt, Tys...>::type;
constexpr grammar(Tys...) {}
constexpr match_result match(std::string_view str) const {
match_result res = start::template match<grammar>(str);
return { res.remainder.size() == 0, res.remainder };
}
};
#include <list>
void trash() {
{
constexpr static auto is_digit = [](char c) { return c >= '0' && c <= '9'; };
constexpr static auto is_alpha = [](char c) { return c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z'; };
constexpr auto MUL_OP = nt<"MULOP">;
constexpr auto ADD_OP = nt<"ADDOP">;
constexpr auto POW_OP = nt<"POWOP">;
constexpr auto number = t < "number", [](std::string_view str) {
std::string_view res = str;
std::size_t size = 0;
while (res.size() > 0 && is_digit(res[0])) res = res.substr(1), ++size;
return match_result{ size > 0, res };
} > ;
constexpr auto variable = t < "variable", [](std::string_view str) {
std::string_view res = str;
std::size_t size = 0;
while (res.size() > 0 && is_alpha(res[0])) res = res.substr(1), ++size;
return match_result{ size > 0, res };
} > ;
constexpr auto PRIMARY = nt<"PRIMARY">;
constexpr auto EXPR = nt<"EXPR">;
constexpr auto TERM = nt<"TERM">;
constexpr auto FACTOR = nt<"FACTOR">;
constexpr auto S = nt<"S">;
constexpr grammar g{
S <<= EXPR,
EXPR <<= TERM * ADD_OP * EXPR | TERM,
TERM <<= FACTOR * MUL_OP * TERM | FACTOR,
FACTOR <<= PRIMARY * POW_OP * FACTOR | PRIMARY,
PRIMARY <<= number | variable | t<"("> *EXPR * t<")">,
ADD_OP <<= t<"+"> | t<"-">,
MUL_OP <<= t<"*"> | t<"/">,
POW_OP <<= t<"^">,
};
constexpr auto m = g.match("(2+2)*8^2");
}
// [1, 2, 3, 4, 5, 6, 7]
//
// 1
// 2 3
// 4 5 6 7
//
//constexpr auto agrg = cs.at("yellow");
//constexpr auto v1 = cs.at("yallow");
//ColorMap colors{
// { "red", { 1, 0, 0, 1 } },
// { "green", { 0, 1, 0, 1 } },
// { "blue", { 0, 0, 1, 1 } },
// { "yellow", { 1, 1, 0, 1 } },
//};
//auto r1 = colors["red"];
//auto r2 = colors["green"];
//auto r3 = colors["blue"];
// (1 - x)^-n = (1 + x + x^2 + ...)
// (1 - x)^-2 * (x^2 * (1 + x + x^2 + ...))^3 = (1-x)^-2*x^6*(1-x)^-3=x^6*(1-x)^-5
std::tuple values{ 0, 1.5, 2.1f, "carrot", 129, "soup" };
kaixo::tfor(values,
[](std::floating_point auto& i) {
std::cout << "floating: " << i << '\n';
},
[](std::integral auto& i) {
std::cout << "integral: " << i << '\n';
},
[](auto& i) {
std::cout << "other: " << i << '\n';
});
return 0;
constexpr integer a = 2;
constexpr integer b = 4;
constexpr integer c = 4;
constexpr integer x = 8;
constexpr integer y = 4;
static_assert(1 | a and a | 0);
static_assert((a | b) && (b | c) ? a | c : true);
static_assert((a | b) && (a | c) ? a | (b * x + c * y) : true);
constexpr auto l = []() {
int a = 0, b = 1;
kaixo::tfor<10>([&]<auto I>{
a += b;
});
return a;
};
constexpr auto res = l();
constexpr UndirectedGraph<5, 7> graph{
Edge{ 0, 1, 45. }, Edge{ 0, 2, 30. },
Edge{ 1, 2, 15. }, Edge{ 1, 3, 10. },
Edge{ 1, 4, 20. }, Edge{ 2, 3, 30. },
Edge{ 3, 4, 35. },
};
//constexpr auto sp = graph.shortest_path(0);
//constexpr auto mst = graph.minimum_spanning_tree();
//constexpr auto sp1 = mst.shortest_path(0);
//constexpr auto sp = graph.shortest_path(0);
//constexpr auto mst = graph.minimum_spanning_tree();
//constexpr auto sp1 = mst.shortest_path(0);
//using my_parser = parser<
// p<"char"> = satisfy < [](std::string_view str, auto c) -> result<char> {
// if (str.size() > 0 && str[0] == c)
// return { true, str.substr(1), str[0] };
// else return { false };
// } >,
// p<"word"> = satisfy < [](std::string_view str, std::string_view word) -> result<std::string_view> {
// bool matches = str.substr(0, std::size(word)) == word;
// if (matches) return { true, str.substr(std::size(word)), str.substr(0, std::size(word)) };
// else return { false };
// } >,
// p<"symbol"> = p<"char">('a') * p<"char">('b') * p<"char">('c') * p<"char">('d') * p<"char">('e')
//>;
//
//constexpr auto res = my_parser::parse<"symbol">("abcdef");
//constexpr auto resv = res.value.value;
constexpr auto h = heap{ 9, 39, 29, 30, 10, 69, 30, 63, 53, 2, 3, 8, 32, 11, 22 };
std::cout << h;
constexpr auto m = dfa<3, 2>{ {
{.fun{ { '0', 0 }, { '1', 1 } }, .accept = true },
{.fun{ { '0', 2 }, { '1', 0 } } },
{.fun{ { '0', 1 }, { '1', 2 } } },
} };
constexpr auto ae = m.accepts("1001");
using enum TuringMachine<>::Direction;
enum : std::size_t { _ = 2, HALT = TuringMachine<>::HALT };
TuringMachine<> machine{
{ // Instruction table for binary addition
{ { 0, 0, }, { 0, 0, Right } },
{ { 0, 1, }, { 0, 1, Right } },
{ { 0, _, }, { 1, _, Right } },
{ { 1, 0, }, { 1, 0, Right } },
{ { 1, 1, }, { 1, 1, Right } },
{ { 1, _, }, { 2, _, Left } },
{ { 2, 0, }, { 2, 1, Left } },
{ { 2, 1, }, { 3, 0, Left } },
{ { 2, _, }, { 5, _, Right } },
{ { 3, 0, }, { 3, 0, Left } },
{ { 3, 1, }, { 3, 1, Left } },
{ { 3, _, }, { 4, _, Left } },
{ { 4, 0, }, { 0, 1, Right } },
{ { 4, 1, }, { 4, 0, Left } },
{ { 4, _, }, { 0, 1, Right } },
{ { 5, 0, }, { 5, _, Right } },
{ { 5, 1, }, { 5, _, Right } },
{ { 5, _, }, { HALT, _, None } },
},
// Initial tape state
{ 0, 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, _, 1, 0, 1, 1, 1, 1, 0, 1, 1, _ }
};
for (auto& i : machine.tape)
std::cout << (i == 2 ? '_' : i == 1 ? '1' : '0');
std::cout << '\n';
while (machine.Step());
for (auto& i : machine.tape)
std::cout << (i == 2 ? '_' : i == 1 ? '1' : '0');
linked_list<int> _list;
_list.push_front(1);
_list.insert_after(_list.begin(), 2);
_list.insert_after(_list.begin(), 3);
for (auto& i : _list)
std::cout << i;
hash_map<std::string, int> _map;
_map["hello"] = 10;
_map["world"] = 12;
_map["0"] = 13;
int val1 = _map["hello"];
int val2 = _map["world"];
int val3 = _map["0"];
_map.puts("0", 1032);
_map = { { "hello", 1 }, { "world", 2 } };
for (auto& i : _map)
{
std::cout << i.first << ", " << i.second << '\n';
}
_map.erase("hello");
int val4 = _map["hello"];
array_list<int> ints;
ints.push_back(0);
ints.push_back(1);
ints.push_back(2);
ints.push_back(3);
for (auto& i : ints) {
std::cout << i << std::endl;
}
std::vector<bool> a;
a[0] = 1;
pa_function<int(int, int, int)> f = [](int a, int b, int c) { return a + b + c; };
binary bin = 913951935;
for (auto i : bin) {
std::cout << i << std::endl;
}
constexpr auto size = sizeof binary::bit;
std::array<int, 2>;
axial_array<int, 3> _a1{ 1, 2, 3, 4, 5 };
axial_array<int, 3> _a2{ 5, 4, 3, 2, 1 };
_a1.swap(_a2);
const axial_array<int, 3> _arr{
{ 1, 2, 3 },
{ 4, 5, 6, 7 },
{ 8, 9, 10, 11, 12 },
{ 13, 14, 15, 16 },
{ 17, 18, 19 },
};
for (auto [val, pos] : _arr.with_index()) {
std::cout << pos.x << ", " << pos.y << " : " << val << std::endl;
}
for (auto& val : _arr) {
std::cout << val << std::endl;
}
axial_array<int, 4> _arr2{
{ 1, 2, 3, 4 },
{ 5, 6, 7, 8, 9 },
{ 10, 11, 12, 13, 14, 15 },
{ 16, 17, 18, 19, 20, 21, 22 },
{ 23, 24, 25, 26, 27, 28 },
{ 29, 30, 31, 32, 33 },
{ 34, 35, 36, 37 },
};
axial_array<int, 5> _arr3{
{ 1, 2, 3, 4, 5 },
{ 6, 7, 8, 9, 10, 11 },
{ 12, 13, 14, 15, 16, 17, 18 },
{ 19, 20, 21, 22, 23, 24, 25, 26 },
{ 27, 28, 29, 30, 31, 32, 33, 34, 35 },
{ 36, 37, 38, 39, 40, 41, 42, 43 },
{ 44, 45, 46, 47, 48, 49, 50 },
{ 51, 52, 53, 54, 55, 56 },
{ 57, 58, 59, 60, 61 }
};
axial_array<int, 6> _arr4{
{ 1, 2, 3, 4, 5, 6 },
{ 7, 8, 9, 10, 11, 12, 13 },
{ 14, 15, 16, 17, 18, 19, 20, 21 },
{ 22, 23, 24, 25, 26, 27, 28, 29, 30 },
{ 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 },
{ 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51 },
{ 52, 53, 54, 55, 56, 57, 58, 59, 60, 61 },
{ 62, 63, 64, 65, 66, 67, 68, 69, 70 },
{ 71, 72, 73, 74, 75, 76, 77, 78 },
{ 79, 80, 81, 82, 83, 84, 85 },
{ 86, 87, 88, 89, 90, 91 }
};
for (auto [val, pos] : _arr4.with_index()) {
std::cout << pos.x << ", " << pos.y << " : " << val << std::endl;
}
for (auto& val : _arr4) {
std::cout << val << std::endl;
}
axial_array<int, 4>::key _key{ -1, 1 };
auto z = _key.z();
// _arr[{ -1, 1 }] = 2;
6 + 7 + 8 + 9 + 10 + 11 + 10 + 9 + 8 + 7 + 6;
5 + 6 + 7 + 8 + 9 + 8 + 7 + 6 + 5; // 61
4 + 5 + 6 + 7 + 6 + 5 + 4; // 37
3 + 4 + 5 + 4 + 3;
2 + 3 + 2;
constexpr int x = 5;
-(x - 1) <=> (x - 1);
2 * x - 1;
constexpr float avg = 3 * (x * x - x) + 1;
constexpr float avg1 = 3 * x * (x - 1);
_arr[{ 0, 0 }];
constexpr auto si = sizeof vec<double, 4>;
vec<double, 2> v2{ 1, 2 };
vec<double, 3> v3{ 3, 4, 5 };
vec<double, 4> v4{ 3, 4, 5, 6 };
vec<double, 2> v20{ 1, 2 };
vec<double, 2> v21{ v2 };
vec<double, 3> v30{ 1, 2, 3 };
vec<double, 3> v31{ v2, 2 };
vec<double, 3> v32{ 1, v2 };
vec<double, 3> v33{ v3 };
vec<double, 4> v40{ 1, 2, 3, 4 };
vec<double, 4> v41{ 1, v2, 2 };
vec<double, 4> v42{ v2, v2 };
vec<double, 4> v43{ v3, 2 };
vec<double, 4> v44{ 1, v3 };
vec<double, 4> v45{ v4 };
vec<double, 2> v22 = v3.xy;
vec<double, 2> v23 = v4.yz;
vec<double, 3> v34 = v4.yzw;
vec<double, 3> v35 = v4.xyz;
//vec<double, 4> v41{ 1, v2, 4 };
//vec<double, 4> v42{ v2, 3, 4 };
//vec<double, 4> v43{ v2, v2 };
//vec<double, 4> v44{ v3, 2, 3, 4 };
//vec<double, 4> v45{ 1, v3 };
v4 /= 4;
vec<double, 4> vv1{ 1, 2, 3, 4 };
vec<double, 4> vv2{ 1, 2, 3, 4 };
auto v = vv1 != vv2;
std::is_trivial_v<vec<double, 4>>;
std::is_trivially_constructible_v<vec<double, 4>>;
std::is_trivially_copyable_v<vec<double, 4>>;
std::is_trivially_copy_assignable_v<vec<double, 4>>;
std::is_trivially_copy_constructible_v<vec<double, 4>>;
std::is_trivially_default_constructible_v<vec<double, 4>>;
std::is_trivially_destructible_v<vec<double, 4>>;
std::is_trivially_move_assignable_v<vec<double, 4>>;
std::is_trivially_move_constructible_v<vec<double, 4>>;
//auto _new = v41 + vec<double, 4>{ 1, 2, 3, 4 };
//vfa.at(3) = 3;
//double& a = _new[0];
//double& b = _new[1];
//double& c = _new[2];
// double& d = _new[3];
constexpr_counter_example();
type_linker_example();
pa_function_example();
smart_tuple_example();
lambda_example();
struct_tuple_example();
}
//template<int Width, int Height>
//constexpr bool has_path1(const Screen<Width, Height>& screen) { //
// int ry = 0, y = 0, x = 0, d = 1; //
// while (ry != Height) { // Continue until the reset y is Height
// while (screen[{ x + 1, y }] == 0) ++x, d = 1; // Check ahead, if free: move and reset direction to 1
// if (x == Width - 1) break; // If after move we're at the edge: win
// if (screen[{ x, y + d }] == 0) y += d; // Check in current direction, if 0: move
// else { if (d == 1) d = -1; else y = ++ry, x = 0; } // Otherwise, if dir is 1, try other dir,
// } // Otherwise start at next y and set x back to 0
// return x == Width - 1; // Win if we're at the final x
//}
struct Point { int x, y; };
template<int Width, int Height>
struct Screen {
constexpr static auto width = Width;
constexpr static auto height = Height;
constexpr auto& operator[](Point p) { return data[p.x + p.y * Width]; }
constexpr auto& operator[](Point p) const { return data[p.x + p.y * Width]; }
std::uint8_t data[Width * Height];
};
constexpr bool check(auto& s, auto& c, Point p) {
if (p.x < 0 || p.x >= s.width || p.y < 0 || p.y >= s.height) return false;
return s[p] == 0 && c[p] == 0 && (c[p] = 1, p.x == s.width - 1
|| check(s, c, { p.x + 1, p.y }) || check(s, c, { p.x - 1, p.y })
|| check(s, c, { p.x, p.y + 1 }) || check(s, c, { p.x, p.y - 1 }));
}
constexpr bool has_path(auto& screen) {
std::decay_t<decltype(screen)> checked{};
return check(screen, checked, { 0, 0 });
}
struct everything { template<class Ty> operator Ty(); };
template<std::size_t N, class Fun, class ...Args> struct partially_invocable;
template<std::size_t N, class Fun, class ...Args> requires std::invocable<Fun, Args...>
struct partially_invocable<N, Fun, Args...> : std::bool_constant<true> {};
template<std::size_t N, class Fun, class ...Args> requires (!std::invocable<Fun, Args...>)
struct partially_invocable<N, Fun, Args...> : std::bool_constant<partially_invocable<N - 1, Fun, Args..., everything>::value> {};
template<class Fun, class ...Args> struct partially_invocable<0, Fun, Args...>
: std::bool_constant<false> {
static_assert(std::invocable<Fun, Args...>, "Incompatible arguments in function call");
};
constexpr auto my_forward(auto& val) { return std::ref(val); }
constexpr auto my_forward(auto&& val) { return std::move(val); }
template<class Lambda>
struct function : Lambda {
template<class ...Args> requires partially_invocable<20, Lambda, Args...>::value
constexpr auto operator()(Args&&...args) const {
if constexpr (std::invocable<Lambda, Args...>)
return Lambda::operator()(std::forward<Args>(args)...);
else {
auto _l = [...args = my_forward(args), fun = *this](auto&&...rem) {
return fun(args..., std::forward<decltype(rem)>(rem)...);
};
return function<decltype(_l)>{ std::move(_l) };
}
}
};
template<size_t V>
struct number {
constexpr static inline size_t value = V;
};
template<class Type>
struct wrapper {
using type = Type;
};
template<class ...Types>
struct type_group {
constexpr static inline size_t count = sizeof...(Types);
using types = std::tuple<Types...>;
};
template<size_t, class>
struct nth_type_of;
template<size_t N, template<class...> class Type, class ...Types>
struct nth_type_of<N, Type<Types...>> {
using type = typename std::tuple_element<N, std::tuple<Types...>>::type;
};
template<size_t N, class Group>
using nth_type_of_t = typename nth_type_of<N, Group>::type;
template<class Test, template<class...> class Ref>
struct is_specialization : std::false_type {};
template<template<class...> class Ref, class... Args>
struct is_specialization<Ref<Args...>, Ref> : std::true_type {};
template<class T, template<class...> class S>
concept specialization_of = is_specialization<T, S>::value;
template<class T, class ...Tys>
concept one_of = (std::same_as<Tys, T> || ...);
template<class>
struct member_signature;
template<class Return, class T, class... Args>
struct member_signature<Return(T::*)(Args...) const> {
using type = Return(Args...);
};
template<class Return, class T, class... Args>
struct member_signature<Return(T::*)(Args...)> {
using type = Return(Args...);
};
template<class T>
using member_signature_t = typename member_signature<T>::type;
template<class, class = void>
struct lambda_signature;
template<class _Fx>
struct lambda_signature<_Fx, std::void_t<decltype(&_Fx::operator())>> {
using type = member_signature<decltype(&_Fx::operator())>::type;
};
template<class T>
using lambda_signature_t = typename lambda_signature<T>::type;
template<class>
struct funptr_to_type;
template<class Return, class ...Args>
struct funptr_to_type<Return(*)(Args...)> {
using type = Return(Args...);
};
template<class T>
using funptr_to_type_t = typename funptr_to_type<T>::type;
template<class, std::size_t>
struct last_n_args;
template<class Return, class ...Args, std::size_t N>
struct last_n_args<Return(Args...), N> {
template<std::size_t... I>
static inline Return(*last_n(std::index_sequence<I...>))(std::tuple_element_t<sizeof...(Args) - N + I, std::tuple<Args...>>...) {};
using type = typename funptr_to_type<decltype(last_n(std::make_index_sequence<N>{})) > ::type;
};
template<class T, std::size_t N>
using last_n_args_t = typename last_n_args<T, N>::type;
template<class, std::size_t>
struct first_n_args;
template<class Return, typename ...Args, std::size_t N>
struct first_n_args<Return(Args...), N> {
template<std::size_t... I>
static inline Return(*first_n(std::index_sequence<I...>))(std::tuple_element_t<I, std::tuple<Args...>>...) {};
using type = typename funptr_to_type<decltype(first_n(std::make_index_sequence<N>{})) > ::type;
};
template<class T, std::size_t N>
using first_n_args_t = typename first_n_args<T, N>::type;
template<class Func, class ...Tys>
concept are_first_n = requires(typename first_n_args<Func, sizeof...(Tys)>::type func, Tys&&...tys) {
func(std::forward<Tys>(tys)...);
};
void print_struct(auto& data)
{
std::byte* _bytes = reinterpret_cast<std::byte*>(std::addressof(data));
constexpr size_t _size = sizeof(decltype(data));
constexpr size_t _bytesperrow = alignof(decltype(data));
for (int i = 0; i < _size; i++)
{
size_t index = (1 + std::floor(i / _bytesperrow)) * _bytesperrow - (1 + i % _bytesperrow);
std::bitset<8> _byte = (char8_t)_bytes[index];
std::cout << _byte << " ";
if ((i + 1) % _bytesperrow == 0)
std::cout << std::endl;
}
}
// group(operation):
// - Closure: all results of operation -> group
// - Identity: XI = IX = X
// - Inverse: AB = BA = I
// - associativity: (ab)c = a(bc) for all a,b,c
// if:
// ab = ba for all a,b: commutative (Abelian)
#include <utility>
struct Data {
int value = 10;
int Test() { return Test(*this); }
static int Test(Data self) {
return self.value;
}
};
struct clvalue_test {
template<class Ty>
constexpr operator const Ty& ();
};
struct rvalue_test {
template<class Ty>
constexpr operator Ty && ();
};
struct lvalue_test {
template<class Ty> requires (!std::is_const_v<Ty>)
constexpr operator Ty& ();
};
constexpr auto value_tester = [](auto fun) {
enum { VALUE, CLVALUE, RVALUE, LVALUE, OTHER };
if constexpr (std::invocable<decltype(fun), rvalue_test>
&& std::invocable<decltype(fun), lvalue_test>) return VALUE;
else if constexpr (std::invocable<decltype(fun), clvalue_test>) return CLVALUE;
else if constexpr (std::invocable<decltype(fun), rvalue_test>) return RVALUE;
else if constexpr (std::invocable<decltype(fun), lvalue_test>) return LVALUE;
else return OTHER;
};
int test(const int&) { return 0; };
template<class Ty>
struct storage {
Ty value;
constexpr operator Ty() const { return value; }
};
template<class Ty> storage(Ty&)->storage<Ty&>;
template<class Ty> storage(const Ty&)->storage<const Ty&>;
template<class Ty> storage(Ty&&)->storage<Ty>;
//template<class F, class ...Tys>
//constexpr auto curry(F&& f, Tys&&... ps) {
// if constexpr (std::invocable<F, Tys...>) {
// return f(std::forward<Tys>(ps)...);
// } else {
// return [f, ...ps = storage{ std::forward<Tys>(ps) }]
// <class Arg, class ...Args>(Arg&& arg, Args&&... args) {
// return curry(f, ps..., storage{ std::forward<Arg>(arg) },
// storage{ std::forward<Args>(args) }...);
// };
// }
//}
//template<class F, class ...Tys>
//constexpr auto curry(F&& f, Tys&&... ps) {
// if constexpr (std::invocable<F, Tys...>) {
// return f(std::forward<Tys>(ps)...);
// } else {
// return [f, ...ps = storage{ std::forward<Tys>(ps) }]
// <class Arg, class ...Args>(Arg&& arg, Args&&... args) {
// return curry(f, ps.value..., std::forward<Arg>(arg),
// std::forward<Args>(args)...);
// };
// }
//}
#include <utility>
#include <tuple>
template<class F, class ...Tys>
constexpr auto curry(F&& f, Tys&&... ps) {
constexpr bool invocable = requires{ f(std::forward<Tys>(ps)...); };
if constexpr (invocable) {
return f(std::forward<Tys>(ps)...);
}
else {
return[f = std::move(f), ps = std::forward_as_tuple(std::forward<Tys>(ps)...)]
<class Arg, class ...Args>(Arg && arg, Args&&... args) {
return[f = std::move(f), tuple = std::tuple_cat(std::move(ps), std::tuple<Arg&&, Args&&...>(
std::forward<Arg>(arg), std::forward<Args>(args)...))]
<std::size_t ...Is>(std::index_sequence<Is...>) {
return curry(std::move(f), std::get<Is>(tuple)...);
}(std::make_index_sequence<sizeof...(Tys) + 1 + sizeof...(Args)>{});
};
}
}
//template<class F, class ...Tys>
//constexpr auto curry(F&& f, Tys&&... ps) {
// if constexpr (std::invocable<F, Tys...>) {
// return f(std::forward<Tys>(ps)...);
// } else {
// return [f, ...ps = ps]
// <class Arg, class ...Args>(Arg&& arg, Args&&... args) {
// return curry(f, ps..., std::forward<Arg>(arg),
// std::forward<Args>(args)...);
// };
// }
//}
constexpr int add(int a, int b, int c, int d) {
return a + b + c + d;
}
#include <iostream>
struct Ataa {
int value;
Ataa(int value = 1) : value(value) { std::cout << "Construct\n"; }
Ataa(const Ataa& a) : value(a.value) { std::cout << "Copy\n"; }
Ataa(Ataa&& a) : value(a.value) { std::cout << "Move\n"; }
~Ataa() { std::cout << "Destroy\n"; }
};
int add2(const Ataa& a, Ataa& b, Ataa& c, Ataa&& d) {
return a.value + b.value + c.value + d.value;
}
#include <vector>
#include <array>
template<class Ty, std::size_t Size>
struct finite_group {
constexpr finite_group(std::array<Ty, Size> elements, Ty(*op)(Ty, Ty))
: elements(elements), op(op) {
}
constexpr const Ty& identity() const {
for (auto& i : elements) {
bool done = true;
for (auto& j : elements) {
if (op(i, j) != j) {
done = false;
break;
}
}
if (done) return i;
}
}
std::array<Ty, Size> elements{};
Ty(*op)(Ty, Ty) = nullptr;
};
#include <numeric>
#include <ranges>
template<class Ty, std::size_t N>
struct permutation {
std::array<Ty, N> data{};
constexpr permutation(std::array<Ty, N>&& data) : data(std::move(data)) {}
constexpr permutation(std::ranges::range auto&& a) {
std::ranges::copy(std::move(a), data.begin());
}
constexpr permutation operator*(const permutation& other) const {
return std::views::transform(other.data, [&](auto& v) { return data[v]; });
}
};
template<class Ty, std::size_t N>
struct cycle_notation {
std::array<std::pair<Ty, Ty>, N> data{};
constexpr cycle_notation() {}
constexpr cycle_notation(std::array<std::pair<Ty, Ty>, N>&& data) : data(data) {}
constexpr cycle_notation(auto&& a) {
std::ranges::copy(std::move(a), data.begin());
}
template<class ...Tys> requires (std::convertible_to<Ty, Tys> && ...)
constexpr auto operator()(Tys&&... vals) const
-> cycle_notation<Ty, N + sizeof...(Tys)> {
std::array<std::pair<Ty, Ty>, N + sizeof...(Tys)> res{};
std::copy(data.begin(), data.end(), res.begin());
std::array<Ty, sizeof...(Tys)> in{ static_cast<Ty>(vals)... };
for (std::size_t i = 0; i < sizeof...(Tys); ++i)
res[i + N] = { in[i], in[(i + 1) % (sizeof...(Tys))] };
return { res };
}
constexpr operator permutation<Ty, N>() const {
std::array<Ty, N> res{};
for (auto& i : data) {
res[i.first] = i.second;
}
return { std::move(res) };
}
};
template<class Ty, class ...Tys>
constexpr cycle_notation<Ty, sizeof...(Tys) + 1> cycle(Ty&& ty, Tys&&... tys) {
return cycle_notation<Ty, 0>{}(std::forward<Ty>(ty), std::forward<Tys>(tys)...);
}
template<class Ty> struct json_type {};
template<std::size_t N> struct json_tag {
char value[N - 1];
constexpr json_tag(const char(&val)[N]) : value() { std::copy_n(val, N - 1, value); }
constexpr operator std::string_view() const { return { value, N - 1 }; }
constexpr std::string_view str() const { return { value, N - 1 }; }
};
struct json {
constexpr json(auto...) {}
constexpr auto operator[](auto) const { return 0; }
};
template<json_tag Name, class Ty>
struct json_member;
constexpr json_tag jm_x{ "x" };
template<class Ty> struct json_member<jm_x, Ty> { Ty x; };
constexpr json_tag jm_y{ "y" };
template<class Ty> struct json_member<jm_y, Ty> { Ty y; };
template<class Ty>
struct vec2 :
json_member<"x", Ty>,
json_member<"y", Ty> {};
template<json_tag Name>
struct json_assign {
template<class Ty>
constexpr auto operator=(Ty&& val) const {
return json_member<Name, Ty>{ std::forward<Ty>(val) };
}
};
//template<json_tag Name>
//constexpr auto operator""m() {
// return json_assign<Name>{};
//}
constexpr std::size_t ipow(std::size_t x, std::size_t p) {
if (p == 0) return 1ull;
else if (p == 1) return x;
else {
const auto tmp = ipow(x, p / 2);
if (p % 2 == 0) return tmp * tmp;
else return x * tmp * tmp;
}
}
constexpr std::size_t modpow(std::size_t base, std::size_t power, std::size_t mod) {
auto view = std::views::iota(0ull, sizeof(power))
| std::views::transform([](auto v) { return (1ull << v); })
| std::views::filter([=](auto v) { return power & v; });
auto op = [=](auto res, auto c) { return (res * (ipow(base, c) % mod)) % mod; };
return std::accumulate(view.begin(), view.end(), 1ull, op);
}
template <class T, class Tuple, size_t... Is>
constexpr T construct_from_tuple(Tuple& tuple, std::index_sequence<Is...>) {
return T{ std::get<Is>(tuple)... };
}
template <class T, class Tuple>
constexpr T construct_from_tuple(Tuple& tuple) {
return construct_from_tuple<T>(tuple,
std::make_index_sequence<std::tuple_size_v<std::decay_t<Tuple>>>{}
);
}
// String literal wrapper for template parameter
template<std::size_t N>
struct tag {
constexpr static auto size = N - 1;
char value[N - 1];
constexpr tag(std::string_view view) : value() { std::copy_n(view.data(), N - 1, value); }
constexpr tag(const char(&val)[N]) : value() { std::copy_n(val, N - 1, value); }
constexpr operator std::string_view() const { return { value, N - 1 }; }
constexpr std::string_view str() const { return { value, N - 1 }; }
constexpr bool operator==(const tag& other) const { return str() == other.str(); }
template<std::size_t M> requires (M != N)
constexpr bool operator==(const tag<M>&) const { return false; }
};
template<bool Parsed, tag Remainder, class Ty = std::string_view>
struct result_type {
using value_type = Ty;
constexpr static auto parsed = Parsed;
constexpr static auto remainder = Remainder;
Ty value{ };
};
struct dud {};
template<class ...Parsers>
struct and_parser_t {
constexpr static auto size = sizeof...(Parsers);
template<class Grammar, tag Str>
using value_type = typename decltype(parse<Grammar, Str>())::template value_type;
template<std::size_t I>
using parser = std::tuple_element_t<I, std::tuple<Parsers...>>;
template<class Grammar, tag Str>
consteval static auto parse() {
return parse_i<0, Grammar, Str>();
}
template<std::size_t I, class Grammar, tag Str>
consteval static auto parse_i() {
if constexpr (I == size) return result_type<true, Str, std::tuple<>>{ {} };
else {
constexpr auto res = parser<I>::template parse<Grammar, Str>();
if constexpr (res.parsed) {
constexpr auto recu = parse_i<I + 1, Grammar, res.remainder>();
if constexpr (!recu.parsed) return result_type<false, Str>{};
else {
constexpr auto tuple = std::tuple_cat(std::tuple{ res.value }, recu.value);
return result_type<true, recu.remainder, decltype(tuple)>{ std::move(tuple) };
}
}
else return result_type<false, Str>{};
}
}
};
template<class ...Parsers>
struct or_parser_t {
constexpr static auto size = sizeof...(Parsers);
template<class Grammar, tag Str>
using value_type = typename decltype(parse<Grammar, Str>())::template value_type;
template<std::size_t I>
using parser = std::tuple_element_t<I, std::tuple<Parsers...>>;
template<class Grammar, tag Str>
consteval static auto parse() {
return parse_i<0, Grammar, Str>();
}
template<std::size_t I, class Grammar, tag Str>
consteval static auto parse_i() {
if constexpr (I == size) return result_type<false, Str>{ };
else {
constexpr auto res = parser<I>::template parse<Grammar, Str>();
if constexpr (res.parsed) return res;
else return parse_i<I + 1, Grammar, Str>();
}
}
};
template<tag Name, class Parser>
struct named_parser {
constexpr static auto name = Name;
using parser = Parser;
template<class Grammar, tag Str>
using value_type = Parser::template value_type<Grammar, Str>;
template<class Parser, tag Str>
consteval static auto parse() {
return parser::template parse<Parser, Str>();
}
};
template<tag Name, auto Lambda = 0>
struct token {
constexpr static auto name = Name;
template<class Grammar, tag Str>
using value_type = typename decltype(parse<Grammar, Str>())::value_type;
template<class Grammar, tag Str>
consteval static auto parse() {
if constexpr (std::same_as<int, decltype(Lambda)>) {
if constexpr (Str.str().starts_with(Name.str())) {
constexpr auto size = Str.size - Name.size;
if constexpr (size == 0)
return result_type<true, "\0", value_type<Grammar, Str>>{ Name.str() };
else {
constexpr auto new_str = Str.str().substr(Name.size);
return result_type < true, tag<size + 1>{ new_str }, value_type<Grammar, Str >> { Name.str() };
}
}
else return result_type<false, Str>{};
}
else return Lambda.template operator() < Grammar, Str > ();
}
};
template<tag Name>
struct non_terminal {
constexpr static auto name = Name;
template<class Grammar, tag Str>
using value_type = std::decay_t<decltype(Grammar::template get<Name>)>::template value_type<Grammar, Str>;
template<class Parser>
consteval auto operator<<=(Parser) const { return named_parser<Name, Parser>{}; }
template<class Grammar, tag Str>
consteval static auto parse() {
return Grammar::template get<Name>.template parse<Grammar, Str>();
}
};
template<class Ty, class Parser>
struct typed_parser {
using type = Ty;
using parser = Parser;
template<class Grammar, tag Str>
using value_type = typename decltype(parse<Grammar, Str>())::template value_type<Grammar, Str>;
template<class Grammar, tag Str>
consteval static auto parse() {
constexpr auto res = Parser::template parse<Grammar, Str>();
if constexpr (res.parsed)
return result_type<true, res.remainder, type>{ construct(res.value) };
else return result_type<false, Str>{};
}
template<class Ty>
consteval static auto construct(const Ty& value) {
if constexpr (kaixo::specialization<Ty, std::tuple>)
return construct_from_tuple<type>(value);
else return type{ value };
}
};
template<auto ...Parsers>
struct parser {
template<tag Name>
static constexpr auto get_impl(auto& P, auto&... Ps) {
if constexpr (std::decay_t<decltype(P)>::name == Name) return P;
else return get_impl<Name>(Ps...);
}
template<tag Name>
static constexpr auto get = get_impl<Name>(Parsers...);
template<tag Name, tag Str>
consteval static auto parse() {
return get<Name>.template parse<parser, Str>();
}
};
template<class A, class B> requires (!kaixo::specialization<A, and_parser_t> && !kaixo::specialization<B, and_parser_t>)
consteval auto operator*(A, B) { return and_parser_t<A, B>{}; }
template<class A, class ...Bs> requires (!kaixo::specialization<A, and_parser_t>)
consteval auto operator*(and_parser_t<Bs...>, A) { return and_parser_t<Bs..., A>{}; }
template<class A, class ...Bs> requires (!kaixo::specialization<A, and_parser_t>)
consteval auto operator*(A, and_parser_t<Bs...>) { return and_parser_t<A, Bs...>{}; }
template<class A, class B> requires (!kaixo::specialization<A, or_parser_t> && !kaixo::specialization<B, or_parser_t>)
consteval auto operator|(A, B) { return or_parser_t<A, B>{}; }
template<class A, class ...Bs> requires (!kaixo::specialization<A, or_parser_t>)
consteval auto operator|(or_parser_t<Bs...>, A) { return or_parser_t<Bs..., A>{}; }
template<class A, class ...Bs> requires (!kaixo::specialization<A, or_parser_t>)
consteval auto operator|(A, or_parser_t<Bs...>) { return or_parser_t<A, Bs...>{}; }
template<class Ty>
struct type_t {
using type = Ty;
};
template<class Ty>
constexpr auto t = type_t<Ty>{};
template<class A, class B>
consteval auto operator^(type_t<A>, B) {
return typed_parser<A, B>{};
}
#include <vector>
#include <iostream>
#include <numbers>
namespace kaixo {
enum class AngleType { Degrees, Radians };
namespace detail {
using namespace std::numbers;
template<AngleType A, AngleType B, class Out, class In>
constexpr decltype(auto) convert(const In& v) {
if constexpr (A == B) {
if constexpr (std::same_as<std::decay_t<In>, std::decay_t<Out>>) return v;
else return static_cast<Out>(v);
}
else if (A == AngleType::Radians) return static_cast<Out>(180. * v / pi_v<double>);
else if (A == AngleType::Degrees) return static_cast<Out>(pi_v<double> *v / 180.);
}
}
template<class Ty, AngleType Vy = AngleType::Radians>
class AngleBase {
public:
constexpr AngleBase() {}
template<std::convertible_to<Ty> T>
constexpr AngleBase(const T& v) : m_Value(static_cast<Ty>(v)) {}
template<std::convertible_to<Ty> T, AngleType V>
constexpr AngleBase(AngleBase<T, V> v) : m_Value(detail::convert<V, Vy, Ty>(v.value())) {}
constexpr decltype(auto) degrees() { return detail::convert<Vy, AngleType::Degrees, Ty>(value()); }
constexpr decltype(auto) radians() { return detail::convert<Vy, AngleType::Radians, Ty>(value()); }
constexpr decltype(auto) degrees() const { return detail::convert<Vy, AngleType::Degrees, Ty>(value()); }
constexpr decltype(auto) radians() const { return detail::convert<Vy, AngleType::Radians, Ty>(value()); }
constexpr Ty& value() { return m_Value; }
constexpr Ty const& value() const { return m_Value; }
constexpr explicit operator AngleBase<Ty, AngleType::Degrees>() const { return degrees(); }
constexpr explicit operator AngleBase<Ty, AngleType::Radians>() const { return radians(); }
constexpr explicit operator Ty& () { return value(); }
constexpr explicit operator Ty const& () const { return value(); }
protected:
Ty m_Value{};
};
template<class Ty> using Degrees = AngleBase<Ty, AngleType::Degrees>;
template<class Ty> using Radians = AngleBase<Ty, AngleType::Radians>;
}
template<class Ty>
concept range_type = requires (Ty a, Ty b) {
{ a == b } -> std::convertible_to<bool>;
{ ++a } -> std::convertible_to<Ty>;
{ a + b } -> std::convertible_to<Ty>;
{ a = a + b } -> std::convertible_to<Ty>;
};
template<range_type Ty>
struct range {
using value_type = Ty;
using reference = Ty&;
using const_reference = const Ty&;
using difference_type = std::ptrdiff_t;
using size_type = std::size_t;
class iterator {
public:
using value_type = Ty;
using reference = Ty&;
using const_reference = const Ty&;
using difference_type = std::ptrdiff_t;
using size_type = std::size_t;
constexpr iterator(Ty value, const range* r) : m_Value(value), m_Range(r) {}
constexpr iterator& operator++() { m_Value = m_Value + m_Range->difference; return *this; }
constexpr Ty const& operator*() const { return m_Value; }
constexpr bool operator==(const iterator& other) const { return other.m_Value == m_Value; }
private:
Ty m_Value;
const range* m_Range;
};
using const_iterator = iterator;
constexpr iterator begin() const { return { a, this }; }
constexpr iterator end() const { return { b, this }; }
Ty a{};
Ty b{};
Ty difference{ [] { Ty v{}; return ++v; }() };
};
template<class Ty> range(Ty, Ty)->range<Ty>;
template<class Ty> range(Ty, Ty, Ty)->range<Ty>;
#include <map>
struct State {
void* data{ nullptr };
template<class Ty> void assign() {
if constexpr (sizeof(Ty) <= sizeof data)
new (&data) Ty{};
else data = new Ty;
}
template<class Ty> Ty const& get() const {
if constexpr (sizeof(Ty) <= sizeof data)
return *static_cast<Ty*>((void*)&data);
else return *static_cast<Ty*>(data);
}
template<class Ty> Ty& get() {
if constexpr (sizeof(Ty) <= sizeof data)
return *static_cast<Ty*>((void*)&data);
else return *static_cast<Ty*>(data);
}
template<class Ty> void clean() {
delete static_cast<Ty*>(data);
}
};
template<class Ty>
struct StateId {
std::string_view id;
constexpr const char* get() const { return id.data(); }
constexpr bool operator==(std::string_view view) const {
return id.data() == view.data();
}
constexpr friend bool operator==(std::string_view view, const StateId& id) {
return id.id.data() == view.data();
}
};
struct StateListener {
virtual void update(std::string_view id, State& state) = 0;
};
class Object {
public:
template<class Ty>
Ty get(const StateId<Ty>& id) const {
if (!m_States.contains(id.get()))
return {};
auto const& _state = m_States.at(id.get());
return _state.get<Ty>();
}
template<class Ty, std::convertible_to<Ty> T>
Ty set(const StateId<Ty>& id, T&& val) {
if (!m_States.contains(id.get()))
m_States[id.get()].assign<Ty>();
auto& _state = m_States[id.get()];
_state.get<Ty>() = std::forward<T>(val);
for (auto& i : m_Listeners)
i->update(id.id, _state);
return _state.get<Ty>();
}
template<std::derived_from<StateListener> Ty>
void link(Ty& l) {
m_Listeners.push_back(dynamic_cast<StateListener*>(&l));
}
private:
std::map<const char*, State> m_States{};
std::vector<StateListener*> m_Listeners;
};
constexpr StateId<bool> Hovering{ "Hovering" };
constexpr StateId<bool> Focused{ "Focused" };
constexpr StateId<int> Pressed{ "Pressed" };
struct MyObject : public Object, public StateListener {
MyObject() {
link(*this);
}
void update(std::string_view id, State& state) override {
if (Hovering == id) {
std::cout << state.get<bool>() << "\n";
}
return;
}
};
template<class Ty> struct delegate;
template<class R, class ...A>
struct delegate<R(A...)> {
template<class Obj>
constexpr delegate(Obj& o, R(Obj::* fun)(A...))
: object_ptr(static_cast<void*>(&o)),
fun_ptr(mem_method<Obj>) {
new (&storage) mem_storage<Obj>{ fun };
}
template<std::invocable<A...> Lambda>
requires (sizeof(Lambda) <= sizeof(void*)
&& !std::convertible_to<Lambda, R(*)(A...)>)
constexpr delegate(Lambda lambda)
: fun_ptr(small_lambda_method<Lambda>) {
new (&object_ptr) Lambda{ std::move(lambda) };
}
template<std::invocable<A...> Lambda>
requires (sizeof(Lambda) > sizeof(void*)
&& !std::convertible_to<Lambda, R(*)(A...)>)
constexpr delegate(Lambda lambda)
: fun_ptr(big_lambda_method<Lambda>),
cleanup(cleanup_method<Lambda>) {
object_ptr = new Lambda{ std::move(lambda) };
}
template<std::invocable<A...> Lambda>
requires (std::convertible_to<Lambda, R(*)(A...)>)
constexpr delegate(Lambda lambda)
: fun_ptr(fun_ptr_method) {
new (&storage) (R(*)(A...)){ (R(*)(A...)) lambda };
}
template<class Obj>
constexpr delegate& operator=(std::pair<Obj&, R(Obj::*)(A...)> a) {
clean();
object_ptr = static_cast<void*>(&a.first);
new (&storage) mem_storage<Obj>{ a.second };
fun_ptr = mem_method<Obj>;
return *this;
}
template<std::invocable<A...> Lambda>
requires (sizeof(Lambda) <= sizeof(void*)
&& !std::convertible_to<Lambda, R(*)(A...)>)
constexpr delegate& operator=(Lambda lambda) {
clean();
fun_ptr = small_lambda_method<Lambda>;
new (&object_ptr) Lambda{ std::move(lambda) };
return *this;
}
template<std::invocable<A...> Lambda>
requires (sizeof(Lambda) > sizeof(void*)
&& !std::convertible_to<Lambda, R(*)(A...)>)
constexpr delegate& operator=(Lambda lambda) {
clean();
fun_ptr = big_lambda_method<Lambda>;
object_ptr = new Lambda{ std::move(lambda) };
cleanup = cleanup_method<Lambda>;
return *this;
}
template<std::invocable<A...> Lambda>
requires (std::convertible_to<Lambda, R(*)(A...)>)
constexpr delegate& operator=(Lambda lambda) {
clean();
fun_ptr = fun_ptr_method;
new (&storage) (R(*)(A...)){ (R(*)(A...)) lambda };
return *this;
}
template<std::convertible_to<A> ...Args>
constexpr R operator()(Args...args) {
return (*fun_ptr)(object_ptr, storage, args...);
}
constexpr ~delegate() { clean(); }
private:
template<class Obj>
struct mem_storage {
R(Obj::* fun)(A...);
};
struct dummy {};
constexpr static auto mem_fun_size = sizeof(mem_storage<dummy>);
void* object_ptr = nullptr;
R(*fun_ptr)(void*, uint8_t(&)[mem_fun_size], A...);
uint8_t storage[mem_fun_size]{};
void(*cleanup)(void*) = nullptr;
constexpr void clean() {
if (cleanup) {
cleanup(object_ptr);
cleanup = nullptr;
}
}
template<class Obj>
constexpr static void cleanup_method(void* obj) {
delete static_cast<Obj*>(obj);
}
template<class Obj>
constexpr static R mem_method(void* o, uint8_t(&fun)[mem_fun_size], A...args) {
return (static_cast<Obj*>(o)->*reinterpret_cast<mem_storage<Obj>*>(&fun)->fun)(args...);
}
template<class Lambda>
constexpr static R small_lambda_method(void* o, uint8_t(&fun)[mem_fun_size], A...args) {
return (*reinterpret_cast<Lambda*>(&o))(args...);
}
template<class Lambda>
constexpr static R big_lambda_method(void* o, uint8_t(&fun)[mem_fun_size], A...args) {
return (*static_cast<Lambda*>(o))(args...);
}
constexpr static R fun_ptr_method(void* o, uint8_t(&fun)[mem_fun_size], A...args) {
return (*reinterpret_cast<R(**)(A...)>(&fun))(args...);
}
};
struct Type {
int thing(int a) {
std::cout << a << '\n';
return a;
}
};
struct Functor {
int operator()(int a) { return a + 1; }
};
struct Functor2 {
int m1 = 10;
int m2 = 20;
int m3 = 30;
int operator()(int a) { return a + m1 + m2 + m3; }
};
#include <functional>
template<std::size_t N, class CharType = char>
struct string_literal {
constexpr static std::size_t npos = std::basic_string_view<CharType>::npos;
using view_type = std::basic_string_view<CharType>;
using size_type = std::size_t;
using difference_type = std::ptrdiff_t;
using value_type = CharType;
using reference = CharType&;
using const_reference = const CharType&;
using pointer = CharType*;
using const_pointer = const CharType*;
class const_iterator {
public:
using iterator_category = std::random_access_iterator_tag;
using size_type = std::size_t;
using difference_type = std::ptrdiff_t;
using value_type = const CharType;
using reference = const CharType&;
constexpr const_iterator(const const_iterator&) = default;
constexpr const_iterator(const_iterator&&) = default;
constexpr const_iterator& operator=(const const_iterator&) = default;
constexpr const_iterator& operator=(const_iterator&&) = default;
constexpr const_iterator() : m_Ptr(nullptr) {}
constexpr const_iterator(const CharType* ptr) : m_Ptr(ptr) {}
constexpr reference operator*() const { return *m_Ptr; }
constexpr const_iterator& operator+=(difference_type d) { m_Ptr += d; return *this; }
constexpr const_iterator& operator-=(difference_type d) { m_Ptr -= d; return *this; }
constexpr const_iterator& operator++() { ++m_Ptr; return *this; }
constexpr const_iterator& operator--() { --m_Ptr; return *this; }
constexpr const_iterator operator++(int) { auto _c = *this; ++m_Ptr; return _c; }
constexpr const_iterator operator--(int) { auto _c = *this; --m_Ptr; return _c; }
constexpr reference operator[](difference_type d) const { return m_Ptr[d]; }
constexpr auto operator<=>(const const_iterator& other) const = default;
friend constexpr const_iterator operator+(difference_type a, const const_iterator& b) { return { a + b.m_Ptr }; }
friend constexpr const_iterator operator+(const const_iterator& a, difference_type b) { return { a.m_Ptr + b }; }
friend constexpr const_iterator operator-(difference_type a, const const_iterator& b) { return { a - b.m_Ptr }; }
friend constexpr const_iterator operator-(const const_iterator& a, difference_type b) { return { a.m_Ptr - b }; }
friend constexpr difference_type operator-(const const_iterator& a, const const_iterator& b) { return a.m_Ptr - b.m_Ptr; }
protected:
const CharType* m_Ptr;
};
class iterator : public const_iterator {
public:
using iterator_category = std::random_access_iterator_tag;
using size_type = std::size_t;
using difference_type = std::ptrdiff_t;
using value_type = CharType;
using reference = CharType&;
constexpr iterator(const iterator&) = default;
constexpr iterator(iterator&&) = default;
constexpr iterator& operator=(const iterator&) = default;
constexpr iterator& operator=(iterator&&) = default;
constexpr iterator() : const_iterator(nullptr) {}
constexpr iterator(CharType* ptr) : const_iterator(ptr) {}
constexpr reference operator*() const { return *const_cast<CharType*>(this->m_Ptr); }
constexpr iterator& operator+=(difference_type d) { this->m_Ptr += d; return *this; }
constexpr iterator& operator-=(difference_type d) { this->m_Ptr -= d; return *this; }
constexpr iterator& operator++() { ++this->m_Ptr; return *this; }
constexpr iterator& operator--() { --this->m_Ptr; return *this; }
constexpr iterator operator++(int) { auto _c = *this; ++this->m_Ptr; return _c; }
constexpr iterator operator--(int) { auto _c = *this; --this->m_Ptr; return _c; }
constexpr reference operator[](difference_type d) const { return const_cast<CharType*>(this->m_Ptr)[d]; }
constexpr auto operator<=>(const iterator& other) const = default;
friend constexpr iterator operator+(difference_type a, const iterator& b) { return { a + b.m_Ptr }; }
friend constexpr iterator operator+(const iterator& a, difference_type b) { return { a.m_Ptr + b }; }
friend constexpr iterator operator-(difference_type a, const iterator& b) { return { a - b.m_Ptr }; }
friend constexpr iterator operator-(const iterator& a, difference_type b) { return { a.m_Ptr - b }; }
friend constexpr difference_type operator-(const iterator& a, const iterator& b) { return a.m_Ptr - b.m_Ptr; }
};
using reverse_iterator = std::reverse_iterator<iterator>;
using const_reverse_iterator = std::reverse_iterator<const_iterator>;
constexpr ~string_literal() = default;
constexpr string_literal() = default;
constexpr string_literal(const CharType(&data)[N]) {
std::copy_n(data, N, m_Data);
}
constexpr string_literal(string_literal&&) = default;
constexpr string_literal(const string_literal&) = default;
constexpr string_literal& operator=(string_literal&&) = default;
constexpr string_literal& operator=(const string_literal&) = default;
template<std::size_t I> requires (I < N)
constexpr string_literal& operator=(const CharType(&data)[I]) {
std::copy_n(data, I, m_Data);
}
constexpr iterator begin() { return { m_Data }; }
constexpr iterator end() { return { m_Data + size() }; }
constexpr const_iterator begin() const { return { m_Data }; }
constexpr const_iterator end() const { return { m_Data + size() }; }
constexpr const_iterator cbegin() const { return begin(); }
constexpr const_iterator cend() const { return end(); }
constexpr reverse_iterator rbegin() { return end(); }
constexpr reverse_iterator rend() { return begin(); }
constexpr const_reverse_iterator rbegin() const { return end(); }
constexpr const_reverse_iterator rend() const { return begin(); }
constexpr const_reverse_iterator crbegin() const { return end(); }
constexpr const_reverse_iterator crend() const { return begin(); }
constexpr reference at(size_type d) { return m_Data[d]; }
constexpr const_reference at(size_type d) const { return m_Data[d]; }
constexpr reference operator[](size_type d) { return m_Data[d]; }
constexpr const_reference operator[](size_type d) const { return m_Data[d]; }
constexpr reference front() { return m_Data[0]; }
constexpr const_reference front() const { return m_Data[0]; }
constexpr reference back() { return m_Data[size() - 1]; }
constexpr const_reference back() const { return m_Data[size() - 1]; }
constexpr pointer data() { return m_Data; }
constexpr const_pointer data() const { return m_Data; }
constexpr const_pointer c_str() const { return m_Data; }
constexpr size_type size() const { return N - 1; }
constexpr size_type length() const { return size(); }
constexpr size_type max_size() const { return size(); }
constexpr bool empty() const { return false; }
constexpr void swap(string_literal& other) { std::swap(data(), other.data()); }
constexpr view_type view() const { return { data(), size() }; }
constexpr operator view_type() const { return { data(), size() }; }
template<std::size_t I>
constexpr auto operator==(const string_literal<I, CharType>& other) const {
if constexpr (I != N) return false;
else return view() == other.view();
};
template<std::size_t I>
constexpr auto operator<=>(const string_literal<I, CharType>& other) const { return view() <=> other.view(); }
constexpr auto starts_with(view_type t) const { return view().starts_with(t); }
constexpr auto ends_with(view_type t) const { return view().ends_with(t); }
constexpr auto substr(size_type pos = 0, size_type count = npos) const { return view().substr(pos, count); }
constexpr auto find(std::string_view t, size_type pos = 0) const { return view().find(t, pos); }
constexpr auto rfind(view_type t, size_type pos = 0) const { return view().rfind(t, pos); }
constexpr auto find_first_of(view_type t, size_type pos = 0) const { return view().find_first_of(t, pos); }
constexpr auto find_first_not_of(view_type t, size_type pos = 0) const { return view().find_first_not_of(t, pos); }
constexpr auto find_last_of(view_type t, size_type pos = 0) const { return view().find_last_of(t, pos); }
constexpr auto find_last_not_of(view_type t, size_type pos = 0) const { return view().find_last_not_of(t, pos); }
CharType m_Data[N]{};
};
#include <array>
template<string_literal Str>
struct meta {
constexpr static auto definition = Str;
struct member {
std::string_view name{};
};
constexpr static std::size_t member_count = []() {
std::size_t _count = 0;
for (auto& i : definition) if (i == ';') ++_count;
return _count;
}();
constexpr static std::array<member, member_count> members = []() {
std::array<member, member_count> _members{};
auto _view = definition.view();
std::size_t _index = 0;
while (true) {
auto _end = _view.find_first_of(';');
if (_end == decltype(definition)::npos) break;
auto _sub = _view.substr(0, _end);
auto _last = _sub.find_last_of(' ');
auto _name = _sub.substr(_last + 1);
_members[_index++].name = _name;
_view = _view.substr(_end + 1);
}
return _members;
}();
};
template<auto Ptr, string_literal Name>
struct Member {
constexpr static auto ptr = Ptr;
constexpr static auto name = Name;
};
template<class Type>
struct Meta {
template<class Ty>
struct Member {
Type::Ty* ptr;
std::string_view name;
};
};
#define META(Name) struct Name { \
using Type = Name; \
template<auto Ptr, string_literal Name> \
struct Variable { \
using type = kaixo::member_type_t<decltype(Ptr)>; \
constexpr static auto _n_Type = 0; \
constexpr static auto ptr = Ptr; \
constexpr static auto name = Name.view(); \
}; \
template<class> struct SignaturedFunction; \
struct GeneralFunction { \
virtual void _n_Link() = 0; \
}; \
template<class R, class ...As> \
struct SignaturedFunction<R(As...)> : GeneralFunction { \
virtual void _n_Link() override {}; \
constexpr SignaturedFunction(R(*fun)(Type&, As...)) : fun(fun) {} \
R(*fun)(Type&, As...); \
}; \
struct FunctionBase { \
const GeneralFunction* fun; \
template<class Ret, class ...Args> \
constexpr Ret invoke(Type& v, Args...args) const { \
auto _self = dynamic_cast<const Type::template \
SignaturedFunction<Ret(Args...)>*>(fun); \
if (!_self) throw "Wrong call!"; \
else return _self->fun(v, args...); \
} \
template<class Ret, class ...Args> \
constexpr Ret invoke(const Type& v, Args...args) const { \
auto _self = dynamic_cast<const Type::template \
SignaturedFunction<Ret(Args...)>*>(fun); \
if (!_self) throw "Wrong call!"; \
else return _self->fun(v, args...); \
} \
template<class Sig> \
constexpr bool invocable() const { \
auto _self = dynamic_cast<const Type::template \
SignaturedFunction<Sig>*>(fun); \
return _self != nullptr; \
} \
}; \
struct GeneralVariable { \
virtual void _n_Link() = 0; \
}; \
template<class Ty> \
struct TypedVariable : GeneralVariable { \
virtual void _n_Link() override {}; \
constexpr TypedVariable(Ty Type::* var) : var(var) {} \
Ty Type::* var; \
}; \
struct VariableBase { \
const GeneralVariable* var; \
template<class Ty> \
constexpr Ty& as(Type& v) const { \
auto _self = dynamic_cast<const Type::template \
TypedVariable<Ty>*>(var); \
if (!_self) throw "Wrong call!"; \
else return v.*(_self->var); \
} \
template<class Ty> \
constexpr const Ty& as(const Type& v) const { \
auto _self = dynamic_cast<const Type::template \
TypedVariable<Ty>*>(var); \
if (!_self) throw "Wrong call!"; \
else return v.*(_self->var); \
} \
template<class Ty> \
constexpr bool is() const { \
auto _self = dynamic_cast<const Type::template \
TypedVariable<Ty>*>(var); \
return _self != nullptr; \
} \
}; \
template<auto Ptr, string_literal Name> \
struct Function { \
constexpr static auto _n_Type = 1; \
constexpr static auto ptr = Ptr; \
constexpr static auto name = Name.view(); \
using signature = kaixo::signature_t<decltype(ptr)>; \
using return_type = kaixo::function_return_t<signature>; \
using argument_types = kaixo::function_args_t<signature>; \
template<class ...Args> \
constexpr static decltype(auto) invoke(Type& v, Args&&...as) { \
return (v.*ptr)(std::forward<Args>(as)...); \
} \
template<class ...Args> \
constexpr static decltype(auto) invoke(const Type& v, Args&&...as) { \
return (v.*ptr)(std::forward<Args>(as)...); \
} \
}; \
template<auto Ptr, string_literal Name> \
requires (std::is_member_object_pointer_v<decltype(Ptr)>) \
struct Function<Ptr, Name> { \
constexpr static auto _n_Type = 1; \
constexpr static auto ptr = Ptr; \
constexpr static auto name = Name.view(); \
template<class ...Args> \
constexpr static decltype(auto) invoke(Type& v, Args&&...as) { \
return (v.*ptr)(std::forward<Args>(as)...); \
} \
template<class ...Args> \
constexpr static decltype(auto) invoke(const Type& v, Args&&...as) { \
return (v.*ptr)(std::forward<Args>(as)...); \
} \
}; \
template<std::size_t I> struct _n_Members { using type = void; }; \
constexpr static std::size_t _n_Start = __COUNTER__; \
#define END_META \
template<std::size_t I> using _n_Members_t = _n_Members<I>::type; \
constexpr static std::size_t _n_End = __COUNTER__; \
constexpr static std::size_t _n_Member_count = _n_End - _n_Start - 1; \
constexpr static std::size_t variable_count = \
[]<std::size_t ...Is>(std::index_sequence<Is...>){ \
std::size_t _count = 0; \
((Type::template _n_Members_t<Is>::_n_Type == 0 \
? (++_count, true) : false), ...); \
return _count; \
}(std::make_index_sequence<Type::_n_Member_count>{}); \
constexpr static std::size_t function_count = \
[]<std::size_t ...Is>(std::index_sequence<Is...>){ \
std::size_t _count = 0; \
((Type::template _n_Members_t<Is>::_n_Type == 1 \
? (++_count, true) : false), ...); \
return _count; \
}(std::make_index_sequence<Type::_n_Member_count>{}); \
template<std::size_t I> using variable = decltype( \
[](){ \
constexpr auto try_n = [] \
<std::size_t N, std::size_t M>(auto& s) { \
if constexpr (std::same_as<void, Type::template _n_Members_t<N>>) return 0; \
else if constexpr (Type::template _n_Members_t<N>::_n_Type == 0) { \
if constexpr (M == 0) return Type::template _n_Members_t<N>{}; \
else return s.operator()<N + 1, M - 1>(s); \
} else return s.operator()<N + 1, M>(s); \
}; \
return try_n.operator()<0, I>(try_n); \
}()); \
template<std::size_t I> using function = decltype( \
[](){ \
constexpr auto try_n = [] \
<std::size_t N, std::size_t M>(auto& s) { \
if constexpr (std::same_as<void, Type::template _n_Members_t<N>>) return 0; \
else if constexpr (Type::template _n_Members_t<N>::_n_Type == 1) { \
if constexpr (M == 0) return Type::template _n_Members_t<N>{}; \
else return s.operator()<N + 1, M - 1>(s); \
} else return s.operator()<N + 1, M>(s); \
}; \
return try_n.operator()<0, I>(try_n); \
}()); \
template<std::size_t I, class ...As> \
constexpr static decltype(auto) _n_Fun_type_t(Type & v, As ...as) { \
return (v.*(Type::template function<I>::ptr))(as...); \
}; \
template<std::size_t I> \
constexpr static auto _n_Fun_types = \
Type::template SignaturedFunction<kaixo::minimal_signature_t \
<decltype(Type::template function<I>::ptr)>>{ _n_Fun_type_t<I> }; \
constexpr static auto functions() { \
return []<std::size_t ...Is>(std::index_sequence<Is...>) { \
return std::array<FunctionBase, Type::function_count>{ \
dynamic_cast<const GeneralFunction*>(&Type::template _n_Fun_types<Is>)... }; \
}(std::make_index_sequence<Type::function_count>{}); \
} \
template<std::size_t I> \
constexpr static auto _n_Var_types = \
Type::template TypedVariable<typename Type::template variable<I>::type>{ \
Type::template variable<I>::ptr }; \
constexpr static auto variables() { \
return []<std::size_t ...Is>(std::index_sequence<Is...>) { \
return std::array<VariableBase, Type::variable_count>{ \
dynamic_cast<const GeneralVariable*>(&Type::template _n_Var_types<Is>)... }; \
}(std::make_index_sequence<Type::variable_count>{}); \
} \
};
#define VAR(ty, name, init) ty name init; \
template<> struct _n_Members<__COUNTER__ - _n_Start - 1> { using type = Variable<&Type::name, #name>; };
#define FUN(pre, name, def) pre name def; \
template<> struct _n_Members<__COUNTER__ - _n_Start - 1> { using type = Function<&Type::name, #name>; };
#define TFUN(pre, name, def) pre name def; \
struct _twrapper_##name { \
constexpr _twrapper_##name(Type& self) : self(self) {} \
Type& self; \
template<class ...Args> requires \
requires(Type& self, Args&&...args) { \
{ self.name(std::forward<Args>(args)...) }; \
} \
constexpr decltype(auto) operator()(Args&&...args) const { \
return self.name(std::forward<Args>(args)...); \
} \
} _fun_##name{ *this }; \
template<> struct _n_Members<__COUNTER__ - _n_Start - 1> { using type = Function<&Type::_fun_##name, #name>; };
//META(Carrot)
// VAR(int, a, { 3 })
// VAR(double, b, { 31 })
// FUN(constexpr double, add, (int a, int b) const { return a + b; })
//END_META
template<class Ty, std::size_t N>
struct NamedArray : std::array<Ty, N> {
constexpr Ty& operator[](std::size_t i) {
return std::array<Ty, N>::operator[](i);
}
constexpr const Ty& operator[](std::size_t i)const {
return std::array<Ty, N>::operator[](i);
}
constexpr bool has(std::string_view name) const {
for (auto& e : *this) {
if (e.name() == name) return true;
}
return false;
}
constexpr Ty& operator[](std::string_view name) {
for (auto& e : *this) {
if (e.name() == name) return e;
}
throw std::exception("Bad access");
}
constexpr const Ty& operator[](std::string_view name) const {
for (auto& e : *this) {
if (e.name() == name) return e;
}
throw std::exception("Bad access");
}
};
template<auto Ptr, string_literal Name>
struct Function {
constexpr static auto ptr = Ptr;
constexpr static auto name = Name.view();
using signature = kaixo::signature_t<decltype(ptr)>;
using return_type = kaixo::function_return_t<signature>;
using argument_types = kaixo::function_args_t<signature>;
template<class ...Args>
constexpr static decltype(auto) invoke(Type& v, Args&&...as) {
return (v.*ptr)(std::forward<Args>(as)...);
}
template<class ...Args>
constexpr static decltype(auto) invoke(const Type& v, Args&&...as) {
return (v.*ptr)(std::forward<Args>(as)...);
}
};
template<auto Lambda, string_literal Name>
requires (kaixo::has_fun_op<decltype(Lambda)>)
struct Function<Lambda, Name> {
constexpr static auto ptr = Lambda;
constexpr static auto name = Name.view();
template<class ...Args>
constexpr static decltype(auto) invoke(Type& v, Args&&...as) {
return (v.*ptr)(std::forward<Args>(as)...);
}
template<class ...Args>
constexpr static decltype(auto) invoke(const Type& v, Args&&...as) {
return (v.*ptr)(std::forward<Args>(as)...);
}
};
template<class ...Funs>
struct Functions {
using Type = kaixo::member_class_t<std::decay_t<decltype(
kaixo::template head_t<std::tuple<Funs...>>::ptr)>>;
constexpr static std::size_t count = sizeof...(Funs);
template<class> struct SignaturedFunction;
struct GeneralFunction {
constexpr GeneralFunction(std::string_view view)
: name(view) {}
std::string_view name{};
virtual void _n_Link() = 0;
};
template<class R, class ...As>
struct SignaturedFunction<R(As...)> : GeneralFunction {
virtual void _n_Link() override {};
constexpr SignaturedFunction(R(*fun)(Type&, As...), std::string_view name)
: fun(fun), GeneralFunction(name) {}
R(*fun)(Type&, As...);
};
struct FunctionBase {
const GeneralFunction* fun;
constexpr auto name() const { return fun->name; }
template<class Ret, class ...Args>
constexpr Ret invoke(const Type& v, Args...args) const {
auto _self = dynamic_cast<const SignaturedFunction<Ret(Args...)>*>(fun);
if (!_self) throw "Wrong call!"; else return _self->fun(*const_cast<Type*>(&v), args...);
}
template<class Sig>
constexpr bool invocable() const {
auto _self = dynamic_cast<const SignaturedFunction<Sig>*>(fun);
return _self != nullptr;
}
};
template<std::size_t I> using function = std::tuple_element_t<I, std::tuple<Funs...>>;
template<std::size_t I, class ...As>
constexpr static decltype(auto) _n_Fun_type_t(Type& v, As ...as) {
return (v.*(function<I>::ptr))(as...);
};
template<std::size_t I>
constexpr static auto _n_Fun_types = SignaturedFunction<kaixo::minimal_signature_t<
decltype(Functions::template function<I>::ptr)>>{
&_n_Fun_type_t<I>, Functions::template function<I>::name };
constexpr static auto functions() {
return[]<std::size_t ...Is>(std::index_sequence<Is...>) {
return NamedArray<FunctionBase, count>{
dynamic_cast<const GeneralFunction*>(&_n_Fun_types<Is>)... };
}(std::make_index_sequence<count>{});
}
};
template<>
struct Functions<> {
constexpr static std::size_t count = 0;
constexpr static auto functions() {
return;
}
};
template<auto Ptr, string_literal Name>
struct Variable {
using type = std::decay_t<kaixo::member_type_t<decltype(Ptr)>>;
constexpr static auto ptr = Ptr;
constexpr static auto name = Name.view();
};
template<class ...Vars>
struct Variables {
using Type = kaixo::member_class_t<std::decay_t<decltype(
kaixo::template head_t<std::tuple<Vars...>>::ptr)>>;
constexpr static std::size_t count = sizeof...(Vars);
struct GeneralVariable {
constexpr GeneralVariable(std::string_view view)
: name(view) {}
std::string_view name{};
virtual void _n_Link() = 0;
};
template<class Ty>
struct TypedVariable : GeneralVariable {
virtual void _n_Link() override {};
constexpr TypedVariable(Ty Type::* var, std::string_view name)
: var(var), GeneralVariable(name) {}
Ty Type::* var;
};
struct VariableBase {
const GeneralVariable* var;
constexpr auto name() const { return var->name; }
template<class Ty>
constexpr Ty& as(Type& v) const {
auto _self = dynamic_cast<const TypedVariable<Ty>*>(var);
if (!_self) throw "Wrong call!"; else return v.*(_self->var);
}
template<class Ty>
constexpr Ty Type::* as() const {
auto _self = dynamic_cast<const TypedVariable<Ty>*>(var);
if (!_self) throw "Wrong call!"; else return _self->var;
}
template<class Ty>
constexpr const Ty& as(const Type& v) const {
auto _self = dynamic_cast<const TypedVariable<Ty>*>(var);
if (!_self) throw "Wrong call!"; else return v.*(_self->var);
}
template<class Ty>
constexpr bool is() const {
auto _self = dynamic_cast<const TypedVariable<Ty>*>(var);
return _self != nullptr;
}
};
template<std::size_t I> using variable = std::tuple_element_t<I, std::tuple<Vars...>>;
template<std::size_t I>
constexpr static auto _n_Var_types = TypedVariable<Variables::template variable<I>::type>{
Variables::template variable<I>::ptr, Variables::template variable<I>::name };
constexpr static auto variables() {
return[]<std::size_t ...Is>(std::index_sequence<Is...>) {
return NamedArray<VariableBase, count>{
dynamic_cast<const GeneralVariable*>(&_n_Var_types<Is>)... };
}(std::make_index_sequence<count>{});
}
};
template<class Vars, class Funs>
struct Reflect : Vars, Funs {};
struct Potato {
int a = 3;
double b = 4;
constexpr double add(int a, int b) const { return a + b; }
using reflect = Reflect<
Variables<
Variable<&Potato::a, "a">,
Variable<&Potato::b, "b">
>,
Functions<
Function<&Potato::add, "add">
>
>;
};
template<class Ty>
struct PointBase {
Ty x;
Ty y;
};
template<class Ty>
struct Point : PointBase<Ty>, Reflect<
Variables<
Variable<&PointBase<Ty>::x, "x">,
Variable<&PointBase<Ty>::y, "y">
>, Functions<>
> {};
template<class Ty>
constexpr auto distance2(auto& p1, auto& p2) {
constexpr auto v1 = std::decay_t<decltype(p1)>::variables();
constexpr auto v2 = std::decay_t<decltype(p2)>::variables();
if constexpr (v1.has("x") && v1.has("y") && v2.has("x") && v2.has("y")) {
constexpr auto x1 = v1["x"];
constexpr auto x2 = v2["x"];
constexpr auto y1 = v1["y"];
constexpr auto y2 = v2["y"];
if constexpr (x1.is<Ty>() && x2.is<Ty>() && y1.is<Ty>() && y2.is<Ty>()) {
constexpr auto x1v = x1.as<Ty>();
constexpr auto x2v = x2.as<Ty>();
constexpr auto y1v = y1.as<Ty>();
constexpr auto y2v = y2.as<Ty>();
return
(p1.*x1v - p2.*x2v) * (p1.*x1v - p2.*x2v) +
(p1.*y1v - p2.*y2v) * (p1.*y1v - p2.*y2v);
}
else return;
}
else return;
}
struct Data {
int a = 10;
int b = 20;
};
template<auto Ptr>
struct Thing {};
struct dynamic_tuple {
constexpr dynamic_tuple() = default;
template<class ...Args>
constexpr dynamic_tuple(Args&&...args) {
constexpr std::size_t _size = ((sizeof(Args)) + ...);
data.reserve(_size);
(push_back(args), ...);
}
template<class Ty>
constexpr std::decay_t<Ty>& push_back(Ty&& ty) {
return emplace_back<std::decay_t<Ty>>(std::forward<Ty>(ty));
}
template<class Ty, class...Args>
constexpr Ty& emplace_back(Args&& ...args) {
info.push_back(entry_info{ &typeid(Ty), (info.empty() ? 0ull : info.back().offset) + sizeof(Ty) });
data.resize(data.size() + sizeof(Ty));
return *std::construct_at((Ty*)(&data.at(data.size() - sizeof(Ty))), std::forward<Args>(args)...);
}
struct entry {
uint8_t* value;
const type_info* type;
template<class Ty> constexpr bool is() const { return *type == typeid(Ty); }
template<class Ty> constexpr Ty& as() const { return *(Ty*)(value); }
template<class Ty> constexpr operator Ty& () const { return *(Ty*)(value); }
};
struct const_entry {
const uint8_t* value;
const type_info* type;
template<class Ty> constexpr bool is() const { return *type == typeid(Ty); }
template<class Ty> constexpr const Ty& as() const { return *(const Ty*)(value); }
template<class Ty> constexpr operator const Ty& () const { return *(const Ty*)(value); }
};
constexpr entry operator[](std::size_t i) { return { data.data() + info[i].offset, info[i + 1].type }; }
constexpr const_entry operator[](std::size_t i) const { return { data.data() + info[i].offset, info[i + 1].type }; }
struct entry_info {
const type_info* type;
std::size_t offset;
};
struct iterator {
std::vector<entry_info>::iterator info;
uint8_t* data;
constexpr iterator& operator++() { ++info; return *this; }
constexpr entry operator*() { return { data + info[-1].offset, info->type }; }
constexpr bool operator==(const iterator& o) const { return info == o.info; }
};
constexpr iterator begin() { return { info.begin() + 1, data.data() }; };
constexpr iterator end() { return { info.end(), data.data() }; };
std::vector<entry_info> info{ { 0, 0 } };
std::vector<uint8_t> data{};
};
struct uv_entry {
constexpr virtual ~uv_entry() = default;
};
template<class Ty>
struct uv_typed_entry : uv_entry {
Ty value{};
template<class ...Args>
constexpr uv_typed_entry(Args&&...args)
: value(std::forward<Args>(args)...) {}
};
class uv_element {
uv_entry* value{ nullptr };
public:
constexpr uv_element(uv_entry* value) : value(value) {}
constexpr uv_element() = default;
constexpr ~uv_element() { delete value; }
constexpr uv_element(uv_element&& o) noexcept
: value(o.value) {
o.value = nullptr;
}
constexpr uv_element& operator=(uv_element&& o) noexcept {
value = o.value, o.value = nullptr;
return *this;
}
constexpr uv_element(const uv_element& o) = delete;
constexpr uv_element& operator=(const uv_element& o) = delete;
template<class Ty> requires (!std::same_as<uv_element, std::decay_t<Ty>>)
constexpr uv_element& operator=(Ty&& arg) {
assign<std::decay_t<Ty>>(std::forward<Ty>(arg));
return *this;
}
template<class Ty, class ...Args>
constexpr void assign(Args&&...args) {
delete value;
value = dynamic_cast<uv_entry*>(
new uv_typed_entry<Ty>{ std::forward<Args>(args)... });
}
template<class Ty>
constexpr Ty& as() {
if (auto _self = dynamic_cast<uv_typed_entry<Ty>*>(value))
return _self->value;
else throw;
}
template<class Ty>
constexpr const Ty& as() const {
if (auto _self = dynamic_cast<const uv_typed_entry<Ty>*>(value))
return _self->value;
else throw;
}
template<class Ty>
constexpr explicit operator Ty& () {
if (auto _self = dynamic_cast<uv_typed_entry<Ty>*>(value))
return _self->value;
else throw;
}
template<class Ty>
constexpr explicit operator const Ty& () const {
if (auto _self = dynamic_cast<const uv_typed_entry<Ty>*>(value))
return _self->value;
else throw;
}
template<class Ty>
constexpr bool is() const {
return dynamic_cast<const uv_typed_entry<Ty>*>(value) != nullptr;
}
};
class untyped_vector : std::vector<uv_element> {
using parent = std::vector<uv_element>;
public:
using value_type = parent::value_type;
using reference = parent::reference;
using const_reference = parent::const_reference;
using pointer = parent::pointer;
using const_pointer = parent::const_pointer;
using size_type = parent::size_type;
using difference_type = parent::difference_type;
using iterator = parent::iterator;
using const_iterator = parent::const_iterator;
using reverse_iterator = parent::reverse_iterator;
using const_reverse_iterator = parent::const_reverse_iterator;
template<class ...Args>
constexpr untyped_vector(Args&& ...args) {
parent::reserve(sizeof...(Args));
(this->push_back(std::forward<Args>(args)), ...);
}
template<class Ty>
constexpr void push_back(Ty&& arg) {
this->emplace_back<std::decay_t<Ty>>(std::forward<Ty>(arg));
}
template<class Ty, class ...Args>
constexpr Ty& emplace_back(Args&&...args) {
auto _ptr = new uv_typed_entry<Ty>(std::forward<Args>(args)...);
parent::emplace_back(dynamic_cast<uv_entry*>(_ptr));
return _ptr->value;
}
using parent::operator=;
using parent::assign;
using parent::at;
using parent::operator[];
using parent::front;
using parent::back;
using parent::data;
using parent::begin;
using parent::cbegin;
using parent::rbegin;
using parent::crbegin;
using parent::end;
using parent::cend;
using parent::rend;
using parent::crend;
using parent::empty;
using parent::size;
using parent::max_size;
using parent::reserve;
using parent::capacity;
using parent::shrink_to_fit;
using parent::clear;
using parent::erase;
using parent::pop_back;
using parent::resize;
using parent::swap;
};
template<class ...Args>
struct Struct {
constexpr static std::size_t bytes = (sizeof(Args) + ...);
template<std::size_t I>
constexpr static std::size_t member_size = sizeof(std::tuple_element_t<I, std::tuple<Args...>>);
template<std::size_t I>
using member_type = std::tuple_element_t<I, std::tuple<Args...>>;
template<std::size_t I> struct member_t {
constexpr static std::size_t value = member_size<I - 1> +member_t<I - 1>::value;
using type = member_type<I>;
};
template<> struct member_t<0> { constexpr static std::size_t value = 0; };
template<std::size_t I> constexpr static auto member = member_t<I>{};
template<class Member>
constexpr auto operator->*(const Member&) const -> Member::type const& {
return *(const Member::type*)(&data[Member::value]);
}
uint8_t data[bytes]{};
};
template<class DataClass>
concept data_class = requires() {
typename DataClass::access_tier;
typename DataClass::dependencies;
};
template<std::size_t Level>
struct tier : std::integral_constant<std::size_t, Level> {};
template<class Me, class ...Tys>
struct dependency_selector {
static_assert(((Tys::access_tier::value
<= Me::access_tier::value) && ...), "Invalid Dependency");
};
template<class Me>
struct dependency_selector<Me> {};
class Cache {
public:
using access_tier = tier<0>;
using dependencies = dependency_selector<Cache>;
};
class TransitionsTradeBlocker {
public:
using access_tier = tier<2>;
using dependencies = dependency_selector<TransitionsTradeBlocker, Cache>;
};
class SettingsManager {
public:
using access_tier = tier<1>; // vvv Won't work vvv
using dependencies = dependency_selector<SettingsManager, Cache, TransitionsTradeBlocker>;
};
template<class Ty, std::size_t I>
using greater_than = Ty;
#include <source_location>
namespace contracts {
template<std::size_t I>
struct arg_t {
constexpr static auto value = I;
constexpr static decltype(auto) get(auto& vals) {
return std::get<value>(vals);
}
};
template<auto Lambda>
struct condition_t {
constexpr static auto value = Lambda;
constexpr static decltype(auto) get(auto& vals) {
return value(vals);
}
};
template<class A, class B>
constexpr auto operator>(A, B) {
return condition_t < [](auto& vals) -> decltype(auto) {
return A::get(vals) > B::get(vals);
} > {};
}
template<class A, class B>
constexpr auto operator+(A, B) {
return condition_t < [](auto& vals) -> decltype(auto) {
return A::get(vals) + B::get(vals);
} > {};
}
template<std::size_t I>
constexpr auto arg = arg_t<I>{};
template<auto Condition, class ...Args>
constexpr void pre(Args&&...args) {
const std::tuple _tuple{ std::forward<Args>(args)... };
if (!Condition.get(_tuple))
throw std::runtime_error("Condition was not satisfied.");
}
}
using namespace contracts;
constexpr auto difference(auto a, auto b) {
pre<(arg<0> > arg<1>)>(a, b);
return a - b;
}
void aoinenoa() {
auto resae = difference(11, 10);
using my_struct = Struct<int, double, float>;
my_struct inst{};
auto vale = inst->*my_struct::member<1>;
constexpr auto as = my_struct::member<1>;
constexpr Point<double> p1{ 1, 2 };
constexpr Point<double> p2{ 2, 4 };
dynamic_tuple tpl{ 1, 10. };
tpl.emplace_back<float>(20.f);
for (auto i : tpl) {
if (i.is<double>()) std::cout << "double: " << i.as<double>() << '\n';
else if (i.is<int>()) std::cout << "int: " << i.as<int>() << '\n';
else if (i.is<float>()) std::cout << "float: " << i.as<float>() << '\n';
}
if (tpl[0].is<int>()) std::cout << "int: " << tpl[0].as<int>() << '\n';
if (tpl[1].is<double>()) std::cout << "double: " << tpl[1].as<double>() << '\n';
if (tpl[2].is<float>()) std::cout << "float: " << tpl[2].as<float>() << '\n';
//constexpr auto var = Carrot::variables()[0];
//if constexpr (var.is<int>()) {
// int& value = var.as<int>(cal);
//}
//auto& fun = Carrot::functions()[0];
//if (fun.invocable<double(int, int)>()) {
// double res = fun.invoke<double>(cal, 1, 1);
//}
Type thing;
delegate<int(int)> d{ thing, &Type::thing };
int res = d(1.f);
constexpr auto aeff = sizeof(delegate<int(int)>);
constexpr auto girn = sizeof(std::function<int(int)>);
d = [](int a) { return a + 1; };
res = d(1);
int a1 = 10;
int a2 = 20;
d = [a1, a2](int a) { return a + a1 + a2; };
res = d(1);
int b1 = 10;
int b2 = 20;
int b3 = 30;
d = [b1, b2, b3](int a) { return a + b1 + b2 + b3; };
res = d(1);
d = Functor{};
res = d(1);
d = Functor2{};
res = d(1);
MyObject obj;
obj.set(Hovering, true);
bool v = obj.get(Hovering);
obj.set(Hovering, false);
return 0;
}
struct HeapChecker {
static inline std::vector<void*> allocated{};
constexpr static void add(void* ptr) {
allocated.push_back(ptr);
}
constexpr static std::size_t check(void* ptr) {
return std::erase(allocated, ptr);
}
};
struct RefCounted {
};
struct Object {
constexpr Object()
: refs(HeapChecker::check(this)) {}
constexpr virtual ~Object() = default;
constexpr void remember() { if (refs) ++refs; }
constexpr void forget() { if (refs && --refs == 0) delete this; }
static void* operator new(std::size_t size) {
void* _ptr = ::operator new(size);
HeapChecker::add(_ptr);
return _ptr;
}
private:
std::size_t refs;
};
template<std::derived_from<Object> Ty>
struct Ptr {
constexpr Ptr() = default;
template<std::derived_from<Ty> T>
constexpr Ptr(Ptr<T>&& val)
: value(val.value) {
val.value = nullptr;
}
template<std::derived_from<Ty> T>
constexpr Ptr(const Ptr<T>& val)
: value(val.value) {
if (value) value->remember();
}
template<std::derived_from<Ty> T>
constexpr Ptr(T*&& val) : value(val) {}
template<std::derived_from<Ty> T>
constexpr Ptr(T*& val) : value(val) { val->remember(); }
template<std::derived_from<Ty> T>
constexpr Ptr& operator=(Ptr<T>&& val) {
if (value) value->forget();
value = val.value;
val.value = nullptr;
return *this;
}
template<std::derived_from<Ty> T>
constexpr Ptr& operator=(const Ptr<T>& val) {
if (value) value->forget();
value = val.value;
if (value) value->remember();
return *this;
}
template<std::derived_from<Ty> T>
constexpr Ptr& operator=(T*&& val) {
if (value) value->forget();
value = val;
return *this;
}
template<std::derived_from<Ty> T>
constexpr Ptr& operator=(T*& val) {
if (value) value->forget();
value = val;
if (value) value->remember();
return *this;
}
constexpr ~Ptr() { if (value) value->forget(); }
constexpr Ty* operator->() { return value; }
constexpr const Ty* operator->() const { return value; }
constexpr Ty& operator*() { return *value; }
constexpr const Ty& operator*() const { return *value; }
private:
Ty* value = nullptr;
template<std::derived_from<Object>>
friend struct Ptr;
};
//namespace kaixo {
// template<class> struct delegate;
// template<class Ret, class ...Args>
// struct delegate<Ret(Args...)> {
// using return_type = Ret;
// using argument_types = pack<Args...>;
// using function_type = Ret(Args...);
// private:
// using stored_function_type = Ret(uint8_t*, Args...);
// template<class Ty> // Check if type is small (8 bytes)
// constexpr static bool small =
// sizeof(std::decay_t<Ty>) <= sizeof(uint8_t) * 8;
// template<class Ty> // Check if type convertible to fun ptr
// constexpr static bool to_ptr = // (usually lambda)
// std::convertible_to<std::decay_t<Ty>, function_type*>;
//
// // Small functor
// struct small_functor {
// constexpr small_functor(Functor&& functor)
// : functor(std::forward<Functor>(functor)){}
//
// std::decay_t<Functor> functor{};
//
// template<class Functor>
// static return_type call(uint8_t* data, Args...args) {
// small_functor* _data = std::bit_cast<small_functor*>(data);
// return (_data->functor)(args...);
// }
// };
//
// public:
//
// template<std::invocable<Args...> Functor>
// requires (to_ptr<Functor>)
// consteval delegate(const Functor& functor) {
// function_type* _ptr = functor;
// }
//
// template<std::invocable<Args...> Functor>
// requires (small<Functor> && !to_ptr<Functor>)
// constexpr delegate(Functor&& functor)
// : ptr(&small_functor<Functor>::call) {
// small_functor<Functor> const* _data = static_cast<small_functor<Functor>*>(static_cast<void*>(data));
//
// //small_functor<Functor> const* _data = std::bit_cast<small_functor<Functor> const*>(&data[0]);
// std::construct_at(_data, std::forward<Functor>(functor));
// }
//
// constexpr return_type operator()(Args...args) {
// return (*ptr)(data, args);
// }
//
// uint8_t data[8]{};
// stored_function_type* ptr = nullptr;
// };
//}
#include "pack_utils.hpp"
#include "utils.hpp"
#include "string_literal.hpp"
using namespace kaixo;
namespace kaixo {
template<class Ty>
concept has_dependencies = requires () { typename Ty::dependencies; };
template<class>
struct dependencies_t { using type = pack<>; };
template<has_dependencies Ty>
struct dependencies_t<Ty> { using type = typename Ty::dependencies; };
template<class Ty>
using dependencies = typename dependencies_t<Ty>::type;
template<class Ty, class Var>
concept has_name = Ty::name == Var::name;
template<string_literal Name, class Ty>
struct named_value {
constexpr static auto name = Name;
using value_type = Ty;
Ty value;
};
template<string_literal Name>
struct var_t {
using dependencies = pack<var_t>;
using definitions = pack<var_t>;
constexpr static string_literal name = Name;
template<class Ty> constexpr auto operator=(Ty&& value) const {
return named_value<name, Ty>{ std::forward<Ty>(value) };
}
};
template<string_literal Name> constexpr auto var = var_t<Name>{};
template<class Ty> concept is_var = requires() { Ty::name; };
template<class ...Args>
struct named_tuple : std::tuple<Args...> {
using std::tuple<Args...>::tuple;
template<class Var> constexpr decltype(auto) get() const {
// Filter the arguments by name and get the first one, then get the
// index of that type in the pack, so we can use the std::get function
constexpr auto filter = []<has_name<Var>>{};
using named_value_type = pack<Args...>::template filter<filter>::head;
constexpr std::size_t index = pack<Args...>::template index<named_value_type>;
return std::get<index>(*this).value;
}
};
template<class ...Args> named_tuple(Args...)->named_tuple<Args...>;
template<class Lambda, class Dependencies>
struct expression : Lambda, Dependencies {
using dependencies = Dependencies::unique;
template<class ...Args>
constexpr decltype(auto) operator()(Args&&... vals) const {
return Lambda::operator()(named_tuple{ std::forward<Args>(vals)... });
}
};
template<class Ty>
concept is_expression = specialization<Ty, expression>;
template<class Ty, class ...Args>
constexpr decltype(auto) use(Ty& v, const named_tuple<Args...>& vals) {
if constexpr (is_expression<Ty>) return v(vals);
else if constexpr (is_var<Ty>) return vals.get<Ty>();
else return v;
}
template<class A, class B>
concept valid_op = is_var<std::decay_t<A>> || is_expression<std::decay_t<A>>
|| is_var<std::decay_t<B>> || is_expression<std::decay_t<B>>;
#define def_op(op) \
template<class Av, class Bv> requires valid_op<Av, Bv> \
constexpr auto operator op(Av&& a, Bv&& b) { \
using A = std::decay_t<Av>; \
using B = std::decay_t<Bv>; \
if constexpr (is_var<A> && !is_var<B>) { \
return expression{ [ \
b = std::forward<Bv>(b) \
] <class...Args>(const named_tuple<Args...>&vals) { \
return vals.get<A>() op use(b, vals); \
}, concat<dependencies<A>, dependencies<B>>{} }; \
} else if constexpr (!is_var<A> && is_var<B>) { \
return expression{ [ \
a = std::forward<Av>(a) \
] <class...Args>(const named_tuple<Args...>&vals) { \
return use(a, vals) op vals.get<B>(); \
}, concat<dependencies<A>, dependencies<B>>{} }; \
} else if constexpr (is_var<A> && is_var<B>) { \
return expression{ [ \
] <class...Args>(const named_tuple<Args...>&vals) { \
return vals.get<A>() op vals.get<B>(); \
}, concat<dependencies<A>, dependencies<B>>{} }; \
} else { \
return expression{ [ \
a = std::forward<Av>(a), b = std::forward<Bv>(b) \
] <class...Args>(const named_tuple<Args...>&vals) { \
return use(a, vals) op use(b, vals); \
}, concat<dependencies<A>, dependencies<B>>{} }; \
} \
}
def_op(+) def_op(-) def_op(*) def_op(/) def_op(%) def_op(&&) def_op(||)
def_op(|) def_op(&) def_op(^) def_op(==) def_op(!=) def_op(<<) def_op(>>)
def_op(<=) def_op(>=) def_op(>) def_op(<) def_op(+=)
#undef def_op
}
#include <cassert>
template<std::size_t, bool = false> struct int_type;
template<> struct int_type<1, true> { using type = bool; };
template<> struct int_type<8, true> { using type = uint8_t; };
template<> struct int_type<16, true> { using type = uint16_t; };
template<> struct int_type<32, true> { using type = uint32_t; };
template<> struct int_type<64, true> { using type = uint64_t; };
template<> struct int_type<1, false> { using type = bool; };
template<> struct int_type<8, false> { using type = int8_t; };
template<> struct int_type<16, false> { using type = int16_t; };
template<> struct int_type<32, false> { using type = int32_t; };
template<> struct int_type<64, false> { using type = int64_t; };
consteval std::size_t up_2_pow(std::size_t v) {
if (v < 8) return 8;
else if (v < 16) return 16;
else if (v < 32) return 32;
else return 64;
}
template<std::size_t S, bool U>
struct int_mask {
using value_type = typename int_type<up_2_pow(S), U>::type;
value_type value : S{};
constexpr int_mask() = default;
constexpr int_mask(value_type v) : value(v) {}
constexpr int_mask& operator=(value_type v) { value = v; return *this; }
constexpr operator value_type () const { return value; }
};
template<std::size_t S>
struct int_type<S, false> {
using type = int_mask<S, false>;
};
template<std::size_t S>
struct int_type<S, true> {
using type = int_mask<S, true>;
};
template<std::size_t S, bool U = false> using int_t = typename int_type<S, U>::type;
template<class Ty>
struct TypeInfo {
constexpr static std::size_t size = sizeof(Ty);
constexpr static std::string_view name = []() {
std::string_view _name = __FUNCSIG__;
return _name.substr(29, _name.size() - 68);
}();
};
#include <memory>
namespace kaixo {
template<class> class delegate;
template<class Ret, class ...Args>
class delegate<Ret(Args...)> {
template<class> struct functor;
template<class Functor>
requires (sizeof(std::decay_t<Functor>) <= 16)
struct functor<Functor> {
std::decay_t<Functor> fun;
constexpr static Ret invoke(void* data, Args...args) {
return static_cast<functor*>(data)->fun(std::forward<Args>(args)...);
}
constexpr static void clean(void* data) {}
};
template<class Functor>
requires (sizeof(std::decay_t<Functor>) > 16)
struct functor<Functor> {
std::unique_ptr<std::decay_t<Functor>> fun;
constexpr functor(Functor functor)
: fun(std::make_unique<std::decay_t<Functor>>(
std::forward<Functor>(functor))) {}
constexpr static Ret invoke(void* data, Args...args) {
return (*static_cast<functor*>(data)->fun)(std::forward<Args>(args)...);
}
constexpr static void clean(void* data) {
(static_cast<functor*>(data)->fun).release();
}
};
template<class Obj, class Fun>
struct mem_fun {
Obj* obj; Fun fun;
constexpr static Ret invoke(void* data, Args...args) {
mem_fun* _fun = static_cast<mem_fun*>(data);
return (_fun->obj->*_fun->fun)(std::forward<Args>(args)...);
}
};
struct fun_ptr {
Ret(*fun)(Args...);
constexpr static Ret invoke(void* data, Args...args) {
return static_cast<fun_ptr*>(data)->fun(std::forward<Args>(args)...);
}
};
public:
template<std::invocable<Args...> Arg>
constexpr delegate(Arg&& arg)
: fun(&functor<Arg>::invoke), clean(&functor<Arg>::clean) {
new (data) functor<Arg>{ std::forward<Arg>(arg) };
}
template<class Obj, class Fun>
constexpr delegate(Obj& obj, Fun fun)
: fun(&mem_fun<Obj, Fun>::invoke) {
new (data) mem_fun<Obj, Fun>(&obj, fun);
}
constexpr delegate(Ret(*fun)(Args...))
: fun(&fun_ptr::invoke) { new (data) fun_ptr{ fun }; }
constexpr Ret operator()(Args...args) const {
return (*fun)(const_cast<void*>(static_cast<const void*>(data)),
std::forward<Args>(args)...);
}
constexpr ~delegate() { if (clean) clean(static_cast<void*>(data)); }
uint8_t data[16];
Ret(*fun)(void*, Args...) = nullptr;
void(*clean)(void*) = nullptr;
};
template<class Lambda>
delegate(Lambda)->delegate<minimal_signature_t<Lambda>>;
template<class Obj, class Fun>
delegate(Obj&, Fun)->delegate<minimal_signature_t<Fun>>;
}
#include <functional>
#include <iostream>
struct A {
int value;
A(int value = 0) : value(value) { std::cout << "Construct\n"; }
A(const A& a) : value(a.value) { std::cout << "Copy\n"; }
A(A&& a) : value(a.value) { std::cout << "Move\n"; }
~A() { std::cout << "Destroy\n"; }
};
int add(A& a, A& b) {
return a.value + b.value;
}
struct Functor {
int a = 10;
constexpr int operator()(int b) {
return a + b;
}
constexpr int add(int b) const { return a + b; }
};
struct RTTI_in_place {
template<class Ty>
constexpr static void destroy_impl(void* const ptr) {
std::destroy_at(static_cast<Ty*>(ptr));
}
template<class Ty>
constexpr static void move_impl(void* const dst, void* const src) {
std::construct_at(static_cast<Ty*>(dst), std::move(*static_cast<Ty*>(src)));
}
template<class Ty>
constexpr static void copy_impl(void* const dst, const void* const src) {
std::construct_at(static_cast<Ty*>(dst), *static_cast<const Ty*>(src));
}
template<class Ty>
constexpr static RTTI_in_place create() {
return RTTI_in_place{ destroy_impl<Ty>, move_impl<Ty>, copy_impl<Ty> };
}
void(*destroy)(void* const);
void(*move)(void* const, void* const);
void(*copy)(void* const, const void* const);
};
struct RTTI_dynamic {
template<class Ty>
constexpr static void destroy_impl(void* const ptr) {
::delete static_cast<Ty*>(ptr);
}
template<class Ty>
constexpr static void* move_impl(void* const src) {
return ::new Ty{ std::move(*static_cast<Ty*>(src)) };
}
template<class Ty>
constexpr static void* copy_impl(const void* const src) {
return ::new Ty{ std::move(*static_cast<const Ty*>(src)) };
}
template<class Ty>
constexpr static RTTI_dynamic create() {
return RTTI_dynamic{ destroy_impl<Ty>, move_impl<Ty>, copy_impl<Ty> };
}
void(*destroy)(void* const) = nullptr;
void*(*move)(void* const) = nullptr;
void*(*copy)(const void* const) = nullptr;
};
struct Any {
template<class Ty>
constexpr Any(Ty&& me) {
using type = std::decay_t<Ty>;
m_Data.rtti = RTTI_dynamic::create<type>();
m_Data.ptr = ::new type{ std::forward<Ty>(me) };
}
struct Data {
constexpr Data() {}
constexpr Data(const Data& data) : ptr(data.copy()), rtti(data.rtti) {}
constexpr Data(Data&& data) noexcept : ptr(data.ptr), rtti(data.rtti) { data.ptr = nullptr, data.rtti = {}; }
void* ptr = nullptr;
RTTI_dynamic rtti{};
constexpr void* copy() const { return rtti.copy(ptr); }
constexpr void* move() const { return rtti.move(ptr); }
};
Data m_Data;
};
namespace kaixo {
struct multi_fun_base { virtual ~multi_fun_base() {}; };
template<class> struct callable_multi_fun_base;
template<class Ret, class ...Args>
struct callable_multi_fun_base<Ret(Args...)>
: virtual multi_fun_base { // Virtual inheritance for single base
virtual Ret call(void*, Args...) = 0;
};
template<class, class> struct callable_multi_fun;
template<class Fun, class Ret, class ...Args>
struct callable_multi_fun<Fun, Ret(Args...)> : callable_multi_fun_base<Ret(Args...)> {
virtual Ret call(void* fun, Args...args) override {
return (*static_cast<Fun*>(fun))(args...);
}
};
template<class Fun, class... Sigs> // Inherit base for all signatures
struct multi_fun_start : callable_multi_fun<Fun, Sigs>... {};
struct multi_fun_storage_base {
virtual ~multi_fun_storage_base() {};
virtual void* get() = 0;
};
template<class Fun> struct multi_fun_storage : multi_fun_storage_base {
Fun fun; // Simple function wrapper
virtual void* get() override { return &fun; };
};
template<class ...Sigs> struct multi_fun {
multi_fun(auto fun) // vvv Create instance for all signatures given fun
: ptr(new multi_fun_start<std::decay_t<decltype(fun)>, Sigs...>{}),
data(new multi_fun_storage<std::decay_t<decltype(fun)>>{ fun }) {}
~multi_fun() { delete ptr; delete data; }
template<class Sig> auto call(auto...args) {
auto _c = dynamic_cast<callable_multi_fun_base<Sig>*>(ptr);
return (*_c).call(data->get(), args...);
}
multi_fun_base* ptr;
multi_fun_storage_base* data;
};
}
template<size_t N, class C>
struct incrementer {
friend constexpr auto magic_incr(incrementer<N, C>);
};
template<size_t N, class C, size_t V>
struct incrementer_def {
friend constexpr auto magic_incr(incrementer<N, C>) { return V; };
};
template<size_t N, class C, class>
concept checker_c = requires() {
magic_incr(incrementer<N, C>{});
};
// This checker first checks if the magic_incr friend function has been defined for N
// in any case, because everything in the boolean expression needs to be valid code
// the incrementer_def is evaluated, creating the definition for the magic_incr friend
// function anyway. So the next time this checker is evaluated for N, it will be valid.
// we need a unique class T to reevaluate N each time.
template<size_t N, class C, class T>
struct checker : std::bool_constant<checker_c<N, C, T> && (sizeof(incrementer_def<N, C, N + 1>), true)> {};
template<size_t, class, auto>
struct incr;
template<size_t V, class C, auto L> requires (!checker<V, C, decltype(L)>::value)
struct incr<V, C, L> {
constexpr static size_t get() { return V; }
};
template<size_t V, class C, auto L> requires (checker<V, C, decltype(L)>::value)
struct incr<V, C, L> : incr<V + 1, C, L> {
using incr<V + 1, C, L>::get;
};
//
struct dud {};
template<std::size_t, class, class...>
constexpr auto vtable = dud{}; // Not found: convertible to bool
template<auto> struct unq {};
template<auto V>
constexpr unq<V> unq_v{};
template<auto Mf, class Base, class ...Args>
constexpr auto find_impl(Base* me, Args ...args) {
using ret = kaixo::function_return_t<kaixo::minimal_signature_t<decltype(Mf)>>;
// Function id
constexpr auto _id1 = incr<0, dud, unq_v<Mf>>::get();
constexpr auto _id2 = incr<0, Base, unq_v<Mf>>::get();
auto test = [&]<std::size_t I>(auto & f) -> ret {
// Make sure it recurses till we get to a non-lambda
if constexpr (!std::same_as<decltype(::vtable<I, decltype(Mf), Args...>), const dud>) {
// Make sure we have the correct function
if constexpr (vtable<I, decltype(Mf), Args...>.second == _id2) {
// Find derived type from first argument
using type = kaixo::member_class_t<decltype(vtable<I, decltype(Mf), Args...>.first)>;
// Try dynamic cast
if (auto _ptr = dynamic_cast<type*>(me)) {
return (_ptr->*(vtable<I, decltype(Mf), Args...>.first))(args...);
}
}
// Recurse if not correct derived
return f.operator()<I+1>(f);
}
};
return test.operator()<0>(test);
}
#define toverride(b, d, f) \
template<class ...Args> constexpr auto \
vtable<(incr<0, b, []{}>::get()), decltype(&b::f<Args...>), Args...>\
= std::pair{ &d::f<Args...>, (incr<0, b, unq_v<&b::f<Args...>>>::get()) };
struct Base {
constexpr virtual ~Base() {}
template<class Arg>
constexpr int my_fun1(Arg arg) { return find_impl<&Base::my_fun1<Arg>>(this, arg); }
template<class Arg>
constexpr int my_fun2(Arg arg) { return find_impl<&Base::my_fun2<Arg>>(this, arg); }
};
struct Derived1 : Base {
template<class Arg>
constexpr int my_fun1(Arg arg) {
std::cout << "called my_fun1 on Derived1 with: " << typeid(Arg).name() << "\n";
return 1;
}
template<class Arg>
constexpr int my_fun2(Arg arg) {
std::cout << "called my_fun2 on Derived1 with: " << typeid(Arg).name() << "\n";
return 2;
}
};
//toverride(Base, Derived1, my_fun1);
//toverride(Base, Derived1, my_fun2);
struct Derived2 : Derived1 {
template<class Arg>
constexpr int my_fun1(Arg arg) {
std::cout << "called my_fun1 on Derived2 with: " << typeid(Arg).name() << "\n";
return 3;
}
template<class Arg>
constexpr int my_fun2(Arg arg) {
std::cout << "called my_fun2 on Derived2 with: " << typeid(Arg).name() << "\n";
return 4;
}
};
//toverride(Base, Derived2, my_fun1);
//toverride(Base, Derived2, my_fun2);
#include <string>
namespace ta {
template<size_t N, class C> struct incrementer {
friend constexpr auto magic_incr(incrementer<N, C>);
};
template<size_t N, class C, size_t V> struct incrementer_def {
friend constexpr auto magic_incr(incrementer<N, C>) { return V; };
};
template<size_t N, class C, class> concept checker_c = requires() {
magic_incr(incrementer<N, C>{});
};
template<size_t N, class C, class T>
struct checker : std::bool_constant<checker_c<N, C, T> && (sizeof(incrementer_def<N, C, N + 1>), true)> {};
template<size_t, auto, auto> struct incr;
template<size_t V, auto C, auto L> requires (!checker<V, decltype(C), decltype(L)>::value)
struct incr<V, C, L> {
constexpr static size_t get() { return V; }
};
template<size_t V, auto C, auto L> requires (checker<V, decltype(C), decltype(L)>::value)
struct incr<V, C, L> : incr<V + 1, C, L> {
using incr<V + 1, C, L>::get;
};
}
struct dud {};
struct type_array {};
template<type_array Arr, std::size_t I> constexpr auto type_array_v = dud{};
template<type_array Arr, std::size_t I> using type_array_t = decltype(type_array_v<Arr, I>);
template<type_array Arr>
struct type_array_i {
template<std::size_t I>
using element = typename std::decay_t<type_array_t<Arr, I>>::type;
constexpr static std::size_t size = []() {
constexpr auto finder = []<std::size_t N>(auto& finder) {
if constexpr (std::same_as<type_array_t<Arr, N>, const dud>) return N;
else return finder.template operator()<(N+1)>(finder);
};
return finder.template operator()<0>(finder);
}();
};
#define push(a, t) template<> constexpr auto type_array_v<a, (ta::incr<0, a, []{}>::get())> = std::type_identity<t>{};
constexpr type_array my_arr;
push(my_arr, int);
push(my_arr, float);
push(my_arr, std::string);
static_assert(type_array_i<my_arr>::size == 3ull);
static_assert(std::same_as<type_array_i<my_arr>::element<0>, int>);
static_assert(std::same_as<type_array_i<my_arr>::element<1>, float>);
static_assert(std::same_as<type_array_i<my_arr>::element<2>, std::string>);
template<class T>
struct is_callable_impl {
private:
typedef char(&yes)[1];
typedef char(&no)[2];
struct Fallback { void operator()(); };
struct Derived : T, Fallback { };
template<typename U, U> struct Check;
template<typename>
static yes test(...);
template<typename C>
static no test(Check<void (Fallback::*)(), &C::operator()>*);
public:
constexpr static bool value = sizeof(test<Derived>(0)) == sizeof(yes);
};
template<class T> requires (std::is_fundamental_v<T>)
struct is_callable_impl<T> {
constexpr static bool value = false;
};
template<class T>
concept is_callable = is_callable_impl<T>::value;
template<class Ty>
constexpr static auto check_invocable(Ty&& v) {
if constexpr (std::invocable<Ty>) return check_invocable(std::forward<Ty>(v)());
else return std::forward<Ty>(v);
}
template<class, class> struct fun_arity {};
template<class Fun>
struct fun_arity<Fun, kaixo::pack<>> : std::integral_constant<std::size_t, 0> {};
template<class Fun, class ...Tys>
struct fun_arity<Fun, kaixo::pack<Tys...>>
: std::conditional_t<std::invocable<Fun, Tys...>, // if invocable
std::integral_constant<std::size_t, sizeof...(Tys)>, // Get integral constant
fun_arity<Fun, typename kaixo::template pack<Tys...>::init>>{}; // Otherwise, remove head and recurse
template<class Fun1, class Fun2, class Args, std::size_t ...Is, std::size_t ...Ns>
constexpr auto invoke_double_impl(Fun1& fun1, Fun2& fun2, Args&& args, std::index_sequence<Is...>, std::index_sequence<Ns...>) {
return ((fun1 << (fun2 << ... << std::get<Is>(args))) << ... << std::get<Ns + sizeof...(Is)>(args));
}
template<class Fun1, class Fun2, class ...Tys> requires requires (Fun1& fun1, Fun2& fun2, std::tuple<Tys&&...> args) {
{ invoke_double_impl(fun1, fun2, args, std::make_index_sequence<fun_arity<Fun2, kaixo::pack<Tys...>>::value>{},
std::make_index_sequence<sizeof...(Tys) - fun_arity<Fun2, kaixo::pack<Tys...>>::value>{}) };
}
constexpr auto invoke_double(Fun1& fun1, Fun2& fun2, Tys&&...args) {
constexpr auto arity = fun_arity<Fun2, kaixo::pack<Tys...>>::value;
return invoke_double_impl(fun1, fun2, std::forward_as_tuple(std::forward<Tys>(args)...),
std::make_index_sequence<arity>{}, std::make_index_sequence<sizeof...(Tys) - arity>{});
}
template<is_callable Fun, class Arg>
constexpr auto operator<<(Fun f, Arg&& v) {
if constexpr (std::invocable<Fun, Arg&&>) return check_invocable(f(v));
else if constexpr (is_callable<std::decay_t<Arg>>) return[v, f = f]<class ...Tys>
(Tys&&...args) {
return invoke_double(v, f, std::forward<Tys>(args)...);
};
else return[v = std::forward<Arg>(v), f = f]<class ...Args>(Args&& ...args)
requires (std::invocable<Fun, Arg&&, Args&&...>) {
return check_invocable(f(v, std::forward<Args>(args)...));
};
}
namespace kaixo {
// general type traits, concept, and helpers:
// The entire structure makes use of definitions and dependencies
// to deduce necessary arguments to lazily evaluated expressions.
template<class Ty> concept has_dependencies = requires () { typename Ty::dependencies; };
template<class Ty> concept has_definitions = requires () { typename Ty::definitions; };
template<class Ty> concept is_named = requires() { Ty::name; };
// General way to retrieve dependencies and definitions from any
// type, even ones that don't have any.
template<class> struct dependencies_t { using type = pack<>; };
template<has_dependencies Ty> struct dependencies_t<Ty> { using type = typename Ty::dependencies; };
template<class Ty> using dependencies = typename dependencies_t<Ty>::type;
template<class> struct definitions_t { using type = pack<>; };
template<has_definitions Ty> struct definitions_t<Ty> { using type = typename Ty::definitions; };
template<class Ty> using definitions = typename definitions_t<Ty>::type;
// For the purpose of list comprehension, we only
// need a begin and end method for iterating.
template<class Ty> concept is_container = requires(const Ty ty) {
{ ty.begin() }; { ty.end() };
};
// fundamental classes:
// Named value is used inside the named tuple,
// links a constexpr name to a value of type Ty
template<string_literal Name, class Ty>
struct named_value {
constexpr static auto name = Name;
using value_type = Ty;
Ty value;
};
// Type wrapper for a constexpr name
template<string_literal Name>
struct var_t {
using dependencies = pack<var_t>; // to make life easier later on, a var
using definitions = pack<var_t>; // depends on itself, and defines itself
constexpr static auto name = Name;
// Assignment operator to create a named_value
template<class Ty> constexpr auto operator=(Ty&& value) const {
return named_value<name, Ty>{ std::forward<Ty>(value) };
}
};
template<string_literal Name> constexpr auto var = var_t<Name>{};
template<class Ty> concept is_var = is_named<Ty> && has_definitions<Ty> && has_dependencies<Ty>;
template<class A, class B> concept name_equals = is_named<A> && is_named<B> && A::name == B::name;
// std::tuple of named_values, contains a get method
// to retrieve a value given a var
template<class ...Args>
struct named_tuple : std::tuple<Args...> {
using std::tuple<Args...>::tuple;
template<is_var Var> constexpr decltype(auto) get() const {
// Filter the arguments by name and get the first one, then get the
// index of that type in the pack, so we can use the std::get function
constexpr auto filter = []<name_equals<Var>>{};
using named_value_type = pack<Args...>::template filter<filter>::head;
constexpr std::size_t index = pack<Args...>::template index<named_value_type>;
return std::get<index>(*this).value;
}
};
template<class ...Args> named_tuple(Args...)->named_tuple<Args...>;
// Lazily evaluated expression
template<class Lambda, class Dependencies>
struct expression : Lambda, Dependencies {
using dependencies = Dependencies::unique;
template<class ...Args>
constexpr decltype(auto) operator()(Args&&... vals) const {
// The named tuple should contain all the dependencies of this expression.
return Lambda::operator()(named_tuple{ std::forward<Args>(vals)... });
}
};
template<class Ty> concept is_expression = specialization<Ty, expression>;
// Constructing the container:
// In order to make our lives easier, we always use a wrapped container
template<is_container C>
struct wrapped_container {
// Retrieve iterator and value types using begin
using iterator = decltype(std::declval<C>().begin());
using value_type = decltype(*std::declval<C>().begin());
using dependencies = dependencies<C>;
using definitions = definitions<C>;
std::reference_wrapper<C> value;
constexpr iterator begin() const { return value.get().begin(); }
constexpr iterator end() const { return value.get().end(); }
};
template<is_container C>
constexpr wrapped_container<C> operator-(C& v) { return { v }; }
// A container that is linked to a name (var)
template<string_literal Name, is_container C>
struct named_container : wrapped_container<C> {
using definitions = definitions<C>::template append<var_t<Name>>::unique;
constexpr static auto name = Name;
};
template<is_var Var, is_container C>
constexpr auto operator<(Var, wrapped_container<C>&& c) {
return named_container<Var::name, C>{ std::move(c) };
}
template<class Ty>
concept is_named_container = is_named<Ty> && is_container<Ty>;
// Concatenation of list comprehension parts
template<class Expr, class ...Parts>
struct lc_construct {
using definitions = concat<definitions<std::decay_t<Parts>>...>;
using dependencies = remove<definitions, concat<dependencies<Expr>, dependencies<std::decay_t<Parts>>...>>;
Expr expression;
std::tuple<Parts...> parts;
};
template<class Ty>
concept is_lc_construct = specialization<Ty, lc_construct>;
template<class Ty>
concept valid_construct_part = has_definitions<Ty> || has_dependencies<Ty>;
// Start construction with an expression and a part.
template<is_expression A, valid_construct_part B>
constexpr auto operator|(A&& expr, B&& part) {
return lc_construct{ std::move(expr), std::forward_as_tuple(std::move(part)) };
}
// Add a part to a construct object.
template<is_lc_construct A, valid_construct_part B>
constexpr auto operator,(A&& a, B&& b) {
return lc_construct{ std::move(a.expression),
std::tuple_cat(std::move(a.parts), std::forward_as_tuple(std::move(b))) };
}
// Construct final list comprehension object:
constexpr static auto container_filter = []<kaixo::is_named_container>{};
constexpr static auto constraint_filter = []<kaixo::is_expression>{};
template<class Expr, class ...Parts>
struct list_comprehension {
constexpr list_comprehension(lc_construct<Expr, Parts&&...>&& parts)
: expression(std::move(parts.expression)),
containers(iterate<pack<Parts...>::template
indices_filter<container_filter>>([&]<std::size_t ...Is>() {
return std::tuple{ std::get<Is>(parts.parts)... };
})),
constraints(iterate<pack<Parts...>::template
indices_filter<constraint_filter>>([&]<std::size_t ...Is>() {
return std::tuple{ std::get<Is>(parts.parts)... };
})) {}
Expr expression;
pack<Parts...>::template filter<container_filter>::template as<std::tuple> containers;
pack<Parts...>::template filter<constraint_filter>::template as<std::tuple> constraints;
};
struct lc_t {
template<class Expr, class ...Parts>
constexpr auto operator[](lc_construct<Expr, Parts...>&& lc) const {
return list_comprehension<Expr, std::decay_t<Parts>...>{ std::move(lc) };
}
};
constexpr lc_t lc;
// Operator overloads:
// function to make writing a general operator overload a little easier
// extracts the 3 different cases: expression, var, value.
template<class Ty, class ...Args>
constexpr decltype(auto) use(Ty& v, const named_tuple<Args...>& vals) {
if constexpr (is_expression<Ty>) return v(vals); // Run expression
else if constexpr (is_var<Ty>) return vals.get<Ty>(); // Get value of var
else return v; // Forward the value
}
// to prevent operator overloads for any 2 types, either of the
// arguments must be a variable or an expression.
template<class A, class B>
concept valid_op = (is_var<A> || is_expression<A> || is_var<B> || is_expression<B>)
&& !is_named_container<A> && !is_named_container<B>;
// Operator macro to define all operators more efficiently
#define def_op(op) \
template<class Av, class Bv> \
requires valid_op<std::decay_t<Av>, std::decay_t<Bv>> \
constexpr auto operator op(Av&& a, Bv&& b) { \
using A = std::decay_t<Av>; \
using B = std::decay_t<Bv>; \
/* Lots of ifs to prevent capturing of vars, as we only */ \
/* need their type, not their value. Saves some memory. */ \
if constexpr (is_var<A> && is_var<B>) { \
return expression{ [ \
] <class...Args>(const named_tuple<Args...>&vals) { \
return vals.get<A>() op vals.get<B>(); \
}, concat<dependencies<A>, dependencies<B>>{} }; \
} else if constexpr (is_var<A> && !is_var<B>) { \
return expression{ [ \
b = std::forward<Bv>(b) \
] <class...Args>(const named_tuple<Args...>&vals) { \
return vals.get<A>() op use(b, vals); \
}, concat<dependencies<A>, dependencies<B>>{} }; \
} else if constexpr (!is_var<A> && is_var<B>) { \
return expression{ [ \
a = std::forward<Av>(a) \
] <class...Args>(const named_tuple<Args...>&vals) { \
return use(a, vals) op vals.get<B>(); \
}, concat<dependencies<A>, dependencies<B>>{} }; \
} else { \
return expression{ [ \
a = std::forward<Av>(a), b = std::forward<Bv>(b) \
] <class...Args>(const named_tuple<Args...>&vals) { \
return use(a, vals) op use(b, vals); \
}, concat<dependencies<A>, dependencies<B>>{} }; \
} \
}
def_op(+) def_op(-) def_op(*) def_op(/ ) def_op(%) def_op(&&) def_op(|| );
def_op(| ) def_op(&) def_op(^) def_op(== ) def_op(!= ) def_op(<< ) def_op(>> );
def_op(<= ) def_op(>= ) def_op(> ) def_op(< ) def_op(+= );
#undef def_op
}
template<class Ty>
struct get_t {
template<class Access>
constexpr get_t(Access access)
: data(std::bit_cast<void*>(access)),
access(&access_impl<Access>) {}
constexpr get_t(Ty& val)
: data(&val), access(&access_impl2) {}
constexpr get_t()
: data(nullptr), access(access_impl2) {}
void* data;
Ty(*access)(void*);
template<class Access>
constexpr static Ty access_impl(void* data) {
return std::bit_cast<Access>(data)();
}
constexpr static Ty access_impl2(void* data) {
return *static_cast<Ty*>(data);
}
};
template<class Ty>
struct set_t {
template<class Access>
constexpr set_t(Access access)
: data(std::bit_cast<void*>(access)),
access(&access_impl<Access>) {}
constexpr set_t(Ty& val)
: data(&val), access(&access_impl2) {}
constexpr set_t()
: data(nullptr), access(access_impl2) {}
void* data;
void(*access)(void*, Ty);
template<class Access>
constexpr static void access_impl(void* data, Ty val) {
(*reinterpret_cast<Access*>(data))(val);
}
constexpr static void access_impl2(void* data, Ty val) {
*static_cast<Ty*>(data) = val;
}
};
template<class Ty, class Me = void>
struct alias {
constexpr alias& operator=(Ty val) { set.access(set.data, val); return *this; }
constexpr operator Ty() const { return get.access(get.data); }
get_t<Ty> get;
set_t<Ty> set;
friend Me;
};
template<class Ty, class Me = void>
struct readonly {
constexpr operator Ty() const { return get.access(get.data); }
get_t<Ty> get;
set_t<Ty> set;
private:
constexpr readonly& operator=(Ty val) { set.access(set.data, val); return *this; }
friend Me;
};
template<class Ty, class Me = void>
struct writeonly {
constexpr writeonly& operator=(Ty val) { set.access(set.data, val); return *this; }
get_t<Ty> get;
set_t<Ty> set;
private:
constexpr operator Ty() const { return get.access(get.data); }
friend Me;
};
// INTERFACE THING
template<class T> struct add_any_arg { using type = T(std::any&); };
template<class R, class ...As>
struct add_any_arg<R(As...)> { using type = R(std::any&, As...); };
template<class Ty> using add_any_arg_t = typename add_any_arg<Ty>::type;
template<class T> struct get_ret_type { using type = T; };
template<class R, class ...As>
struct get_ret_type<R(As...)> { using type = R; };
template<class Ty> using get_ret_type_t = typename get_ret_type<Ty>::type;
template<class Ty>
concept has_signature = requires() {
typename Ty::signature;
};
template<class Ty>
struct type_impl {
using type = typename Ty::type&;
};
template<class Ty> requires has_signature<Ty>
struct type_impl<Ty> {
using type = typename Ty::signature;
};
template<class Fun>
using type_impl_t = typename type_impl<Fun>::type;
template<class Ty>
struct member {
member(const member&) = delete;
member(member&&) = default;
member& operator=(const member&) = delete;
member& operator=(member&&) = default;
member(Ty& val) : _value(&val) {}
operator Ty& () { return *_value; }
operator Ty const& () const { return *_value; }
template<std::convertible_to<Ty> Arg>
member& operator=(Arg&& v) { return (*_value = std::forward<Arg>(v), *this); }
private:
Ty* _value;
};
template<class ...Funs>
class interface {
using vtable = std::tuple<add_any_arg_t<type_impl_t<Funs>>*...>;
public:
interface(const interface&) = delete;
interface(interface&&) = default;
interface& operator=(const interface&) = delete;
interface& operator=(interface&&) = default;
template<class Ty>
interface(Ty& value) : _storage(std::ref(value)), _vtable{
[](std::any& val, auto ...args) -> get_ret_type_t<type_impl_t<Funs>> {
if constexpr (has_signature<Funs>) {
constexpr auto v = &Funs::template call<Ty>;
return v(std::any_cast<std::reference_wrapper<Ty>&>(val).get(), args...);
}
else {
constexpr auto v = &Funs::template get<Ty>;
return v(std::any_cast<std::reference_wrapper<Ty>&>(val).get(), args...);
}
}... } {}
template<class Ty>
interface(Ty&& value) : _storage(std::forward<Ty>(value)), _vtable{
[](std::any& val, auto ...args) -> get_ret_type_t<type_impl_t<Funs>> {
if constexpr (has_signature<Funs>) {
constexpr auto v = &Funs::template call<Ty>;
return v(std::any_cast<Ty&>(val), args...);
}
else {
constexpr auto v = &Funs::template get<Ty>;
return v(std::any_cast<Ty&>(val), args...);
}
}... } {}
template<class Fun, class ...Args> decltype(auto) call(Args&& ...args) const {
using type = add_any_arg_t<type_impl_t<Fun>>*;
return std::get<type>(const_cast<vtable&>(_vtable))(
const_cast<std::any&>(_storage), std::forward<Args>(args)...);
}
template<class Fun> auto get() -> decltype(call<Fun>()) {
return call<Fun>();
}
private:
std::any _storage;
vtable _vtable;
};
struct DrawContext { /* ... */ };
struct Point {
double x;
double y;
};
struct draw_fun {
using signature = void(DrawContext&);
void call(this auto& self, DrawContext& c) { self.draw(c); }
};
struct update_fun {
using signature = void();
void call(this auto& self) { self.update(); }
};
struct hitbox_fun {
using signature = bool(const Point&);
bool call(this const auto& self, const Point& p) { return self.hitbox(p); }
};
struct value_mem {
using type = int;
int& get(this auto& self) { return self.value; }
};
struct GuiObject : interface<
draw_fun,
update_fun,
hitbox_fun,
value_mem
> {
using interface::interface;
void draw(DrawContext& v) { call<draw_fun>(v); }
void update() { call<update_fun>(); }
bool hitbox(const Point& p) { return call<hitbox_fun>(p); }
member<int> value = get<value_mem>();
};
struct CustomGuiObject {
int value = 1;
void draw(DrawContext& v) { std::cout << value << ": drawing...\n"; }
void update() { std::cout << value << ": updating...\n"; }
bool hitbox(const Point& p) const {
std::cout << value << ": hitbox test: [" << p.x << ", " << p.y << "]\n";
return false;
}
};
void setValue(GuiObject obj, int v) {
obj.value = v;
}
template<auto V>
struct constant_v {
constexpr static auto value = V;
};
template<char ...S>
consteval std::size_t to_index() {
constexpr std::size_t size = sizeof...(S);
using values = kaixo::to_pack<static_cast<int>(S - '0')...>;
return[&]<std::size_t ...Is>(std::index_sequence<Is...>) {
std::size_t m = 1;
std::size_t res = 0;
((res += m * (values::template element<size - Is - 1>), m *= 10), ...);
return res;
}(std::make_index_sequence<size>{});
}
template<char ...S>
requires ((S >= '0' && S <= '9') && ...)
consteval constant_v<to_index<S...>()> operator""_() {
return {};
}
template<class ...Tys>
struct tuple : std::tuple<Tys...> {
using std::tuple<Tys...>::tuple;
using types = kaixo::pack<Tys...>;
template<class Self, std::size_t I>
constexpr auto operator[](this Self&& self, constant_v<I>)
noexcept(noexcept(std::get<I>(std::forward<Self>(self))))
-> decltype(std::get<I>(std::forward<Self>(self))) {
return std::get<I>(std::forward<Self>(self));
}
};
|
#include<iostream>
#include<algorithm>
#include<cmath>
#include<vector>
#include<map>
#include<queue>
#define rep(i, n) for (int i = 0; i < (n); ++i)
#define rep1(i, n) for (int i = 1; i < (n); ++i)
using namespace std;
using ll = long long;
using P = pair<int, int>;
const int INF = 1001001001;
int res[3][3];
int main() {
int A[3][3];
rep(i,3)rep(j,3) cin >> A[i][j];
int N;
cin >> N;
int b[N];
rep(i,N) cin >> b[i];
if (N < 3) {
cout << "No" << endl;
return 0;
}
rep(i,N)rep(j,3)rep(k,3) {
if (b[i] == A[j][k]) res[j][k] = 1;
}
if ((res[0][0] == 1 && res[1][1] == 1 && res[2][2] == 1) || (res[0][2] == 1 && res[1][1] == 1 && res[2][0] == 1)) {
cout << "Yes" << endl;
return 0;
}
rep(i,3) {
if ((res[i][0] == 1 && res[i][1] == 1 && res[i][2] == 1) || (res[0][i] == 1 && res[1][i] == 1 && res[2][i] == 1)) {
cout << "Yes" << endl;
return 0;
}
}
cout << "No" << endl;
return 0;
}
|
#pragma once
#include "partners_api/booking_availability_params.hpp"
#include "partners_api/booking_block_params.hpp"
#include "platform/safe_callback.hpp"
#include <chrono>
#include <functional>
#include <string>
#include <vector>
namespace booking
{
struct HotelPhotoUrls
{
std::string m_small;
std::string m_original;
};
struct HotelReview
{
/// An issue date.
std::chrono::time_point<std::chrono::system_clock> m_date;
/// Author's hotel evaluation.
float m_score = 0.0;
/// Review author name.
std::string m_author;
/// Review text. There can be either one or both positive/negative review.
std::string m_pros;
std::string m_cons;
};
struct HotelFacility
{
std::string m_type;
std::string m_name;
};
struct HotelInfo
{
std::string m_hotelId;
std::string m_description;
std::vector<HotelPhotoUrls> m_photos;
std::vector<HotelFacility> m_facilities;
std::vector<HotelReview> m_reviews;
float m_score = 0.0;
uint32_t m_scoreCount = 0;
};
struct Deals
{
enum class Type
{
/// Good price.
Smart,
/// Sale with discount in percent from base price.
LastMinute
};
std::vector<Type> m_types;
uint8_t m_discount = 0;
};
struct BlockInfo
{
static double constexpr kIncorrectPrice = std::numeric_limits<double>::max();
std::string m_blockId;
std::string m_name;
std::string m_description;
uint8_t m_maxOccupancy = 0;
double m_minPrice = kIncorrectPrice;
std::string m_currency;
std::vector<std::string> m_photos;
Deals m_deals;
std::chrono::time_point<std::chrono::system_clock> m_refundableUntil;
bool m_breakfastIncluded = false;
bool m_depositRequired = false;
};
struct Blocks
{
void Add(BlockInfo && block)
{
if (block.m_minPrice < m_totalMinPrice)
{
m_totalMinPrice = block.m_minPrice;
m_currency = block.m_currency;
}
if (!m_hasSmartDeal)
{
auto const & types = block.m_deals.m_types;
m_hasSmartDeal = std::find(types.cbegin(), types.cend(), Deals::Type::Smart) != types.cend();
}
if (block.m_deals.m_discount > m_maxDiscount)
m_maxDiscount = block.m_deals.m_discount;
m_blocks.emplace_back(block);
}
double m_totalMinPrice = BlockInfo::kIncorrectPrice;
std::string m_currency;
uint8_t m_maxDiscount = 0;
bool m_hasSmartDeal = false;
std::vector<BlockInfo> m_blocks;
};
class RawApi
{
public:
// Booking Api v1 methods:
static bool GetHotelAvailability(std::string const & hotelId, std::string const & currency, std::string & result);
static bool GetExtendedInfo(std::string const & hotelId, std::string const & lang, std::string & result);
// Booking Api v2 methods:
static bool HotelAvailability(AvailabilityParams const & params, std::string & result);
static bool BlockAvailability(BlockParams const & params, string & result);
static size_t constexpr GetMaxHotelsInAvailabilityRequest() { return 300; };
};
using BlockAvailabilityCallback =
platform::SafeCallback<void(std::string const & hotelId, Blocks const & blocks)>;
using GetHotelInfoCallback = platform::SafeCallback<void(HotelInfo const & hotelInfo)>;
// NOTE: this callback will be called on the network thread.
using GetHotelAvailabilityCallback = std::function<void(std::vector<std::string> hotelIds)>;
/// This is a lightweight class but methods are non-static in order to support the NetworkPolicy
/// restrictions.
/// Callbacks will be called in the same order as methods are called.
class Api
{
public:
std::string GetBookHotelUrl(std::string const & baseUrl) const;
std::string GetDeepLink(std::string const & hotelId) const;
std::string GetDescriptionUrl(std::string const & baseUrl) const;
std::string GetMoreUrl(string const & baseUrl) const;
std::string GetHotelReviewsUrl(std::string const & hotelId, std::string const & baseUrl) const;
std::string GetSearchUrl(std::string const & city, std::string const & name) const;
std::string ApplyAvailabilityParams(std::string const & url,
AvailabilityParams const & params) const;
/// Real-time information methods (used for retrieving rapidly changing information).
/// These methods send requests directly to Booking.
void GetBlockAvailability(BlockParams && params, BlockAvailabilityCallback const & fn) const;
/// NOTE: callback will be called on the network thread.
void GetHotelAvailability(AvailabilityParams const & params,
GetHotelAvailabilityCallback const & fn) const;
/// Static information methods (use for information that can be cached).
/// These methods use caching server to prevent Booking from being ddossed.
void GetHotelInfo(std::string const & hotelId, std::string const & lang,
GetHotelInfoCallback const & fn) const;
};
void SetBookingUrlForTesting(std::string const & url);
} // namespace booking
|
// Copyright (c) Prevail Verifier contributors.
// SPDX-License-Identifier: Apache-2.0
#pragma once
/*
* Build a CFG to interface with the abstract domains and fixpoint
* iterators.
*
* All the CFG statements are strongly typed. However, only variables
* need to be typed. The types of constants can be inferred from the
* context since they always appear together with at least one
* variable.
*
*/
#include <map>
#include <memory>
#include <set>
#include <variant>
#include <vector>
#include <boost/iterator/transform_iterator.hpp>
#include <boost/range/iterator_range.hpp>
#include <boost/lexical_cast.hpp>
#include "crab/variable.hpp"
#include "crab_utils/bignums.hpp"
#include "crab_utils/debug.hpp"
#include "asm_syntax.hpp"
#include "asm_ostream.hpp"
#include "spec_type_descriptors.hpp"
namespace crab {
class cfg_t;
class basic_block_t final {
friend class cfg_t;
private:
public:
basic_block_t(const basic_block_t&) = delete;
using label_vec_t = std::set<label_t>;
using stmt_list_t = std::vector<Instruction>;
using succ_iterator = label_vec_t::iterator;
using const_succ_iterator = label_vec_t::const_iterator;
using pred_iterator = succ_iterator;
using const_pred_iterator = const_succ_iterator;
using iterator = typename stmt_list_t::iterator;
using const_iterator = typename stmt_list_t::const_iterator;
using reverse_iterator = typename stmt_list_t::reverse_iterator;
using const_reverse_iterator = typename stmt_list_t::const_reverse_iterator;
private:
label_t m_label;
stmt_list_t m_ts;
label_vec_t m_prev, m_next;
public:
template <typename T, typename... Args>
void insert(Args&&... args) {
m_ts.emplace_back(T{std::forward<Args>(args)...});
}
void insert(const Instruction& arg) {
assert(label() != label_t::entry);
assert(label() != label_t::exit);
m_ts.push_back(arg);
}
explicit basic_block_t(label_t _label) : m_label(_label) {}
~basic_block_t() = default;
[[nodiscard]] label_t label() const { return m_label; }
iterator begin() { return (m_ts.begin()); }
iterator end() { return (m_ts.end()); }
[[nodiscard]] const_iterator begin() const { return (m_ts.begin()); }
[[nodiscard]] const_iterator end() const { return (m_ts.end()); }
reverse_iterator rbegin() { return (m_ts.rbegin()); }
reverse_iterator rend() { return (m_ts.rend()); }
[[nodiscard]] const_reverse_iterator rbegin() const { return (m_ts.rbegin()); }
[[nodiscard]] const_reverse_iterator rend() const { return (m_ts.rend()); }
[[nodiscard]] size_t size() const { return static_cast<size_t>(std::distance(begin(), end())); }
std::pair<succ_iterator, succ_iterator> next_blocks() { return std::make_pair(m_next.begin(), m_next.end()); }
std::pair<pred_iterator, pred_iterator> prev_blocks() { return std::make_pair(m_prev.begin(), m_prev.end()); }
[[nodiscard]] std::pair<const_succ_iterator, const_succ_iterator> next_blocks() const {
return std::make_pair(m_next.begin(), m_next.end());
}
[[nodiscard]] std::pair<const_pred_iterator, const_pred_iterator> prev_blocks() const {
return std::make_pair(m_prev.begin(), m_prev.end());
}
[[nodiscard]] const label_vec_t& next_blocks_set() const {
return m_next;
}
[[nodiscard]] const label_vec_t& prev_blocks_set() const {
return m_prev;
}
// Add a cfg_t edge from *this to b
void operator>>(basic_block_t& b) {
assert(b.label() != label_t::entry);
assert(this->label() != label_t::exit);
m_next.insert(b.m_label);
b.m_prev.insert(m_label);
}
// Remove a cfg_t edge from *this to b
void operator-=(basic_block_t& b) {
m_next.erase(b.m_label);
b.m_prev.erase(m_label);
}
// insert all statements of other at the back
void move_back(basic_block_t& other) {
m_ts.reserve(m_ts.size() + other.m_ts.size());
std::move(other.m_ts.begin(), other.m_ts.end(), std::back_inserter(m_ts));
}
[[nodiscard]] size_t in_degree() const {
return m_prev.size();
}
[[nodiscard]] size_t out_degree() const {
return m_next.size();
}
void swap_instructions(stmt_list_t& ts) { std::swap(m_ts, ts); }
};
// Viewing basic_block_t with all statements reversed. Useful for
// backward analysis.
class basic_block_rev_t final {
public:
using succ_iterator = typename basic_block_t::succ_iterator;
using const_succ_iterator = typename basic_block_t::const_succ_iterator;
using pred_iterator = succ_iterator;
using const_pred_iterator = const_succ_iterator;
using iterator = typename basic_block_t::reverse_iterator;
using const_iterator = typename basic_block_t::const_reverse_iterator;
public:
basic_block_t& _bb;
explicit basic_block_rev_t(basic_block_t& bb) : _bb(bb) {}
[[nodiscard]] label_t label() const { return _bb.label(); }
iterator begin() { return _bb.rbegin(); }
iterator end() { return _bb.rend(); }
[[nodiscard]] const_iterator begin() const { return _bb.rbegin(); }
[[nodiscard]] const_iterator end() const { return _bb.rend(); }
[[nodiscard]] std::size_t size() const { return static_cast<size_t>(std::distance(begin(), end())); }
std::pair<succ_iterator, succ_iterator> next_blocks() { return _bb.prev_blocks(); }
std::pair<pred_iterator, pred_iterator> prev_blocks() { return _bb.next_blocks(); }
[[nodiscard]] std::pair<const_succ_iterator, const_succ_iterator> next_blocks() const { return _bb.prev_blocks(); }
[[nodiscard]] std::pair<const_pred_iterator, const_pred_iterator> prev_blocks() const { return _bb.next_blocks(); }
[[nodiscard]] const basic_block_t::label_vec_t& next_blocks_set() const {
return _bb.prev_blocks_set();
}
[[nodiscard]] const basic_block_t::label_vec_t& prev_blocks_set() const {
return _bb.next_blocks_set();
}
};
/// Control-Flow Graph.
class cfg_t final {
public:
using node_t = label_t; // for Bgl graphs
using succ_iterator = typename basic_block_t::succ_iterator;
using pred_iterator = typename basic_block_t::pred_iterator;
using const_succ_iterator = typename basic_block_t::const_succ_iterator;
using const_pred_iterator = typename basic_block_t::const_pred_iterator;
using succ_range = boost::iterator_range<succ_iterator>;
using pred_range = boost::iterator_range<pred_iterator>;
using const_succ_range = boost::iterator_range<const_succ_iterator>;
using const_pred_range = boost::iterator_range<const_pred_iterator>;
private:
using basic_block_map_t = std::map<label_t, basic_block_t>;
using binding_t = typename basic_block_map_t::value_type;
struct get_label {
label_t operator()(const binding_t& p) const { return p.second.label(); }
};
public:
using iterator = typename basic_block_map_t::iterator;
using const_iterator = typename basic_block_map_t::const_iterator;
using label_iterator = boost::transform_iterator<get_label, typename basic_block_map_t::iterator>;
using const_label_iterator = boost::transform_iterator<get_label, typename basic_block_map_t::const_iterator>;
private:
basic_block_map_t m_blocks;
using visited_t = std::set<label_t>;
public:
cfg_t() {
m_blocks.emplace(entry_label(), entry_label());
m_blocks.emplace(exit_label(), exit_label());
}
cfg_t(const cfg_t&) = delete;
cfg_t(cfg_t&& o) noexcept : m_blocks(std::move(o.m_blocks)) {}
~cfg_t() = default;
[[nodiscard]] label_t exit_label() const { return label_t::exit; }
// --- Begin ikos fixpoint API
[[nodiscard]] label_t entry_label() const { return label_t::entry; }
[[nodiscard]] const_succ_range next_nodes(const label_t& _label) const {
return boost::make_iterator_range(get_node(_label).next_blocks());
}
[[nodiscard]] const_pred_range prev_nodes(const label_t& _label) const {
return boost::make_iterator_range(get_node(_label).prev_blocks());
}
succ_range next_nodes(const label_t& _label) { return boost::make_iterator_range(get_node(_label).next_blocks()); }
pred_range prev_nodes(const label_t& _label) { return boost::make_iterator_range(get_node(_label).prev_blocks()); }
basic_block_t& get_node(const label_t& _label) {
auto it = m_blocks.find(_label);
if (it == m_blocks.end()) {
CRAB_ERROR("Basic block ", _label, " not found in the CFG: ", __LINE__);
}
return it->second;
}
[[nodiscard]] const basic_block_t& get_node(const label_t& _label) const {
auto it = m_blocks.find(_label);
if (it == m_blocks.end()) {
CRAB_ERROR("Basic block ", _label, " not found in the CFG: ", __LINE__);
}
return it->second;
}
// --- End ikos fixpoint API
basic_block_t& insert(const label_t& _label) {
auto it = m_blocks.find(_label);
if (it != m_blocks.end())
return it->second;
m_blocks.emplace(_label, _label);
return get_node(_label);
}
void remove(const label_t& _label) {
if (_label == entry_label())
CRAB_ERROR("Cannot remove entry block");
if (_label == exit_label())
CRAB_ERROR("Cannot remove exit block");
std::vector<std::pair<basic_block_t*, basic_block_t*>> dead_edges;
auto& bb = get_node(_label);
for (const auto& id : boost::make_iterator_range(bb.prev_blocks())) {
if (_label != id) {
dead_edges.emplace_back(&get_node(id), &bb);
}
}
for (const auto& id : boost::make_iterator_range(bb.next_blocks())) {
if (_label != id) {
dead_edges.emplace_back(&bb, &get_node(id));
}
}
for (auto p : dead_edges) {
(*p.first) -= (*p.second);
}
m_blocks.erase(_label);
}
//! return a begin iterator of basic_block_t's
iterator begin() { return m_blocks.begin(); }
//! return an end iterator of basic_block_t's
iterator end() { return m_blocks.end(); }
[[nodiscard]] const_iterator begin() const { return m_blocks.begin(); }
[[nodiscard]] const_iterator end() const { return m_blocks.end(); }
//! return a begin iterator of label_t's
label_iterator label_begin() { return boost::make_transform_iterator(m_blocks.begin(), get_label()); }
//! return an end iterator of label_t's
label_iterator label_end() { return boost::make_transform_iterator(m_blocks.end(), get_label()); }
//! return a begin iterator of label_t's
[[nodiscard]] std::vector<label_t> labels() const {
std::vector<label_t> res;
res.reserve(m_blocks.size());
for (const auto& p : m_blocks)
res.push_back(p.first);
return res;
}
[[nodiscard]] size_t size() const { return static_cast<size_t>(std::distance(begin(), end())); }
void simplify() {
std::set<label_t> worklist(this->label_begin(), this->label_end());
while (!worklist.empty()) {
label_t label = *worklist.begin();
worklist.erase(label);
basic_block_t& bb = get_node(label);
if (bb.in_degree() == 1 && get_parent(label).out_degree() == 1) {
continue;
}
while (bb.out_degree() == 1) {
basic_block_t& next_bb = get_child(label);
if (&next_bb == &bb || next_bb.in_degree() != 1) {
break;
}
if (next_bb.label() == exit_label()) {
break;
}
worklist.erase(next_bb.label());
bb.move_back(next_bb);
bb -= next_bb;
auto children = next_bb.m_next;
for (const label_t& next_next_label : children) {
basic_block_t& next_next_bb = get_node(next_next_label);
bb >> next_next_bb;
}
// delete next_bb entirely
remove(next_bb.label());
}
}
}
[[nodiscard]] std::vector<label_t> sorted_labels() const {
std::vector<label_t> labels = this->labels();
std::sort(labels.begin(), labels.end());
return labels;
}
private:
// Helpers
[[nodiscard]] bool has_one_child(const label_t& b) const {
auto rng = next_nodes(b);
return (std::distance(rng.begin(), rng.end()) == 1);
}
[[nodiscard]] bool has_one_parent(const label_t& b) const {
auto rng = prev_nodes(b);
return (std::distance(rng.begin(), rng.end()) == 1);
}
basic_block_t& get_child(const label_t& b) {
assert(has_one_child(b));
auto rng = next_nodes(b);
return get_node(*(rng.begin()));
}
basic_block_t& get_parent(const label_t& b) {
assert(has_one_parent(b));
auto rng = prev_nodes(b);
return get_node(*(rng.begin()));
}
// mark reachable blocks from curId
template <class AnyCfg>
void mark_alive_blocks(label_t curId, AnyCfg& cfg_t, visited_t& visited) {
if (visited.count(curId) > 0)
return;
visited.insert(curId);
for (const auto& child : cfg_t.next_nodes(curId)) {
mark_alive_blocks(child, cfg_t, visited);
}
}
void remove_unreachable_blocks();
// remove blocks that cannot reach the exit block
void remove_useless_blocks();
};
// Viewing a cfg_t with all edges and block statements reversed. Useful for backward analysis.
class cfg_rev_t final {
public:
using node_t = label_t; // for Bgl graphs
using pred_range = typename cfg_t::succ_range;
using succ_range = typename cfg_t::pred_range;
using const_pred_range = typename cfg_t::const_succ_range;
using const_succ_range = typename cfg_t::const_pred_range;
// For BGL
using succ_iterator = typename basic_block_t::succ_iterator;
using pred_iterator = typename basic_block_t::pred_iterator;
using const_succ_iterator = typename basic_block_t::const_succ_iterator;
using const_pred_iterator = typename basic_block_t::const_pred_iterator;
public:
using basic_block_rev_map_t = std::map<label_t, basic_block_rev_t>;
using iterator = typename basic_block_rev_map_t::iterator;
using const_iterator = typename basic_block_rev_map_t::const_iterator;
using label_iterator = typename cfg_t::label_iterator;
using const_label_iterator = typename cfg_t::const_label_iterator;
private:
cfg_t& _cfg;
basic_block_rev_map_t _rev_bbs;
public:
explicit cfg_rev_t(cfg_t& cfg) : _cfg(cfg) {
// Create basic_block_rev_t from basic_block_t objects
// Note that basic_block_rev_t is also a view of basic_block_t so it
// doesn't modify basic_block_t objects.
for (auto& [label, bb] : cfg) {
_rev_bbs.emplace(label, bb);
}
}
cfg_rev_t(const cfg_rev_t& o) = default;
cfg_rev_t(cfg_rev_t&& o) noexcept : _cfg(o._cfg), _rev_bbs(std::move(o._rev_bbs)) {}
[[nodiscard]] label_t entry_label() const { return _cfg.exit_label(); }
[[nodiscard]] const_succ_range next_nodes(const label_t& bb) const { return _cfg.prev_nodes(bb); }
[[nodiscard]] const_pred_range prev_nodes(const label_t& bb) const { return _cfg.next_nodes(bb); }
succ_range next_nodes(const label_t& bb) { return _cfg.prev_nodes(bb); }
pred_range prev_nodes(const label_t& bb) { return _cfg.next_nodes(bb); }
basic_block_rev_t& get_node(const label_t& _label) {
auto it = _rev_bbs.find(_label);
if (it == _rev_bbs.end())
CRAB_ERROR("Basic block ", _label, " not found in the CFG: ", __LINE__);
return it->second;
}
[[nodiscard]] const basic_block_rev_t& get_node(const label_t& _label) const {
auto it = _rev_bbs.find(_label);
if (it == _rev_bbs.end())
CRAB_ERROR("Basic block ", _label, " not found in the CFG: ", __LINE__);
return it->second;
}
iterator begin() { return _rev_bbs.begin(); }
iterator end() { return _rev_bbs.end(); }
[[nodiscard]] const_iterator begin() const { return _rev_bbs.begin(); }
[[nodiscard]] const_iterator end() const { return _rev_bbs.end(); }
label_iterator label_begin() { return _cfg.label_begin(); }
label_iterator label_end() { return _cfg.label_end(); }
[[nodiscard]] label_t exit_label() const { return _cfg.entry_label(); }
};
inline void cfg_t::remove_useless_blocks() {
cfg_rev_t rev_cfg(*this);
visited_t useful, useless;
mark_alive_blocks(rev_cfg.entry_label(), rev_cfg, useful);
if (!useful.count(exit_label()))
CRAB_ERROR("Exit block must be reachable");
for (auto const& label : labels()) {
if (!useful.count(label)) {
useless.insert(label);
}
}
for (const auto& _label : useless) {
remove(_label);
}
}
inline void cfg_t::remove_unreachable_blocks() {
visited_t alive, dead;
mark_alive_blocks(entry_label(), *this, alive);
for (auto const& label : labels()) {
if (alive.count(label) <= 0) {
dead.insert(label);
}
}
if (dead.count(exit_label()))
CRAB_ERROR("Exit block must be reachable");
for (const auto& _label : dead) {
remove(_label);
}
}
} // end namespace crab
using crab::basic_block_t;
using crab::cfg_t;
std::vector<std::string> stats_headers();
std::map<std::string, int> collect_stats(const cfg_t&);
cfg_t prepare_cfg(const InstructionSeq& prog, const program_info& info, bool simplify);
void explicate_assertions(cfg_t& cfg, const program_info& info);
void print_dot(const cfg_t& cfg, std::ostream& out);
void print_dot(const cfg_t& cfg, const std::string& outfile);
std::ostream& operator<<(std::ostream& o, const crab::basic_block_t& bb);
std::ostream& operator<<(std::ostream& o, const crab::basic_block_rev_t& bb);
std::ostream& operator<<(std::ostream& o, const cfg_t& cfg);
|
// Copyright 2015 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 "services/tracing/trace_recorder_impl.h"
#include <utility>
namespace tracing {
TraceRecorderImpl::TraceRecorderImpl(
mojo::InterfaceRequest<TraceRecorder> request,
TraceDataSink* sink)
: sink_(sink), binding_(this, std::move(request)) {}
TraceRecorderImpl::~TraceRecorderImpl() {
}
void TraceRecorderImpl::TryRead() {
binding_.WaitForIncomingMethodCall(MojoDeadline(0));
}
mojo::Handle TraceRecorderImpl::TraceRecorderHandle() const {
return binding_.handle();
}
void TraceRecorderImpl::Record(const mojo::String& json) {
sink_->AddChunk(json.To<std::string>());
}
} // namespace tracing
|
// Python includes
#include <Python.h>
// Stl includes
#include <fstream>
// Qt includes
#include <QResource>
#include <QMetaType>
#include <QFile>
#include <QDir>
// hyperion util includes
#include <utils/jsonschema/JsonSchemaChecker.h>
// effect engine includes
#include <effectengine/EffectEngine.h>
#include "Effect.h"
EffectEngine::EffectEngine(Hyperion * hyperion, const Json::Value & jsonEffectConfig) :
_hyperion(hyperion),
_availableEffects(),
_activeEffects(),
_mainThreadState(nullptr)
{
qRegisterMetaType<std::vector<ColorRgb>>("std::vector<ColorRgb>");
// connect the Hyperion channel clear feedback
connect(_hyperion, SIGNAL(channelCleared(int)), this, SLOT(channelCleared(int)));
connect(_hyperion, SIGNAL(allChannelsCleared()), this, SLOT(allChannelsCleared()));
// read all effects
const Json::Value & paths = jsonEffectConfig["paths"];
for (Json::UInt i = 0; i < paths.size(); ++i)
{
const std::string & path = paths[i].asString();
QDir directory(QString::fromStdString(path));
if (!directory.exists())
{
std::cerr << "Effect directory can not be loaded: " << path << std::endl;
continue;
}
QStringList filenames = directory.entryList(QStringList() << "*.json", QDir::Files, QDir::Name | QDir::IgnoreCase);
foreach (const QString & filename, filenames)
{
EffectDefinition def;
if (loadEffectDefinition(path, filename.toStdString(), def))
{
_availableEffects.push_back(def);
}
}
}
// initialize the python interpreter
std::cout << "Initializing Python interpreter" << std::endl;
Effect::registerHyperionExtensionModule();
Py_InitializeEx(0);
PyEval_InitThreads(); // Create the GIL
_mainThreadState = PyEval_SaveThread();
}
EffectEngine::~EffectEngine()
{
// clean up the Python interpreter
std::cout << "Cleaning up Python interpreter" << std::endl;
PyEval_RestoreThread(_mainThreadState);
Py_Finalize();
}
const std::list<EffectDefinition> &EffectEngine::getEffects() const
{
return _availableEffects;
}
bool EffectEngine::loadEffectDefinition(const std::string &path, const std::string &effectConfigFile, EffectDefinition & effectDefinition)
{
std::string fileName = path + QDir::separator().toAscii() + effectConfigFile;
std::ifstream file(fileName.c_str());
if (!file.is_open())
{
std::cerr << "Effect file '" << fileName << "' could not be loaded" << std::endl;
return false;
}
// Read the json config file
Json::Reader jsonReader;
Json::Value config;
if (!jsonReader.parse(file, config, false))
{
std::cerr << "Error while reading effect '" << fileName << "': " << jsonReader.getFormattedErrorMessages() << std::endl;
return false;
}
// Read the json schema file
QResource schemaData(":effect-schema");
JsonSchemaChecker schemaChecker;
Json::Value schema;
Json::Reader().parse(reinterpret_cast<const char *>(schemaData.data()), reinterpret_cast<const char *>(schemaData.data()) + schemaData.size(), schema, false);
schemaChecker.setSchema(schema);
if (!schemaChecker.validate(config))
{
const std::list<std::string> & errors = schemaChecker.getMessages();
foreach (const std::string & error, errors) {
std::cerr << "Error while checking '" << fileName << "':" << error << std::endl;
}
return false;
}
// setup the definition
effectDefinition.name = config["name"].asString();
effectDefinition.script = path + QDir::separator().toAscii() + config["script"].asString();
effectDefinition.args = config["args"];
// return succes
std::cout << "Effect loaded: " + effectDefinition.name << std::endl;
return true;
}
int EffectEngine::runEffect(const std::string &effectName, int priority, int timeout)
{
return runEffect(effectName, Json::Value(Json::nullValue), priority, timeout);
}
int EffectEngine::runEffect(const std::string &effectName, const Json::Value &args, int priority, int timeout)
{
std::cout << "run effect " << effectName << " on channel " << priority << std::endl;
const EffectDefinition * effectDefinition = nullptr;
for (const EffectDefinition & e : _availableEffects)
{
if (e.name == effectName)
{
effectDefinition = &e;
break;
}
}
if (effectDefinition == nullptr)
{
// no such effect
std::cerr << "effect " << effectName << " not found" << std::endl;
return -1;
}
return runEffectScript(effectDefinition->script, args.isNull() ? effectDefinition->args : args, priority, timeout);
}
int EffectEngine::runEffectScript(const std::string &script, const Json::Value &args, int priority, int timeout)
{
// clear current effect on the channel
channelCleared(priority);
// create the effect
Effect * effect = new Effect(_mainThreadState, priority, timeout, script, args);
connect(effect, SIGNAL(setColors(int,std::vector<ColorRgb>,int,bool)), _hyperion, SLOT(setColors(int,std::vector<ColorRgb>,int,bool)), Qt::QueuedConnection);
connect(effect, SIGNAL(effectFinished(Effect*)), this, SLOT(effectFinished(Effect*)));
_activeEffects.push_back(effect);
// start the effect
effect->start();
return 0;
}
void EffectEngine::channelCleared(int priority)
{
for (Effect * effect : _activeEffects)
{
if (effect->getPriority() == priority)
{
effect->abort();
}
}
}
void EffectEngine::allChannelsCleared()
{
for (Effect * effect : _activeEffects)
{
effect->abort();
}
}
void EffectEngine::effectFinished(Effect *effect)
{
if (!effect->isAbortRequested())
{
// effect stopped by itself. Clear the channel
_hyperion->clear(effect->getPriority());
}
std::cout << "effect finished" << std::endl;
for (auto effectIt = _activeEffects.begin(); effectIt != _activeEffects.end(); ++effectIt)
{
if (*effectIt == effect)
{
_activeEffects.erase(effectIt);
break;
}
}
// cleanup the effect
effect->deleteLater();
}
|
#include <iostream>
#include <vector>
using namespace std;
int main(void)
{
int n, x, sum = 0;
cin >> n >> x;
vector<int> nums(n);
for (int i = 0; i < n; ++i) {
cin >> nums[i];
sum += nums[i];
}
if (sum < x) {
cout << -1 << endl;
return 0;
}
int ret = sum;
for (int i = 1, iend = 1 << n; i < iend; ++i) {
if (ret == x)
break;
int cur = 0;
for (int j = 0; j < n; ++j) {
if (((1 << j) & i))
cur += nums[j];
if (cur >= x) {
break;
}
}
if (cur >= x && cur < ret)
ret = cur;
}
cout << ret << endl;
return 0;
}
|
/*
* Copyright (c) 2017-2021, The OSKAR Developers.
* See the LICENSE file at the top-level directory of this distribution.
*/
#include <gtest/gtest.h>
#include "math/oskar_prefix_sum.h"
#include "utility/oskar_timer.h"
#include "utility/oskar_device.h"
#include <cstdlib>
static const bool save = true;
void run_test(const oskar_Mem* in_cpu, const char* fname)
{
int status = 0;
const int n = (int) oskar_mem_length(in_cpu);
// Run on CPU.
oskar_Mem* out_cpu = oskar_mem_create(OSKAR_INT, OSKAR_CPU, n + 1, &status);
oskar_Timer* tmr = oskar_timer_create(OSKAR_TIMER_NATIVE);
oskar_timer_start(tmr);
oskar_prefix_sum(n, in_cpu, out_cpu, &status);
EXPECT_EQ(0, status);
printf("Prefix sum on CPU took %.3f sec\n", oskar_timer_elapsed(tmr));
oskar_timer_free(tmr);
#ifdef OSKAR_HAVE_CUDA
// Run on GPU with CUDA.
oskar_Mem* in_gpu = oskar_mem_create_copy(in_cpu, OSKAR_GPU, &status);
oskar_Mem* out_gpu = oskar_mem_create(OSKAR_INT, OSKAR_GPU, n + 1, &status);
tmr = oskar_timer_create(OSKAR_TIMER_CUDA);
oskar_timer_start(tmr);
oskar_prefix_sum(n, in_gpu, out_gpu, &status);
EXPECT_EQ(0, status);
printf("Prefix sum on GPU took %.3f sec\n", oskar_timer_elapsed(tmr));
oskar_timer_free(tmr);
// Check consistency between CPU and GPU results.
oskar_Mem* out_cmp_gpu = oskar_mem_create_copy(out_gpu, OSKAR_CPU, &status);
EXPECT_EQ(0, oskar_mem_different(out_cpu, out_cmp_gpu, n + 1, &status));
#endif
#ifdef OSKAR_HAVE_OPENCL
// Run on OpenCL.
oskar_Mem* in_cl = oskar_mem_create_copy(in_cpu, OSKAR_CL, &status);
oskar_Mem* out_cl = oskar_mem_create(OSKAR_INT, OSKAR_CL, n + 1, &status);
tmr = oskar_timer_create(OSKAR_TIMER_CL);
char* device_name = oskar_device_name(OSKAR_CL, 0);
oskar_timer_start(tmr);
oskar_prefix_sum(n, in_cl, out_cl, &status);
EXPECT_EQ(0, status);
printf("Prefix sum on OpenCL device '%s' took %.3f sec\n", device_name,
oskar_timer_elapsed(tmr));
free(device_name);
oskar_timer_free(tmr);
// Check consistency between CPU and OpenCL results.
oskar_Mem* out_cmp_cl = oskar_mem_create_copy(out_cl, OSKAR_CPU, &status);
EXPECT_EQ(0, oskar_mem_different(out_cpu, out_cmp_cl, n + 1, &status));
#endif
if (save)
{
size_t num_mem = 1;
FILE* fhan = fopen(fname, "w");
#ifdef OSKAR_HAVE_CUDA
num_mem += 1;
#endif
#ifdef OSKAR_HAVE_OPENCL
num_mem += 1;
#endif
oskar_mem_save_ascii(fhan, num_mem, 0, n + 1, &status, out_cpu
#ifdef OSKAR_HAVE_CUDA
, out_cmp_gpu
#endif
#ifdef OSKAR_HAVE_OPENCL
, out_cmp_cl
#endif
);
fclose(fhan);
}
// Clean up.
#ifdef OSKAR_HAVE_CUDA
oskar_mem_free(in_gpu, &status);
oskar_mem_free(out_gpu, &status);
oskar_mem_free(out_cmp_gpu, &status);
#endif
#ifdef OSKAR_HAVE_OPENCL
oskar_mem_free(in_cl, &status);
oskar_mem_free(out_cl, &status);
oskar_mem_free(out_cmp_cl, &status);
#endif
oskar_mem_free(out_cpu, &status);
}
TEST(prefix_sum, test1)
{
int n = 100000, status = 0;
oskar_Mem* in = oskar_mem_create(OSKAR_INT, OSKAR_CPU, n, &status);
int* t = oskar_mem_int(in, &status);
srand(1556);
for (int i = 0; i < n; ++i)
{
t[i] = (int) (10.0 * rand() / ((double) RAND_MAX));
}
t[0] = 3;
run_test(in, "prefix_sum_test1.txt");
oskar_mem_free(in, &status);
}
TEST(prefix_sum, test2)
{
int n = 4, status = 0;
oskar_Mem* in = oskar_mem_create(OSKAR_INT, OSKAR_CPU, n, &status);
int* t = oskar_mem_int(in, &status);
for (int i = 0; i < n; ++i) t[i] = i + 1;
run_test(in, "prefix_sum_test2.txt");
oskar_mem_free(in, &status);
}
|
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2017 - ROLI Ltd.
JUCE is an open source library subject to commercial or open-source
licensing.
By using JUCE, you agree to the terms of both the JUCE 5 End-User License
Agreement and JUCE 5 Privacy Policy (both updated and effective as of the
27th April 2017).
End User License Agreement: www.juce.com/juce-5-licence
Privacy Policy: www.juce.com/juce-5-privacy-policy
Or: You may also use this code under the terms of the GPL v3 (see
www.gnu.org/licenses).
JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
DISCLAIMED.
==============================================================================
*/
#include "../Application/jucer_Headers.h"
#include "jucer_JucerDocument.h"
#include "Components/jucer_ComponentUndoableAction.h"
#include "Properties/jucer_JustificationProperty.h"
#include "Properties/jucer_FontPropertyComponent.h"
#include "Properties/jucer_ComponentBooleanProperty.h"
#include "Properties/jucer_ComponentChoiceProperty.h"
#include "Properties/jucer_ComponentTextProperty.h"
#include "Properties/jucer_ComponentColourProperty.h"
#include "Properties/jucer_FilePropertyComponent.h"
#include "PaintElements/jucer_ImageResourceProperty.h"
#include "jucer_ObjectTypes.h"
#include "PaintElements/jucer_PaintElementUndoableAction.h"
#include "PaintElements/jucer_PaintElementRectangle.h"
#include "PaintElements/jucer_PaintElementRoundedRectangle.h"
#include "PaintElements/jucer_PaintElementImage.h"
#include "PaintElements/jucer_PaintElementEllipse.h"
#include "PaintElements/jucer_PaintElementPath.h"
#include "PaintElements/jucer_PaintElementText.h"
#include "PaintElements/jucer_PaintElementGroup.h"
#include "Components/jucer_ButtonHandler.h"
#include "Components/jucer_TextButtonHandler.h"
#include "Components/jucer_ToggleButtonHandler.h"
#include "Components/jucer_SliderHandler.h"
#include "Components/jucer_LabelHandler.h"
#include "Components/jucer_TextEditorHandler.h"
#include "Components/jucer_ComboBoxHandler.h"
#include "Components/jucer_GroupComponentHandler.h"
#include "Components/jucer_JucerComponentHandler.h"
#include "Components/jucer_HyperlinkButtonHandler.h"
#include "Components/jucer_ViewportHandler.h"
#include "Components/jucer_TabbedComponentHandler.h"
#include "Components/jucer_TreeViewHandler.h"
#include "Components/jucer_GenericComponentHandler.h"
#include "Components/jucer_ImageButtonHandler.h"
namespace ObjectTypes
{
static const char* const elementNames[] =
{
"Rectangle",
"Rounded Rectangle",
"Ellipse",
"Path",
"Image",
"Text",
nullptr
};
const char** const elementTypeNames = (const char**) elementNames;
const int numElementTypes = (sizeof (elementNames) / sizeof (elementNames[0])) - 1;
PaintElement* createNewElement (const int index, PaintRoutine* owner)
{
switch (index)
{
case 0: return new PaintElementRectangle (owner);
case 1: return new PaintElementRoundedRectangle (owner);
case 2: return new PaintElementEllipse (owner);
case 3: return new PaintElementPath (owner);
case 4: return new PaintElementImage (owner);
case 5: return new PaintElementText (owner);
default: jassertfalse; break;
}
return nullptr;
}
PaintElement* createNewImageElement (PaintRoutine* owner)
{
return new PaintElementImage (owner);
}
PaintElement* createElementForXml (const XmlElement* const e, PaintRoutine* const owner)
{
jassert (e != nullptr);
std::unique_ptr<PaintElement> pe;
if (e->hasTagName (PaintElementRectangle::getTagName())) pe.reset (new PaintElementRectangle (owner));
else if (e->hasTagName (PaintElementRoundedRectangle::getTagName())) pe.reset (new PaintElementRoundedRectangle (owner));
else if (e->hasTagName (PaintElementEllipse::getTagName())) pe.reset (new PaintElementEllipse (owner));
else if (e->hasTagName (PaintElementImage::getTagName())) pe.reset (new PaintElementImage (owner));
else if (e->hasTagName (PaintElementPath::getTagName())) pe.reset (new PaintElementPath (owner));
else if (e->hasTagName (PaintElementText::getTagName())) pe.reset (new PaintElementText (owner));
else if (e->hasTagName (PaintElementGroup::getTagName())) pe.reset (new PaintElementGroup (owner));
if (pe != nullptr && pe->loadFromXml (*e))
return pe.release();
jassertfalse;
return nullptr;
}
//==============================================================================
static TextButtonHandler textButton;
static ToggleButtonHandler toggleButton;
static SliderHandler slider;
static LabelHandler label;
static TextEditorHandler textEditor;
static ComboBoxHandler comboBox;
static JucerComponentHandler jucerCompHandler;
static GroupComponentHandler group;
static HyperlinkButtonHandler hyperlink;
static ViewportHandler viewport;
static TabbedComponentHandler tabbedComp;
static TreeViewHandler treeview;
static GenericComponentHandler genericHandler;
static ImageButtonHandler imageButtonHandler;
static ComponentTypeHandler* const compTypes[] =
{
&textButton,
&toggleButton,
&slider,
&label,
&textEditor,
&comboBox,
&group,
&jucerCompHandler,
&hyperlink,
&viewport,
&tabbedComp,
&treeview,
&genericHandler,
&imageButtonHandler,
nullptr
};
ComponentTypeHandler** const componentTypeHandlers = (ComponentTypeHandler**) compTypes;
const int numComponentTypes = numElementsInArray (compTypes) - 1;
}
|
#ifndef CONTROLS_HPP
#define CONTROLS_HPP
#include <glm/glm.hpp>
#include "Config.hpp"
struct GLFWwindow;
namespace flogl {
class Config;
class Window
{
public:
Window(const Config& config);
~Window();
void processInputs();
const glm::mat4& getViewMatrix() const;
const glm::mat4& getProjectionMatrix() const;
void swapBuffers();
bool shouldClose() const;
private:
glm::vec3 getDirection() const;
static void doKeyCallback(GLFWwindow* window, int key, int scan_code, int action, int mods);
void keyCallback(int key, int scan_code, int action, int mods);
static void doScrollCallback(GLFWwindow* window, double xoffset, double yoffset);
void scrollCallback(float xoffset, float yoffset);
void selectView(unsigned index);
Config m_config;
GLFWwindow* m_window;
glm::vec3 m_position;
float m_horizontal_angle_rad;
float m_vertical_angle_rad;
float m_fov_deg;
float m_speed;
float m_scroll_speed;
float m_mouse_speed;
glm::mat4 m_view_matrix;
glm::mat4 m_projection_matrix;
double m_last_time;
bool m_control_mouse;
bool m_shift_pressed;
bool m_should_close;
};
}
#endif
|
/**
* Copyright (c) 2013 David Young dayoung@goliathdesigns.com
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#include "PrecompiledHeaders.h"
#include "demo_framework/include/AgentPath.h"
AgentPath::AgentPath() : PolylinePathway()
{
}
AgentPath::AgentPath(
const std::vector<Ogre::Vector3>& points,
const Ogre::Real radius,
const bool cyclic)
{
OpenSteer::Vec3 vec3Point[MAX_PATH_POINTS];
assert(points.size() < MAX_PATH_POINTS);
std::vector<Ogre::Vector3>::const_iterator it;
int count = 0;
for (it = points.begin(); it != points.end(); ++it)
{
const Ogre::Vector3& vec = *it;
vec3Point[count].x = vec.x;
vec3Point[count].y = vec.y;
vec3Point[count].z = vec.z;
++count;
}
initialize(count, vec3Point, static_cast<float>(radius), cyclic);
}
AgentPath::~AgentPath()
{
}
AgentPath::AgentPath(const AgentPath& path)
{
initialize(path.pointCount, path.points, path.radius, path.cyclic);
}
AgentPath& AgentPath::operator=(const AgentPath& path)
{
initialize(path.pointCount, path.points, path.radius, path.cyclic);
return *this;
}
Ogre::Real AgentPath::GetDistanceAlongPath(const Ogre::Vector3& position) const
{
const OpenSteer::Vec3 vec3(position.x, position.y, position.z);
return const_cast<AgentPath*>(this)->mapPointToPathDistance(vec3);
}
Ogre::Vector3 AgentPath::GetNearestPointOnPath(
const Ogre::Vector3& position) const
{
const OpenSteer::Vec3 vec3(position.x, position.y, position.z);
OpenSteer::Vec3 tangent;
float outside;
const OpenSteer::Vec3 pointOnPath =
const_cast<AgentPath*>(this)->mapPointToPath(vec3, tangent, outside);
return Ogre::Vector3(pointOnPath.x, pointOnPath.y, pointOnPath.z);
}
size_t AgentPath::GetNumberOfPathPoints() const
{
return pointCount;
}
Ogre::Real AgentPath::GetPathLength() const
{
// XXX(8-22-13) - This variable may become private in the future.
return Ogre::Real(totalPathLength);
}
void AgentPath::GetPathPoints(std::vector<Ogre::Vector3>& outPoints) const
{
outPoints.clear();
const size_t pathPoints = GetNumberOfPathPoints();
for (size_t index = 0; index < pathPoints; ++index)
{
const OpenSteer::Vec3& vec3 = points[index];
outPoints.push_back(Ogre::Vector3(vec3.x, vec3.y, vec3.z));
}
}
Ogre::Vector3 AgentPath::GetPointOnPath(const Ogre::Real distance) const
{
const OpenSteer::Vec3 pointOnPath =
const_cast<AgentPath*>(this)->mapPathDistanceToPoint(distance);
return Ogre::Vector3(pointOnPath.x, pointOnPath.y, pointOnPath.z);
}
Ogre::Real AgentPath::GetRadius() const
{
return radius;
}
unsigned int AgentPath::GetSegmentCount() const
{
return static_cast<unsigned int>(pointCount) - 1;
}
|
#include "vcpkg.h"
#include <regex>
#include "vcpkg_Files.h"
#include "vcpkglib_helpers.h"
namespace
{
using namespace vcpkg;
struct Parser
{
Parser(const char* c, const char* e) : cur(c), end(e)
{
}
private:
const char* cur;
const char* const end;
void peek(char& ch) const
{
if (cur == end)
ch = 0;
else
ch = *cur;
}
void next(char& ch)
{
if (cur == end)
ch = 0;
else
{
++cur;
peek(ch);
}
}
void skip_spaces(char& ch)
{
while (ch == ' ' || ch == '\t')
next(ch);
}
static bool is_alphanum(char ch)
{
return (ch >= 'A' && ch <= 'Z')
|| (ch >= 'a' && ch <= 'z')
|| (ch >= '0' && ch <= '9');
}
static bool is_lineend(char ch)
{
return ch == '\r' || ch == '\n' || ch == 0;
}
void get_fieldvalue(char& ch, std::string& fieldvalue)
{
fieldvalue.clear();
auto beginning_of_line = cur;
do
{
// scan to end of current line (it is part of the field value)
while (!is_lineend(ch))
next(ch);
fieldvalue.append(beginning_of_line, cur);
if (ch == '\r')
next(ch);
if (ch == '\n')
next(ch);
if (is_alphanum(ch))
{
// Line begins a new field.
return;
}
beginning_of_line = cur;
// Line may continue the current field with data or terminate the paragraph,
// depending on first nonspace character.
skip_spaces(ch);
if (is_lineend(ch))
{
// Line was whitespace or empty.
// This terminates the field and the paragraph.
// We leave the blank line's whitespace consumed, because it doesn't matter.
return;
}
// First nonspace is not a newline. This continues the current field value.
// We forcibly convert all newlines into single '\n' for ease of text handling later on.
fieldvalue.push_back('\n');
}
while (true);
}
void get_fieldname(char& ch, std::string& fieldname)
{
auto begin_fieldname = cur;
while (is_alphanum(ch) || ch == '-')
next(ch);
Checks::check_throw(ch == ':', "Expected ':'");
fieldname = std::string(begin_fieldname, cur);
// skip ': '
next(ch);
skip_spaces(ch);
}
void get_paragraph(char& ch, std::unordered_map<std::string, std::string>& fields)
{
fields.clear();
std::string fieldname;
std::string fieldvalue;
do
{
get_fieldname(ch, fieldname);
auto it = fields.find(fieldname);
Checks::check_throw(it == fields.end(), "Duplicate field");
get_fieldvalue(ch, fieldvalue);
fields.emplace(fieldname, fieldvalue);
}
while (!is_lineend(ch));
}
public:
std::vector<std::unordered_map<std::string, std::string>> get_paragraphs()
{
std::vector<std::unordered_map<std::string, std::string>> paragraphs;
char ch;
peek(ch);
while (ch != 0)
{
if (ch == '\n' || ch == '\r' || ch == ' ' || ch == '\t')
{
next(ch);
continue;
}
paragraphs.emplace_back();
get_paragraph(ch, paragraphs.back());
}
return paragraphs;
}
};
}
namespace vcpkg
{
std::string shorten_description(const std::string& desc)
{
auto simple_desc = std::regex_replace(desc.substr(0, 49), std::regex("\\n( |\\t)?"), "");
if (desc.size() > 49)
simple_desc.append("...");
return simple_desc;
}
std::vector<std::unordered_map<std::string, std::string>> get_paragraphs(const fs::path& control_path)
{
return parse_paragraphs(Files::get_contents(control_path).get_or_throw());
}
std::vector<std::unordered_map<std::string, std::string>> parse_paragraphs(const std::string& str)
{
return Parser(str.c_str(), str.c_str() + str.size()).get_paragraphs();
}
}
|
#include <QtGlobal>
// Automatically generated by extract_strings.py
#ifdef __GNUC__
#define UNUSED __attribute__((unused))
#else
#define UNUSED
#endif
static const char UNUSED *diminutivecoin_strings[] = {QT_TRANSLATE_NOOP("diminutivecoin-core", "DiminutiveCoin version"),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Usage:"),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Send command to -server or diminutivecoind"),
QT_TRANSLATE_NOOP("diminutivecoin-core", "List commands"),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Get help for a command"),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Options:"),
QT_TRANSLATE_NOOP("diminutivecoin-core", "This help message"),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Specify configuration file (default: diminutivecoin.conf)"),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Specify pid file (default: diminutivecoind.pid)"),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Specify data directory"),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Specify wallet file (within data directory)"),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Set database cache size in megabytes (default: 25)"),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Set database disk log size in megabytes (default: 100)"),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Specify connection timeout in milliseconds (default: 5000)"),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Connect through SOCKS5 proxy"),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Use proxy to reach tor hidden services (default: same as -proxy)"),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Allow DNS lookups for -addnode, -seednode and -connect"),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Listen for connections on <port> (default: 16000 or testnet: 25798)"),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Maintain at most <n> connections to peers (default: 125)"),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Add a node to connect to and attempt to keep the connection open"),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Connect only to the specified node(s)"),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Connect to a node to retrieve peer addresses, and disconnect"),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Specify your own public address"),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Only connect to nodes in network <net> (IPv4, IPv6 or Tor)"),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Discover own IP address (default: 1 when listening and no -externalip)"),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Accept connections from outside (default: 1 if no -proxy or -connect)"),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Bind to given address. Use [host]:port notation for IPv6"),
QT_TRANSLATE_NOOP("diminutivecoin-core", ""
"Query for peer addresses via DNS lookup, if low on addresses (default: 1 "
"unless -connect)"),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Always query for peer addresses via DNS lookup (default: 0)"),
QT_TRANSLATE_NOOP("diminutivecoin-core", ""
"Sync time with other nodes. Disable if time on your system is precise e.g. "
"syncing with NTP (default: 1)"),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Threshold for disconnecting misbehaving peers (default: 100)"),
QT_TRANSLATE_NOOP("diminutivecoin-core", ""
"Number of seconds to keep misbehaving peers from reconnecting (default: "
"86400)"),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)"),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)"),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Fee per KB to add to transactions you send"),
QT_TRANSLATE_NOOP("diminutivecoin-core", ""
"When creating transactions, ignore inputs with value less than this "
"(default: 0.01)"),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Accept command line and JSON-RPC commands"),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Run in the background as a daemon and accept commands"),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Use the test network"),
QT_TRANSLATE_NOOP("diminutiveoin-core", ""
"Output debugging information (default: 0, supplying <category> is optional)"),
QT_TRANSLATE_NOOP("diminutivecoin-core", "If <category> is not supplied, output all debugging information."),
QT_TRANSLATE_NOOP("diminutivecoin-core", "<category> can be:"),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Prepend debug output with timestamp"),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Shrink debug.log file on client startup (default: 1 when no -debug)"),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Send trace/debug info to console instead of debug.log file"),
QT_TRANSLATE_NOOP("diminutivecoin-core", ""
"Enter regression test mode, which uses a special chain in which blocks can "
"be solved instantly. This is intended for regression testing tools and app "
"development."),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Username for JSON-RPC connections"),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Password for JSON-RPC connections"),
QT_TRANSLATE_NOOP("diminutivecoin-core", ""
"Listen for JSON-RPC connections on <port> (default: 16001 or testnet: 25799)"),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Allow JSON-RPC connections from specified IP address"),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Send commands to node running on <ip> (default: 127.0.0.1)"),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Wait for RPC server to start"),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Set the number of threads to service RPC calls (default: 4)"),
QT_TRANSLATE_NOOP("diminutivecoin-core", ""
"Execute command when the best block changes (%s in cmd is replaced by block "
"hash)"),
QT_TRANSLATE_NOOP("diminutivecoin-core", ""
"Execute command when a wallet transaction changes (%s in cmd is replaced by "
"TxID)"),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Require a confirmations for change (default: 0)"),
QT_TRANSLATE_NOOP("diminutivecoin-core", ""
"Execute command when a relevant alert is received (%s in cmd is replaced by "
"message)"),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Upgrade wallet to latest format"),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Set key pool size to <n> (default: 100)"),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Rescan the block chain for missing wallet transactions"),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Attempt to recover private keys from a corrupt wallet.dat"),
QT_TRANSLATE_NOOP("diminutivecoin-core", "How many blocks to check at startup (default: 500, 0 = all)"),
QT_TRANSLATE_NOOP("diminutivecoin-core", "How thorough the block verification is (0-6, default: 1)"),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Imports blocks from external blk000?.dat file"),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Keep at most <n> MiB of unconnectable blocks in memory (default: %u)"),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Block creation options:"),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Set minimum block size in bytes (default: 0)"),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Set maximum block size in bytes (default: 250000)"),
QT_TRANSLATE_NOOP("diminutivecoin-core", "SSL options: (see the DiminutiveCoin Wiki for SSL setup instructions)"),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Use OpenSSL (https) for JSON-RPC connections"),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Server certificate file (default: server.cert)"),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Server private key (default: server.pem)"),
QT_TRANSLATE_NOOP("diminutivecoin-core", ""
"Acceptable ciphers (default: TLSv1.2+HIGH:TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!"
"3DES:@STRENGTH)"),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Warning: Deprecated argument -debugnet ignored, use -debug=net"),
QT_TRANSLATE_NOOP("diminutivecoin-core", ""
"Error: Unsupported argument -socks found. Setting SOCKS version isn't "
"possible anymore, only SOCKS5 proxies are supported."),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Invalid amount for -paytxfee=<amount>: '%s'"),
QT_TRANSLATE_NOOP("diminutivecoin-core", ""
"Warning: -paytxfee is set very high! This is the transaction fee you will "
"pay if you send a transaction."),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Invalid amount for -mininput=<amount>: '%s'"),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Initialization sanity check failed. DiminutiveCoin is shutting down."),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Wallet %s resides outside data directory %s."),
QT_TRANSLATE_NOOP("diminutivecoin-core", ""
"Cannot obtain a lock on data directory %s. DiminutiveCoin is probably already "
"running."),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Verifying database integrity..."),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Error initializing wallet database environment %s!"),
QT_TRANSLATE_NOOP("diminutivecoin-core", ""
"Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as "
"wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect "
"you should restore from a backup."),
QT_TRANSLATE_NOOP("diminutivecoin-core", "wallet.dat corrupt, salvage failed"),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Unknown network specified in -onlynet: '%s'"),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Invalid -proxy address: '%s'"),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Invalid -tor address: '%s'"),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Cannot resolve -bind address: '%s'"),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Failed to listen on any port. Use -listen=0 if you want this."),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Cannot resolve -externalip address: '%s'"),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Invalid amount for -reservebalance=<amount>"),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Loading block index..."),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Error loading block database"),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Loading wallet..."),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Error loading wallet.dat: Wallet corrupted"),
QT_TRANSLATE_NOOP("diminutivecoin-core", ""
"Warning: error reading wallet.dat! All keys read correctly, but transaction "
"data or address book entries might be missing or incorrect."),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Error loading wallet.dat: Wallet requires newer version of DiminutiveCoin"),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Wallet needed to be rewritten: restart DiminutiveCoin to complete"),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Error loading wallet.dat"),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Cannot downgrade wallet"),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Cannot write default address"),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Rescanning..."),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Loading addresses..."),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Done loading"),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Warning: This version is obsolete, upgrade required!"),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Error: Disk space is low!"),
QT_TRANSLATE_NOOP("diminutivecoin-core", ""
"This is a pre-release test build - use at your own risk - do not use for "
"mining or merchant applications"),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Error"),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Warning"),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Information"),
QT_TRANSLATE_NOOP("diminutivecoin-core", ""
"Warning: Please check that your computer's date and time are correct! If "
"your clock is wrong DiminutiveCoin will not work properly."),
QT_TRANSLATE_NOOP("diminutivecoin-core", ""
"Unable to bind to %s on this computer. DiminutiveCoin is probably already running."),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Unable to bind to %s on this computer (bind returned error %d, %s)"),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Error: Wallet locked, unable to create transaction!"),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Error: Wallet unlocked for staking only, unable to create transaction."),
QT_TRANSLATE_NOOP("diminutivecoin-core", ""
"Error: This transaction requires a transaction fee of at least %s because of "
"its amount, complexity, or use of recently received funds!"),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Error: Transaction creation failed!"),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Sending..."),
QT_TRANSLATE_NOOP("diminutivecoin-core", ""
"Error: The transaction was rejected! This might happen if some of the coins "
"in your wallet were already spent, such as if you used a copy of wallet.dat "
"and coins were spent in the copy but not marked as spent here."),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Invalid amount"),
QT_TRANSLATE_NOOP("diminutivecoin-core", "Insufficient funds"),
QT_TRANSLATE_NOOP("diminutivecoin-core", ""
"You must set rpcpassword=<password> in the configuration file:\n"
"%s\n"
"If the file does not exist, create it with owner-readable-only file "
"permissions."),
QT_TRANSLATE_NOOP("diminutivecoin-core", "To use the %s option"),
QT_TRANSLATE_NOOP("diminutivecoin-core", ""
"%s, you must set a rpcpassword in the configuration file:\n"
"%s\n"
"It is recommended you use the following random password:\n"
"rpcuser=diminutivecoinrpc\n"
"rpcpassword=%s\n"
"(you do not need to remember this password)\n"
"The username and password MUST NOT be the same.\n"
"If the file does not exist, create it with owner-readable-only file "
"permissions.\n"
"It is also recommended to set alertnotify so you are notified of problems;\n"
"for example: alertnotify=echo %%s | mail -s \"DiminutiveCoin Alert\" admin@foo."
"com\n"),
QT_TRANSLATE_NOOP("diminutivecoin-core", ""
"An error occurred while setting up the RPC port %u for listening on IPv6, "
"falling back to IPv4: %s"),
QT_TRANSLATE_NOOP("diminutivecoin-core", ""
"An error occurred while setting up the RPC port %u for listening on IPv4: %s"),
};
|
#include "stdafx.h"
#include "RendererWindow.h"
#include "RenderPath3D.h"
#include "Editor.h"
#include "wiPhysicsEngine.h"
void RendererWindow::Create(EditorComponent* editor)
{
wiWindow::Create("Renderer Window");
wiRenderer::SetToDrawDebugEnvProbes(true);
wiRenderer::SetToDrawGridHelper(true);
wiRenderer::SetToDrawDebugCameras(true);
SetSize(XMFLOAT2(580, 550));
float x = 220, y = 5, step = 20, itemheight = 18;
vsyncCheckBox.Create("VSync: ");
vsyncCheckBox.SetTooltip("Toggle vertical sync");
vsyncCheckBox.SetScriptTip("SetVSyncEnabled(opt bool enabled)");
vsyncCheckBox.SetPos(XMFLOAT2(x, y += step));
vsyncCheckBox.SetSize(XMFLOAT2(itemheight, itemheight));
vsyncCheckBox.SetCheck(editor->main->swapChain.desc.vsync);
vsyncCheckBox.OnClick([=](wiEventArgs args) {
wiEvent::SetVSync(args.bValue);
});
AddWidget(&vsyncCheckBox);
swapchainComboBox.Create("Swapchain format: ");
swapchainComboBox.SetSize(XMFLOAT2(100, itemheight));
swapchainComboBox.SetPos(XMFLOAT2(x, y += step));
swapchainComboBox.SetTooltip("Choose between different display output formats.\nIf the display doesn't support the selected format, it will switch back to a reasonable default.\nHDR formats will be only selectable when the current display supports HDR output");
AddWidget(&swapchainComboBox);
UpdateSwapChainFormats(&editor->main->swapChain);
occlusionCullingCheckBox.Create("Occlusion Culling: ");
occlusionCullingCheckBox.SetTooltip("Toggle occlusion culling. This can boost framerate if many objects are occluded in the scene.");
occlusionCullingCheckBox.SetScriptTip("SetOcclusionCullingEnabled(bool enabled)");
occlusionCullingCheckBox.SetPos(XMFLOAT2(x, y += step));
occlusionCullingCheckBox.SetSize(XMFLOAT2(itemheight, itemheight));
occlusionCullingCheckBox.OnClick([](wiEventArgs args) {
wiRenderer::SetOcclusionCullingEnabled(args.bValue);
});
occlusionCullingCheckBox.SetCheck(wiRenderer::GetOcclusionCullingEnabled());
AddWidget(&occlusionCullingCheckBox);
resolutionScaleSlider.Create(0.25f, 2.0f, 1.0f, 7.0f, "Resolution Scale: ");
resolutionScaleSlider.SetTooltip("Adjust the internal rendering resolution.");
resolutionScaleSlider.SetSize(XMFLOAT2(100, itemheight));
resolutionScaleSlider.SetPos(XMFLOAT2(x, y += step));
resolutionScaleSlider.SetValue(editor->resolutionScale);
resolutionScaleSlider.OnSlide([editor](wiEventArgs args) {
if (editor->resolutionScale != args.fValue)
{
editor->renderPath->resolutionScale = args.fValue;
editor->resolutionScale = args.fValue;
editor->ResizeBuffers();
}
});
AddWidget(&resolutionScaleSlider);
surfelGICheckBox.Create("Surfel GI: ");
surfelGICheckBox.SetTooltip("Surfel GI is a raytraced diffuse GI using raytracing and surface cache.");
surfelGICheckBox.SetPos(XMFLOAT2(x, y += step));
surfelGICheckBox.SetSize(XMFLOAT2(itemheight, itemheight));
surfelGICheckBox.OnClick([](wiEventArgs args) {
wiRenderer::SetSurfelGIEnabled(args.bValue);
});
surfelGICheckBox.SetCheck(wiRenderer::GetSurfelGIEnabled());
AddWidget(&surfelGICheckBox);
surfelGIDebugCheckBox.Create("DEBUG: ");
surfelGIDebugCheckBox.SetTooltip("Toggle Surfel GI visualization.");
surfelGIDebugCheckBox.SetPos(XMFLOAT2(x + 122, y));
surfelGIDebugCheckBox.SetSize(XMFLOAT2(itemheight, itemheight));
surfelGIDebugCheckBox.OnClick([](wiEventArgs args) {
wiRenderer::SetSurfelGIDebugEnabled(args.bValue);
});
surfelGIDebugCheckBox.SetCheck(wiRenderer::GetSurfelGIDebugEnabled());
AddWidget(&surfelGIDebugCheckBox);
voxelRadianceCheckBox.Create("Voxel GI: ");
voxelRadianceCheckBox.SetTooltip("Toggle voxel Global Illumination computation.");
voxelRadianceCheckBox.SetPos(XMFLOAT2(x, y += step));
voxelRadianceCheckBox.SetSize(XMFLOAT2(itemheight, itemheight));
voxelRadianceCheckBox.OnClick([](wiEventArgs args) {
wiRenderer::SetVoxelRadianceEnabled(args.bValue);
});
voxelRadianceCheckBox.SetCheck(wiRenderer::GetVoxelRadianceEnabled());
AddWidget(&voxelRadianceCheckBox);
voxelRadianceDebugCheckBox.Create("DEBUG: ");
voxelRadianceDebugCheckBox.SetTooltip("Toggle Voxel GI visualization.");
voxelRadianceDebugCheckBox.SetPos(XMFLOAT2(x + 122, y));
voxelRadianceDebugCheckBox.SetSize(XMFLOAT2(itemheight, itemheight));
voxelRadianceDebugCheckBox.OnClick([](wiEventArgs args) {
wiRenderer::SetToDrawVoxelHelper(args.bValue);
});
voxelRadianceDebugCheckBox.SetCheck(wiRenderer::GetToDrawVoxelHelper());
AddWidget(&voxelRadianceDebugCheckBox);
voxelRadianceSecondaryBounceCheckBox.Create("Secondary Light Bounce: ");
voxelRadianceSecondaryBounceCheckBox.SetTooltip("Toggle secondary light bounce computation for Voxel GI.");
voxelRadianceSecondaryBounceCheckBox.SetPos(XMFLOAT2(x, y += step));
voxelRadianceSecondaryBounceCheckBox.SetSize(XMFLOAT2(itemheight, itemheight));
voxelRadianceSecondaryBounceCheckBox.OnClick([](wiEventArgs args) {
wiRenderer::SetVoxelRadianceSecondaryBounceEnabled(args.bValue);
});
voxelRadianceSecondaryBounceCheckBox.SetCheck(wiRenderer::GetVoxelRadianceSecondaryBounceEnabled());
AddWidget(&voxelRadianceSecondaryBounceCheckBox);
voxelRadianceReflectionsCheckBox.Create("Reflections: ");
voxelRadianceReflectionsCheckBox.SetTooltip("Toggle specular reflections computation for Voxel GI.");
voxelRadianceReflectionsCheckBox.SetPos(XMFLOAT2(x + 122, y));
voxelRadianceReflectionsCheckBox.SetSize(XMFLOAT2(itemheight, itemheight));
voxelRadianceReflectionsCheckBox.OnClick([](wiEventArgs args) {
wiRenderer::SetVoxelRadianceReflectionsEnabled(args.bValue);
});
voxelRadianceReflectionsCheckBox.SetCheck(wiRenderer::GetVoxelRadianceReflectionsEnabled());
AddWidget(&voxelRadianceReflectionsCheckBox);
voxelRadianceVoxelSizeSlider.Create(0.25, 2, 1, 7, "Voxel GI Voxel Size: ");
voxelRadianceVoxelSizeSlider.SetTooltip("Adjust the voxel size for Voxel GI calculations.");
voxelRadianceVoxelSizeSlider.SetSize(XMFLOAT2(100, itemheight));
voxelRadianceVoxelSizeSlider.SetPos(XMFLOAT2(x, y += step));
voxelRadianceVoxelSizeSlider.SetValue(wiRenderer::GetVoxelRadianceVoxelSize());
voxelRadianceVoxelSizeSlider.OnSlide([&](wiEventArgs args) {
wiRenderer::SetVoxelRadianceVoxelSize(args.fValue);
});
AddWidget(&voxelRadianceVoxelSizeSlider);
voxelRadianceConeTracingSlider.Create(1, 16, 8, 15, "Voxel GI NumCones: ");
voxelRadianceConeTracingSlider.SetTooltip("Adjust the number of cones sampled in the radiance gathering phase.");
voxelRadianceConeTracingSlider.SetSize(XMFLOAT2(100, itemheight));
voxelRadianceConeTracingSlider.SetPos(XMFLOAT2(x, y += step));
voxelRadianceConeTracingSlider.SetValue((float)wiRenderer::GetVoxelRadianceNumCones());
voxelRadianceConeTracingSlider.OnSlide([&](wiEventArgs args) {
wiRenderer::SetVoxelRadianceNumCones(args.iValue);
});
AddWidget(&voxelRadianceConeTracingSlider);
voxelRadianceRayStepSizeSlider.Create(0.5f, 2.0f, 0.5f, 10000, "Voxel GI Ray Step Size: ");
voxelRadianceRayStepSizeSlider.SetTooltip("Adjust the precision of ray marching for cone tracing step. Lower values = more precision but slower performance.");
voxelRadianceRayStepSizeSlider.SetSize(XMFLOAT2(100, itemheight));
voxelRadianceRayStepSizeSlider.SetPos(XMFLOAT2(x, y += step));
voxelRadianceRayStepSizeSlider.SetValue(wiRenderer::GetVoxelRadianceRayStepSize());
voxelRadianceRayStepSizeSlider.OnSlide([&](wiEventArgs args) {
wiRenderer::SetVoxelRadianceRayStepSize(args.fValue);
});
AddWidget(&voxelRadianceRayStepSizeSlider);
voxelRadianceMaxDistanceSlider.Create(0, 100, 10, 10000, "Voxel GI Max Distance: ");
voxelRadianceMaxDistanceSlider.SetTooltip("Adjust max raymarching distance for voxel GI.");
voxelRadianceMaxDistanceSlider.SetSize(XMFLOAT2(100, itemheight));
voxelRadianceMaxDistanceSlider.SetPos(XMFLOAT2(x, y += step));
voxelRadianceMaxDistanceSlider.SetValue(wiRenderer::GetVoxelRadianceMaxDistance());
voxelRadianceMaxDistanceSlider.OnSlide([&](wiEventArgs args) {
wiRenderer::SetVoxelRadianceMaxDistance(args.fValue);
});
AddWidget(&voxelRadianceMaxDistanceSlider);
wireFrameCheckBox.Create("Render Wireframe: ");
wireFrameCheckBox.SetTooltip("Visualize the scene as a wireframe");
wireFrameCheckBox.SetPos(XMFLOAT2(x, y += step));
wireFrameCheckBox.SetSize(XMFLOAT2(itemheight, itemheight));
wireFrameCheckBox.OnClick([](wiEventArgs args) {
wiRenderer::SetWireRender(args.bValue);
});
wireFrameCheckBox.SetCheck(wiRenderer::IsWireRender());
AddWidget(&wireFrameCheckBox);
variableRateShadingClassificationCheckBox.Create("VRS Classification: ");
variableRateShadingClassificationCheckBox.SetTooltip("Enable classification of variable rate shading on the screen. Less important parts will be shaded with lesser resolution.\nRequires Tier2 support for variable shading rate");
variableRateShadingClassificationCheckBox.SetPos(XMFLOAT2(x, y += step));
variableRateShadingClassificationCheckBox.SetSize(XMFLOAT2(itemheight, itemheight));
variableRateShadingClassificationCheckBox.OnClick([editor](wiEventArgs args) {
wiRenderer::SetVariableRateShadingClassification(args.bValue);
editor->ResizeBuffers();
});
variableRateShadingClassificationCheckBox.SetCheck(wiRenderer::GetVariableRateShadingClassification());
AddWidget(&variableRateShadingClassificationCheckBox);
variableRateShadingClassificationCheckBox.SetEnabled(wiGraphics::GetDevice()->CheckCapability(wiGraphics::GraphicsDeviceCapability::VARIABLE_RATE_SHADING_TIER2));
variableRateShadingClassificationDebugCheckBox.Create("DEBUG: ");
variableRateShadingClassificationDebugCheckBox.SetTooltip("Toggle visualization of variable rate shading classification feature");
variableRateShadingClassificationDebugCheckBox.SetPos(XMFLOAT2(x + 122, y));
variableRateShadingClassificationDebugCheckBox.SetSize(XMFLOAT2(itemheight, itemheight));
variableRateShadingClassificationDebugCheckBox.OnClick([](wiEventArgs args) {
wiRenderer::SetVariableRateShadingClassificationDebug(args.bValue);
});
variableRateShadingClassificationDebugCheckBox.SetCheck(wiRenderer::GetVariableRateShadingClassificationDebug());
AddWidget(&variableRateShadingClassificationDebugCheckBox);
variableRateShadingClassificationDebugCheckBox.SetEnabled(wiGraphics::GetDevice()->CheckCapability(wiGraphics::GraphicsDeviceCapability::VARIABLE_RATE_SHADING_TIER2));
advancedLightCullingCheckBox.Create("2.5D Light Culling: ");
advancedLightCullingCheckBox.SetTooltip("Enable a more aggressive light culling approach which can result in slower culling but faster rendering (Tiled renderer only)");
advancedLightCullingCheckBox.SetPos(XMFLOAT2(x, y += step));
advancedLightCullingCheckBox.SetSize(XMFLOAT2(itemheight, itemheight));
advancedLightCullingCheckBox.OnClick([](wiEventArgs args) {
wiRenderer::SetAdvancedLightCulling(args.bValue);
});
advancedLightCullingCheckBox.SetCheck(wiRenderer::GetAdvancedLightCulling());
AddWidget(&advancedLightCullingCheckBox);
debugLightCullingCheckBox.Create("DEBUG: ");
debugLightCullingCheckBox.SetTooltip("Toggle visualization of the screen space light culling heatmap grid (Tiled renderer only)");
debugLightCullingCheckBox.SetPos(XMFLOAT2(x + 122, y));
debugLightCullingCheckBox.SetSize(XMFLOAT2(itemheight, itemheight));
debugLightCullingCheckBox.OnClick([](wiEventArgs args) {
wiRenderer::SetDebugLightCulling(args.bValue);
});
debugLightCullingCheckBox.SetCheck(wiRenderer::GetDebugLightCulling());
AddWidget(&debugLightCullingCheckBox);
tessellationCheckBox.Create("Tessellation Enabled: ");
tessellationCheckBox.SetTooltip("Enable tessellation feature. You also need to specify a tessellation factor for individual objects.");
tessellationCheckBox.SetPos(XMFLOAT2(x, y += step));
tessellationCheckBox.SetSize(XMFLOAT2(itemheight, itemheight));
tessellationCheckBox.OnClick([=](wiEventArgs args) {
wiRenderer::SetTessellationEnabled(args.bValue);
});
tessellationCheckBox.SetCheck(wiRenderer::GetTessellationEnabled());
AddWidget(&tessellationCheckBox);
tessellationCheckBox.SetEnabled(wiGraphics::GetDevice()->CheckCapability(wiGraphics::GraphicsDeviceCapability::TESSELLATION));
speedMultiplierSlider.Create(0, 4, 1, 100000, "Speed: ");
speedMultiplierSlider.SetTooltip("Adjust the global speed (time multiplier)");
speedMultiplierSlider.SetSize(XMFLOAT2(100, itemheight));
speedMultiplierSlider.SetPos(XMFLOAT2(x, y += step));
speedMultiplierSlider.SetValue(wiRenderer::GetGameSpeed());
speedMultiplierSlider.OnSlide([&](wiEventArgs args) {
wiRenderer::SetGameSpeed(args.fValue);
});
AddWidget(&speedMultiplierSlider);
transparentShadowsCheckBox.Create("Transparent Shadows: ");
transparentShadowsCheckBox.SetTooltip("Enables color tinted shadows and refraction caustics effects for transparent objects and water.");
transparentShadowsCheckBox.SetPos(XMFLOAT2(x, y += step));
transparentShadowsCheckBox.SetSize(XMFLOAT2(itemheight, itemheight));
transparentShadowsCheckBox.SetCheck(wiRenderer::GetTransparentShadowsEnabled());
transparentShadowsCheckBox.OnClick([=](wiEventArgs args) {
wiRenderer::SetTransparentShadowsEnabled(args.bValue);
});
AddWidget(&transparentShadowsCheckBox);
shadowTypeComboBox.Create("Shadow type: ");
shadowTypeComboBox.SetSize(XMFLOAT2(100, itemheight));
shadowTypeComboBox.SetPos(XMFLOAT2(x, y += step));
shadowTypeComboBox.AddItem("Shadowmaps");
if (wiGraphics::GetDevice()->CheckCapability(wiGraphics::GraphicsDeviceCapability::RAYTRACING))
{
shadowTypeComboBox.AddItem("Ray traced");
}
shadowTypeComboBox.OnSelect([&](wiEventArgs args) {
switch (args.iValue)
{
default:
case 0:
wiRenderer::SetRaytracedShadowsEnabled(false);
break;
case 1:
wiRenderer::SetRaytracedShadowsEnabled(true);
break;
}
});
shadowTypeComboBox.SetSelected(0);
shadowTypeComboBox.SetTooltip("Choose between shadowmaps and ray traced shadows (if available).\n(ray traced shadows need hardware raytracing support)");
AddWidget(&shadowTypeComboBox);
shadowProps2DComboBox.Create("2D Shadowmap resolution: ");
shadowProps2DComboBox.SetSize(XMFLOAT2(100, itemheight));
shadowProps2DComboBox.SetPos(XMFLOAT2(x, y += step));
shadowProps2DComboBox.AddItem("Off");
shadowProps2DComboBox.AddItem("128");
shadowProps2DComboBox.AddItem("256");
shadowProps2DComboBox.AddItem("512");
shadowProps2DComboBox.AddItem("1024");
shadowProps2DComboBox.AddItem("2048");
shadowProps2DComboBox.AddItem("4096");
shadowProps2DComboBox.OnSelect([&](wiEventArgs args) {
switch (args.iValue)
{
case 0:
wiRenderer::SetShadowProps2D(0, -1);
break;
case 1:
wiRenderer::SetShadowProps2D(128, -1);
break;
case 2:
wiRenderer::SetShadowProps2D(256, -1);
break;
case 3:
wiRenderer::SetShadowProps2D(512, -1);
break;
case 4:
wiRenderer::SetShadowProps2D(1024, -1);
break;
case 5:
wiRenderer::SetShadowProps2D(2048, -1);
break;
case 6:
wiRenderer::SetShadowProps2D(4096, -1);
break;
default:
break;
}
});
shadowProps2DComboBox.SetSelected(4);
shadowProps2DComboBox.SetTooltip("Choose a shadow quality preset for 2D shadow maps (spotlights, directional lights)...");
shadowProps2DComboBox.SetScriptTip("SetShadowProps2D(int resolution, int count, int softShadowQuality)");
AddWidget(&shadowProps2DComboBox);
shadowPropsCubeComboBox.Create("Cube Shadowmap resolution: ");
shadowPropsCubeComboBox.SetSize(XMFLOAT2(100, itemheight));
shadowPropsCubeComboBox.SetPos(XMFLOAT2(x, y += step));
shadowPropsCubeComboBox.AddItem("Off");
shadowPropsCubeComboBox.AddItem("128");
shadowPropsCubeComboBox.AddItem("256");
shadowPropsCubeComboBox.AddItem("512");
shadowPropsCubeComboBox.AddItem("1024");
shadowPropsCubeComboBox.AddItem("2048");
shadowPropsCubeComboBox.AddItem("4096");
shadowPropsCubeComboBox.OnSelect([&](wiEventArgs args) {
switch (args.iValue)
{
case 0:
wiRenderer::SetShadowPropsCube(0, -1);
break;
case 1:
wiRenderer::SetShadowPropsCube(128, -1);
break;
case 2:
wiRenderer::SetShadowPropsCube(256, -1);
break;
case 3:
wiRenderer::SetShadowPropsCube(512, -1);
break;
case 4:
wiRenderer::SetShadowPropsCube(1024, -1);
break;
case 5:
wiRenderer::SetShadowPropsCube(2048, -1);
break;
case 6:
wiRenderer::SetShadowPropsCube(4096, -1);
break;
default:
break;
}
});
shadowPropsCubeComboBox.SetSelected(2);
shadowPropsCubeComboBox.SetTooltip("Choose a shadow quality preset for cube shadow maps (pointlights, area lights)...");
shadowPropsCubeComboBox.SetScriptTip("SetShadowPropsCube(int resolution, int count)");
AddWidget(&shadowPropsCubeComboBox);
MSAAComboBox.Create("MSAA: ");
MSAAComboBox.SetSize(XMFLOAT2(100, itemheight));
MSAAComboBox.SetPos(XMFLOAT2(x, y += step));
MSAAComboBox.AddItem("Off");
MSAAComboBox.AddItem("2");
MSAAComboBox.AddItem("4");
MSAAComboBox.AddItem("8");
MSAAComboBox.OnSelect([=](wiEventArgs args) {
switch (args.iValue)
{
case 0:
editor->renderPath->setMSAASampleCount(1);
break;
case 1:
editor->renderPath->setMSAASampleCount(2);
break;
case 2:
editor->renderPath->setMSAASampleCount(4);
break;
case 3:
editor->renderPath->setMSAASampleCount(8);
break;
default:
break;
}
editor->ResizeBuffers();
});
MSAAComboBox.SetSelected(0);
MSAAComboBox.SetTooltip("Multisampling Anti Aliasing quality. ");
AddWidget(&MSAAComboBox);
temporalAACheckBox.Create("Temporal AA: ");
temporalAACheckBox.SetTooltip("Toggle Temporal Anti Aliasing. It is a supersampling techique which is performed across multiple frames.");
temporalAACheckBox.SetPos(XMFLOAT2(x, y += step));
temporalAACheckBox.SetSize(XMFLOAT2(itemheight, itemheight));
temporalAACheckBox.OnClick([](wiEventArgs args) {
wiRenderer::SetTemporalAAEnabled(args.bValue);
});
temporalAACheckBox.SetCheck(wiRenderer::GetTemporalAAEnabled());
AddWidget(&temporalAACheckBox);
temporalAADebugCheckBox.Create("DEBUGJitter: ");
temporalAADebugCheckBox.SetText("DEBUG: ");
temporalAADebugCheckBox.SetTooltip("Disable blending of frame history. Camera Subpixel jitter will be visible.");
temporalAADebugCheckBox.SetPos(XMFLOAT2(x + 122, y));
temporalAADebugCheckBox.SetSize(XMFLOAT2(itemheight, itemheight));
temporalAADebugCheckBox.OnClick([](wiEventArgs args) {
wiRenderer::SetTemporalAADebugEnabled(args.bValue);
});
temporalAADebugCheckBox.SetCheck(wiRenderer::GetTemporalAADebugEnabled());
AddWidget(&temporalAADebugCheckBox);
textureQualityComboBox.Create("Texture Quality: ");
textureQualityComboBox.SetSize(XMFLOAT2(100, itemheight));
textureQualityComboBox.SetPos(XMFLOAT2(x, y += step));
textureQualityComboBox.AddItem("Nearest");
textureQualityComboBox.AddItem("Bilinear");
textureQualityComboBox.AddItem("Trilinear");
textureQualityComboBox.AddItem("Anisotropic");
textureQualityComboBox.OnSelect([&](wiEventArgs args) {
wiGraphics::SamplerDesc desc = wiRenderer::GetSampler(SSLOT_OBJECTSHADER)->GetDesc();
switch (args.iValue)
{
case 0:
desc.filter = wiGraphics::Filter::MIN_MAG_MIP_POINT;
break;
case 1:
desc.filter = wiGraphics::Filter::MIN_MAG_LINEAR_MIP_POINT;
break;
case 2:
desc.filter = wiGraphics::Filter::MIN_MAG_MIP_LINEAR;
break;
case 3:
desc.filter = wiGraphics::Filter::ANISOTROPIC;
break;
default:
break;
}
wiRenderer::ModifyObjectSampler(desc);
});
textureQualityComboBox.SetSelected(3);
textureQualityComboBox.SetTooltip("Choose a texture sampling method for material textures.");
AddWidget(&textureQualityComboBox);
mipLodBiasSlider.Create(-2, 2, 0, 100000, "MipLOD Bias: ");
mipLodBiasSlider.SetTooltip("Bias the rendered mip map level of the material textures.");
mipLodBiasSlider.SetSize(XMFLOAT2(100, itemheight));
mipLodBiasSlider.SetPos(XMFLOAT2(x, y += step));
mipLodBiasSlider.OnSlide([&](wiEventArgs args) {
wiGraphics::SamplerDesc desc = wiRenderer::GetSampler(SSLOT_OBJECTSHADER)->GetDesc();
desc.mip_lod_bias = wiMath::Clamp(args.fValue, -15.9f, 15.9f);
wiRenderer::ModifyObjectSampler(desc);
});
AddWidget(&mipLodBiasSlider);
raytraceBounceCountSlider.Create(1, 10, 1, 9, "Raytrace Bounces: ");
raytraceBounceCountSlider.SetTooltip("How many light bounces to compute when doing ray tracing.");
raytraceBounceCountSlider.SetSize(XMFLOAT2(100, itemheight));
raytraceBounceCountSlider.SetPos(XMFLOAT2(x, y += step));
raytraceBounceCountSlider.SetValue((float)wiRenderer::GetRaytraceBounceCount());
raytraceBounceCountSlider.OnSlide([&](wiEventArgs args) {
wiRenderer::SetRaytraceBounceCount((uint32_t)args.iValue);
});
AddWidget(&raytraceBounceCountSlider);
// Visualizer toggles:
x = 540, y = 5;
physicsDebugCheckBox.Create("Physics visualizer: ");
physicsDebugCheckBox.SetTooltip("Visualize the physics world");
physicsDebugCheckBox.SetPos(XMFLOAT2(x, y += step));
physicsDebugCheckBox.SetSize(XMFLOAT2(itemheight, itemheight));
physicsDebugCheckBox.OnClick([](wiEventArgs args) {
wiPhysicsEngine::SetDebugDrawEnabled(args.bValue);
});
physicsDebugCheckBox.SetCheck(wiPhysicsEngine::IsDebugDrawEnabled());
AddWidget(&physicsDebugCheckBox);
partitionBoxesCheckBox.Create("SPTree visualizer: ");
partitionBoxesCheckBox.SetTooltip("Visualize the scene bounding boxes");
partitionBoxesCheckBox.SetScriptTip("SetDebugPartitionTreeEnabled(bool enabled)");
partitionBoxesCheckBox.SetPos(XMFLOAT2(x, y += step));
partitionBoxesCheckBox.SetSize(XMFLOAT2(itemheight, itemheight));
partitionBoxesCheckBox.OnClick([](wiEventArgs args) {
wiRenderer::SetToDrawDebugPartitionTree(args.bValue);
});
partitionBoxesCheckBox.SetCheck(wiRenderer::GetToDrawDebugPartitionTree());
AddWidget(&partitionBoxesCheckBox);
boneLinesCheckBox.Create("Bone line visualizer: ");
boneLinesCheckBox.SetTooltip("Visualize bones of armatures");
boneLinesCheckBox.SetScriptTip("SetDebugBonesEnabled(bool enabled)");
boneLinesCheckBox.SetPos(XMFLOAT2(x, y += step));
boneLinesCheckBox.SetSize(XMFLOAT2(itemheight, itemheight));
boneLinesCheckBox.OnClick([](wiEventArgs args) {
wiRenderer::SetToDrawDebugBoneLines(args.bValue);
});
boneLinesCheckBox.SetCheck(wiRenderer::GetToDrawDebugBoneLines());
AddWidget(&boneLinesCheckBox);
debugEmittersCheckBox.Create("Emitter visualizer: ");
debugEmittersCheckBox.SetTooltip("Visualize emitters");
debugEmittersCheckBox.SetScriptTip("SetDebugEmittersEnabled(bool enabled)");
debugEmittersCheckBox.SetPos(XMFLOAT2(x, y += step));
debugEmittersCheckBox.SetSize(XMFLOAT2(itemheight, itemheight));
debugEmittersCheckBox.OnClick([](wiEventArgs args) {
wiRenderer::SetToDrawDebugEmitters(args.bValue);
});
debugEmittersCheckBox.SetCheck(wiRenderer::GetToDrawDebugEmitters());
AddWidget(&debugEmittersCheckBox);
debugForceFieldsCheckBox.Create("Force Field visualizer: ");
debugForceFieldsCheckBox.SetTooltip("Visualize force fields");
debugForceFieldsCheckBox.SetScriptTip("SetDebugForceFieldsEnabled(bool enabled)");
debugForceFieldsCheckBox.SetPos(XMFLOAT2(x, y += step));
debugForceFieldsCheckBox.SetSize(XMFLOAT2(itemheight, itemheight));
debugForceFieldsCheckBox.OnClick([](wiEventArgs args) {
wiRenderer::SetToDrawDebugForceFields(args.bValue);
});
debugForceFieldsCheckBox.SetCheck(wiRenderer::GetToDrawDebugForceFields());
AddWidget(&debugForceFieldsCheckBox);
debugRaytraceBVHCheckBox.Create("Raytrace BVH visualizer: ");
debugRaytraceBVHCheckBox.SetTooltip("Visualize scene BVH if raytracing is enabled");
debugRaytraceBVHCheckBox.SetPos(XMFLOAT2(x, y += step));
debugRaytraceBVHCheckBox.SetSize(XMFLOAT2(itemheight, itemheight));
debugRaytraceBVHCheckBox.OnClick([](wiEventArgs args) {
wiRenderer::SetRaytraceDebugBVHVisualizerEnabled(args.bValue);
});
debugRaytraceBVHCheckBox.SetCheck(wiRenderer::GetRaytraceDebugBVHVisualizerEnabled());
AddWidget(&debugRaytraceBVHCheckBox);
envProbesCheckBox.Create("Env probe visualizer: ");
envProbesCheckBox.SetTooltip("Toggle visualization of environment probes as reflective spheres");
envProbesCheckBox.SetPos(XMFLOAT2(x, y += step));
envProbesCheckBox.SetSize(XMFLOAT2(itemheight, itemheight));
envProbesCheckBox.OnClick([](wiEventArgs args) {
wiRenderer::SetToDrawDebugEnvProbes(args.bValue);
});
envProbesCheckBox.SetCheck(wiRenderer::GetToDrawDebugEnvProbes());
AddWidget(&envProbesCheckBox);
cameraVisCheckBox.Create("Camera Proxy visualizer: ");
cameraVisCheckBox.SetTooltip("Toggle visualization of camera proxies in the scene");
cameraVisCheckBox.SetPos(XMFLOAT2(x, y += step));
cameraVisCheckBox.SetSize(XMFLOAT2(itemheight, itemheight));
cameraVisCheckBox.OnClick([](wiEventArgs args) {
wiRenderer::SetToDrawDebugCameras(args.bValue);
});
cameraVisCheckBox.SetCheck(wiRenderer::GetToDrawDebugCameras());
AddWidget(&cameraVisCheckBox);
gridHelperCheckBox.Create("Grid helper: ");
gridHelperCheckBox.SetTooltip("Toggle showing of unit visualizer grid in the world origin");
gridHelperCheckBox.SetPos(XMFLOAT2(x, y += step));
gridHelperCheckBox.SetSize(XMFLOAT2(itemheight, itemheight));
gridHelperCheckBox.OnClick([](wiEventArgs args) {
wiRenderer::SetToDrawGridHelper(args.bValue);
});
gridHelperCheckBox.SetCheck(wiRenderer::GetToDrawGridHelper());
AddWidget(&gridHelperCheckBox);
pickTypeObjectCheckBox.Create("Pick Objects: ");
pickTypeObjectCheckBox.SetTooltip("Enable if you want to pick objects with the pointer");
pickTypeObjectCheckBox.SetPos(XMFLOAT2(x, y += step * 2));
pickTypeObjectCheckBox.SetSize(XMFLOAT2(itemheight, itemheight));
pickTypeObjectCheckBox.SetCheck(true);
AddWidget(&pickTypeObjectCheckBox);
pickTypeEnvProbeCheckBox.Create("Pick EnvProbes: ");
pickTypeEnvProbeCheckBox.SetTooltip("Enable if you want to pick environment probes with the pointer");
pickTypeEnvProbeCheckBox.SetPos(XMFLOAT2(x, y += step));
pickTypeEnvProbeCheckBox.SetSize(XMFLOAT2(itemheight, itemheight));
pickTypeEnvProbeCheckBox.SetCheck(true);
AddWidget(&pickTypeEnvProbeCheckBox);
pickTypeLightCheckBox.Create("Pick Lights: ");
pickTypeLightCheckBox.SetTooltip("Enable if you want to pick lights with the pointer");
pickTypeLightCheckBox.SetPos(XMFLOAT2(x, y += step));
pickTypeLightCheckBox.SetSize(XMFLOAT2(itemheight, itemheight));
pickTypeLightCheckBox.SetCheck(true);
AddWidget(&pickTypeLightCheckBox);
pickTypeDecalCheckBox.Create("Pick Decals: ");
pickTypeDecalCheckBox.SetTooltip("Enable if you want to pick decals with the pointer");
pickTypeDecalCheckBox.SetPos(XMFLOAT2(x, y += step));
pickTypeDecalCheckBox.SetSize(XMFLOAT2(itemheight, itemheight));
pickTypeDecalCheckBox.SetCheck(true);
AddWidget(&pickTypeDecalCheckBox);
pickTypeForceFieldCheckBox.Create("Pick Force Fields: ");
pickTypeForceFieldCheckBox.SetTooltip("Enable if you want to pick force fields with the pointer");
pickTypeForceFieldCheckBox.SetPos(XMFLOAT2(x, y += step));
pickTypeForceFieldCheckBox.SetSize(XMFLOAT2(itemheight, itemheight));
pickTypeForceFieldCheckBox.SetCheck(true);
AddWidget(&pickTypeForceFieldCheckBox);
pickTypeEmitterCheckBox.Create("Pick Emitters: ");
pickTypeEmitterCheckBox.SetTooltip("Enable if you want to pick emitters with the pointer");
pickTypeEmitterCheckBox.SetPos(XMFLOAT2(x, y += step));
pickTypeEmitterCheckBox.SetSize(XMFLOAT2(itemheight, itemheight));
pickTypeEmitterCheckBox.SetCheck(true);
AddWidget(&pickTypeEmitterCheckBox);
pickTypeHairCheckBox.Create("Pick Hairs: ");
pickTypeHairCheckBox.SetTooltip("Enable if you want to pick hairs with the pointer");
pickTypeHairCheckBox.SetPos(XMFLOAT2(x, y += step));
pickTypeHairCheckBox.SetSize(XMFLOAT2(itemheight, itemheight));
pickTypeHairCheckBox.SetCheck(true);
AddWidget(&pickTypeHairCheckBox);
pickTypeCameraCheckBox.Create("Pick Cameras: ");
pickTypeCameraCheckBox.SetTooltip("Enable if you want to pick cameras with the pointer");
pickTypeCameraCheckBox.SetPos(XMFLOAT2(x, y += step));
pickTypeCameraCheckBox.SetSize(XMFLOAT2(itemheight, itemheight));
pickTypeCameraCheckBox.SetCheck(true);
AddWidget(&pickTypeCameraCheckBox);
pickTypeArmatureCheckBox.Create("Pick Armatures: ");
pickTypeArmatureCheckBox.SetTooltip("Enable if you want to pick armatures with the pointer");
pickTypeArmatureCheckBox.SetPos(XMFLOAT2(x, y += step));
pickTypeArmatureCheckBox.SetSize(XMFLOAT2(itemheight, itemheight));
pickTypeArmatureCheckBox.SetCheck(true);
AddWidget(&pickTypeArmatureCheckBox);
pickTypeSoundCheckBox.Create("Pick Sounds: ");
pickTypeSoundCheckBox.SetTooltip("Enable if you want to pick sounds with the pointer");
pickTypeSoundCheckBox.SetPos(XMFLOAT2(x, y += step));
pickTypeSoundCheckBox.SetSize(XMFLOAT2(itemheight, itemheight));
pickTypeSoundCheckBox.SetCheck(true);
AddWidget(&pickTypeSoundCheckBox);
freezeCullingCameraCheckBox.Create("Freeze culling camera: ");
freezeCullingCameraCheckBox.SetTooltip("Freeze culling camera update. Scene culling will not be updated with the view");
freezeCullingCameraCheckBox.SetPos(XMFLOAT2(x, y += step * 2));
freezeCullingCameraCheckBox.SetSize(XMFLOAT2(itemheight, itemheight));
freezeCullingCameraCheckBox.OnClick([](wiEventArgs args) {
wiRenderer::SetFreezeCullingCameraEnabled(args.bValue);
});
freezeCullingCameraCheckBox.SetCheck(wiRenderer::GetFreezeCullingCameraEnabled());
AddWidget(&freezeCullingCameraCheckBox);
disableAlbedoMapsCheckBox.Create("Disable albedo maps: ");
disableAlbedoMapsCheckBox.SetTooltip("Disables albedo maps on objects for easier lighting debugging");
disableAlbedoMapsCheckBox.SetPos(XMFLOAT2(x, y += step));
disableAlbedoMapsCheckBox.SetSize(XMFLOAT2(itemheight, itemheight));
disableAlbedoMapsCheckBox.OnClick([](wiEventArgs args) {
wiRenderer::SetDisableAlbedoMaps(args.bValue);
});
disableAlbedoMapsCheckBox.SetCheck(wiRenderer::IsDisableAlbedoMaps());
AddWidget(&disableAlbedoMapsCheckBox);
forceDiffuseLightingCheckBox.Create("Force diffuse lighting: ");
forceDiffuseLightingCheckBox.SetTooltip("Sets every surface fully diffuse, with zero specularity");
forceDiffuseLightingCheckBox.SetPos(XMFLOAT2(x, y += step));
forceDiffuseLightingCheckBox.SetSize(XMFLOAT2(itemheight, itemheight));
forceDiffuseLightingCheckBox.OnClick([](wiEventArgs args) {
wiRenderer::SetForceDiffuseLighting(args.bValue);
});
forceDiffuseLightingCheckBox.SetCheck(wiRenderer::IsForceDiffuseLighting());
AddWidget(&forceDiffuseLightingCheckBox);
Translate(XMFLOAT3(100, 50, 0));
SetVisible(false);
}
uint32_t RendererWindow::GetPickType() const
{
uint32_t pickType = PICK_VOID;
if (pickTypeObjectCheckBox.GetCheck())
{
pickType |= PICK_OBJECT;
}
if (pickTypeEnvProbeCheckBox.GetCheck())
{
pickType |= PICK_ENVPROBE;
}
if (pickTypeLightCheckBox.GetCheck())
{
pickType |= PICK_LIGHT;
}
if (pickTypeDecalCheckBox.GetCheck())
{
pickType |= PICK_DECAL;
}
if (pickTypeForceFieldCheckBox.GetCheck())
{
pickType |= PICK_FORCEFIELD;
}
if (pickTypeEmitterCheckBox.GetCheck())
{
pickType |= PICK_EMITTER;
}
if (pickTypeHairCheckBox.GetCheck())
{
pickType |= PICK_HAIR;
}
if (pickTypeCameraCheckBox.GetCheck())
{
pickType |= PICK_CAMERA;
}
if (pickTypeArmatureCheckBox.GetCheck())
{
pickType |= PICK_ARMATURE;
}
if (pickTypeSoundCheckBox.GetCheck())
{
pickType |= PICK_SOUND;
}
return pickType;
}
void RendererWindow::UpdateSwapChainFormats(wiGraphics::SwapChain* swapChain)
{
swapchainComboBox.OnSelect(nullptr);
swapchainComboBox.ClearItems();
swapchainComboBox.AddItem("SDR 8bit", static_cast<uint64_t>(wiGraphics::Format::R8G8B8A8_UNORM));
swapchainComboBox.AddItem("SDR 10bit", static_cast<uint64_t>(wiGraphics::Format::R10G10B10A2_UNORM));
if (wiGraphics::GetDevice()->IsSwapChainSupportsHDR(swapChain))
{
swapchainComboBox.AddItem("HDR 10bit", static_cast<uint64_t>(wiGraphics::Format::R10G10B10A2_UNORM));
swapchainComboBox.AddItem("HDR 16bit", static_cast<uint64_t>(wiGraphics::Format::R16G16B16A16_FLOAT));
switch (swapChain->desc.format)
{
default:
case wiGraphics::Format::R8G8B8A8_UNORM:
swapchainComboBox.SetSelected(0);
break;
case wiGraphics::Format::R10G10B10A2_UNORM:
if (swapChain->desc.allow_hdr)
{
swapchainComboBox.SetSelected(2);
}
else
{
swapchainComboBox.SetSelected(1);
}
break;
case wiGraphics::Format::R16G16B16A16_FLOAT:
swapchainComboBox.SetSelected(4);
break;
}
}
else
{
switch (swapChain->desc.format)
{
default:
case wiGraphics::Format::R8G8B8A8_UNORM:
swapchainComboBox.SetSelected(0);
break;
case wiGraphics::Format::R10G10B10A2_UNORM:
swapchainComboBox.SetSelected(1);
break;
case wiGraphics::Format::R16G16B16A16_FLOAT:
swapchainComboBox.SetSelected(1);
break;
}
}
swapchainComboBox.OnSelect([=](wiEventArgs args) {
swapChain->desc.format = (wiGraphics::Format)args.userdata;
switch (args.iValue)
{
default:
case 0:
case 1:
swapChain->desc.allow_hdr = false;
break;
case 2:
case 3:
swapChain->desc.allow_hdr = true;
break;
}
bool success = wiGraphics::GetDevice()->CreateSwapChain(&swapChain->desc, nullptr, swapChain);
assert(success);
});
}
|
#include "Singleton.h"
int main()
{
Singleton* sgn = Singleton::Instance();
return 0;
}
|
// 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 "core/operation/unary_activations.h"
#include "driver/cambricon_mlu/converter.h"
#include "utility/debug.h"
#include "utility/logging.h"
namespace nnadapter {
namespace cambricon_mlu {
const std::map<NNAdapterOperationType, magicmind::IActivation>*
ActivationOperationMap() {
static auto* const m =
new std::map<NNAdapterOperationType, magicmind::IActivation>{
{NNADAPTER_RELU, magicmind::IActivation::RELU},
{NNADAPTER_RELU6, magicmind::IActivation::RELU6},
{NNADAPTER_SIGMOID, magicmind::IActivation::SIGMOID},
{NNADAPTER_TANH, magicmind::IActivation::TANH},
};
return m;
}
int ConvertActivations(Converter* converter, hal::Operation* operation) {
UNARY_ACTIVATIONS_OPERATION_EXTRACT_INPUTS_OUTPUTS
// Convert to magicmind tensors and node
auto input_tensor = converter->GetMappedTensor(input_operand);
if (!input_tensor) {
input_tensor = converter->ConvertOperand(input_operand);
}
auto op_pair = ActivationOperationMap()->find(operation->type);
if (op_pair == ActivationOperationMap()->end()) {
NNADAPTER_VLOG(5) << "Unsupported activation op.";
return NNADAPTER_DEVICE_INTERNAL_ERROR;
}
auto activation_node =
converter->network()->AddIActivationNode(input_tensor, op_pair->second);
if (activation_node == nullptr) {
NNADAPTER_VLOG(5) << "Failed to add activation node.";
return NNADAPTER_DEVICE_INTERNAL_ERROR;
}
auto output_tensor = activation_node->GetOutput(0);
converter->UpdateTensorMap(output_operand, output_tensor);
return NNADAPTER_NO_ERROR;
}
} // namespace cambricon_mlu
} // namespace nnadapter
|
//
// Copyright 2021 Google LLC
//
// 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 "algorithms/quantiles.h"
#include <algorithm>
#include "base/testing/proto_matchers.h"
#include "base/testing/status_matchers.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/random/random.h"
#include "algorithms/numerical-mechanisms-testing.h"
namespace differential_privacy {
namespace {
using ::differential_privacy::test_utils::ZeroNoiseMechanism;
using ::testing::HasSubstr;
using ::differential_privacy::base::testing::StatusIs;
const int kDefaultDatasetSize = 1001;
const int kNumRanksToTest = 10;
template <typename T>
class QuantilesTest : public ::testing::Test {
protected:
void SetUp() override {}
void TearDown() override {}
};
typedef ::testing::Types<int64_t, double> NumericTypes;
TYPED_TEST_SUITE(QuantilesTest, NumericTypes);
TEST(QuantilesTest, InvalidParametersTest) {
EXPECT_THAT(Quantiles<double>::Builder()
.SetLower(0)
.SetUpper(1)
.SetQuantiles({})
.Build(),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("must specify at least one quantile")));
EXPECT_THAT(Quantiles<double>::Builder()
.SetLower(0)
.SetUpper(1)
.SetQuantiles({-1})
.Build(),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("quantiles to calculate must be in [0, 1]")));
EXPECT_THAT(Quantiles<double>::Builder()
.SetLower(0)
.SetUpper(1)
.SetQuantiles({1.5})
.Build(),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("quantiles to calculate must be in [0, 1]")));
EXPECT_THAT(
Quantiles<double>::Builder()
.SetLower(2)
.SetUpper(1)
.SetQuantiles({0.5})
.Build(),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("Lower bound cannot be greater than upper bound")));
EXPECT_THAT(Quantiles<double>::Builder().SetQuantiles({0.5}).Build(),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("Lower and upper bounds must both be set")));
}
// Input must be sorted.
template <typename T>
double TrueQuantileFromSorted(std::vector<T> inputs, double quantile) {
int rank = std::round(quantile * (inputs.size() - 1));
return inputs[rank];
}
TYPED_TEST(QuantilesTest, ApproximatesTrueQuantile) {
std::vector<double> quantiles;
for (int i = 0; i < kNumRanksToTest; ++i) {
quantiles.push_back(static_cast<double>(i) / kNumRanksToTest);
}
std::unique_ptr<Quantiles<TypeParam>> test_quantiles =
typename Quantiles<TypeParam>::Builder()
.SetUpper(50)
.SetLower(-50)
.SetQuantiles(quantiles)
.SetLaplaceMechanism(absl::make_unique<ZeroNoiseMechanism::Builder>())
.Build()
.value();
std::vector<TypeParam> inputs;
for (int i = 0; i < kDefaultDatasetSize; ++i) {
inputs.push_back(absl::Uniform(absl::BitGen(), -25, 25));
}
for (TypeParam input : inputs) {
test_quantiles->AddEntry(input);
}
double tolerance = 0.01; // > upper - lower / branchingFactor ^ treeHeight
std::sort(inputs.begin(), inputs.end());
Output results = test_quantiles->PartialResult().value();
for (int i = 0; i < quantiles.size(); ++i) {
double quantile = quantiles[i];
EXPECT_NEAR(results.elements(i).value().float_value(),
TrueQuantileFromSorted(inputs, quantile), tolerance);
}
}
TYPED_TEST(QuantilesTest, InputOrderInvariant) {
std::vector<double> quantiles;
for (int i = 0; i < kNumRanksToTest; ++i) {
quantiles.push_back(static_cast<double>(i) / kNumRanksToTest);
}
std::unique_ptr<Quantiles<TypeParam>> test_quantiles1 =
typename Quantiles<TypeParam>::Builder()
.SetUpper(50)
.SetLower(-50)
.SetQuantiles(quantiles)
.SetLaplaceMechanism(absl::make_unique<ZeroNoiseMechanism::Builder>())
.Build()
.value();
std::unique_ptr<Quantiles<TypeParam>> test_quantiles2 =
typename Quantiles<TypeParam>::Builder()
.SetUpper(50)
.SetLower(-50)
.SetQuantiles(quantiles)
.SetLaplaceMechanism(absl::make_unique<ZeroNoiseMechanism::Builder>())
.Build()
.value();
absl::BitGen gen;
std::vector<TypeParam> inputs;
for (int i = 0; i < kDefaultDatasetSize; ++i) {
inputs.push_back(absl::Uniform(gen, -25, 25));
}
for (TypeParam input : inputs) {
test_quantiles1->AddEntry(input);
}
std::shuffle(inputs.begin(), inputs.end(), gen);
for (TypeParam input : inputs) {
test_quantiles2->AddEntry(input);
}
Output results1 = test_quantiles1->PartialResult().value();
Output results2 = test_quantiles2->PartialResult().value();
EXPECT_THAT(results1, ::differential_privacy::base::testing::EqualsProto(results2));
}
// This should hold even with noise enabled.
TYPED_TEST(QuantilesTest, ResultsIncreaseMonotonically) {
std::vector<double> quantiles;
for (int i = 0; i < kNumRanksToTest; ++i) {
quantiles.push_back(static_cast<double>(i) / kNumRanksToTest);
}
std::unique_ptr<Quantiles<TypeParam>> test_quantiles =
typename Quantiles<TypeParam>::Builder()
.SetUpper(50)
.SetLower(-50)
.SetQuantiles(quantiles)
.SetLaplaceMechanism(absl::make_unique<ZeroNoiseMechanism::Builder>())
.Build()
.value();
absl::BitGen gen;
std::vector<TypeParam> inputs;
for (int i = 0; i < kDefaultDatasetSize; ++i) {
inputs.push_back(absl::Uniform(gen, -25, 25));
}
for (TypeParam input : inputs) {
test_quantiles->AddEntry(input);
}
Output result = test_quantiles->PartialResult().value();
double last_result = std::numeric_limits<double>::lowest();
for (int i = 0; i < result.elements_size(); ++i) {
EXPECT_GE(result.elements(i).value().float_value(), last_result);
last_result = result.elements(i).value().float_value();
}
}
TYPED_TEST(QuantilesTest, SerializeMergeTest) {
std::vector<double> quantiles;
for (int i = 0; i < kNumRanksToTest; ++i) {
quantiles.push_back(static_cast<double>(i) / kNumRanksToTest);
}
std::unique_ptr<Quantiles<TypeParam>> test_quantiles1 =
typename Quantiles<TypeParam>::Builder()
.SetUpper(50)
.SetLower(-50)
.SetQuantiles(quantiles)
.SetLaplaceMechanism(absl::make_unique<ZeroNoiseMechanism::Builder>())
.Build()
.value();
std::unique_ptr<Quantiles<TypeParam>> test_quantiles2 =
typename Quantiles<TypeParam>::Builder()
.SetUpper(50)
.SetLower(-50)
.SetQuantiles(quantiles)
.SetLaplaceMechanism(absl::make_unique<ZeroNoiseMechanism::Builder>())
.Build()
.value();
absl::BitGen gen;
std::vector<TypeParam> first_inputs;
std::vector<TypeParam> second_inputs;
for (int i = 0; i < kDefaultDatasetSize; ++i) {
TypeParam input = absl::Uniform(gen, -25, 25);
if (i < kDefaultDatasetSize / 2) {
first_inputs.push_back(input);
} else {
second_inputs.push_back(input);
}
}
for (TypeParam input : first_inputs) {
test_quantiles1->AddEntry(input);
}
EXPECT_OK(test_quantiles2->Merge(test_quantiles1->Serialize()));
for (TypeParam input : second_inputs) {
test_quantiles1->AddEntry(input);
test_quantiles2->AddEntry(input);
}
Output results1 = test_quantiles1->PartialResult().value();
Output results2 = test_quantiles2->PartialResult().value();
EXPECT_THAT(results1, ::differential_privacy::base::testing::EqualsProto(results2));
}
TEST(QuantilesTest, MergeFailsWithBadBounds) {
std::unique_ptr<Quantiles<double>> test_quantiles =
typename Quantiles<double>::Builder()
.SetUpper(50)
.SetLower(-50)
.SetQuantiles({0.5})
.Build()
.value();
std::unique_ptr<Quantiles<double>> wrong_lower =
typename Quantiles<double>::Builder()
.SetUpper(50)
.SetLower(-49)
.SetQuantiles({0.5})
.Build()
.value();
std::unique_ptr<Quantiles<double>> wrong_upper =
typename Quantiles<double>::Builder()
.SetUpper(49)
.SetLower(-50)
.SetQuantiles({0.5})
.Build()
.value();
EXPECT_THAT(wrong_lower->Merge(test_quantiles->Serialize()),
StatusIs(absl::StatusCode::kInternal, HasSubstr("Bounds")));
EXPECT_THAT(wrong_upper->Merge(test_quantiles->Serialize()),
StatusIs(absl::StatusCode::kInternal, HasSubstr("Bounds")));
}
TEST(QuantilesTest, IgnoresNaN) {
std::unique_ptr<Quantiles<double>> test_quantiles1 =
typename Quantiles<double>::Builder()
.SetUpper(50)
.SetLower(-50)
.SetQuantiles({0.5})
.SetLaplaceMechanism(absl::make_unique<ZeroNoiseMechanism::Builder>())
.Build()
.value();
std::unique_ptr<Quantiles<double>> test_quantiles2 =
typename Quantiles<double>::Builder()
.SetUpper(50)
.SetLower(-50)
.SetQuantiles({0.5})
.SetLaplaceMechanism(absl::make_unique<ZeroNoiseMechanism::Builder>())
.Build()
.value();
test_quantiles1->AddEntry(5.0);
test_quantiles2->AddEntry(5.0);
for (int i = 0; i < 100; ++i) {
test_quantiles2->AddEntry(std::nan(""));
}
Output results1 = test_quantiles1->PartialResult().value();
Output results2 = test_quantiles2->PartialResult().value();
EXPECT_THAT(results1, ::differential_privacy::base::testing::EqualsProto(results2));
}
TYPED_TEST(QuantilesTest, MemoryUsed) {
std::unique_ptr<Quantiles<TypeParam>> empty =
typename Quantiles<TypeParam>::Builder()
.SetUpper(50)
.SetLower(-50)
.SetQuantiles({0.5})
.Build()
.value();
std::unique_ptr<Quantiles<TypeParam>> once =
typename Quantiles<TypeParam>::Builder()
.SetUpper(50)
.SetLower(-50)
.SetQuantiles({0.5})
.Build()
.value();
std::unique_ptr<Quantiles<TypeParam>> twice =
typename Quantiles<TypeParam>::Builder()
.SetUpper(50)
.SetLower(-50)
.SetQuantiles({0.5})
.Build()
.value();
once->AddEntry(-49);
twice->AddEntry(49);
twice->AddEntry(49);
EXPECT_GT(once->MemoryUsed(), empty->MemoryUsed());
EXPECT_EQ(once->MemoryUsed(), twice->MemoryUsed());
}
TYPED_TEST(QuantilesTest, Reset) {
std::vector<double> quantiles;
for (int i = 0; i < kNumRanksToTest; ++i) {
quantiles.push_back(static_cast<double>(i) / kNumRanksToTest);
}
std::unique_ptr<Quantiles<TypeParam>> test_quantiles1 =
typename Quantiles<TypeParam>::Builder()
.SetUpper(50)
.SetLower(-50)
.SetQuantiles(quantiles)
.SetLaplaceMechanism(absl::make_unique<ZeroNoiseMechanism::Builder>())
.Build()
.value();
std::unique_ptr<Quantiles<TypeParam>> test_quantiles2 =
typename Quantiles<TypeParam>::Builder()
.SetUpper(50)
.SetLower(-50)
.SetQuantiles(quantiles)
.SetLaplaceMechanism(absl::make_unique<ZeroNoiseMechanism::Builder>())
.Build()
.value();
std::vector<TypeParam> first_inputs;
std::vector<TypeParam> second_inputs;
for (int i = 0; i < kDefaultDatasetSize; ++i) {
TypeParam input = absl::Uniform(absl::BitGen(), -25, 25);
if (i < kDefaultDatasetSize / 2) {
first_inputs.push_back(input);
} else {
second_inputs.push_back(input);
}
}
for (TypeParam input : first_inputs) {
test_quantiles1->AddEntry(input);
}
test_quantiles1->Reset();
for (TypeParam input : second_inputs) {
test_quantiles1->AddEntry(input);
test_quantiles2->AddEntry(input);
}
Output results1 = test_quantiles1->PartialResult().value();
Output results2 = test_quantiles2->PartialResult().value();
EXPECT_THAT(results1, ::differential_privacy::base::testing::EqualsProto(results2));
}
TYPED_TEST(QuantilesTest, GetQuantiles) {
std::vector<double> quantiles = {0.3, 0.5, 0.9};
std::unique_ptr<Quantiles<TypeParam>> test_quantiles =
typename Quantiles<TypeParam>::Builder()
.SetUpper(50)
.SetLower(-50)
.SetQuantiles(quantiles)
.Build()
.value();
EXPECT_THAT(test_quantiles->GetQuantiles(),
testing::UnorderedElementsAre(0.3, 0.5, 0.9));
}
} // namespace
} // namespace differential_privacy
|
// 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 "kudu/util/subprocess.h"
#include <errno.h>
#include <pthread.h>
#include <string.h>
#include <unistd.h>
#include <atomic>
#include <csignal>
#include <cstdio>
#include <cstdlib>
#include <functional>
#include <memory>
#include <ostream>
#include <string>
#include <thread>
#include <vector>
#include <glog/logging.h>
#include <gtest/gtest.h>
#include "kudu/gutil/macros.h"
#include "kudu/gutil/strings/substitute.h"
#include "kudu/util/barrier.h"
#include "kudu/util/env.h"
#include "kudu/util/monotime.h"
#include "kudu/util/path_util.h"
#include "kudu/util/scoped_cleanup.h"
#include "kudu/util/status.h"
#include "kudu/util/test_macros.h"
#include "kudu/util/test_util.h"
using std::atomic;
using std::string;
using std::thread;
using std::vector;
using strings::Substitute;
namespace kudu {
class SubprocessTest : public KuduTest {};
TEST_F(SubprocessTest, TestSimplePipe) {
Subprocess p({ "/usr/bin/tr", "a-z", "A-Z" });
p.ShareParentStdout(false);
ASSERT_OK(p.Start());
FILE* out = fdopen(p.ReleaseChildStdinFd(), "w");
PCHECK(out);
FILE* in = fdopen(p.from_child_stdout_fd(), "r");
PCHECK(in);
fprintf(out, "hello world\n");
// We have to close 'out' or else tr won't write any output, since
// it enters a buffered mode if it detects that its input is a FIFO.
int err;
RETRY_ON_EINTR(err, fclose(out));
char buf[1024];
ASSERT_EQ(buf, fgets(buf, sizeof(buf), in));
ASSERT_STREQ("HELLO WORLD\n", &buf[0]);
int wait_status = 0;
ASSERT_OK(p.Wait(&wait_status));
ASSERT_TRUE(WIFEXITED(wait_status));
ASSERT_EQ(0, WEXITSTATUS(wait_status));
}
TEST_F(SubprocessTest, TestErrPipe) {
Subprocess p({ "/usr/bin/tee", "/dev/stderr" });
p.ShareParentStderr(false);
ASSERT_OK(p.Start());
FILE* out = fdopen(p.ReleaseChildStdinFd(), "w");
PCHECK(out);
fprintf(out, "Hello, World\n");
// Same reasoning as above, flush to prevent tee buffering.
int err;
RETRY_ON_EINTR(err, fclose(out));
FILE* in = fdopen(p.from_child_stderr_fd(), "r");
PCHECK(in);
char buf[1024];
ASSERT_EQ(buf, fgets(buf, sizeof(buf), in));
ASSERT_STREQ("Hello, World\n", &buf[0]);
int wait_status = 0;
ASSERT_OK(p.Wait(&wait_status));
ASSERT_TRUE(WIFEXITED(wait_status));
ASSERT_EQ(0, WEXITSTATUS(wait_status));
}
TEST_F(SubprocessTest, TestKill) {
Subprocess p({ "/bin/cat" });
ASSERT_OK(p.Start());
ASSERT_OK(p.Kill(SIGKILL));
int wait_status = 0;
ASSERT_OK(p.Wait(&wait_status));
ASSERT_TRUE(WIFSIGNALED(wait_status));
ASSERT_EQ(SIGKILL, WTERMSIG(wait_status));
// Test that calling Wait() a second time returns the same
// cached value instead of trying to wait on some other process
// that was assigned the same pid.
wait_status = 0;
ASSERT_OK(p.Wait(&wait_status));
ASSERT_TRUE(WIFSIGNALED(wait_status));
ASSERT_EQ(SIGKILL, WTERMSIG(wait_status));
}
// Writes enough bytes to stdout and stderr concurrently that if Call() were
// fully reading them one at a time, the test would deadlock.
TEST_F(SubprocessTest, TestReadFromStdoutAndStderr) {
// Set an alarm to break out of any potential deadlocks (if the implementation
// regresses).
alarm(60);
string stdout;
string stderr;
ASSERT_OK(Subprocess::Call({
"/bin/bash",
"-c",
"dd if=/dev/urandom of=/dev/stdout bs=512 count=2048 &"
"dd if=/dev/urandom of=/dev/stderr bs=512 count=2048 &"
"wait"
}, "", &stdout, &stderr));
// Reset the alarm when the test is done
SCOPED_CLEANUP({ alarm(0); });
}
// Test that environment variables can be passed to the subprocess.
TEST_F(SubprocessTest, TestEnvVars) {
Subprocess p({ "/bin/bash", "-c", "echo $FOO" });
p.SetEnvVars({{"FOO", "bar"}});
p.ShareParentStdout(false);
ASSERT_OK(p.Start());
FILE* in = fdopen(p.from_child_stdout_fd(), "r");
PCHECK(in);
char buf[1024];
ASSERT_EQ(buf, fgets(buf, sizeof(buf), in));
ASSERT_STREQ("bar\n", &buf[0]);
ASSERT_OK(p.Wait());
}
// Test that the the subprocesses CWD can be set.
TEST_F(SubprocessTest, TestCurrentDir) {
string dir_path = GetTestPath("d");
string file_path = JoinPathSegments(dir_path, "f");
ASSERT_OK(Env::Default()->CreateDir(dir_path));
std::unique_ptr<WritableFile> file;
ASSERT_OK(Env::Default()->NewWritableFile(file_path, &file));
Subprocess p({ "/bin/ls", "f" });
p.SetCurrentDir(dir_path);
p.ShareParentStdout(false);
ASSERT_OK(p.Start());
ASSERT_OK(p.Wait());
int rc;
ASSERT_OK(p.GetExitStatus(&rc, nullptr));
EXPECT_EQ(0, rc);
}
// Tests writing to the subprocess stdin.
TEST_F(SubprocessTest, TestCallWithStdin) {
string stdout;
ASSERT_OK(Subprocess::Call({ "/bin/bash" },
"echo \"quick brown fox\"",
&stdout));
EXPECT_EQ("quick brown fox\n", stdout);
}
// Test KUDU-1674: '/bin/bash -c "echo"' command below is expected to
// capture a string on stderr. This test validates that passing
// stderr alone doesn't result in SIGSEGV as reported in the bug and
// also check for sanity of stderr in the output.
TEST_F(SubprocessTest, TestReadSingleFD) {
string stderr;
const string str = "ApacheKudu";
const string cmd_str = Substitute("/bin/echo -n $0 1>&2", str);
ASSERT_OK(Subprocess::Call({"/bin/sh", "-c", cmd_str}, "", nullptr, &stderr));
ASSERT_EQ(stderr, str);
// Also sanity check other combinations.
string stdout;
ASSERT_OK(Subprocess::Call({"/bin/ls", "/dev/null"}, "", &stdout, nullptr));
ASSERT_STR_CONTAINS(stdout, "/dev/null");
ASSERT_OK(Subprocess::Call({"/bin/ls", "/dev/zero"}, "", nullptr, nullptr));
}
TEST_F(SubprocessTest, TestGetExitStatusExitSuccess) {
Subprocess p({ "/bin/sh", "-c", "exit 0" });
ASSERT_OK(p.Start());
ASSERT_OK(p.Wait());
int exit_status;
string exit_info;
ASSERT_OK(p.GetExitStatus(&exit_status, &exit_info));
ASSERT_EQ(0, exit_status);
ASSERT_STR_CONTAINS(exit_info, "process successfully exited");
}
TEST_F(SubprocessTest, TestGetExitStatusExitFailure) {
static const vector<int> kStatusCodes = { 1, 255 };
for (auto code : kStatusCodes) {
Subprocess p({ "/bin/sh", "-c", Substitute("exit $0", code) });
ASSERT_OK(p.Start());
ASSERT_OK(p.Wait());
int exit_status;
string exit_info;
ASSERT_OK(p.GetExitStatus(&exit_status, &exit_info));
ASSERT_EQ(code, exit_status);
ASSERT_STR_CONTAINS(exit_info,
Substitute("process exited with non-zero status $0",
exit_status));
}
}
TEST_F(SubprocessTest, TestGetExitStatusSignaled) {
static const vector<int> kSignals = {
SIGHUP,
SIGABRT,
SIGKILL,
SIGTERM,
SIGUSR2,
};
for (auto signum : kSignals) {
Subprocess p({ "/bin/cat" });
ASSERT_OK(p.Start());
ASSERT_OK(p.Kill(signum));
ASSERT_OK(p.Wait());
int exit_status;
string exit_info;
ASSERT_OK(p.GetExitStatus(&exit_status, &exit_info));
EXPECT_EQ(signum, exit_status);
ASSERT_STR_CONTAINS(exit_info, Substitute("process exited on signal $0",
signum));
}
}
TEST_F(SubprocessTest, TestSubprocessDestroyWithCustomSignal) {
string kTestFile = GetTestPath("foo");
// Start a subprocess that creates kTestFile immediately and deletes it on exit.
//
// Note: it's important that the shell not invoke a command while waiting
// to be killed (i.e. "sleep 60"); if it did, the signal could be delivered
// just after the command starts but just before the shell decides to forward
// signals to it, and we wind up with a deadlock.
vector<string> argv = {
"/bin/bash",
"-c",
Substitute(
// Delete kTestFile on exit.
"trap \"rm $0\" EXIT;"
// Create kTestFile on start.
"touch $0;"
// Spin in a tight loop waiting to be killed.
"while true;"
" do FOO=$$((FOO + 1));"
"done", kTestFile)
};
{
Subprocess s(argv);
ASSERT_OK(s.Start());
AssertEventually([&]{
ASSERT_TRUE(env_->FileExists(kTestFile));
});
}
// The subprocess went out of scope and was killed with SIGKILL, so it left
// kTestFile behind.
ASSERT_TRUE(env_->FileExists(kTestFile));
ASSERT_OK(env_->DeleteFile(kTestFile));
{
Subprocess s(argv, SIGTERM);
ASSERT_OK(s.Start());
AssertEventually([&]{
ASSERT_TRUE(env_->FileExists(kTestFile));
});
}
// The subprocess was killed with SIGTERM, giving it a chance to delete kTestFile.
ASSERT_FALSE(env_->FileExists(kTestFile));
}
// TEST KUDU-2208: Test subprocess interruption handling
void handler(int /* signal */) {
}
TEST_F(SubprocessTest, TestSubprocessInterruptionHandling) {
// Create Subprocess thread
pthread_t t;
Subprocess p({ "/bin/sleep", "1" });
atomic<bool> t_started(false);
atomic<bool> t_finished(false);
thread subprocess_thread([&]() {
t = pthread_self();
t_started = true;
SleepFor(MonoDelta::FromMilliseconds(50));
CHECK_OK(p.Start());
CHECK_OK(p.Wait());
t_finished = true;
});
// Set up a no-op signal handler for SIGUSR2.
struct sigaction sa, sa_old;
memset(&sa, 0, sizeof(sa));
sa.sa_handler = &handler;
sigaction(SIGUSR2, &sa, &sa_old);
SCOPED_CLEANUP({ sigaction(SIGUSR2, &sa_old, nullptr); });
SCOPED_CLEANUP({ subprocess_thread.join(); });
// Send kill signals to Subprocess thread
LOG(INFO) << "Start sending kill signals to Subprocess thread";
while (!t_finished) {
if (t_started) {
int err = pthread_kill(t, SIGUSR2);
ASSERT_TRUE(err == 0 || err == ESRCH);
if (err == ESRCH) {
LOG(INFO) << "Async kill signal failed with err=" << err <<
" because it tried to kill vanished subprocess_thread";
ASSERT_TRUE(t_finished);
}
// Add microseconds delay to make the unit test runs faster and more reliable
SleepFor(MonoDelta::FromMicroseconds(rand() % 1));
}
}
}
// Test to make sure the spawned child process does not deadlock while running
// the code between fork() and exec().
TEST_F(SubprocessTest, TestSubprocessDeadlockOnLogging) {
int kNumLoggingThreads = 8;
// Participants are the logging threads and the main test thread.
Barrier barrier(kNumLoggingThreads + 1);
// It should not take too long to run the scenario unless it's deadlocked.
alarm(15);
SCOPED_CLEANUP({
alarm(0);
});
// Adding multiple threads writing logs. Each thread sleeps a bit after each
// message to get off from CPU.
atomic<bool> stop_logging(false);
vector<thread> threads;
for (auto i = 0; i < kNumLoggingThreads; ++i) {
const auto thread_idx = i;
threads.emplace_back([&barrier, &stop_logging, thread_idx] () {
barrier.Wait();
size_t msg_id = 0;
while (!stop_logging) {
LOG(INFO) << Substitute("$0: $1", thread_idx, msg_id++);
SleepFor(MonoDelta::FromNanoseconds(thread_idx));
}
});
}
SCOPED_CLEANUP({
stop_logging = true;
for (auto& thread : threads) {
thread.join();
}
});
barrier.Wait();
// Prior to the patch that fixed the problem, it was enough to have just one
// iteration to have the spawned process deadlocked. However, it does not hurt
// to run several iterations to give the issue, if any, a greater chance to
// manifest itself.
for (auto i = 0; i < 32; ++i) {
auto s = Subprocess::Call("./nonexistent.file");
ASSERT_TRUE(s.IsRuntimeError()) << s.ToString();
}
}
#ifdef __linux__
// This test requires a system with /proc/<pid>/stat.
TEST_F(SubprocessTest, TestGetProcfsState) {
// This test should be RUNNING.
Subprocess::ProcfsState state;
ASSERT_OK(Subprocess::GetProcfsState(getpid(), &state));
ASSERT_EQ(Subprocess::ProcfsState::RUNNING, state);
// When started, /bin/sleep will be RUNNING (even though it's asleep).
Subprocess sleep({"/bin/sleep", "1000"});
ASSERT_OK(sleep.Start());
ASSERT_OK(Subprocess::GetProcfsState(sleep.pid(), &state));
ASSERT_EQ(Subprocess::ProcfsState::RUNNING, state);
// After a SIGSTOP, it should be PAUSED.
ASSERT_OK(sleep.Kill(SIGSTOP));
ASSERT_OK(Subprocess::GetProcfsState(sleep.pid(), &state));
ASSERT_EQ(Subprocess::ProcfsState::PAUSED, state);
// After a SIGCONT, it should be RUNNING again.
ASSERT_OK(sleep.Kill(SIGCONT));
ASSERT_OK(Subprocess::GetProcfsState(sleep.pid(), &state));
ASSERT_EQ(Subprocess::ProcfsState::RUNNING, state);
}
#endif
} // namespace kudu
|
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2021 Laurent Gomila (laurent@sfml-dev.org)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_SYSTEM_HPP
#define SFML_SYSTEM_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Config.hpp>
#include <SFML/System/Clock.hpp>
#include <SFML/System/Err.hpp>
#include <SFML/System/FileInputStream.hpp>
#include <SFML/System/InputStream.hpp>
#include <SFML/System/Lock.hpp>
#include <SFML/System/MemoryInputStream.hpp>
#include <SFML/System/Mutex.hpp>
#include <SFML/System/NonCopyable.hpp>
#include <SFML/System/Sleep.hpp>
#include <SFML/System/String.hpp>
#include <SFML/System/Thread.hpp>
#include <SFML/System/ThreadLocal.hpp>
#include <SFML/System/ThreadLocalPtr.hpp>
#include <SFML/System/Time.hpp>
#include <SFML/System/Utf.hpp>
#include <SFML/System/Vector2.hpp>
#include <SFML/System/Vector3.hpp>
#endif // SFML_SYSTEM_HPP
////////////////////////////////////////////////////////////
/// \defgroup system System module
///
/// Base module of SFML, defining various utilities. It provides
/// vector classes, Unicode strings and conversion functions,
/// threads and mutexes, timing classes.
///
////////////////////////////////////////////////////////////
|
// Copyright (c) 2005-2014 Code Synthesis Tools CC
//
// This program was generated by CodeSynthesis XSD, an XML Schema to
// C++ data binding compiler.
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 2 as
// published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
//
// In addition, as a special exception, Code Synthesis Tools CC gives
// permission to link this program with the Xerces-C++ library (or with
// modified versions of Xerces-C++ that use the same license as Xerces-C++),
// and distribute linked combinations including the two. You must obey
// the GNU General Public License version 2 in all respects for all of
// the code used other than Xerces-C++. If you modify this copy of the
// program, you may extend this exception to your version of the program,
// but you are not obligated to do so. If you do not wish to do so, delete
// this exception statement from your version.
//
// Furthermore, Code Synthesis Tools CC makes a special exception for
// the Free/Libre and Open Source Software (FLOSS) which is described
// in the accompanying FLOSSE file.
//
#ifndef SIM_RAILING_PARAMS_RAILING_DEFAULT_HXX
#define SIM_RAILING_PARAMS_RAILING_DEFAULT_HXX
#ifndef XSD_USE_CHAR
#define XSD_USE_CHAR
#endif
#ifndef XSD_CXX_TREE_USE_CHAR
#define XSD_CXX_TREE_USE_CHAR
#endif
// Begin prologue.
//
//
// End prologue.
#include <xsd/cxx/config.hxx>
#if (XSD_INT_VERSION != 4000000L)
#error XSD runtime version mismatch
#endif
#include <xsd/cxx/pre.hxx>
#include <xsd/cxx/xml/char-utf8.hxx>
#include <xsd/cxx/tree/exceptions.hxx>
#include <xsd/cxx/tree/elements.hxx>
#include <xsd/cxx/tree/types.hxx>
#include <xsd/cxx/xml/error-handler.hxx>
#include <xsd/cxx/xml/dom/auto-ptr.hxx>
#include <xsd/cxx/tree/parsing.hxx>
#include <xsd/cxx/tree/parsing/byte.hxx>
#include <xsd/cxx/tree/parsing/unsigned-byte.hxx>
#include <xsd/cxx/tree/parsing/short.hxx>
#include <xsd/cxx/tree/parsing/unsigned-short.hxx>
#include <xsd/cxx/tree/parsing/int.hxx>
#include <xsd/cxx/tree/parsing/unsigned-int.hxx>
#include <xsd/cxx/tree/parsing/long.hxx>
#include <xsd/cxx/tree/parsing/unsigned-long.hxx>
#include <xsd/cxx/tree/parsing/boolean.hxx>
#include <xsd/cxx/tree/parsing/float.hxx>
#include <xsd/cxx/tree/parsing/double.hxx>
#include <xsd/cxx/tree/parsing/decimal.hxx>
namespace xml_schema
{
// anyType and anySimpleType.
//
typedef ::xsd::cxx::tree::type type;
typedef ::xsd::cxx::tree::simple_type< char, type > simple_type;
typedef ::xsd::cxx::tree::type container;
// 8-bit
//
typedef signed char byte;
typedef unsigned char unsigned_byte;
// 16-bit
//
typedef short short_;
typedef unsigned short unsigned_short;
// 32-bit
//
typedef int int_;
typedef unsigned int unsigned_int;
// 64-bit
//
typedef long long long_;
typedef unsigned long long unsigned_long;
// Supposed to be arbitrary-length integral types.
//
typedef long long integer;
typedef long long non_positive_integer;
typedef unsigned long long non_negative_integer;
typedef unsigned long long positive_integer;
typedef long long negative_integer;
// Boolean.
//
typedef bool boolean;
// Floating-point types.
//
typedef float float_;
typedef double double_;
typedef double decimal;
// String types.
//
typedef ::xsd::cxx::tree::string< char, simple_type > string;
typedef ::xsd::cxx::tree::normalized_string< char, string > normalized_string;
typedef ::xsd::cxx::tree::token< char, normalized_string > token;
typedef ::xsd::cxx::tree::name< char, token > name;
typedef ::xsd::cxx::tree::nmtoken< char, token > nmtoken;
typedef ::xsd::cxx::tree::nmtokens< char, simple_type, nmtoken > nmtokens;
typedef ::xsd::cxx::tree::ncname< char, name > ncname;
typedef ::xsd::cxx::tree::language< char, token > language;
// ID/IDREF.
//
typedef ::xsd::cxx::tree::id< char, ncname > id;
typedef ::xsd::cxx::tree::idref< char, ncname, type > idref;
typedef ::xsd::cxx::tree::idrefs< char, simple_type, idref > idrefs;
// URI.
//
typedef ::xsd::cxx::tree::uri< char, simple_type > uri;
// Qualified name.
//
typedef ::xsd::cxx::tree::qname< char, simple_type, uri, ncname > qname;
// Binary.
//
typedef ::xsd::cxx::tree::buffer< char > buffer;
typedef ::xsd::cxx::tree::base64_binary< char, simple_type > base64_binary;
typedef ::xsd::cxx::tree::hex_binary< char, simple_type > hex_binary;
// Date/time.
//
typedef ::xsd::cxx::tree::time_zone time_zone;
typedef ::xsd::cxx::tree::date< char, simple_type > date;
typedef ::xsd::cxx::tree::date_time< char, simple_type > date_time;
typedef ::xsd::cxx::tree::duration< char, simple_type > duration;
typedef ::xsd::cxx::tree::gday< char, simple_type > gday;
typedef ::xsd::cxx::tree::gmonth< char, simple_type > gmonth;
typedef ::xsd::cxx::tree::gmonth_day< char, simple_type > gmonth_day;
typedef ::xsd::cxx::tree::gyear< char, simple_type > gyear;
typedef ::xsd::cxx::tree::gyear_month< char, simple_type > gyear_month;
typedef ::xsd::cxx::tree::time< char, simple_type > time;
// Entity.
//
typedef ::xsd::cxx::tree::entity< char, ncname > entity;
typedef ::xsd::cxx::tree::entities< char, simple_type, entity > entities;
typedef ::xsd::cxx::tree::content_order content_order;
// Flags and properties.
//
typedef ::xsd::cxx::tree::flags flags;
typedef ::xsd::cxx::tree::properties< char > properties;
// Parsing/serialization diagnostics.
//
typedef ::xsd::cxx::tree::severity severity;
typedef ::xsd::cxx::tree::error< char > error;
typedef ::xsd::cxx::tree::diagnostics< char > diagnostics;
// Exceptions.
//
typedef ::xsd::cxx::tree::exception< char > exception;
typedef ::xsd::cxx::tree::bounds< char > bounds;
typedef ::xsd::cxx::tree::duplicate_id< char > duplicate_id;
typedef ::xsd::cxx::tree::parsing< char > parsing;
typedef ::xsd::cxx::tree::expected_element< char > expected_element;
typedef ::xsd::cxx::tree::unexpected_element< char > unexpected_element;
typedef ::xsd::cxx::tree::expected_attribute< char > expected_attribute;
typedef ::xsd::cxx::tree::unexpected_enumerator< char > unexpected_enumerator;
typedef ::xsd::cxx::tree::expected_text_content< char > expected_text_content;
typedef ::xsd::cxx::tree::no_prefix_mapping< char > no_prefix_mapping;
typedef ::xsd::cxx::tree::no_type_info< char > no_type_info;
typedef ::xsd::cxx::tree::not_derived< char > not_derived;
// Error handler callback interface.
//
typedef ::xsd::cxx::xml::error_handler< char > error_handler;
// DOM interaction.
//
namespace dom
{
// Automatic pointer for DOMDocument.
//
using ::xsd::cxx::xml::dom::auto_ptr;
#ifndef XSD_CXX_TREE_TREE_NODE_KEY__XML_SCHEMA
#define XSD_CXX_TREE_TREE_NODE_KEY__XML_SCHEMA
// DOM user data key for back pointers to tree nodes.
//
const XMLCh* const tree_node_key = ::xsd::cxx::tree::user_data_keys::node;
#endif
}
}
// Forward declarations.
//
namespace schema
{
namespace simxml
{
namespace ResourcesGeneral
{
class SimRailingParams_Railing_Default;
}
}
}
#include <memory> // ::std::auto_ptr
#include <limits> // std::numeric_limits
#include <algorithm> // std::binary_search
#include <xsd/cxx/xml/char-utf8.hxx>
#include <xsd/cxx/tree/exceptions.hxx>
#include <xsd/cxx/tree/elements.hxx>
#include <xsd/cxx/tree/containers.hxx>
#include <xsd/cxx/tree/list.hxx>
#include <xsd/cxx/xml/dom/parsing-header.hxx>
#include "simrailingparams_railing.hxx"
namespace schema
{
namespace simxml
{
namespace ResourcesGeneral
{
class SimRailingParams_Railing_Default: public ::schema::simxml::ResourcesGeneral::SimRailingParams_Railing
{
public:
// Constructors.
//
SimRailingParams_Railing_Default ();
SimRailingParams_Railing_Default (const RefId_type&);
SimRailingParams_Railing_Default (const ::xercesc::DOMElement& e,
::xml_schema::flags f = 0,
::xml_schema::container* c = 0);
SimRailingParams_Railing_Default (const SimRailingParams_Railing_Default& x,
::xml_schema::flags f = 0,
::xml_schema::container* c = 0);
virtual SimRailingParams_Railing_Default*
_clone (::xml_schema::flags f = 0,
::xml_schema::container* c = 0) const;
virtual
~SimRailingParams_Railing_Default ();
};
}
}
}
#include <iosfwd>
#include <xercesc/sax/InputSource.hpp>
#include <xercesc/dom/DOMDocument.hpp>
#include <xercesc/dom/DOMErrorHandler.hpp>
namespace schema
{
namespace simxml
{
namespace ResourcesGeneral
{
}
}
}
#include <xsd/cxx/post.hxx>
// Begin epilogue.
//
//
// End epilogue.
#endif // SIM_RAILING_PARAMS_RAILING_DEFAULT_HXX
|
/*
* Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
// CLASS HEADER
#include <dali/internal/window-system/ubuntu-x11/window-base-ecore-x.h>
// INTERNAL HEADERS
#include <dali/internal/window-system/common/window-impl.h>
#include <dali/internal/window-system/common/window-render-surface.h>
#include <dali/internal/window-system/common/window-system.h>
#include <dali/internal/window-system/ubuntu-x11/ecore-x-types.h>
// EXTERNAL_HEADERS
#include <dali/integration-api/debug.h>
#include <dali/internal/input/ubuntu-x11/dali-ecore-input.h>
#include <dali/public-api/events/mouse-button.h>
#include <dali/public-api/object/any.h>
namespace Dali
{
namespace Internal
{
namespace Adaptor
{
namespace
{
const std::string DEFAULT_DEVICE_NAME = "";
const Device::Class::Type DEFAULT_DEVICE_CLASS = Device::Class::NONE;
const Device::Subclass::Type DEFAULT_DEVICE_SUBCLASS = Device::Subclass::NONE;
const unsigned int PRIMARY_TOUCH_BUTTON_ID(1);
#if defined(DEBUG_ENABLED)
Debug::Filter* gWindowBaseLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_WINDOW_BASE");
#endif
/////////////////////////////////////////////////////////////////////////////////////////////////
// Window Callbacks
/////////////////////////////////////////////////////////////////////////////////////////////////
static Eina_Bool EcoreEventWindowPropertyChanged(void* data, int type, void* event)
{
WindowBaseEcoreX* windowBase = static_cast<WindowBaseEcoreX*>(data);
if(windowBase)
{
return windowBase->OnWindowPropertyChanged(data, type, event);
}
return ECORE_CALLBACK_PASS_ON;
}
/**
* Called when the window receives a delete request
*/
static Eina_Bool EcoreEventWindowDeleteRequest(void* data, int type, void* event)
{
WindowBaseEcoreX* windowBase = static_cast<WindowBaseEcoreX*>(data);
if(windowBase)
{
windowBase->OnDeleteRequest();
}
return ECORE_CALLBACK_DONE;
}
/**
* Called when the window gains focus.
*/
static Eina_Bool EcoreEventWindowFocusIn(void* data, int type, void* event)
{
WindowBaseEcoreX* windowBase = static_cast<WindowBaseEcoreX*>(data);
if(windowBase)
{
windowBase->OnFocusIn(data, type, event);
}
return ECORE_CALLBACK_PASS_ON;
}
/**
* Called when the window loses focus.
*/
static Eina_Bool EcoreEventWindowFocusOut(void* data, int type, void* event)
{
WindowBaseEcoreX* windowBase = static_cast<WindowBaseEcoreX*>(data);
if(windowBase)
{
windowBase->OnFocusOut(data, type, event);
}
return ECORE_CALLBACK_PASS_ON;
}
/**
* Called when the window is damaged.
*/
static Eina_Bool EcoreEventWindowDamaged(void* data, int type, void* event)
{
WindowBaseEcoreX* windowBase = static_cast<WindowBaseEcoreX*>(data);
if(windowBase)
{
windowBase->OnWindowDamaged(data, type, event);
}
return ECORE_CALLBACK_PASS_ON;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
// Selection Callbacks
/////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Called when the source window notifies us the content in clipboard is selected.
*/
static Eina_Bool EcoreEventSelectionClear(void* data, int type, void* event)
{
WindowBaseEcoreX* windowBase = static_cast<WindowBaseEcoreX*>(data);
if(windowBase)
{
windowBase->OnSelectionClear(data, type, event);
}
return ECORE_CALLBACK_PASS_ON;
}
/**
* Called when the source window sends us about the selected content.
* For example, when dragged items are dragged INTO our window or when items are selected in the clipboard.
*/
static Eina_Bool EcoreEventSelectionNotify(void* data, int type, void* event)
{
WindowBaseEcoreX* windowBase = static_cast<WindowBaseEcoreX*>(data);
if(windowBase)
{
windowBase->OnSelectionNotify(data, type, event);
}
return ECORE_CALLBACK_PASS_ON;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
// Touch Callbacks
/////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Called when a touch down is received.
*/
static Eina_Bool EcoreEventMouseButtonDown(void* data, int type, void* event)
{
WindowBaseEcoreX* windowBase = static_cast<WindowBaseEcoreX*>(data);
if(windowBase)
{
windowBase->OnMouseButtonDown(data, type, event);
}
return ECORE_CALLBACK_PASS_ON;
}
/**
* Called when a touch up is received.
*/
static Eina_Bool EcoreEventMouseButtonUp(void* data, int type, void* event)
{
WindowBaseEcoreX* windowBase = static_cast<WindowBaseEcoreX*>(data);
if(windowBase)
{
windowBase->OnMouseButtonUp(data, type, event);
}
return ECORE_CALLBACK_PASS_ON;
}
/**
* Called when a touch motion is received.
*/
static Eina_Bool EcoreEventMouseButtonMove(void* data, int type, void* event)
{
WindowBaseEcoreX* windowBase = static_cast<WindowBaseEcoreX*>(data);
if(windowBase)
{
windowBase->OnMouseButtonMove(data, type, event);
}
return ECORE_CALLBACK_PASS_ON;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
// Wheel Callbacks
/////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Called when a mouse wheel is received.
*/
static Eina_Bool EcoreEventMouseWheel(void* data, int type, void* event)
{
WindowBaseEcoreX* windowBase = static_cast<WindowBaseEcoreX*>(data);
if(windowBase)
{
windowBase->OnMouseWheel(data, type, event);
}
return ECORE_CALLBACK_PASS_ON;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
// Key Callbacks
/////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Called when a key down is received.
*/
static Eina_Bool EcoreEventKeyDown(void* data, int type, void* event)
{
WindowBaseEcoreX* windowBase = static_cast<WindowBaseEcoreX*>(data);
if(windowBase)
{
windowBase->OnKeyDown(data, type, event);
}
return ECORE_CALLBACK_PASS_ON;
}
/**
* Called when a key up is received.
*/
static Eina_Bool EcoreEventKeyUp(void* data, int type, void* event)
{
WindowBaseEcoreX* windowBase = static_cast<WindowBaseEcoreX*>(data);
if(windowBase)
{
windowBase->OnKeyUp(data, type, event);
}
return ECORE_CALLBACK_PASS_ON;
}
} // unnamed namespace
WindowBaseEcoreX::WindowBaseEcoreX(Dali::PositionSize positionSize, Any surface, bool isTransparent)
: mEcoreEventHandler(),
mEcoreWindow(0),
mOwnSurface(false),
mIsTransparent(false), // Should only be set to true once we actually create a transparent window regardless of what isTransparent is.
mRotationAppSet(false),
mWindowRotationAngle(0)
{
Initialize(positionSize, surface, isTransparent);
}
WindowBaseEcoreX::~WindowBaseEcoreX()
{
for(Dali::Vector<Ecore_Event_Handler*>::Iterator iter = mEcoreEventHandler.Begin(), endIter = mEcoreEventHandler.End(); iter != endIter; ++iter)
{
ecore_event_handler_del(*iter);
}
mEcoreEventHandler.Clear();
if(mOwnSurface)
{
ecore_x_window_free(mEcoreWindow);
WindowSystem::Shutdown();
}
}
void WindowBaseEcoreX::Initialize(PositionSize positionSize, Any surface, bool isTransparent)
{
// see if there is a surface in Any surface
unsigned int surfaceId = GetSurfaceId(surface);
// if the surface is empty, create a new one.
if(surfaceId == 0)
{
WindowSystem::Initialize();
// we own the surface about to created
mOwnSurface = true;
CreateWindow(positionSize, isTransparent);
}
else
{
// XLib should already be initialized so no point in calling XInitThreads
mEcoreWindow = static_cast<Ecore_X_Window>(surfaceId);
}
// set up etc properties to match with ecore-evas
char* id = NULL;
if((id = getenv("DESKTOP_STARTUP_ID")))
{
ecore_x_netwm_startup_id_set(mEcoreWindow, id);
}
ecore_x_icccm_hints_set(mEcoreWindow,
1, // accepts_focus
ECORE_X_WINDOW_STATE_HINT_NORMAL, // initial_state
0, // icon_pixmap
0, // icon_mask
0, // icon_window
0, // window_group
0); // is_urgent
// we SHOULD guarantee the x11 window was created in x server.
ecore_x_sync();
ecore_x_input_multi_select(mEcoreWindow);
// This ensures that we catch the window close (or delete) request
ecore_x_icccm_protocol_set(mEcoreWindow, ECORE_X_WM_PROTOCOL_DELETE_REQUEST, EINA_TRUE);
// Enable Drag & Drop
ecore_x_dnd_aware_set(mEcoreWindow, EINA_TRUE);
mEcoreEventHandler.PushBack(ecore_event_handler_add(ECORE_X_EVENT_WINDOW_PROPERTY, EcoreEventWindowPropertyChanged, this));
mEcoreEventHandler.PushBack(ecore_event_handler_add(ECORE_X_EVENT_WINDOW_DELETE_REQUEST, EcoreEventWindowDeleteRequest, this));
// Register window focus events
mEcoreEventHandler.PushBack(ecore_event_handler_add(ECORE_X_EVENT_WINDOW_FOCUS_IN, EcoreEventWindowFocusIn, this));
mEcoreEventHandler.PushBack(ecore_event_handler_add(ECORE_X_EVENT_WINDOW_FOCUS_OUT, EcoreEventWindowFocusOut, this));
// Register Window damage events
mEcoreEventHandler.PushBack(ecore_event_handler_add(ECORE_X_EVENT_WINDOW_DAMAGE, EcoreEventWindowDamaged, this));
// Register Touch events
mEcoreEventHandler.PushBack(ecore_event_handler_add(ECORE_EVENT_MOUSE_BUTTON_DOWN, EcoreEventMouseButtonDown, this));
mEcoreEventHandler.PushBack(ecore_event_handler_add(ECORE_EVENT_MOUSE_BUTTON_UP, EcoreEventMouseButtonUp, this));
mEcoreEventHandler.PushBack(ecore_event_handler_add(ECORE_EVENT_MOUSE_MOVE, EcoreEventMouseButtonMove, this));
mEcoreEventHandler.PushBack(ecore_event_handler_add(ECORE_EVENT_MOUSE_OUT, EcoreEventMouseButtonUp, this)); // process mouse out event like up event
// Register Mouse wheel events
mEcoreEventHandler.PushBack(ecore_event_handler_add(ECORE_EVENT_MOUSE_WHEEL, EcoreEventMouseWheel, this));
// Register Key events
mEcoreEventHandler.PushBack(ecore_event_handler_add(ECORE_EVENT_KEY_DOWN, EcoreEventKeyDown, this));
mEcoreEventHandler.PushBack(ecore_event_handler_add(ECORE_EVENT_KEY_UP, EcoreEventKeyUp, this));
// Register Selection event
mEcoreEventHandler.PushBack(ecore_event_handler_add(ECORE_X_EVENT_SELECTION_CLEAR, EcoreEventSelectionClear, this));
mEcoreEventHandler.PushBack(ecore_event_handler_add(ECORE_X_EVENT_SELECTION_NOTIFY, EcoreEventSelectionNotify, this));
}
Eina_Bool WindowBaseEcoreX::OnWindowPropertyChanged(void* data, int type, void* event)
{
Ecore_X_Event_Window_Property* propertyChangedEvent = static_cast<Ecore_X_Event_Window_Property*>(event);
Eina_Bool handled(ECORE_CALLBACK_PASS_ON);
if(propertyChangedEvent->win == mEcoreWindow)
{
Ecore_X_Window_State_Hint state(ecore_x_icccm_state_get(propertyChangedEvent->win));
switch(state)
{
case ECORE_X_WINDOW_STATE_HINT_WITHDRAWN:
{
// Window was hidden.
mIconifyChangedSignal.Emit(true);
handled = ECORE_CALLBACK_DONE;
break;
}
case ECORE_X_WINDOW_STATE_HINT_ICONIC:
{
// Window was iconified (minimised).
mIconifyChangedSignal.Emit(true);
handled = ECORE_CALLBACK_DONE;
break;
}
case ECORE_X_WINDOW_STATE_HINT_NORMAL:
{
// Window was shown.
mIconifyChangedSignal.Emit(false);
handled = ECORE_CALLBACK_DONE;
break;
}
default:
{
// Ignore
break;
}
}
}
return handled;
}
void WindowBaseEcoreX::OnDeleteRequest()
{
mDeleteRequestSignal.Emit();
}
void WindowBaseEcoreX::OnFocusIn(void* data, int type, void* event)
{
Ecore_X_Event_Window_Focus_In* focusInEvent = static_cast<Ecore_X_Event_Window_Focus_In*>(event);
if(focusInEvent->win == mEcoreWindow)
{
DALI_LOG_INFO(gWindowBaseLogFilter, Debug::General, "Window EcoreEventWindowFocusIn\n");
mFocusChangedSignal.Emit(true);
}
}
void WindowBaseEcoreX::OnFocusOut(void* data, int type, void* event)
{
Ecore_X_Event_Window_Focus_Out* focusOutEvent = static_cast<Ecore_X_Event_Window_Focus_Out*>(event);
// If the window loses focus then hide the keyboard.
if(focusOutEvent->win == mEcoreWindow)
{
DALI_LOG_INFO(gWindowBaseLogFilter, Debug::General, "Window EcoreEventWindowFocusOut\n");
mFocusChangedSignal.Emit(false);
}
}
void WindowBaseEcoreX::OnWindowDamaged(void* data, int type, void* event)
{
Ecore_X_Event_Window_Damage* windowDamagedEvent = static_cast<Ecore_X_Event_Window_Damage*>(event);
if(windowDamagedEvent->win == mEcoreWindow)
{
DamageArea area;
area.x = windowDamagedEvent->x;
area.y = windowDamagedEvent->y;
area.width = windowDamagedEvent->w;
area.height = windowDamagedEvent->h;
mWindowDamagedSignal.Emit(area);
}
}
void WindowBaseEcoreX::OnMouseButtonDown(void* data, int type, void* event)
{
Ecore_Event_Mouse_Button* touchEvent = static_cast<Ecore_Event_Mouse_Button*>(event);
if(touchEvent->window == mEcoreWindow)
{
PointState::Type state(PointState::DOWN);
Integration::Point point;
point.SetDeviceId(touchEvent->multi.device);
point.SetState(state);
point.SetScreenPosition(Vector2(touchEvent->x, touchEvent->y));
point.SetRadius(touchEvent->multi.radius, Vector2(touchEvent->multi.radius_x, touchEvent->multi.radius_y));
point.SetPressure(touchEvent->multi.pressure);
point.SetAngle(Degree(touchEvent->multi.angle));
if(touchEvent->buttons)
{
point.SetMouseButton(static_cast<MouseButton::Type>(touchEvent->buttons));
}
mTouchEventSignal.Emit(point, touchEvent->timestamp);
}
}
void WindowBaseEcoreX::OnMouseButtonUp(void* data, int type, void* event)
{
Ecore_Event_Mouse_Button* touchEvent = static_cast<Ecore_Event_Mouse_Button*>(event);
if(touchEvent->window == mEcoreWindow)
{
Integration::Point point;
point.SetDeviceId(touchEvent->multi.device);
point.SetState(PointState::UP);
point.SetScreenPosition(Vector2(touchEvent->x, touchEvent->y));
point.SetRadius(touchEvent->multi.radius, Vector2(touchEvent->multi.radius_x, touchEvent->multi.radius_y));
point.SetPressure(touchEvent->multi.pressure);
point.SetAngle(Degree(static_cast<float>(touchEvent->multi.angle)));
if(touchEvent->buttons)
{
point.SetMouseButton(static_cast<MouseButton::Type>(touchEvent->buttons));
}
mTouchEventSignal.Emit(point, touchEvent->timestamp);
}
}
void WindowBaseEcoreX::OnMouseButtonMove(void* data, int type, void* event)
{
Ecore_Event_Mouse_Move* touchEvent = static_cast<Ecore_Event_Mouse_Move*>(event);
if(touchEvent->window == mEcoreWindow)
{
Integration::Point point;
point.SetDeviceId(touchEvent->multi.device);
point.SetState(PointState::MOTION);
point.SetScreenPosition(Vector2(static_cast<float>(touchEvent->x), static_cast<float>(touchEvent->y)));
point.SetRadius(static_cast<float>(touchEvent->multi.radius), Vector2(static_cast<float>(touchEvent->multi.radius_x), static_cast<float>(touchEvent->multi.radius_y)));
point.SetPressure(static_cast<float>(touchEvent->multi.pressure));
point.SetAngle(Degree(static_cast<float>(touchEvent->multi.angle)));
mTouchEventSignal.Emit(point, touchEvent->timestamp);
}
}
void WindowBaseEcoreX::OnMouseWheel(void* data, int type, void* event)
{
Ecore_Event_Mouse_Wheel* mouseWheelEvent = static_cast<Ecore_Event_Mouse_Wheel*>(event);
if(mouseWheelEvent->window == mEcoreWindow)
{
DALI_LOG_INFO(gWindowBaseLogFilter, Debug::General, "WindowBaseEcoreX::OnMouseWheel: direction: %d, modifiers: %d, x: %d, y: %d, z: %d\n", mouseWheelEvent->direction, mouseWheelEvent->modifiers, mouseWheelEvent->x, mouseWheelEvent->y, mouseWheelEvent->z);
Integration::WheelEvent wheelEvent(Integration::WheelEvent::MOUSE_WHEEL, mouseWheelEvent->direction, mouseWheelEvent->modifiers, Vector2(static_cast<float>(mouseWheelEvent->x), static_cast<float>(mouseWheelEvent->y)), mouseWheelEvent->z, mouseWheelEvent->timestamp);
mWheelEventSignal.Emit(wheelEvent);
}
}
void WindowBaseEcoreX::OnKeyDown(void* data, int type, void* event)
{
Ecore_Event_Key* keyEvent = static_cast<Ecore_Event_Key*>(event);
if(keyEvent->window == mEcoreWindow)
{
DALI_LOG_INFO(gWindowBaseLogFilter, Debug::General, "WindowBaseEcoreX::OnKeyDown\n");
std::string keyName(keyEvent->keyname);
std::string logicalKey("");
std::string keyString("");
std::string compose("");
// Ensure key compose string is not NULL as keys like SHIFT or arrow have a null string.
if(keyEvent->compose)
{
compose = keyEvent->compose;
}
// Ensure key symbol is not NULL as keys like SHIFT have a null string.
if(keyEvent->key)
{
logicalKey = keyEvent->key;
}
int keyCode = ecore_x_keysym_keycode_get(keyEvent->keyname);
int modifier(keyEvent->modifiers);
unsigned long time = keyEvent->timestamp;
// Ensure key event string is not NULL as keys like SHIFT have a null string.
if(keyEvent->string)
{
keyString = keyEvent->string;
}
Integration::KeyEvent keyEvent(keyName, logicalKey, keyString, keyCode, modifier, time, Integration::KeyEvent::DOWN, compose, DEFAULT_DEVICE_NAME, DEFAULT_DEVICE_CLASS, DEFAULT_DEVICE_SUBCLASS);
mKeyEventSignal.Emit(keyEvent);
}
}
void WindowBaseEcoreX::OnKeyUp(void* data, int type, void* event)
{
Ecore_Event_Key* keyEvent = static_cast<Ecore_Event_Key*>(event);
if(keyEvent->window == mEcoreWindow)
{
DALI_LOG_INFO(gWindowBaseLogFilter, Debug::General, " WindowBaseEcoreX::OnKeyUp\n");
std::string keyName(keyEvent->keyname);
std::string logicalKey("");
std::string keyString("");
std::string compose("");
// Ensure key compose string is not NULL as keys like SHIFT or arrow have a null string.
if(keyEvent->compose)
{
compose = keyEvent->compose;
}
// Ensure key symbol is not NULL as keys like SHIFT have a null string.
if(keyEvent->key)
{
logicalKey = keyEvent->key;
}
int keyCode = ecore_x_keysym_keycode_get(keyEvent->keyname);
int modifier(keyEvent->modifiers);
unsigned long time(keyEvent->timestamp);
// Ensure key event string is not NULL as keys like SHIFT have a null string.
if(keyEvent->string)
{
keyString = keyEvent->string;
}
Integration::KeyEvent keyEvent(keyName, logicalKey, keyString, keyCode, modifier, time, Integration::KeyEvent::UP, compose, DEFAULT_DEVICE_NAME, DEFAULT_DEVICE_CLASS, DEFAULT_DEVICE_SUBCLASS);
mKeyEventSignal.Emit(keyEvent);
}
}
void WindowBaseEcoreX::OnSelectionClear(void* data, int type, void* event)
{
Ecore_X_Event_Selection_Clear* selectionClearEvent = static_cast<Ecore_X_Event_Selection_Clear*>(event);
if(selectionClearEvent->win == mEcoreWindow)
{
DALI_LOG_INFO(gWindowBaseLogFilter, Debug::Concise, " WindowBaseEcoreX::OnSelectionClear\n");
if(selectionClearEvent->selection == ECORE_X_SELECTION_SECONDARY)
{
// Request to get the content from Ecore.
ecore_x_selection_secondary_request(selectionClearEvent->win, ECORE_X_SELECTION_TARGET_TEXT);
}
}
}
void WindowBaseEcoreX::OnSelectionNotify(void* data, int type, void* event)
{
Ecore_X_Event_Selection_Notify* selectionNotifyEvent = static_cast<Ecore_X_Event_Selection_Notify*>(event);
if(selectionNotifyEvent->win == mEcoreWindow)
{
DALI_LOG_INFO(gWindowBaseLogFilter, Debug::Concise, " WindowBaseEcoreX::OnSelectionNotify\n");
Ecore_X_Selection_Data* selectionData = static_cast<Ecore_X_Selection_Data*>(selectionNotifyEvent->data);
if(selectionData->data)
{
if(selectionNotifyEvent->selection == ECORE_X_SELECTION_SECONDARY)
{
mSelectionDataReceivedSignal.Emit(event);
}
}
}
}
Any WindowBaseEcoreX::GetNativeWindow()
{
return mEcoreWindow;
}
int WindowBaseEcoreX::GetNativeWindowId()
{
return mEcoreWindow;
}
EGLNativeWindowType WindowBaseEcoreX::CreateEglWindow(int width, int height)
{
// need to create X handle as in 64bit system ECore handle is 32 bit whereas EGLnative and XWindow are 64 bit
XWindow window(mEcoreWindow);
return reinterpret_cast<EGLNativeWindowType>(window);
}
void WindowBaseEcoreX::DestroyEglWindow()
{
}
void WindowBaseEcoreX::SetEglWindowRotation(int angle)
{
}
void WindowBaseEcoreX::SetEglWindowBufferTransform(int angle)
{
}
void WindowBaseEcoreX::SetEglWindowTransform(int angle)
{
}
void WindowBaseEcoreX::ResizeEglWindow(PositionSize positionSize)
{
}
bool WindowBaseEcoreX::IsEglWindowRotationSupported()
{
return false;
}
void WindowBaseEcoreX::Move(PositionSize positionSize)
{
ecore_x_window_move(mEcoreWindow, positionSize.x, positionSize.y);
}
void WindowBaseEcoreX::Resize(PositionSize positionSize)
{
ecore_x_window_resize(mEcoreWindow, positionSize.width, positionSize.height);
}
void WindowBaseEcoreX::MoveResize(PositionSize positionSize)
{
ecore_x_window_move_resize(mEcoreWindow, positionSize.x, positionSize.y, positionSize.width, positionSize.height);
}
void WindowBaseEcoreX::SetClass(const std::string& name, const std::string& className)
{
ecore_x_icccm_title_set(mEcoreWindow, name.c_str());
ecore_x_netwm_name_set(mEcoreWindow, name.c_str());
ecore_x_icccm_name_class_set(mEcoreWindow, name.c_str(), className.c_str());
}
void WindowBaseEcoreX::Raise()
{
ecore_x_window_raise(mEcoreWindow);
}
void WindowBaseEcoreX::Lower()
{
ecore_x_window_lower(mEcoreWindow);
}
void WindowBaseEcoreX::Activate()
{
ecore_x_netwm_client_active_request(ecore_x_window_root_get(mEcoreWindow), mEcoreWindow, 1 /* request type, 1:application, 2:pager */, 0);
}
void WindowBaseEcoreX::SetAvailableAnlges(const std::vector<int>& angles)
{
}
void WindowBaseEcoreX::SetPreferredAngle(int angle)
{
}
void WindowBaseEcoreX::SetAcceptFocus(bool accept)
{
}
void WindowBaseEcoreX::Show()
{
ecore_x_window_show(mEcoreWindow);
}
void WindowBaseEcoreX::Hide()
{
ecore_x_window_hide(mEcoreWindow);
}
unsigned int WindowBaseEcoreX::GetSupportedAuxiliaryHintCount() const
{
return 0;
}
std::string WindowBaseEcoreX::GetSupportedAuxiliaryHint(unsigned int index) const
{
return std::string();
}
unsigned int WindowBaseEcoreX::AddAuxiliaryHint(const std::string& hint, const std::string& value)
{
return 0;
}
bool WindowBaseEcoreX::RemoveAuxiliaryHint(unsigned int id)
{
return false;
}
bool WindowBaseEcoreX::SetAuxiliaryHintValue(unsigned int id, const std::string& value)
{
return false;
}
std::string WindowBaseEcoreX::GetAuxiliaryHintValue(unsigned int id) const
{
return std::string();
}
unsigned int WindowBaseEcoreX::GetAuxiliaryHintId(const std::string& hint) const
{
return 0;
}
void WindowBaseEcoreX::SetInputRegion(const Rect<int>& inputRegion)
{
}
void WindowBaseEcoreX::SetType(Dali::WindowType type)
{
}
Dali::WindowType WindowBaseEcoreX::GetType() const
{
return Dali::WindowType::NORMAL;
}
Dali::WindowOperationResult WindowBaseEcoreX::SetNotificationLevel(Dali::WindowNotificationLevel level)
{
return Dali::WindowOperationResult::NOT_SUPPORTED;
}
Dali::WindowNotificationLevel WindowBaseEcoreX::GetNotificationLevel() const
{
return Dali::WindowNotificationLevel::NONE;
}
void WindowBaseEcoreX::SetOpaqueState(bool opaque)
{
}
Dali::WindowOperationResult WindowBaseEcoreX::SetScreenOffMode(WindowScreenOffMode screenOffMode)
{
return Dali::WindowOperationResult::NOT_SUPPORTED;
}
WindowScreenOffMode WindowBaseEcoreX::GetScreenOffMode() const
{
return WindowScreenOffMode::TIMEOUT;
}
Dali::WindowOperationResult WindowBaseEcoreX::SetBrightness(int brightness)
{
return Dali::WindowOperationResult::NOT_SUPPORTED;
}
int WindowBaseEcoreX::GetBrightness() const
{
return 0;
}
bool WindowBaseEcoreX::GrabKey(Dali::KEY key, KeyGrab::KeyGrabMode grabMode)
{
return false;
}
bool WindowBaseEcoreX::UngrabKey(Dali::KEY key)
{
return false;
}
bool WindowBaseEcoreX::GrabKeyList(const Dali::Vector<Dali::KEY>& key, const Dali::Vector<KeyGrab::KeyGrabMode>& grabMode, Dali::Vector<bool>& result)
{
return false;
}
bool WindowBaseEcoreX::UngrabKeyList(const Dali::Vector<Dali::KEY>& key, Dali::Vector<bool>& result)
{
return false;
}
void WindowBaseEcoreX::GetDpi(unsigned int& dpiHorizontal, unsigned int& dpiVertical)
{
// 1 inch = 25.4 millimeters
// ecore does not account for differing DPI in the x and y axes, so only get for x is available
dpiHorizontal = ecore_x_dpi_get();
dpiVertical = ecore_x_dpi_get();
}
int WindowBaseEcoreX::GetOrientation() const
{
return 0;
}
int WindowBaseEcoreX::GetScreenRotationAngle()
{
return 0;
}
void WindowBaseEcoreX::SetWindowRotationAngle(int degree)
{
mWindowRotationAngle = degree;
}
void WindowBaseEcoreX::WindowRotationCompleted(int degree, int width, int height)
{
}
void WindowBaseEcoreX::SetTransparency(bool transparent)
{
}
unsigned int WindowBaseEcoreX::GetSurfaceId(Any surface) const
{
unsigned int surfaceId = 0;
if(surface.Empty() == false)
{
// check we have a valid type
DALI_ASSERT_ALWAYS(((surface.GetType() == typeid(XWindow)) || (surface.GetType() == typeid(Ecore_X_Window))) && "Surface type is invalid");
if(surface.GetType() == typeid(Ecore_X_Window))
{
surfaceId = AnyCast<Ecore_X_Window>(surface);
}
else
{
surfaceId = static_cast<unsigned int>(AnyCast<XWindow>(surface));
}
}
return surfaceId;
}
void WindowBaseEcoreX::CreateWindow(PositionSize positionSize, bool isTransparent)
{
if(isTransparent)
{
// create 32 bit window
mEcoreWindow = ecore_x_window_argb_new(0, positionSize.x, positionSize.y, positionSize.width, positionSize.height);
mIsTransparent = true;
}
else
{
// create 24 bit window
mEcoreWindow = ecore_x_window_new(0, positionSize.x, positionSize.y, positionSize.width, positionSize.height);
}
if(mEcoreWindow == 0)
{
DALI_ASSERT_ALWAYS(0 && "Failed to create X window");
}
}
void WindowBaseEcoreX::SetParent(WindowBase* parentWinBase, bool belowParent)
{
Ecore_X_Window ecoreParent = 0;
if(parentWinBase)
{
WindowBaseEcoreX* winBaseEcoreX = static_cast<WindowBaseEcoreX*>(parentWinBase);
ecoreParent = winBaseEcoreX->mEcoreWindow;
ecore_x_icccm_transient_for_set(mEcoreWindow, ecoreParent);
}
else
{
ecoreParent = 0;
ecore_x_icccm_transient_for_unset(mEcoreWindow);
}
}
int WindowBaseEcoreX::CreateFrameRenderedSyncFence()
{
return -1;
}
int WindowBaseEcoreX::CreateFramePresentedSyncFence()
{
return -1;
}
void WindowBaseEcoreX::SetPositionSizeWithAngle(PositionSize positionSize, int angle)
{
}
void WindowBaseEcoreX::InitializeIme()
{
}
void WindowBaseEcoreX::ImeWindowReadyToRender()
{
}
void WindowBaseEcoreX::RequestMoveToServer()
{
}
void WindowBaseEcoreX::RequestResizeToServer(WindowResizeDirection direction)
{
}
void WindowBaseEcoreX::EnableFloatingMode(bool enable)
{
}
bool WindowBaseEcoreX::IsFloatingModeEnabled() const
{
return false;
}
void WindowBaseEcoreX::IncludeInputRegion(const Rect<int>& inputRegion)
{
}
void WindowBaseEcoreX::ExcludeInputRegion(const Rect<int>& inputRegion)
{
}
} // namespace Adaptor
} // namespace Internal
} // namespace Dali
|
/*
* Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
*/
#include <boost/statechart/custom_reaction.hpp>
#include <boost/statechart/event.hpp>
#include <boost/statechart/simple_state.hpp>
#include <boost/statechart/state.hpp>
#include <boost/statechart/state_machine.hpp>
#include <cmn/agent_cmn.h>
#include <route/route.h>
#include <oper/route_common.h>
#include <oper/vrf.h>
#include <oper/mirror_table.h>
#include <oper/path_preference.h>
namespace sc = boost::statechart;
namespace mpl = boost::mpl;
SandeshTraceBufferPtr PathPreferenceTraceBuf(
SandeshTraceBufferCreate("PathPreference", 5000));
struct EvStart : sc::event<EvStart> {
EvStart() {
}
static const char *Name() {
return "Start";
}
};
struct EvTrafficSeen : sc::event<EvTrafficSeen> {
EvTrafficSeen() {
}
static const char *Name() {
return "TrafficSeen";
}
};
struct EvWaitForTraffic : sc::event<EvWaitForTraffic> {
EvWaitForTraffic() {
}
static const char *Name() {
return "WaitForTraffic";
}
};
struct EvSeqChange : sc::event<EvSeqChange> {
EvSeqChange(uint32_t sequence) : sequence_(sequence) {
}
static const char *Name() {
return "SeqChange";
}
uint32_t sequence_;
};
//Path transition to ECMP
struct EvActiveActiveMode : sc::event<EvActiveActiveMode> {
EvActiveActiveMode() {
}
static const char *Name() {
return "EcmpRoute";
}
};
struct Init : public sc::state<Init, PathPreferenceSM> {
typedef mpl::list<
sc::custom_reaction<EvStart>
> reactions;
Init(my_context ctx) : my_base(ctx) {
PathPreferenceSM *state_machine = &context<PathPreferenceSM>();
state_machine->Log("INIT");
}
sc::result react(const EvStart &event) {
return transit<WaitForTraffic>();
}
};
struct WaitForTraffic : sc::state<WaitForTraffic, PathPreferenceSM> {
typedef mpl::list<
sc::custom_reaction<EvTrafficSeen>,
sc::custom_reaction<EvSeqChange>,
sc::custom_reaction<EvWaitForTraffic>,
sc::custom_reaction<EvActiveActiveMode>
> reactions;
WaitForTraffic(my_context ctx) : my_base(ctx) {
PathPreferenceSM *state_machine = &context<PathPreferenceSM>();
if (state_machine->wait_for_traffic() == false) {
state_machine->set_wait_for_traffic(true);
state_machine->set_preference(PathPreference::LOW);
state_machine->EnqueuePathChange();
state_machine->Log("Wait For Traffic");
}
}
sc::result react(const EvTrafficSeen &event) {
return transit<TrafficSeen>();
}
sc::result react(const EvSeqChange &event) {
PathPreferenceSM *state_machine = &context<PathPreferenceSM>();
state_machine->set_max_sequence(event.sequence_);
return discard_event();
}
sc::result react(const EvWaitForTraffic &event) {
return discard_event();
}
sc::result react(const EvActiveActiveMode &event) {
return transit<ActiveActiveState>();
}
};
struct TrafficSeen : sc::state<TrafficSeen, PathPreferenceSM> {
typedef mpl::list<
sc::custom_reaction<EvTrafficSeen>,
sc::custom_reaction<EvSeqChange>,
sc::custom_reaction<EvWaitForTraffic>,
sc::custom_reaction<EvActiveActiveMode>
> reactions;
TrafficSeen(my_context ctx) : my_base(ctx) {
PathPreferenceSM *state_machine = &context<PathPreferenceSM>();
//Enqueue a route change
if (state_machine->wait_for_traffic() == true) {
uint32_t seq = state_machine->max_sequence();
state_machine->set_wait_for_traffic(false);
seq++;
state_machine->set_max_sequence(seq);
state_machine->set_sequence(seq);
state_machine->set_preference(PathPreference::HIGH);
state_machine->EnqueuePathChange();
state_machine->Log("Traffic seen");
}
}
sc::result react(const EvTrafficSeen &event) {
return discard_event();
}
sc::result react(const EvWaitForTraffic &event) {
return transit<WaitForTraffic>();
}
sc::result react(const EvSeqChange &event) {
PathPreferenceSM *state_machine = &context<PathPreferenceSM>();
if (event.sequence_ > state_machine->sequence()) {
state_machine->set_max_sequence(event.sequence_);
return transit<WaitForTraffic>();
}
return discard_event();
}
sc::result react(const EvActiveActiveMode &event) {
return transit<ActiveActiveState>();
}
};
struct ActiveActiveState : sc::state<ActiveActiveState, PathPreferenceSM> {
typedef mpl::list<
sc::custom_reaction<EvTrafficSeen>,
sc::custom_reaction<EvSeqChange>,
sc::custom_reaction<EvWaitForTraffic>,
sc::custom_reaction<EvActiveActiveMode>
> reactions;
ActiveActiveState(my_context ctx) : my_base(ctx) {
PathPreferenceSM *state_machine = &context<PathPreferenceSM>();
//Enqueue a route change
if (state_machine->preference() == PathPreference::LOW) {
state_machine->set_wait_for_traffic(false);
uint32_t seq = 0;
state_machine->set_max_sequence(seq);
state_machine->set_sequence(seq);
state_machine->set_preference(PathPreference::HIGH);
state_machine->EnqueuePathChange();
state_machine->Log("Ecmp path");
}
}
sc::result react(const EvTrafficSeen &event) {
return discard_event();
}
sc::result react(const EvWaitForTraffic &event) {
return transit<WaitForTraffic>();
}
sc::result react(const EvSeqChange &event) {
PathPreferenceSM *state_machine = &context<PathPreferenceSM>();
state_machine->set_max_sequence(event.sequence_);
return transit<WaitForTraffic>();
}
sc::result react(const EvActiveActiveMode &event) {
return discard_event();
}
};
PathPreferenceSM::PathPreferenceSM(Agent *agent, const Peer *peer,
InetUnicastRouteEntry *rt): agent_(agent), peer_(peer), rt_(rt),
path_preference_(0, PathPreference::LOW, false, false), max_sequence_(0) {
initiate();
process_event(EvStart());
}
void PathPreferenceSM::Process() {
uint32_t max_sequence = 0;
const AgentPath *best_path = NULL;
const AgentPath *local_path = rt_->FindPath(peer_);
if (local_path->path_preference().ecmp() == true) {
path_preference_.set_ecmp(true);
//If a path is ecmp, just set the priority to HIGH
process_event(EvActiveActiveMode());
return;
}
//Check if BGP path is present
for (Route::PathList::iterator it = rt_->GetPathList().begin();
it != rt_->GetPathList().end(); ++it) {
const AgentPath *path =
static_cast<const AgentPath *>(it.operator->());
//Get best preference and sequence no from all BGP peer
if (max_sequence < path->sequence()) {
max_sequence = path->sequence();
best_path = path;
}
}
if (!best_path) {
return;
}
if (max_sequence > sequence()) {
process_event(EvSeqChange(max_sequence));
} else if (sequence() == max_sequence &&
best_path->nexthop(agent_) != local_path->nexthop(agent_)) {
//Control node chosen path and local path are different
//move to wait for traffic state
process_event(EvWaitForTraffic());
} else if (ecmp() == true) {
path_preference_.set_ecmp(local_path->path_preference().ecmp());
//Route transition from ECMP to non ECMP,
//move to wait for traffic state
process_event(EvWaitForTraffic());
}
}
void PathPreferenceSM::Log(std::string state) {
PATH_PREFERENCE_TRACE(rt_->vrf()->GetName(), rt_->GetAddressString(),
preference(), sequence(), state);
}
void PathPreferenceSM::EnqueuePathChange() {
std::string vrf_name = rt_->vrf()->GetName();
DBRequest req(DBRequest::DB_ENTRY_ADD_CHANGE);
InetUnicastRouteKey *rt_key =
new InetUnicastRouteKey(peer_, vrf_name, rt_->addr(), rt_->plen());
rt_key->sub_op_ = AgentKey::RESYNC;
req.key.reset(rt_key);
req.data.reset(new PathPreferenceData(path_preference_));
AgentRouteTable *table =
agent_->vrf_table()->GetInet4UnicastRouteTable(vrf_name);
if (table) {
table->Enqueue(&req);
}
}
bool PathPreferenceIntfState::RouteAddrList::operator<(
const RouteAddrList &rhs) const {
if (family_ != rhs.family_) {
return family_ < rhs.family_;
}
if (ip_ != rhs.ip_) {
return ip_ < rhs.ip_;
}
if (plen_ != rhs.plen_) {
return plen_ < rhs.plen_;
}
return vrf_name_ < rhs.vrf_name_;
}
bool PathPreferenceIntfState::RouteAddrList::operator==(
const RouteAddrList &rhs) const {
if ((family_ == rhs.family_) && (ip_ == rhs.ip_) &&
(plen_ == rhs.plen_) && (vrf_name_ == rhs.vrf_name_)) {
return true;
}
return false;
}
PathPreferenceIntfState::PathPreferenceIntfState(const VmInterface *intf):
intf_(intf) {
}
void PathPreferenceIntfState::Insert(RouteAddrList &rt, bool traffic_seen) {
std::set<RouteAddrList>::const_iterator it = dependent_rt_.find(rt);
if (it != dependent_rt_.end()) {
it->seen_ = true;
return;
}
rt.seen_ = true;
dependent_rt_.insert(rt);
}
void PathPreferenceIntfState::DeleteOldEntries() {
std::set<RouteAddrList>::const_iterator it = dependent_rt_.begin();
while (it != dependent_rt_.end()) {
std::set<RouteAddrList>::const_iterator prev_it = it++;
if (prev_it->seen_ == false) {
dependent_rt_.erase(prev_it);
continue;
}
prev_it->seen_ = false;
}
}
/* Updates the preference of routes dependent on given IP/prefix */
void PathPreferenceIntfState::UpdateDependentRoute(std::string vrf_name,
Ip4Address ip, uint32_t plen,
bool traffic_seen,
PathPreferenceModule
*path_preference_module) {
if (instance_ip_.vrf_name_ != vrf_name ||
instance_ip_.plen_ != plen ||
instance_ip_.ip_ != ip) {
return;
}
Agent *agent = path_preference_module->agent();
std::set<RouteAddrList>::const_iterator it = dependent_rt_.begin();
for(;it != dependent_rt_.end();it++) {
const VrfEntry *vrf =
agent->vrf_table()->FindVrfFromName(it->vrf_name_);
if (vrf == NULL) {
continue;
}
const PathPreferenceVrfState *state =
static_cast<const PathPreferenceVrfState *>(
vrf->GetState(agent->vrf_table(),
path_preference_module->vrf_id()));
if (!state) {
continue;
}
InetUnicastRouteKey rt_key(NULL, it->vrf_name_, it->ip_.to_v4(),
it->plen_);
const InetUnicastRouteEntry *rt =
static_cast<const InetUnicastRouteEntry *>(
vrf->GetInet4UnicastRouteTable()->FindActiveEntry(&rt_key));
if (!rt) {
continue;
}
const PathPreferenceState *cpath_preference =
static_cast<const PathPreferenceState *>(
rt->GetState(vrf->GetInet4UnicastRouteTable(), state->id()));
if (!cpath_preference) {
continue;
}
PathPreferenceState *path_preference =
const_cast<PathPreferenceState *>(cpath_preference);
PathPreferenceSM *path_preference_sm =
path_preference->GetSM(intf_->peer());
if (path_preference_sm && traffic_seen) {
EvTrafficSeen ev;
path_preference_sm->process_event(ev);
}
}
}
void PathPreferenceIntfState::Notify() {
//Copy over instance IP
if (intf_->vrf()) {
instance_ip_.vrf_name_ = intf_->vrf()->GetName();
}
instance_ip_.ip_ = intf_->ip_addr();
instance_ip_.plen_ = 32;
//Check if the native IP is active
bool traffic_seen = true;
if (intf_->WaitForTraffic() == true) {
traffic_seen = false;
}
//Go thru floating ip
const VmInterface::FloatingIpSet &fip_list = intf_->floating_ip_list().list_;
VmInterface::FloatingIpSet::const_iterator it = fip_list.begin();
for (;it != fip_list.end(); ++it) {
RouteAddrList rt;
rt.vrf_name_ = it->vrf_name_;
if (it->floating_ip_.is_v4()) {
rt.plen_ = 32;
rt.ip_ = it->floating_ip_.to_v4();
Insert(rt, traffic_seen);
}
}
//Go thru interface static routes
const VmInterface::ServiceVlanSet &service_vlan_set =
intf_->service_vlan_list().list_;
VmInterface::ServiceVlanSet::const_iterator service_vlan_it =
service_vlan_set.begin();
for (;service_vlan_it != service_vlan_set.end(); ++service_vlan_it) {
RouteAddrList rt;
rt.plen_ = service_vlan_it->plen_;
rt.ip_ = service_vlan_it->addr_;
rt.vrf_name_ = service_vlan_it->vrf_name_;
Insert(rt, traffic_seen);
}
//Go thru interface static routes
const VmInterface::StaticRouteSet &static_rt_list =
intf_->static_route_list().list_;
VmInterface::StaticRouteSet::const_iterator static_rt_it =
static_rt_list.begin();
for (;static_rt_it != static_rt_list.end(); ++static_rt_it) {
if (static_rt_it->addr_.is_v4()) {
RouteAddrList rt;
if (static_rt_it->vrf_ == "") {
continue;
}
rt.plen_ = static_rt_it->plen_;
rt.ip_ = static_rt_it->addr_;
rt.vrf_name_ = static_rt_it->vrf_;
Insert(rt, traffic_seen);
}
}
//Delete all old entries not present in new list
DeleteOldEntries();
}
PathPreferenceState::PathPreferenceState(Agent *agent,
InetUnicastRouteEntry *rt): agent_(agent), rt_(rt) {
}
PathPreferenceState::~PathPreferenceState() {
PeerPathPreferenceMap::iterator path_preference_it =
path_preference_peer_map_.begin();
while (path_preference_it != path_preference_peer_map_.end()) {
PeerPathPreferenceMap::iterator prev_it = path_preference_it++;
PathPreferenceSM *path_preference_sm = prev_it->second;
delete path_preference_sm;
path_preference_peer_map_.erase(prev_it);
}
}
void PathPreferenceState::Process() {
//Set all the path as not seen, eventually when path is seen
//flag would be set appropriatly
PeerPathPreferenceMap::iterator path_preference_it =
path_preference_peer_map_.begin();
while (path_preference_it != path_preference_peer_map_.end()) {
PathPreferenceSM *path_preference_sm = path_preference_it->second;
path_preference_sm->set_seen(false);
path_preference_it++;
}
for (Route::PathList::iterator it = rt_->GetPathList().begin();
it != rt_->GetPathList().end(); ++it) {
const AgentPath *path =
static_cast<const AgentPath *>(it.operator->());
if (path->peer() == NULL) {
continue;
}
if (path->peer()->GetType() != Peer::LOCAL_VM_PORT_PEER) {
continue;
}
PathPreferenceSM *path_preference_sm;
if (path_preference_peer_map_.find(path->peer()) ==
path_preference_peer_map_.end()) {
//Add new path
path_preference_sm =
new PathPreferenceSM(agent_, path->peer(), rt_);
path_preference_peer_map_.insert(
std::pair<const Peer *, PathPreferenceSM *>
(path->peer(), path_preference_sm));
} else {
path_preference_sm =
path_preference_peer_map_.find(path->peer())->second;
}
path_preference_sm->set_seen(true);
path_preference_sm->Process();
}
//Delete all path not seen, in latest path list
path_preference_it = path_preference_peer_map_.begin();
while (path_preference_it != path_preference_peer_map_.end()) {
PeerPathPreferenceMap::iterator prev_it = path_preference_it++;
PathPreferenceSM *path_preference_sm = prev_it->second;
if (path_preference_sm->seen() == false) {
delete path_preference_sm;
path_preference_peer_map_.erase(prev_it);
}
}
}
PathPreferenceSM* PathPreferenceState::GetSM(const Peer *peer) {
if (path_preference_peer_map_.find(peer) ==
path_preference_peer_map_.end()) {
return NULL;
}
return path_preference_peer_map_.find(peer)->second;
}
PathPreferenceVrfState::PathPreferenceVrfState(Agent *agent,
AgentRouteTable *table): agent_(agent), rt_table_(table),
id_(DBTableBase::kInvalidId), table_delete_ref_(this, table->deleter()),
deleted_(false) {
}
void PathPreferenceVrfState::Init() {
id_ = rt_table_->Register(boost::bind(&PathPreferenceVrfState::Notify, this,
_1, _2));
}
void PathPreferenceVrfState::Delete() {
deleted_ = true;
DBTableWalker *walker = agent_->db()->GetWalker();
walker->WalkTable(rt_table_, NULL,
boost::bind(&PathPreferenceVrfState::DeleteState,
this, _1, _2),
boost::bind(&PathPreferenceVrfState::Walkdone, this,
_1, this));
}
void PathPreferenceVrfState::Walkdone(DBTableBase *partition,
PathPreferenceVrfState *state) {
rt_table_->Unregister(id_);
table_delete_ref_.Reset(NULL);
delete state;
}
bool PathPreferenceVrfState::DeleteState(DBTablePartBase *partition,
DBEntryBase *e) {
PathPreferenceState *state =
static_cast<PathPreferenceState *>(e->GetState(rt_table_, id_));
if (state) {
e->ClearState(rt_table_, id_);
delete state;
}
return true;
}
void PathPreferenceVrfState::Notify(DBTablePartBase *partition,
DBEntryBase *e) {
PathPreferenceState *state =
static_cast<PathPreferenceState *>(e->GetState(rt_table_, id_));
if (e->IsDeleted()) {
if (state) {
e->ClearState(rt_table_, id_);
delete state;
}
return;
}
InetUnicastRouteEntry *rt =
static_cast<InetUnicastRouteEntry *>(e);
for (Route::PathList::iterator it = rt->GetPathList().begin();
it != rt->GetPathList().end(); ++it) {
const AgentPath *path =
static_cast<const AgentPath *>(it.operator->());
if (path->peer() == NULL) {
continue;
}
if (path->peer()->GetType() != Peer::LOCAL_VM_PORT_PEER) {
continue;
}
if (path->path_preference().static_preference() == true) {
return;
}
}
if (!state) {
state = new PathPreferenceState(agent_, rt);
}
state->Process();
e->SetState(rt_table_, id_, state);
}
PathPreferenceModule::PathPreferenceModule(Agent *agent):
agent_(agent), vrf_id_(DBTableBase::kInvalidId),
work_queue_(TaskScheduler::GetInstance()->GetTaskId("db::DBTable"), 0,
boost::bind(&PathPreferenceModule::DequeueEvent, this, _1)) {
}
bool PathPreferenceModule::DequeueEvent(PathPreferenceEventContainer event) {
const Interface *intf =
agent_->interface_table()->FindInterface(event.interface_index_);
if (intf == NULL || (intf->type() != Interface::VM_INTERFACE)) {
return true;
}
const VmInterface *vm_intf = static_cast<const VmInterface *>(intf);
const VrfEntry *vrf =
agent_->vrf_table()->FindVrfFromId(event.vrf_index_);
if (vrf == NULL) {
return true;
}
const PathPreferenceVrfState *state =
static_cast<const PathPreferenceVrfState *>(
vrf->GetState(agent_->vrf_table(), vrf_id_));
if (!state) {
return true;
}
InetUnicastRouteKey rt_key(NULL, vrf->GetName(), event.ip_, event.plen_);
const InetUnicastRouteEntry *rt =
static_cast<const InetUnicastRouteEntry *>(
vrf->GetInet4UnicastRouteTable()->FindActiveEntry(&rt_key));
if (!rt) {
return true;
}
const PathPreferenceState *cpath_preference =
static_cast<const PathPreferenceState *>(
rt->GetState(vrf->GetInet4UnicastRouteTable(), state->id()));
if (!cpath_preference) {
return true;
}
PathPreferenceState *path_preference =
const_cast<PathPreferenceState *>(cpath_preference);
PathPreferenceSM *path_preference_sm =
path_preference->GetSM(vm_intf->peer());
if (path_preference_sm) {
EvTrafficSeen ev;
path_preference_sm->process_event(ev);
}
//Enqueue event for same on all dependent routes of interface
const PathPreferenceIntfState *cintf_state =
static_cast<const PathPreferenceIntfState *>(
vm_intf->GetState(agent_->interface_table(), intf_id_));
PathPreferenceIntfState *intf_state =
const_cast<PathPreferenceIntfState *>(cintf_state);
/* Only events with IPv4 IP is enqueued now */
intf_state->UpdateDependentRoute(vrf->GetName(), event.ip_.to_v4(),
event.plen_, true, this);
return true;
}
void PathPreferenceModule::EnqueueTrafficSeen(Ip4Address ip, uint32_t plen,
uint32_t interface_index,
uint32_t vrf_index) {
const Interface *intf =
agent_->interface_table()->FindInterface(interface_index);
if (intf == NULL || (intf->type() != Interface::VM_INTERFACE)) {
return;
}
const VmInterface *vm_intf = static_cast<const VmInterface *>(intf);
//If the local preference is set by config, we dont identify Active
//node dynamically
if (vm_intf->local_preference() != VmInterface::INVALID) {
return;
}
const VrfEntry *vrf = agent_->vrf_table()->FindVrfFromId(vrf_index);
if (vrf == NULL) {
return;
}
InetUnicastRouteEntry *rt = vrf->GetUcRoute(ip);
if (!rt) {
return;
}
const AgentPath *path = rt->FindPath(vm_intf->peer());
if (!path|| path->path_preference().wait_for_traffic() == false) {
return;
}
PathPreferenceEventContainer event;
event.ip_ = rt->addr();
event.plen_ = rt->plen();
event.interface_index_ = interface_index;
event.vrf_index_ = vrf_index;
work_queue_.Enqueue(event);
}
void PathPreferenceModule::VrfNotify(DBTablePartBase *partition,
DBEntryBase *e) {
const VrfEntry *vrf = static_cast<const VrfEntry *>(e);
PathPreferenceVrfState *vrf_state =
static_cast<PathPreferenceVrfState *>(e->GetState(partition->parent(),
vrf_id_));
if (vrf->IsDeleted() && vrf_state) {
vrf_state->Delete();
e->ClearState(partition->parent(), vrf_id_);
return;
}
if (vrf_state) {
return;
}
vrf_state = new PathPreferenceVrfState(agent_,
vrf->GetInet4UnicastRouteTable());
vrf_state->Init();
e->SetState(partition->parent(), vrf_id_, vrf_state);
return;
}
void PathPreferenceModule::IntfNotify(DBTablePartBase *partition,
DBEntryBase *e) {
const Interface *intf = static_cast<const Interface *>(e);
if (intf->type() != Interface::VM_INTERFACE) {
return;
}
PathPreferenceIntfState *intf_state =
static_cast<PathPreferenceIntfState *>(e->GetState(partition->parent(),
intf_id_));
if (intf->IsDeleted()) {
if (intf_state) {
e->ClearState(partition->parent(), intf_id_);
delete intf_state;
}
return;
}
const VmInterface *vm_intf = static_cast<const VmInterface *>(intf);
if (!intf_state) {
intf_state = new PathPreferenceIntfState(vm_intf);
}
intf_state->Notify();
e->SetState(partition->parent(), intf_id_, intf_state);
}
void PathPreferenceModule::Init() {
vrf_id_ = agent_->vrf_table()->Register(
boost::bind(&PathPreferenceModule::VrfNotify, this, _1, _2));
intf_id_ = agent_->interface_table()->Register(
boost::bind(&PathPreferenceModule::IntfNotify, this, _1, _2));
}
void PathPreferenceModule::Shutdown() {
agent_->vrf_table()->Unregister(vrf_id_);
agent_->interface_table()->Unregister(intf_id_);
}
|
//==================================================================================================
/*!
@file
@copyright 2016 NumScale SAS
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
//==================================================================================================
#ifndef BOOST_SIMD_CONSTANT_DEFINITION_TWOTONMB_HPP_INCLUDED
#define BOOST_SIMD_CONSTANT_DEFINITION_TWOTONMB_HPP_INCLUDED
#include <boost/simd/config.hpp>
#include <boost/simd/detail/nsm.hpp>
#include <boost/simd/detail/dispatch.hpp>
#include <boost/simd/detail/constant_traits.hpp>
#include <boost/simd/detail/dispatch/function/make_callable.hpp>
#include <boost/simd/detail/dispatch/hierarchy/functions.hpp>
#include <boost/simd/detail/dispatch/as.hpp>
namespace boost { namespace simd
{
namespace tag
{
struct twotonmb_ : boost::dispatch::constant_value_<twotonmb_>
{
BOOST_DISPATCH_MAKE_CALLABLE(ext,twotonmb_,boost::dispatch::constant_value_<twotonmb_>);
BOOST_SIMD_REGISTER_CONSTANT(1, 0x4B000000UL, 0x4330000000000000ULL);
};
}
namespace ext
{
BOOST_DISPATCH_FUNCTION_DECLARATION(tag, twotonmb_)
}
namespace detail
{
BOOST_DISPATCH_CALLABLE_DEFINITION(tag::twotonmb_,twotonmb);
}
template<typename T> BOOST_FORCEINLINE auto Twotonmb()
BOOST_NOEXCEPT_DECLTYPE(detail::twotonmb( boost::dispatch::as_<T>{}))
{
return detail::twotonmb( boost::dispatch::as_<T>{} );
}
template<typename T> BOOST_FORCEINLINE
auto Twotonmb(boost::dispatch::as_<T> const&) BOOST_NOEXCEPT_DECLTYPE(Twotonmb<T>())
{
return Twotonmb<T>();
}
} }
#endif
|
#include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
int A, B;
cin >> A >> B;
int C = 2 * A + 100;
int r = (C - B);
cout << r << endl;
return 0;
}
|
// Copyright Carl Philipp Reh 2009 - 2018.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef FCPPT_MATH_VECTOR_STATIC_FWD_HPP_INCLUDED
#define FCPPT_MATH_VECTOR_STATIC_FWD_HPP_INCLUDED
#include <fcppt/math/size_type.hpp>
#include <fcppt/math/detail/static_storage_fwd.hpp>
#include <fcppt/math/vector/object_fwd.hpp>
namespace fcppt
{
namespace math
{
namespace vector
{
/**
\brief Typedef helper for static vectors
\ingroup fcpptmathvector
\tparam T The vector's <code>value_type</code>
See the introduction to fcppt::math::vector::object for more information on
static vectors (and on this class).
*/
template<
typename T,
fcppt::math::size_type N
>
using static_
=
fcppt::math::vector::object<
T,
N,
fcppt::math::detail::static_storage<
T,
N
>
>;
}
}
}
#endif
|
#ifndef MODELLOADER_H_
#define MODELLOADER_H_
#include <string>
#include <vector>
#include <memory>
#include <assimp/cimport.h>
#include <assimp/scene.h>
#include "IdManager.hpp"
namespace glmd = glm::detail;
namespace glr
{
namespace glw
{
class IOpenGlDevice;
class BoneData;
class BoneNode;
}
namespace models
{
class Model;
class AnimationSet;
class ModelData;
class MeshData;
class TextureData;
class MaterialData;
class ModelLoader
{
public:
ModelLoader(glw::IOpenGlDevice* openGlDevice);
virtual ~ModelLoader();
std::unique_ptr<Model> loadModel(const std::string& name, const std::string& filename, IdManager& idManager);
/**
* Loads model data from the file specified by filename.
*
* @param filename The file we want to load
* @param idManager
*
* @returns A vector of ModelData objects (as shared pointers). We do this so as not to have to copy the
* model data when we return from this method.
*/
std::unique_ptr<Model> loadModel(const std::string& filename, IdManager& idManager);
/**
*
*/
std::pair<std::vector< ModelData >, AnimationSet> loadModelData(const std::string& name, const std::string& filename);
private:
aiLogStream stream;
glw::IOpenGlDevice* openGlDevice_;
/**
* Will initialize a model with data given through the modelData object.
*
* @param modelData The data to use to initialize this model. Each element of the modelData vector corresponds to a new
* mesh/material/texture/animation set.
* @param animationSet The set of animations to be associated with the model.
* @param idManager
*/
std::unique_ptr<Model> generateModel(const std::string& name, const std::vector<ModelData>& modelData, const AnimationSet& animationSet, IdManager& idManager);
/**
* Load the vertex, normal, texture, and color data for the given mesh.
*
* Note: We only support models that have faces with 3 points (i.e. triangles)
*
* @param filename The file being loaded
* @param index The current index of the mesh being loaded
* @param mesh The AssImp mesh data structure to load data from. Must not be null.
* @param boneIndexMap A map associating an AssImp bone name with a bone index (of type uint32). Note that this variable is NOT const - this is
* only so that we can access elements in the map using the operator[] operator.
*/
MeshData loadMesh(const std::string& name, const std::string& filename, glmd::uint32 index, const aiMesh* mesh, std::map< std::string, glmd::uint32 >& boneIndexMap);
/**
* Load the texture filename for the given material.
*
* @param filename The file being loaded
* @param index The current index of the texture being loaded
* @param mesh The AssImp material data structure to load data from. Must not be null.
*/
TextureData loadTexture(const std::string& name, const std::string& filename, glmd::uint32 index, const aiMaterial* material);
/**
* Load the material data for the given material.
*
* @param filename The file being loaded
* @param index The current index of the material being loaded
* @param material The AssImp material data structure to load data from. Must not be null.
*/
MaterialData loadMaterial(const std::string& name, const std::string& filename, glmd::uint32 index, const aiMaterial* material);
/**
* Will load the bone data for the given AssImp mesh.
*
* @param filename The file being loaded
* @param index The current index of the mesh being loaded
* @param mesh The AssImp mesh data structure to load data from. Must not be null.
*/
glw::BoneData loadBones(const std::string& name, const std::string& filename, glmd::uint32 index, const aiMesh* mesh);
/**
* Will load the animations for the given scene.
*
* @param filename The file being loaded
* @param scene The AssImp scene data structure to load animation data from. Must not be null.
*/
AnimationSet loadAnimations(const std::string& name, const std::string& filename, const aiScene* scene);
/**
* Helper method - recursively loads bone node information from the AssImp node.
*
* @param node An AssImp Node.
*
* @return The BoneNode containing the bone information from the given AssImp node.
*/
glw::BoneNode loadBoneNode( const aiNode* node );
/**
* Helper method - converts an AssImp 4x4 matrix into a glm 4x4 matrix.
*
* @param m A 4x4 AssImp matrix
*
* @return A 4x4 glm matrix
*/
glm::mat4 convertAssImpMatrix(const aiMatrix4x4* m);
};
}
}
#endif /* MODELLOADER_H_ */
|
///////////////////////////////////////////////////////////////////////////////
// Name: src/common/strvararg.cpp
// Purpose: macros for implementing type-safe vararg passing of strings
// Author: Vaclav Slavik
// Created: 2007-02-19
// RCS-ID: $Id$
// Copyright: (c) 2007 REA Elektronik GmbH
// Licence: wxWindows licence
///////////////////////////////////////////////////////////////////////////////
// ============================================================================
// declarations
// ============================================================================
// ----------------------------------------------------------------------------
// headers
// ----------------------------------------------------------------------------
// for compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#include "wx/strvararg.h"
#include "wx/string.h"
#include "wx/crt.h"
#include "wx/private/wxprintf.h"
// ============================================================================
// implementation
// ============================================================================
// ----------------------------------------------------------------------------
// wxArgNormalizer<>
// ----------------------------------------------------------------------------
const wxStringCharType *wxArgNormalizerNative<const wxString&>::get() const
{
return m_value.wx_str();
}
const wxStringCharType *wxArgNormalizerNative<const wxCStrData&>::get() const
{
return m_value.AsInternal();
}
#if wxUSE_UNICODE_UTF8 && !wxUSE_UTF8_LOCALE_ONLY
wxArgNormalizerWchar<const wxString&>::wxArgNormalizerWchar(
const wxString& s,
const wxFormatString *fmt, unsigned index)
: wxArgNormalizerWithBuffer<wchar_t>(s.wc_str(), fmt, index)
{
}
wxArgNormalizerWchar<const wxCStrData&>::wxArgNormalizerWchar(
const wxCStrData& s,
const wxFormatString *fmt, unsigned index)
: wxArgNormalizerWithBuffer<wchar_t>(s.AsWCharBuf(), fmt, index)
{
}
#endif // wxUSE_UNICODE_UTF8 && !wxUSE_UTF8_LOCALE_ONLY
// ----------------------------------------------------------------------------
// wxArgNormalizedString
// ----------------------------------------------------------------------------
wxString wxArgNormalizedString::GetString() const
{
if ( !IsValid() )
return wxEmptyString;
#if wxUSE_UTF8_LOCALE_ONLY
return wxString(reinterpret_cast<const char*>(m_ptr));
#else
#if wxUSE_UNICODE_UTF8
if ( wxLocaleIsUtf8 )
return wxString(reinterpret_cast<const char*>(m_ptr));
else
#endif
return wxString(reinterpret_cast<const wxChar*>(m_ptr));
#endif // !wxUSE_UTF8_LOCALE_ONLY
}
wxArgNormalizedString::operator wxString() const
{
return GetString();
}
// ----------------------------------------------------------------------------
// wxFormatConverter: class doing the "%s" and "%c" normalization
// ----------------------------------------------------------------------------
/*
There are four problems with wxPrintf() etc. format strings:
1) The printf vararg macros convert all forms of strings into
wxStringCharType* representation. This may make the format string
incorrect: for example, if %ls was used together with a wchar_t*
variadic argument, this would no longer work, because the templates
would change wchar_t* argument to wxStringCharType* and %ls would now
be incorrect in e.g. UTF-8 build. We need make sure only one specifier
form is used.
2) To complicate matters further, the meaning of %s and %c is different
under Windows and on Unix. The Windows/MS convention is as follows:
In ANSI mode:
format specifier results in
-----------------------------------
%s, %hs, %hS char*
%ls, %S, %lS wchar_t*
In Unicode mode:
format specifier results in
-----------------------------------
%hs, %S, %hS char*
%s, %ls, %lS wchar_t*
(While on POSIX systems we have %C identical to %lc and %c always means
char (in any mode) while %lc always means wchar_t.)
In other words, we should _only_ use %s on Windows and %ls on Unix for
wxUSE_UNICODE_WCHAR build.
3) To make things even worse, we need two forms in UTF-8 build: one for
passing strings to ANSI functions under UTF-8 locales (this one should
use %s) and one for widechar functions used under non-UTF-8 locales
(this one should use %ls).
And, of course, the same should be done for %c as well.
wxScanf() family of functions is simpler, because we don't normalize their
variadic arguments and we only have to handle 2) above and only for widechar
versions.
*/
template<typename T>
class wxFormatConverterBase
{
public:
typedef T CharType;
wxFormatConverterBase()
{
m_fmtOrig = NULL;
m_fmtLast = NULL;
m_nCopied = 0;
}
wxScopedCharTypeBuffer<CharType> Convert(const CharType *format)
{
// this is reset to NULL if we modify the format string
m_fmtOrig = format;
while ( *format )
{
if ( CopyFmtChar(*format++) == wxT('%') )
{
// skip any flags
while ( IsFlagChar(*format) )
CopyFmtChar(*format++);
// and possible width
if ( *format == wxT('*') )
CopyFmtChar(*format++);
else
SkipDigits(&format);
// precision?
if ( *format == wxT('.') )
{
CopyFmtChar(*format++);
if ( *format == wxT('*') )
CopyFmtChar(*format++);
else
SkipDigits(&format);
}
// next we can have a size modifier
SizeModifier size;
switch ( *format )
{
case 'h':
size = Size_Short;
format++;
break;
case 'l':
// "ll" has a different meaning!
if ( format[1] != 'l' )
{
size = Size_Long;
format++;
break;
}
//else: fall through
default:
size = Size_Default;
}
CharType outConv = *format;
SizeModifier outSize = size;
// and finally we should have the type
switch ( *format )
{
case wxT('S'):
case wxT('s'):
// all strings were converted into the same form by
// wxArgNormalizer<T>, this form depends on the context
// in which the value is used (scanf/printf/wprintf):
HandleString(*format, size, outConv, outSize);
break;
case wxT('C'):
case wxT('c'):
HandleChar(*format, size, outConv, outSize);
break;
default:
// nothing special to do
break;
}
if ( outConv == *format && outSize == size ) // no change
{
if ( size != Size_Default )
CopyFmtChar(*(format - 1));
CopyFmtChar(*format);
}
else // something changed
{
switch ( outSize )
{
case Size_Long:
InsertFmtChar(wxT('l'));
break;
case Size_Short:
InsertFmtChar(wxT('h'));
break;
case Size_Default:
// nothing to do
break;
}
InsertFmtChar(outConv);
}
format++;
}
}
// notice that we only translated the string if m_fmtOrig == NULL (as
// set by CopyAllBefore()), otherwise we should simply use the original
// format
if ( m_fmtOrig )
{
return wxScopedCharTypeBuffer<CharType>::CreateNonOwned(m_fmtOrig);
}
else
{
// shrink converted format string to actual size (instead of
// over-sized allocation from CopyAllBefore()) and NUL-terminate
// it:
m_fmt.shrink(m_fmtLast - m_fmt.data());
return m_fmt;
}
}
virtual ~wxFormatConverterBase() {}
protected:
enum SizeModifier
{
Size_Default,
Size_Short,
Size_Long
};
// called to handle %S or %s; 'conv' is conversion specifier ('S' or 's'
// respectively), 'size' is the preceding size modifier; the new values of
// conversion and size specifiers must be written to outConv and outSize
virtual void HandleString(CharType conv, SizeModifier size,
CharType& outConv, SizeModifier& outSize) = 0;
// ditto for %C or %c
virtual void HandleChar(CharType conv, SizeModifier size,
CharType& outConv, SizeModifier& outSize) = 0;
private:
// copy another character to the translated format: this function does the
// copy if we are translating but doesn't do anything at all if we don't,
// so we don't create the translated format string at all unless we really
// need to (i.e. InsertFmtChar() is called)
CharType CopyFmtChar(CharType ch)
{
if ( !m_fmtOrig )
{
// we're translating, do copy
*(m_fmtLast++) = ch;
}
else
{
// simply increase the count which should be copied by
// CopyAllBefore() later if needed
m_nCopied++;
}
return ch;
}
// insert an extra character
void InsertFmtChar(CharType ch)
{
if ( m_fmtOrig )
{
// so far we haven't translated anything yet
CopyAllBefore();
}
*(m_fmtLast++) = ch;
}
void CopyAllBefore()
{
wxASSERT_MSG( m_fmtOrig && m_fmt.data() == NULL, "logic error" );
// the modified format string is guaranteed to be no longer than
// 3/2 of the original (worst case: the entire format string consists
// of "%s" repeated and is expanded to "%ls" on Unix), so we can
// allocate the buffer now and not worry about running out of space if
// we over-allocate a bit:
size_t fmtLen = wxStrlen(m_fmtOrig);
// worst case is of even length, so there's no rounding error in *3/2:
m_fmt.extend(fmtLen * 3 / 2);
if ( m_nCopied > 0 )
wxStrncpy(m_fmt.data(), m_fmtOrig, m_nCopied);
m_fmtLast = m_fmt.data() + m_nCopied;
// we won't need it any longer and resetting it also indicates that we
// modified the format
m_fmtOrig = NULL;
}
static bool IsFlagChar(CharType ch)
{
return ch == wxT('-') || ch == wxT('+') ||
ch == wxT('0') || ch == wxT(' ') || ch == wxT('#');
}
void SkipDigits(const CharType **ptpc)
{
while ( **ptpc >= wxT('0') && **ptpc <= wxT('9') )
CopyFmtChar(*(*ptpc)++);
}
// the translated format
wxCharTypeBuffer<CharType> m_fmt;
CharType *m_fmtLast;
// the original format
const CharType *m_fmtOrig;
// the number of characters already copied (i.e. already parsed, but left
// unmodified)
size_t m_nCopied;
};
#ifdef __WINDOWS__
// on Windows, we should use %s and %c regardless of the build:
class wxPrintfFormatConverterWchar : public wxFormatConverterBase<wchar_t>
{
virtual void HandleString(CharType WXUNUSED(conv),
SizeModifier WXUNUSED(size),
CharType& outConv, SizeModifier& outSize)
{
outConv = 's';
outSize = Size_Default;
}
virtual void HandleChar(CharType WXUNUSED(conv),
SizeModifier WXUNUSED(size),
CharType& outConv, SizeModifier& outSize)
{
outConv = 'c';
outSize = Size_Default;
}
};
#else // !__WINDOWS__
// on Unix, it's %s for ANSI functions and %ls for widechar:
#if !wxUSE_UTF8_LOCALE_ONLY
class wxPrintfFormatConverterWchar : public wxFormatConverterBase<wchar_t>
{
virtual void HandleString(CharType WXUNUSED(conv),
SizeModifier WXUNUSED(size),
CharType& outConv, SizeModifier& outSize)
{
outConv = 's';
outSize = Size_Long;
}
virtual void HandleChar(CharType WXUNUSED(conv),
SizeModifier WXUNUSED(size),
CharType& outConv, SizeModifier& outSize)
{
outConv = 'c';
outSize = Size_Long;
}
};
#endif // !wxUSE_UTF8_LOCALE_ONLY
#if wxUSE_UNICODE_UTF8
class wxPrintfFormatConverterUtf8 : public wxFormatConverterBase<char>
{
virtual void HandleString(CharType WXUNUSED(conv),
SizeModifier WXUNUSED(size),
CharType& outConv, SizeModifier& outSize)
{
outConv = 's';
outSize = Size_Default;
}
virtual void HandleChar(CharType WXUNUSED(conv),
SizeModifier WXUNUSED(size),
CharType& outConv, SizeModifier& outSize)
{
// chars are represented using wchar_t in both builds, so this is
// the same as above
outConv = 'c';
outSize = Size_Long;
}
};
#endif // wxUSE_UNICODE_UTF8
#endif // __WINDOWS__/!__WINDOWS__
#if !wxUSE_UNICODE // FIXME-UTF8: remove
class wxPrintfFormatConverterANSI : public wxFormatConverterBase<char>
{
virtual void HandleString(CharType WXUNUSED(conv),
SizeModifier WXUNUSED(size),
CharType& outConv, SizeModifier& outSize)
{
outConv = 's';
outSize = Size_Default;
}
virtual void HandleChar(CharType WXUNUSED(conv),
SizeModifier WXUNUSED(size),
CharType& outConv, SizeModifier& outSize)
{
outConv = 'c';
outSize = Size_Default;
}
};
#endif // ANSI
#ifndef __WINDOWS__
/*
wxScanf() format translation is different, we need to translate %s to %ls
and %c to %lc on Unix (but not Windows and for widechar functions only!).
So to use native functions in order to get our semantics we must do the
following translations in Unicode mode:
wxWidgets specifier POSIX specifier
----------------------------------------
%hc, %C, %hC %c
%c %lc
*/
class wxScanfFormatConverterWchar : public wxFormatConverterBase<wchar_t>
{
virtual void HandleString(CharType conv, SizeModifier size,
CharType& outConv, SizeModifier& outSize)
{
outConv = 's';
outSize = GetOutSize(conv == 'S', size);
}
virtual void HandleChar(CharType conv, SizeModifier size,
CharType& outConv, SizeModifier& outSize)
{
outConv = 'c';
outSize = GetOutSize(conv == 'C', size);
}
SizeModifier GetOutSize(bool convIsUpper, SizeModifier size)
{
// %S and %hS -> %s and %lS -> %ls
if ( convIsUpper )
{
if ( size == Size_Long )
return Size_Long;
else
return Size_Default;
}
else // %s or %c
{
if ( size == Size_Default )
return Size_Long;
else
return size;
}
}
};
const wxScopedWCharBuffer wxScanfConvertFormatW(const wchar_t *format)
{
return wxScanfFormatConverterWchar().Convert(format);
}
#endif // !__WINDOWS__
// ----------------------------------------------------------------------------
// wxFormatString
// ----------------------------------------------------------------------------
#if !wxUSE_UNICODE_WCHAR
const char* wxFormatString::InputAsChar()
{
if ( m_char )
return m_char.data();
// in ANSI build, wx_str() returns char*, in UTF-8 build, this function
// is only called under UTF-8 locales, so we should return UTF-8 string,
// which is, again, what wx_str() returns:
if ( m_str )
return m_str->wx_str();
// ditto wxCStrData:
if ( m_cstr )
return m_cstr->AsInternal();
// the last case is that wide string was passed in: in that case, we need
// to convert it:
wxASSERT( m_wchar );
m_char = wxConvLibc.cWC2MB(m_wchar.data());
return m_char.data();
}
const char* wxFormatString::AsChar()
{
if ( !m_convertedChar )
#if !wxUSE_UNICODE // FIXME-UTF8: remove this
m_convertedChar = wxPrintfFormatConverterANSI().Convert(InputAsChar());
#else
m_convertedChar = wxPrintfFormatConverterUtf8().Convert(InputAsChar());
#endif
return m_convertedChar.data();
}
#endif // !wxUSE_UNICODE_WCHAR
#if wxUSE_UNICODE && !wxUSE_UTF8_LOCALE_ONLY
const wchar_t* wxFormatString::InputAsWChar()
{
if ( m_wchar )
return m_wchar.data();
#if wxUSE_UNICODE_WCHAR
if ( m_str )
return m_str->wc_str();
if ( m_cstr )
return m_cstr->AsInternal();
#else // wxUSE_UNICODE_UTF8
if ( m_str )
{
m_wchar = m_str->wc_str();
return m_wchar.data();
}
if ( m_cstr )
{
m_wchar = m_cstr->AsWCharBuf();
return m_wchar.data();
}
#endif // wxUSE_UNICODE_WCHAR/UTF8
// the last case is that narrow string was passed in: in that case, we need
// to convert it:
wxASSERT( m_char );
m_wchar = wxConvLibc.cMB2WC(m_char.data());
return m_wchar.data();
}
const wchar_t* wxFormatString::AsWChar()
{
if ( !m_convertedWChar )
m_convertedWChar = wxPrintfFormatConverterWchar().Convert(InputAsWChar());
return m_convertedWChar.data();
}
#endif // wxUSE_UNICODE && !wxUSE_UTF8_LOCALE_ONLY
wxString wxFormatString::InputAsString() const
{
if ( m_str )
return *m_str;
if ( m_cstr )
return m_cstr->AsString();
if ( m_wchar )
return wxString(m_wchar);
if ( m_char )
return wxString(m_char);
wxFAIL_MSG( "invalid wxFormatString - not initialized?" );
return wxString();
}
// ----------------------------------------------------------------------------
// wxFormatString::GetArgumentType()
// ----------------------------------------------------------------------------
namespace
{
template<typename CharType>
wxFormatString::ArgumentType DoGetArgumentType(const CharType *format,
unsigned n)
{
wxCHECK_MSG( format, wxFormatString::Arg_Unknown,
"empty format string not allowed here" );
wxPrintfConvSpecParser<CharType> parser(format);
wxCHECK_MSG( n <= parser.nargs, wxFormatString::Arg_Unknown,
"more arguments than format string specifiers?" );
wxCHECK_MSG( parser.pspec[n-1] != NULL, wxFormatString::Arg_Unknown,
"requested argument not found - invalid format string?" );
switch ( parser.pspec[n-1]->m_type )
{
case wxPAT_CHAR:
case wxPAT_WCHAR:
return wxFormatString::Arg_Char;
case wxPAT_PCHAR:
case wxPAT_PWCHAR:
return wxFormatString::Arg_String;
case wxPAT_INT:
return wxFormatString::Arg_Int;
case wxPAT_LONGINT:
return wxFormatString::Arg_LongInt;
#ifdef wxLongLong_t
case wxPAT_LONGLONGINT:
return wxFormatString::Arg_LongLongInt;
#endif
case wxPAT_SIZET:
return wxFormatString::Arg_Size_t;
case wxPAT_DOUBLE:
return wxFormatString::Arg_Double;
case wxPAT_LONGDOUBLE:
return wxFormatString::Arg_LongDouble;
case wxPAT_POINTER:
return wxFormatString::Arg_Pointer;
case wxPAT_NINT:
return wxFormatString::Arg_IntPtr;
case wxPAT_NSHORTINT:
return wxFormatString::Arg_ShortIntPtr;
case wxPAT_NLONGINT:
return wxFormatString::Arg_LongIntPtr;
case wxPAT_STAR:
// "*" requires argument of type int
return wxFormatString::Arg_Int;
case wxPAT_INVALID:
// (handled after the switch statement)
break;
}
// silence warning
wxFAIL_MSG( "unexpected argument type" );
return wxFormatString::Arg_Unknown;
}
} // anonymous namespace
wxFormatString::ArgumentType wxFormatString::GetArgumentType(unsigned n) const
{
if ( m_char )
return DoGetArgumentType(m_char.data(), n);
else if ( m_wchar )
return DoGetArgumentType(m_wchar.data(), n);
else if ( m_str )
return DoGetArgumentType(m_str->wx_str(), n);
else if ( m_cstr )
return DoGetArgumentType(m_cstr->AsInternal(), n);
wxFAIL_MSG( "unreachable code" );
return Arg_Unknown;
}
|
#include <stdlib.h>
#include "mapreduce/functions/map/WordTokenizer.h"
WordTokenizer::WordTokenizer() {
stopCharacters.push_back(' ');
stopCharacters.push_back('"');
stopCharacters.push_back('.');
stopCharacters.push_back(',');
stopCharacters.push_back('/');
stopCharacters.push_back('/');
stopCharacters.push_back('(');
stopCharacters.push_back(')');
stopCharacters.push_back('?');
stopCharacters.push_back(';');
}
void WordTokenizer::loadSentence(
const uint8_t* _sentence, uint32_t _sentenceLength) {
sentence = _sentence;
sentenceLength = _sentenceLength;
wordStartIndex = 0;
sentenceIndex = 0;
}
bool WordTokenizer::nextWord(const uint8_t*& word, uint32_t& wordLength) {
word = NULL;
wordLength = 0;
while (sentenceIndex < sentenceLength && word == NULL) {
uint8_t currentCharacter = sentence[sentenceIndex];
bool stopCharacter = false;
if (sentenceIndex < sentenceLength - 1 && currentCharacter == '\\' &&
sentence[sentenceIndex + 1] == 'n') {
// Break on '\n'
stopCharacter = true;
}
for (std::vector<uint8_t>::iterator iter = stopCharacters.begin();
!stopCharacter && iter != stopCharacters.end(); iter++) {
if (currentCharacter == *iter) {
stopCharacter = true;
}
}
if (stopCharacter) {
if (wordStartIndex == sentenceIndex) {
// Ignore multiple contiguous stop characters
wordStartIndex++;
} else {
word = sentence + wordStartIndex;
wordLength = sentenceIndex - wordStartIndex;
wordStartIndex = sentenceIndex + 1;
}
}
sentenceIndex++;
}
if (word == NULL && wordStartIndex < sentenceLength) {
// Count a word at the end of the line without spaces behind it
word = sentence + wordStartIndex;
wordLength = sentenceLength - wordStartIndex;
wordStartIndex = sentenceIndex + 1;
}
return (word != NULL);
}
|
/*************************************************************************/
/* script_text_editor.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
/* */
/* 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 "script_text_editor.h"
#include "core/os/keyboard.h"
#include "editor/editor_node.h"
#include "editor/editor_settings.h"
#include "editor/script_editor_debugger.h"
void ConnectionInfoDialog::ok_pressed() {
}
void ConnectionInfoDialog::popup_connections(String p_method, Vector<Node *> p_nodes) {
method->set_text(p_method);
tree->clear();
TreeItem *root = tree->create_item();
for (int i = 0; i < p_nodes.size(); i++) {
List<Connection> all_connections;
p_nodes[i]->get_signals_connected_to_this(&all_connections);
for (List<Connection>::Element *E = all_connections.front(); E; E = E->next()) {
Connection connection = E->get();
if (connection.method != p_method) {
continue;
}
TreeItem *node_item = tree->create_item(root);
node_item->set_text(0, Object::cast_to<Node>(connection.source)->get_name());
node_item->set_icon(0, EditorNode::get_singleton()->get_object_icon(connection.source, "Node"));
node_item->set_selectable(0, false);
node_item->set_editable(0, false);
node_item->set_text(1, connection.signal);
node_item->set_icon(1, get_parent_control()->get_icon("Slot", "EditorIcons"));
node_item->set_selectable(1, false);
node_item->set_editable(1, false);
node_item->set_text(2, Object::cast_to<Node>(connection.target)->get_name());
node_item->set_icon(2, EditorNode::get_singleton()->get_object_icon(connection.target, "Node"));
node_item->set_selectable(2, false);
node_item->set_editable(2, false);
}
}
popup_centered(Size2(400, 300) * EDSCALE);
}
ConnectionInfoDialog::ConnectionInfoDialog() {
set_title(TTR("Connections to method:"));
VBoxContainer *vbc = memnew(VBoxContainer);
vbc->set_anchor_and_margin(MARGIN_LEFT, ANCHOR_BEGIN, 8 * EDSCALE);
vbc->set_anchor_and_margin(MARGIN_TOP, ANCHOR_BEGIN, 8 * EDSCALE);
vbc->set_anchor_and_margin(MARGIN_RIGHT, ANCHOR_END, -8 * EDSCALE);
vbc->set_anchor_and_margin(MARGIN_BOTTOM, ANCHOR_END, -8 * EDSCALE);
add_child(vbc);
method = memnew(Label);
method->set_align(Label::ALIGN_CENTER);
vbc->add_child(method);
tree = memnew(Tree);
tree->set_columns(3);
tree->set_hide_root(true);
tree->set_column_titles_visible(true);
tree->set_column_title(0, TTR("Source"));
tree->set_column_title(1, TTR("Signal"));
tree->set_column_title(2, TTR("Target"));
vbc->add_child(tree);
tree->set_v_size_flags(SIZE_EXPAND_FILL);
tree->set_allow_rmb_select(true);
}
////////////////////////////////////////////////////////////////////////////////
Vector<String> ScriptTextEditor::get_functions() {
String errortxt;
int line = -1, col;
TextEdit *te = code_editor->get_text_edit();
String text = te->get_text();
List<String> fnc;
if (script->get_language()->validate(text, line, col, errortxt, script->get_path(), &fnc)) {
//if valid rewrite functions to latest
functions.clear();
for (List<String>::Element *E = fnc.front(); E; E = E->next()) {
functions.push_back(E->get());
}
}
return functions;
}
void ScriptTextEditor::apply_code() {
if (script.is_null())
return;
script->set_source_code(code_editor->get_text_edit()->get_text());
script->update_exports();
_update_member_keywords();
}
RES ScriptTextEditor::get_edited_resource() const {
return script;
}
void ScriptTextEditor::set_edited_resource(const RES &p_res) {
ERR_FAIL_COND(!script.is_null());
script = p_res;
_set_theme_for_script();
code_editor->get_text_edit()->set_text(script->get_source_code());
code_editor->get_text_edit()->clear_undo_history();
code_editor->get_text_edit()->tag_saved_version();
emit_signal("name_changed");
code_editor->update_line_and_column();
_validate_script();
}
void ScriptTextEditor::_update_member_keywords() {
member_keywords.clear();
code_editor->get_text_edit()->clear_member_keywords();
Color member_variable_color = EDITOR_GET("text_editor/highlighting/member_variable_color");
StringName instance_base = script->get_instance_base_type();
if (instance_base == StringName())
return;
List<PropertyInfo> plist;
ClassDB::get_property_list(instance_base, &plist);
for (List<PropertyInfo>::Element *E = plist.front(); E; E = E->next()) {
String name = E->get().name;
if (E->get().usage & PROPERTY_USAGE_CATEGORY || E->get().usage & PROPERTY_USAGE_GROUP)
continue;
if (name.find("/") != -1)
continue;
code_editor->get_text_edit()->add_member_keyword(name, member_variable_color);
}
List<String> clist;
ClassDB::get_integer_constant_list(instance_base, &clist);
for (List<String>::Element *E = clist.front(); E; E = E->next()) {
code_editor->get_text_edit()->add_member_keyword(E->get(), member_variable_color);
}
}
void ScriptTextEditor::_load_theme_settings() {
TextEdit *text_edit = code_editor->get_text_edit();
text_edit->clear_colors();
Color background_color = EDITOR_GET("text_editor/highlighting/background_color");
Color completion_background_color = EDITOR_GET("text_editor/highlighting/completion_background_color");
Color completion_selected_color = EDITOR_GET("text_editor/highlighting/completion_selected_color");
Color completion_existing_color = EDITOR_GET("text_editor/highlighting/completion_existing_color");
Color completion_scroll_color = EDITOR_GET("text_editor/highlighting/completion_scroll_color");
Color completion_font_color = EDITOR_GET("text_editor/highlighting/completion_font_color");
Color text_color = EDITOR_GET("text_editor/highlighting/text_color");
Color line_number_color = EDITOR_GET("text_editor/highlighting/line_number_color");
Color safe_line_number_color = EDITOR_GET("text_editor/highlighting/safe_line_number_color");
Color caret_color = EDITOR_GET("text_editor/highlighting/caret_color");
Color caret_background_color = EDITOR_GET("text_editor/highlighting/caret_background_color");
Color text_selected_color = EDITOR_GET("text_editor/highlighting/text_selected_color");
Color selection_color = EDITOR_GET("text_editor/highlighting/selection_color");
Color brace_mismatch_color = EDITOR_GET("text_editor/highlighting/brace_mismatch_color");
Color current_line_color = EDITOR_GET("text_editor/highlighting/current_line_color");
Color line_length_guideline_color = EDITOR_GET("text_editor/highlighting/line_length_guideline_color");
Color word_highlighted_color = EDITOR_GET("text_editor/highlighting/word_highlighted_color");
Color number_color = EDITOR_GET("text_editor/highlighting/number_color");
Color function_color = EDITOR_GET("text_editor/highlighting/function_color");
Color member_variable_color = EDITOR_GET("text_editor/highlighting/member_variable_color");
Color mark_color = EDITOR_GET("text_editor/highlighting/mark_color");
Color bookmark_color = EDITOR_GET("text_editor/highlighting/bookmark_color");
Color breakpoint_color = EDITOR_GET("text_editor/highlighting/breakpoint_color");
Color executing_line_color = EDITOR_GET("text_editor/highlighting/executing_line_color");
Color code_folding_color = EDITOR_GET("text_editor/highlighting/code_folding_color");
Color search_result_color = EDITOR_GET("text_editor/highlighting/search_result_color");
Color search_result_border_color = EDITOR_GET("text_editor/highlighting/search_result_border_color");
Color symbol_color = EDITOR_GET("text_editor/highlighting/symbol_color");
Color keyword_color = EDITOR_GET("text_editor/highlighting/keyword_color");
Color basetype_color = EDITOR_GET("text_editor/highlighting/base_type_color");
Color type_color = EDITOR_GET("text_editor/highlighting/engine_type_color");
Color comment_color = EDITOR_GET("text_editor/highlighting/comment_color");
Color string_color = EDITOR_GET("text_editor/highlighting/string_color");
text_edit->add_color_override("background_color", background_color);
text_edit->add_color_override("completion_background_color", completion_background_color);
text_edit->add_color_override("completion_selected_color", completion_selected_color);
text_edit->add_color_override("completion_existing_color", completion_existing_color);
text_edit->add_color_override("completion_scroll_color", completion_scroll_color);
text_edit->add_color_override("completion_font_color", completion_font_color);
text_edit->add_color_override("font_color", text_color);
text_edit->add_color_override("line_number_color", line_number_color);
text_edit->add_color_override("safe_line_number_color", safe_line_number_color);
text_edit->add_color_override("caret_color", caret_color);
text_edit->add_color_override("caret_background_color", caret_background_color);
text_edit->add_color_override("font_color_selected", text_selected_color);
text_edit->add_color_override("selection_color", selection_color);
text_edit->add_color_override("brace_mismatch_color", brace_mismatch_color);
text_edit->add_color_override("current_line_color", current_line_color);
text_edit->add_color_override("line_length_guideline_color", line_length_guideline_color);
text_edit->add_color_override("word_highlighted_color", word_highlighted_color);
text_edit->add_color_override("number_color", number_color);
text_edit->add_color_override("function_color", function_color);
text_edit->add_color_override("member_variable_color", member_variable_color);
text_edit->add_color_override("bookmark_color", bookmark_color);
text_edit->add_color_override("breakpoint_color", breakpoint_color);
text_edit->add_color_override("executing_line_color", executing_line_color);
text_edit->add_color_override("mark_color", mark_color);
text_edit->add_color_override("code_folding_color", code_folding_color);
text_edit->add_color_override("search_result_color", search_result_color);
text_edit->add_color_override("search_result_border_color", search_result_border_color);
text_edit->add_color_override("symbol_color", symbol_color);
text_edit->add_constant_override("line_spacing", EDITOR_DEF("text_editor/theme/line_spacing", 6));
colors_cache.symbol_color = symbol_color;
colors_cache.keyword_color = keyword_color;
colors_cache.basetype_color = basetype_color;
colors_cache.type_color = type_color;
colors_cache.comment_color = comment_color;
colors_cache.string_color = string_color;
theme_loaded = true;
if (!script.is_null())
_set_theme_for_script();
}
void ScriptTextEditor::_set_theme_for_script() {
if (!theme_loaded)
return;
TextEdit *text_edit = code_editor->get_text_edit();
List<String> keywords;
script->get_language()->get_reserved_words(&keywords);
for (List<String>::Element *E = keywords.front(); E; E = E->next()) {
text_edit->add_keyword_color(E->get(), colors_cache.keyword_color);
}
//colorize core types
const Color basetype_color = colors_cache.basetype_color;
text_edit->add_keyword_color("String", basetype_color);
text_edit->add_keyword_color("Vector2", basetype_color);
text_edit->add_keyword_color("Rect2", basetype_color);
text_edit->add_keyword_color("Transform2D", basetype_color);
text_edit->add_keyword_color("Vector3", basetype_color);
text_edit->add_keyword_color("AABB", basetype_color);
text_edit->add_keyword_color("Basis", basetype_color);
text_edit->add_keyword_color("Plane", basetype_color);
text_edit->add_keyword_color("Transform", basetype_color);
text_edit->add_keyword_color("Quat", basetype_color);
text_edit->add_keyword_color("Color", basetype_color);
text_edit->add_keyword_color("Object", basetype_color);
text_edit->add_keyword_color("NodePath", basetype_color);
text_edit->add_keyword_color("RID", basetype_color);
text_edit->add_keyword_color("Dictionary", basetype_color);
text_edit->add_keyword_color("Array", basetype_color);
text_edit->add_keyword_color("PoolByteArray", basetype_color);
text_edit->add_keyword_color("PoolIntArray", basetype_color);
text_edit->add_keyword_color("PoolRealArray", basetype_color);
text_edit->add_keyword_color("PoolStringArray", basetype_color);
text_edit->add_keyword_color("PoolVector2Array", basetype_color);
text_edit->add_keyword_color("PoolVector3Array", basetype_color);
text_edit->add_keyword_color("PoolColorArray", basetype_color);
//colorize engine types
List<StringName> types;
ClassDB::get_class_list(&types);
for (List<StringName>::Element *E = types.front(); E; E = E->next()) {
String n = E->get();
if (n.begins_with("_"))
n = n.substr(1, n.length());
text_edit->add_keyword_color(n, colors_cache.type_color);
}
_update_member_keywords();
//colorize comments
List<String> comments;
script->get_language()->get_comment_delimiters(&comments);
for (List<String>::Element *E = comments.front(); E; E = E->next()) {
String comment = E->get();
String beg = comment.get_slice(" ", 0);
String end = comment.get_slice_count(" ") > 1 ? comment.get_slice(" ", 1) : String();
text_edit->add_color_region(beg, end, colors_cache.comment_color, end == "");
}
//colorize strings
List<String> strings;
script->get_language()->get_string_delimiters(&strings);
for (List<String>::Element *E = strings.front(); E; E = E->next()) {
String string = E->get();
String beg = string.get_slice(" ", 0);
String end = string.get_slice_count(" ") > 1 ? string.get_slice(" ", 1) : String();
text_edit->add_color_region(beg, end, colors_cache.string_color, end == "");
}
}
void ScriptTextEditor::_show_warnings_panel(bool p_show) {
warnings_panel->set_visible(p_show);
}
void ScriptTextEditor::_error_pressed() {
code_editor->goto_error();
}
void ScriptTextEditor::_warning_clicked(Variant p_line) {
if (p_line.get_type() == Variant::INT) {
code_editor->get_text_edit()->cursor_set_line(p_line.operator int64_t());
} else if (p_line.get_type() == Variant::DICTIONARY) {
Dictionary meta = p_line.operator Dictionary();
code_editor->get_text_edit()->insert_at("# warning-ignore:" + meta["code"].operator String(), meta["line"].operator int64_t() - 1);
_validate_script();
}
}
void ScriptTextEditor::reload_text() {
ERR_FAIL_COND(script.is_null());
TextEdit *te = code_editor->get_text_edit();
int column = te->cursor_get_column();
int row = te->cursor_get_line();
int h = te->get_h_scroll();
int v = te->get_v_scroll();
te->set_text(script->get_source_code());
te->cursor_set_line(row);
te->cursor_set_column(column);
te->set_h_scroll(h);
te->set_v_scroll(v);
te->tag_saved_version();
code_editor->update_line_and_column();
}
void ScriptTextEditor::_notification(int p_what) {
switch (p_what) {
case NOTIFICATION_READY:
_load_theme_settings();
break;
}
}
void ScriptTextEditor::add_callback(const String &p_function, PoolStringArray p_args) {
String code = code_editor->get_text_edit()->get_text();
int pos = script->get_language()->find_function(p_function, code);
if (pos == -1) {
//does not exist
code_editor->get_text_edit()->deselect();
pos = code_editor->get_text_edit()->get_line_count() + 2;
String func = script->get_language()->make_function("", p_function, p_args);
//code=code+func;
code_editor->get_text_edit()->cursor_set_line(pos + 1);
code_editor->get_text_edit()->cursor_set_column(1000000); //none shall be that big
code_editor->get_text_edit()->insert_text_at_cursor("\n\n" + func);
}
code_editor->get_text_edit()->cursor_set_line(pos);
code_editor->get_text_edit()->cursor_set_column(1);
}
bool ScriptTextEditor::show_members_overview() {
return true;
}
void ScriptTextEditor::update_settings() {
code_editor->update_editor_settings();
}
bool ScriptTextEditor::is_unsaved() {
return code_editor->get_text_edit()->get_version() != code_editor->get_text_edit()->get_saved_version();
}
Variant ScriptTextEditor::get_edit_state() {
return code_editor->get_edit_state();
}
void ScriptTextEditor::set_edit_state(const Variant &p_state) {
code_editor->set_edit_state(p_state);
Dictionary state = p_state;
if (state.has("syntax_highlighter")) {
int idx = highlighter_menu->get_item_idx_from_text(state["syntax_highlighter"]);
if (idx >= 0) {
_change_syntax_highlighter(idx);
}
}
}
void ScriptTextEditor::_convert_case(CodeTextEditor::CaseStyle p_case) {
code_editor->convert_case(p_case);
}
void ScriptTextEditor::trim_trailing_whitespace() {
code_editor->trim_trailing_whitespace();
}
void ScriptTextEditor::insert_final_newline() {
code_editor->insert_final_newline();
}
void ScriptTextEditor::convert_indent_to_spaces() {
code_editor->convert_indent_to_spaces();
}
void ScriptTextEditor::convert_indent_to_tabs() {
code_editor->convert_indent_to_tabs();
}
void ScriptTextEditor::tag_saved_version() {
code_editor->get_text_edit()->tag_saved_version();
}
void ScriptTextEditor::goto_line(int p_line, bool p_with_error) {
code_editor->goto_line(p_line);
}
void ScriptTextEditor::goto_line_selection(int p_line, int p_begin, int p_end) {
code_editor->goto_line_selection(p_line, p_begin, p_end);
}
void ScriptTextEditor::goto_line_centered(int p_line) {
code_editor->goto_line_centered(p_line);
}
void ScriptTextEditor::set_executing_line(int p_line) {
code_editor->set_executing_line(p_line);
}
void ScriptTextEditor::clear_executing_line() {
code_editor->clear_executing_line();
}
void ScriptTextEditor::ensure_focus() {
code_editor->get_text_edit()->grab_focus();
}
String ScriptTextEditor::get_name() {
String name;
if (script->get_path().find("local://") == -1 && script->get_path().find("::") == -1) {
name = script->get_path().get_file();
if (is_unsaved()) {
name += "(*)";
}
} else if (script->get_name() != "")
name = script->get_name();
else
name = script->get_class() + "(" + itos(script->get_instance_id()) + ")";
return name;
}
Ref<Texture> ScriptTextEditor::get_icon() {
if (get_parent_control() && get_parent_control()->has_icon(script->get_class(), "EditorIcons")) {
return get_parent_control()->get_icon(script->get_class(), "EditorIcons");
}
return Ref<Texture>();
}
void ScriptTextEditor::_validate_script() {
String errortxt;
int line = -1, col;
TextEdit *te = code_editor->get_text_edit();
String text = te->get_text();
List<String> fnc;
Set<int> safe_lines;
List<ScriptLanguage::Warning> warnings;
if (!script->get_language()->validate(text, line, col, errortxt, script->get_path(), &fnc, &warnings, &safe_lines)) {
String error_text = "error(" + itos(line) + "," + itos(col) + "): " + errortxt;
code_editor->set_error(error_text);
code_editor->set_error_pos(line - 1, col - 1);
} else {
code_editor->set_error("");
line = -1;
if (!script->is_tool()) {
script->set_source_code(text);
script->update_exports();
_update_member_keywords();
}
functions.clear();
for (List<String>::Element *E = fnc.front(); E; E = E->next()) {
functions.push_back(E->get());
}
}
_update_connected_methods();
int warning_nb = warnings.size();
warnings_panel->clear();
// Add missing connections.
if (GLOBAL_GET("debug/gdscript/warnings/enable").booleanize()) {
Node *base = get_tree()->get_edited_scene_root();
if (base && missing_connections.size() > 0) {
warnings_panel->push_table(1);
for (List<Connection>::Element *E = missing_connections.front(); E; E = E->next()) {
Connection connection = E->get();
String base_path = base->get_name();
String source_path = base == connection.source ? base_path : base_path + "/" + base->get_path_to(Object::cast_to<Node>(connection.source));
String target_path = base == connection.target ? base_path : base_path + "/" + base->get_path_to(Object::cast_to<Node>(connection.target));
warnings_panel->push_cell();
warnings_panel->push_color(warnings_panel->get_color("warning_color", "Editor"));
warnings_panel->add_text(vformat(TTR("Missing connected method '%s' for signal '%s' from node '%s' to node '%s'."), connection.method, connection.signal, source_path, target_path));
warnings_panel->pop(); // Color.
warnings_panel->pop(); // Cell.
}
warnings_panel->pop(); // Table.
warning_nb += missing_connections.size();
}
}
code_editor->set_warning_nb(warning_nb);
// Add script warnings.
warnings_panel->push_table(3);
for (List<ScriptLanguage::Warning>::Element *E = warnings.front(); E; E = E->next()) {
ScriptLanguage::Warning w = E->get();
warnings_panel->push_cell();
warnings_panel->push_meta(w.line - 1);
warnings_panel->push_color(warnings_panel->get_color("warning_color", "Editor"));
warnings_panel->add_text(TTR("Line") + " " + itos(w.line));
warnings_panel->add_text(" (" + w.string_code + "):");
warnings_panel->pop(); // Color.
warnings_panel->pop(); // Meta goto.
warnings_panel->pop(); // Cell.
warnings_panel->push_cell();
warnings_panel->add_text(w.message);
warnings_panel->pop(); // Cell.
Dictionary ignore_meta;
ignore_meta["line"] = w.line;
ignore_meta["code"] = w.string_code.to_lower();
warnings_panel->push_cell();
warnings_panel->push_meta(ignore_meta);
warnings_panel->add_text(TTR("(ignore)"));
warnings_panel->pop(); // Meta ignore.
warnings_panel->pop(); // Cell.
}
warnings_panel->pop(); // Table.
line--;
bool highlight_safe = EDITOR_DEF("text_editor/highlighting/highlight_type_safe_lines", true);
bool last_is_safe = false;
for (int i = 0; i < te->get_line_count(); i++) {
te->set_line_as_marked(i, line == i);
if (highlight_safe) {
if (safe_lines.has(i + 1)) {
te->set_line_as_safe(i, true);
last_is_safe = true;
} else if (last_is_safe && (te->is_line_comment(i) || te->get_line(i).strip_edges().empty())) {
te->set_line_as_safe(i, true);
} else {
te->set_line_as_safe(i, false);
last_is_safe = false;
}
} else {
te->set_line_as_safe(i, false);
}
}
emit_signal("name_changed");
emit_signal("edited_script_changed");
}
void ScriptTextEditor::_update_bookmark_list() {
bookmarks_menu->get_popup()->clear();
bookmarks_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/toggle_bookmark"), BOOKMARK_TOGGLE);
bookmarks_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/remove_all_bookmarks"), BOOKMARK_REMOVE_ALL);
bookmarks_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/goto_next_bookmark"), BOOKMARK_GOTO_NEXT);
bookmarks_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/goto_previous_bookmark"), BOOKMARK_GOTO_PREV);
Array bookmark_list = code_editor->get_text_edit()->get_bookmarks_array();
if (bookmark_list.size() == 0) {
return;
}
bookmarks_menu->get_popup()->add_separator();
for (int i = 0; i < bookmark_list.size(); i++) {
String line = code_editor->get_text_edit()->get_line(bookmark_list[i]).strip_edges();
// Limit the size of the line if too big.
if (line.length() > 50) {
line = line.substr(0, 50);
}
bookmarks_menu->get_popup()->add_item(String::num((int)bookmark_list[i] + 1) + " - \"" + line + "\"");
bookmarks_menu->get_popup()->set_item_metadata(bookmarks_menu->get_popup()->get_item_count() - 1, bookmark_list[i]);
}
}
void ScriptTextEditor::_bookmark_item_pressed(int p_idx) {
if (p_idx < 4) { // Any item before the separator.
_edit_option(bookmarks_menu->get_popup()->get_item_id(p_idx));
} else {
code_editor->goto_line(bookmarks_menu->get_popup()->get_item_metadata(p_idx));
}
}
static Vector<Node *> _find_all_node_for_script(Node *p_base, Node *p_current, const Ref<Script> &p_script) {
Vector<Node *> nodes;
if (p_current->get_owner() != p_base && p_base != p_current) {
return nodes;
}
Ref<Script> c = p_current->get_script();
if (c == p_script) {
nodes.push_back(p_current);
}
for (int i = 0; i < p_current->get_child_count(); i++) {
Vector<Node *> found = _find_all_node_for_script(p_base, p_current->get_child(i), p_script);
nodes.append_array(found);
}
return nodes;
}
static Node *_find_node_for_script(Node *p_base, Node *p_current, const Ref<Script> &p_script) {
if (p_current->get_owner() != p_base && p_base != p_current)
return NULL;
Ref<Script> c = p_current->get_script();
if (c == p_script)
return p_current;
for (int i = 0; i < p_current->get_child_count(); i++) {
Node *found = _find_node_for_script(p_base, p_current->get_child(i), p_script);
if (found)
return found;
}
return NULL;
}
static void _find_changed_scripts_for_external_editor(Node *p_base, Node *p_current, Set<Ref<Script> > &r_scripts) {
if (p_current->get_owner() != p_base && p_base != p_current)
return;
Ref<Script> c = p_current->get_script();
if (c.is_valid())
r_scripts.insert(c);
for (int i = 0; i < p_current->get_child_count(); i++) {
_find_changed_scripts_for_external_editor(p_base, p_current->get_child(i), r_scripts);
}
}
void ScriptEditor::_update_modified_scripts_for_external_editor(Ref<Script> p_for_script) {
if (!bool(EditorSettings::get_singleton()->get("text_editor/external/use_external_editor")))
return;
ERR_FAIL_COND(!get_tree());
Set<Ref<Script> > scripts;
Node *base = get_tree()->get_edited_scene_root();
if (base) {
_find_changed_scripts_for_external_editor(base, base, scripts);
}
for (Set<Ref<Script> >::Element *E = scripts.front(); E; E = E->next()) {
Ref<Script> script = E->get();
if (p_for_script.is_valid() && p_for_script != script)
continue;
if (script->get_path() == "" || script->get_path().find("local://") != -1 || script->get_path().find("::") != -1) {
continue; //internal script, who cares, though weird
}
uint64_t last_date = script->get_last_modified_time();
uint64_t date = FileAccess::get_modified_time(script->get_path());
if (last_date != date) {
Ref<Script> rel_script = ResourceLoader::load(script->get_path(), script->get_class(), true);
ERR_CONTINUE(!rel_script.is_valid());
script->set_source_code(rel_script->get_source_code());
script->set_last_modified_time(rel_script->get_last_modified_time());
script->update_exports();
}
}
}
void ScriptTextEditor::_code_complete_scripts(void *p_ud, const String &p_code, List<String> *r_options, bool &r_force) {
ScriptTextEditor *ste = (ScriptTextEditor *)p_ud;
ste->_code_complete_script(p_code, r_options, r_force);
}
void ScriptTextEditor::_code_complete_script(const String &p_code, List<String> *r_options, bool &r_force) {
if (color_panel->is_visible_in_tree()) return;
Node *base = get_tree()->get_edited_scene_root();
if (base) {
base = _find_node_for_script(base, base, script);
}
String hint;
Error err = script->get_language()->complete_code(p_code, script->get_path(), base, r_options, r_force, hint);
if (err == OK && hint != "") {
code_editor->get_text_edit()->set_code_hint(hint);
}
}
void ScriptTextEditor::_breakpoint_toggled(int p_row) {
ScriptEditor::get_singleton()->get_debugger()->set_breakpoint(script->get_path(), p_row + 1, code_editor->get_text_edit()->is_line_set_as_breakpoint(p_row));
}
void ScriptTextEditor::_lookup_symbol(const String &p_symbol, int p_row, int p_column) {
Node *base = get_tree()->get_edited_scene_root();
if (base) {
base = _find_node_for_script(base, base, script);
}
ScriptLanguage::LookupResult result;
if (ScriptServer::is_global_class(p_symbol)) {
EditorNode::get_singleton()->load_resource(ScriptServer::get_global_class_path(p_symbol));
} else if (p_symbol.is_resource_file()) {
List<String> scene_extensions;
ResourceLoader::get_recognized_extensions_for_type("PackedScene", &scene_extensions);
if (scene_extensions.find(p_symbol.get_extension())) {
EditorNode::get_singleton()->load_scene(p_symbol);
} else {
EditorNode::get_singleton()->load_resource(p_symbol);
}
} else if (script->get_language()->lookup_code(code_editor->get_text_edit()->get_text_for_lookup_completion(), p_symbol, script->get_path(), base, result) == OK) {
_goto_line(p_row);
result.class_name = result.class_name.trim_prefix("_");
switch (result.type) {
case ScriptLanguage::LookupResult::RESULT_SCRIPT_LOCATION: {
if (result.script.is_valid()) {
emit_signal("request_open_script_at_line", result.script, result.location - 1);
} else {
emit_signal("request_save_history");
_goto_line(result.location - 1);
}
} break;
case ScriptLanguage::LookupResult::RESULT_CLASS: {
emit_signal("go_to_help", "class_name:" + result.class_name);
} break;
case ScriptLanguage::LookupResult::RESULT_CLASS_CONSTANT: {
StringName cname = result.class_name;
bool success;
while (true) {
ClassDB::get_integer_constant(cname, result.class_member, &success);
if (success) {
result.class_name = cname;
cname = ClassDB::get_parent_class(cname);
} else {
break;
}
}
emit_signal("go_to_help", "class_constant:" + result.class_name + ":" + result.class_member);
} break;
case ScriptLanguage::LookupResult::RESULT_CLASS_PROPERTY: {
emit_signal("go_to_help", "class_property:" + result.class_name + ":" + result.class_member);
} break;
case ScriptLanguage::LookupResult::RESULT_CLASS_METHOD: {
StringName cname = result.class_name;
while (true) {
if (ClassDB::has_method(cname, result.class_member)) {
result.class_name = cname;
cname = ClassDB::get_parent_class(cname);
} else {
break;
}
}
emit_signal("go_to_help", "class_method:" + result.class_name + ":" + result.class_member);
} break;
case ScriptLanguage::LookupResult::RESULT_CLASS_ENUM: {
StringName cname = result.class_name;
StringName success;
while (true) {
success = ClassDB::get_integer_constant_enum(cname, result.class_member, true);
if (success != StringName()) {
result.class_name = cname;
cname = ClassDB::get_parent_class(cname);
} else {
break;
}
}
emit_signal("go_to_help", "class_enum:" + result.class_name + ":" + result.class_member);
} break;
case ScriptLanguage::LookupResult::RESULT_CLASS_TBD_GLOBALSCOPE: {
emit_signal("go_to_help", "class_global:" + result.class_name + ":" + result.class_member);
} break;
}
}
}
void ScriptTextEditor::_update_connected_methods() {
TextEdit *text_edit = code_editor->get_text_edit();
text_edit->clear_info_icons();
missing_connections.clear();
Node *base = get_tree()->get_edited_scene_root();
if (!base) {
return;
}
Vector<Node *> nodes = _find_all_node_for_script(base, base, script);
for (int i = 0; i < nodes.size(); i++) {
List<Connection> connections;
nodes[i]->get_signals_connected_to_this(&connections);
for (List<Connection>::Element *E = connections.front(); E; E = E->next()) {
Connection connection = E->get();
if (!(connection.flags & CONNECT_PERSIST)) {
continue;
}
// As deleted nodes are still accessible via the undo/redo system, check if they're still on the tree.
Node *source = Object::cast_to<Node>(connection.source);
if (source && !source->is_inside_tree()) {
continue;
}
if (!ClassDB::has_method(script->get_instance_base_type(), connection.method)) {
int line = script->get_language()->find_function(connection.method, text_edit->get_text());
if (line < 0) {
// There is a chance that the method is inherited from another script.
bool found_inherited_function = false;
Ref<Script> inherited_script = script->get_base_script();
while (!inherited_script.is_null()) {
line = inherited_script->get_language()->find_function(connection.method, inherited_script->get_source_code());
if (line != -1) {
found_inherited_function = true;
break;
}
inherited_script = inherited_script->get_base_script();
}
if (!found_inherited_function) {
missing_connections.push_back(connection);
}
} else {
text_edit->set_line_info_icon(line - 1, get_parent_control()->get_icon("Slot", "EditorIcons"), connection.method);
}
}
}
}
}
void ScriptTextEditor::_lookup_connections(int p_row, String p_method) {
Node *base = get_tree()->get_edited_scene_root();
if (!base) {
return;
}
Vector<Node *> nodes = _find_all_node_for_script(base, base, script);
connection_info_dialog->popup_connections(p_method, nodes);
}
void ScriptTextEditor::_edit_option(int p_op) {
TextEdit *tx = code_editor->get_text_edit();
switch (p_op) {
case EDIT_UNDO: {
tx->undo();
tx->call_deferred("grab_focus");
} break;
case EDIT_REDO: {
tx->redo();
tx->call_deferred("grab_focus");
} break;
case EDIT_CUT: {
tx->cut();
tx->call_deferred("grab_focus");
} break;
case EDIT_COPY: {
tx->copy();
tx->call_deferred("grab_focus");
} break;
case EDIT_PASTE: {
tx->paste();
tx->call_deferred("grab_focus");
} break;
case EDIT_SELECT_ALL: {
tx->select_all();
tx->call_deferred("grab_focus");
} break;
case EDIT_MOVE_LINE_UP: {
code_editor->move_lines_up();
} break;
case EDIT_MOVE_LINE_DOWN: {
code_editor->move_lines_down();
} break;
case EDIT_INDENT_LEFT: {
Ref<Script> scr = script;
if (scr.is_null())
return;
tx->indent_left();
} break;
case EDIT_INDENT_RIGHT: {
Ref<Script> scr = script;
if (scr.is_null())
return;
tx->indent_right();
} break;
case EDIT_DELETE_LINE: {
code_editor->delete_lines();
} break;
case EDIT_CLONE_DOWN: {
code_editor->clone_lines_down();
} break;
case EDIT_TOGGLE_FOLD_LINE: {
tx->toggle_fold_line(tx->cursor_get_line());
tx->update();
} break;
case EDIT_FOLD_ALL_LINES: {
tx->fold_all_lines();
tx->update();
} break;
case EDIT_UNFOLD_ALL_LINES: {
tx->unhide_all_lines();
tx->update();
} break;
case EDIT_TOGGLE_COMMENT: {
_edit_option_toggle_inline_comment();
} break;
case EDIT_COMPLETE: {
tx->query_code_comple();
} break;
case EDIT_AUTO_INDENT: {
String text = tx->get_text();
Ref<Script> scr = script;
if (scr.is_null())
return;
tx->begin_complex_operation();
int begin, end;
if (tx->is_selection_active()) {
begin = tx->get_selection_from_line();
end = tx->get_selection_to_line();
// ignore if the cursor is not past the first column
if (tx->get_selection_to_column() == 0) {
end--;
}
} else {
begin = 0;
end = tx->get_line_count() - 1;
}
scr->get_language()->auto_indent_code(text, begin, end);
Vector<String> lines = text.split("\n");
for (int i = begin; i <= end; ++i) {
tx->set_line(i, lines[i]);
}
tx->end_complex_operation();
} break;
case EDIT_TRIM_TRAILING_WHITESAPCE: {
trim_trailing_whitespace();
} break;
case EDIT_CONVERT_INDENT_TO_SPACES: {
convert_indent_to_spaces();
} break;
case EDIT_CONVERT_INDENT_TO_TABS: {
convert_indent_to_tabs();
} break;
case EDIT_PICK_COLOR: {
color_panel->popup();
} break;
case EDIT_TO_UPPERCASE: {
_convert_case(CodeTextEditor::UPPER);
} break;
case EDIT_TO_LOWERCASE: {
_convert_case(CodeTextEditor::LOWER);
} break;
case EDIT_CAPITALIZE: {
_convert_case(CodeTextEditor::CAPITALIZE);
} break;
case SEARCH_FIND: {
code_editor->get_find_replace_bar()->popup_search();
} break;
case SEARCH_FIND_NEXT: {
code_editor->get_find_replace_bar()->search_next();
} break;
case SEARCH_FIND_PREV: {
code_editor->get_find_replace_bar()->search_prev();
} break;
case SEARCH_REPLACE: {
code_editor->get_find_replace_bar()->popup_replace();
} break;
case SEARCH_IN_FILES: {
String selected_text = code_editor->get_text_edit()->get_selection_text();
// Yep, because it doesn't make sense to instance this dialog for every single script open...
// So this will be delegated to the ScriptEditor.
emit_signal("search_in_files_requested", selected_text);
} break;
case SEARCH_LOCATE_FUNCTION: {
quick_open->popup_dialog(get_functions());
quick_open->set_title(TTR("Go to Function"));
} break;
case SEARCH_GOTO_LINE: {
goto_line_dialog->popup_find_line(tx);
} break;
case BOOKMARK_TOGGLE: {
code_editor->toggle_bookmark();
} break;
case BOOKMARK_GOTO_NEXT: {
code_editor->goto_next_bookmark();
} break;
case BOOKMARK_GOTO_PREV: {
code_editor->goto_prev_bookmark();
} break;
case BOOKMARK_REMOVE_ALL: {
code_editor->remove_all_bookmarks();
} break;
case DEBUG_TOGGLE_BREAKPOINT: {
int line = tx->cursor_get_line();
bool dobreak = !tx->is_line_set_as_breakpoint(line);
tx->set_line_as_breakpoint(line, dobreak);
ScriptEditor::get_singleton()->get_debugger()->set_breakpoint(script->get_path(), line + 1, dobreak);
} break;
case DEBUG_REMOVE_ALL_BREAKPOINTS: {
List<int> bpoints;
tx->get_breakpoints(&bpoints);
for (List<int>::Element *E = bpoints.front(); E; E = E->next()) {
int line = E->get();
bool dobreak = !tx->is_line_set_as_breakpoint(line);
tx->set_line_as_breakpoint(line, dobreak);
ScriptEditor::get_singleton()->get_debugger()->set_breakpoint(script->get_path(), line + 1, dobreak);
}
} break;
case DEBUG_GOTO_NEXT_BREAKPOINT: {
List<int> bpoints;
tx->get_breakpoints(&bpoints);
if (bpoints.size() <= 0) {
return;
}
int line = tx->cursor_get_line();
// wrap around
if (line >= bpoints[bpoints.size() - 1]) {
tx->unfold_line(bpoints[0]);
tx->cursor_set_line(bpoints[0]);
} else {
for (List<int>::Element *E = bpoints.front(); E; E = E->next()) {
int bline = E->get();
if (bline > line) {
tx->unfold_line(bline);
tx->cursor_set_line(bline);
return;
}
}
}
} break;
case DEBUG_GOTO_PREV_BREAKPOINT: {
List<int> bpoints;
tx->get_breakpoints(&bpoints);
if (bpoints.size() <= 0) {
return;
}
int line = tx->cursor_get_line();
// wrap around
if (line <= bpoints[0]) {
tx->unfold_line(bpoints[bpoints.size() - 1]);
tx->cursor_set_line(bpoints[bpoints.size() - 1]);
} else {
for (List<int>::Element *E = bpoints.back(); E; E = E->prev()) {
int bline = E->get();
if (bline < line) {
tx->unfold_line(bline);
tx->cursor_set_line(bline);
return;
}
}
}
} break;
case HELP_CONTEXTUAL: {
String text = tx->get_selection_text();
if (text == "")
text = tx->get_word_under_cursor();
if (text != "") {
emit_signal("request_help", text);
}
} break;
case LOOKUP_SYMBOL: {
String text = tx->get_word_under_cursor();
if (text == "")
text = tx->get_selection_text();
if (text != "") {
_lookup_symbol(text, tx->cursor_get_line(), tx->cursor_get_column());
}
} break;
}
}
void ScriptTextEditor::_edit_option_toggle_inline_comment() {
if (script.is_null())
return;
String delimiter = "#";
List<String> comment_delimiters;
script->get_language()->get_comment_delimiters(&comment_delimiters);
for (List<String>::Element *E = comment_delimiters.front(); E; E = E->next()) {
String script_delimiter = E->get();
if (script_delimiter.find(" ") == -1) {
delimiter = script_delimiter;
break;
}
}
code_editor->toggle_inline_comment(delimiter);
}
void ScriptTextEditor::add_syntax_highlighter(SyntaxHighlighter *p_highlighter) {
highlighters[p_highlighter->get_name()] = p_highlighter;
highlighter_menu->add_radio_check_item(p_highlighter->get_name());
}
void ScriptTextEditor::set_syntax_highlighter(SyntaxHighlighter *p_highlighter) {
TextEdit *te = code_editor->get_text_edit();
te->_set_syntax_highlighting(p_highlighter);
if (p_highlighter != NULL)
highlighter_menu->set_item_checked(highlighter_menu->get_item_idx_from_text(p_highlighter->get_name()), true);
else
highlighter_menu->set_item_checked(highlighter_menu->get_item_idx_from_text(TTR("Standard")), true);
}
void ScriptTextEditor::_change_syntax_highlighter(int p_idx) {
Map<String, SyntaxHighlighter *>::Element *el = highlighters.front();
while (el != NULL) {
highlighter_menu->set_item_checked(highlighter_menu->get_item_idx_from_text(el->key()), false);
el = el->next();
}
// highlighter_menu->set_item_checked(p_idx, true);
set_syntax_highlighter(highlighters[highlighter_menu->get_item_text(p_idx)]);
}
void ScriptTextEditor::_bind_methods() {
ClassDB::bind_method("_validate_script", &ScriptTextEditor::_validate_script);
ClassDB::bind_method("_update_bookmark_list", &ScriptTextEditor::_update_bookmark_list);
ClassDB::bind_method("_bookmark_item_pressed", &ScriptTextEditor::_bookmark_item_pressed);
ClassDB::bind_method("_load_theme_settings", &ScriptTextEditor::_load_theme_settings);
ClassDB::bind_method("_breakpoint_toggled", &ScriptTextEditor::_breakpoint_toggled);
ClassDB::bind_method("_lookup_connections", &ScriptTextEditor::_lookup_connections);
ClassDB::bind_method("_update_connected_methods", &ScriptTextEditor::_update_connected_methods);
ClassDB::bind_method("_change_syntax_highlighter", &ScriptTextEditor::_change_syntax_highlighter);
ClassDB::bind_method("_edit_option", &ScriptTextEditor::_edit_option);
ClassDB::bind_method("_goto_line", &ScriptTextEditor::_goto_line);
ClassDB::bind_method("_lookup_symbol", &ScriptTextEditor::_lookup_symbol);
ClassDB::bind_method("_text_edit_gui_input", &ScriptTextEditor::_text_edit_gui_input);
ClassDB::bind_method("_show_warnings_panel", &ScriptTextEditor::_show_warnings_panel);
ClassDB::bind_method("_error_pressed", &ScriptTextEditor::_error_pressed);
ClassDB::bind_method("_warning_clicked", &ScriptTextEditor::_warning_clicked);
ClassDB::bind_method("_color_changed", &ScriptTextEditor::_color_changed);
ClassDB::bind_method("get_drag_data_fw", &ScriptTextEditor::get_drag_data_fw);
ClassDB::bind_method("can_drop_data_fw", &ScriptTextEditor::can_drop_data_fw);
ClassDB::bind_method("drop_data_fw", &ScriptTextEditor::drop_data_fw);
}
Control *ScriptTextEditor::get_edit_menu() {
return edit_hb;
}
void ScriptTextEditor::clear_edit_menu() {
memdelete(edit_hb);
}
void ScriptTextEditor::reload(bool p_soft) {
TextEdit *te = code_editor->get_text_edit();
Ref<Script> scr = script;
if (scr.is_null())
return;
scr->set_source_code(te->get_text());
bool soft = p_soft || scr->get_instance_base_type() == "EditorPlugin"; //always soft-reload editor plugins
scr->get_language()->reload_tool_script(scr, soft);
}
void ScriptTextEditor::get_breakpoints(List<int> *p_breakpoints) {
code_editor->get_text_edit()->get_breakpoints(p_breakpoints);
}
void ScriptTextEditor::set_tooltip_request_func(String p_method, Object *p_obj) {
code_editor->get_text_edit()->set_tooltip_request_func(p_obj, p_method, this);
}
void ScriptTextEditor::set_debugger_active(bool p_active) {
}
Variant ScriptTextEditor::get_drag_data_fw(const Point2 &p_point, Control *p_from) {
return Variant();
}
bool ScriptTextEditor::can_drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) const {
Dictionary d = p_data;
if (d.has("type") && (String(d["type"]) == "resource" ||
String(d["type"]) == "files" ||
String(d["type"]) == "nodes" ||
String(d["type"]) == "files_and_dirs")) {
return true;
}
return false;
}
#ifdef TOOLS_ENABLED
static Node *_find_script_node(Node *p_edited_scene, Node *p_current_node, const Ref<Script> &script) {
if (p_edited_scene != p_current_node && p_current_node->get_owner() != p_edited_scene)
return NULL;
Ref<Script> scr = p_current_node->get_script();
if (scr.is_valid() && scr == script)
return p_current_node;
for (int i = 0; i < p_current_node->get_child_count(); i++) {
Node *n = _find_script_node(p_edited_scene, p_current_node->get_child(i), script);
if (n)
return n;
}
return NULL;
}
#else
static Node *_find_script_node(Node *p_edited_scene, Node *p_current_node, const Ref<Script> &script) {
return NULL;
}
#endif
void ScriptTextEditor::drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) {
Dictionary d = p_data;
TextEdit *te = code_editor->get_text_edit();
int row, col;
te->_get_mouse_pos(p_point, row, col);
if (d.has("type") && String(d["type"]) == "resource") {
Ref<Resource> res = d["resource"];
if (!res.is_valid()) {
return;
}
if (res->get_path().is_resource_file()) {
EditorNode::get_singleton()->show_warning(TTR("Only resources from filesystem can be dropped."));
return;
}
te->cursor_set_line(row);
te->cursor_set_column(col);
te->insert_text_at_cursor(res->get_path());
}
if (d.has("type") && (String(d["type"]) == "files" || String(d["type"]) == "files_and_dirs")) {
Array files = d["files"];
String text_to_drop;
for (int i = 0; i < files.size(); i++) {
if (i > 0)
text_to_drop += ",";
text_to_drop += "\"" + String(files[i]).c_escape() + "\"";
}
te->cursor_set_line(row);
te->cursor_set_column(col);
te->insert_text_at_cursor(text_to_drop);
}
if (d.has("type") && String(d["type"]) == "nodes") {
Node *sn = _find_script_node(get_tree()->get_edited_scene_root(), get_tree()->get_edited_scene_root(), script);
if (!sn) {
EditorNode::get_singleton()->show_warning("Can't drop nodes because script '" + get_name() + "' is not used in this scene.");
return;
}
Array nodes = d["nodes"];
String text_to_drop;
for (int i = 0; i < nodes.size(); i++) {
if (i > 0)
text_to_drop += ",";
NodePath np = nodes[i];
Node *node = get_node(np);
if (!node) {
continue;
}
String path = sn->get_path_to(node);
text_to_drop += "\"" + path.c_escape() + "\"";
}
te->cursor_set_line(row);
te->cursor_set_column(col);
te->insert_text_at_cursor(text_to_drop);
}
}
void ScriptTextEditor::_text_edit_gui_input(const Ref<InputEvent> &ev) {
Ref<InputEventMouseButton> mb = ev;
if (mb.is_valid()) {
if (mb->get_button_index() == BUTTON_RIGHT && mb->is_pressed()) {
int col, row;
TextEdit *tx = code_editor->get_text_edit();
tx->_get_mouse_pos(mb->get_global_position() - tx->get_global_position(), row, col);
Vector2 mpos = mb->get_global_position() - tx->get_global_position();
tx->set_right_click_moves_caret(EditorSettings::get_singleton()->get("text_editor/cursor/right_click_moves_caret"));
if (tx->is_right_click_moving_caret()) {
if (tx->is_selection_active()) {
int from_line = tx->get_selection_from_line();
int to_line = tx->get_selection_to_line();
int from_column = tx->get_selection_from_column();
int to_column = tx->get_selection_to_column();
if (row < from_line || row > to_line || (row == from_line && col < from_column) || (row == to_line && col > to_column)) {
// Right click is outside the selected text
tx->deselect();
}
}
if (!tx->is_selection_active()) {
tx->cursor_set_line(row, true, false);
tx->cursor_set_column(col);
}
}
String word_at_mouse = tx->get_word_at_pos(mpos);
if (word_at_mouse == "")
word_at_mouse = tx->get_word_under_cursor();
if (word_at_mouse == "")
word_at_mouse = tx->get_selection_text();
bool has_color = (word_at_mouse == "Color");
bool foldable = tx->can_fold(row) || tx->is_folded(row);
bool open_docs = false;
bool goto_definition = false;
if (word_at_mouse.is_resource_file()) {
open_docs = true;
} else {
Node *base = get_tree()->get_edited_scene_root();
if (base) {
base = _find_node_for_script(base, base, script);
}
ScriptLanguage::LookupResult result;
if (script->get_language()->lookup_code(code_editor->get_text_edit()->get_text_for_lookup_completion(), word_at_mouse, script->get_path(), base, result) == OK) {
open_docs = true;
}
}
if (has_color) {
String line = tx->get_line(row);
color_line = row;
int begin = 0;
int end = 0;
bool valid = false;
for (int i = col; i < line.length(); i++) {
if (line[i] == '(') {
begin = i;
continue;
} else if (line[i] == ')') {
end = i + 1;
valid = true;
break;
}
}
if (valid) {
color_args = line.substr(begin, end - begin);
String stripped = color_args.replace(" ", "").replace("(", "").replace(")", "");
Vector<float> color = stripped.split_floats(",");
if (color.size() > 2) {
float alpha = color.size() > 3 ? color[3] : 1.0f;
color_picker->set_pick_color(Color(color[0], color[1], color[2], alpha));
}
color_panel->set_position(get_global_transform().xform(get_local_mouse_position()));
} else {
has_color = false;
}
}
_make_context_menu(tx->is_selection_active(), has_color, foldable, open_docs, goto_definition);
}
}
}
void ScriptTextEditor::_color_changed(const Color &p_color) {
String new_args;
if (p_color.a == 1.0f) {
new_args = String("(" + rtos(p_color.r) + ", " + rtos(p_color.g) + ", " + rtos(p_color.b) + ")");
} else {
new_args = String("(" + rtos(p_color.r) + ", " + rtos(p_color.g) + ", " + rtos(p_color.b) + ", " + rtos(p_color.a) + ")");
}
String line = code_editor->get_text_edit()->get_line(color_line);
String new_line = line.replace(color_args, new_args);
color_args = new_args;
code_editor->get_text_edit()->set_line(color_line, new_line);
}
void ScriptTextEditor::_make_context_menu(bool p_selection, bool p_color, bool p_foldable, bool p_open_docs, bool p_goto_definition) {
context_menu->clear();
if (p_selection) {
context_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/cut"), EDIT_CUT);
context_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/copy"), EDIT_COPY);
}
context_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/paste"), EDIT_PASTE);
context_menu->add_separator();
context_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/select_all"), EDIT_SELECT_ALL);
context_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/undo"), EDIT_UNDO);
context_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/redo"), EDIT_REDO);
context_menu->add_separator();
context_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/indent_left"), EDIT_INDENT_LEFT);
context_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/indent_right"), EDIT_INDENT_RIGHT);
context_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/toggle_comment"), EDIT_TOGGLE_COMMENT);
context_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/toggle_bookmark"), BOOKMARK_TOGGLE);
if (p_selection) {
context_menu->add_separator();
context_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/convert_to_uppercase"), EDIT_TO_UPPERCASE);
context_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/convert_to_lowercase"), EDIT_TO_LOWERCASE);
}
if (p_foldable)
context_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/toggle_fold_line"), EDIT_TOGGLE_FOLD_LINE);
if (p_color || p_open_docs || p_goto_definition) {
context_menu->add_separator();
if (p_open_docs)
context_menu->add_item(TTR("Lookup Symbol"), LOOKUP_SYMBOL);
if (p_color)
context_menu->add_item(TTR("Pick Color"), EDIT_PICK_COLOR);
}
context_menu->set_position(get_global_transform().xform(get_local_mouse_position()));
context_menu->set_size(Vector2(1, 1));
context_menu->popup();
}
ScriptTextEditor::ScriptTextEditor() {
theme_loaded = false;
VSplitContainer *editor_box = memnew(VSplitContainer);
add_child(editor_box);
editor_box->set_anchors_and_margins_preset(Control::PRESET_WIDE);
editor_box->set_v_size_flags(SIZE_EXPAND_FILL);
code_editor = memnew(CodeTextEditor);
editor_box->add_child(code_editor);
code_editor->add_constant_override("separation", 2);
code_editor->set_anchors_and_margins_preset(Control::PRESET_WIDE);
code_editor->connect("validate_script", this, "_validate_script");
code_editor->connect("load_theme_settings", this, "_load_theme_settings");
code_editor->set_code_complete_func(_code_complete_scripts, this);
code_editor->get_text_edit()->connect("breakpoint_toggled", this, "_breakpoint_toggled");
code_editor->get_text_edit()->connect("symbol_lookup", this, "_lookup_symbol");
code_editor->get_text_edit()->connect("info_clicked", this, "_lookup_connections");
code_editor->set_v_size_flags(SIZE_EXPAND_FILL);
warnings_panel = memnew(RichTextLabel);
editor_box->add_child(warnings_panel);
warnings_panel->set_custom_minimum_size(Size2(0, 100 * EDSCALE));
warnings_panel->set_h_size_flags(SIZE_EXPAND_FILL);
warnings_panel->set_meta_underline(true);
warnings_panel->set_selection_enabled(true);
warnings_panel->set_focus_mode(FOCUS_CLICK);
warnings_panel->hide();
code_editor->connect("error_pressed", this, "_error_pressed");
code_editor->connect("show_warnings_panel", this, "_show_warnings_panel");
warnings_panel->connect("meta_clicked", this, "_warning_clicked");
update_settings();
code_editor->get_text_edit()->set_callhint_settings(
EditorSettings::get_singleton()->get("text_editor/completion/put_callhint_tooltip_below_current_line"),
EditorSettings::get_singleton()->get("text_editor/completion/callhint_tooltip_offset"));
code_editor->get_text_edit()->set_select_identifiers_on_hover(true);
code_editor->get_text_edit()->set_context_menu_enabled(false);
code_editor->get_text_edit()->connect("gui_input", this, "_text_edit_gui_input");
context_menu = memnew(PopupMenu);
add_child(context_menu);
context_menu->connect("id_pressed", this, "_edit_option");
context_menu->set_hide_on_window_lose_focus(true);
color_panel = memnew(PopupPanel);
add_child(color_panel);
color_picker = memnew(ColorPicker);
color_panel->add_child(color_picker);
color_picker->connect("color_changed", this, "_color_changed");
edit_hb = memnew(HBoxContainer);
edit_menu = memnew(MenuButton);
edit_menu->set_text(TTR("Edit"));
edit_menu->set_switch_on_hover(true);
edit_menu->get_popup()->set_hide_on_window_lose_focus(true);
edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/undo"), EDIT_UNDO);
edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/redo"), EDIT_REDO);
edit_menu->get_popup()->add_separator();
edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/cut"), EDIT_CUT);
edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/copy"), EDIT_COPY);
edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/paste"), EDIT_PASTE);
edit_menu->get_popup()->add_separator();
edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/select_all"), EDIT_SELECT_ALL);
edit_menu->get_popup()->add_separator();
edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/move_up"), EDIT_MOVE_LINE_UP);
edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/move_down"), EDIT_MOVE_LINE_DOWN);
edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/indent_left"), EDIT_INDENT_LEFT);
edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/indent_right"), EDIT_INDENT_RIGHT);
edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/delete_line"), EDIT_DELETE_LINE);
edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/toggle_comment"), EDIT_TOGGLE_COMMENT);
edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/toggle_fold_line"), EDIT_TOGGLE_FOLD_LINE);
edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/fold_all_lines"), EDIT_FOLD_ALL_LINES);
edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/unfold_all_lines"), EDIT_UNFOLD_ALL_LINES);
edit_menu->get_popup()->add_separator();
edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/clone_down"), EDIT_CLONE_DOWN);
edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/complete_symbol"), EDIT_COMPLETE);
edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/trim_trailing_whitespace"), EDIT_TRIM_TRAILING_WHITESAPCE);
edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/convert_indent_to_spaces"), EDIT_CONVERT_INDENT_TO_SPACES);
edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/convert_indent_to_tabs"), EDIT_CONVERT_INDENT_TO_TABS);
edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/auto_indent"), EDIT_AUTO_INDENT);
edit_menu->get_popup()->connect("id_pressed", this, "_edit_option");
edit_menu->get_popup()->add_separator();
edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/toggle_breakpoint"), DEBUG_TOGGLE_BREAKPOINT);
edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/remove_all_breakpoints"), DEBUG_REMOVE_ALL_BREAKPOINTS);
edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/goto_next_breakpoint"), DEBUG_GOTO_NEXT_BREAKPOINT);
edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/goto_previous_breakpoint"), DEBUG_GOTO_PREV_BREAKPOINT);
edit_menu->get_popup()->add_separator();
PopupMenu *convert_case = memnew(PopupMenu);
convert_case->set_name("convert_case");
edit_menu->get_popup()->add_child(convert_case);
edit_menu->get_popup()->add_submenu_item(TTR("Convert Case"), "convert_case");
convert_case->add_shortcut(ED_SHORTCUT("script_text_editor/convert_to_uppercase", TTR("Uppercase"), KEY_MASK_SHIFT | KEY_F4), EDIT_TO_UPPERCASE);
convert_case->add_shortcut(ED_SHORTCUT("script_text_editor/convert_to_lowercase", TTR("Lowercase"), KEY_MASK_SHIFT | KEY_F5), EDIT_TO_LOWERCASE);
convert_case->add_shortcut(ED_SHORTCUT("script_text_editor/capitalize", TTR("Capitalize"), KEY_MASK_SHIFT | KEY_F6), EDIT_CAPITALIZE);
convert_case->connect("id_pressed", this, "_edit_option");
highlighters[TTR("Standard")] = NULL;
highlighter_menu = memnew(PopupMenu);
highlighter_menu->set_name("highlighter_menu");
edit_menu->get_popup()->add_child(highlighter_menu);
edit_menu->get_popup()->add_submenu_item(TTR("Syntax Highlighter"), "highlighter_menu");
highlighter_menu->add_radio_check_item(TTR("Standard"));
highlighter_menu->connect("id_pressed", this, "_change_syntax_highlighter");
search_menu = memnew(MenuButton);
edit_hb->add_child(search_menu);
search_menu->set_text(TTR("Search"));
search_menu->set_switch_on_hover(true);
search_menu->get_popup()->set_hide_on_window_lose_focus(true);
search_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/find"), SEARCH_FIND);
search_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/find_next"), SEARCH_FIND_NEXT);
search_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/find_previous"), SEARCH_FIND_PREV);
search_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/replace"), SEARCH_REPLACE);
search_menu->get_popup()->add_separator();
search_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/find_in_files"), SEARCH_IN_FILES);
search_menu->get_popup()->add_separator();
search_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/goto_function"), SEARCH_LOCATE_FUNCTION);
search_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/goto_line"), SEARCH_GOTO_LINE);
search_menu->get_popup()->add_separator();
search_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/contextual_help"), HELP_CONTEXTUAL);
search_menu->get_popup()->connect("id_pressed", this, "_edit_option");
edit_hb->add_child(edit_menu);
bookmarks_menu = memnew(MenuButton);
edit_hb->add_child(bookmarks_menu);
bookmarks_menu->set_text(TTR("Bookmarks"));
bookmarks_menu->set_switch_on_hover(true);
_update_bookmark_list();
bookmarks_menu->connect("about_to_show", this, "_update_bookmark_list");
bookmarks_menu->get_popup()->connect("index_pressed", this, "_bookmark_item_pressed");
quick_open = memnew(ScriptEditorQuickOpen);
add_child(quick_open);
quick_open->connect("goto_line", this, "_goto_line");
goto_line_dialog = memnew(GotoLineDialog);
add_child(goto_line_dialog);
connection_info_dialog = memnew(ConnectionInfoDialog);
add_child(connection_info_dialog);
code_editor->get_text_edit()->set_drag_forwarding(this);
}
static ScriptEditorBase *create_editor(const RES &p_resource) {
if (Object::cast_to<Script>(*p_resource)) {
return memnew(ScriptTextEditor);
}
return NULL;
}
void ScriptTextEditor::register_editor() {
ED_SHORTCUT("script_text_editor/undo", TTR("Undo"), KEY_MASK_CMD | KEY_Z);
ED_SHORTCUT("script_text_editor/redo", TTR("Redo"), KEY_MASK_CMD | KEY_Y);
ED_SHORTCUT("script_text_editor/cut", TTR("Cut"), KEY_MASK_CMD | KEY_X);
ED_SHORTCUT("script_text_editor/copy", TTR("Copy"), KEY_MASK_CMD | KEY_C);
ED_SHORTCUT("script_text_editor/paste", TTR("Paste"), KEY_MASK_CMD | KEY_V);
ED_SHORTCUT("script_text_editor/select_all", TTR("Select All"), KEY_MASK_CMD | KEY_A);
ED_SHORTCUT("script_text_editor/move_up", TTR("Move Up"), KEY_MASK_ALT | KEY_UP);
ED_SHORTCUT("script_text_editor/move_down", TTR("Move Down"), KEY_MASK_ALT | KEY_DOWN);
ED_SHORTCUT("script_text_editor/delete_line", TTR("Delete Line"), KEY_MASK_CMD | KEY_MASK_SHIFT | KEY_K);
//leave these at zero, same can be accomplished with tab/shift-tab, including selection
//the next/previous in history shortcut in this case makes a lot more sene.
ED_SHORTCUT("script_text_editor/indent_left", TTR("Indent Left"), 0);
ED_SHORTCUT("script_text_editor/indent_right", TTR("Indent Right"), 0);
ED_SHORTCUT("script_text_editor/toggle_comment", TTR("Toggle Comment"), KEY_MASK_CMD | KEY_K);
ED_SHORTCUT("script_text_editor/toggle_bookmark", TTR("Toggle Bookmark"), KEY_MASK_CMD | KEY_MASK_ALT | KEY_B);
ED_SHORTCUT("script_text_editor/goto_next_bookmark", TTR("Go to Next Bookmark"), KEY_MASK_CMD | KEY_B);
ED_SHORTCUT("script_text_editor/goto_previous_bookmark", TTR("Go to Previous Bookmark"), KEY_MASK_CMD | KEY_MASK_SHIFT | KEY_B);
ED_SHORTCUT("script_text_editor/remove_all_bookmarks", TTR("Remove All Bookmarks"), 0);
ED_SHORTCUT("script_text_editor/toggle_fold_line", TTR("Fold/Unfold Line"), KEY_MASK_ALT | KEY_F);
ED_SHORTCUT("script_text_editor/fold_all_lines", TTR("Fold All Lines"), 0);
ED_SHORTCUT("script_text_editor/unfold_all_lines", TTR("Unfold All Lines"), 0);
#ifdef OSX_ENABLED
ED_SHORTCUT("script_text_editor/clone_down", TTR("Clone Down"), KEY_MASK_SHIFT | KEY_MASK_CMD | KEY_C);
ED_SHORTCUT("script_text_editor/complete_symbol", TTR("Complete Symbol"), KEY_MASK_CTRL | KEY_SPACE);
#else
ED_SHORTCUT("script_text_editor/clone_down", TTR("Clone Down"), KEY_MASK_CMD | KEY_D);
ED_SHORTCUT("script_text_editor/complete_symbol", TTR("Complete Symbol"), KEY_MASK_CMD | KEY_SPACE);
#endif
ED_SHORTCUT("script_text_editor/trim_trailing_whitespace", TTR("Trim Trailing Whitespace"), KEY_MASK_CMD | KEY_MASK_ALT | KEY_T);
ED_SHORTCUT("script_text_editor/convert_indent_to_spaces", TTR("Convert Indent to Spaces"), KEY_MASK_CMD | KEY_MASK_SHIFT | KEY_Y);
ED_SHORTCUT("script_text_editor/convert_indent_to_tabs", TTR("Convert Indent to Tabs"), KEY_MASK_CMD | KEY_MASK_SHIFT | KEY_I);
ED_SHORTCUT("script_text_editor/auto_indent", TTR("Auto Indent"), KEY_MASK_CMD | KEY_I);
#ifdef OSX_ENABLED
ED_SHORTCUT("script_text_editor/toggle_breakpoint", TTR("Toggle Breakpoint"), KEY_MASK_CMD | KEY_MASK_SHIFT | KEY_B);
#else
ED_SHORTCUT("script_text_editor/toggle_breakpoint", TTR("Toggle Breakpoint"), KEY_F9);
#endif
ED_SHORTCUT("script_text_editor/remove_all_breakpoints", TTR("Remove All Breakpoints"), KEY_MASK_CMD | KEY_MASK_SHIFT | KEY_F9);
ED_SHORTCUT("script_text_editor/goto_next_breakpoint", TTR("Go to Next Breakpoint"), KEY_MASK_CMD | KEY_PERIOD);
ED_SHORTCUT("script_text_editor/goto_previous_breakpoint", TTR("Go to Previous Breakpoint"), KEY_MASK_CMD | KEY_COMMA);
ED_SHORTCUT("script_text_editor/find", TTR("Find..."), KEY_MASK_CMD | KEY_F);
#ifdef OSX_ENABLED
ED_SHORTCUT("script_text_editor/find_next", TTR("Find Next"), KEY_MASK_CMD | KEY_G);
ED_SHORTCUT("script_text_editor/find_previous", TTR("Find Previous"), KEY_MASK_CMD | KEY_MASK_SHIFT | KEY_G);
ED_SHORTCUT("script_text_editor/replace", TTR("Replace..."), KEY_MASK_ALT | KEY_MASK_CMD | KEY_F);
#else
ED_SHORTCUT("script_text_editor/find_next", TTR("Find Next"), KEY_F3);
ED_SHORTCUT("script_text_editor/find_previous", TTR("Find Previous"), KEY_MASK_SHIFT | KEY_F3);
ED_SHORTCUT("script_text_editor/replace", TTR("Replace..."), KEY_MASK_CMD | KEY_R);
#endif
ED_SHORTCUT("script_text_editor/find_in_files", TTR("Find in Files..."), KEY_MASK_CMD | KEY_MASK_SHIFT | KEY_F);
#ifdef OSX_ENABLED
ED_SHORTCUT("script_text_editor/goto_function", TTR("Go to Function..."), KEY_MASK_CTRL | KEY_MASK_CMD | KEY_J);
#else
ED_SHORTCUT("script_text_editor/goto_function", TTR("Go to Function..."), KEY_MASK_ALT | KEY_MASK_CMD | KEY_F);
#endif
ED_SHORTCUT("script_text_editor/goto_line", TTR("Go to Line..."), KEY_MASK_CMD | KEY_L);
#ifdef OSX_ENABLED
ED_SHORTCUT("script_text_editor/contextual_help", TTR("Contextual Help"), KEY_MASK_ALT | KEY_MASK_SHIFT | KEY_SPACE);
#else
ED_SHORTCUT("script_text_editor/contextual_help", TTR("Contextual Help"), KEY_MASK_ALT | KEY_F1);
#endif
ScriptEditor::register_create_script_editor_function(create_editor);
}
void ScriptTextEditor::validate() {
this->code_editor->validate_script();
}
|
/**
* @file src/fileinfo/file_presentation/getters/iterative_getter/iterative_subtitle_getter/segment_json_getter.cpp
* @brief Methods of SegmentJsonGetter class.
* @copyright (c) 2017 Avast Software, licensed under the MIT license
*/
#include "retdec/utils/string.h"
#include "retdec/fileformat/utils/conversions.h"
#include "fileinfo/file_presentation/getters/iterative_getter/iterative_subtitle_getter/segment_json_getter.h"
using namespace retdec::utils;
using namespace retdec::fileformat;
namespace fileinfo {
/**
* Constructor
* @param fileInfo Information about file
*/
SegmentJsonGetter::SegmentJsonGetter(FileInformation &fileInfo) : IterativeSubtitleGetter(fileInfo)
{
numberOfStructures = 1;
numberOfStoredRecords.push_back(fileinfo.getNumberOfStoredSegments());
numberOfExtraElements.push_back(0);
title = "segmentTable";
subtitle = "segments";
commonHeaderElements.push_back("index");
commonHeaderElements.push_back("type");
commonHeaderElements.push_back("offset");
commonHeaderElements.push_back("sizeInFile");
commonHeaderElements.push_back("virtualAddress");
commonHeaderElements.push_back("physicalAddress");
commonHeaderElements.push_back("sizeInMemory");
commonHeaderElements.push_back("alignmentInMemory");
commonHeaderElements.push_back("crc32");
commonHeaderElements.push_back("md5");
commonHeaderElements.push_back("sha256");
}
/**
* Destructor
*/
SegmentJsonGetter::~SegmentJsonGetter()
{
}
std::size_t SegmentJsonGetter::getBasicInfo(std::size_t structIndex, std::vector<std::string> &desc, std::vector<std::string> &info) const
{
static_cast<void>(structIndex);
static_cast<void>(desc);
static_cast<void>(info);
return 0;
}
bool SegmentJsonGetter::getRecord(std::size_t structIndex, std::size_t recIndex, std::vector<std::string> &record) const
{
if(structIndex >= numberOfStructures || recIndex >= numberOfStoredRecords[structIndex])
{
return false;
}
record.clear();
record.push_back(fileinfo.getSegmentIndexStr(recIndex));
record.push_back(toLower(fileinfo.getSegmentType(recIndex)));
record.push_back(fileinfo.getSegmentOffsetStr(recIndex, hexWithPrefix));
record.push_back(fileinfo.getSegmentSizeInFileStr(recIndex, hexWithPrefix));
record.push_back(fileinfo.getSegmentVirtualAddressStr(recIndex, hexWithPrefix));
record.push_back(fileinfo.getSegmentPhysicalAddressStr(recIndex, hexWithPrefix));
record.push_back(fileinfo.getSegmentSizeInMemoryStr(recIndex, hexWithPrefix));
record.push_back(fileinfo.getSegmentAlignmentStr(recIndex, hexWithPrefix));
record.push_back(fileinfo.getSegmentCrc32(recIndex));
record.push_back(fileinfo.getSegmentMd5(recIndex));
record.push_back(fileinfo.getSegmentSha256(recIndex));
return true;
}
bool SegmentJsonGetter::getFlags(std::size_t structIndex, std::size_t recIndex, std::string &flagsValue, std::vector<std::string> &desc) const
{
if(structIndex >= numberOfStructures || recIndex >= numberOfStoredRecords[structIndex])
{
return false;
}
flagsValue = fileinfo.getSegmentFlagsStr(recIndex);
std::vector<std::string> optional;
fileinfo.getSegmentFlagsDescriptors(recIndex, desc, optional);
return true;
}
} // namespace fileinfo
|
// Copyright 2015 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 <cmath>
#include "src/api/api-inl.h"
#include "src/base/utils/random-number-generator.h"
#include "src/builtins/builtins-promise-gen.h"
#include "src/builtins/builtins-string-gen.h"
#include "src/codegen/code-factory.h"
#include "src/codegen/code-stub-assembler.h"
#include "src/compiler/node.h"
#include "src/debug/debug.h"
#include "src/execution/isolate.h"
#include "src/objects/elements-kind.h"
#include "src/objects/objects-inl.h"
#include "src/objects/promise-inl.h"
#include "src/strings/char-predicates.h"
#include "test/cctest/compiler/code-assembler-tester.h"
#include "test/cctest/compiler/function-tester.h"
namespace v8 {
namespace internal {
namespace compiler {
namespace {
using Variable = CodeAssemblerVariable;
class TestTorqueAssembler : public CodeStubAssembler {
public:
explicit TestTorqueAssembler(CodeAssemblerState* state)
: CodeStubAssembler(state) {}
};
} // namespace
TEST(TestConstexpr1) {
Isolate* isolate(CcTest::InitIsolateOnce());
CodeAssemblerTester asm_tester(isolate, 0);
TestTorqueAssembler m(asm_tester.state());
{
m.TestConstexpr1();
m.Return(m.UndefinedConstant());
}
FunctionTester ft(asm_tester.GenerateCode(), 0);
ft.Call();
}
TEST(TestConstexprIf) {
Isolate* isolate(CcTest::InitIsolateOnce());
CodeAssemblerTester asm_tester(isolate, 0);
TestTorqueAssembler m(asm_tester.state());
{
m.TestConstexprIf();
m.Return(m.UndefinedConstant());
}
FunctionTester ft(asm_tester.GenerateCode(), 0);
ft.Call();
}
TEST(TestConstexprReturn) {
Isolate* isolate(CcTest::InitIsolateOnce());
CodeAssemblerTester asm_tester(isolate, 0);
TestTorqueAssembler m(asm_tester.state());
{
m.TestConstexprReturn();
m.Return(m.UndefinedConstant());
}
FunctionTester ft(asm_tester.GenerateCode(), 0);
ft.Call();
}
TEST(TestGotoLabel) {
Isolate* isolate(CcTest::InitIsolateOnce());
CodeAssemblerTester asm_tester(isolate, 0);
TestTorqueAssembler m(asm_tester.state());
{ m.Return(m.TestGotoLabel()); }
FunctionTester ft(asm_tester.GenerateCode(), 0);
ft.CheckCall(ft.true_value());
}
TEST(TestGotoLabelWithOneParameter) {
Isolate* isolate(CcTest::InitIsolateOnce());
CodeAssemblerTester asm_tester(isolate, 0);
TestTorqueAssembler m(asm_tester.state());
{ m.Return(m.TestGotoLabelWithOneParameter()); }
FunctionTester ft(asm_tester.GenerateCode(), 0);
ft.CheckCall(ft.true_value());
}
TEST(TestGotoLabelWithTwoParameters) {
Isolate* isolate(CcTest::InitIsolateOnce());
CodeAssemblerTester asm_tester(isolate, 0);
TestTorqueAssembler m(asm_tester.state());
{ m.Return(m.TestGotoLabelWithTwoParameters()); }
FunctionTester ft(asm_tester.GenerateCode(), 0);
ft.CheckCall(ft.true_value());
}
TEST(TestPartiallyUnusedLabel) {
Isolate* isolate(CcTest::InitIsolateOnce());
CodeAssemblerTester asm_tester(isolate, 0);
TestTorqueAssembler m(asm_tester.state());
{ m.Return(m.TestPartiallyUnusedLabel()); }
FunctionTester ft(asm_tester.GenerateCode(), 0);
ft.CheckCall(ft.true_value());
}
TEST(TestBuiltinSpecialization) {
Isolate* isolate(CcTest::InitIsolateOnce());
CodeAssemblerTester asm_tester(isolate, 0);
TestTorqueAssembler m(asm_tester.state());
{
TNode<Object> temp = m.SmiConstant(0);
m.TestBuiltinSpecialization(m.UncheckedCast<Context>(temp));
m.Return(m.UndefinedConstant());
}
FunctionTester ft(asm_tester.GenerateCode(), 0);
ft.Call();
}
TEST(TestMacroSpecialization) {
Isolate* isolate(CcTest::InitIsolateOnce());
CodeAssemblerTester asm_tester(isolate, 0);
TestTorqueAssembler m(asm_tester.state());
{
m.TestMacroSpecialization();
m.Return(m.UndefinedConstant());
}
FunctionTester ft(asm_tester.GenerateCode(), 0);
ft.Call();
}
TEST(TestFunctionPointers) {
Isolate* isolate(CcTest::InitIsolateOnce());
const int kNumParams = 0;
CodeAssemblerTester asm_tester(isolate, kNumParams);
TestTorqueAssembler m(asm_tester.state());
{
TNode<Context> context =
m.UncheckedCast<Context>(m.Parameter(kNumParams + 2));
m.Return(m.TestFunctionPointers(context));
}
FunctionTester ft(asm_tester.GenerateCode(), kNumParams);
ft.CheckCall(ft.true_value());
}
TEST(TestTernaryOperator) {
Isolate* isolate(CcTest::InitIsolateOnce());
const int kNumParams = 1;
CodeAssemblerTester asm_tester(isolate, kNumParams);
TestTorqueAssembler m(asm_tester.state());
{
TNode<Smi> arg = m.UncheckedCast<Smi>(m.Parameter(0));
m.Return(m.TestTernaryOperator(arg));
}
FunctionTester ft(asm_tester.GenerateCode(), kNumParams);
Handle<Object> result1 =
ft.Call(Handle<Smi>(Smi::FromInt(-5), isolate)).ToHandleChecked();
CHECK_EQ(-15, Handle<Smi>::cast(result1)->value());
Handle<Object> result2 =
ft.Call(Handle<Smi>(Smi::FromInt(3), isolate)).ToHandleChecked();
CHECK_EQ(103, Handle<Smi>::cast(result2)->value());
}
TEST(TestFunctionPointerToGeneric) {
Isolate* isolate(CcTest::InitIsolateOnce());
CodeAssemblerTester asm_tester(isolate, 0);
TestTorqueAssembler m(asm_tester.state());
{
TNode<Object> temp = m.SmiConstant(0);
m.TestFunctionPointerToGeneric(m.UncheckedCast<Context>(temp));
m.Return(m.UndefinedConstant());
}
FunctionTester ft(asm_tester.GenerateCode(), 0);
ft.Call();
}
TEST(TestUnsafeCast) {
Isolate* isolate(CcTest::InitIsolateOnce());
CodeAssemblerTester asm_tester(isolate, 0);
TestTorqueAssembler m(asm_tester.state());
{
TNode<Object> temp = m.SmiConstant(0);
TNode<Smi> n = m.SmiConstant(10);
m.Return(m.TestUnsafeCast(m.UncheckedCast<Context>(temp),
m.UncheckedCast<Number>(n)));
}
FunctionTester ft(asm_tester.GenerateCode(), 0);
ft.CheckCall(ft.true_value());
}
TEST(TestHexLiteral) {
Isolate* isolate(CcTest::InitIsolateOnce());
CodeAssemblerTester asm_tester(isolate, 0);
TestTorqueAssembler m(asm_tester.state());
{
m.TestHexLiteral();
m.Return(m.UndefinedConstant());
}
FunctionTester ft(asm_tester.GenerateCode(), 0);
ft.Call();
}
TEST(TestModuleConstBindings) {
Isolate* isolate(CcTest::InitIsolateOnce());
CodeAssemblerTester asm_tester(isolate, 0);
TestTorqueAssembler m(asm_tester.state());
{
m.TestModuleConstBindings();
m.Return(m.UndefinedConstant());
}
FunctionTester ft(asm_tester.GenerateCode(), 0);
ft.Call();
}
TEST(TestLocalConstBindings) {
Isolate* isolate(CcTest::InitIsolateOnce());
CodeAssemblerTester asm_tester(isolate, 0);
TestTorqueAssembler m(asm_tester.state());
{
m.TestLocalConstBindings();
m.Return(m.UndefinedConstant());
}
FunctionTester ft(asm_tester.GenerateCode(), 0);
ft.Call();
}
TEST(TestForLoop) {
Isolate* isolate(CcTest::InitIsolateOnce());
CodeAssemblerTester asm_tester(isolate, 0);
TestTorqueAssembler m(asm_tester.state());
{
m.TestForLoop();
m.Return(m.UndefinedConstant());
}
FunctionTester ft(asm_tester.GenerateCode(), 0);
ft.Call();
}
TEST(TestTypeswitch) {
CcTest::InitializeVM();
Isolate* isolate(CcTest::i_isolate());
i::HandleScope scope(isolate);
Handle<Context> context =
Utils::OpenHandle(*v8::Isolate::GetCurrent()->GetCurrentContext());
CodeAssemblerTester asm_tester(isolate, 0);
TestTorqueAssembler m(asm_tester.state());
{
m.TestTypeswitch(m.UncheckedCast<Context>(m.HeapConstant(context)));
m.Return(m.UndefinedConstant());
}
FunctionTester ft(asm_tester.GenerateCode(), 0);
ft.Call();
}
TEST(TestGenericOverload) {
CcTest::InitializeVM();
Isolate* isolate(CcTest::i_isolate());
i::HandleScope scope(isolate);
Handle<Context> context =
Utils::OpenHandle(*v8::Isolate::GetCurrent()->GetCurrentContext());
CodeAssemblerTester asm_tester(isolate, 0);
TestTorqueAssembler m(asm_tester.state());
{
m.TestGenericOverload(m.UncheckedCast<Context>(m.HeapConstant(context)));
m.Return(m.UndefinedConstant());
}
FunctionTester ft(asm_tester.GenerateCode(), 0);
ft.Call();
}
TEST(TestEquality) {
CcTest::InitializeVM();
Isolate* isolate(CcTest::i_isolate());
i::HandleScope scope(isolate);
Handle<Context> context =
Utils::OpenHandle(*v8::Isolate::GetCurrent()->GetCurrentContext());
CodeAssemblerTester asm_tester(isolate, 0);
TestTorqueAssembler m(asm_tester.state());
{
m.TestEquality(m.UncheckedCast<Context>(m.HeapConstant(context)));
m.Return(m.UndefinedConstant());
}
FunctionTester ft(asm_tester.GenerateCode(), 0);
ft.Call();
}
TEST(TestLogicalOperators) {
Isolate* isolate(CcTest::InitIsolateOnce());
CodeAssemblerTester asm_tester(isolate, 0);
TestTorqueAssembler m(asm_tester.state());
{
m.TestLogicalOperators();
m.Return(m.UndefinedConstant());
}
FunctionTester ft(asm_tester.GenerateCode(), 0);
ft.Call();
}
TEST(TestOtherwiseAndLabels) {
Isolate* isolate(CcTest::InitIsolateOnce());
CodeAssemblerTester asm_tester(isolate, 0);
TestTorqueAssembler m(asm_tester.state());
{
m.TestOtherwiseWithCode1();
m.TestOtherwiseWithCode2();
m.TestOtherwiseWithCode3();
m.TestForwardLabel();
m.Return(m.UndefinedConstant());
}
FunctionTester ft(asm_tester.GenerateCode(), 0);
ft.Call();
}
TEST(TestCatch1) {
CcTest::InitializeVM();
Isolate* isolate(CcTest::i_isolate());
i::HandleScope scope(isolate);
Handle<Context> context =
Utils::OpenHandle(*v8::Isolate::GetCurrent()->GetCurrentContext());
CodeAssemblerTester asm_tester(isolate, 0);
TestTorqueAssembler m(asm_tester.state());
{
TNode<Smi> result =
m.TestCatch1(m.UncheckedCast<Context>(m.HeapConstant(context)));
USE(result);
CSA_ASSERT(&m, m.TaggedEqual(result, m.SmiConstant(1)));
m.Return(m.UndefinedConstant());
}
FunctionTester ft(asm_tester.GenerateCode(), 0);
ft.Call();
}
TEST(TestCatch2) {
CcTest::InitializeVM();
Isolate* isolate(CcTest::i_isolate());
i::HandleScope scope(isolate);
Handle<Context> context =
Utils::OpenHandle(*v8::Isolate::GetCurrent()->GetCurrentContext());
CodeAssemblerTester asm_tester(isolate, 0);
TestTorqueAssembler m(asm_tester.state());
{
TNode<Smi> result =
m.TestCatch2(m.UncheckedCast<Context>(m.HeapConstant(context)));
USE(result);
CSA_ASSERT(&m, m.TaggedEqual(result, m.SmiConstant(2)));
m.Return(m.UndefinedConstant());
}
FunctionTester ft(asm_tester.GenerateCode(), 0);
ft.Call();
}
TEST(TestCatch3) {
CcTest::InitializeVM();
Isolate* isolate(CcTest::i_isolate());
i::HandleScope scope(isolate);
Handle<Context> context =
Utils::OpenHandle(*v8::Isolate::GetCurrent()->GetCurrentContext());
CodeAssemblerTester asm_tester(isolate, 0);
TestTorqueAssembler m(asm_tester.state());
{
TNode<Smi> result =
m.TestCatch3(m.UncheckedCast<Context>(m.HeapConstant(context)));
USE(result);
CSA_ASSERT(&m, m.TaggedEqual(result, m.SmiConstant(2)));
m.Return(m.UndefinedConstant());
}
FunctionTester ft(asm_tester.GenerateCode(), 0);
ft.Call();
}
TEST(TestLookup) {
CcTest::InitializeVM();
Isolate* isolate(CcTest::i_isolate());
i::HandleScope scope(isolate);
Handle<Context> context =
Utils::OpenHandle(*v8::Isolate::GetCurrent()->GetCurrentContext());
CodeAssemblerTester asm_tester(isolate, 0);
TestTorqueAssembler m(asm_tester.state());
{
m.TestQualifiedAccess(m.UncheckedCast<Context>(m.HeapConstant(context)));
m.Return(m.UndefinedConstant());
}
FunctionTester ft(asm_tester.GenerateCode(), 0);
ft.Call();
}
TEST(TestFrame1) {
CcTest::InitializeVM();
Isolate* isolate(CcTest::i_isolate());
i::HandleScope scope(isolate);
Handle<Context> context =
Utils::OpenHandle(*v8::Isolate::GetCurrent()->GetCurrentContext());
CodeAssemblerTester asm_tester(isolate);
TestTorqueAssembler m(asm_tester.state());
{
m.TestFrame1(m.UncheckedCast<Context>(m.HeapConstant(context)));
m.Return(m.UndefinedConstant());
}
FunctionTester ft(asm_tester.GenerateCode(), 0);
ft.Call();
}
TEST(TestNew) {
CcTest::InitializeVM();
Isolate* isolate(CcTest::i_isolate());
i::HandleScope scope(isolate);
Handle<Context> context =
Utils::OpenHandle(*v8::Isolate::GetCurrent()->GetCurrentContext());
CodeAssemblerTester asm_tester(isolate);
TestTorqueAssembler m(asm_tester.state());
{
m.TestNew(m.UncheckedCast<Context>(m.HeapConstant(context)));
m.Return(m.UndefinedConstant());
}
FunctionTester ft(asm_tester.GenerateCode(), 0);
ft.Call();
}
TEST(TestStructConstructor) {
CcTest::InitializeVM();
Isolate* isolate(CcTest::i_isolate());
i::HandleScope scope(isolate);
Handle<Context> context =
Utils::OpenHandle(*v8::Isolate::GetCurrent()->GetCurrentContext());
CodeAssemblerTester asm_tester(isolate);
TestTorqueAssembler m(asm_tester.state());
{
m.TestStructConstructor(m.UncheckedCast<Context>(m.HeapConstant(context)));
m.Return(m.UndefinedConstant());
}
FunctionTester ft(asm_tester.GenerateCode(), 0);
ft.Call();
}
TEST(TestInternalClass) {
CcTest::InitializeVM();
Isolate* isolate(CcTest::i_isolate());
i::HandleScope scope(isolate);
Handle<Context> context =
Utils::OpenHandle(*v8::Isolate::GetCurrent()->GetCurrentContext());
CodeAssemblerTester asm_tester(isolate);
TestTorqueAssembler m(asm_tester.state());
{
m.TestInternalClass(m.UncheckedCast<Context>(m.HeapConstant(context)));
m.Return(m.UndefinedConstant());
}
FunctionTester ft(asm_tester.GenerateCode(), 0);
ft.Call();
}
TEST(TestNewFixedArrayFromSpread) {
CcTest::InitializeVM();
Isolate* isolate(CcTest::i_isolate());
i::HandleScope scope(isolate);
Handle<Context> context =
Utils::OpenHandle(*v8::Isolate::GetCurrent()->GetCurrentContext());
CodeAssemblerTester asm_tester(isolate);
TestTorqueAssembler m(asm_tester.state());
{
m.TestNewFixedArrayFromSpread(
m.UncheckedCast<Context>(m.HeapConstant(context)));
m.Return(m.UndefinedConstant());
}
FunctionTester ft(asm_tester.GenerateCode(), 0);
ft.Call();
}
TEST(TestReferences) {
CcTest::InitializeVM();
Isolate* isolate(CcTest::i_isolate());
i::HandleScope scope(isolate);
CodeAssemblerTester asm_tester(isolate);
TestTorqueAssembler m(asm_tester.state());
{
m.TestReferences();
m.Return(m.UndefinedConstant());
}
FunctionTester ft(asm_tester.GenerateCode(), 0);
ft.Call();
}
TEST(TestSlices) {
CcTest::InitializeVM();
Isolate* isolate(CcTest::i_isolate());
i::HandleScope scope(isolate);
CodeAssemblerTester asm_tester(isolate);
TestTorqueAssembler m(asm_tester.state());
{
m.TestSlices();
m.Return(m.UndefinedConstant());
}
FunctionTester ft(asm_tester.GenerateCode(), 0);
ft.Call();
}
TEST(TestSliceEnumeration) {
CcTest::InitializeVM();
Isolate* isolate(CcTest::i_isolate());
i::HandleScope scope(isolate);
Handle<Context> context =
Utils::OpenHandle(*v8::Isolate::GetCurrent()->GetCurrentContext());
CodeAssemblerTester asm_tester(isolate);
TestTorqueAssembler m(asm_tester.state());
{
m.TestSliceEnumeration(m.UncheckedCast<Context>(m.HeapConstant(context)));
m.Return(m.UndefinedConstant());
}
FunctionTester ft(asm_tester.GenerateCode(), 0);
ft.Call();
}
TEST(TestStaticAssert) {
CcTest::InitializeVM();
Isolate* isolate(CcTest::i_isolate());
i::HandleScope scope(isolate);
CodeAssemblerTester asm_tester(isolate);
TestTorqueAssembler m(asm_tester.state());
{
m.TestStaticAssert();
m.Return(m.UndefinedConstant());
}
FunctionTester ft(asm_tester.GenerateCode(), 0);
ft.Call();
}
TEST(TestLoadEliminationFixed) {
CcTest::InitializeVM();
Isolate* isolate(CcTest::i_isolate());
i::HandleScope scope(isolate);
Handle<Context> context =
Utils::OpenHandle(*v8::Isolate::GetCurrent()->GetCurrentContext());
CodeAssemblerTester asm_tester(isolate);
TestTorqueAssembler m(asm_tester.state());
{
m.TestLoadEliminationFixed(
m.UncheckedCast<Context>(m.HeapConstant(context)));
m.Return(m.UndefinedConstant());
}
asm_tester.GenerateCode();
}
TEST(TestLoadEliminationVariable) {
CcTest::InitializeVM();
Isolate* isolate(CcTest::i_isolate());
i::HandleScope scope(isolate);
Handle<Context> context =
Utils::OpenHandle(*v8::Isolate::GetCurrent()->GetCurrentContext());
CodeAssemblerTester asm_tester(isolate);
TestTorqueAssembler m(asm_tester.state());
{
m.TestLoadEliminationVariable(
m.UncheckedCast<Context>(m.HeapConstant(context)));
m.Return(m.UndefinedConstant());
}
asm_tester.GenerateCode();
}
TEST(TestRedundantArrayElementCheck) {
CcTest::InitializeVM();
Isolate* isolate(CcTest::i_isolate());
i::HandleScope scope(isolate);
Handle<Context> context =
Utils::OpenHandle(*v8::Isolate::GetCurrent()->GetCurrentContext());
CodeAssemblerTester asm_tester(isolate);
TestTorqueAssembler m(asm_tester.state());
{
m.Return(m.TestRedundantArrayElementCheck(
m.UncheckedCast<Context>(m.HeapConstant(context))));
}
asm_tester.GenerateCode();
}
TEST(TestRedundantSmiCheck) {
CcTest::InitializeVM();
Isolate* isolate(CcTest::i_isolate());
i::HandleScope scope(isolate);
Handle<Context> context =
Utils::OpenHandle(*v8::Isolate::GetCurrent()->GetCurrentContext());
CodeAssemblerTester asm_tester(isolate);
TestTorqueAssembler m(asm_tester.state());
{
m.Return(m.TestRedundantSmiCheck(
m.UncheckedCast<Context>(m.HeapConstant(context))));
}
asm_tester.GenerateCode();
}
TEST(TestGenericStruct1) {
CcTest::InitializeVM();
Isolate* isolate(CcTest::i_isolate());
i::HandleScope scope(isolate);
CodeAssemblerTester asm_tester(isolate);
TestTorqueAssembler m(asm_tester.state());
{
m.TestGenericStruct1();
m.Return(m.UndefinedConstant());
}
FunctionTester ft(asm_tester.GenerateCode(), 0);
ft.Call();
}
TEST(TestGenericStruct2) {
CcTest::InitializeVM();
Isolate* isolate(CcTest::i_isolate());
i::HandleScope scope(isolate);
CodeAssemblerTester asm_tester(isolate);
TestTorqueAssembler m(asm_tester.state());
{ m.Return(m.TestGenericStruct2().snd.fst); }
FunctionTester ft(asm_tester.GenerateCode(), 0);
ft.Call();
}
TEST(TestBranchOnBoolOptimization) {
CcTest::InitializeVM();
Isolate* isolate(CcTest::i_isolate());
i::HandleScope scope(isolate);
Handle<Context> context =
Utils::OpenHandle(*v8::Isolate::GetCurrent()->GetCurrentContext());
CodeAssemblerTester asm_tester(isolate, 1);
TestTorqueAssembler m(asm_tester.state());
{
m.TestBranchOnBoolOptimization(
m.UncheckedCast<Context>(m.HeapConstant(context)),
m.UncheckedCast<Smi>(m.Parameter(0)));
m.Return(m.UndefinedConstant());
}
asm_tester.GenerateCode();
}
TEST(TestBitFieldLoad) {
CcTest::InitializeVM();
Isolate* isolate(CcTest::i_isolate());
i::HandleScope scope(isolate);
const int kNumParams = 5;
CodeAssemblerTester asm_tester(isolate, kNumParams);
TestTorqueAssembler m(asm_tester.state());
{
// Untag all of the parameters to get plain integer values.
TNode<Uint8T> val =
m.UncheckedCast<Uint8T>(m.Unsigned(m.SmiToInt32(m.Parameter(0))));
TNode<BoolT> expected_a =
m.UncheckedCast<BoolT>(m.Unsigned(m.SmiToInt32(m.Parameter(1))));
TNode<Uint16T> expected_b =
m.UncheckedCast<Uint16T>(m.Unsigned(m.SmiToInt32(m.Parameter(2))));
TNode<Uint32T> expected_c =
m.UncheckedCast<Uint32T>(m.Unsigned(m.SmiToInt32(m.Parameter(3))));
TNode<BoolT> expected_d =
m.UncheckedCast<BoolT>(m.Unsigned(m.SmiToInt32(m.Parameter(4))));
// Call the Torque-defined macro, which verifies that reading each bitfield
// out of val yields the correct result.
m.TestBitFieldLoad(val, expected_a, expected_b, expected_c, expected_d);
m.Return(m.UndefinedConstant());
}
FunctionTester ft(asm_tester.GenerateCode(), kNumParams);
// Test every possible bit combination for this 8-bit value.
for (int a = 0; a <= 1; ++a) {
for (int b = 0; b <= 7; ++b) {
for (int c = 0; c <= 7; ++c) {
for (int d = 0; d <= 1; ++d) {
int val = a | ((b & 7) << 1) | (c << 4) | (d << 7);
ft.Call(ft.Val(val), ft.Val(a), ft.Val(b), ft.Val(c), ft.Val(d));
}
}
}
}
}
TEST(TestBitFieldStore) {
CcTest::InitializeVM();
Isolate* isolate(CcTest::i_isolate());
i::HandleScope scope(isolate);
const int kNumParams = 1;
CodeAssemblerTester asm_tester(isolate, kNumParams);
TestTorqueAssembler m(asm_tester.state());
{
// Untag the parameters to get a plain integer value.
TNode<Uint8T> val =
m.UncheckedCast<Uint8T>(m.Unsigned(m.SmiToInt32(m.Parameter(0))));
m.TestBitFieldStore(val);
m.Return(m.UndefinedConstant());
}
FunctionTester ft(asm_tester.GenerateCode(), kNumParams);
// Test every possible bit combination for this 8-bit value.
for (int i = 0; i < 256; ++i) {
ft.Call(ft.Val(i));
}
}
TEST(TestBitFieldUintptrOps) {
CcTest::InitializeVM();
Isolate* isolate(CcTest::i_isolate());
i::HandleScope scope(isolate);
const int kNumParams = 2;
CodeAssemblerTester asm_tester(isolate, kNumParams);
TestTorqueAssembler m(asm_tester.state());
{
// Untag the parameters to get a plain integer value.
TNode<Uint32T> val2 =
m.UncheckedCast<Uint32T>(m.Unsigned(m.SmiToInt32(m.Parameter(0))));
TNode<UintPtrT> val3 = m.UncheckedCast<UintPtrT>(
m.ChangeUint32ToWord(m.Unsigned(m.SmiToInt32(m.Parameter(1)))));
m.TestBitFieldUintptrOps(val2, val3);
m.Return(m.UndefinedConstant());
}
FunctionTester ft(asm_tester.GenerateCode(), kNumParams);
// Construct the expected test values.
int val2 = 3 | (61 << 5);
int val3 = 1 | (500 << 1) | (0x1cc << 10);
ft.Call(ft.Val(val2), ft.Val(val3));
}
TEST(TestTestParentFrameArguments) {
CcTest::InitializeVM();
Isolate* isolate(CcTest::i_isolate());
i::HandleScope scope(isolate);
Handle<Context> context =
Utils::OpenHandle(*v8::Isolate::GetCurrent()->GetCurrentContext());
CodeAssemblerTester asm_tester(isolate, 1);
TestTorqueAssembler m(asm_tester.state());
{
m.TestParentFrameArguments(
m.UncheckedCast<Context>(m.HeapConstant(context)));
m.Return(m.UndefinedConstant());
}
asm_tester.GenerateCode();
}
TEST(TestFullyGeneratedClassFromCpp) {
CcTest::InitializeVM();
Isolate* isolate(CcTest::i_isolate());
i::HandleScope scope(isolate);
CodeAssemblerTester asm_tester(isolate, 1);
TestTorqueAssembler m(asm_tester.state());
{ m.Return(m.TestFullyGeneratedClassFromCpp()); }
FunctionTester ft(asm_tester.GenerateCode(), 0);
Handle<ExportedSubClass> result =
Handle<ExportedSubClass>::cast(ft.Call().ToHandleChecked());
CHECK_EQ(result->c_field(), 7);
CHECK_EQ(result->d_field(), 8);
CHECK_EQ(Smi::ToInt(result->e_field()), 9);
}
TEST(TestFullyGeneratedClassWithElements) {
CcTest::InitializeVM();
Isolate* isolate(CcTest::i_isolate());
i::HandleScope scope(isolate);
CodeAssemblerTester asm_tester(isolate, 1);
TestTorqueAssembler m(asm_tester.state());
{
m.TestFullyGeneratedClassWithElements();
m.Return(m.UndefinedConstant());
}
FunctionTester ft(asm_tester.GenerateCode(), 0);
ft.Call();
}
} // namespace compiler
} // namespace internal
} // namespace v8
|
#include "sendcoinsdialog.h"
#include "ui_sendcoinsdialog.h"
#include "init.h"
#include "walletmodel.h"
#include "addresstablemodel.h"
#include "bitcoinunits.h"
#include "addressbookpage.h"
#include "optionsmodel.h"
#include "sendcoinsentry.h"
#include "guiutil.h"
#include "askpassphrasedialog.h"
#include "coincontrol.h"
#include "coincontroldialog.h"
#include <QMessageBox>
#include <QTextDocument>
#include <QScrollBar>
#include <QClipboard>
SendCoinsDialog::SendCoinsDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::SendCoinsDialog),
model(0)
{
ui->setupUi(this);
#ifdef Q_OS_MAC // Icons on push buttons are very uncommon on Mac
ui->addButton->setIcon(QIcon());
ui->clearButton->setIcon(QIcon());
ui->sendButton->setIcon(QIcon());
#endif
#if QT_VERSION >= 0x040700
/* Do not move this to the XML file, Qt before 4.7 will choke on it */
ui->lineEditCoinControlChange->setPlaceholderText(tr("Enter a Genesiscoin address (e.g. EQsabeCxbbdjoQE4d2VJeTvPqK4RJj1sMo)"));
#endif
addEntry();
connect(ui->addButton, SIGNAL(clicked()), this, SLOT(addEntry()));
connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear()));
// Coin Control
ui->lineEditCoinControlChange->setFont(GUIUtil::bitcoinAddressFont());
connect(ui->pushButtonCoinControl, SIGNAL(clicked()), this, SLOT(coinControlButtonClicked()));
connect(ui->checkBoxCoinControlChange, SIGNAL(stateChanged(int)), this, SLOT(coinControlChangeChecked(int)));
connect(ui->lineEditCoinControlChange, SIGNAL(textEdited(const QString &)), this, SLOT(coinControlChangeEdited(const QString &)));
// Coin Control: clipboard actions
QAction *clipboardQuantityAction = new QAction(tr("Copy quantity"), this);
QAction *clipboardAmountAction = new QAction(tr("Copy amount"), this);
QAction *clipboardFeeAction = new QAction(tr("Copy fee"), this);
QAction *clipboardAfterFeeAction = new QAction(tr("Copy after fee"), this);
QAction *clipboardBytesAction = new QAction(tr("Copy bytes"), this);
QAction *clipboardPriorityAction = new QAction(tr("Copy priority"), this);
QAction *clipboardLowOutputAction = new QAction(tr("Copy low output"), this);
QAction *clipboardChangeAction = new QAction(tr("Copy change"), this);
connect(clipboardQuantityAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardQuantity()));
connect(clipboardAmountAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardAmount()));
connect(clipboardFeeAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardFee()));
connect(clipboardAfterFeeAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardAfterFee()));
connect(clipboardBytesAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardBytes()));
connect(clipboardPriorityAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardPriority()));
connect(clipboardLowOutputAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardLowOutput()));
connect(clipboardChangeAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardChange()));
ui->labelCoinControlQuantity->addAction(clipboardQuantityAction);
ui->labelCoinControlAmount->addAction(clipboardAmountAction);
ui->labelCoinControlFee->addAction(clipboardFeeAction);
ui->labelCoinControlAfterFee->addAction(clipboardAfterFeeAction);
ui->labelCoinControlBytes->addAction(clipboardBytesAction);
ui->labelCoinControlPriority->addAction(clipboardPriorityAction);
ui->labelCoinControlLowOutput->addAction(clipboardLowOutputAction);
ui->labelCoinControlChange->addAction(clipboardChangeAction);
fNewRecipientAllowed = true;
}
void SendCoinsDialog::setModel(WalletModel *model)
{
this->model = model;
for(int i = 0; i < ui->entries->count(); ++i)
{
SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
if(entry)
{
entry->setModel(model);
}
}
if(model && model->getOptionsModel())
{
setBalance(model->getBalance(), model->getUnconfirmedBalance(), model->getImmatureBalance());
connect(model, SIGNAL(balanceChanged(qint64, qint64, qint64)), this, SLOT(setBalance(qint64, qint64, qint64)));
connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
// Coin Control
connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(coinControlUpdateLabels()));
connect(model->getOptionsModel(), SIGNAL(coinControlFeaturesChanged(bool)), this, SLOT(coinControlFeatureChanged(bool)));
connect(model->getOptionsModel(), SIGNAL(transactionFeeChanged(qint64)), this, SLOT(coinControlUpdateLabels()));
ui->frameCoinControl->setVisible(model->getOptionsModel()->getCoinControlFeatures());
coinControlUpdateLabels();
}
}
SendCoinsDialog::~SendCoinsDialog()
{
delete ui;
}
void SendCoinsDialog::on_sendButton_clicked()
{
QList<SendCoinsRecipient> recipients;
bool valid = true;
if(!model)
return;
for(int i = 0; i < ui->entries->count(); ++i)
{
SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
if(entry)
{
if(entry->validate())
{
recipients.append(entry->getValue());
}
else
{
valid = false;
}
}
}
if(!valid || recipients.isEmpty())
{
return;
}
// Format confirmation message
QStringList formatted;
foreach(const SendCoinsRecipient &rcp, recipients)
{
#if QT_VERSION < 0x050000
formatted.append(tr("<b>%1</b> to %2 (%3)").arg(BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, rcp.amount), Qt::escape(rcp.label), rcp.address));
#else
formatted.append(tr("<b>%1</b> to %2 (%3)").arg(BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, rcp.amount), rcp.label.toHtmlEscaped(), rcp.address));
#endif
}
fNewRecipientAllowed = false;
QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm send coins"),
tr("Are you sure you want to send %1?").arg(formatted.join(tr(" and "))),
QMessageBox::Yes|QMessageBox::Cancel,
QMessageBox::Cancel);
if(retval != QMessageBox::Yes)
{
fNewRecipientAllowed = true;
return;
}
WalletModel::UnlockContext ctx(model->requestUnlock());
if(!ctx.isValid())
{
// Unlock wallet was cancelled
fNewRecipientAllowed = true;
return;
}
WalletModel::SendCoinsReturn sendstatus;
if (!model->getOptionsModel() || !model->getOptionsModel()->getCoinControlFeatures())
sendstatus = model->sendCoins(recipients);
else
sendstatus = model->sendCoins(recipients, CoinControlDialog::coinControl);
switch(sendstatus.status)
{
case WalletModel::InvalidAddress:
QMessageBox::warning(this, tr("Send Coins"),
tr("The recipient address is not valid, please recheck."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::InvalidAmount:
QMessageBox::warning(this, tr("Send Coins"),
tr("The amount to pay must be larger than 0."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::AmountExceedsBalance:
QMessageBox::warning(this, tr("Send Coins"),
tr("The amount exceeds your balance."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::AmountWithFeeExceedsBalance:
QMessageBox::warning(this, tr("Send Coins"),
tr("The total exceeds your balance when the %1 transaction fee is included.").
arg(BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, sendstatus.fee)),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::DuplicateAddress:
QMessageBox::warning(this, tr("Send Coins"),
tr("Duplicate address found, can only send to each address once per send operation."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::TransactionCreationFailed:
QMessageBox::warning(this, tr("Send Coins"),
tr("Error: Transaction creation failed!"),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::TransactionCommitFailed:
QMessageBox::warning(this, tr("Send Coins"),
tr("Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::Aborted: // User aborted, nothing to do
break;
case WalletModel::OK:
accept();
CoinControlDialog::coinControl->UnSelectAll();
coinControlUpdateLabels();
break;
}
fNewRecipientAllowed = true;
}
void SendCoinsDialog::clear()
{
// Remove entries until only one left
while(ui->entries->count())
{
ui->entries->takeAt(0)->widget()->deleteLater();
}
addEntry();
updateRemoveEnabled();
ui->sendButton->setDefault(true);
}
void SendCoinsDialog::reject()
{
clear();
}
void SendCoinsDialog::accept()
{
clear();
}
SendCoinsEntry *SendCoinsDialog::addEntry()
{
SendCoinsEntry *entry = new SendCoinsEntry(this);
entry->setModel(model);
ui->entries->addWidget(entry);
connect(entry, SIGNAL(removeEntry(SendCoinsEntry*)), this, SLOT(removeEntry(SendCoinsEntry*)));
connect(entry, SIGNAL(payAmountChanged()), this, SLOT(coinControlUpdateLabels()));
updateRemoveEnabled();
// Focus the field, so that entry can start immediately
entry->clear();
entry->setFocus();
ui->scrollAreaWidgetContents->resize(ui->scrollAreaWidgetContents->sizeHint());
qApp->processEvents();
QScrollBar* bar = ui->scrollArea->verticalScrollBar();
if(bar)
bar->setSliderPosition(bar->maximum());
return entry;
}
void SendCoinsDialog::updateRemoveEnabled()
{
// Remove buttons are enabled as soon as there is more than one send-entry
bool enabled = (ui->entries->count() > 1);
for(int i = 0; i < ui->entries->count(); ++i)
{
SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
if(entry)
{
entry->setRemoveEnabled(enabled);
}
}
setupTabChain(0);
coinControlUpdateLabels();
}
void SendCoinsDialog::removeEntry(SendCoinsEntry* entry)
{
entry->deleteLater();
updateRemoveEnabled();
}
QWidget *SendCoinsDialog::setupTabChain(QWidget *prev)
{
for(int i = 0; i < ui->entries->count(); ++i)
{
SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
if(entry)
{
prev = entry->setupTabChain(prev);
}
}
QWidget::setTabOrder(prev, ui->addButton);
QWidget::setTabOrder(ui->addButton, ui->sendButton);
return ui->sendButton;
}
void SendCoinsDialog::setAddress(const QString &address)
{
SendCoinsEntry *entry = 0;
// Replace the first entry if it is still unused
if(ui->entries->count() == 1)
{
SendCoinsEntry *first = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(0)->widget());
if(first->isClear())
{
entry = first;
}
}
if(!entry)
{
entry = addEntry();
}
entry->setAddress(address);
}
void SendCoinsDialog::pasteEntry(const SendCoinsRecipient &rv)
{
if(!fNewRecipientAllowed)
return;
SendCoinsEntry *entry = 0;
// Replace the first entry if it is still unused
if(ui->entries->count() == 1)
{
SendCoinsEntry *first = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(0)->widget());
if(first->isClear())
{
entry = first;
}
}
if(!entry)
{
entry = addEntry();
}
entry->setValue(rv);
}
bool SendCoinsDialog::handleURI(const QString &uri)
{
SendCoinsRecipient rv;
// URI has to be valid
if (GUIUtil::parseBitcoinURI(uri, &rv))
{
CBitcoinAddress address(rv.address.toStdString());
if (!address.IsValid())
return false;
pasteEntry(rv);
return true;
}
return false;
}
void SendCoinsDialog::setBalance(qint64 balance, qint64 unconfirmedBalance, qint64 immatureBalance)
{
Q_UNUSED(unconfirmedBalance);
Q_UNUSED(immatureBalance);
if(!model || !model->getOptionsModel())
return;
int unit = model->getOptionsModel()->getDisplayUnit();
ui->labelBalance->setText(BitcoinUnits::formatWithUnit(unit, balance));
}
void SendCoinsDialog::updateDisplayUnit()
{
if(model && model->getOptionsModel())
{
// Update labelBalance with the current balance and the current unit
ui->labelBalance->setText(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), model->getBalance()));
}
}
// Coin Control: copy label "Quantity" to clipboard
void SendCoinsDialog::coinControlClipboardQuantity()
{
GUIUtil::setClipboard(ui->labelCoinControlQuantity->text());
}
// Coin Control: copy label "Amount" to clipboard
void SendCoinsDialog::coinControlClipboardAmount()
{
GUIUtil::setClipboard(ui->labelCoinControlAmount->text().left(ui->labelCoinControlAmount->text().indexOf(" ")));
}
// Coin Control: copy label "Fee" to clipboard
void SendCoinsDialog::coinControlClipboardFee()
{
GUIUtil::setClipboard(ui->labelCoinControlFee->text().left(ui->labelCoinControlFee->text().indexOf(" ")));
}
// Coin Control: copy label "After fee" to clipboard
void SendCoinsDialog::coinControlClipboardAfterFee()
{
GUIUtil::setClipboard(ui->labelCoinControlAfterFee->text().left(ui->labelCoinControlAfterFee->text().indexOf(" ")));
}
// Coin Control: copy label "Bytes" to clipboard
void SendCoinsDialog::coinControlClipboardBytes()
{
GUIUtil::setClipboard(ui->labelCoinControlBytes->text());
}
// Coin Control: copy label "Priority" to clipboard
void SendCoinsDialog::coinControlClipboardPriority()
{
GUIUtil::setClipboard(ui->labelCoinControlPriority->text());
}
// Coin Control: copy label "Low output" to clipboard
void SendCoinsDialog::coinControlClipboardLowOutput()
{
GUIUtil::setClipboard(ui->labelCoinControlLowOutput->text());
}
// Coin Control: copy label "Change" to clipboard
void SendCoinsDialog::coinControlClipboardChange()
{
GUIUtil::setClipboard(ui->labelCoinControlChange->text().left(ui->labelCoinControlChange->text().indexOf(" ")));
}
// Coin Control: settings menu - coin control enabled/disabled by user
void SendCoinsDialog::coinControlFeatureChanged(bool checked)
{
ui->frameCoinControl->setVisible(checked);
if (!checked && model) // coin control features disabled
CoinControlDialog::coinControl->SetNull();
}
// Coin Control: button inputs -> show actual coin control dialog
void SendCoinsDialog::coinControlButtonClicked()
{
CoinControlDialog dlg;
dlg.setModel(model);
dlg.exec();
coinControlUpdateLabels();
}
// Coin Control: checkbox custom change address
void SendCoinsDialog::coinControlChangeChecked(int state)
{
if (model)
{
if (state == Qt::Checked)
CoinControlDialog::coinControl->destChange = CBitcoinAddress(ui->lineEditCoinControlChange->text().toStdString()).Get();
else
CoinControlDialog::coinControl->destChange = CNoDestination();
}
ui->lineEditCoinControlChange->setEnabled((state == Qt::Checked));
ui->labelCoinControlChangeLabel->setVisible((state == Qt::Checked));
}
// Coin Control: custom change address changed
void SendCoinsDialog::coinControlChangeEdited(const QString & text)
{
if (model)
{
CoinControlDialog::coinControl->destChange = CBitcoinAddress(text.toStdString()).Get();
// label for the change address
ui->labelCoinControlChangeLabel->setStyleSheet("QLabel{color:black;}");
if (text.isEmpty())
ui->labelCoinControlChangeLabel->setText("");
else if (!CBitcoinAddress(text.toStdString()).IsValid())
{
ui->labelCoinControlChangeLabel->setStyleSheet("QLabel{color:red;}");
ui->labelCoinControlChangeLabel->setText(tr("Warning: Invalid Bitcoin address"));
}
else
{
QString associatedLabel = model->getAddressTableModel()->labelForAddress(text);
if (!associatedLabel.isEmpty())
ui->labelCoinControlChangeLabel->setText(associatedLabel);
else
{
CPubKey pubkey;
CKeyID keyid;
CBitcoinAddress(text.toStdString()).GetKeyID(keyid);
if (model->getPubKey(keyid, pubkey))
ui->labelCoinControlChangeLabel->setText(tr("(no label)"));
else
{
ui->labelCoinControlChangeLabel->setStyleSheet("QLabel{color:red;}");
ui->labelCoinControlChangeLabel->setText(tr("Warning: Unknown change address"));
}
}
}
}
}
// Coin Control: update labels
void SendCoinsDialog::coinControlUpdateLabels()
{
if (!model || !model->getOptionsModel() || !model->getOptionsModel()->getCoinControlFeatures())
return;
// set pay amounts
CoinControlDialog::payAmounts.clear();
for(int i = 0; i < ui->entries->count(); ++i)
{
SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
if(entry)
CoinControlDialog::payAmounts.append(entry->getValue().amount);
}
if (CoinControlDialog::coinControl->HasSelected())
{
// actual coin control calculation
CoinControlDialog::updateLabels(model, this);
// show coin control stats
ui->labelCoinControlAutomaticallySelected->hide();
ui->widgetCoinControl->show();
}
else
{
// hide coin control stats
ui->labelCoinControlAutomaticallySelected->show();
ui->widgetCoinControl->hide();
ui->labelCoinControlInsuffFunds->hide();
}
}
|
/*
* 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/dataworks-public/model/UpdateNodeOwnerResult.h>
#include <json/json.h>
using namespace AlibabaCloud::Dataworks_public;
using namespace AlibabaCloud::Dataworks_public::Model;
UpdateNodeOwnerResult::UpdateNodeOwnerResult() :
ServiceResult()
{}
UpdateNodeOwnerResult::UpdateNodeOwnerResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
UpdateNodeOwnerResult::~UpdateNodeOwnerResult()
{}
void UpdateNodeOwnerResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
if(!value["Success"].isNull())
success_ = value["Success"].asString() == "true";
}
bool UpdateNodeOwnerResult::getSuccess()const
{
return success_;
}
|
/*
* Copyright (C) 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.
*/
#include <gtest/gtest.h>
#include "fg/FrameGraph.h"
#include "fg/FrameGraphPassResources.h"
#include "fg/ResourceAllocator.h"
#include <backend/Platform.h>
#include "private/backend/CommandStream.h"
using namespace filament;
using namespace backend;
static CircularBuffer buffer(8192);
static Backend gBackend = Backend::NOOP;
static DefaultPlatform* platform = DefaultPlatform::create(&gBackend);
static CommandStream driverApi(*platform->createDriver(nullptr), buffer);
class MockResourceAllocator : public fg::ResourceAllocatorInterface {
uint32_t handle = 0;
public:
backend::RenderTargetHandle createRenderTarget(const char* name,
backend::TargetBufferFlags targetBufferFlags,
uint32_t width,
uint32_t height,
uint8_t samples,
backend::MRT color,
backend::TargetBufferInfo depth,
backend::TargetBufferInfo stencil) noexcept override {
return backend::RenderTargetHandle(++handle);
}
void destroyRenderTarget(backend::RenderTargetHandle h) noexcept override {
}
backend::TextureHandle createTexture(const char* name, backend::SamplerType target,
uint8_t levels,
backend::TextureFormat format, uint8_t samples, uint32_t width, uint32_t height,
uint32_t depth, backend::TextureUsage usage) noexcept override {
return backend::TextureHandle(++handle);
}
void destroyTexture(backend::TextureHandle h) noexcept override {
}
};
struct GenericResource {
struct Descriptor {};
void create(FrameGraph& fg, const char* name, Descriptor const& desc) noexcept {
id = ++state;
}
void destroy(FrameGraph& fg) noexcept {}
int id = 0;
private:
static int state;
};
int GenericResource::state = 0;
TEST(FrameGraphTest, SimpleRenderPass) {
fg::ResourceAllocator resourceAllocator(driverApi);
FrameGraph fg(resourceAllocator);
bool renderPassExecuted = false;
struct RenderPassData {
FrameGraphId<FrameGraphTexture> output;
FrameGraphRenderTargetHandle rt;
};
auto& renderPass = fg.addPass<RenderPassData>("Render",
[&](FrameGraph::Builder& builder, auto& data) {
FrameGraphTexture::Descriptor desc{ .format = TextureFormat::RGBA16F };
data.output = builder.createTexture("color buffer", desc);
data.output = builder.write(data.output);
data.rt = builder.createRenderTarget("color buffer", {
.attachments = { data.output } });
// rendertargets are weird...
// A) reading from an attachment is equivalent to reading from the RT
// so any reads on any attachment should trigger a read on the RT,
// meaning the RT can't be culled.
// Or maybe, there should be a .use(RT) to declare it's going to be used
// in that pass.
// B) writing to a RT, should propagate to its attachments, but then, how
// is the new attachment value returned??
// maybe it's a special type of write that doesn't change the version??
// or maybe we require writes to be set on the resource.
EXPECT_TRUE(fg.isValid(data.output));
EXPECT_TRUE(fg.isValid(data.rt));
},
[=, &renderPassExecuted](FrameGraphPassResources const& resources,
auto const& data, DriverApi& driver) {
renderPassExecuted = true;
auto const& rt = resources.get(data.rt);
EXPECT_TRUE(rt.target);
EXPECT_EQ(TargetBufferFlags::COLOR, rt.params.flags.discardStart);
EXPECT_EQ(TargetBufferFlags::NONE, rt.params.flags.discardEnd);
});
fg.present(renderPass.getData().output); // TODO: this should trigger a read() on the RT
fg.compile();
fg.execute(driverApi);
EXPECT_TRUE(renderPassExecuted);
resourceAllocator.terminate();
}
TEST(FrameGraphTest, SimpleRenderPass2) {
fg::ResourceAllocator resourceAllocator(driverApi);
FrameGraph fg(resourceAllocator);
bool renderPassExecuted = false;
struct RenderPassData {
FrameGraphId<FrameGraphTexture> outColor;
FrameGraphId<FrameGraphTexture> outDepth;
FrameGraphRenderTargetHandle rt;
};
auto& renderPass = fg.addPass<RenderPassData>("Render",
[&](FrameGraph::Builder& builder, auto& data) {
data.outColor = builder.createTexture("color buffer",
{ .format = TextureFormat::RGBA16F });
data.outDepth = builder.createTexture("depth buffer",
{ .format = TextureFormat::DEPTH24 });
data.outColor = builder.write(builder.read(data.outColor));
data.outDepth = builder.write(builder.read(data.outDepth));
data.rt = builder.createRenderTarget("rt", {
.attachments = { data.outColor, data.outDepth }
});
EXPECT_TRUE(fg.isValid(data.outColor));
EXPECT_TRUE(fg.isValid(data.outDepth));
EXPECT_TRUE(fg.isValid(data.rt));
},
[=, &renderPassExecuted](FrameGraphPassResources const& resources,
auto const& data, DriverApi& driver) {
renderPassExecuted = true;
auto const& rt = resources.get(data.rt);
EXPECT_TRUE(rt.target);
EXPECT_EQ(TargetBufferFlags::COLOR0 | TargetBufferFlags::DEPTH, rt.params.flags.discardStart);
EXPECT_EQ(TargetBufferFlags::NONE, rt.params.flags.discardEnd);
});
fg.present(renderPass.getData().outColor);
fg.present(renderPass.getData().outDepth);
fg.compile();
fg.execute(driverApi);
EXPECT_TRUE(renderPassExecuted);
resourceAllocator.terminate();
}
TEST(FrameGraphTest, ScenarioDepthPrePass) {
fg::ResourceAllocator resourceAllocator(driverApi);
FrameGraph fg(resourceAllocator);
bool depthPrepassExecuted = false;
bool colorPassExecuted = false;
struct DepthPrepassData {
FrameGraphId<FrameGraphTexture> outDepth;
FrameGraphRenderTargetHandle rt;
};
auto& depthPrepass = fg.addPass<DepthPrepassData>("depth prepass",
[&](FrameGraph::Builder& builder, auto& data) {
data.outDepth = builder.createTexture("depth buffer",
{ .format = TextureFormat::DEPTH24 });
data.outDepth = builder.write(builder.read(data.outDepth));
data.rt = builder.createRenderTarget("rt depth", {
.attachments = {{}, data.outDepth }
});
EXPECT_TRUE(fg.isValid(data.outDepth));
EXPECT_TRUE(fg.isValid(data.rt));
},
[=, &depthPrepassExecuted](FrameGraphPassResources const& resources,
auto const& data, DriverApi& driver) {
depthPrepassExecuted = true;
auto const& rt = resources.get(data.rt);
EXPECT_TRUE(rt.target);
EXPECT_EQ(TargetBufferFlags::DEPTH, rt.params.flags.discardStart);
EXPECT_EQ(TargetBufferFlags::NONE, rt.params.flags.discardEnd);
});
struct ColorPassData {
FrameGraphId<FrameGraphTexture> outColor;
FrameGraphId<FrameGraphTexture> outDepth;
FrameGraphRenderTargetHandle rt;
};
auto& colorPass = fg.addPass<ColorPassData>("color pass",
[&](FrameGraph::Builder& builder, auto& data) {
data.outColor = builder.createTexture("color buffer",
{ .format = TextureFormat::RGBA16F });
// declare a read here, so a reference is added to the previous pass
data.outDepth = depthPrepass.getData().outDepth;
data.outColor = builder.write(builder.read(data.outColor));
data.outDepth = builder.write(builder.read(data.outDepth));
data.rt = builder.createRenderTarget("rt color+depth", {
.attachments = { data.outColor, data.outDepth }
});
EXPECT_FALSE(fg.isValid(depthPrepass.getData().outDepth));
EXPECT_TRUE(fg.isValid(data.outColor));
EXPECT_TRUE(fg.isValid(data.outDepth));
EXPECT_TRUE(fg.isValid(data.rt));
},
[=, &colorPassExecuted](FrameGraphPassResources const& resources,
auto const& data, DriverApi& driver) {
colorPassExecuted = true;
auto const& rt = resources.get(data.rt);
EXPECT_TRUE(rt.target);
EXPECT_EQ(TargetBufferFlags::COLOR, rt.params.flags.discardStart);
EXPECT_EQ(TargetBufferFlags::DEPTH, rt.params.flags.discardEnd);
});
fg.present(colorPass.getData().outColor);
fg.compile();
fg.execute(driverApi);
EXPECT_TRUE(depthPrepassExecuted);
EXPECT_TRUE(colorPassExecuted);
resourceAllocator.terminate();
}
TEST(FrameGraphTest, SimplePassCulling) {
fg::ResourceAllocator resourceAllocator(driverApi);
FrameGraph fg(resourceAllocator);
bool renderPassExecuted = false;
bool postProcessPassExecuted = false;
bool culledPassExecuted = false;
struct RenderPassData {
FrameGraphId<FrameGraphTexture> output;
FrameGraphRenderTargetHandle rt;
};
auto& renderPass = fg.addPass<RenderPassData>("Render",
[&](FrameGraph::Builder& builder, auto& data) {
data.output = builder.createTexture("renderTarget");
data.output = builder.write(data.output);
data.rt = builder.createRenderTarget("renderTarget", {
.attachments = { data.output }
});
EXPECT_TRUE(fg.isValid(data.output));
EXPECT_TRUE(fg.isValid(data.rt));
},
[=, &renderPassExecuted](FrameGraphPassResources const& resources,
auto const& data, backend::DriverApi& driver) {
renderPassExecuted = true;
auto const& rt = resources.get(data.rt);
EXPECT_TRUE(rt.target);
EXPECT_EQ(TargetBufferFlags::COLOR, rt.params.flags.discardStart);
EXPECT_EQ(TargetBufferFlags::NONE, rt.params.flags.discardEnd);
});
struct PostProcessPassData {
FrameGraphId<FrameGraphTexture> input;
FrameGraphId<FrameGraphTexture> output;
FrameGraphRenderTargetHandle rt;
};
auto& postProcessPass = fg.addPass<PostProcessPassData>("PostProcess",
[&](FrameGraph::Builder& builder, auto& data) {
data.input = builder.sample(renderPass.getData().output);
data.output = builder.createTexture("postprocess-renderTarget");
data.output = builder.write(data.output);
data.rt = builder.createRenderTarget("postprocess-renderTarget",{
.attachments = { data.output }
});
EXPECT_TRUE(fg.isValid(data.input));
EXPECT_TRUE(fg.isValid(data.output));
EXPECT_TRUE(fg.isValid(data.rt));
},
[=, &postProcessPassExecuted](FrameGraphPassResources const& resources,
auto const& data, backend::DriverApi& driver) {
postProcessPassExecuted = true;
auto const& rt = resources.get(data.rt);
EXPECT_TRUE(rt.target);
EXPECT_EQ(TargetBufferFlags::COLOR, rt.params.flags.discardStart);
EXPECT_EQ(TargetBufferFlags::NONE, rt.params.flags.discardEnd);
});
struct CulledPassData {
FrameGraphId<FrameGraphTexture> input;
FrameGraphId<FrameGraphTexture> output;
FrameGraphRenderTargetHandle rt;
};
auto& culledPass = fg.addPass<CulledPassData>("CulledPass",
[&](FrameGraph::Builder& builder, auto& data) {
data.input = builder.sample(renderPass.getData().output);
data.output = builder.createTexture("unused-rendertarget");
data.output = builder.write(data.output);
data.rt = builder.createRenderTarget("unused-rendertarget", {
.attachments = { data.output }
});
EXPECT_TRUE(fg.isValid(data.input));
EXPECT_TRUE(fg.isValid(data.output));
EXPECT_TRUE(fg.isValid(data.rt));
},
[=, &culledPassExecuted](FrameGraphPassResources const& resources,
auto const& data, backend::DriverApi& driver) {
culledPassExecuted = true;
});
fg.present(postProcessPass.getData().output);
EXPECT_TRUE(fg.isValid(renderPass.getData().output));
EXPECT_TRUE(fg.isValid(postProcessPass.getData().input));
EXPECT_TRUE(fg.isValid(postProcessPass.getData().output));
EXPECT_TRUE(fg.isValid(culledPass.getData().input));
EXPECT_TRUE(fg.isValid(culledPass.getData().output));
fg.compile();
//fg.export_graphviz(utils::slog.d);
fg.execute(driverApi);
EXPECT_TRUE(renderPassExecuted);
EXPECT_TRUE(postProcessPassExecuted);
EXPECT_FALSE(culledPassExecuted);
resourceAllocator.terminate();
}
TEST(FrameGraphTest, MoveGenericResource) {
// This checks that:
// - two passes writing in the same resource, that is replaced (moved) by
// another resource, end-up both using the 'replacing' resource.
// - these passes are not culled, even though they're not consumed by
// anyone initially -- but the 'replacing' resource was.
// - passes writing to the moved resource no longer do (and are culled)
MockResourceAllocator resourceAllocator;
FrameGraph fg(resourceAllocator);
struct RenderPassData {
FrameGraphId<GenericResource> output;
};
bool p0Executed = false;
bool p1Executed = false;
bool p2Executed = false;
bool p3Executed = false;
int h[4];
auto& p0 = fg.addPass<RenderPassData>("P0",
[&](FrameGraph::Builder& builder, auto& data) {
data.output = builder.create<GenericResource>("r0");
data.output = builder.write(data.output);
EXPECT_TRUE(fg.isValid(data.output));
},
[&](FrameGraphPassResources const& resources,
auto const& data, backend::DriverApi& driver) {
p0Executed = true;
h[0] = resources.get(data.output).id;
EXPECT_TRUE(h[0]);
});
auto& p1 = fg.addPass<RenderPassData>("P1",
[&](FrameGraph::Builder& builder, auto& data) {
data.output = p0.getData().output;
data.output = builder.read(data.output);
data.output = builder.write(data.output);
EXPECT_TRUE(fg.isValid(data.output));
},
[&](FrameGraphPassResources const& resources,
auto const& data, backend::DriverApi& driver) {
p1Executed = true;
h[1] = resources.get(data.output).id;
EXPECT_TRUE(h[1]);
});
auto& p2 = fg.addPass<RenderPassData>("P2",
[&](FrameGraph::Builder& builder, auto& data) {
data.output = builder.create<GenericResource>("r2");
data.output = builder.write(data.output);
EXPECT_TRUE(fg.isValid(data.output));
},
[&](FrameGraphPassResources const& resources,
auto const& data, backend::DriverApi& driver) {
p2Executed = true;
h[2] = resources.get(data.output).id;
EXPECT_TRUE(h[2]);
});
auto& p3 = fg.addPass<RenderPassData>("P3",
[&](FrameGraph::Builder& builder, auto& data) {
data.output = builder.read(p2.getData().output);
builder.sideEffect();
EXPECT_TRUE(fg.isValid(data.output));
},
[&](FrameGraphPassResources const& resources,
auto const& data, backend::DriverApi& driver) {
p3Executed = true;
h[3] = resources.get(data.output).id;
EXPECT_TRUE(h[3]);
});
fg.moveResource(p3.getData().output, p1.getData().output);
fg.compile();
fg.execute(driverApi);
EXPECT_TRUE(p0Executed);
EXPECT_TRUE(p1Executed);
EXPECT_FALSE(p2Executed);
EXPECT_TRUE(p3Executed);
EXPECT_EQ(h[0], h[1]);
EXPECT_EQ(h[1], h[3]);
EXPECT_EQ(h[3], h[0]);
}
|
#include "platform/servers_list.hpp"
#include "platform/http_request.hpp"
#include "platform/settings.hpp"
#include "platform/platform.hpp"
#include "base/logging.hpp"
#include "base/assert.hpp"
#include "3party/jansson/myjansson.hpp"
namespace downloader
{
// Returns false if can't parse urls. Note that it also clears outUrls.
bool ParseServerList(string const & jsonStr, vector<string> & outUrls)
{
outUrls.clear();
try
{
my::Json root(jsonStr.c_str());
for (size_t i = 0; i < json_array_size(root.get()); ++i)
{
char const * url = json_string_value(json_array_get(root.get(), i));
if (url)
outUrls.push_back(url);
}
}
catch (my::Json::Exception const & ex)
{
LOG(LERROR, ("Can't parse server list json:", ex.Msg(), jsonStr));
}
return !outUrls.empty();
}
void GetServerListFromRequest(HttpRequest const & request, vector<string> & urls)
{
if (request.Status() == HttpRequest::ECompleted && ParseServerList(request.Data(), urls))
{
return;
}
else
{
VERIFY(ParseServerList(GetPlatform().DefaultUrlsJSON(), urls), ());
LOG(LWARNING, ("Can't get servers list from request, using default servers:", urls));
}
}
} // namespace downloader
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.