hexsha
stringlengths 40
40
| size
int64 7
1.05M
| ext
stringclasses 13
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
269
| max_stars_repo_name
stringlengths 5
109
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
listlengths 1
9
| max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 4
269
| max_issues_repo_name
stringlengths 5
116
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
listlengths 1
9
| max_issues_count
int64 1
48.5k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 4
269
| max_forks_repo_name
stringlengths 5
116
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
listlengths 1
9
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 7
1.05M
| avg_line_length
float64 1.21
330k
| max_line_length
int64 6
990k
| alphanum_fraction
float64 0.01
0.99
| author_id
stringlengths 2
40
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a80df1f81aa18fc0fc67ea3d06bfc7d71e86a1ac
| 1,107
|
hpp
|
C++
|
etl/_functional/divides.hpp
|
tobanteEmbedded/tetl
|
fc3272170843bcab47971191bcd269a86c5b5101
|
[
"BSL-1.0"
] | 4
|
2021-11-28T08:48:11.000Z
|
2021-12-14T09:53:51.000Z
|
etl/_functional/divides.hpp
|
tobanteEmbedded/tetl
|
fc3272170843bcab47971191bcd269a86c5b5101
|
[
"BSL-1.0"
] | null | null | null |
etl/_functional/divides.hpp
|
tobanteEmbedded/tetl
|
fc3272170843bcab47971191bcd269a86c5b5101
|
[
"BSL-1.0"
] | null | null | null |
/// \copyright Tobias Hienzsch 2019-2021
/// Distributed under the Boost Software License, Version 1.0.
/// See accompanying file LICENSE or copy at http://boost.org/LICENSE_1_0.txt
#ifndef TETL_FUNCTIONAL_DIVIDES_HPP
#define TETL_FUNCTIONAL_DIVIDES_HPP
#include "etl/_utility/forward.hpp"
namespace etl {
/// \brief Function object for performing division. Effectively calls operator/
/// on two instances of type T.
/// https://en.cppreference.com/w/cpp/utility/functional/divides
/// \group divides
/// \module Utility
template <typename T = void>
struct divides {
[[nodiscard]] constexpr auto operator()(T const& lhs, T const& rhs) const -> T { return lhs / rhs; }
};
/// \group divides
template <>
struct divides<void> {
using is_transparent = void;
template <typename T, typename U>
[[nodiscard]] constexpr auto operator()(T&& lhs, U&& rhs) const
noexcept(noexcept(forward<T>(lhs) / forward<U>(rhs))) -> decltype(forward<T>(lhs) / forward<U>(rhs))
{
return forward<T>(lhs) / forward<U>(rhs);
}
};
} // namespace etl
#endif // TETL_FUNCTIONAL_DIVIDES_HPP
| 29.918919
| 108
| 0.699187
|
tobanteEmbedded
|
a80e57eb1bd0f8ff23b77b57e412fce9edf2f8ab
| 7,342
|
cpp
|
C++
|
src/commands.cpp
|
averrin/lss
|
c2aa0486641fba15daceab3241122e387720c898
|
[
"MIT"
] | 4
|
2018-07-09T20:53:06.000Z
|
2018-07-12T07:10:19.000Z
|
src/commands.cpp
|
averrin/lss
|
c2aa0486641fba15daceab3241122e387720c898
|
[
"MIT"
] | null | null | null |
src/commands.cpp
|
averrin/lss
|
c2aa0486641fba15daceab3241122e387720c898
|
[
"MIT"
] | null | null | null |
#include <sstream>
#include <utility>
#include "lss/commands.hpp"
#include "lss/utils.hpp"
#include "lss/game/events.hpp"
#include "EventBus.hpp"
using namespace std::string_literals;
Command::Command(std::vector<std::string> a) : aliases(a) {}
CommandEvent::CommandEvent(eb::ObjectPtr s) : eb::Event(s) {}
MoveCommand::MoveCommand()
: Command({"move", "m"s, "n"s, "e"s, "s"s, "w"s, "nw", "ne", "se", "sw"}) {}
QuitCommand::QuitCommand() : Command({"quit", "q"s}) {}
PickCommand::PickCommand() : Command({"pick", "p"s}) {}
DigCommand::DigCommand() : Command({"dig", "d"s}) {}
AttackCommand::AttackCommand() : Command({"attack", "a"s}) {}
EquipCommand::EquipCommand() : Command({"equip", "eq"s}) {}
HelpCommand::HelpCommand() : Command({"help", "h"s}) {}
HeroCommand::HeroCommand() : Command({"hero"}) {}
LightCommand::LightCommand() : Command({"light", "l"s}) {}
InventoryCommand::InventoryCommand() : Command({"inventory", "i"s}) {}
DropCommand::DropCommand() : Command({"drop", "dr"s}) {}
ThrowCommand::ThrowCommand() : Command({"throw", "t"s}) {}
WaitCommand::WaitCommand() : Command({"wait"}) {}
ZapCommand::ZapCommand() : Command({"zap", "z"s}) {}
UpCommand::UpCommand() : Command({"up"}) {}
DownCommand::DownCommand() : Command({"down"}) {}
UseCommand::UseCommand() : Command({"use", "u"s}) {}
WalkCommandEvent::WalkCommandEvent(Direction d)
: CommandEvent(nullptr), direction(d) {}
WalkCommand::WalkCommand() : Command({"walk"}) {}
std::optional<std::shared_ptr<CommandEvent>>
WalkCommand::getEvent(std::string cmd) {
auto tokens = lu::split(cmd, ' ');
std::string dirString = tokens.front();
if (tokens.size() > 1) {
dirString = tokens[1];
}
auto direction = utils::getDirectionByName(dirString);
if (direction == std::nullopt) {
MessageEvent me(nullptr,
"Please specify direction: n, e, s, w, nw, ne, se, sw.");
eb::EventBus::FireEvent(me);
return std::nullopt;
}
return std::make_shared<WalkCommandEvent>(*direction);
}
DigCommandEvent::DigCommandEvent(Direction d)
: CommandEvent(nullptr), direction(d) {}
std::optional<std::shared_ptr<CommandEvent>>
DigCommand::getEvent(std::string cmd) {
auto tokens = lu::split(cmd, ' ');
std::string dirString = tokens.front();
if (tokens.size() > 1) {
dirString = tokens[1];
}
auto direction = utils::getDirectionByName(dirString);
if (direction == std::nullopt) {
MessageEvent me(nullptr,
"Please specify direction: n, e, s, w, nw, ne, se, sw.");
eb::EventBus::FireEvent(me);
return std::nullopt;
}
return std::make_shared<DigCommandEvent>(*direction);
}
MoveCommandEvent::MoveCommandEvent(Direction d)
: CommandEvent(nullptr), direction(d) {}
std::optional<std::shared_ptr<CommandEvent>>
MoveCommand::getEvent(std::string cmd) {
auto tokens = lu::split(cmd, ' ');
std::string dirString = tokens.front();
if (tokens.size() > 1) {
dirString = tokens[1];
}
auto direction = utils::getDirectionByName(dirString);
if (direction == std::nullopt) {
MessageEvent me(nullptr,
"Please specify direction: n, e, s, w, nw, ne, se, sw.");
eb::EventBus::FireEvent(me);
return std::nullopt;
}
return std::make_shared<MoveCommandEvent>(*direction);
}
AttackCommandEvent::AttackCommandEvent(Direction d)
: CommandEvent(nullptr), direction(d) {}
std::optional<std::shared_ptr<CommandEvent>>
AttackCommand::getEvent(std::string cmd) {
auto tokens = lu::split(cmd, ' ');
std::string dirString = tokens.front();
if (tokens.size() > 1) {
dirString = tokens[1];
}
auto direction = utils::getDirectionByName(dirString);
if (direction == std::nullopt) {
MessageEvent me(nullptr,
"Please specify direction: n, e, s, w, nw, ne, se, sw.");
eb::EventBus::FireEvent(me);
return std::nullopt;
}
return std::make_shared<AttackCommandEvent>(*direction);
}
PickCommandEvent::PickCommandEvent() : CommandEvent(nullptr) {}
std::optional<std::shared_ptr<CommandEvent>>
PickCommand::getEvent(std::string s) {
return std::make_shared<PickCommandEvent>();
}
EquipCommandEvent::EquipCommandEvent() : CommandEvent(nullptr) {}
EquipCommandEvent::EquipCommandEvent(std::shared_ptr<Slot> s,
std::shared_ptr<Item> i)
: CommandEvent(nullptr), item(i), slot(s) {}
std::optional<std::shared_ptr<CommandEvent>>
EquipCommand::getEvent(std::string s) {
return std::make_shared<EquipCommandEvent>();
}
UnEquipCommandEvent::UnEquipCommandEvent(std::shared_ptr<Slot> s)
: CommandEvent(nullptr), slot(s) {}
HelpCommandEvent::HelpCommandEvent() : CommandEvent(nullptr) {}
HeroCommandEvent::HeroCommandEvent() : CommandEvent(nullptr) {}
LightCommandEvent::LightCommandEvent() : CommandEvent(nullptr) {}
InventoryCommandEvent::InventoryCommandEvent() : CommandEvent(nullptr) {}
std::optional<std::shared_ptr<CommandEvent>>
HelpCommand::getEvent(std::string s) {
return std::make_shared<HelpCommandEvent>();
}
std::optional<std::shared_ptr<CommandEvent>>
HeroCommand::getEvent(std::string s) {
return std::make_shared<HeroCommandEvent>();
}
std::optional<std::shared_ptr<CommandEvent>>
LightCommand::getEvent(std::string s) {
return std::make_shared<LightCommandEvent>();
}
std::optional<std::shared_ptr<CommandEvent>>
InventoryCommand::getEvent(std::string s) {
return std::make_shared<InventoryCommandEvent>();
}
DropCommandEvent::DropCommandEvent() : CommandEvent(nullptr) {}
DropCommandEvent::DropCommandEvent(std::shared_ptr<Item> i)
: CommandEvent(nullptr), item(i) {}
std::optional<std::shared_ptr<CommandEvent>>
DropCommand::getEvent(std::string s) {
return std::make_shared<DropCommandEvent>();
}
ThrowCommandEvent::ThrowCommandEvent() : CommandEvent(nullptr) {}
ThrowCommandEvent::ThrowCommandEvent(std::shared_ptr<Item> i,
std::shared_ptr<Cell> c)
: CommandEvent(nullptr), item(i), cell(c) {}
std::optional<std::shared_ptr<CommandEvent>>
ThrowCommand::getEvent(std::string s) {
return std::make_shared<ThrowCommandEvent>();
}
ZapCommandEvent::ZapCommandEvent() : CommandEvent(nullptr) {}
ZapCommandEvent::ZapCommandEvent(eb::ObjectPtr c, std::shared_ptr<Spell> i)
: CommandEvent(c), spell(i) {}
std::optional<std::shared_ptr<CommandEvent>>
ZapCommand::getEvent(std::string s) {
return std::make_shared<ZapCommandEvent>();
}
WaitCommandEvent::WaitCommandEvent() : CommandEvent(nullptr) {}
std::optional<std::shared_ptr<CommandEvent>>
WaitCommand::getEvent(std::string s) {
return std::make_shared<WaitCommandEvent>();
}
StairEvent::StairEvent(StairType st) : CommandEvent(nullptr), dir(st) {}
std::optional<std::shared_ptr<CommandEvent>>
UpCommand::getEvent(std::string s) {
return std::make_shared<StairEvent>(StairType::UP);
}
std::optional<std::shared_ptr<CommandEvent>>
DownCommand::getEvent(std::string s) {
return std::make_shared<StairEvent>(StairType::DOWN);
}
UseCommandEvent::UseCommandEvent() : CommandEvent(nullptr) {}
UseCommandEvent::UseCommandEvent(std::shared_ptr<Item> i)
: CommandEvent(nullptr), item(i) {}
UseCommandEvent::UseCommandEvent(std::shared_ptr<UsableTerrain> i)
: CommandEvent(nullptr), terrain(i) {}
std::optional<std::shared_ptr<CommandEvent>>
UseCommand::getEvent(std::string s) {
return std::make_shared<UseCommandEvent>();
}
| 35.640777
| 80
| 0.695859
|
averrin
|
a80f528d248df0ee1b9ec2494d2f292c94092b97
| 2,825
|
cpp
|
C++
|
io/internal/StdioEx.cpp
|
Andrewich/deadjustice
|
48bea56598e79a1a10866ad41aa3517bf7d7c724
|
[
"BSD-3-Clause"
] | 3
|
2019-04-20T10:16:36.000Z
|
2021-03-21T19:51:38.000Z
|
io/internal/StdioEx.cpp
|
Andrewich/deadjustice
|
48bea56598e79a1a10866ad41aa3517bf7d7c724
|
[
"BSD-3-Clause"
] | null | null | null |
io/internal/StdioEx.cpp
|
Andrewich/deadjustice
|
48bea56598e79a1a10866ad41aa3517bf7d7c724
|
[
"BSD-3-Clause"
] | 2
|
2020-04-18T20:04:24.000Z
|
2021-09-19T05:07:41.000Z
|
#include "StdioEx.h"
#include <lang/String.h>
#include <assert.h>
#include "config.h"
//----------------------------------------------------------------------------
using namespace lang;
//----------------------------------------------------------------------------
namespace io
{
// Truncates string to char string, ignores non-convertable characters
static void truncate( const String& str, char* buffer, int bufferSize )
{
assert( str.length() < bufferSize );
if ( bufferSize > 0 )
{
int iend = str.length();
char* bufferEnd = buffer+bufferSize-1;
for ( int i = 0 ; i != iend && buffer != bufferEnd ; ++i )
{
Char ch = str.charAt(i);
if ( ch < Char(0x80) )
*buffer++ = (char)ch;
}
*buffer++ = 0;
}
}
// Truncates string to char string, ignores non-convertable characters
static void truncate_w( const String& str, wchar_t* buffer, int bufferSize )
{
assert( str.length() < bufferSize );
if ( bufferSize > 0 )
{
int iend = str.length();
wchar_t* bufferEnd = buffer+bufferSize-1;
for ( int i = 0 ; i != iend && buffer != bufferEnd ; ++i )
{
Char ch = str.charAt(i);
*buffer++ = (wchar_t)ch;
}
*buffer++ = 0;
}
}
/*
* Truncates Unicode file name to ASCII-7 range and tries to open a file.
* Ignores non-convertable characters.
*/
static FILE* fopen_ascii7( const String& filename, const char* access )
{
FILE* file = 0;
if ( filename.length()+1 < 2048 )
{
char filenameBuffer[2048];
truncate( filename, filenameBuffer, 2048 );
file = ::fopen( filenameBuffer, access );
}
else
{
char* filenameBuffer = new char[filename.length()+1];
truncate( filename, filenameBuffer, filename.length()+1 );
file = ::fopen( filenameBuffer, access );
delete[] filenameBuffer;
}
return file;
}
//-----------------------------------------------------------------------------
FILE* fopen( const String& filename, const char* access )
{
#ifdef WIN32
wchar_t accessW[16];
int i;
for ( i = 0 ; access[i] && i+1 < 16 ; ++i )
accessW[i] = (unsigned char)access[i];
accessW[i] = 0;
FILE* file = 0;
if ( filename.length()+1 < 2048 )
{
wchar_t filenameBuffer[2048];
truncate_w( filename, filenameBuffer, 2048 );
file = _wfopen( filenameBuffer, accessW );
}
else
{
wchar_t* filenameBuffer = new wchar_t[filename.length()+1];
truncate_w( filename, filenameBuffer, filename.length()+1 );
file = _wfopen( filenameBuffer, accessW );
delete[] filenameBuffer;
}
// if we failed then we still try to open with ASCII-7 filename
// (in case the Windows platform doesn't support _wfopen)
if ( !file )
return fopen_ascii7( filename, access );
return file;
#else
return fopen_ascii7( filename, access );
#endif
}
} // io
| 23.739496
| 80
| 0.574159
|
Andrewich
|
a8177fe69b6af22c09905a628fca730c5711266c
| 3,675
|
cc
|
C++
|
libpfkthread/pk_filedescs.cc
|
flipk/pfkutils
|
d8f6c22720b6fcc44a882927c745a822282d1f69
|
[
"Unlicense"
] | 4
|
2015-06-12T05:08:56.000Z
|
2017-11-13T11:34:27.000Z
|
libpfkthread/pk_filedescs.cc
|
flipk/pfkutils
|
d8f6c22720b6fcc44a882927c745a822282d1f69
|
[
"Unlicense"
] | null | null | null |
libpfkthread/pk_filedescs.cc
|
flipk/pfkutils
|
d8f6c22720b6fcc44a882927c745a822282d1f69
|
[
"Unlicense"
] | 1
|
2021-10-20T02:04:53.000Z
|
2021-10-20T02:04:53.000Z
|
/*
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
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 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.
For more information, please refer to <http://unlicense.org>
*/
#include "pk_threads.h"
#include "pk_filedescs_internal.h"
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <signal.h>
#include <unistd.h>
PK_File_Descriptor_Manager * PK_File_Descriptors_global;
/** \cond INTERNAL */
PK_File_Descriptor_List :: ~PK_File_Descriptor_List( void )
{
//? destroy pending data on the list
}
PK_File_Descriptor_Manager :: PK_File_Descriptor_Manager( void )
{
if ( PK_File_Descriptors_global )
{
fprintf( stderr, "PK_File_Descriptor_Manager already exists?!\n" );
kill(0,6);
}
descs = new PK_File_Descriptor_List;
pthread_mutex_init( &mutex, NULL );
PK_File_Descriptors_global = this;
if (pipe(wakeup_pipe) < 0)
fprintf(stderr, "PK_File_Descriptor_Manager: pipe failed\n");
thread = new PK_File_Descriptor_Thread(this);
}
PK_File_Descriptor_Manager :: ~PK_File_Descriptor_Manager( void )
{
delete descs;
pthread_mutex_destroy( &mutex );
PK_File_Descriptors_global = NULL;
close(wakeup_pipe[0]);
close(wakeup_pipe[1]);
}
void
PK_File_Descriptor_Manager :: stop( void )
{
thread->stop();
}
int // pkfdid
PK_File_Descriptor_Manager :: register_fd( int fd, PK_FD_RW rw,
int qid, void *obj )
{
int pkfdid;
PK_File_Descriptor * pkfd = new PK_File_Descriptor;
pkfd->fd = fd;
pkfd->rw = rw;
pkfd->qid = qid;
pkfd->obj = obj;
// find a unique id
_lock();
do {
do {
pkfdid = random();
} while (pkfdid == -1 || pkfdid == 0); // never use -1 or 0
} while (descs->find(pkfdid) != NULL);
pkfd->pkfdid = pkfdid;
descs->add(pkfd);
_unlock();
// awaken the thread
char c = 1;
if (write(wakeup_pipe[1], &c, 1) < 0)
fprintf(stderr, "PK_File_Descriptor_Manager: write failed\n");
return pkfdid;
}
void *
PK_File_Descriptor_Manager :: unregister_fd( int pkfdid )
{
PK_File_Descriptor * pkfd;
void * obj = NULL;
_lock();
pkfd = descs->find(pkfdid);
if (pkfd)
{
descs->remove(pkfd);
_unlock();
obj = pkfd->obj;
delete pkfd;
}
else
_unlock();
if (pkfd) // don't dereference, just check nonnull
{
// awaken the thread
char c = 1;
if (write(wakeup_pipe[1], &c, 1) < 0)
fprintf(stderr, "PK_File_Descriptor_Manager: write failed\n");
}
return obj;
}
/** \endcond */
| 27.222222
| 75
| 0.67483
|
flipk
|
a818b28c5b2192ac31b58e9d1afafc1c6c22a764
| 956
|
cpp
|
C++
|
dynamic programming/416. Partition Equal Subset Sum.cpp
|
Constantine-L01/leetcode
|
1f1e3a8226fcec036370e75c1d69e823d1323392
|
[
"MIT"
] | 1
|
2021-04-08T10:33:48.000Z
|
2021-04-08T10:33:48.000Z
|
dynamic programming/416. Partition Equal Subset Sum.cpp
|
Constantine-L01/leetcode
|
1f1e3a8226fcec036370e75c1d69e823d1323392
|
[
"MIT"
] | null | null | null |
dynamic programming/416. Partition Equal Subset Sum.cpp
|
Constantine-L01/leetcode
|
1f1e3a8226fcec036370e75c1d69e823d1323392
|
[
"MIT"
] | 1
|
2021-02-23T05:58:58.000Z
|
2021-02-23T05:58:58.000Z
|
Given a non-empty array nums containing only positive integers, find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal.
Example 1:
Input: nums = [1,5,11,5]
Output: true
Explanation: The array can be partitioned as [1, 5, 5] and [11].
class Solution {
public:
bool canPartition(vector<int>& nums) {
int sum = 0;
for(int i = 0; i < nums.size(); i++){
sum += nums[i];
}
if(sum % 2 == 1) {
return false;
}
int target = sum / 2;
vector<int> dp(target + 1, 0);
for(int i = 0; i < nums.size(); i++){
for(int j = target; j >= nums[i]; j--){
dp[j] = max(dp[j], dp[j - nums[i]] + nums[i]);
}
}
if(dp[target] == target){
return true;
}
else {
return false;
}
}
};
| 24.512821
| 174
| 0.470711
|
Constantine-L01
|
a81cede09c643e75123a727946cb687c1c7468db
| 234
|
cpp
|
C++
|
firmware-latest/user/tests/unit/ipaddress.cpp
|
adeeshag/particle_project
|
0c2ab278cf902f97d2422c44c008978be58fe6b7
|
[
"Unlicense"
] | 1
|
2019-02-24T07:13:51.000Z
|
2019-02-24T07:13:51.000Z
|
firmware-latest/user/tests/unit/ipaddress.cpp
|
adeeshag/particle_project
|
0c2ab278cf902f97d2422c44c008978be58fe6b7
|
[
"Unlicense"
] | 1
|
2018-05-29T19:27:53.000Z
|
2018-05-29T19:27:53.000Z
|
firmware-latest/user/tests/unit/ipaddress.cpp
|
adeeshag/particle_project
|
0c2ab278cf902f97d2422c44c008978be58fe6b7
|
[
"Unlicense"
] | null | null | null |
#include "catch.hpp"
#include "spark_wiring_ipaddress.h"
TEST_CASE("Can Construct From Uint32") {
IPAddress ip(1<<24 | 2<<16 | 3<<8 | 4);
CHECK(ip[3]==4);
CHECK(ip[2]==3);
CHECK(ip[1]==2);
CHECK(ip[0]==1);
}
| 14.625
| 43
| 0.564103
|
adeeshag
|
a81d0789097f698944baa0be926a6c99b5a4035c
| 6,706
|
cpp
|
C++
|
src/librt/primitives/epa/epa_brep.cpp
|
earl-ducaine/brlcad-mirror
|
402bd3542a10618d1f749b264cadf9b0bd723546
|
[
"BSD-4-Clause",
"BSD-3-Clause"
] | 1
|
2019-10-23T16:17:49.000Z
|
2019-10-23T16:17:49.000Z
|
src/librt/primitives/epa/epa_brep.cpp
|
pombredanne/sf.net-brlcad
|
fb56f37c201b51241e8f3aa7b979436856f43b8c
|
[
"BSD-4-Clause",
"BSD-3-Clause"
] | null | null | null |
src/librt/primitives/epa/epa_brep.cpp
|
pombredanne/sf.net-brlcad
|
fb56f37c201b51241e8f3aa7b979436856f43b8c
|
[
"BSD-4-Clause",
"BSD-3-Clause"
] | null | null | null |
/* E P A _ B R E P . C P P
* BRL-CAD
*
* Copyright (c) 2008-2019 United States Government as represented by
* the U.S. Army Research Laboratory.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this file; see the file named COPYING for more
* information.
*/
/** @file epa_brep.cpp
*
* Convert an Elliptical Paraboloid to b-rep form
*
*/
#include "common.h"
#include "raytrace.h"
#include "rt/geom.h"
#include "brep.h"
extern "C" void
rt_epa_brep(ON_Brep **b, const struct rt_db_internal *ip, const struct bn_tol *)
{
struct rt_epa_internal *eip;
RT_CK_DB_INTERNAL(ip);
eip = (struct rt_epa_internal *)ip->idb_ptr;
RT_EPA_CK_MAGIC(eip);
point_t p1_origin;
ON_3dPoint plane1_origin, plane2_origin;
ON_3dVector plane_x_dir, plane_y_dir;
// First, find plane in 3 space corresponding to the bottom face of the EPA.
vect_t x_dir, y_dir;
VMOVE(x_dir, eip->epa_Au);
VCROSS(y_dir, eip->epa_Au, eip->epa_H);
VUNITIZE(y_dir);
VMOVE(p1_origin, eip->epa_V);
plane1_origin = ON_3dPoint(p1_origin);
plane_x_dir = ON_3dVector(x_dir);
plane_y_dir = ON_3dVector(y_dir);
const ON_Plane epa_bottom_plane = ON_Plane(plane1_origin, plane_x_dir, plane_y_dir);
// Next, create an ellipse in the plane corresponding to the edge of the epa.
ON_Ellipse ellipse1 = ON_Ellipse(epa_bottom_plane, eip->epa_r1, eip->epa_r2);
ON_NurbsCurve ellcurve1;
ellipse1.GetNurbForm(ellcurve1);
ellcurve1.SetDomain(0.0, 1.0);
// Generate the bottom cap
ON_SimpleArray<ON_Curve*> boundary;
boundary.Append(ON_Curve::Cast(&ellcurve1));
ON_PlaneSurface* bp = new ON_PlaneSurface();
bp->m_plane = epa_bottom_plane;
bp->SetDomain(0, -100.0, 100.0);
bp->SetDomain(1, -100.0, 100.0);
bp->SetExtents(0, bp->Domain(0));
bp->SetExtents(1, bp->Domain(1));
(*b)->m_S.Append(bp);
const int bsi = (*b)->m_S.Count() - 1;
ON_BrepFace& bface = (*b)->NewFace(bsi);
(*b)->NewPlanarFaceLoop(bface.m_face_index, ON_BrepLoop::outer, boundary, true);
const ON_BrepLoop* bloop = (*b)->m_L.Last();
bp->SetDomain(0, bloop->m_pbox.m_min.x, bloop->m_pbox.m_max.x);
bp->SetDomain(1, bloop->m_pbox.m_min.y, bloop->m_pbox.m_max.y);
bp->SetExtents(0, bp->Domain(0));
bp->SetExtents(1, bp->Domain(1));
(*b)->SetTrimIsoFlags(bface);
// Now, the hard part. Need an elliptical parabolic NURBS surface
ON_NurbsSurface* epacurvedsurf = ON_NurbsSurface::New(3, true, 3, 3, 9, 3);
epacurvedsurf->SetKnot(0, 0, 0);
epacurvedsurf->SetKnot(0, 1, 0);
epacurvedsurf->SetKnot(0, 2, 1.571);
epacurvedsurf->SetKnot(0, 3, 1.571);
epacurvedsurf->SetKnot(0, 4, 3.142);
epacurvedsurf->SetKnot(0, 5, 3.142);
epacurvedsurf->SetKnot(0, 6, 4.713);
epacurvedsurf->SetKnot(0, 7, 4.713);
epacurvedsurf->SetKnot(0, 8, 6.284);
epacurvedsurf->SetKnot(0, 9, 6.284);
epacurvedsurf->SetKnot(1, 0, 0);
epacurvedsurf->SetKnot(1, 1, 0);
epacurvedsurf->SetKnot(1, 2, eip->epa_r1*2);
epacurvedsurf->SetKnot(1, 3, eip->epa_r1*2);
double h = MAGNITUDE(eip->epa_H);
double r1 = eip->epa_r1;
double r2 = eip->epa_r2;
ON_4dPoint pt01 = ON_4dPoint(0, 0, h, 1);
epacurvedsurf->SetCV(0, 0, pt01);
ON_4dPoint pt02 = ON_4dPoint(0, r2/2, h, 1);
epacurvedsurf->SetCV(0, 1, pt02);
ON_4dPoint pt03 = ON_4dPoint(0, r2, 0, 1);
epacurvedsurf->SetCV(0, 2, pt03);
ON_4dPoint pt04 = ON_4dPoint(0, 0, h/sqrt(2.), 1/sqrt(2.));
epacurvedsurf->SetCV(1, 0, pt04);
ON_4dPoint pt05 = ON_4dPoint(r1/2/sqrt(2.), r2/2/sqrt(2.), h/sqrt(2.), 1/sqrt(2.));
epacurvedsurf->SetCV(1, 1, pt05);
ON_4dPoint pt06 = ON_4dPoint(r1/sqrt(2.), r2/sqrt(2.), 0, 1/sqrt(2.));
epacurvedsurf->SetCV(1, 2, pt06);
ON_4dPoint pt07 = ON_4dPoint(0, 0, h, 1);
epacurvedsurf->SetCV(2, 0, pt07);
ON_4dPoint pt08 = ON_4dPoint(r1/2, 0, h, 1);
epacurvedsurf->SetCV(2, 1, pt08);
ON_4dPoint pt09 = ON_4dPoint(r1, 0, 0, 1);
epacurvedsurf->SetCV(2, 2, pt09);
ON_4dPoint pt10 = ON_4dPoint(0, 0, h/sqrt(2.), 1/sqrt(2.));
epacurvedsurf->SetCV(3, 0, pt10);
ON_4dPoint pt11 = ON_4dPoint(r1/2/sqrt(2.), -r2/2/sqrt(2.), h/sqrt(2.), 1/sqrt(2.));
epacurvedsurf->SetCV(3, 1, pt11);
ON_4dPoint pt12 = ON_4dPoint(r1/sqrt(2.), -r2/sqrt(2.), 0, 1/sqrt(2.));
epacurvedsurf->SetCV(3, 2, pt12);
ON_4dPoint pt13 = ON_4dPoint(0, 0, h, 1);
epacurvedsurf->SetCV(4, 0, pt13);
ON_4dPoint pt14 = ON_4dPoint(0, -r2/2, h, 1);
epacurvedsurf->SetCV(4, 1, pt14);
ON_4dPoint pt15 = ON_4dPoint(0, -r2, 0, 1);
epacurvedsurf->SetCV(4, 2, pt15);
ON_4dPoint pt16 = ON_4dPoint(0, 0, h/sqrt(2.), 1/sqrt(2.));
epacurvedsurf->SetCV(5, 0, pt16);
ON_4dPoint pt17 = ON_4dPoint(-r1/2/sqrt(2.), -r2/2/sqrt(2.), h/sqrt(2.), 1/sqrt(2.));
epacurvedsurf->SetCV(5, 1, pt17);
ON_4dPoint pt18 = ON_4dPoint(-r1/sqrt(2.), -r2/sqrt(2.), 0, 1/sqrt(2.));
epacurvedsurf->SetCV(5, 2, pt18);
ON_4dPoint pt19 = ON_4dPoint(0, 0, h, 1);
epacurvedsurf->SetCV(6, 0, pt19);
ON_4dPoint pt20 = ON_4dPoint(-r1/2, 0, h, 1);
epacurvedsurf->SetCV(6, 1, pt20);
ON_4dPoint pt21 = ON_4dPoint(-r1, 0, 0, 1);
epacurvedsurf->SetCV(6, 2, pt21);
ON_4dPoint pt22 = ON_4dPoint(0, 0, h/sqrt(2.), 1/sqrt(2.));
epacurvedsurf->SetCV(7, 0, pt22);
ON_4dPoint pt23 = ON_4dPoint(-r1/2/sqrt(2.), r2/2/sqrt(2.), h/sqrt(2.), 1/sqrt(2.));
epacurvedsurf->SetCV(7, 1, pt23);
ON_4dPoint pt24 = ON_4dPoint(-r1/sqrt(2.), r2/sqrt(2.), 0, 1/sqrt(2.));
epacurvedsurf->SetCV(7, 2, pt24);
ON_4dPoint pt25 = ON_4dPoint(0, 0, h, 1);
epacurvedsurf->SetCV(8, 0, pt25);
ON_4dPoint pt26 = ON_4dPoint(0, r2/2, h, 1);
epacurvedsurf->SetCV(8, 1, pt26);
ON_4dPoint pt27 = ON_4dPoint(0, r2, 0, 1);
epacurvedsurf->SetCV(8, 2, pt27);
(*b)->m_S.Append(epacurvedsurf);
int surfindex = (*b)->m_S.Count();
(*b)->NewFace(surfindex - 1);
int faceindex = (*b)->m_F.Count();
(*b)->NewOuterLoop(faceindex-1);
}
// Local Variables:
// tab-width: 8
// mode: C++
// c-basic-offset: 4
// indent-tabs-mode: t
// c-file-style: "stroustrup"
// End:
// ex: shiftwidth=4 tabstop=8
| 35.670213
| 89
| 0.64569
|
earl-ducaine
|
a82040e0d433ff52e3e0bf924d028b33b471a062
| 4,752
|
cpp
|
C++
|
test/LaneDetectionModuleTest.cpp
|
rohit517/Lane-Detection
|
4374934828e18236ad97ba032a718f8301a86ba9
|
[
"MIT"
] | 3
|
2018-10-31T01:32:02.000Z
|
2021-03-16T10:12:52.000Z
|
test/LaneDetectionModuleTest.cpp
|
rohit517/Lane-Detection
|
4374934828e18236ad97ba032a718f8301a86ba9
|
[
"MIT"
] | null | null | null |
test/LaneDetectionModuleTest.cpp
|
rohit517/Lane-Detection
|
4374934828e18236ad97ba032a718f8301a86ba9
|
[
"MIT"
] | 1
|
2020-05-27T18:01:29.000Z
|
2020-05-27T18:01:29.000Z
|
/************************************************************************
MIT License
Copyright (c) 2018 Harsh Kakashaniya,Rohitkrishna Nambiar
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*************************************************************************/
/**
* @file LaneDetectionModuleTest.cpp
* @author Rohitkrishna Nambiar (rohit517)
* @date 10/10/2018
* @version 1.0
*
* @brief Program to test LaneDetectionModule class.
*
* @section DESCRIPTION
*
* This is a program that tests LaneDetectionModule class.
*/
#include <gtest/gtest.h>
#include "LaneDetectionModule.hpp"
#include "opencv2/opencv.hpp"
// LaneDetectionModule module object
LaneDetectionModule laneModule;
/**
*@brief Test get grey scale min threshold function.
*
*@param GetSetTest Get set function test
*@param getGrayScaleMin Name of the unit test
*/
TEST(GetSetTest, GetGrayScaleMin) {
int lowTheshold = laneModule.getGrayScaleMin();
ASSERT_EQ(lowTheshold, 200);
}
/**
*@brief Test get grey scale max threshold function.
*
*@param GetSetTest Get set function test
*@param getGrayScaleMax Name of the unit test
*/
TEST(GetSetTest, GetGrayScaleMax) {
int highTheshold = laneModule.getGrayScaleMax();
ASSERT_EQ(highTheshold, 255);
}
/**
*@brief Test get yellow min threshold function.
*
*@param GetSetTest Get set function test
*@param getYellowMin Name of the unit test
*/
TEST(GetSetTest, GetYellowMin) {
cv::Scalar lowTheshold = laneModule.getYellowMin();
ASSERT_EQ(lowTheshold, cv::Scalar(20, 100, 100));
}
/**
*@brief Test get yellow max threshold function.
*
*@param GetSetTest Get set function test
*@param getYellowMax Name of the unit test
*/
TEST(GetSetTest, GetYellowMax) {
cv::Scalar highTheshold = laneModule.getYellowMax();
ASSERT_EQ(highTheshold, cv::Scalar(30, 255, 255));
}
/**
*@brief Test set grey min threshold function.
*
*@param GetSetTest Get set function test
*@param setGrayScaleMin Name of the unit test
*/
TEST(GetSetTest, SetGrayScaleMin) {
laneModule.setGrayScaleMin(150);
int lowTheshold = laneModule.getGrayScaleMin();
ASSERT_EQ(lowTheshold, 150);
}
/**
*@brief Test set grey max threshold function.
*
*@param GetSetTest Get set function test
*@param SetGrayScaleMax Name of the unit test
*/
TEST(GetSetTest, SetGrayScaleMax) {
laneModule.setGrayScaleMax(210);
int highTheshold = laneModule.getGrayScaleMax();
ASSERT_EQ(highTheshold, 210);
}
/**
*@brief Test set yellow min threshold function.
*
*@param GetSetTest Get set function test
*@param setYellowMin Name of the unit test
*/
TEST(GetSetTest, SetYellowMin) {
laneModule.setYellowMin(cv::Scalar(50, 50, 50));
cv::Scalar lowTheshold = laneModule.getYellowMin();
ASSERT_EQ(lowTheshold, cv::Scalar(50, 50, 50));
}
/**
*@brief Test set yellow max threshold function.
*
*@param GetSetTest Get set function test
*@param SetYellowMax Name of the unit test
*/
TEST(GetSetTest, SetYellowMax) {
laneModule.setYellowMax(cv::Scalar(150, 150, 150));
cv::Scalar highTheshold = laneModule.getYellowMax();
ASSERT_EQ(highTheshold, cv::Scalar(150, 150, 150));
}
/**
*@brief Test for single image execution..
*
*@param FunctionalTest Get set function test
*@param TestImage Name of the unit test
*/
TEST(FunctionalTest, TestImage) {
bool status = laneModule.detectLane("../input/ColorImage.jpg");
ASSERT_EQ(status, true);
}
/**
*@brief Test for false image path.
*
*@param FunctionalTest Get set function test
*@param TestFalseImagePath Name of the unit test
*/
TEST(FunctionalTest, TestFalseImagePath) {
bool status = laneModule.detectLane("../input/ColorImage1.jpg");
ASSERT_EQ(status, false);
}
| 30.075949
| 79
| 0.710438
|
rohit517
|
a824b440efad478e8f18db06a1b0925e08ccdf5e
| 2,863
|
hxx
|
C++
|
src/texture.hxx
|
DaWelter/NaiveTrace
|
a904785a0e13c394b2c221bc918cddb41bc8b175
|
[
"FSFAP"
] | 16
|
2018-04-25T08:14:14.000Z
|
2022-01-29T06:19:16.000Z
|
src/texture.hxx
|
DaWelter/NaiveTrace
|
a904785a0e13c394b2c221bc918cddb41bc8b175
|
[
"FSFAP"
] | null | null | null |
src/texture.hxx
|
DaWelter/NaiveTrace
|
a904785a0e13c394b2c221bc918cddb41bc8b175
|
[
"FSFAP"
] | null | null | null |
#ifndef TEXTURE_HXX
#define TEXTURE_HXX
#include"image.hxx"
#include"vec3f.hxx"
#include"spectral.hxx"
#include"util.hxx"
namespace boost { namespace filesystem {
class path;
}}
class Texture
{
ToyVector<std::uint8_t> data;
int w, h;
// Always 3 channels
enum Type {
BYTE, // 1 byte per channel
FLOAT // 4 byte per channel, data really contains floats
} type;
//void MakeDefaultImage();
void ReadFile(const std::string &filename);
public:
Texture(const boost::filesystem::path &filename);
int Width() const { return w; }
int Height() const { return h; }
inline RGB GetPixel(int x, int y) const;
inline RGB GetPixel(std::pair<int,int> xy) const;
};
inline std::pair<int, int> UvToPixel(const Texture &tex, Float2 uv)
{
const int w = tex.Width();
const int h = tex.Height();
float u = uv[0];
float v = uv[1];
float dummy;
u = std::modf(u, &dummy);
v = std::modf(v, &dummy);
if (u < 0.f) u = 1.f + u;
if (v < 0.f) v = 1.f + v;
if (u > 1.f - EpsilonFloat) u -= EpsilonFloat;
if (v > 1.f - EpsilonFloat) v -= EpsilonFloat;
int x = (int)(u * w);
int y = (int)(v * h);
y = h - y - 1;
assert (x>=0 && x<tex.Width());
assert (y>=0 && y<tex.Height());
return std::make_pair(x,y);
}
inline Float2 PixelCenterToUv(const Texture &tex, std::pair<int,int> xy)
{
const int w = tex.Width();
const int h = tex.Height();
Float2 uv( (float)(xy.first),
(float)(h - 1 - xy.second));
uv.array() += 0.5f;
uv[0] /= w;
uv[1] /= h;
return uv;
}
inline std::pair<Float2,Float2> PixelToUvBounds(const Texture &tex, std::pair<int,int> xy)
{
const int w = tex.Width();
const int h = tex.Height();
Float2 uv_lower(
(float)xy.first,
(float)xy.second );
uv_lower[0] /= w;
uv_lower[1] /= h;
Float2 uv_upper = uv_lower;
uv_upper[0] += 1.f/w;
uv_upper[1] += 1.f/h;
uv_lower[1] = 1.f-uv_lower[1];
uv_upper[1] = 1.f-uv_upper[1];
return std::make_pair(uv_lower, uv_upper);
}
inline RGB Texture::GetPixel(std::pair<int,int> xy) const
{
return GetPixel(xy.first, xy.second);
}
inline RGB Texture::GetPixel(int x, int y) const
{
assert (x>=0 && x<Width());
assert (y>=0 && y<Height());
constexpr int num_channels = 3;
const int idx = (y * w + x)*num_channels;
if (type == BYTE)
{
return RGB{
Color::SRGBToLinear(Color::RGBScalar(data[idx ] / 255.0)),
Color::SRGBToLinear(Color::RGBScalar(data[idx+1] / 255.0)),
Color::SRGBToLinear(Color::RGBScalar(data[idx+2] / 255.0))
};
}
else
{
const auto* pix = reinterpret_cast<const float*>(&data[idx*sizeof(float)]);
return RGB{
Color::RGBScalar{pix[0]},
Color::RGBScalar{pix[1]},
Color::RGBScalar{pix[2]}
};
}
}
#endif
| 23.661157
| 91
| 0.584701
|
DaWelter
|
a8263eb3def14e466f38b73292378f325f59d5c5
| 8,921
|
cpp
|
C++
|
src/input.cpp
|
IndianBoy42/nvui
|
ee139c1b1317dbc5ad408ce21871f2b1a92b295f
|
[
"MIT"
] | null | null | null |
src/input.cpp
|
IndianBoy42/nvui
|
ee139c1b1317dbc5ad408ce21871f2b1a92b295f
|
[
"MIT"
] | null | null | null |
src/input.cpp
|
IndianBoy42/nvui
|
ee139c1b1317dbc5ad408ce21871f2b1a92b295f
|
[
"MIT"
] | null | null | null |
#include "input.hpp"
#include <fmt/format.h>
#include <fmt/core.h>
#include <unordered_map>
#include <string>
#include <string_view>
#include <QEvent>
#include <QKeyEvent>
#include <QString>
std::string event_to_string(const QKeyEvent* event, bool* special)
{
*special = true;
switch(event->key())
{
case Qt::Key_Enter:
return "CR";
case Qt::Key_Return:
return "CR";
case Qt::Key_Backspace:
return "BS";
case Qt::Key_Tab:
return "Tab";
case Qt::Key_Backtab:
return "Tab";
case Qt::Key_Down:
return "Down";
case Qt::Key_Up:
return "Up";
case Qt::Key_Left:
return "Left";
case Qt::Key_Right:
return "Right";
case Qt::Key_Escape:
return "Esc";
case Qt::Key_Home:
return "Home";
case Qt::Key_End:
return "End";
case Qt::Key_Insert:
return "Insert";
case Qt::Key_Delete:
return "Del";
case Qt::Key_PageUp:
return "PageUp";
case Qt::Key_PageDown:
return "PageDown";
case Qt::Key_Less:
return "LT";
case Qt::Key_Space:
return "Space";
case Qt::Key_F1:
return "F1";
case Qt::Key_F2:
return "F2";
case Qt::Key_F3:
return "F3";
case Qt::Key_F4:
return "F4";
case Qt::Key_F5:
return "F5";
case Qt::Key_F6:
return "F6";
case Qt::Key_F7:
return "F7";
case Qt::Key_F8:
return "F8";
case Qt::Key_F9:
return "F9";
case Qt::Key_F10:
return "F10";
case Qt::Key_F11:
return "F11";
case Qt::Key_F12:
return "F12";
case Qt::Key_F13:
return "F13";
case Qt::Key_F14:
return "F14";
case Qt::Key_F15:
return "F15";
case Qt::Key_F16:
return "F16";
case Qt::Key_F17:
return "F17";
case Qt::Key_F18:
return "F18";
case Qt::Key_F19:
return "F19";
case Qt::Key_F20:
return "F20";
default:
*special = false;
return event->text().toStdString();
}
}
[[maybe_unused]]
static bool is_modifier(int key)
{
switch(key)
{
case Qt::Key_Meta:
case Qt::Key_Control:
case Qt::Key_Alt:
case Qt::Key_AltGr:
case Qt::Key_Shift:
case Qt::Key_Super_L:
case Qt::Key_Super_R:
case Qt::Key_CapsLock:
return true;
default:
return false;
}
return false;
}
/// Taken from Neovim-Qt's "IsAsciiCharRequiringAlt" function in input.cpp.
[[maybe_unused]]
static bool requires_alt(int key, Qt::KeyboardModifiers mods, QChar c)
{
// Ignore all key events where Alt is not pressed
if (!(mods & Qt::AltModifier)) return false;
// These low-ascii characters may require AltModifier on MacOS
if ((c == '[' && key != Qt::Key_BracketLeft)
|| (c == ']' && key != Qt::Key_BracketRight)
|| (c == '{' && key != Qt::Key_BraceLeft)
|| (c == '}' && key != Qt::Key_BraceRight)
|| (c == '|' && key != Qt::Key_Bar)
|| (c == '~' && key != Qt::Key_AsciiTilde)
|| (c == '@' && key != Qt::Key_At))
{
return true;
}
return false;
}
/// Normalizes a key event. Does nothing for non-Mac platforms.
/// Taken from Neovim-Qt's "CreatePlatformNormalizedKeyEvent"
/// function for each platform.
static QKeyEvent normalize_key_event(
QEvent::Type type,
int key,
Qt::KeyboardModifiers mods,
const QString& text
)
{
#if !defined(Q_OS_MAC)
return {type, key, mods, text};
#else
if (text.isEmpty())
{
return {type, key, mods, text};
}
const QChar& c = text.at(0);
if ((c.unicode() >= 0x80 && c.isPrint()) || requires_alt(key, mods, c))
{
mods &= ~Qt::AltModifier;
}
return {type, key, mods, text};
#endif // !defined(Q_OS_MAC)
}
/// Taken from Neovim-Qt's Input::ControlModifier()
static constexpr auto c_mod()
{
#if defined(Q_OS_WIN)
return Qt::ControlModifier;
#elif defined(Q_OS_MAC)
return Qt::MetaModifier;
#else
return Qt::ControlModifier;
#endif
}
/// Taken from NeovimQt's Input::CmdModifier()
static constexpr auto d_mod()
{
#if defined(Q_OS_WIN)
return Qt::NoModifier;
#elif defined(Q_OS_MAC)
return Qt::ControlModifier;
#else
return Qt::MetaModifier;
#endif
}
static std::string mod_prefix(Qt::KeyboardModifiers mods)
{
std::string result;
if (mods & Qt::ShiftModifier) result.append("S-");
if (mods & c_mod()) result.append("C-");
if (mods & Qt::AltModifier) result.append("M-");
if (mods & d_mod()) result.append("D-");
return result;
}
/// Equivalent of Neovim's "ToKeyString",
/// but returning an std::string.
static std::string key_mod_str(
Qt::KeyboardModifiers mods,
std::string_view text
)
{
return fmt::format("<{}{}>", mod_prefix(mods), text);
}
/// Derived from Neovim-Qt's NeovimQt::Input::convertKey
/// method, see
/// https://github.com/equalsraf/neovim-qt/blob/master/src/gui/input.cpp#L144
static std::string convertKey(const QKeyEvent& ev) noexcept
{
bool x = requires_alt(0, Qt::NoModifier, 0);
Q_UNUSED(x);
QString text = ev.text();
auto mod = ev.modifiers();
int key = ev.key();
static const std::unordered_map<int, std::string_view> keypadKeys {
{ Qt::Key_Home, "Home" },
{ Qt::Key_End, "End" },
{ Qt::Key_PageUp, "PageUp" },
{ Qt::Key_PageDown, "PageDown" },
{ Qt::Key_Plus, "Plus" },
{ Qt::Key_Minus, "Minus" },
{ Qt::Key_multiply, "Multiply" },
{ Qt::Key_division, "Divide" },
{ Qt::Key_Enter, "Enter" },
{ Qt::Key_Period, "Point" },
{ Qt::Key_0, "0" },
{ Qt::Key_1, "1" },
{ Qt::Key_2, "2" },
{ Qt::Key_3, "3" },
{ Qt::Key_4, "4" },
{ Qt::Key_5, "5" },
{ Qt::Key_6, "6" },
{ Qt::Key_7, "7" },
{ Qt::Key_8, "8" },
{ Qt::Key_9, "9" },
};
#ifdef Q_OS_WIN
/// Windows sends Ctrl+Alt when AltGr is pressed,
/// but the text already factors in AltGr. Solution: Ignore Ctrl and Alt
if ((mod & Qt::ControlModifier) && (mod & Qt::AltModifier))
{
mod &= ~Qt::ControlModifier;
mod &= ~Qt::AltModifier;
}
#endif // Q_OS_WIN
if (mod & Qt::KeypadModifier && keypadKeys.contains(key))
{
return fmt::format("<{}{}>", mod_prefix(mod), keypadKeys.at(key));
}
// Issue#917: On Linux, Control + Space sends text as "\u0000"
if (key == Qt::Key_Space && text.size() > 0 && !text.at(0).isPrint())
{
text = " ";
}
bool is_special = false;
auto s = event_to_string(&ev, &is_special);
if (is_special)
{
if (key == Qt::Key_Space
|| key == Qt::Key_Backspace)
{
mod &= ~Qt::ShiftModifier;
}
return key_mod_str(mod, s);
}
// Issue#864: Some international layouts insert accents (~^`) on Key_Space
if (key == Qt::Key_Space && !text.isEmpty() && text != " ")
{
if (mod != Qt::NoModifier)
{
return key_mod_str(mod, text.toStdString());
}
return text.toStdString();
}
// The key "<" should be sent as "<lt>"
// Issue#607: Remove ShiftModifier from "<", shift is implied
if (text == "<")
{
const Qt::KeyboardModifiers modNoShift = mod & ~Qt::KeyboardModifier::ShiftModifier;
return key_mod_str(modNoShift, "LT");
}
// Issue#170: Normalize modifiers, CTRL+^ always sends as <C-^>
const bool isCaretKey = (key == Qt::Key_6 || key == Qt::Key_AsciiCircum);
if (isCaretKey && mod & c_mod())
{
const Qt::KeyboardModifiers modNoShiftMeta = mod
& Qt::KeyboardModifier::ShiftModifier
& ~d_mod();
return key_mod_str(modNoShiftMeta, "^");
}
if (text == "\\")
{
return key_mod_str(mod, "Bslash");
}
if (text.isEmpty())
{
// Ignore all modifier-only key events.
// Issue#344: Ignore Ctrl-Shift, C-S- being treated as C-Space
// Issue#593: Pressing Control + Super inserts ^S
// Issue#199: Pressing Control + CapsLock inserts $
if (is_modifier(key)) return {};
// Ignore special keys
// Issue#671: `q`/`p`/`r` key is sent by Mute/Volume DOWN/Volume UP
if (key == Qt::Key::Key_VolumeDown
|| key == Qt::Key::Key_VolumeMute
|| key == Qt::Key::Key_VolumeUp) return {};
text = QChar(key);
if (!(mod & Qt::ShiftModifier)) text = text.toLower();
}
const QChar c = text.at(0);
// Remove Shift, skip when ALT or CTRL are pressed
if ((c.unicode() >= 0x80 || c.isPrint())
&& !(mod & c_mod()) && !(mod & d_mod()))
{
mod &= ~Qt::ShiftModifier;
}
// Ignore empty characters at the start of the ASCII range
if (c.unicode() < 0x20)
{
text = QChar(key);
if (!(mod & Qt::ShiftModifier)) text = text.toLower();
}
// Perform any platform specific QKeyEvent modifications
auto evNormalized = normalize_key_event(ev.type(), key, mod, text);
const auto prefix = mod_prefix(evNormalized.modifiers());
if (!prefix.empty())
{
auto normalized_mods = evNormalized.modifiers();
return key_mod_str(normalized_mods, evNormalized.text().toStdString());
}
return evNormalized.text().toStdString();
}
std::string convert_key(const QKeyEvent& ev)
{
return convertKey(ev);
}
| 24.508242
| 88
| 0.604417
|
IndianBoy42
|
a82690d7915b913444a0c189e9685ec1854247e7
| 478
|
cpp
|
C++
|
experiments/ym2612/note.cpp
|
krismuad/TOWNSEMU
|
49c098ecb4686a506a208e01271ed135c0c3c482
|
[
"BSD-3-Clause"
] | 124
|
2020-03-17T05:49:47.000Z
|
2022-03-27T00:11:33.000Z
|
experiments/ym2612/note.cpp
|
krismuad/TOWNSEMU
|
49c098ecb4686a506a208e01271ed135c0c3c482
|
[
"BSD-3-Clause"
] | 40
|
2020-05-24T12:50:43.000Z
|
2022-02-22T05:32:18.000Z
|
experiments/ym2612/note.cpp
|
krismuad/TOWNSEMU
|
49c098ecb4686a506a208e01271ed135c0c3c482
|
[
"BSD-3-Clause"
] | 11
|
2020-05-26T17:52:04.000Z
|
2021-07-31T01:07:31.000Z
|
// Does the formula on [2] pp.204 make sense? It doesn't.
#include <iostream>
int main(void)
{
for(unsigned int F_NUM=0; F_NUM<2048; F_NUM+=64)
{
unsigned int F10=((F_NUM>>10)&1);
unsigned int F9= ((F_NUM>> 9)&1);
unsigned int F8= ((F_NUM>> 8)&1);
unsigned int F7=((F_NUM>>11)&1);
unsigned int N3=(F10&(F9|F8|F7))|((~F10)&F9&F8&F7);
unsigned int NOTE=(F10<<1)|N3;
std::cout << F_NUM << "(" << (F_NUM>>9) << ")"<< "->" << NOTE << std::endl;
};
return 0;
}
| 23.9
| 78
| 0.569038
|
krismuad
|
a8295c5de04e8b5d3f31168570e16bcbc659076e
| 11,467
|
cpp
|
C++
|
CSRMatrix.cpp
|
Mountiko/LinearSolvers
|
ffb4e18adc64951f730f9d1d5254ca55efc5d7ed
|
[
"MIT"
] | 3
|
2020-07-29T10:45:32.000Z
|
2022-02-03T02:32:59.000Z
|
CSRMatrix.cpp
|
Mountiko/LinearSolvers
|
ffb4e18adc64951f730f9d1d5254ca55efc5d7ed
|
[
"MIT"
] | null | null | null |
CSRMatrix.cpp
|
Mountiko/LinearSolvers
|
ffb4e18adc64951f730f9d1d5254ca55efc5d7ed
|
[
"MIT"
] | 5
|
2020-08-04T14:44:17.000Z
|
2021-12-11T04:28:47.000Z
|
#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
#include "CSRMatrix.h"
using namespace std;
// Constructor - using an initialisation list here
template <class T>
CSRMatrix<T>::CSRMatrix(int rows, int cols, int nnzs, bool preallocate):\
Matrix<T>(rows, cols, false), nnzs(nnzs)
{
// If we don't pass false in the initialisation list base constructor,
// it would allocate values to be of size
// rows * cols in our base matrix class
// So then we need to set it to the real value we had passed in
this->preallocate = preallocate;
// If we want to handle memory ourselves
if (this->preallocate)
{
// Must remember to delete this in the destructor
this->values.reset(new T[this->nnzs]);
this->row_position.reset(new int[this->rows+1]);
this->col_index.reset(new int[this->nnzs]);
}
}
// Constructor - now just setting the value of our T pointer
template <class T>
CSRMatrix<T>::CSRMatrix(int rows, int cols, int nnzs, T *values_ptr,\
int *row_position, int *col_index): Matrix<T>(rows, cols, values_ptr),\
nnzs(nnzs)
{
this->row_position.reset(row_position);
this->col_index.reset(col_index);
}
// destructor
template <class T>
CSRMatrix<T>::~CSRMatrix()
{}
// turn a dense matrix intpo a CSR matrix
template<class T>
void CSRMatrix<T>::dense2csr(const Matrix<T>& denseMat)
{
if (this->rows != denseMat.rows || this->cols != denseMat.cols)
{
cerr << "Dimensions of CSR matrix and dense Matrix don't match!" << endl;
return;
}
this->row_position[0] = 0; // IA has the first element as 0
int non_zero_count = 0;
for (int i = 0; i < this->rows; i++)
{
for (int j = 0; j < this->cols; j++)
{
if (denseMat.values[i * this->rows + j] != 0)
{
this->col_index[non_zero_count] = j;
this->values[non_zero_count++] =\
denseMat.values[i * this->rows + j];
}
}
row_position[i+1] = non_zero_count;
}
}
// turn a CSR matrix into a dense matrix
template<class T>
void CSRMatrix<T>::csr2dense(Matrix<T>& denseMat)
{
if (this->rows != denseMat.rows || this->cols != denseMat.cols)
{
cerr << "Dimensions of CSR matrix and dense Matrix don't match!" << endl;
return;
}
for (int i = 0; i < this->nnzs; i++)
{
for (int val_index = this->row_position[i];\
val_index < this->row_position[i+1]; val_index++)
{
denseMat.values[i * this->cols + this->col_index[val_index]] =\
this->values[val_index];
}
}
}
// Explicitly print out the values in values array as if they are a matrix
template <class T>
void CSRMatrix<T>::printMatrix()
{
std::cout << "Printing CSR Matrix" << std::endl;
std::cout << "Values: ";
for (int j = 0; j< this->nnzs; j++)
{
std::cout << this->values[j] << " ";
}
std::cout << std::endl;
std::cout << "row_position: ";
for (int j = 0; j< this->rows+1; j++)
{
std::cout << this->row_position[j] << " ";
}
std::cout << std::endl;
std::cout << "col_index: ";
for (int j = 0; j< this->nnzs; j++)
{
std::cout << this->col_index[j] << " ";
}
std::cout << std::endl;
}
// Do a matrix-vector product
// output = this * input
template<class T>
void CSRMatrix<T>::matVecMult(T* &b, T *x)
{
if (b == nullptr || x == nullptr)
{
std::cerr << "b or x haven't been created" << std::endl;
return;
}
// Set the output to zero
for (int i = 0; i < this->rows; i++)
{
x[i] = 0.0;
}
int val_counter = 0;
// Loop over each row
for (int i = 0; i < this->rows; i++)
{
// Loop over all the entries in this col
for (int val_index = this->row_position[i]; \
val_index < this->row_position[i+1]; val_index++)
{
// This is an example of indirect addressing
// Can make it harder for the compiler to vectorise!
x[i] += this->values[val_index] * b[this->col_index[val_index]];
}
}
}
// Do matrix matrix multiplication
// output = this * mat_right
template <class T>
void CSRMatrix<T>::matMatMult(CSRMatrix<T>& B, CSRMatrix<T>* &X)
{
// Check our dimensions match
if (this->cols != B.rows)
{
std::cerr << "Input dimensions for matrices don't match" << std::endl;
return;
}
// set temporary vectors to store indices and computed values
vector<matRes<T>> temp;
// Loop over each row
for (int i = 0; i < this->rows; i++)
{
// Loop over the non-zero values in the i-th row of LHS matrix
for (int val_index = this->row_position[i];\
val_index < this->row_position[i+1]; val_index++)
{
// Loop over the non-zero values of RHS matrix
// with matching indices:
// row-index of LHS matrix matches column-index of RHS matrix
for (int row_index = B.row_position[this->col_index[val_index]];\
row_index < B.row_position[this->col_index[val_index] + 1];\
row_index++)
{
// record position of the idividual values
// ie record row index and column index for each multiplied value
matRes<T> res; // create struct to store result
// populate res object
res.inner = B.col_index[row_index];
res.outer = i;
res.value = this->values[val_index] * B.values[row_index];
// push to the temp struct
temp.push_back(res);
}
}
}
// sort the entries of temp, initially
// according to column and then according to row
sort(temp.begin(), temp.end(), this->compareMatResInner);
sort(temp.begin(), temp.end(), this->compareMatResOut);
// create vectors to temporarily store the arrays of our CSR output Matrix
vector<T> values;
vector<int> cols;
vector<int> rows;
rows.push_back(0); // first entry of rows is always 0
// in this loop we essentially add together the results of our
// multiplications to populate the output matrix
for (int i = 0; i < temp.size(); i++)
{
// create temporary variable
T tem = temp[i].value;
// if the next value belongs to the same position in the output matrix
// then add it, else move on.
while ((i+1) != temp.size() && temp[i].outer == temp[i+1].outer &&\
temp[i].inner == temp[i+1].inner)
{
tem += temp[i+1].value;
i++;
}
// add it to the values array
values.push_back(tem);
// add the row position to the cols array
cols.push_back(temp[i].inner);
// get the number of rows that hold no entries
if ((i+1) != temp.size() && (temp[i+1].outer - temp[i].outer > 0)) {
int dif = temp[i+1].outer - temp[i].outer;
// push to the rows the value size to indicate empty row
for (int j = 0; j < dif; j++) rows.push_back(values.size());
}
}
// make sure that rows with zeros in the end of
// the output matrix ger represented.
while (rows.size() <= this->rows+1) {
rows.push_back(values.size());
}
// initialize the pointer we gave as input
X = new CSRMatrix<T>(this->rows, this->cols, values.size(), true);
// populate the output matrix
for (int i =0; i < values.size(); i++)
{
X->values[i] = values[i];
X->col_index[i] = cols[i];
}
for (int i = 0; i < rows.size(); i++) X->row_position[i] = rows[i];
}
// Helper function for matMatMult
// compares the inner struct elements of two matRes objects
template<class T>
bool CSRMatrix<T>::compareMatResInner(matRes<T> a, matRes<T> b)
{
// return bool for comparison
return (a.inner < b.inner);
}
// Helper function for matMatMult
// compares the outer struct elements of two matRes objects
template<class T>
bool CSRMatrix<T>::compareMatResOut(matRes<T> a, matRes<T> b)
{
// return bool for comparison
return (a.outer < b.outer);
}
// the algorithm for this function is found on:
// https://en.wikipedia.org/wiki/Successive_over-relaxation
template<class T>
void CSRMatrix<T>::SOR(T *b, T *x, double omega, double atol)
{
// check if omega is set well
if (omega <= 0 || omega >= 2)
{
cout << "Error: 0 < omega < 1" << endl;
return;
}
// set default initial guess
for (int i = 0; i < this->cols; i++)
{
x[i] = (T)1;
}
// initiate array pointers to store A*x
// and rk
T* x_A = new T[this->cols];
T* r_k = new T[this->rows];
// compute A*x
this->matVecMult(x, x_A);
// initiate a variable for the residual
double tot_rk = 0;
// compute residual as vector norm
for (int i = 0; i < this->rows; i++)
{
// res = b - Ax
r_k[i] = b[i] - x_A[i];
tot_rk += r_k[i] * r_k[i];
}
tot_rk = sqrt(tot_rk); // sqrt to complete vector norm
// initiate count
int count = 0;
// and the algorithm iterations start
while (tot_rk >= atol)
{
// loop through rows and cols
for (int i = 0; i < this->rows; i++)
{
double sigma = 0; // reset sigma to zero to re-compute it
T diag_val = 0;
// loop through all nnzs of the ith row
for (int val_index = this->row_position[i];\
val_index < this->row_position[i+1]; val_index++)
{
// if valie not in diagonal
// multiply it with the element in x
// that has the same index as the column index of the
// non zero value of the current iteration
if (this->col_index[val_index] != i)
{
sigma += this->values[val_index] *\
x[this->col_index[val_index]];
}
else if(this->col_index[val_index] == i)
{
diag_val = this->values[val_index];
}
}
// computing ith value of result for current interation
x[i] = (1 - omega) * x[i] +\
(omega / diag_val) * (b[i] - sigma);
}
// reset residual
tot_rk = 0;
// compute A*x
this->matVecMult(x, x_A);
// compute total residual using vector norm
for (int i = 0; i < this->rows; i++)
{
r_k[i] = b[i] - x_A[i];
tot_rk += r_k[i] * r_k[i];
}
tot_rk = sqrt(tot_rk); // sqrt to complete vector norm
// update count
count++;
// break at maximum
if (count == 10000)
{
cout << "SOR CRS is not converging!!!" << endl;
break;
}
/*
// print some cool stuff
cout << "Iteration: " << count << endl;
cout << "Residual: " << tot_rk << endl;
cout << "x:" << endl;
for (int i = 0; i < this->rows; i++)
{
cout << x[i] << endl;
} */
}
// print some cool stuff at the end
cout << "Total iteration; " << count << endl;
cout << "Total Residual: " << tot_rk << endl;
delete[] x_A;
delete[] r_k;
}
| 30.335979
| 81
| 0.547222
|
Mountiko
|
a82a51412f5e80e196b60776533499f799c02255
| 19,339
|
cpp
|
C++
|
src/test/interface/io/json/json_parser_test.cpp
|
jtimonen/cmdstan
|
8c1e014ed28b4ac3b0f8acc676a4508d07ab8f10
|
[
"BSD-3-Clause"
] | null | null | null |
src/test/interface/io/json/json_parser_test.cpp
|
jtimonen/cmdstan
|
8c1e014ed28b4ac3b0f8acc676a4508d07ab8f10
|
[
"BSD-3-Clause"
] | null | null | null |
src/test/interface/io/json/json_parser_test.cpp
|
jtimonen/cmdstan
|
8c1e014ed28b4ac3b0f8acc676a4508d07ab8f10
|
[
"BSD-3-Clause"
] | null | null | null |
#include <cmdstan/io/json/json_data.hpp>
#include <cmdstan/io/json/json_data_handler.hpp>
#include <cmdstan/io/json/json_error.hpp>
#include <cmdstan/io/json/json_handler.hpp>
#include <cmdstan/io/json/rapidjson_parser.hpp>
#include <gtest/gtest.h>
class recording_handler : public cmdstan::json::json_handler {
public:
std::stringstream os_;
recording_handler() : json_handler(), os_() {}
void start_text() { os_ << "S:text"; }
void end_text() { os_ << "E:text"; }
void start_array() { os_ << "S:arr"; }
void end_array() { os_ << "E:arr"; }
void start_object() { os_ << "S:obj"; }
void end_object() { os_ << "E:obj"; }
void null() { os_ << "NULL:null"; }
void boolean(bool p) { os_ << "BOOL:" << p; }
void string(const std::string &s) { os_ << "STR:\"" << s << "\""; }
void key(const std::string &key) { os_ << "KEY:\"" << key << "\""; }
void number_double(double x) { os_ << "D(REAL):" << x; }
void number_int(int n) { os_ << "I(INT):" << n; }
void number_unsigned_int(unsigned n) { os_ << "U(INT):" << n; }
void number_int64(int64_t n) { os_ << "I64(INT):" << n; }
void number_unsigned_int64(uint64_t n) { os_ << "U64(INT):" << n; }
};
bool hasEnding(std::string const &fullString, std::string const &ending) {
if (fullString.length() >= ending.length()) {
return (0
== fullString.compare(fullString.length() - ending.length(),
ending.length(), ending));
} else {
return false;
}
}
void test_parser(const std::string &input, const std::string &expected_output) {
recording_handler handler;
std::stringstream s(input);
cmdstan::json::rapidjson_parse(s, handler);
EXPECT_EQ(expected_output, handler.os_.str());
}
void test_exception(const std::string &input,
const std::string &exception_text) {
try {
recording_handler handler;
std::stringstream s(input);
cmdstan::json::rapidjson_parse(s, handler);
} catch (const std::exception &e) {
EXPECT_TRUE(hasEnding(e.what(), exception_text));
return;
}
FAIL(); // didn't throw an exception as expected.
}
TEST(ioJson, jsonParserA0) {
test_parser("[0]",
"S:text"
"S:arr"
"U(INT):0"
"E:arr"
"E:text");
}
TEST(ioJson, jsonParserA1) {
test_parser("[5]",
"S:text"
"S:arr"
"U(INT):5"
"E:arr"
"E:text");
}
TEST(ioJson, jsonParserA2) {
test_parser("[5,10]",
"S:text"
"S:arr"
"U(INT):5"
"U(INT):10"
"E:arr"
"E:text");
}
TEST(ioJson, jsonParserA3) {
test_parser("[]",
"S:text"
"S:arr"
"E:arr"
"E:text");
}
TEST(ioJson, jsonParserA4) {
std::stringstream textReport;
textReport << "S:text"
<< "S:arr"
<< "D(REAL):" << 0.100019 << "E:arr"
<< "E:text";
test_parser("[ 0.100019 ]", textReport.str());
}
TEST(ioJson, jsonParserA5) {
std::stringstream textReport;
textReport << "S:text"
<< "S:arr"
<< "D(REAL):" << 0.10001900 << "E:arr"
<< "E:text";
test_parser("[ 0.10001900 ]", textReport.str());
}
TEST(ioJson, jsonParserA6) {
std::stringstream textReport;
textReport << "S:text"
<< "S:arr"
<< "D(REAL):" << -0.10001900 << "E:arr"
<< "E:text";
test_parser("[ -0.10001900 ]", textReport.str());
}
TEST(ioJson, jsonParserA7) {
test_parser("[ -1, -2, \"-inf\"]",
"S:text"
"S:arr"
"I(INT):-1"
"I(INT):-2"
"STR:\"-inf\""
"E:arr"
"E:text");
}
TEST(ioJson, jsonParserA8) {
test_parser("[ [ -1, -2 ],[ 1, 2 ] ]",
"S:text"
"S:arr"
"S:arr"
"I(INT):-1"
"I(INT):-2"
"E:arr"
"S:arr"
"U(INT):1"
"U(INT):2"
"E:arr"
"E:arr"
"E:text");
}
TEST(ioJson, jsonParserA9) {
test_parser("[ [ [1, 2 ],[ 3, 4 ] ],[ [5, 6 ],[ 7, 8 ] ] ]",
"S:text"
"S:arr"
"S:arr"
"S:arr"
"U(INT):1"
"U(INT):2"
"E:arr"
"S:arr"
"U(INT):3"
"U(INT):4"
"E:arr"
"E:arr"
"S:arr"
"S:arr"
"U(INT):5"
"U(INT):6"
"E:arr"
"S:arr"
"U(INT):7"
"U(INT):8"
"E:arr"
"E:arr"
"E:arr"
"E:text");
}
TEST(ioJson, jsonParserA10) {
std::stringstream textReport;
textReport << "S:text"
<< "S:arr"
<< "I(INT):-2147483648"
<< "U(INT):2147483647"
<< "I64(INT):-2147483649"
<< "U(INT):2147483648"
<< "U(INT):4294967295"
<< "U64(INT):4294967296"
<< "I64(INT):-9223372036854775808"
<< "U64(INT):9223372036854775807"
<< "U64(INT):18446744073709551615"
<< "D(REAL):" << -9223372036854775809.0
<< "U64(INT):9223372036854775808"
<< "D(REAL):" << 18446744073709551616.0 << "E:arr"
<< "E:text";
test_parser(
"[ -2147483648, 2147483647, -2147483649, 2147483648, "
"4294967295, 4294967296, "
"-9223372036854775808, 9223372036854775807, 18446744073709551615, "
"-9223372036854775809, 9223372036854775808, 18446744073709551616 ]",
textReport.str());
}
TEST(ioJson, jsonParserO1) {
test_parser("{ \"foo\" : 1 } ",
"S:text"
"S:obj"
"KEY:\"foo\""
"U(INT):1"
"E:obj"
"E:text");
}
TEST(ioJson, jsonParserO11) {
test_parser("{ \"foo\" : { \"bar\": 1 } } ",
"S:text"
"S:obj"
"KEY:\"foo\""
"S:obj"
"KEY:\"bar\""
"U(INT):1"
"E:obj"
"E:obj"
"E:text");
}
TEST(ioJson, jsonParserO12) {
test_parser("{ \"foo\" : { \"bar\": 1, \"baz\": 2 } } ",
"S:text"
"S:obj"
"KEY:\"foo\""
"S:obj"
"KEY:\"bar\""
"U(INT):1"
"KEY:\"baz\""
"U(INT):2"
"E:obj"
"E:obj"
"E:text");
}
TEST(ioJson, jsonParserO13) {
test_parser("{ \"foo\" : { \"bar\": { \"baz\": [ 1, 2] } } } ",
"S:text"
"S:obj"
"KEY:\"foo\""
"S:obj"
"KEY:\"bar\""
"S:obj"
"KEY:\"baz\""
"S:arr"
"U(INT):1"
"U(INT):2"
"E:arr"
"E:obj"
"E:obj"
"E:obj"
"E:text");
}
TEST(ioJson, jsonParserO14) {
test_parser(
"{ \"foo\" : [ { \"bar\": { \"baz\": [ 1, 2] } }, -3, -4.44 ] } ",
"S:text"
"S:obj"
"KEY:\"foo\""
"S:arr"
"S:obj"
"KEY:\"bar\""
"S:obj"
"KEY:\"baz\""
"S:arr"
"U(INT):1"
"U(INT):2"
"E:arr"
"E:obj"
"E:obj"
"I(INT):-3"
"D(REAL):-4.44"
"E:arr"
"E:obj"
"E:text");
}
TEST(ioJson, jsonParserO2) {
test_parser("{ \"foo\" : 1 , \n \"bar\" : 2 }",
"S:text"
"S:obj"
"KEY:\"foo\""
"U(INT):1"
"KEY:\"bar\""
"U(INT):2"
"E:obj"
"E:text");
}
TEST(ioJson, jsonParserO3) {
test_parser("{\"foo\":1,\"bar\":2,\"baz\":[2]}",
"S:text"
"S:obj"
"KEY:\"foo\""
"U(INT):1"
"KEY:\"bar\""
"U(INT):2"
"KEY:\"baz\""
"S:arr"
"U(INT):2"
"E:arr"
"E:obj"
"E:text");
}
TEST(ioJson, jsonParserO4) {
std::stringstream textReport;
textReport << "S:text"
<< "S:obj"
<< "KEY:\"foo\""
<< "U(INT):1"
<< "KEY:\"baz\""
<< "S:arr"
<< "U(INT):2"
<< "U(INT):3"
<< "D(REAL):" << 4.01001 << "E:arr"
<< "E:obj"
<< "E:text";
test_parser("{ \"foo\" : 1, \n \"baz\" : [ 2, 3, 4.01001 ] }",
textReport.str());
}
TEST(ioJson, jsonParserO5) {
std::stringstream textReport;
textReport << "S:text"
<< "S:obj"
<< "KEY:\"foo\""
<< "D(REAL):" << -0.10001900 << "E:obj"
<< "E:text";
test_parser("{ \"foo\": -0.10001900 }", textReport.str());
}
TEST(ioJson, jsonParserO6) {
std::stringstream textReport;
textReport << "S:text"
<< "S:obj"
<< "KEY:\"foo\""
<< "D(REAL):" << -1.0100e09 << "E:obj"
<< "E:text";
test_parser("{ \"foo\": -1.0100e09 }", textReport.str());
}
TEST(ioJson, jsonParserO7) {
std::stringstream textReport;
textReport << "S:text"
<< "S:obj"
<< "KEY:\"foo\""
<< "D(REAL):" << -1.0100e09 << "E:obj"
<< "E:text";
test_parser("{ \"foo\": -1.0100e09 }", textReport.str());
}
TEST(ioJson, jsonParserStr0) {
test_parser("[ \"foo\" ]",
"S:text"
"S:arr"
"STR:\"foo\""
"E:arr"
"E:text");
}
TEST(ioJson, jsonParserStr1) {
test_parser("[ \"\\nfoo\" ]",
"S:text"
"S:arr"
"STR:\"\nfoo\""
"E:arr"
"E:text");
}
TEST(ioJson, jsonParserStr2) {
test_parser("[ \"\\nfoo\\bbar\" ]",
"S:text"
"S:arr"
"STR:\"\nfoo\bbar\""
"E:arr"
"E:text");
}
TEST(ioJson, jsonParserStr3) {
test_parser("[ \"\\bfoo\\nbar\" ]",
"S:text"
"S:arr"
"STR:\"\bfoo\nbar\""
"E:arr"
"E:text");
}
TEST(ioJson, jsonParserStr4) {
test_parser("[ \"\\\"foo\\/bar\" ]",
"S:text"
"S:arr"
"STR:\"\"foo/bar\""
"E:arr"
"E:text");
}
TEST(ioJson, jsonParserStr5) {
test_parser("[ \"\\\"foo\\\\bar\" ]",
"S:text"
"S:arr"
"STR:\"\"foo\\bar\""
"E:arr"
"E:text");
}
TEST(ioJson, jsonParserStr6) {
test_parser("[ \"\\tfoo\\tbar\" ]",
"S:text"
"S:arr"
"STR:\"\tfoo\tbar\""
"E:arr"
"E:text");
}
TEST(ioJson, jsonParserStr7) {
test_parser("[ \"\\nfoo\\nbar\\n\" ]",
"S:text"
"S:arr"
"STR:\"\nfoo\nbar\n\""
"E:arr"
"E:text");
}
TEST(ioJson, jsonParserStr8) {
test_parser("[ \"\\nfoo\\nbar\\\"\" ]",
"S:text"
"S:arr"
"STR:\"\nfoo\nbar\"\""
"E:arr"
"E:text");
}
TEST(ioJson, jsonParserStr9) {
test_parser("[ \"foo\\nbar\\\"\" , \"foo\\nbar\\\"\" ]",
"S:text"
"S:arr"
"STR:\"foo\nbar\"\""
"STR:\"foo\nbar\"\""
"E:arr"
"E:text");
}
TEST(ioJson, jsonParserStr10) {
test_parser("[ \"\\u0069\" ]",
"S:text"
"S:arr"
"STR:\"i\""
"E:arr"
"E:text");
}
// surrogate pair for G clef character from extended multilingual plane:
// specified here using hex values for non-ASCII UTF-8 bytes
TEST(ioJson, jsonParserStr11) {
test_parser("[ \"\\uD834\\uDD1E\" ]",
"S:text"
"S:arr"
"STR:\"\xf0\x9D\x84\x9E\""
"E:arr"
"E:text");
}
// string w/ two non-ascii Latin 1 chars
TEST(ioJson, jsonParserStr12) {
test_parser("[ \"D\\u00E9j\\u00E0 vu\" ]",
"S:text"
"S:arr"
"STR:\"D\xc3\xa9j\xc3\xa0 vu\""
"E:arr"
"E:text");
}
// same string w/ non-ASCII chars not \u escaped (specified as hex byte values)
TEST(ioJson, jsonParserStr13) {
test_parser("[ \"D\xc3\xa9j\xc3\xa0 vu\" ]",
"S:text"
"S:arr"
"STR:\"D\xc3\xa9j\xc3\xa0 vu\""
"E:arr"
"E:text");
}
// surrogate pair boundary conditions
TEST(ioJson, jsonParserStr14) {
test_parser("[ \"\\uD800\\uDC00\" ]",
"S:text"
"S:arr"
"STR:\"\xf0\x90\x80\x80\""
"E:arr"
"E:text");
}
// surrogate pair boundary conditions
TEST(ioJson, jsonParserStr15) {
test_parser("[ \"\\uD800\\uDFFF\" ]",
"S:text"
"S:arr"
"STR:\"\xf0\x90\x8F\xBF\""
"E:arr"
"E:text");
}
// surrogate pair boundary conditions
TEST(ioJson, jsonParserStr16) {
test_parser("[ \"\\uDBFF\\uDC00\" ]",
"S:text"
"S:arr"
"STR:\"\xf4\x8f\xb0\x80\""
"E:arr"
"E:text");
}
// surrogate pair boundary conditions
TEST(ioJson, jsonParserStr17) {
test_parser("[ \"a\\uE000\" ]",
"S:text"
"S:arr"
"STR:\"a\xEE\x80\x80\""
"E:arr"
"E:text");
}
TEST(ioJson, jsonParserErr01) {
test_exception(" \n \n 5 ",
"expecting start of object ({) or array ([)\n");
}
TEST(ioJson, jsonParserErr02) { test_exception("[ .5 ]", "Invalid value.\n"); }
TEST(ioJson, jsonParserErr02a) {
test_exception("[ 0",
"Missing a comma or ']' after an array element or "
"found a zero padded number.\n");
}
TEST(ioJson, jsonParserErr02b) {
test_exception("[ 0.", "Missing fraction part in number.\n");
}
TEST(ioJson, jsonParserErr02c) {
test_exception("[ 99.9",
"Missing a comma or ']' after an array element or "
"found a zero padded number.\n");
}
TEST(ioJson, jsonParserErr03) {
test_exception("[ 000.005 ]",
"Missing a comma or ']' after an array element "
"or found a zero padded number.\n");
}
TEST(ioJson, jsonParserErr04) {
test_exception("[ 1. ]", "Missing fraction part in number.\n");
}
TEST(ioJson, jsonParserErr05) {
test_exception("[ 1.009e ]", "Missing exponent in number.\n");
}
TEST(ioJson, jsonParserErr06b) {
test_exception("[ \"\\uD834abc\" ]",
"The surrogate pair in string is invalid.\n");
}
TEST(ioJson, jsonParserErr06e) {
test_exception("[ \"\\uD834", "The surrogate pair in string is invalid.\n");
}
TEST(ioJson, jsonParserErr06f) {
test_exception("[ \"\\uD8",
"Incorrect hex digit after \\u escape in string.\n");
}
TEST(ioJson, jsonParserErr06g) {
test_exception("[ \"\\uE000\\uD",
"Incorrect hex digit after \\u escape in string.\n");
}
TEST(ioJson, jsonParserErr07) {
test_exception("[ \"\\aFFFF\" ]", "Invalid escape character in string.\n");
}
TEST(ioJson, jsonParserErr08) {
std::stringstream ss;
char c = 11;
ss << "[ \"" << c << "\" ]";
test_exception(ss.str(), "Invalid encoding in string.\n");
}
TEST(ioJson, jsonParserErr09) { test_exception("[ t ]", "Invalid value.\n"); }
TEST(ioJson, jsonParserErr10) { test_exception("[ f ]", "Invalid value.\n"); }
TEST(ioJson, jsonParserErr11) { test_exception("[ n ]", "Invalid value.\n"); }
TEST(ioJson, jsonParserErr12) {
test_exception("[5}",
"Missing a comma or ']' after an array element or "
"found a zero padded number.\n");
}
TEST(ioJson, jsonParserErr12a) { test_exception("[ a ]", "Invalid value.\n"); }
TEST(ioJson, jsonParserErr12b) {
test_exception("[ \"a\", a ]", "Invalid value.\n");
}
TEST(ioJson, jsonParserErr12c) {
test_exception("[ \"a\", ", "Invalid value.\n");
}
TEST(ioJson, jsonParserErr12d) {
test_exception("{ \"a\" : 5 ] }",
"Missing a comma or '}' after an object member.\n");
}
TEST(ioJson, jsonParserErr12e) {
test_exception("{ \"a\" : [ 5 ] ] }",
"Missing a comma or '}' after an object member.\n");
}
TEST(ioJson, jsonParserErr13) {
test_exception("{ hello }", "Missing a name for object member.\n");
}
TEST(ioJson, jsonParserErr14) {
test_exception("{ \"foo\": -1.0100e09 , }",
"Missing a name for object member.\n");
}
TEST(ioJson, jsonParserErr14a) {
test_exception("{ { \"foo\": -1.0100e09 , }",
"Missing a name for object member.\n");
}
TEST(ioJson, jsonParserErr14b) {
test_exception("{ \"bar\" : { \"foo\": -1.0100e09 , }",
"Missing a name for object member.\n");
}
TEST(ioJson, jsonParserErr14c) {
test_exception("{ \"bar\" : [ \"foo\": -1.0100e09 , }",
"Missing a comma or ']' after an array element or found a "
"zero padded number.\n");
}
TEST(ioJson, jsonParseErr14d) {
test_exception(
"{ \"foo\" : [ { \"bar\": { \"baz\": [ 1, 2] } }, -3, -4.44 } ",
"Missing a comma or ']' after an array element or found a zero padded "
"number.\n");
}
TEST(ioJson, jsonParseErr14e) {
test_exception(
"{ \"foo\" : [ { \"bar\": { \"baz\": [ 1, 2] } }, -3, -4.44 "
"} } } ] } ",
"Missing a comma or ']' after an array element or found a "
"zero padded number.\n");
}
TEST(ioJson, jsonParserErr14f) {
test_exception("{ \"foo\": -1.0100e09 , ",
"Missing a name for object member.\n");
}
TEST(ioJson, jsonParserErr15) {
test_exception("{ \"5\" 5 }",
"Missing a colon after a name of object member.\n");
}
TEST(ioJson, jsonParserErr16) {
test_exception("{ \"5\" : 5 \"6\" : 6 }",
"Missing a comma or '}' after an object member.\n");
}
TEST(ioJson, jsonParserErr17) {
test_exception("{ \"5\" : ", "Invalid value.\n");
}
TEST(ioJson, jsonParserErr18) {
test_exception("[ -1, -2, \"-inf\", ]", "Invalid value.\n");
}
TEST(ioJson, jsonParserErr19a) {
test_exception(
"[ "
"111111111111111111111111111111111111111111111111111111111111111111111111"
"111111111111111111111111111111111111111111111111111111111111111111111111"
"111111111111111111111111111111111111111111111111111111111111111111111111"
"111111111111111111111111111111111111111111111111111111111111111111111111"
"1111111111111111111111 ]",
"Number too big to be stored in double.\n");
}
TEST(ioJson, jsonParserErr19b) {
test_exception(
"[ "
"-11111111111111111111111111111111111111111111111111111111111111111111111"
"111111111111111111111111111111111111111111111111111111111111111111111111"
"111111111111111111111111111111111111111111111111111111111111111111111111"
"111111111111111111111111111111111111111111111111111111111111111111111111"
"11111111111111111111111 ]",
"Number too big to be stored in double.\n");
}
TEST(ioJson, jsonParserErr19d) {
test_exception("[ 9.19191919191919e1000000000000 ]",
"Number too big to be stored in double.\n");
}
| 26.897079
| 80
| 0.475671
|
jtimonen
|
a834c85d046203a3c7f788fbf22628fa9a8a6f6a
| 1,119
|
cpp
|
C++
|
Space Harrier Clone/Engine/BehavioursManager.cpp
|
BrunoAOR/Space-Harrier-Clone
|
35465ad2d421f69a75a02855627c8ea726b248c6
|
[
"MIT"
] | 12
|
2018-12-07T16:05:02.000Z
|
2021-09-06T01:46:50.000Z
|
Potato Engine/Engine/BehavioursManager.cpp
|
BrunoAOR/Potato-Engine
|
7395f7b10c6a7537c7880194c4b61ee001dc8372
|
[
"MIT"
] | null | null | null |
Potato Engine/Engine/BehavioursManager.cpp
|
BrunoAOR/Potato-Engine
|
7395f7b10c6a7537c7880194c4b61ee001dc8372
|
[
"MIT"
] | 1
|
2020-06-03T03:37:27.000Z
|
2020-06-03T03:37:27.000Z
|
#include "BehavioursManager.h"
#include "Behaviour.h"
#include "ComponentType.h"
#include "GameObject.h"
BehavioursManager::BehavioursManager()
{
}
BehavioursManager::~BehavioursManager()
{
}
ComponentType BehavioursManager::managedComponentType() const
{
return ComponentType::BEHAVIOUR;
}
void BehavioursManager::update()
{
// Note: refreshComponents ensures that all Reference in m_components are valid, so they can be safely used
refreshComponents();
for (Reference<Component>& componentRef : m_components)
{
Behaviour* behaviourPtr = static_cast<Behaviour*>(componentRef.get());
// Actual update
if (!behaviourPtr->m_isAwake)
{
behaviourPtr->awake();
behaviourPtr->m_isAwake = true;
}
else if (behaviourPtr->gameObject()->isActive())
{
if (!behaviourPtr->m_started) {
behaviourPtr->start();
behaviourPtr->m_started = true;
}
else
{
behaviourPtr->update();
}
}
}
}
bool BehavioursManager::init()
{
return true;
}
void BehavioursManager::close()
{
}
bool BehavioursManager::initializeComponent(Reference<Component>& component)
{
return true;
}
| 16.701493
| 108
| 0.716711
|
BrunoAOR
|
a83a609acab3490579980b747d22bed131d98a8f
| 153
|
cpp
|
C++
|
sw02.cpp
|
luqmaanb/pxt-SW02
|
fc2743763bb1f47398ca163ddfec23aeef6b7481
|
[
"MIT"
] | null | null | null |
sw02.cpp
|
luqmaanb/pxt-SW02
|
fc2743763bb1f47398ca163ddfec23aeef6b7481
|
[
"MIT"
] | null | null | null |
sw02.cpp
|
luqmaanb/pxt-SW02
|
fc2743763bb1f47398ca163ddfec23aeef6b7481
|
[
"MIT"
] | null | null | null |
#include "pxt.h"
#include <cstdint>
#include <math.h>
using namespace pxt;
namespace SW02 {
//%
uint8_t getID() {
return 29;
}
}
| 10.2
| 21
| 0.568627
|
luqmaanb
|
a83b990caa313fea5f9ab35adcadfec4756ba9b8
| 5,221
|
cpp
|
C++
|
src/bin/dump_xml_compiler_result/dump_xml_compiler_result/main.cpp
|
gkb/Karabiner
|
f47307d4fc89a4c421d10157d059293c508f721a
|
[
"Unlicense"
] | null | null | null |
src/bin/dump_xml_compiler_result/dump_xml_compiler_result/main.cpp
|
gkb/Karabiner
|
f47307d4fc89a4c421d10157d059293c508f721a
|
[
"Unlicense"
] | null | null | null |
src/bin/dump_xml_compiler_result/dump_xml_compiler_result/main.cpp
|
gkb/Karabiner
|
f47307d4fc89a4c421d10157d059293c508f721a
|
[
"Unlicense"
] | null | null | null |
#include <iostream>
#include <boost/algorithm/string.hpp>
#include "pqrs/xml_compiler.hpp"
namespace {
int total_identifier_count_ = 0;
void
escapeHTML(std::string& string) {
boost::replace_all(string, "&", "&");
boost::replace_all(string, "<", "<");
boost::replace_all(string, ">", ">");
}
void
dump_tree(const pqrs::xml_compiler::preferences_node_tree<pqrs::xml_compiler::preferences_checkbox_node>& node_tree,
bool dump_all) {
auto children_ptr = node_tree.get_children();
if (children_ptr) {
auto& children = *children_ptr;
static bool first_ul = true;
if (first_ul) {
std::cout << "<ul id=\"collapser\">";
first_ul = false;
} else {
std::cout << "<ul>";
}
for (auto& it : children) {
auto& node = it->get_node();
std::string name = node.get_name();
escapeHTML(name);
std::cout << "<li>" << name;
if (dump_all) {
std::cout << "<identifier>" << node.get_identifier() << "</identifier>" << std::endl;
std::cout << "<name_for_filter>" << node.get_name_for_filter() << "</name_for_filter>" << std::endl;
}
dump_tree(*it, dump_all);
std::cout << "</li>";
auto& identifier = node.get_identifier();
if (!identifier.empty()) {
++total_identifier_count_;
}
}
std::cout << "</ul>";
}
}
void
dump_number(const pqrs::xml_compiler::preferences_node_tree<pqrs::xml_compiler::preferences_number_node>& node_tree) {
auto children_ptr = node_tree.get_children();
if (children_ptr) {
auto& children = *children_ptr;
for (auto& it : children) {
auto& node = it->get_node();
std::cout << node.get_name() << std::endl
<< " default_value:" << node.get_default_value() << std::endl
<< " step:" << node.get_step() << std::endl
<< " base_unit:" << node.get_base_unit() << std::endl
<< std::endl;
dump_number(*it);
}
}
}
}
int
main(int argc, const char* argv[]) {
if (argc != 4) {
std::cerr << "Usage: " << argv[0] << " system_xml_directory private_xml_directory command" << std::endl
<< std::endl
<< "Example: " << argv[0]
<< " /Applications/Karabiner.app/Contents/Resources"
<< " ~/Library/Application\\ Support/Karabiner"
<< " dump_data"
<< std::endl;
exit(1);
}
pqrs::xml_compiler xml_compiler(argv[1], argv[2]);
xml_compiler.reload();
if (xml_compiler.get_error_information().get_count() > 0) {
std::cerr << xml_compiler.get_error_information().get_message() << std::endl;
exit(1);
}
std::string command(argv[3]);
if (command == "dump_data") {
auto v = xml_compiler.get_remapclasses_initialize_vector().get();
for (auto& it : v) {
std::cout << it << std::endl;
}
} else if (command == "dump_tree") {
dump_tree(xml_compiler.get_preferences_checkbox_node_tree(), false);
std::cout << std::endl;
std::cout << std::endl;
std::cout << "Total items: " << total_identifier_count_ << std::endl;
} else if (command == "dump_tree_all") {
dump_tree(xml_compiler.get_preferences_checkbox_node_tree(), true);
std::cout << std::endl;
std::cout << std::endl;
std::cout << "Total items: " << total_identifier_count_ << std::endl;
} else if (command == "dump_number") {
dump_number(xml_compiler.get_preferences_number_node_tree());
} else if (command == "dump_identifier_except_essential") {
for (int i = 0;; ++i) {
auto identifier = xml_compiler.get_identifier(i);
if (!identifier) break;
std::cout << *identifier << std::endl;
}
} else if (command == "dump_symbol_map") {
xml_compiler.get_symbol_map().dump();
} else if (command == "output_bridge_essential_configuration_enum_h") {
std::cout << "enum {" << std::endl;
for (size_t i = 0;; ++i) {
auto essential_configuration = xml_compiler.get_essential_configuration(i);
if (!essential_configuration) {
std::cout << "BRIDGE_ESSENTIAL_CONFIG_INDEX__END__ = " << i << std::endl;
break;
}
std::cout << "BRIDGE_ESSENTIAL_CONFIG_INDEX_" << essential_configuration->get_identifier()
<< " = " << i << ","
<< std::endl;
}
std::cout << "};" << std::endl;
} else if (command == "output_bridge_essential_configuration_default_values_c") {
for (size_t i = 0;; ++i) {
auto essential_configuration = xml_compiler.get_essential_configuration(i);
if (!essential_configuration) {
break;
}
std::cout << essential_configuration->get_default_value()
<< ","
<< std::endl;
}
} else if (command == "output_bridge_essential_configuration_identifiers_m") {
for (size_t i = 0;; ++i) {
auto essential_configuration = xml_compiler.get_essential_configuration(i);
if (!essential_configuration) {
std::cout << "nil" << std::endl;
break;
}
std::cout << "@\"" << essential_configuration->get_raw_identifier() << "\""
<< ","
<< std::endl;
}
}
return 0;
}
| 29.834286
| 118
| 0.587818
|
gkb
|
a83c62d90307528d2e63bc0f7262e4de0f07f4ab
| 3,017
|
hpp
|
C++
|
vm/test/test_nativemethod.hpp
|
gdoleczek/rubinius
|
d8b16a76ada3531791260779ee747d11b75aba0e
|
[
"BSD-3-Clause"
] | 1
|
2018-11-24T17:34:58.000Z
|
2018-11-24T17:34:58.000Z
|
vm/test/test_nativemethod.hpp
|
gdoleczek/rubinius
|
d8b16a76ada3531791260779ee747d11b75aba0e
|
[
"BSD-3-Clause"
] | null | null | null |
vm/test/test_nativemethod.hpp
|
gdoleczek/rubinius
|
d8b16a76ada3531791260779ee747d11b75aba0e
|
[
"BSD-3-Clause"
] | null | null | null |
#include "vm/test/test.hpp"
#include "builtin/nativemethod.hpp"
#include "vm.hpp"
#include "objectmemory.hpp"
using namespace rubinius;
class TestNativeMethod : public CxxTest::TestSuite, public VMTest {
public:
void setUp() {
create();
}
void tearDown() {
destroy();
}
void test_native_method_frame_get_object() {
NativeMethodFrame nmf(NULL);
String* str = String::create(state, "test");
Integer* id = str->id(state);
VALUE handle = nmf.get_handle(state, str);
TS_ASSERT_EQUALS(id, nmf.get_object(handle)->id(state));
}
NativeMethodEnvironment* create_native_method_environment() {
NativeMethodFrame* nmf = new NativeMethodFrame(NULL);
CallFrame* cf = new CallFrame;
NativeMethodEnvironment* nme = new NativeMethodEnvironment(state);
nme->set_current_call_frame(cf);
nme->set_current_native_frame(nmf);
return nme;
}
void destroy_native_method_environment(NativeMethodEnvironment* nme) {
delete nme->current_call_frame();
delete nme->current_native_frame();
delete nme;
}
void test_native_method_environment_get_Qfalse_handle() {
NativeMethodEnvironment* nme = create_native_method_environment();
TS_ASSERT_EQUALS(cCApiHandleQfalse, nme->get_handle(Qfalse));
destroy_native_method_environment(nme);
}
void test_native_method_environment_get_Qtrue_handle() {
NativeMethodEnvironment* nme = create_native_method_environment();
TS_ASSERT_EQUALS(cCApiHandleQtrue, nme->get_handle(Qtrue));
destroy_native_method_environment(nme);
}
void test_native_method_environment_get_Qnil_handle() {
NativeMethodEnvironment* nme = create_native_method_environment();
TS_ASSERT_EQUALS(cCApiHandleQnil, nme->get_handle(Qnil));
destroy_native_method_environment(nme);
}
void test_native_method_environment_get_Qundef_handle() {
NativeMethodEnvironment* nme = create_native_method_environment();
TS_ASSERT_EQUALS(cCApiHandleQundef, nme->get_handle(Qundef));
destroy_native_method_environment(nme);
}
void test_native_method_environment_get_Symbol_handle() {
NativeMethodEnvironment* nme = create_native_method_environment();
Symbol* sym = state->symbol("capi_symbol");
TS_ASSERT_EQUALS(sym, reinterpret_cast<Symbol*>(nme->get_handle(sym)));
destroy_native_method_environment(nme);
}
void test_native_method_environment_get_Fixnum_handle() {
NativeMethodEnvironment* nme = create_native_method_environment();
Fixnum* fix = Fixnum::from(28);
TS_ASSERT_EQUALS(fix, reinterpret_cast<Fixnum*>(nme->get_handle(fix)));
destroy_native_method_environment(nme);
}
void test_native_method_environment_get_object() {
NativeMethodEnvironment* nme = create_native_method_environment();
String* str = String::create(state, "test");
Integer* id = str->id(state);
VALUE handle = nme->get_handle(str);
TS_ASSERT_EQUALS(id, nme->get_object(handle)->id(state));
destroy_native_method_environment(nme);
}
};
| 28.196262
| 75
| 0.74942
|
gdoleczek
|
a8410530ee9abe9187aee3687d2f65f533f3c403
| 12,925
|
cc
|
C++
|
Cassie_Example/opt_two_step/gen/opt/h_RightToeBottom_cassie.cc
|
prem-chand/Cassie_CFROST
|
da4bd51442f86e852cbb630cc91c9a380a10b66d
|
[
"BSD-3-Clause"
] | null | null | null |
Cassie_Example/opt_two_step/gen/opt/h_RightToeBottom_cassie.cc
|
prem-chand/Cassie_CFROST
|
da4bd51442f86e852cbb630cc91c9a380a10b66d
|
[
"BSD-3-Clause"
] | null | null | null |
Cassie_Example/opt_two_step/gen/opt/h_RightToeBottom_cassie.cc
|
prem-chand/Cassie_CFROST
|
da4bd51442f86e852cbb630cc91c9a380a10b66d
|
[
"BSD-3-Clause"
] | null | null | null |
/*
* Automatically Generated from Mathematica.
* Thu 14 Oct 2021 09:53:09 GMT-04:00
*/
#ifdef MATLAB_MEX_FILE
#include <stdexcept>
#include <cmath>
#include<math.h>
/**
* Copied from Wolfram Mathematica C Definitions file mdefs.hpp
* Changed marcos to inline functions (Eric Cousineau)
*/
inline double Power(double x, double y) { return pow(x, y); }
inline double Sqrt(double x) { return sqrt(x); }
inline double Abs(double x) { return fabs(x); }
inline double Exp(double x) { return exp(x); }
inline double Log(double x) { return log(x); }
inline double Sin(double x) { return sin(x); }
inline double Cos(double x) { return cos(x); }
inline double Tan(double x) { return tan(x); }
inline double ArcSin(double x) { return asin(x); }
inline double ArcCos(double x) { return acos(x); }
inline double ArcTan(double x) { return atan(x); }
/* update ArcTan function to use atan2 instead. */
inline double ArcTan(double x, double y) { return atan2(y,x); }
inline double Sinh(double x) { return sinh(x); }
inline double Cosh(double x) { return cosh(x); }
inline double Tanh(double x) { return tanh(x); }
const double E = 2.71828182845904523536029;
const double Pi = 3.14159265358979323846264;
const double Degree = 0.01745329251994329576924;
inline double Sec(double x) { return 1/cos(x); }
inline double Csc(double x) { return 1/sin(x); }
#endif
/*
* Sub functions
*/
static void output1(double *p_output1,const double *var1,const double *var2)
{
double t154;
double t1244;
double t1349;
double t1291;
double t1355;
double t660;
double t758;
double t770;
double t888;
double t1231;
double t1348;
double t1450;
double t1486;
double t1527;
double t1693;
double t1715;
double t1737;
double t487;
double t2057;
double t2163;
double t2168;
double t2209;
double t2262;
double t2276;
double t2362;
double t2621;
double t2683;
double t2712;
double t3293;
double t3350;
double t3355;
double t3367;
double t3381;
double t3384;
double t3399;
double t3423;
double t3464;
double t3490;
double t3679;
double t3696;
double t3778;
double t3859;
double t3941;
double t4009;
double t4042;
double t4045;
double t4208;
double t4244;
double t4249;
double t4322;
double t4341;
double t4350;
double t4377;
double t4394;
double t4421;
double t4435;
double t4482;
double t4489;
double t4516;
double t4528;
double t4529;
double t4533;
double t4556;
double t4570;
double t4572;
double t4599;
double t4615;
double t4621;
double t4630;
double t778;
double t987;
double t989;
double t1556;
double t1568;
double t1878;
double t1955;
double t1984;
double t4823;
double t4836;
double t4838;
double t4849;
double t4855;
double t4901;
double t2357;
double t2366;
double t2521;
double t4903;
double t4912;
double t4921;
double t3156;
double t3163;
double t3255;
double t3398;
double t3412;
double t3413;
double t4966;
double t4974;
double t4976;
double t5021;
double t5034;
double t5056;
double t3619;
double t3641;
double t3645;
double t3863;
double t3917;
double t3918;
double t3961;
double t3991;
double t5060;
double t5061;
double t5062;
double t5153;
double t5160;
double t5207;
double t4063;
double t4131;
double t4141;
double t4199;
double t4361;
double t4384;
double t4393;
double t5232;
double t5247;
double t5270;
double t5287;
double t5299;
double t5306;
double t4464;
double t4465;
double t4479;
double t4548;
double t4568;
double t4569;
double t5317;
double t5318;
double t5319;
double t5328;
double t5380;
double t5411;
double t4603;
double t4604;
double t4608;
double t5427;
double t5428;
double t5466;
double t5499;
double t5506;
double t5512;
double t5589;
double t5590;
double t5591;
double t5594;
double t5603;
double t5618;
double t5632;
double t5636;
double t5637;
double t5641;
double t5642;
double t5644;
double t5651;
double t5657;
double t5660;
double t5664;
double t5665;
double t5667;
double t5692;
double t5694;
double t5696;
double t5709;
double t5715;
double t5728;
double t5740;
double t5741;
double t5749;
double t5768;
double t5780;
double t5783;
double t5802;
double t5803;
double t5804;
double t5817;
double t5822;
double t5824;
double t5827;
double t5831;
double t5835;
double t5861;
double t5862;
double t5864;
double t5854;
double t5857;
double t5858;
double t5517;
double t5519;
double t5521;
double t5535;
double t5539;
double t5581;
double t5881;
double t5890;
double t5899;
double t5901;
double t4659;
double t4670;
double t4702;
double t4736;
double t4762;
double t4775;
t154 = Cos(var1[3]);
t1244 = Cos(var1[5]);
t1349 = Sin(var1[3]);
t1291 = Sin(var1[4]);
t1355 = Sin(var1[5]);
t660 = Cos(var1[14]);
t758 = -1.*t660;
t770 = 1. + t758;
t888 = Sin(var1[14]);
t1231 = Sin(var1[13]);
t1348 = t154*t1244*t1291;
t1450 = t1349*t1355;
t1486 = t1348 + t1450;
t1527 = Cos(var1[13]);
t1693 = -1.*t1244*t1349;
t1715 = t154*t1291*t1355;
t1737 = t1693 + t1715;
t487 = Cos(var1[4]);
t2057 = t1231*t1486;
t2163 = t1527*t1737;
t2168 = t2057 + t2163;
t2209 = Cos(var1[15]);
t2262 = -1.*t2209;
t2276 = 1. + t2262;
t2362 = Sin(var1[15]);
t2621 = t1527*t1486;
t2683 = -1.*t1231*t1737;
t2712 = t2621 + t2683;
t3293 = t660*t154*t487;
t3350 = t888*t2168;
t3355 = t3293 + t3350;
t3367 = Cos(var1[16]);
t3381 = -1.*t3367;
t3384 = 1. + t3381;
t3399 = Sin(var1[16]);
t3423 = t2362*t2712;
t3464 = t2209*t3355;
t3490 = t3423 + t3464;
t3679 = t2209*t2712;
t3696 = -1.*t2362*t3355;
t3778 = t3679 + t3696;
t3859 = Cos(var1[17]);
t3941 = Sin(var1[17]);
t4009 = -1.*t3399*t3490;
t4042 = t3367*t3778;
t4045 = t4009 + t4042;
t4208 = t3367*t3490;
t4244 = t3399*t3778;
t4249 = t4208 + t4244;
t4322 = Cos(var1[18]);
t4341 = -1.*t4322;
t4350 = 1. + t4341;
t4377 = Sin(var1[18]);
t4394 = t3941*t4045;
t4421 = t3859*t4249;
t4435 = t4394 + t4421;
t4482 = t3859*t4045;
t4489 = -1.*t3941*t4249;
t4516 = t4482 + t4489;
t4528 = Cos(var1[19]);
t4529 = -1.*t4528;
t4533 = 1. + t4529;
t4556 = Sin(var1[19]);
t4570 = -1.*t4377*t4435;
t4572 = t4322*t4516;
t4599 = t4570 + t4572;
t4615 = t4322*t4435;
t4621 = t4377*t4516;
t4630 = t4615 + t4621;
t778 = -0.049*t770;
t987 = -0.135*t888;
t989 = t778 + t987;
t1556 = -1.*t1527;
t1568 = 1. + t1556;
t1878 = -0.135*t770;
t1955 = 0.049*t888;
t1984 = t1878 + t1955;
t4823 = t1244*t1349*t1291;
t4836 = -1.*t154*t1355;
t4838 = t4823 + t4836;
t4849 = t154*t1244;
t4855 = t1349*t1291*t1355;
t4901 = t4849 + t4855;
t2357 = -0.09*t2276;
t2366 = 0.049*t2362;
t2521 = t2357 + t2366;
t4903 = t1231*t4838;
t4912 = t1527*t4901;
t4921 = t4903 + t4912;
t3156 = -0.049*t2276;
t3163 = -0.09*t2362;
t3255 = t3156 + t3163;
t3398 = -0.049*t3384;
t3412 = -0.21*t3399;
t3413 = t3398 + t3412;
t4966 = t1527*t4838;
t4974 = -1.*t1231*t4901;
t4976 = t4966 + t4974;
t5021 = t660*t487*t1349;
t5034 = t888*t4921;
t5056 = t5021 + t5034;
t3619 = -0.21*t3384;
t3641 = 0.049*t3399;
t3645 = t3619 + t3641;
t3863 = -1.*t3859;
t3917 = 1. + t3863;
t3918 = -0.2707*t3917;
t3961 = 0.0016*t3941;
t3991 = t3918 + t3961;
t5060 = t2362*t4976;
t5061 = t2209*t5056;
t5062 = t5060 + t5061;
t5153 = t2209*t4976;
t5160 = -1.*t2362*t5056;
t5207 = t5153 + t5160;
t4063 = -1. + t3859;
t4131 = 0.0016*t4063;
t4141 = -0.2707*t3941;
t4199 = t4131 + t4141;
t4361 = 0.0184*t4350;
t4384 = -0.7055*t4377;
t4393 = t4361 + t4384;
t5232 = -1.*t3399*t5062;
t5247 = t3367*t5207;
t5270 = t5232 + t5247;
t5287 = t3367*t5062;
t5299 = t3399*t5207;
t5306 = t5287 + t5299;
t4464 = -0.7055*t4350;
t4465 = -0.0184*t4377;
t4479 = t4464 + t4465;
t4548 = -1.1135*t4533;
t4568 = 0.0216*t4556;
t4569 = t4548 + t4568;
t5317 = t3941*t5270;
t5318 = t3859*t5306;
t5319 = t5317 + t5318;
t5328 = t3859*t5270;
t5380 = -1.*t3941*t5306;
t5411 = t5328 + t5380;
t4603 = -0.0216*t4533;
t4604 = -1.1135*t4556;
t4608 = t4603 + t4604;
t5427 = -1.*t4377*t5319;
t5428 = t4322*t5411;
t5466 = t5427 + t5428;
t5499 = t4322*t5319;
t5506 = t4377*t5411;
t5512 = t5499 + t5506;
t5589 = t487*t1244*t1231;
t5590 = t1527*t487*t1355;
t5591 = t5589 + t5590;
t5594 = t1527*t487*t1244;
t5603 = -1.*t487*t1231*t1355;
t5618 = t5594 + t5603;
t5632 = -1.*t660*t1291;
t5636 = t888*t5591;
t5637 = t5632 + t5636;
t5641 = t2362*t5618;
t5642 = t2209*t5637;
t5644 = t5641 + t5642;
t5651 = t2209*t5618;
t5657 = -1.*t2362*t5637;
t5660 = t5651 + t5657;
t5664 = -1.*t3399*t5644;
t5665 = t3367*t5660;
t5667 = t5664 + t5665;
t5692 = t3367*t5644;
t5694 = t3399*t5660;
t5696 = t5692 + t5694;
t5709 = t3941*t5667;
t5715 = t3859*t5696;
t5728 = t5709 + t5715;
t5740 = t3859*t5667;
t5741 = -1.*t3941*t5696;
t5749 = t5740 + t5741;
t5768 = -1.*t4377*t5728;
t5780 = t4322*t5749;
t5783 = t5768 + t5780;
t5802 = t4322*t5728;
t5803 = t4377*t5749;
t5804 = t5802 + t5803;
t5817 = t4556*t5783;
t5822 = t4528*t5804;
t5824 = t5817 + t5822;
t5827 = t4528*t5783;
t5831 = -1.*t4556*t5804;
t5835 = t5827 + t5831;
t5861 = 0.642788*t5824;
t5862 = 0.766044*t5835;
t5864 = t5861 + t5862;
t5854 = -0.766044*t5824;
t5857 = 0.642788*t5835;
t5858 = t5854 + t5857;
t5517 = t4556*t5466;
t5519 = t4528*t5512;
t5521 = t5517 + t5519;
t5535 = t4528*t5466;
t5539 = -1.*t4556*t5512;
t5581 = t5535 + t5539;
t5881 = Power(t5858,2);
t5890 = Power(t5864,2);
t5899 = t5881 + t5890;
t5901 = 1/Sqrt(t5899);
t4659 = t4556*t4599;
t4670 = t4528*t4630;
t4702 = t4659 + t4670;
t4736 = t4528*t4599;
t4762 = -1.*t4556*t4630;
t4775 = t4736 + t4762;
p_output1[0]=0.135*t1231*t1486 - 0.135*t1568*t1737 + t1984*t2168 + t2521*t2712 + t3255*t3355 + t3413*t3490 + t3645*t3778 + t3991*t4045 + t4199*t4249 + t4393*t4435 + t4479*t4516 + t4569*t4599 + t4608*t4630 + 0.0306*t4702 - 1.1312*t4775 - 0.1305*(t2168*t660 - 1.*t154*t487*t888) + t154*t487*t989 + var1[0] - 1.*var2[0];
p_output1[1]=0.135*t1231*t4838 - 0.135*t1568*t4901 + t1984*t4921 + t2521*t4976 + t3255*t5056 + t3413*t5062 + t3645*t5207 + t3991*t5270 + t4199*t5306 + t4393*t5319 + t4479*t5411 + t4569*t5466 + t4608*t5512 + 0.0306*t5521 - 1.1312*t5581 - 0.1305*(t4921*t660 - 1.*t1349*t487*t888) + t1349*t487*t989 + var1[1] - 1.*var2[1];
p_output1[2]=0.135*t1231*t1244*t487 - 0.135*t1355*t1568*t487 + t1984*t5591 + t2521*t5618 + t3255*t5637 + t3413*t5644 + t3645*t5660 + t3991*t5667 + t4199*t5696 + t4393*t5728 + t4479*t5749 + t4569*t5783 + t4608*t5804 + 0.0306*t5824 - 1.1312*t5835 - 0.1305*(t5591*t660 + t1291*t888) - 1.*t1291*t989 + var1[2] - 1.*var2[2];
p_output1[3]=ArcTan(t5858,t5864) - 1.*var2[3];
p_output1[4]=ArcTan((0.642788*t5521 + 0.766044*t5581)*t5858*t5901 - 1.*(-0.766044*t5521 + 0.642788*t5581)*t5864*t5901,-1.*(0.642788*t4702 + 0.766044*t4775)*t5858*t5901 + (-0.766044*t4702 + 0.642788*t4775)*t5864*t5901) - 1.*var2[4];
}
#ifdef MATLAB_MEX_FILE
#include "mex.h"
/*
* Main function
*/
void mexFunction( int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[] )
{
size_t mrows, ncols;
double *var1,*var2;
double *p_output1;
/* Check for proper number of arguments. */
if( nrhs != 2)
{
mexErrMsgIdAndTxt("MATLAB:MShaped:invalidNumInputs", "Two input(s) required (var1,var2).");
}
else if( nlhs > 1)
{
mexErrMsgIdAndTxt("MATLAB:MShaped:maxlhs", "Too many output arguments.");
}
/* The input must be a noncomplex double vector or scaler. */
mrows = mxGetM(prhs[0]);
ncols = mxGetN(prhs[0]);
if( !mxIsDouble(prhs[0]) || mxIsComplex(prhs[0]) ||
( !(mrows == 20 && ncols == 1) &&
!(mrows == 1 && ncols == 20)))
{
mexErrMsgIdAndTxt( "MATLAB:MShaped:inputNotRealVector", "var1 is wrong.");
}
mrows = mxGetM(prhs[1]);
ncols = mxGetN(prhs[1]);
if( !mxIsDouble(prhs[1]) || mxIsComplex(prhs[1]) ||
( !(mrows == 5 && ncols == 1) &&
!(mrows == 1 && ncols == 5)))
{
mexErrMsgIdAndTxt( "MATLAB:MShaped:inputNotRealVector", "var2 is wrong.");
}
/* Assign pointers to each input. */
var1 = mxGetPr(prhs[0]);
var2 = mxGetPr(prhs[1]);
/* Create matrices for return arguments. */
plhs[0] = mxCreateDoubleMatrix((mwSize) 5, (mwSize) 1, mxREAL);
p_output1 = mxGetPr(plhs[0]);
/* Call the calculation subroutine. */
output1(p_output1,var1,var2);
}
#else // MATLAB_MEX_FILE
#include "h_RightToeBottom_cassie.hh"
namespace RightStance
{
void h_RightToeBottom_cassie_raw(double *p_output1, const double *var1,const double *var2)
{
// Call Subroutines
output1(p_output1, var1, var2);
}
}
#endif // MATLAB_MEX_FILE
| 23.204668
| 321
| 0.646886
|
prem-chand
|
61b438043916f7d69b5852688703f6b2a6df908a
| 1,028
|
cpp
|
C++
|
AdvancedAnchor/src/dbg/debugVehicleSpawner.cpp
|
PsychoDad9999/GTA5-Mods
|
38a3aa2ec48cd52cb851f1cda636c53bfbc058ad
|
[
"MIT"
] | 5
|
2020-09-23T06:03:48.000Z
|
2021-04-14T19:37:55.000Z
|
AdvancedAnchor/src/dbg/debugVehicleSpawner.cpp
|
PsychoDad9999/GTA5-Mods
|
38a3aa2ec48cd52cb851f1cda636c53bfbc058ad
|
[
"MIT"
] | null | null | null |
AdvancedAnchor/src/dbg/debugVehicleSpawner.cpp
|
PsychoDad9999/GTA5-Mods
|
38a3aa2ec48cd52cb851f1cda636c53bfbc058ad
|
[
"MIT"
] | null | null | null |
// ----------------------------------------------------------------------------
#include "debugVehicleSpawner.h"
#include "inc/natives.h"
#include "framework/world/world.h"
// ----------------------------------------------------------------------------
/// <summery>Spawn a vehicle close to ped position</summery>
/// <param name="ped">ped</param>
/// <param name="vehicleHash">hash of vehicle that will be spawned</param>
// ----------------------------------------------------------------------------
void DebugVehicleSpawner::spawnVehicleAtPedLocation(Ped ped, VehicleEntity::eVehicleHash vehicleHash)
{
if (vehicleHash == VehicleEntity::eVehicleHash::VehicleHashInvalid)
return;
Vector3 pedPos = World::getPosition(ped);
// offset position
pedPos.x += 10;
pedPos.y += 10;
Vehicle vehicle = VEHICLE::CREATE_VEHICLE(vehicleHash, pedPos.x, pedPos.y, pedPos.z, 0, FALSE, FALSE);
OBJECT::PLACE_OBJECT_ON_GROUND_PROPERLY(vehicle);
}
// ----------------------------------------------------------------------------
| 34.266667
| 103
| 0.515564
|
PsychoDad9999
|
61b46e28c83c45b3bf931b810a62b648cf7a8ff1
| 122
|
cc
|
C++
|
src/UserTrackInformation.cc
|
omar-moreno/simulation-formerly-known-as-slic
|
331d0452d05762e2f4554f0ace6fe46922a7333c
|
[
"BSD-3-Clause-LBNL"
] | null | null | null |
src/UserTrackInformation.cc
|
omar-moreno/simulation-formerly-known-as-slic
|
331d0452d05762e2f4554f0ace6fe46922a7333c
|
[
"BSD-3-Clause-LBNL"
] | null | null | null |
src/UserTrackInformation.cc
|
omar-moreno/simulation-formerly-known-as-slic
|
331d0452d05762e2f4554f0ace6fe46922a7333c
|
[
"BSD-3-Clause-LBNL"
] | null | null | null |
#include "UserTrackInformation.hh"
namespace slic {
G4Allocator<UserTrackInformation> UserTrackInformationAllocator;
}
| 15.25
| 64
| 0.836066
|
omar-moreno
|
61b735891cf0b3c0a307dcaba3c4136870987e51
| 7,231
|
cpp
|
C++
|
bin/sinsy.cpp
|
Erin59/sinsy0.91
|
249bd757c975436824b88aa773ecb4078eb4d696
|
[
"Unlicense"
] | 1
|
2018-12-17T08:41:19.000Z
|
2018-12-17T08:41:19.000Z
|
bin/sinsy.cpp
|
Erin59/sinsy0.91
|
249bd757c975436824b88aa773ecb4078eb4d696
|
[
"Unlicense"
] | null | null | null |
bin/sinsy.cpp
|
Erin59/sinsy0.91
|
249bd757c975436824b88aa773ecb4078eb4d696
|
[
"Unlicense"
] | 1
|
2019-09-24T05:52:54.000Z
|
2019-09-24T05:52:54.000Z
|
/* ----------------------------------------------------------------- */
/* The HMM-Based Singing Voice Synthesis System "Sinsy" */
/* developed by Sinsy Working Group */
/* http://sinsy.sourceforge.net/ */
/* ----------------------------------------------------------------- */
/* */
/* Copyright (c) 2009-2013 Nagoya Institute of Technology */
/* Department of Computer Science */
/* */
/* All rights reserved. */
/* */
/* Redistribution and use in source and binary forms, with or */
/* without modification, are permitted provided that the following */
/* conditions are met: */
/* */
/* - Redistributions of source code must retain the above copyright */
/* notice, this list of conditions and the following disclaimer. */
/* - Redistributions in binary form must reproduce the above */
/* copyright notice, this list of conditions and the following */
/* disclaimer in the documentation and/or other materials provided */
/* with the distribution. */
/* - Neither the name of the Sinsy working group nor the names of */
/* its contributors may be used to endorse or promote products */
/* derived from this software without specific prior written */
/* permission. */
/* */
/* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND */
/* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, */
/* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF */
/* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE */
/* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS */
/* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, */
/* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED */
/* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, */
/* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON */
/* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, */
/* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY */
/* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE */
/* POSSIBILITY OF SUCH DAMAGE. */
/* ----------------------------------------------------------------- */
#include <string.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include "sinsy.h"
namespace
{
const char* DEFAULT_LANGS = "j";
};
void usage()
{
std::cout << "The HMM-Based Singing Voice Syntheis System \"Sinsy\"" << std::endl;
std::cout << "Version 0.90 (http://sinsy.sourceforge.net/)" << std::endl;
std::cout << "Copyright (C) 2009-2013 Nagoya Institute of Technology" << std::endl;
std::cout << "All rights reserved." << std::endl;
std::cout << "" << std::endl;
std::cout << "The HMM-Based Speech Synthesis Engine \"hts_engine API\"" << std::endl;
std::cout << "Version 1.08 (http://hts-engine.sourceforge.net/)" << std::endl;
std::cout << "Copyright (C) 2001-2013 Nagoya Institute of Technology" << std::endl;
std::cout << " 2001-2008 Tokyo Institute of Technology" << std::endl;
std::cout << "All rights reserved." << std::endl;
std::cout << "" << std::endl;
std::cout << "sinsy - The HMM-based singing voice synthesis system \"Sinsy\"" << std::endl;
std::cout << "" << std::endl;
std::cout << " usage:" << std::endl;
std::cout << " sinsy [ options ] [ infile ]" << std::endl;
std::cout << " options: [def]" << std::endl;
std::cout << " -w langs : languages [ j]" << std::endl;
std::cout << " j: Japanese g: German " << std::endl;
std::cout << " (Currently, you can set only Japanese or German) " << std::endl;
std::cout << " -x dir : dictionary directory [N/A]" << std::endl;
std::cout << " -m htsvoice : HTS voice file [N/A]" << std::endl;
std::cout << " -o file : filename of output wav audio [N/A]" << std::endl;
std::cout << " -l file : save labels to file, no voice/output needed [N/A]" << std::endl;
std::cout << " infile:" << std::endl;
std::cout << " MusicXML file" << std::endl;
}
int main(int argc, char **argv)
{
if (argc < 2) {
usage();
return -1;
}
std::string xml;
std::string voice;
std::string config;
std::string wav;
std::string labfn;
std::string languages(DEFAULT_LANGS);
bool print_label=false;
int i(1);
for(; i < argc; ++i) {
if ('-' != argv[i][0]) {
if (xml.empty()) {
xml = argv[i];
} else {
std::cout << "[ERROR] invalid option : '" << argv[i][1] << "'" << std::endl;
usage();
return -1;
}
} else {
switch (argv[i][1]) {
case 'w' :
languages = argv[++i];
break;
case 'x' :
config = argv[++i];
break;
case 'm' :
voice = argv[++i];
break;
case 'o' :
wav = argv[++i];
break;
case 'l':
print_label = true;
labfn = argv[++i];
break;
case 'h' :
usage();
return 0;
default :
std::cout << "[ERROR] invalid option : '-" << argv[i][1] << "'" << std::endl;
usage();
return -1;
}
}
}
if((xml.empty() || voice.empty())&&(xml.empty() && print_label)) {
usage();
return -1;
}
sinsy::Sinsy sinsy;
std::vector<std::string> voices;
voices.push_back(voice);
if (!sinsy.setLanguages(languages, config)) {
std::cout << "[ERROR] failed to set languages : " << languages << ", config dir : " << config << std::endl;
return -1;
}
if (!print_label && !sinsy.loadVoices(voices)) {
std::cout << "[ERROR] failed to load voices : " << voice << std::endl;
return -1;
}
if (!sinsy.loadScoreFromMusicXML(xml)) {
std::cout << "[ERROR] failed to load score from MusicXML file : " << xml << std::endl;
return -1;
}
sinsy::SynthCondition condition;
if (wav.empty()&& !print_label) {
condition.setPlayFlag();
} else if (!print_label){
condition.setSaveFilePath(wav);
}
if(!print_label){
sinsy.synthesize(condition);
} else {
condition.setSaveLabelFilePath(labfn);
sinsy.printlabel(condition);
}
return 0;
}
| 40.623596
| 113
| 0.482229
|
Erin59
|
61bae19f0a8b4bb1b2e0e02ab25f86f4a3e38184
| 2,064
|
cpp
|
C++
|
lib/chunk/Chunk.cpp
|
NetherGamesMC/noiselib
|
56fc48ea1367e1d08b228dfa580b513fbec8ca31
|
[
"MIT"
] | 14
|
2021-08-16T18:58:30.000Z
|
2022-02-13T01:12:31.000Z
|
lib/chunk/Chunk.cpp
|
NetherGamesMC/ext-vanillagenerator
|
56fc48ea1367e1d08b228dfa580b513fbec8ca31
|
[
"MIT"
] | 2
|
2021-06-21T15:10:01.000Z
|
2021-07-19T01:48:00.000Z
|
lib/chunk/Chunk.cpp
|
NetherGamesMC/ext-vanillagenerator
|
56fc48ea1367e1d08b228dfa580b513fbec8ca31
|
[
"MIT"
] | 3
|
2021-06-21T02:10:39.000Z
|
2021-08-04T01:36:08.000Z
|
#include "Chunk.h"
#include <lib/MortonHelper.h>
Chunk::Chunk(int64_t chunk, std::array<NormalBlockArrayContainer *, 16> &b, BiomeArray &biomeArray) : biomeArray(biomeArray) {
std::copy(std::begin(b), std::end(b), std::begin(blockLayer));
int64_t x, z;
morton2d_decode(chunk, x, z);
chunkX = static_cast<int_fast32_t>(x);
chunkZ = static_cast<int_fast32_t>(z);
}
NormalBlockArrayContainer *Chunk::GetSubChunk(uint_fast8_t y) {
if (y < 0 || y >= blockLayer.size()) {
return nullptr;
}
return blockLayer[y];
}
void Chunk::SetFullBlock(int_fast8_t x, int_fast16_t y, int_fast8_t z, Block block) {
NormalBlockArrayContainer *subChunk;
if ((subChunk = GetSubChunk(y >> 4)) == nullptr) {
throw std::invalid_argument("Subchunk y=" + std::to_string(y >> 4) + " was not found [SetFullBlock]");
}
subChunk->set(x, y & 0xf, z, block);
chunkDirty = true;
}
Block Chunk::GetFullBlock(int_fast8_t x, int_fast16_t y, int_fast8_t z) {
BlockArrayContainer<Block> *subChunk;
if ((subChunk = GetSubChunk(y >> 4)) == nullptr) {
throw std::invalid_argument("Subchunk y=" + std::to_string(y >> 4) + " was not found [GetFullBlock]");
}
return subChunk->get(x, y & 0x0f, z);
}
int_fast16_t Chunk::GetHighestBlockAt(uint_fast8_t x, uint_fast8_t z) {
for (auto y = static_cast<int_fast16_t>(blockLayer.size() - 1); y >= 0; --y) {
int_fast16_t height = GetHighestBlockAt(GetSubChunk(y), x, z);
if (height != -1) {
return static_cast<int_fast16_t>(height | (y << 4));
}
}
return -1;
}
BiomeArray &Chunk::GetBiomeArray() const {
return biomeArray;
}
int_fast32_t Chunk::GetX() const {
return chunkX;
}
int_fast32_t Chunk::GetZ() const {
return chunkZ;
}
bool Chunk::IsDirty() const {
return chunkDirty;
}
void Chunk::SetDirty(bool isDirty) {
chunkDirty = isDirty;
}
int_fast16_t Chunk::GetHighestBlockAt(NormalBlockArrayContainer *blocks, int_fast32_t x, int_fast32_t z) {
for (int_fast16_t y = 15; y >= 0; --y) {
if (blocks->get(x, y, z) != 0) {
return y;
}
}
return -1;
}
| 25.170732
| 126
| 0.668605
|
NetherGamesMC
|
61bce725c5f29cf304b499a34481bfc6f6f00ee5
| 2,897
|
cpp
|
C++
|
Source/source/mob_categories/group_task_category.cpp
|
ElatedEatrs/Pikifen
|
1e834d5241fc631f8dfc519c17358051e867164f
|
[
"MIT"
] | null | null | null |
Source/source/mob_categories/group_task_category.cpp
|
ElatedEatrs/Pikifen
|
1e834d5241fc631f8dfc519c17358051e867164f
|
[
"MIT"
] | null | null | null |
Source/source/mob_categories/group_task_category.cpp
|
ElatedEatrs/Pikifen
|
1e834d5241fc631f8dfc519c17358051e867164f
|
[
"MIT"
] | null | null | null |
/*
* Copyright (c) Andre 'Espyo' Silva 2013.
* The following source file belongs to the open-source project Pikifen.
* Please read the included README and LICENSE files for more information.
* Pikmin is copyright (c) Nintendo.
*
* === FILE DESCRIPTION ===
* Group task mob category class.
*/
#include <algorithm>
#include "group_task_category.h"
#include "../mob_types/group_task_type.h"
#include "../vars.h"
/* ----------------------------------------------------------------------------
* Creates an instance of the group task category.
*/
group_task_category::group_task_category() :
mob_category(
MOB_CATEGORY_GROUP_TASKS, "Group task", "Group tasks",
GROUP_TASKS_FOLDER_PATH, al_map_rgb(224, 104, 176)
) {
}
/* ----------------------------------------------------------------------------
* Returns all types of group tasks by name.
*/
void group_task_category::get_type_names(vector<string> &list) {
for(auto t = group_task_types.begin(); t != group_task_types.end(); ++t) {
list.push_back(t->first);
}
}
/* ----------------------------------------------------------------------------
* Returns a type of group task given its name, or NULL on error.
*/
mob_type* group_task_category::get_type(const string &name) {
auto it = group_task_types.find(name);
if(it == group_task_types.end()) return NULL;
return it->second;
}
/* ----------------------------------------------------------------------------
* Creates a new, empty type of group task.
*/
mob_type* group_task_category::create_type() {
return new group_task_type();
}
/* ----------------------------------------------------------------------------
* Registers a created type of group task.
*/
void group_task_category::register_type(mob_type* type) {
group_task_types[type->name] = (group_task_type*) type;
}
/* ----------------------------------------------------------------------------
* Creates a group task and adds it to the list of group tasks.
*/
mob* group_task_category::create_mob(
const point &pos, mob_type* type, const float angle
) {
group_task* m = new group_task(pos, (group_task_type*) type, angle);
group_tasks.push_back(m);
return m;
}
/* ----------------------------------------------------------------------------
* Clears a group task from the list of group task.
*/
void group_task_category::erase_mob(mob* m) {
group_tasks.erase(
find(group_tasks.begin(), group_tasks.end(), (group_task*) m)
);
}
/* ----------------------------------------------------------------------------
* Clears the list of registered types of group tasks.
*/
void group_task_category::clear_types() {
for(auto t = group_task_types.begin(); t != group_task_types.end(); ++t) {
delete t->second;
}
group_task_types.clear();
}
group_task_category::~group_task_category() { }
| 28.683168
| 79
| 0.535381
|
ElatedEatrs
|
61c3c6dc9fde0d997d8ecc3e5fdfefd01b3d72bf
| 3,058
|
cpp
|
C++
|
Sources_Common/HTTP/CardDAVClient/CCardDAVMultigetReport.cpp
|
mbert/mulberry-main
|
6b7951a3ca56e01a7be67aa12e55bfeafc63950d
|
[
"ECL-2.0",
"Apache-2.0"
] | 12
|
2015-04-21T16:10:43.000Z
|
2021-11-05T13:41:46.000Z
|
Sources_Common/HTTP/CardDAVClient/CCardDAVMultigetReport.cpp
|
mbert/mulberry-main
|
6b7951a3ca56e01a7be67aa12e55bfeafc63950d
|
[
"ECL-2.0",
"Apache-2.0"
] | 2
|
2015-11-02T13:32:11.000Z
|
2019-07-10T21:11:21.000Z
|
Sources_Common/HTTP/CardDAVClient/CCardDAVMultigetReport.cpp
|
mbert/mulberry-main
|
6b7951a3ca56e01a7be67aa12e55bfeafc63950d
|
[
"ECL-2.0",
"Apache-2.0"
] | 6
|
2015-01-12T08:49:12.000Z
|
2021-03-27T09:11:10.000Z
|
/*
Copyright (c) 2007 Cyrus Daboo. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
CCardDAVMultigetReport.cpp
Author:
Description: <describe the CCardDAVMultigetReport class here>
*/
#include "CCardDAVMultigetReport.h"
#include "CHTTPDataString.h"
#include "CWebDAVDefinitions.h"
#include "XMLDocument.h"
#include "XMLNode.h"
#include <strstream>
using namespace webdav;
using namespace carddav;
CCardDAVMultigetReport::CCardDAVMultigetReport(CWebDAVSession* session, const cdstring& ruri, const cdstrvect& hrefs) :
CWebDAVReport(session, ruri)
{
InitRequestData(hrefs);
}
CCardDAVMultigetReport::~CCardDAVMultigetReport()
{
// We own the request data and will delete it here
if (mRequestData != NULL)
{
delete mRequestData;
mRequestData = NULL;
}
}
void CCardDAVMultigetReport::InitRequestData(const cdstrvect& hrefs)
{
// Write XML info to a string
std::ostrstream os;
GenerateXML(os, hrefs);
os << std::ends;
mRequestData = new CHTTPInputDataString(os.str(), "text/xml; charset=utf-8");
}
void CCardDAVMultigetReport::GenerateXML(std::ostream& os, const cdstrvect& hrefs)
{
using namespace xmllib;
// Structure of document is:
//
// <CardDAV:addressbook-multiget>
// <DAV:prop>
// <DAV:getetag>
// <CardDAV:address-data/>
// </DAV:prop>
// <DAV:href>...</DAV:href>
// ...
// </CardDAV:addressbook-multiget>
// Create document and get the root
xmllib::XMLDocument xmldoc;
// <CardDAV:addressbook-multiget> element
xmllib::XMLNode* multiget = xmldoc.GetRoot();
xmllib::XMLNamespace dav_namespc(webdav::cNamespace, "D");
xmllib::XMLNamespace carddav_namespc(carddav::cNamespace, "C");
multiget->SetName(cElement_adbkmultiget.Name(), carddav_namespc);
multiget->AddNamespace(dav_namespc);
multiget->AddNamespace(carddav_namespc);
// <DAV:prop> element
xmllib::XMLNode* prop = new xmllib::XMLNode(&xmldoc, multiget, cElement_prop.Name(), dav_namespc);
// <DAV:getetag> element
new xmllib::XMLNode(&xmldoc, prop, cProperty_getetag.Name(), dav_namespc);
// <CardDAV:address-data> element
new xmllib::XMLNode(&xmldoc, prop, cElement_adbkdata.Name(), carddav_namespc);
// Do for each href
for(cdstrvect::const_iterator iter = hrefs.begin(); iter != hrefs.end(); iter++)
{
// <DAV:href> element
new xmllib::XMLNode(&xmldoc, multiget, cProperty_href.Name(), dav_namespc, *iter);
}
// Now we have the complete document, so write it out (no indentation)
xmldoc.Generate(os, false);
}
| 28.055046
| 119
| 0.717462
|
mbert
|
61c5d9c23bc509b3b9509404fd3ae9041e1d29a9
| 4,350
|
cpp
|
C++
|
Janus/src/Scene/Scene.cpp
|
Kytha/janus-engine
|
ca0ce92d38a9bdb52ec76c9ebf782b993791a08d
|
[
"MIT"
] | null | null | null |
Janus/src/Scene/Scene.cpp
|
Kytha/janus-engine
|
ca0ce92d38a9bdb52ec76c9ebf782b993791a08d
|
[
"MIT"
] | null | null | null |
Janus/src/Scene/Scene.cpp
|
Kytha/janus-engine
|
ca0ce92d38a9bdb52ec76c9ebf782b993791a08d
|
[
"MIT"
] | null | null | null |
#include "jnpch.h"
#include "Core/Core.h"
#include "Core/Input.h"
#include "Scene.h"
#include "Graphics/SceneRenderer.h"
#include <glm/glm.hpp>
#include <glm/gtc/type_ptr.hpp>
#include "Scene/Entity.h"
#include "Graphics/Renderer.h"
namespace Janus
{
Scene::Scene(const std::string &debugName)
: m_DebugName(debugName)
{
Init();
}
Scene::~Scene()
{
}
void Scene::Init()
{
auto skyboxShader = Renderer::GetShaderLibrary()->Get("janus_skybox");
m_SkyboxMaterial = Material::Create(skyboxShader, "skybox_material");
m_SkyboxMaterial->SetFlag(MaterialFlag::DepthTest, false);
}
void Scene::OnUpdate(Timestep ts, EditorCamera &editorCamera)
{
JN_PROFILE_FUNCTION();
glEnable(GL_DEPTH_TEST);
auto lights = m_Registry.group<SkyLightComponent>(entt::get<TransformComponent>);
for (auto entity : lights)
{
auto [transformComponent, skyLightComponent] = lights.get<TransformComponent, SkyLightComponent>(entity);
m_Environment = skyLightComponent.SceneEnvironment;
m_EnvironmentIntensity = skyLightComponent.Intensity;
m_SkyboxLod = skyLightComponent.LOD;
}
if (lights.empty() || !m_Environment)
{
m_Environment = Ref<Environment>::Create(Renderer::GetBlackCubeTexture(), Renderer::GetBlackCubeTexture());
}
SetSkybox(m_Environment->RadianceMap);
m_SkyboxMaterial->Set("u_TextureLod", m_SkyboxLod);
{
auto pointLights = m_Registry.group<PointLightComponent>(entt::get<TransformComponent>);
m_LightEnvironment.PointLights.resize(pointLights.size());
uint32_t pointLightIndex = 0;
for (auto entity : pointLights)
{
auto [transformComponent, lightComponent] = pointLights.get<TransformComponent, PointLightComponent>(entity);
//Also copy the light size?
m_LightEnvironment.PointLights[pointLightIndex++] = {
transformComponent.Translation,
lightComponent.Radiance,
lightComponent.Intensity,
lightComponent.Radius,
lightComponent.Falloff,
};
}
}
SceneRenderer::BeginScene(this, {editorCamera, editorCamera.GetViewMatrix(), 0.1f, 1000.0f, 45.0f});
auto group = m_Registry.group<MeshComponent>(entt::get<TransformComponent>);
for (auto entity : group)
{
auto [transformComponent, meshComponent] = group.get<TransformComponent, MeshComponent>(entity);
if (meshComponent.Mesh)
{
Entity e = Entity(entity, this);
Ref<Material> overrideMaterial = nullptr;
SceneRenderer::SubmitMesh(meshComponent.Mesh, transformComponent.GetTransform(), overrideMaterial);
}
}
SceneRenderer::EndScene();
}
Entity Scene::CreateEntity(const std::string &name)
{
JN_PROFILE_FUNCTION();
auto entity = Entity{m_Registry.create(), this};
auto &idComponent = entity.AddComponent<IDComponent>();
idComponent.ID = {};
entity.AddComponent<TransformComponent>();
if (!name.empty())
entity.AddComponent<TagComponent>(name);
m_EntityIDMap[idComponent.ID] = entity;
return entity;
}
Entity Scene::CreateEntityWithID(UUID uuid, const std::string &name, bool runtimeMap)
{
JN_PROFILE_FUNCTION();
auto entity = Entity{m_Registry.create(), this};
auto &idComponent = entity.AddComponent<IDComponent>();
idComponent.ID = uuid;
entity.AddComponent<TransformComponent>();
if (!name.empty())
entity.AddComponent<TagComponent>(name);
JN_ASSERT(m_EntityIDMap.find(uuid) == m_EntityIDMap.end(), "");
m_EntityIDMap[uuid] = entity;
return entity;
}
void Scene::DestroyEntity(Entity entity)
{
JN_PROFILE_FUNCTION();
m_Registry.destroy(entity.m_EntityHandle);
}
Entity Scene::FindEntityByTag(const std::string &tag)
{
// TODO: If this becomes used often, consider indexing by tag
auto view = m_Registry.view<TagComponent>();
for (auto entity : view)
{
const auto &canditate = view.get<TagComponent>(entity).Tag;
if (canditate == tag)
return Entity(entity, this);
}
return Entity{};
}
Entity Scene::FindEntityByUUID(UUID id)
{
auto view = m_Registry.view<IDComponent>();
for (auto entity : view)
{
auto &idComponent = m_Registry.get<IDComponent>(entity);
if (idComponent.ID == id)
return Entity(entity, this);
}
return Entity{};
}
Ref<Scene> Scene::CreateEmpty()
{
return new Scene("Empty");
}
void Scene::SetSkybox(const Ref<TextureCube> &skybox)
{
m_SkyboxTexture = skybox;
m_SkyboxMaterial->Set("u_Texture", skybox);
}
}
| 27.1875
| 113
| 0.721609
|
Kytha
|
61ca05251c7b4567c3bcbb095b2d4d5f710a91a5
| 3,444
|
hpp
|
C++
|
cpp/subprojects/common/include/common/binning/threshold_vector.hpp
|
Waguy02/Boomer-Scripted
|
b06bb9213d64dca0c05d41701dea12666931618c
|
[
"MIT"
] | 8
|
2020-06-30T01:06:43.000Z
|
2022-03-14T01:58:29.000Z
|
cpp/subprojects/common/include/common/binning/threshold_vector.hpp
|
Waguy02/Boomer-Scripted
|
b06bb9213d64dca0c05d41701dea12666931618c
|
[
"MIT"
] | 3
|
2020-12-14T11:30:18.000Z
|
2022-02-07T06:31:51.000Z
|
cpp/subprojects/common/include/common/binning/threshold_vector.hpp
|
Waguy02/Boomer-Scripted
|
b06bb9213d64dca0c05d41701dea12666931618c
|
[
"MIT"
] | 4
|
2020-06-24T08:45:00.000Z
|
2021-12-23T21:44:51.000Z
|
/*
* @author Michael Rapp (michael.rapp.ml@gmail.com)
*/
#pragma once
#include "common/data/vector_dense.hpp"
#include "common/input/missing_feature_vector.hpp"
/**
* An one-dimensional vector that stores thresholds that may be used by conditions.
*/
class ThresholdVector final : public MissingFeatureVector {
private:
DenseVector<float32> vector_;
uint32 sparseBinIndex_;
public:
/**
* @param missingFeatureVector A reference to an object of type `MissingFeatureVector` the missing indices
* should be taken from
* @param numElements The number of elements in the vector
*/
ThresholdVector(MissingFeatureVector& missingFeatureVector, uint32 numElements);
/**
* @param missingFeatureVector A reference to an object of type `MissingFeatureVector` the missing indices
* should be taken from
* @param numElements The number of elements in the vector
* @param init True, if all elements in the vector should be value-initialized, false otherwise
*/
ThresholdVector(MissingFeatureVector& missingFeatureVector, uint32 numElements, bool init);
/**
* An iterator that provides access to the thresholds in the vector and allows to modify them.
*/
typedef DenseVector<float32>::iterator iterator;
/**
* An iterator that provides read-only access to the thresholds in the vector.
*/
typedef const DenseVector<float32>::const_iterator const_iterator;
/**
* Returns an `iterator` to the beginning of the vector.
*
* @return An `iterator` to the beginning
*/
iterator begin();
/**
* Returns an `iterator` to the end of the vector.
*
* @return An `iterator` to the end
*/
iterator end();
/**
* Returns a `const_iterator` to the beginning of the vector.
*
* @return A `const_iterator` to the beginning
*/
const_iterator cbegin() const;
/**
* Returns a `const_iterator` to the end of the vector.
*
* @return A `const_iterator` to the end
*/
const_iterator cend() const;
/**
* Returns the number of elements in the vector.
*
* @return The number of elements in the vector
*/
uint32 getNumElements() const;
/**
* Sets the number of elements in the vector.
*
* @param numElements The number of elements to be set
* @param freeMemory True, if unused memory should be freed, if possible, false otherwise
*/
void setNumElements(uint32 numElements, bool freeMemory);
/**
* Returns the index of the bin, sparse values have been assigned to.
*
* @return The index of the bin, sparse values have been assigned to. If there is no such bin, the returned
* index is equal to `getNumElements()`
*/
uint32 getSparseBinIndex() const;
/**
* Sets the index of the bin, sparse values have been assigned to.
*
* @param sparseBinIndex The index to be set
*/
void setSparseBinIndex(uint32 sparseBinIndex);
};
| 32.186916
| 120
| 0.589141
|
Waguy02
|
61cabc45d6d2c04f3eb69f296aea3dffbe9cd560
| 1,773
|
cpp
|
C++
|
velox/exec/Limit.cpp
|
HuamengJiang/velox-1
|
031066cb33ebc78e0cca3f9638d0eaa238bcbec0
|
[
"Apache-2.0"
] | null | null | null |
velox/exec/Limit.cpp
|
HuamengJiang/velox-1
|
031066cb33ebc78e0cca3f9638d0eaa238bcbec0
|
[
"Apache-2.0"
] | null | null | null |
velox/exec/Limit.cpp
|
HuamengJiang/velox-1
|
031066cb33ebc78e0cca3f9638d0eaa238bcbec0
|
[
"Apache-2.0"
] | null | null | null |
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* 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 "velox/exec/Limit.h"
namespace facebook::velox::exec {
Limit::Limit(
int32_t operatorId,
DriverCtx* driverCtx,
const std::shared_ptr<const core::LimitNode>& limitNode)
: Operator(
driverCtx,
limitNode->outputType(),
operatorId,
limitNode->id(),
"Limit"),
remainingLimit_(limitNode->count()) {}
bool Limit::needsInput() const {
return remainingLimit_ > 0 && input_ == nullptr;
}
void Limit::addInput(RowVectorPtr input) {
VELOX_CHECK(input_ == nullptr);
input_ = input;
}
RowVectorPtr Limit::getOutput() {
if (input_ == nullptr || remainingLimit_ == 0) {
return nullptr;
}
if (remainingLimit_ <= input_->size()) {
isFinishing_ = true;
}
if (remainingLimit_ >= input_->size()) {
remainingLimit_ -= input_->size();
auto output = input_;
input_.reset();
return output;
}
auto output = std::make_shared<RowVector>(
input_->pool(),
input_->type(),
input_->nulls(),
remainingLimit_,
input_->children());
input_.reset();
remainingLimit_ = 0;
return output;
}
} // namespace facebook::velox::exec
| 26.462687
| 75
| 0.661027
|
HuamengJiang
|
61cd5227db8cfd123104b2cd2121a7f8e5a9f294
| 1,671
|
cpp
|
C++
|
DynamicProgramming/trappingrainwater.cpp
|
thisisnitish/cp-dsa-
|
9ae94930b65f8dc293d088e9148960939b9f6fa4
|
[
"MIT"
] | null | null | null |
DynamicProgramming/trappingrainwater.cpp
|
thisisnitish/cp-dsa-
|
9ae94930b65f8dc293d088e9148960939b9f6fa4
|
[
"MIT"
] | null | null | null |
DynamicProgramming/trappingrainwater.cpp
|
thisisnitish/cp-dsa-
|
9ae94930b65f8dc293d088e9148960939b9f6fa4
|
[
"MIT"
] | null | null | null |
/*
Leetcode Question 42. Trapping Rain Water
https://leetcode.com/problems/trapping-rain-water/
*/
// Solution 1
class Solution
{
public:
// Time: O(N^2), Space: O(N)
int trap(vector<int> &height)
{
int n = height.size();
int trappedWater = 0;
for (int i = 0; i < n; i++)
{
int maxLeft = 0, maxRight = 0;
// moving to the left side
for (int j = i; j >= 0; j--)
{
maxLeft = max(maxLeft, height[j]);
}
// moving to the right side
for (int j = i; j < n; j++)
{
maxRight = max(maxRight, height[j]);
}
int currentTrapped = min(maxLeft, maxRight) - height[i];
trappedWater += currentTrapped;
}
return trappedWater;
}
};
// Solution 2
class Solution
{
public:
// Time: O(N), Space: O(N)
int trap(vector<int> &height)
{
int n = height.size();
if (n == 0)
return 0;
vector<int> leftMax(n);
vector<int> rightMax(n);
// calculate the left side
leftMax[0] = height[0];
for (int i = 1; i < n; i++)
{
leftMax[i] = max(leftMax[i - 1], height[i]);
}
// calculate the right side
rightMax[n - 1] = height[n - 1];
for (int i = n - 2; i >= 0; i--)
{
rightMax[i] = max(rightMax[i + 1], height[i]);
}
int trappedWater = 0;
for (int i = 0; i < n; i++)
{
trappedWater += min(rightMax[i], leftMax[i]) - height[i];
}
return trappedWater;
}
};
| 22.28
| 69
| 0.453621
|
thisisnitish
|
61ce1574b4254dc87fdcef0f115ef029ddb1cd09
| 743
|
cpp
|
C++
|
boost_asio/boost_asio_net_program_book/e.g.6.cpp
|
adlternative/boost-learn
|
8efe901dec2b0caa1b6d59b805fd4af121c51e05
|
[
"BSD-2-Clause"
] | null | null | null |
boost_asio/boost_asio_net_program_book/e.g.6.cpp
|
adlternative/boost-learn
|
8efe901dec2b0caa1b6d59b805fd4af121c51e05
|
[
"BSD-2-Clause"
] | null | null | null |
boost_asio/boost_asio_net_program_book/e.g.6.cpp
|
adlternative/boost-learn
|
8efe901dec2b0caa1b6d59b805fd4af121c51e05
|
[
"BSD-2-Clause"
] | null | null | null |
#include <boost/asio.hpp>
#include <boost/bind/placeholders.hpp>
#include <boost/thread.hpp>
#include <iostream>
/* 不可编译 */
using namespace boost::asio;
bool reads = false;
void deadline_handler(const boost::system::error_code &) {
std::cout << (((reads) ? "reads successfully" : "reads failed")) << std::endl;
}
void reads_handler(const boost::system::error_code &) { reads = true; }
int main(int argc, char const *argv[]) {
io_service service;
ip::tcp::socket sock(service);
reads = false;
char data[512];
boost::system::error_code ec;
sock.async_read_some(buffer(data, 512), reads_handler);
deadline_timer t(service, boost::posix_time::milliseconds(100));
t.async_wait(&deadline_handler);
service.run();
return 0;
}
| 28.576923
| 80
| 0.703903
|
adlternative
|
61cf11066eb994db74ad474415ea46e636ef7d7b
| 946
|
hpp
|
C++
|
math/primitive/2d/ray.hpp
|
aconstlink/natus
|
d2123c6e1798bd0771b8a1a05721c68392afc92f
|
[
"MIT"
] | null | null | null |
math/primitive/2d/ray.hpp
|
aconstlink/natus
|
d2123c6e1798bd0771b8a1a05721c68392afc92f
|
[
"MIT"
] | 292
|
2020-03-19T22:38:52.000Z
|
2022-03-05T22:49:34.000Z
|
math/primitive/2d/ray.hpp
|
aconstlink/natus
|
d2123c6e1798bd0771b8a1a05721c68392afc92f
|
[
"MIT"
] | null | null | null |
#pragma once
#include "../../vector/vector2.hpp"
namespace natus
{
namespace math
{
namespace m2d
{
template< typename type_t >
class ray
{
typedef natus::math::vector2< type_t > vec2_t ;
typedef vec2_t const& vec2_cref_t ;
private:
vec2_t _origin ;
vec2_t _dir ;
public:
ray( void_t ) {}
ray( vec2_cref_t orig, vec2_cref_t dir )
{
_origin = orig ;
_dir = dir ;
}
vec2_cref_t get_origin( void_t ) const { return _origin ; }
vec2_cref_t get_direction( void_t ) const { return _dir ; }
vec2_t point_at( type_t dist ) const { return _origin + _dir * dist ; }
};
}
typedef natus_2d::ray< float > ray2f_t ;
}
}
| 23.65
| 87
| 0.455603
|
aconstlink
|
61d087c177e256f55cc16e00357ce665ee4dd355
| 34,718
|
cpp
|
C++
|
src/Generating/HeiGen.cpp
|
planetx/MCServer
|
4e119b522409af682e62ed38f4d22ddd9da40170
|
[
"Apache-2.0"
] | null | null | null |
src/Generating/HeiGen.cpp
|
planetx/MCServer
|
4e119b522409af682e62ed38f4d22ddd9da40170
|
[
"Apache-2.0"
] | null | null | null |
src/Generating/HeiGen.cpp
|
planetx/MCServer
|
4e119b522409af682e62ed38f4d22ddd9da40170
|
[
"Apache-2.0"
] | null | null | null |
// HeiGen.cpp
// Implements the various terrain height generators
#include "Globals.h"
#include "HeiGen.h"
#include "../LinearUpscale.h"
#include "../IniFile.h"
#include "DistortedHeightmap.h"
#include "EndGen.h"
#include "Noise3DGenerator.h"
////////////////////////////////////////////////////////////////////////////////
// cHeiGenFlat:
void cHeiGenFlat::GenHeightMap(int a_ChunkX, int a_ChunkZ, cChunkDef::HeightMap & a_HeightMap)
{
for (size_t i = 0; i < ARRAYCOUNT(a_HeightMap); i++)
{
a_HeightMap[i] = m_Height;
}
}
void cHeiGenFlat::InitializeHeightGen(cIniFile & a_IniFile)
{
m_Height = a_IniFile.GetValueSetI("Generator", "FlatHeight", m_Height);
}
////////////////////////////////////////////////////////////////////////////////
// cHeiGenCache:
cHeiGenCache::cHeiGenCache(cTerrainHeightGenPtr a_HeiGenToCache, int a_CacheSize) :
m_HeiGenToCache(a_HeiGenToCache),
m_CacheSize(a_CacheSize),
m_CacheOrder(new int[a_CacheSize]),
m_CacheData(new sCacheData[a_CacheSize]),
m_NumHits(0),
m_NumMisses(0),
m_TotalChain(0)
{
for (int i = 0; i < m_CacheSize; i++)
{
m_CacheOrder[i] = i;
m_CacheData[i].m_ChunkX = 0x7fffffff;
m_CacheData[i].m_ChunkZ = 0x7fffffff;
}
}
cHeiGenCache::~cHeiGenCache()
{
delete[] m_CacheData;
m_CacheData = nullptr;
delete[] m_CacheOrder;
m_CacheOrder = nullptr;
}
void cHeiGenCache::GenHeightMap(int a_ChunkX, int a_ChunkZ, cChunkDef::HeightMap & a_HeightMap)
{
/*
if (((m_NumHits + m_NumMisses) % 1024) == 10)
{
LOGD("HeiGenCache: %d hits, %d misses, saved %.2f %%", m_NumHits, m_NumMisses, 100.0 * m_NumHits / (m_NumHits + m_NumMisses));
LOGD("HeiGenCache: Avg cache chain length: %.2f", (float)m_TotalChain / m_NumHits);
}
//*/
for (int i = 0; i < m_CacheSize; i++)
{
if (
(m_CacheData[m_CacheOrder[i]].m_ChunkX != a_ChunkX) ||
(m_CacheData[m_CacheOrder[i]].m_ChunkZ != a_ChunkZ)
)
{
continue;
}
// Found it in the cache
int Idx = m_CacheOrder[i];
// Move to front:
for (int j = i; j > 0; j--)
{
m_CacheOrder[j] = m_CacheOrder[j - 1];
}
m_CacheOrder[0] = Idx;
// Use the cached data:
memcpy(a_HeightMap, m_CacheData[Idx].m_HeightMap, sizeof(a_HeightMap));
m_NumHits++;
m_TotalChain += i;
return;
} // for i - cache
// Not in the cache:
m_NumMisses++;
m_HeiGenToCache->GenHeightMap(a_ChunkX, a_ChunkZ, a_HeightMap);
// Insert it as the first item in the MRU order:
int Idx = m_CacheOrder[m_CacheSize - 1];
for (int i = m_CacheSize - 1; i > 0; i--)
{
m_CacheOrder[i] = m_CacheOrder[i - 1];
} // for i - m_CacheOrder[]
m_CacheOrder[0] = Idx;
memcpy(m_CacheData[Idx].m_HeightMap, a_HeightMap, sizeof(a_HeightMap));
m_CacheData[Idx].m_ChunkX = a_ChunkX;
m_CacheData[Idx].m_ChunkZ = a_ChunkZ;
}
bool cHeiGenCache::GetHeightAt(int a_ChunkX, int a_ChunkZ, int a_RelX, int a_RelZ, HEIGHTTYPE & a_Height)
{
for (int i = 0; i < m_CacheSize; i++)
{
if ((m_CacheData[i].m_ChunkX == a_ChunkX) && (m_CacheData[i].m_ChunkZ == a_ChunkZ))
{
a_Height = cChunkDef::GetHeight(m_CacheData[i].m_HeightMap, a_RelX, a_RelZ);
return true;
}
} // for i - m_CacheData[]
return false;
}
////////////////////////////////////////////////////////////////////////////////
// cHeiGenMultiCache:
cHeiGenMultiCache::cHeiGenMultiCache(cTerrainHeightGenPtr a_HeiGenToCache, size_t a_SubCacheSize, size_t a_NumSubCaches):
m_NumSubCaches(a_NumSubCaches)
{
// Create the individual sub-caches:
m_SubCaches.reserve(a_NumSubCaches);
for (size_t i = 0; i < a_NumSubCaches; i++)
{
m_SubCaches.push_back(std::make_shared<cHeiGenCache>(a_HeiGenToCache, a_SubCacheSize));
}
}
void cHeiGenMultiCache::GenHeightMap(int a_ChunkX, int a_ChunkZ, cChunkDef::HeightMap & a_HeightMap)
{
// Get the subcache responsible for this chunk:
const size_t cacheIdx = ((size_t)a_ChunkX + m_CoeffZ * (size_t)a_ChunkZ) % m_NumSubCaches;
// Ask the subcache:
m_SubCaches[cacheIdx]->GenHeightMap(a_ChunkX, a_ChunkZ, a_HeightMap);
}
bool cHeiGenMultiCache::GetHeightAt(int a_ChunkX, int a_ChunkZ, int a_RelX, int a_RelZ, HEIGHTTYPE & a_Height)
{
// Get the subcache responsible for this chunk:
const size_t cacheIdx = ((size_t)a_ChunkX + m_CoeffZ * (size_t)a_ChunkZ) % m_NumSubCaches;
// Ask the subcache:
return m_SubCaches[cacheIdx]->GetHeightAt(a_ChunkX, a_ChunkZ, a_RelX, a_RelZ, a_Height);
}
////////////////////////////////////////////////////////////////////////////////
// cHeiGenClassic:
cHeiGenClassic::cHeiGenClassic(int a_Seed) :
m_Seed(a_Seed),
m_Noise(a_Seed),
m_HeightFreq1(1.0f),
m_HeightAmp1(1.0f),
m_HeightFreq2(0.5f),
m_HeightAmp2(0.5f),
m_HeightFreq3(0.1f),
m_HeightAmp3(0.1f)
{
}
float cHeiGenClassic::GetNoise(float x, float y)
{
float oct1 = m_Noise.CubicNoise2D(x * m_HeightFreq1, y * m_HeightFreq1) * m_HeightAmp1;
float oct2 = m_Noise.CubicNoise2D(x * m_HeightFreq2, y * m_HeightFreq2) * m_HeightAmp2;
float oct3 = m_Noise.CubicNoise2D(x * m_HeightFreq3, y * m_HeightFreq3) * m_HeightAmp3;
float height = m_Noise.CubicNoise2D(x * 0.1f, y * 0.1f) * 2;
float flatness = ((m_Noise.CubicNoise2D(x * 0.5f, y * 0.5f) + 1.f) * 0.5f) * 1.1f; // 0 ... 1.5
flatness *= flatness * flatness;
return (oct1 + oct2 + oct3) * flatness + height;
}
void cHeiGenClassic::GenHeightMap(int a_ChunkX, int a_ChunkZ, cChunkDef::HeightMap & a_HeightMap)
{
for (int z = 0; z < cChunkDef::Width; z++)
{
const float zz = (float)(a_ChunkZ * cChunkDef::Width + z);
for (int x = 0; x < cChunkDef::Width; x++)
{
const float xx = (float)(a_ChunkX * cChunkDef::Width + x);
int hei = 64 + (int)(GetNoise(xx * 0.05f, zz * 0.05f) * 16);
if (hei < 10)
{
hei = 10;
}
if (hei > 250)
{
hei = 250;
}
cChunkDef::SetHeight(a_HeightMap, x, z, hei);
} // for x
} // for z
}
void cHeiGenClassic::InitializeHeightGen(cIniFile & a_IniFile)
{
m_HeightFreq1 = (float)a_IniFile.GetValueSetF("Generator", "ClassicHeightFreq1", 0.1);
m_HeightFreq2 = (float)a_IniFile.GetValueSetF("Generator", "ClassicHeightFreq2", 1.0);
m_HeightFreq3 = (float)a_IniFile.GetValueSetF("Generator", "ClassicHeightFreq3", 2.0);
m_HeightAmp1 = (float)a_IniFile.GetValueSetF("Generator", "ClassicHeightAmp1", 1.0);
m_HeightAmp2 = (float)a_IniFile.GetValueSetF("Generator", "ClassicHeightAmp2", 0.5);
m_HeightAmp3 = (float)a_IniFile.GetValueSetF("Generator", "ClassicHeightAmp3", 0.5);
}
////////////////////////////////////////////////////////////////////////////////
// cHeiGenMountains:
cHeiGenMountains::cHeiGenMountains(int a_Seed) :
m_Seed(a_Seed),
m_MountainNoise(a_Seed + 100),
m_DitchNoise(a_Seed + 200),
m_Perlin(a_Seed + 300)
{
}
void cHeiGenMountains::GenHeightMap(int a_ChunkX, int a_ChunkZ, cChunkDef::HeightMap & a_HeightMap)
{
NOISE_DATATYPE StartX = (NOISE_DATATYPE)(a_ChunkX * cChunkDef::Width);
NOISE_DATATYPE EndX = (NOISE_DATATYPE)(a_ChunkX * cChunkDef::Width + cChunkDef::Width - 1);
NOISE_DATATYPE StartZ = (NOISE_DATATYPE)(a_ChunkZ * cChunkDef::Width);
NOISE_DATATYPE EndZ = (NOISE_DATATYPE)(a_ChunkZ * cChunkDef::Width + cChunkDef::Width - 1);
NOISE_DATATYPE Workspace[16 * 16];
NOISE_DATATYPE MountainNoise[16 * 16];
NOISE_DATATYPE DitchNoise[16 * 16];
NOISE_DATATYPE PerlinNoise[16 * 16];
m_MountainNoise.Generate2D(MountainNoise, 16, 16, StartX, EndX, StartZ, EndZ, Workspace);
m_DitchNoise.Generate2D(DitchNoise, 16, 16, StartX, EndX, StartZ, EndZ, Workspace);
m_Perlin.Generate2D(PerlinNoise, 16, 16, StartX, EndX, StartZ, EndZ, Workspace);
for (int z = 0; z < cChunkDef::Width; z++)
{
int IdxZ = z * cChunkDef::Width;
for (int x = 0; x < cChunkDef::Width; x++)
{
int idx = IdxZ + x;
int hei = 100 - (int)((MountainNoise[idx] - DitchNoise[idx] + PerlinNoise[idx]) * 15);
if (hei < 10)
{
hei = 10;
}
if (hei > 250)
{
hei = 250;
}
cChunkDef::SetHeight(a_HeightMap, x, z, hei);
} // for x
} // for z
}
void cHeiGenMountains::InitializeHeightGen(cIniFile & a_IniFile)
{
// TODO: Read the params from an INI file
m_MountainNoise.AddOctave(0.1f, 0.2f);
m_MountainNoise.AddOctave(0.05f, 0.4f);
m_MountainNoise.AddOctave(0.02f, 1.0f);
m_DitchNoise.AddOctave(0.1f, 0.2f);
m_DitchNoise.AddOctave(0.05f, 0.4f);
m_DitchNoise.AddOctave(0.02f, 1.0f);
m_Perlin.AddOctave(0.01f, 1.5f);
}
////////////////////////////////////////////////////////////////////////////////
// cHeiGenBiomal:
const cHeiGenBiomal::sGenParam cHeiGenBiomal::m_GenParam[256] =
{
/* Fast-changing | Middle-changing | Slow-changing |*/
/* Biome | Freq1 | Amp1 | Freq2 | Amp2 | Freq3 | Amp3 | BaseHeight */
/* biOcean */ { 0.1f, 2.0f, 0.05f, 10.0f, 0.01f, 8.0f, 50},
/* biPlains */ { 0.1f, 1.0f, 0.05f, 1.5f, 0.01f, 4.0f, 68},
/* biDesert */ { 0.1f, 1.0f, 0.05f, 1.5f, 0.01f, 4.0f, 68},
/* biExtremeHills */ { 0.2f, 4.0f, 0.05f, 20.0f, 0.01f, 16.0f, 100},
/* biForest */ { 0.1f, 1.0f, 0.05f, 2.0f, 0.01f, 4.0f, 70},
/* biTaiga */ { 0.1f, 1.0f, 0.05f, 2.0f, 0.01f, 4.0f, 70},
/* biSwampland */ { 0.1f, 1.1f, 0.05f, 1.5f, 0.02f, 2.5f, 61.5},
/* biRiver */ { 0.2f, 0.1f, 0.05f, 0.1f, 0.01f, 0.1f, 56},
/* biNether */ { 0.1f, 0.0f, 0.01f, 0.0f, 0.01f, 0.0f, 0}, // Unused, but must be here due to indexing
/* biSky */ { 0.1f, 0.0f, 0.01f, 0.0f, 0.01f, 0.0f, 0}, // Unused, but must be here due to indexing
/* biFrozenOcean */ { 0.1f, 2.0f, 0.05f, 12.0f, 0.01f, 10.0f, 40},
/* biFrozenRiver */ { 0.2f, 0.1f, 0.05f, 0.1f, 0.01f, 0.1f, 56},
/* biIcePlains */ { 0.1f, 1.0f, 0.05f, 1.5f, 0.01f, 4.0f, 68},
/* biIceMountains */ { 0.2f, 2.0f, 0.05f, 10.0f, 0.01f, 8.0f, 80},
/* biMushroomIsland */ { 0.1f, 2.0f, 0.05f, 8.0f, 0.01f, 6.0f, 80},
/* biMushroomShore */ { 0.1f, 1.0f, 0.05f, 2.0f, 0.01f, 4.0f, 64},
/* biBeach */ { 0.1f, 0.5f, 0.05f, 1.0f, 0.01f, 1.0f, 64},
/* biDesertHills */ { 0.2f, 2.0f, 0.05f, 5.0f, 0.01f, 4.0f, 75},
/* biForestHills */ { 0.2f, 2.0f, 0.05f, 12.0f, 0.01f, 10.0f, 80},
/* biTaigaHills */ { 0.2f, 2.0f, 0.05f, 12.0f, 0.01f, 10.0f, 80},
/* biExtremeHillsEdge */ { 0.2f, 3.0f, 0.05f, 16.0f, 0.01f, 12.0f, 80},
/* biJungle */ { 0.1f, 3.0f, 0.05f, 6.0f, 0.01f, 6.0f, 70},
/* biJungleHills */ { 0.2f, 3.0f, 0.05f, 12.0f, 0.01f, 10.0f, 80},
/* biJungleEdge */ { 0.1f, 3.0f, 0.05f, 6.0f, 0.01f, 6.0f, 70},
/* biDeepOcean */ { 0.1f, 2.0f, 0.05f, 12.0f, 0.01f, 10.0f, 40},
/* biStoneBeach */ { 0.1f, 2.0f, 0.05f, 12.0f, 0.01f, 10.0f, 40},
/* biColdBeach */ { 0.1f, 0.5f, 0.05f, 1.0f, 0.01f, 1.0f, 64},
/* biBirchForest */ { 0.1f, 1.0f, 0.05f, 2.0f, 0.01f, 4.0f, 70},
/* biBirchForestHills */ { 0.2f, 2.0f, 0.05f, 10.0f, 0.01f, 8.0f, 80},
/* biRoofedForest */ { 0.1f, 1.0f, 0.05f, 2.0f, 0.01f, 4.0f, 70},
/* biColdTaiga */ { 0.1f, 1.0f, 0.05f, 2.0f, 0.01f, 4.0f, 70},
/* biColdTaigaHills */ { 0.2f, 2.0f, 0.05f, 10.0f, 0.01f, 8.0f, 80},
/* biMegaTaiga */ { 0.1f, 1.0f, 0.05f, 2.0f, 0.01f, 4.0f, 70},
/* biMegaTaigaHills */ { 0.2f, 2.0f, 0.05f, 10.0f, 0.01f, 8.0f, 80},
/* biExtremeHillsPlus */ { 0.2f, 4.0f, 0.05f, 20.0f, 0.01f, 16.0f, 120},
/* biSavanna */ { 0.1f, 1.0f, 0.05f, 1.5f, 0.01f, 4.0f, 68},
/* biSavannaPlateau */ { 0.1f, 1.0f, 0.05f, 1.5f, 0.01f, 4.0f, 80},
/* biMesa */ { 0.2f, 2.0f, 0.05f, 10.0f, 0.01f, 8.0f, 70}, // 165
/* biMesaPlateauF */ { 0.1f, 1.0f, 0.05f, 1.5f, 0.01f, 4.0f, 80},
/* biMesaPlateau */ { 0.1f, 1.0f, 0.05f, 1.5f, 0.01f, 4.0f, 80},
// biomes 40 .. 128 are unused, 89 empty placeholders here:
{0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, // 40 .. 49
{0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, // 50 .. 59
{0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, // 60 .. 69
{0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, // 70 .. 79
{0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, // 80 .. 89
{0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, // 90 .. 99
{0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, // 100 .. 109
{0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, // 110 .. 119
{0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, // 120 .. 128
/* biSunflowerPlains */ { 0.1f, 2.0f, 0.05f, 12.0f, 0.01f, 10.0f, 40}, // 129
/* biDesertM */ { 0.1f, 2.0f, 0.05f, 12.0f, 0.01f, 10.0f, 40}, // 130
/* biExtremeHillsM */ { 0.1f, 2.0f, 0.05f, 12.0f, 0.01f, 10.0f, 40}, // 131
/* biFlowerForest */ { 0.1f, 2.0f, 0.05f, 12.0f, 0.01f, 10.0f, 40}, // 132
/* biTaigaM */ { 0.1f, 2.0f, 0.05f, 12.0f, 0.01f, 10.0f, 40}, // 133
/* biSwamplandM */ { 1.0f, 3.0f, 1.10f, 7.0f, 0.01f, 0.01f, 60}, // 134
// Biomes 135 .. 139 unused, 5 empty placeholders here:
{0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, // 135 .. 139
/* biIcePlainsSpikes */ { 0.1f, 2.0f, 0.05f, 12.0f, 0.01f, 10.0f, 40}, // 140
// Biomes 141 .. 148 unused, 8 empty placeholders here:
{0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, // 141 .. 148
/* biJungleM */ { 0.1f, 3.0f, 0.05f, 6.0f, 0.01f, 6.0f, 70}, // 149
{0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, // 150
/* biJungleEdgeM */ { 0.1f, 3.0f, 0.05f, 6.0f, 0.01f, 6.0f, 70}, // 151
{0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, // 152 .. 154
/* biBirchForestM */ { 0.1f, 1.0f, 0.05f, 2.0f, 0.01f, 4.0f, 70}, // 155
/* biBirchForestHillsM */ { 0.2f, 2.0f, 0.05f, 10.0f, 0.01f, 8.0f, 80}, // 156
/* biRoofedForestM */ { 0.1f, 1.0f, 0.05f, 2.0f, 0.01f, 4.0f, 70}, // 157
/* biColdTaigaM */ { 0.1f, 1.0f, 0.05f, 2.0f, 0.01f, 4.0f, 70}, // 158
{0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, // 159
/* biMegaSpruceTaiga */ { 0.1f, 1.0f, 0.05f, 2.0f, 0.01f, 4.0f, 70}, // 160
/* biMegaSpruceTaigaHills */ { 0.2f, 2.0f, 0.05f, 10.0f, 0.01f, 8.0f, 80}, // 161
/* biExtremeHillsPlusM */ { 0.2f, 4.0f, 0.05f, 20.0f, 0.01f, 16.0f, 120}, // 162
/* biSavannaM */ { 0.1f, 1.0f, 0.05f, 1.5f, 0.01f, 4.0f, 68}, // 163
/* biSavannaPlateauM */ { 0.1f, 1.0f, 0.05f, 1.5f, 0.01f, 4.0f, 80}, // 164
/* biMesaBryce */ { 0.2f, 2.0f, 0.1f, 30.0f, 0.01f, 8.0f, 80},
/* biMesaPlateauFM */ { 0.1f, 1.0f, 0.05f, 1.5f, 0.01f, 4.0f, 80}, // 166
/* biMesaPlateauM */ { 0.1f, 1.0f, 0.05f, 1.5f, 0.01f, 4.0f, 80}, // 167
} ;
void cHeiGenBiomal::GenHeightMap(int a_ChunkX, int a_ChunkZ, cChunkDef::HeightMap & a_HeightMap)
{
// Generate a 3x3 chunk area of biomes around this chunk:
BiomeNeighbors Biomes;
for (int z = -1; z <= 1; z++)
{
for (int x = -1; x <= 1; x++)
{
m_BiomeGen->GenBiomes(a_ChunkX + x, a_ChunkZ + z, Biomes[x + 1][z + 1]);
} // for x
} // for z
/*
_X 2013_04_22:
There's no point in precalculating the entire perlin noise arrays, too many values are calculated uselessly,
resulting in speed DEcrease.
*/
//*
// Linearly interpolate 4x4 blocks of heightmap:
// Must be done on a floating point datatype, else the results are ugly!
const int STEPZ = 4; // Must be a divisor of 16
const int STEPX = 4; // Must be a divisor of 16
NOISE_DATATYPE Height[17 * 17];
for (int z = 0; z < 17; z += STEPZ)
{
for (int x = 0; x < 17; x += STEPX)
{
Height[x + 17 * z] = GetHeightAt(x, z, a_ChunkX, a_ChunkZ, Biomes);
}
}
LinearUpscale2DArrayInPlace<17, 17, STEPX, STEPZ>(Height);
// Copy into the heightmap
for (int z = 0; z < cChunkDef::Width; z++)
{
for (int x = 0; x < cChunkDef::Width; x++)
{
cChunkDef::SetHeight(a_HeightMap, x, z, (int)Height[x + 17 * z]);
}
}
//*/
/*
// For each height, go through neighboring biomes and add up their idea of height:
for (int z = 0; z < cChunkDef::Width; z++)
{
for (int x = 0; x < cChunkDef::Width; x++)
{
cChunkDef::SetHeight(a_HeightMap, x, z, GetHeightAt(x, z, a_ChunkX, a_ChunkZ, Biomes));
} // for x
}
//*/
}
void cHeiGenBiomal::InitializeHeightGen(cIniFile & a_IniFile)
{
// No user-settable params
}
NOISE_DATATYPE cHeiGenBiomal::GetHeightAt(int a_RelX, int a_RelZ, int a_ChunkX, int a_ChunkZ, const cHeiGenBiomal::BiomeNeighbors & a_BiomeNeighbors)
{
// Sum up how many biomes of each type there are in the neighborhood:
int BiomeCounts[256];
memset(BiomeCounts, 0, sizeof(BiomeCounts));
int Sum = 0;
for (int z = -8; z <= 8; z++)
{
int FinalZ = a_RelZ + z + cChunkDef::Width;
int IdxZ = FinalZ / cChunkDef::Width;
int ModZ = FinalZ % cChunkDef::Width;
int WeightZ = 9 - abs(z);
for (int x = -8; x <= 8; x++)
{
int FinalX = a_RelX + x + cChunkDef::Width;
int IdxX = FinalX / cChunkDef::Width;
int ModX = FinalX % cChunkDef::Width;
EMCSBiome Biome = cChunkDef::GetBiome(a_BiomeNeighbors[IdxX][IdxZ], ModX, ModZ);
int WeightX = 9 - abs(x);
BiomeCounts[Biome] += WeightX + WeightZ;
Sum += WeightX + WeightZ;
} // for x
} // for z
// For each biome type that has a nonzero count, calc its height and add it:
if (Sum > 0)
{
NOISE_DATATYPE Height = 0;
int BlockX = a_ChunkX * cChunkDef::Width + a_RelX;
int BlockZ = a_ChunkZ * cChunkDef::Width + a_RelZ;
for (size_t i = 0; i < ARRAYCOUNT(BiomeCounts); i++)
{
if (BiomeCounts[i] == 0)
{
continue;
}
/*
// Sanity checks for biome parameters, enable them to check the biome param table in runtime (slow):
ASSERT(m_GenParam[i].m_HeightFreq1 >= 0);
ASSERT(m_GenParam[i].m_HeightFreq1 < 1000);
ASSERT(m_GenParam[i].m_HeightFreq2 >= 0);
ASSERT(m_GenParam[i].m_HeightFreq2 < 1000);
ASSERT(m_GenParam[i].m_HeightFreq3 >= 0);
ASSERT(m_GenParam[i].m_HeightFreq3 < 1000);
*/
NOISE_DATATYPE oct1 = m_Noise.CubicNoise2D(BlockX * m_GenParam[i].m_HeightFreq1, BlockZ * m_GenParam[i].m_HeightFreq1) * m_GenParam[i].m_HeightAmp1;
NOISE_DATATYPE oct2 = m_Noise.CubicNoise2D(BlockX * m_GenParam[i].m_HeightFreq2, BlockZ * m_GenParam[i].m_HeightFreq2) * m_GenParam[i].m_HeightAmp2;
NOISE_DATATYPE oct3 = m_Noise.CubicNoise2D(BlockX * m_GenParam[i].m_HeightFreq3, BlockZ * m_GenParam[i].m_HeightFreq3) * m_GenParam[i].m_HeightAmp3;
Height += BiomeCounts[i] * (m_GenParam[i].m_BaseHeight + oct1 + oct2 + oct3);
}
NOISE_DATATYPE res = Height / Sum;
return std::min((NOISE_DATATYPE)250, std::max(res, (NOISE_DATATYPE)5));
}
// No known biome around? Weird. Return a bogus value:
ASSERT(!"cHeiGenBiomal: Biome sum failed, no known biome around");
return 5;
}
////////////////////////////////////////////////////////////////////////////////
// cHeiGenMinMax:
class cHeiGenMinMax:
public cTerrainHeightGen
{
typedef cTerrainHeightGen super;
/** Size of the averaging process, in columns (for each direction). Must be less than 16. */
static const int AVERAGING_SIZE = 4;
public:
cHeiGenMinMax(int a_Seed, cBiomeGenPtr a_BiomeGen):
m_Noise(a_Seed),
m_BiomeGen(a_BiomeGen),
m_TotalWeight(0)
{
// Initialize the weights:
for (int z = 0; z <= AVERAGING_SIZE * 2; z++)
{
for (int x = 0; x <= AVERAGING_SIZE * 2; x++)
{
m_Weights[z][x] = 1 + 2 * AVERAGING_SIZE - std::abs(x - AVERAGING_SIZE) - std::abs(z - AVERAGING_SIZE);
m_TotalWeight += m_Weights[z][x];
}
}
// Initialize the Perlin generator:
m_Perlin.AddOctave(0.04f, 0.2f);
m_Perlin.AddOctave(0.02f, 0.1f);
m_Perlin.AddOctave(0.01f, 0.05f);
}
virtual void GenHeightMap(int a_ChunkX, int a_ChunkZ, cChunkDef::HeightMap & a_HeightMap)
{
// Generate the biomes for the 3*3 neighbors:
cChunkDef::BiomeMap neighborBiomes[3][3];
for (int z = 0; z < 3; z++) for (int x = 0; x < 3; x++)
{
m_BiomeGen->GenBiomes(a_ChunkX + x - 1, a_ChunkZ + z - 1, neighborBiomes[z][x]);
}
// Get the min and max heights based on the biomes:
double minHeight[cChunkDef::Width * cChunkDef::Width];
double maxHeight[cChunkDef::Width * cChunkDef::Width];
for (int z = 0; z < cChunkDef::Width; z++)
{
for (int x = 0; x < cChunkDef::Width; x++)
{
// For each column, sum the min and max values of the neighborhood around it:
double min = 0, max = 0;
for (int relz = 0; relz <= AVERAGING_SIZE * 2; relz++)
{
int bz = z + 16 + relz - AVERAGING_SIZE; // Biome Z coord relative to the neighborBiomes start
int cz = bz / 16; // Chunk Z coord relative to the neighborBiomes start
bz = bz % 16; // Biome Z coord relative to cz in neighborBiomes
for (int relx = 0; relx <= AVERAGING_SIZE * 2; relx++)
{
int bx = x + 16 + relx - AVERAGING_SIZE; // Biome X coord relative to the neighborBiomes start
int cx = bx / 16; // Chunk X coord relative to the neighborBiomes start
bx = bx % 16; // Biome X coord relative to cz in neighborBiomes
// Get the biome's min and max heights:
double bmin, bmax;
getBiomeMinMax(cChunkDef::GetBiome(neighborBiomes[cz][cx], bx, bz), bmin, bmax);
// Add them to the total, with the weight depending on their relative position to the column:
min += bmin * m_Weights[relz][relx];
max += bmax * m_Weights[relz][relx];
} // for relx
} // for relz
minHeight[x + z * cChunkDef::Width] = min / m_TotalWeight;
maxHeight[x + z * cChunkDef::Width] = max / m_TotalWeight;
} // for x
} // for z
// Generate the base noise:
NOISE_DATATYPE noise[cChunkDef::Width * cChunkDef::Width];
NOISE_DATATYPE workspace[cChunkDef::Width * cChunkDef::Width];
NOISE_DATATYPE startX = static_cast<float>(a_ChunkX * cChunkDef::Width);
NOISE_DATATYPE endX = startX + cChunkDef::Width - 1;
NOISE_DATATYPE startZ = static_cast<float>(a_ChunkZ * cChunkDef::Width);
NOISE_DATATYPE endZ = startZ + cChunkDef::Width - 1;
m_Perlin.Generate2D(noise, 16, 16, startX, endX, startZ, endZ, workspace);
// Make the height by ranging the noise between min and max:
for (int z = 0; z < cChunkDef::Width; z++)
{
for (int x = 0; x < cChunkDef::Width; x++)
{
double min = minHeight[x + z * cChunkDef::Width];
double max = maxHeight[x + z * cChunkDef::Width];
double h = (max + min) / 2 + noise[x + z * cChunkDef::Width] * (max - min);
cChunkDef::SetHeight(a_HeightMap, x, z, static_cast<HEIGHTTYPE>(h));
}
}
}
virtual void InitializeHeightGen(cIniFile & a_IniFile)
{
// No settings available
}
protected:
cNoise m_Noise;
cPerlinNoise m_Perlin;
/** The biome generator to query for the underlying biomes. */
cBiomeGenPtr m_BiomeGen;
/** Weights applied to each of the min / max values in the neighborhood of the currently evaluated column. */
double m_Weights[AVERAGING_SIZE * 2 + 1][AVERAGING_SIZE * 2 + 1];
/** Sum of all the m_Weights items. */
double m_TotalWeight;
/** Returns the minimum and maximum heights for the given biome. */
void getBiomeMinMax(EMCSBiome a_Biome, double & a_Min, double & a_Max)
{
switch (a_Biome)
{
case biBeach: a_Min = 61; a_Max = 64; break;
case biBirchForest: a_Min = 63; a_Max = 75; break;
case biBirchForestHills: a_Min = 63; a_Max = 90; break;
case biBirchForestHillsM: a_Min = 63; a_Max = 90; break;
case biBirchForestM: a_Min = 63; a_Max = 75; break;
case biColdBeach: a_Min = 61; a_Max = 64; break;
case biColdTaiga: a_Min = 63; a_Max = 75; break;
case biColdTaigaHills: a_Min = 63; a_Max = 90; break;
case biColdTaigaM: a_Min = 63; a_Max = 75; break;
case biDeepOcean: a_Min = 30; a_Max = 60; break;
case biDesert: a_Min = 63; a_Max = 70; break;
case biDesertHills: a_Min = 63; a_Max = 85; break;
case biDesertM: a_Min = 63; a_Max = 70; break;
case biEnd: a_Min = 10; a_Max = 100; break;
case biExtremeHills: a_Min = 60; a_Max = 120; break;
case biExtremeHillsEdge: a_Min = 63; a_Max = 100; break;
case biExtremeHillsM: a_Min = 60; a_Max = 120; break;
case biExtremeHillsPlus: a_Min = 60; a_Max = 140; break;
case biExtremeHillsPlusM: a_Min = 60; a_Max = 140; break;
case biFlowerForest: a_Min = 63; a_Max = 75; break;
case biForest: a_Min = 63; a_Max = 75; break;
case biForestHills: a_Min = 63; a_Max = 90; break;
case biFrozenOcean: a_Min = 45; a_Max = 64; break;
case biFrozenRiver: a_Min = 60; a_Max = 62; break;
case biIceMountains: a_Min = 63; a_Max = 90; break;
case biIcePlains: a_Min = 63; a_Max = 70; break;
case biIcePlainsSpikes: a_Min = 60; a_Max = 70; break;
case biJungle: a_Min = 60; a_Max = 80; break;
case biJungleEdge: a_Min = 62; a_Max = 75; break;
case biJungleEdgeM: a_Min = 62; a_Max = 75; break;
case biJungleHills: a_Min = 60; a_Max = 90; break;
case biJungleM: a_Min = 60; a_Max = 75; break;
case biMegaSpruceTaiga: a_Min = 63; a_Max = 75; break;
case biMegaSpruceTaigaHills: a_Min = 63; a_Max = 90; break;
case biMegaTaiga: a_Min = 63; a_Max = 75; break;
case biMegaTaigaHills: a_Min = 63; a_Max = 90; break;
case biMesa: a_Min = 63; a_Max = 90; break;
case biMesaBryce: a_Min = 60; a_Max = 67; break;
case biMesaPlateau: a_Min = 75; a_Max = 85; break;
case biMesaPlateauF: a_Min = 80; a_Max = 90; break;
case biMesaPlateauFM: a_Min = 80; a_Max = 90; break;
case biMesaPlateauM: a_Min = 75; a_Max = 85; break;
case biMushroomIsland: a_Min = 63; a_Max = 90; break;
case biMushroomShore: a_Min = 60; a_Max = 75; break;
case biNether: a_Min = 10; a_Max = 100; break;
case biOcean: a_Min = 45; a_Max = 64; break;
case biPlains: a_Min = 63; a_Max = 70; break;
case biRiver: a_Min = 60; a_Max = 62; break;
case biRoofedForest: a_Min = 63; a_Max = 75; break;
case biRoofedForestM: a_Min = 63; a_Max = 75; break;
case biSavanna: a_Min = 63; a_Max = 75; break;
case biSavannaM: a_Min = 63; a_Max = 80; break;
case biSavannaPlateau: a_Min = 75; a_Max = 100; break;
case biSavannaPlateauM: a_Min = 80; a_Max = 160; break;
case biStoneBeach: a_Min = 60; a_Max = 64; break;
case biSunflowerPlains: a_Min = 63; a_Max = 70; break;
case biSwampland: a_Min = 60; a_Max = 67; break;
case biSwamplandM: a_Min = 61; a_Max = 67; break;
case biTaiga: a_Min = 63; a_Max = 75; break;
case biTaigaHills: a_Min = 63; a_Max = 90; break;
case biTaigaM: a_Min = 63; a_Max = 80; break;
default:
{
ASSERT(!"Unknown biome");
a_Min = 10;
a_Max = 10;
break;
}
}
}
};
////////////////////////////////////////////////////////////////////////////////
// cTerrainHeightGen:
cTerrainHeightGenPtr cTerrainHeightGen::CreateHeightGen(cIniFile & a_IniFile, cBiomeGenPtr a_BiomeGen, int a_Seed, bool & a_CacheOffByDefault)
{
AString HeightGenName = a_IniFile.GetValueSet("Generator", "HeightGen", "");
if (HeightGenName.empty())
{
LOGWARN("[Generator] HeightGen value not set in world.ini, using \"Biomal\".");
HeightGenName = "Biomal";
}
a_CacheOffByDefault = false;
cTerrainHeightGenPtr res;
if (NoCaseCompare(HeightGenName, "Flat") == 0)
{
res = std::make_shared<cHeiGenFlat>();
a_CacheOffByDefault = true; // We're generating faster than a cache would retrieve data
}
else if (NoCaseCompare(HeightGenName, "classic") == 0)
{
res = std::make_shared<cHeiGenClassic>(a_Seed);
}
else if (NoCaseCompare(HeightGenName, "DistortedHeightmap") == 0)
{
// Not a heightmap-based generator, but it used to be accessible via HeightGen, so we need to skip making the default out of it
// Return an empty pointer, the caller will create the proper generator:
return cTerrainHeightGenPtr();
}
else if (NoCaseCompare(HeightGenName, "End") == 0)
{
// Not a heightmap-based generator, but it used to be accessible via HeightGen, so we need to skip making the default out of it
// Return an empty pointer, the caller will create the proper generator:
return cTerrainHeightGenPtr();
}
else if (NoCaseCompare(HeightGenName, "MinMax") == 0)
{
res = std::make_shared<cHeiGenMinMax>(a_Seed, a_BiomeGen);
}
else if (NoCaseCompare(HeightGenName, "Mountains") == 0)
{
res = std::make_shared<cHeiGenMountains>(a_Seed);
}
else if (NoCaseCompare(HeightGenName, "BiomalNoise3D") == 0)
{
// Not a heightmap-based generator, but it used to be accessible via HeightGen, so we need to skip making the default out of it
// Return an empty pointer, the caller will create the proper generator:
return cTerrainHeightGenPtr();
}
else if (NoCaseCompare(HeightGenName, "Noise3D") == 0)
{
// Not a heightmap-based generator, but it used to be accessible via HeightGen, so we need to skip making the default out of it
// Return an empty pointer, the caller will create the proper generator:
return cTerrainHeightGenPtr();
}
else if (NoCaseCompare(HeightGenName, "Biomal") == 0)
{
res = std::make_shared<cHeiGenBiomal>(a_Seed, a_BiomeGen);
/*
// Performance-testing:
LOGINFO("Measuring performance of cHeiGenBiomal...");
clock_t BeginTick = clock();
for (int x = 0; x < 500; x++)
{
cChunkDef::HeightMap Heights;
res->GenHeightMap(x * 5, x * 5, Heights);
}
clock_t Duration = clock() - BeginTick;
LOGINFO("HeightGen for 500 chunks took %d ticks (%.02f sec)", Duration, (double)Duration / CLOCKS_PER_SEC);
//*/
}
else
{
// No match found, force-set the default and retry
LOGWARN("Unknown HeightGen \"%s\", using \"Biomal\" instead.", HeightGenName.c_str());
a_IniFile.SetValue("Generator", "HeightGen", "Biomal");
return CreateHeightGen(a_IniFile, a_BiomeGen, a_Seed, a_CacheOffByDefault);
}
// Read the settings:
res->InitializeHeightGen(a_IniFile);
return res;
}
| 40.136416
| 425
| 0.578518
|
planetx
|
61d6707cc833bbd6dfa8335f8eec7c9411842562
| 1,018
|
cpp
|
C++
|
libs/gui/src/gui/widget/preferred_size.cpp
|
cpreh/spacegameengine
|
313a1c34160b42a5135f8223ffaa3a31bc075a01
|
[
"BSL-1.0"
] | 2
|
2016-01-27T13:18:14.000Z
|
2018-05-11T01:11:32.000Z
|
libs/gui/src/gui/widget/preferred_size.cpp
|
cpreh/spacegameengine
|
313a1c34160b42a5135f8223ffaa3a31bc075a01
|
[
"BSL-1.0"
] | null | null | null |
libs/gui/src/gui/widget/preferred_size.cpp
|
cpreh/spacegameengine
|
313a1c34160b42a5135f8223ffaa3a31bc075a01
|
[
"BSL-1.0"
] | 3
|
2018-05-11T01:11:34.000Z
|
2021-04-24T19:47:45.000Z
|
// Copyright Carl Philipp Reh 2006 - 2019.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <sge/gui/widget/base.hpp>
#include <sge/gui/widget/dummy.hpp>
#include <sge/gui/widget/preferred_size.hpp>
#include <sge/rucksack/axis_policy.hpp>
#include <sge/rucksack/axis_policy2.hpp>
#include <sge/rucksack/dim.hpp>
#include <sge/rucksack/preferred_size.hpp>
#include <sge/rucksack/widget/base_fwd.hpp>
sge::gui::widget::preferred_size::preferred_size(sge::rucksack::dim const &_area)
: sge::gui::widget::dummy(),
layout_{sge::rucksack::axis_policy2{
sge::rucksack::axis_policy{sge::rucksack::preferred_size{_area.w()}},
sge::rucksack::axis_policy{sge::rucksack::preferred_size{_area.h()}}}}
{
}
sge::gui::widget::preferred_size::~preferred_size() = default;
sge::rucksack::widget::base &sge::gui::widget::preferred_size::layout() { return layout_; }
| 39.153846
| 91
| 0.714145
|
cpreh
|
61df96c924580d4f1c49c829e1ff9128d0a96631
| 6,019
|
cc
|
C++
|
table/two_level_iterator.cc
|
Meggie4/partnercompaction_for_read
|
6fdc54910fbb80ddfeefec7dfc83cef5f1e2e77f
|
[
"BSD-3-Clause"
] | null | null | null |
table/two_level_iterator.cc
|
Meggie4/partnercompaction_for_read
|
6fdc54910fbb80ddfeefec7dfc83cef5f1e2e77f
|
[
"BSD-3-Clause"
] | null | null | null |
table/two_level_iterator.cc
|
Meggie4/partnercompaction_for_read
|
6fdc54910fbb80ddfeefec7dfc83cef5f1e2e77f
|
[
"BSD-3-Clause"
] | null | null | null |
// 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 "table/two_level_iterator.h"
#include "leveldb/table.h"
#include "table/block.h"
#include "table/format.h"
#include "table/iterator_wrapper.h"
///////////meggie
#include "leveldb/comparator.h"
#include "db/dbformat.h"
///////////meggie
namespace leveldb {
namespace {
typedef Iterator* (*BlockFunction)(void*, const ReadOptions&, const Slice&);
class TwoLevelIterator: public Iterator {
public:
TwoLevelIterator(
Iterator* index_iter,
BlockFunction block_function,
void* arg,
const ReadOptions& options);
virtual ~TwoLevelIterator();
virtual void Seek(const Slice& target);
virtual void SeekToFirst();
virtual void SeekToLast();
virtual void Next();
virtual void Prev();
virtual bool Valid() const {
///////////////meggie
if(set_range_){
return Range_iter_valid();
}
///////////////meggie
else
return data_iter_.Valid();
}
virtual Slice key() const {
assert(Valid());
return data_iter_.key();
}
virtual Slice value() const {
assert(Valid());
return data_iter_.value();
}
virtual Status status() const {
// It'd be nice if status() returned a const Status& instead of a Status
if (!index_iter_.status().ok()) {
return index_iter_.status();
} else if (data_iter_.iter() != nullptr && !data_iter_.status().ok()) {
return data_iter_.status();
} else {
return status_;
}
}
//////////////////meggie
virtual void SetRange(Slice start, Slice end) {
set_range_ = true;
range_start_ = start;
range_end_ = end;
comparator_ = new InternalKeyComparator(BytewiseComparator());
}
//////////////////meggie
private:
void SaveError(const Status& s) {
if (status_.ok() && !s.ok()) status_ = s;
}
void SkipEmptyDataBlocksForward();
void SkipEmptyDataBlocksBackward();
void SetDataIterator(Iterator* data_iter);
void InitDataBlock();
BlockFunction block_function_;
void* arg_;
const ReadOptions options_;
Status status_;
IteratorWrapper index_iter_;
IteratorWrapper data_iter_; // May be nullptr
// If data_iter_ is non-null, then "data_block_handle_" holds the
// "index_value" passed to block_function_ to create the data_iter_.
std::string data_block_handle_;
////////////////meggie
bool set_range_;
Slice range_start_;
Slice range_end_;
InternalKeyComparator* comparator_;
bool Range_iter_valid() const;
////////////////meggie
};
TwoLevelIterator::TwoLevelIterator(
Iterator* index_iter,
BlockFunction block_function,
void* arg,
const ReadOptions& options)
: block_function_(block_function),
arg_(arg),
options_(options),
index_iter_(index_iter),
/////////////meggie
set_range_(false),
comparator_(nullptr),
/////////////meggie
data_iter_(nullptr)
{
}
TwoLevelIterator::~TwoLevelIterator() {
////////////////meggie
if(comparator_ != nullptr)
delete comparator_;
////////////////meggie
}
/////////////////meggie
bool TwoLevelIterator::Range_iter_valid() const {
if(!data_iter_.Valid())
return false;
Slice key = data_iter_.key();
if(comparator_->Compare(key, range_end_) <= 0)
return true;
else
return false;
}
/////////////////meggie
void TwoLevelIterator::Seek(const Slice& target) {
index_iter_.Seek(target);
InitDataBlock();
if (data_iter_.iter() != nullptr) data_iter_.Seek(target);
SkipEmptyDataBlocksForward();
}
void TwoLevelIterator::SeekToFirst() {
///////////////meggie
if(set_range_){
Seek(range_start_);
return;
}
///////////////meggie
index_iter_.SeekToFirst();
InitDataBlock();
if (data_iter_.iter() != nullptr) data_iter_.SeekToFirst();
SkipEmptyDataBlocksForward();
}
void TwoLevelIterator::SeekToLast() {
index_iter_.SeekToLast();
InitDataBlock();
if (data_iter_.iter() != nullptr) data_iter_.SeekToLast();
SkipEmptyDataBlocksBackward();
}
void TwoLevelIterator::Next() {
assert(Valid());
data_iter_.Next();
SkipEmptyDataBlocksForward();
}
void TwoLevelIterator::Prev() {
assert(Valid());
data_iter_.Prev();
SkipEmptyDataBlocksBackward();
}
void TwoLevelIterator::SkipEmptyDataBlocksForward() {
while (data_iter_.iter() == nullptr || !data_iter_.Valid()) {
// Move to next block
if (!index_iter_.Valid()) {
SetDataIterator(nullptr);
return;
}
index_iter_.Next();
InitDataBlock();
if (data_iter_.iter() != nullptr) data_iter_.SeekToFirst();
}
}
void TwoLevelIterator::SkipEmptyDataBlocksBackward() {
while (data_iter_.iter() == nullptr || !data_iter_.Valid()) {
// Move to next block
if (!index_iter_.Valid()) {
SetDataIterator(nullptr);
return;
}
index_iter_.Prev();
InitDataBlock();
if (data_iter_.iter() != nullptr) data_iter_.SeekToLast();
}
}
void TwoLevelIterator::SetDataIterator(Iterator* data_iter) {
if (data_iter_.iter() != nullptr) SaveError(data_iter_.status());
data_iter_.Set(data_iter);
}
void TwoLevelIterator::InitDataBlock() {
if (!index_iter_.Valid()) {
SetDataIterator(nullptr);
} else {
Slice handle = index_iter_.value();
if (data_iter_.iter() != nullptr && handle.compare(data_block_handle_) == 0) {
// data_iter_ is already constructed with this iterator, so
// no need to change anything
} else {
Iterator* iter = (*block_function_)(arg_, options_, handle);
data_block_handle_.assign(handle.data(), handle.size());
SetDataIterator(iter);
}
}
}
} // namespace
Iterator* NewTwoLevelIterator(
Iterator* index_iter,
BlockFunction block_function,
void* arg,
const ReadOptions& options) {
return new TwoLevelIterator(index_iter, block_function, arg, options);
}
} // namespace leveldb
| 25.396624
| 82
| 0.65775
|
Meggie4
|
61e8b10dd0a7007bef237495a4588bcdbca02ddc
| 10,392
|
cpp
|
C++
|
Code/Projects/Eldritch/src/Components/wbcompeldhealth.cpp
|
kas1e/Eldritch
|
032b4ac52f7508c89efa407d6fe60f40c6281fd9
|
[
"Zlib"
] | null | null | null |
Code/Projects/Eldritch/src/Components/wbcompeldhealth.cpp
|
kas1e/Eldritch
|
032b4ac52f7508c89efa407d6fe60f40c6281fd9
|
[
"Zlib"
] | null | null | null |
Code/Projects/Eldritch/src/Components/wbcompeldhealth.cpp
|
kas1e/Eldritch
|
032b4ac52f7508c89efa407d6fe60f40c6281fd9
|
[
"Zlib"
] | null | null | null |
#include "core.h"
#include "wbcompeldhealth.h"
#include "wbeventmanager.h"
#include "configmanager.h"
#include "idatastream.h"
#include "mathcore.h"
#include "eldritchgame.h"
#include "Components/wbcompstatmod.h"
WBCompEldHealth::WBCompEldHealth()
: m_Health(0),
m_MaxHealth(0),
m_InitialHealth(0),
m_PublishToHUD(false),
m_DamageTimeout(0.0f),
m_NextDamageTime(0.0f),
m_Invulnerable(false),
m_HidePickupScreenDelay(0.0f),
m_HidePickupScreenUID(0),
m_DefaultDamageMod(),
m_DamageTypeMods() {}
WBCompEldHealth::~WBCompEldHealth() {}
/*virtual*/ void WBCompEldHealth::InitializeFromDefinition(
const SimpleString& DefinitionName) {
Super::InitializeFromDefinition(DefinitionName);
MAKEHASH(DefinitionName);
STATICHASH(Health);
m_Health = ConfigManager::GetInheritedInt(sHealth, 0, sDefinitionName);
m_InitialHealth = m_Health;
STATICHASH(MaxHealth);
m_MaxHealth =
ConfigManager::GetInheritedInt(sMaxHealth, m_Health, sDefinitionName);
STATICHASH(PublishToHUD);
m_PublishToHUD =
ConfigManager::GetInheritedBool(sPublishToHUD, false, sDefinitionName);
STATICHASH(DamageTimeout);
m_DamageTimeout =
ConfigManager::GetInheritedFloat(sDamageTimeout, 0.0f, sDefinitionName);
STATICHASH(HidePickupScreenDelay);
m_HidePickupScreenDelay = ConfigManager::GetInheritedFloat(
sHidePickupScreenDelay, 0.0f, sDefinitionName);
STATICHASH(DefaultDamageModMul);
m_DefaultDamageMod.m_Multiply = ConfigManager::GetInheritedFloat(
sDefaultDamageModMul, 1.0f, sDefinitionName);
STATICHASH(DefaultDamageModAdd);
m_DefaultDamageMod.m_Add = ConfigManager::GetInheritedFloat(
sDefaultDamageModAdd, 0.0f, sDefinitionName);
STATICHASH(NumDamageTypeMods);
const uint NumDamageTypeMods =
ConfigManager::GetInheritedInt(sNumDamageTypeMods, 0, sDefinitionName);
for (uint DamageTypeModIndex = 0; DamageTypeModIndex < NumDamageTypeMods;
++DamageTypeModIndex) {
const HashedString DamageType = ConfigManager::GetInheritedSequenceHash(
"DamageTypeMod%dType", DamageTypeModIndex, HashedString::NullString,
sDefinitionName);
SDamageTypeMod& DamageTypeMod = m_DamageTypeMods[DamageType];
DamageTypeMod.m_Multiply = ConfigManager::GetInheritedSequenceFloat(
"DamageTypeMod%dMul", DamageTypeModIndex, 1.0f, sDefinitionName);
DamageTypeMod.m_Add = ConfigManager::GetInheritedSequenceFloat(
"DamageTypeMod%dAdd", DamageTypeModIndex, 0.0f, sDefinitionName);
}
}
/*virtual*/ void WBCompEldHealth::HandleEvent(const WBEvent& Event) {
XTRACE_FUNCTION;
Super::HandleEvent(Event);
STATIC_HASHED_STRING(TakeDamage);
STATIC_HASHED_STRING(GiveHealth);
STATIC_HASHED_STRING(RestoreHealth);
STATIC_HASHED_STRING(GiveMaxHealth);
STATIC_HASHED_STRING(SetInvulnerable);
STATIC_HASHED_STRING(SetVulnerable);
STATIC_HASHED_STRING(OnInitialized);
STATIC_HASHED_STRING(PushPersistence);
STATIC_HASHED_STRING(PullPersistence);
const HashedString EventName = Event.GetEventName();
if (EventName == sOnInitialized) {
if (m_PublishToHUD) {
PublishToHUD();
}
} else if (EventName == sTakeDamage) {
STATIC_HASHED_STRING(DamageAmount);
const int DamageAmount = Event.GetInt(sDamageAmount);
STATIC_HASHED_STRING(Damager);
WBEntity* const pDamager = Event.GetEntity(sDamager);
STATIC_HASHED_STRING(DamageType);
const HashedString DamageType = Event.GetHash(sDamageType);
TakeDamage(DamageAmount, pDamager, DamageType);
} else if (EventName == sGiveHealth) {
STATIC_HASHED_STRING(HealthAmount);
const int HealthAmount = Event.GetInt(sHealthAmount);
GiveHealth(HealthAmount);
} else if (EventName == sGiveMaxHealth) {
STATIC_HASHED_STRING(MaxHealthAmount);
const int MaxHealthAmount = Event.GetInt(sMaxHealthAmount);
STATIC_HASHED_STRING(HealthAmount);
const int HealthAmount = Event.GetInt(sHealthAmount);
GiveMaxHealth(MaxHealthAmount, HealthAmount);
} else if (EventName == sRestoreHealth) {
STATIC_HASHED_STRING(TargetHealth);
const int TargetHealth = Event.GetInt(sTargetHealth);
RestoreHealth(TargetHealth);
} else if (EventName == sSetInvulnerable) {
m_Invulnerable = true;
} else if (EventName == sSetVulnerable) {
m_Invulnerable = false;
} else if (EventName == sPushPersistence) {
PushPersistence();
} else if (EventName == sPullPersistence) {
PullPersistence();
}
}
/*virtual*/ void WBCompEldHealth::AddContextToEvent(WBEvent& Event) const {
Super::AddContextToEvent(Event);
WB_SET_CONTEXT(Event, Bool, IsAlive, IsAlive());
WB_SET_CONTEXT(Event, Bool, IsDead, IsDead());
}
void WBCompEldHealth::TakeDamage(const int DamageAmount,
WBEntity* const pDamager,
const HashedString& DamageType) {
XTRACE_FUNCTION;
if (m_Invulnerable) {
return;
}
const float CurrentTime = GetTime();
if (CurrentTime < m_NextDamageTime) {
return;
}
const int ModifiedDamageAmount = ModifyDamageAmount(DamageAmount, DamageType);
if (ModifiedDamageAmount <= 0) {
return;
}
// Send the event before subtracting health. This way, the event arrives
// while the entity is still alive, if this is the killing blow.
WB_MAKE_EVENT(OnDamaged, GetEntity());
WB_LOG_EVENT(OnDamaged);
WB_SET_AUTO(OnDamaged, Entity, Damager, pDamager);
WB_SET_AUTO(OnDamaged, Hash, DamageType, DamageType);
WB_DISPATCH_EVENT(GetEventManager(), OnDamaged, GetEntity());
const int PreviousHealth = m_Health;
m_Health -= ModifiedDamageAmount;
m_NextDamageTime = CurrentTime + m_DamageTimeout;
if (m_Health <= 0 && PreviousHealth > 0) {
WB_MAKE_EVENT(OnDied, GetEntity());
WB_LOG_EVENT(OnDied);
WB_SET_AUTO(OnDied, Entity, Killer, pDamager);
WB_DISPATCH_EVENT(GetEventManager(), OnDied, GetEntity());
}
if (m_PublishToHUD) {
PublishToHUD();
}
}
int WBCompEldHealth::ModifyDamageAmount(const int DamageAmount,
const HashedString& DamageType) {
const float fDamageAmount = static_cast<float>(DamageAmount);
float fModifiedDamageAmount = fDamageAmount;
Map<HashedString, SDamageTypeMod>::Iterator ModIter =
m_DamageTypeMods.Search(DamageType);
if (ModIter.IsValid()) {
const SDamageTypeMod& DamageTypeMod = ModIter.GetValue();
fModifiedDamageAmount = (fModifiedDamageAmount * DamageTypeMod.m_Multiply) +
DamageTypeMod.m_Add;
} else {
fModifiedDamageAmount =
(fModifiedDamageAmount * m_DefaultDamageMod.m_Multiply) +
m_DefaultDamageMod.m_Add;
}
WBCompStatMod* const pStatMod = GET_WBCOMP(GetEntity(), StatMod);
if (pStatMod) {
WB_MODIFY_FLOAT_SAFE(DamageTaken, fModifiedDamageAmount, pStatMod);
fModifiedDamageAmount = WB_MODDED(DamageTaken);
}
const int ModifiedDamageAmount = static_cast<int>(fModifiedDamageAmount);
return ModifiedDamageAmount;
}
void WBCompEldHealth::GiveHealth(const int HealthAmount) {
XTRACE_FUNCTION;
m_Health = Min(m_Health + HealthAmount, m_MaxHealth);
if (m_PublishToHUD) {
PublishToHUD();
}
// Show the health pickup screen and hide it after some time
STATICHASH(HealthPickup);
STATICHASH(Health);
ConfigManager::SetInt(sHealth, HealthAmount, sHealthPickup);
STATIC_HASHED_STRING(HealthPickupScreen);
{
WB_MAKE_EVENT(PushUIScreen, NULL);
WB_SET_AUTO(PushUIScreen, Hash, Screen, sHealthPickupScreen);
WB_DISPATCH_EVENT(GetEventManager(), PushUIScreen, NULL);
}
{
// Remove previously queued hide event if any
GetEventManager()->UnqueueEvent(m_HidePickupScreenUID);
WB_MAKE_EVENT(RemoveUIScreen, NULL);
WB_SET_AUTO(RemoveUIScreen, Hash, Screen, sHealthPickupScreen);
m_HidePickupScreenUID = WB_QUEUE_EVENT_DELAY(
GetEventManager(), RemoveUIScreen, NULL, m_HidePickupScreenDelay);
}
}
void WBCompEldHealth::GiveMaxHealth(const int MaxHealthAmount,
const int HealthAmount) {
m_MaxHealth += MaxHealthAmount;
GiveHealth(HealthAmount);
}
void WBCompEldHealth::RestoreHealth(const int TargetHealth) {
const int ActualTargetHealth =
(TargetHealth > 0) ? TargetHealth : m_InitialHealth;
m_Health = Max(ActualTargetHealth, m_Health);
if (m_PublishToHUD) {
PublishToHUD();
}
}
void WBCompEldHealth::PublishToHUD() const {
ASSERT(m_PublishToHUD);
STATICHASH(HUD);
STATICHASH(Health);
ConfigManager::SetInt(sHealth, Max(0, m_Health), sHUD);
STATICHASH(MaxHealth);
ConfigManager::SetInt(sMaxHealth, m_MaxHealth, sHUD);
}
void WBCompEldHealth::PushPersistence() const {
TPersistence& Persistence = EldritchGame::StaticGetTravelPersistence();
STATIC_HASHED_STRING(Health);
Persistence.SetInt(sHealth, m_Health);
STATIC_HASHED_STRING(MaxHealth);
Persistence.SetInt(sMaxHealth, m_MaxHealth);
}
void WBCompEldHealth::PullPersistence() {
TPersistence& Persistence = EldritchGame::StaticGetTravelPersistence();
STATIC_HASHED_STRING(Health);
m_Health = Persistence.GetInt(sHealth);
STATIC_HASHED_STRING(MaxHealth);
m_MaxHealth = Persistence.GetInt(sMaxHealth);
if (m_PublishToHUD) {
PublishToHUD();
}
}
#define VERSION_EMPTY 0
#define VERSION_HEALTH 1
#define VERSION_NEXTDAMAGETIME 2
#define VERSION_MAXHEALTH 3
#define VERSION_INVULNERABLE 4
#define VERSION_CURRENT 4
uint WBCompEldHealth::GetSerializationSize() {
uint Size = 0;
Size += 4; // Version
Size += 4; // m_Health
Size += 4; // m_NextDamageTime (as time remaining)
Size += 4; // m_MaxHealth
Size += 1; // m_Invulnerable
return Size;
}
void WBCompEldHealth::Save(const IDataStream& Stream) {
Stream.WriteUInt32(VERSION_CURRENT);
Stream.WriteInt32(m_Health);
Stream.WriteFloat(m_NextDamageTime - GetTime());
Stream.WriteInt32(m_MaxHealth);
Stream.WriteBool(m_Invulnerable);
}
void WBCompEldHealth::Load(const IDataStream& Stream) {
XTRACE_FUNCTION;
const uint Version = Stream.ReadUInt32();
if (Version >= VERSION_HEALTH) {
m_Health = Stream.ReadInt32();
}
if (Version >= VERSION_NEXTDAMAGETIME) {
m_NextDamageTime = GetTime() + Stream.ReadFloat();
}
if (Version >= VERSION_MAXHEALTH) {
m_MaxHealth = Stream.ReadInt32();
}
if (Version >= VERSION_INVULNERABLE) {
m_Invulnerable = Stream.ReadBool();
}
}
| 29.355932
| 80
| 0.734122
|
kas1e
|
61ec522c0e7c6d2e64c1a1a6b19461e2a3a1c665
| 3,543
|
hpp
|
C++
|
graphics/source/renderer/render_pass.hpp
|
HrvojeFER/irg-lab
|
53f27430d39fa099dd605cfd632e38b55a392699
|
[
"MIT"
] | null | null | null |
graphics/source/renderer/render_pass.hpp
|
HrvojeFER/irg-lab
|
53f27430d39fa099dd605cfd632e38b55a392699
|
[
"MIT"
] | null | null | null |
graphics/source/renderer/render_pass.hpp
|
HrvojeFER/irg-lab
|
53f27430d39fa099dd605cfd632e38b55a392699
|
[
"MIT"
] | null | null | null |
#ifndef IRGLAB_RENDER_PASS_HPP
#define IRGLAB_RENDER_PASS_HPP
#include "../external/pch.hpp"
#include "../environment/device.hpp"
#include "swapchain.hpp"
namespace il
{
struct render_pass
{
explicit render_pass(const device& device, const swapchain& swapchain) :
inner_{ create_inner(device, swapchain) } { }
[[nodiscard]] const vk::RenderPass& operator*() const
{
return *inner_;
}
void reconstruct(const device& device, const swapchain& swapchain)
{
inner_ = create_inner(device, swapchain);
}
private:
vk::UniqueRenderPass inner_;
[[nodiscard]] static vk::UniqueRenderPass create_inner(
const device& device,
const swapchain& swapchain)
{
std::vector<vk::AttachmentDescription> color_attachment_descriptions
{
vk::AttachmentDescription
{
{},
swapchain.get_configuration().format,
vk::SampleCountFlagBits::e1,
vk::AttachmentLoadOp::eClear,
vk::AttachmentStoreOp::eStore,
vk::AttachmentLoadOp::eDontCare,
vk::AttachmentStoreOp::eDontCare,
{},
vk::ImageLayout::ePresentSrcKHR
}
};
std::vector<vk::AttachmentReference> color_attachment_references
{
vk::AttachmentReference
{
0,
vk::ImageLayout::eColorAttachmentOptimal
}
};
std::vector<vk::SubpassDescription> subpass_descriptions
{
vk::SubpassDescription
{
{},
vk::PipelineBindPoint::eGraphics,
0,
nullptr,
static_cast<unsigned int>(color_attachment_references.size()),
color_attachment_references.data(),
nullptr,
nullptr,
0,
nullptr
}
};
std::vector<vk::SubpassDependency> subpass_dependencies
{
vk::SubpassDependency
{
VK_SUBPASS_EXTERNAL,
0,
vk::PipelineStageFlagBits::eColorAttachmentOutput,
vk::PipelineStageFlagBits::eColorAttachmentOutput,
{},
vk::AccessFlagBits::eColorAttachmentRead
| vk::AccessFlagBits::eColorAttachmentWrite,
{}
}
};
auto result = device->createRenderPassUnique(
{
{},
static_cast<unsigned int>(color_attachment_descriptions.size()),
color_attachment_descriptions.data(),
static_cast<unsigned int>(subpass_descriptions.size()),
subpass_descriptions.data(),
static_cast<unsigned int>(subpass_dependencies.size()),
subpass_dependencies.data()
});
#if !defined(NDEBUG)
std::cout << "Render pass created" << std::endl;
#endif
return result;
}
};
}
#endif
| 31.353982
| 85
| 0.47361
|
HrvojeFER
|
61ecd281e46e5a97614d2a2c6b29d582663768ca
| 781
|
cpp
|
C++
|
Leetcode Solution/Particular Patterns Question/Sliding Windows pattern/904. Fruit Into Baskets.cpp
|
bilwa496/Placement-Preparation
|
bd32ee717f671d95c17f524ed28b0179e0feb044
|
[
"MIT"
] | 169
|
2021-05-30T10:02:19.000Z
|
2022-03-27T18:09:32.000Z
|
Leetcode Solution/Particular Patterns Question/Sliding Windows pattern/904. Fruit Into Baskets.cpp
|
bilwa496/Placement-Preparation
|
bd32ee717f671d95c17f524ed28b0179e0feb044
|
[
"MIT"
] | 1
|
2021-10-02T14:46:26.000Z
|
2021-10-02T14:46:26.000Z
|
Leetcode Solution/Particular Patterns Question/Sliding Windows pattern/904. Fruit Into Baskets.cpp
|
bilwa496/Placement-Preparation
|
bd32ee717f671d95c17f524ed28b0179e0feb044
|
[
"MIT"
] | 44
|
2021-05-30T19:56:29.000Z
|
2022-03-17T14:49:00.000Z
|
class Solution {
public:
int totalFruit(vector<int>& t) {
int n=t.size();
int j=0;
int ans=0;
int count=0;
unordered_map<int,int> mp;
for(int i=0;i<t.size();i++)
{
mp[t[i]]++;
while(mp.size()>2 && j<n)
{
mp[t[j]]--;
if(mp[t[j]]==0)
{
mp.erase(t[j]);
}
j++;
}
ans = max(ans,i-j+1);
}
return ans;
}
};
| 23.666667
| 51
| 0.215109
|
bilwa496
|
61edebead0047f6b691c4e24ec8d108b257fb0c8
| 817
|
cpp
|
C++
|
Source/10.0.18362.0/ucrt/stdio/feoferr.cpp
|
825126369/UCRT
|
8853304fdc2a5c216658d08b6dbbe716aa2a7b1f
|
[
"MIT"
] | 2
|
2021-01-27T10:19:30.000Z
|
2021-02-09T06:24:30.000Z
|
Source/10.0.18362.0/ucrt/stdio/feoferr.cpp
|
825126369/UCRT
|
8853304fdc2a5c216658d08b6dbbe716aa2a7b1f
|
[
"MIT"
] | null | null | null |
Source/10.0.18362.0/ucrt/stdio/feoferr.cpp
|
825126369/UCRT
|
8853304fdc2a5c216658d08b6dbbe716aa2a7b1f
|
[
"MIT"
] | 1
|
2021-01-27T10:19:36.000Z
|
2021-01-27T10:19:36.000Z
|
//
// feoferr.cpp
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Defines feof() and ferror(), which test the end-of-file and error states of a
// stream, respectively.
//
#include <corecrt_internal_stdio.h>
// Tests the stream for the end-of-file condition. Returns nonzero if and only
// if the stream is at end-of-file.
extern "C" int __cdecl feof(FILE* const public_stream)
{
_VALIDATE_RETURN(public_stream != nullptr, EINVAL, 0);
return __crt_stdio_stream(public_stream).eof();
}
// Tests the stream error indicator. Returns nonzero if and only if the error
// indicator for the stream is set.
extern "C" int __cdecl ferror(FILE* const public_stream)
{
_VALIDATE_RETURN(public_stream != nullptr, EINVAL, 0);
return __crt_stdio_stream(public_stream).error();
}
| 27.233333
| 80
| 0.723378
|
825126369
|
61f44fe6d928e39b026252bcb9ee16e46ffa56dc
| 2,376
|
cc
|
C++
|
src/base/WCSimStackingAction.cc
|
chipsneutrino/chips-sim
|
19d3f2d75c674c06d2f27b9a344b70ca53e672c5
|
[
"MIT"
] | null | null | null |
src/base/WCSimStackingAction.cc
|
chipsneutrino/chips-sim
|
19d3f2d75c674c06d2f27b9a344b70ca53e672c5
|
[
"MIT"
] | null | null | null |
src/base/WCSimStackingAction.cc
|
chipsneutrino/chips-sim
|
19d3f2d75c674c06d2f27b9a344b70ca53e672c5
|
[
"MIT"
] | null | null | null |
#include "WCSimStackingAction.hh"
#include "WCSimDetectorConstruction.hh"
#include "G4Track.hh"
#include "G4TrackStatus.hh"
#include "G4VProcess.hh"
#include "G4VPhysicalVolume.hh"
#include "Randomize.hh"
#include "G4Navigator.hh"
#include "G4TransportationManager.hh"
#include "G4ParticleDefinition.hh"
#include "G4ParticleTypes.hh"
//class WCSimDetectorConstruction;
WCSimStackingAction::WCSimStackingAction(WCSimDetectorConstruction *myDet) : DetConstruct(myDet)
{
}
WCSimStackingAction::~WCSimStackingAction()
{
}
G4ClassificationOfNewTrack WCSimStackingAction::ClassifyNewTrack(const G4Track *aTrack)
{
G4ClassificationOfNewTrack classification = fWaiting;
G4ParticleDefinition *particleType = aTrack->GetDefinition();
// The following code implements the PMT quantum efficiency
// Make sure it is an optical photon
if (particleType == G4OpticalPhoton::OpticalPhotonDefinition())
{
G4float photonWavelength = (2.0 * M_PI * 197.3) / (aTrack->GetTotalEnergy() / CLHEP::eV);
G4float ratio = 1. / (1.0 - 0.25);
ratio = 1.0;
G4float wavelengthQE = 0;
if (aTrack->GetCreatorProcess() == NULL)
{
wavelengthQE = DetConstruct->GetPMTQE(photonWavelength, 1, 240, 660, ratio);
if (G4UniformRand() > wavelengthQE)
classification = fKill;
}
else if (((G4VProcess *)(aTrack->GetCreatorProcess()))->GetProcessType() != 3)
{
G4float photonWavelength = (2.0 * M_PI * 197.3) / (aTrack->GetTotalEnergy() / CLHEP::eV);
// MF : translated from skdetsim : better to increase the number of photons
// than to throw in a global factor at Digitization time !
G4float ratio = 1. / (1.0 - 0.25);
ratio = 1.0;
// XQ: get the maximum QE and multiply it by the ratio
// only work for the range between 240 nm and 660 nm for now
// Even with WLS
G4float wavelengthQE = 0;
if (DetConstruct->GetPMT_QE_Method() == 1)
{
wavelengthQE = DetConstruct->GetPMTQE(photonWavelength, 1, 240, 660, ratio);
}
else if (DetConstruct->GetPMT_QE_Method() == 2)
{
wavelengthQE = DetConstruct->GetPMTQE(photonWavelength, 0, 240, 660, ratio);
}
else if (DetConstruct->GetPMT_QE_Method() == 3)
{
wavelengthQE = 1.1;
}
if (G4UniformRand() > wavelengthQE)
classification = fKill;
}
}
return classification;
}
void WCSimStackingAction::NewStage()
{
;
}
void WCSimStackingAction::PrepareNewEvent()
{
;
}
| 28.626506
| 96
| 0.712963
|
chipsneutrino
|
61f5742cd088eaea2c5bf10cbd3f09b45feb2ca3
| 3,894
|
cpp
|
C++
|
PIXEL2D/Graphics/Window.cpp
|
Maxchii/PIXEL2D
|
ac1ce604e4f1b8448f14a4f92c69a2ff6d127f56
|
[
"Apache-2.0"
] | 1
|
2015-05-18T15:20:19.000Z
|
2015-05-18T15:20:19.000Z
|
PIXEL2D/Graphics/Window.cpp
|
Ossadtchii/PIXEL2D
|
ac1ce604e4f1b8448f14a4f92c69a2ff6d127f56
|
[
"Apache-2.0"
] | 5
|
2015-05-18T15:21:28.000Z
|
2015-06-28T12:43:52.000Z
|
PIXEL2D/Graphics/Window.cpp
|
Maxchii/PIXEL2D
|
ac1ce604e4f1b8448f14a4f92c69a2ff6d127f56
|
[
"Apache-2.0"
] | null | null | null |
#include "Window.h"
#include "..//Debugging/Debug.h"
namespace PIXL{ namespace graphics {
int Window::m_height;
int Window::m_width;
Window::Window(const std::string& windowHandle, int width, int height, UInt32 windowFlags /*= 0*/)
: m_windowHandle(windowHandle), m_windowFlags(windowFlags)
{
m_width = width;
m_height = height;
if (!Init()){
glfwTerminate();
debugging::Debug::LogError("Window.cpp", "Fatal Error! GLFW terminated!");
}
}
bool Window::Init()
{
if (!glfwInit()){
debugging::Debug::LogError("Window.cpp", "Failed to initialize GLFW!");
return false;
}
const GLFWvidmode* monitor = glfwGetVideoMode(glfwGetPrimaryMonitor());
bool fullscreen = false;
bool windowedFullscreen = false;
glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
if (m_windowFlags & RESIZABLE){
glfwWindowHint(GLFW_RESIZABLE, GL_TRUE);
}
if (m_windowFlags & FULLSCREEN){
m_window = glfwCreateWindow(m_width, m_height, m_windowHandle.c_str(), glfwGetPrimaryMonitor(), NULL);
fullscreen = true;
}
if (m_windowFlags & BORDERLESS){
m_width = monitor->width;
m_height = monitor->height;
glfwWindowHint(GLFW_DECORATED, GL_FALSE);
m_window = glfwCreateWindow(m_width, m_height, m_windowHandle.c_str(), NULL, NULL);
glfwSetWindowPos(m_window, 0, 0);
windowedFullscreen = true;
}
if (!fullscreen && !windowedFullscreen)
{
m_window = glfwCreateWindow(m_width, m_height, m_windowHandle.c_str(), NULL, NULL);
glfwSetWindowPos(m_window, monitor->width / 2 - m_width / 2, monitor->height / 2 - m_height / 2);
}
if (!m_window)
{
debugging::Debug::LogError("Window.cpp", "Failed to create GLFW Window!");
return false;
}
glfwMakeContextCurrent(m_window);
//glfwSetFramebufferSizeCallback(m_window, window_frame_buffer_size);
if (glewInit() != GLEW_OK)
{
debugging::Debug::LogError("Window.cpp", "Failed to initialize GLEW!");
return false;
}
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_TEXTURE_2D);
/*glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);*/
return true;
}
void Window::Clear() const
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
}
void Window::Update()
{
GLenum error = glGetError();
while (error != GL_NO_ERROR)
{
std::string errorString;
switch (error) {
case GL_INVALID_OPERATION:
errorString = "INVALID_OPERATION";
break;
case GL_INVALID_ENUM:
errorString = "INVALID_ENUM";
break;
case GL_INVALID_VALUE:
errorString = "INVALID_VALUE";
break;
case GL_OUT_OF_MEMORY:
errorString = "OUT_OF_MEMORY";
break;
case GL_INVALID_FRAMEBUFFER_OPERATION:
errorString = "INVALID_FRAMEBUFFER_OPERATION";
break;
default:
break;
}
std::string fullErrorMessage = "OpenGL Error: ";
fullErrorMessage.append(errorString.c_str());
debugging::Debug::LogError(nullptr, fullErrorMessage.c_str());
error = glGetError();
}
glfwSwapBuffers(m_window);
glfwPollEvents();
}
bool Window::Closed() const
{
return glfwWindowShouldClose(m_window) == 1;
}
void Window::EnableVsync(bool state)
{
glfwSwapInterval(state);
}
void Window::SetWindowName(const std::string& newName)
{
glfwSetWindowTitle(m_window, newName.c_str());
m_windowHandle = newName;
}
void Window::SetWindowFlags(unsigned int windowFlags)
{
glfwDestroyWindow(m_window);
m_windowFlags = windowFlags;
if (!Init()){
glfwTerminate();
debugging::Debug::LogError("Window.cpp", "Fatal Error! GLFW terminated!");
}
}
Window::~Window()
{
glfwTerminate();
}
GLFWwindow* Window::m_window;
/*
void window_frame_buffer_size(GLFWwindow* window, int width, int height)
{
glViewport(0, 0, width, height);
Window* win = (Window*)glfwGetWindowUserPointer(window);
win->m_width = width;
win->m_height = height;
}*/
}
}
| 23.317365
| 105
| 0.701079
|
Maxchii
|
61fad223167c48716cb174bd73e32873916dbe2c
| 803
|
cpp
|
C++
|
src/system/event_loop.cpp
|
thknepper/CPPurses
|
4f35ba5284bc5ac563214f73f494bd75fd5bf73b
|
[
"MIT"
] | 1
|
2020-02-22T21:18:11.000Z
|
2020-02-22T21:18:11.000Z
|
src/system/event_loop.cpp
|
thknepper/CPPurses
|
4f35ba5284bc5ac563214f73f494bd75fd5bf73b
|
[
"MIT"
] | null | null | null |
src/system/event_loop.cpp
|
thknepper/CPPurses
|
4f35ba5284bc5ac563214f73f494bd75fd5bf73b
|
[
"MIT"
] | null | null | null |
#include <cppurses/system/event_loop.hpp>
#include <cppurses/system/detail/event_engine.hpp>
#include <cppurses/system/system.hpp>
namespace cppurses {
auto Event_loop::run() -> int
{
if (running_)
return -1;
running_ = true;
auto notify = true;
while (not exit_) {
if (notify)
detail::Event_engine::get().notify();
if (is_main_thread_)
detail::Event_engine::get().process();
notify = this->loop_function();
}
running_ = false;
exit_ = false;
return return_code_;
}
void Event_loop::connect_to_system_exit()
{
auto exit_loop =
sig::Slot<void(int)>{[this](int code) { this->exit(code); }};
exit_loop.track(lifetime_);
System::exit_signal.connect(exit_loop);
}
} // namespace cppurses
| 22.942857
| 69
| 0.625156
|
thknepper
|
61fc93dd7531c03aef7a64a043afd04eba1c3172
| 10,816
|
cpp
|
C++
|
third_party/assimp-5.0.1/test/unit/utValidateDataStructure.cpp
|
hporro/grafica_cpp
|
1427bb6e8926b44be474b906e9f52cca77b3df9d
|
[
"MIT"
] | 158
|
2016-11-17T19:37:51.000Z
|
2022-03-21T19:57:55.000Z
|
third_party/assimp-5.0.1/test/unit/utValidateDataStructure.cpp
|
hporro/grafica_cpp
|
1427bb6e8926b44be474b906e9f52cca77b3df9d
|
[
"MIT"
] | 94
|
2016-11-18T09:55:57.000Z
|
2021-01-14T08:50:40.000Z
|
third_party/assimp-5.0.1/test/unit/utValidateDataStructure.cpp
|
hporro/grafica_cpp
|
1427bb6e8926b44be474b906e9f52cca77b3df9d
|
[
"MIT"
] | 51
|
2017-05-24T10:20:25.000Z
|
2022-03-17T15:07:02.000Z
|
/*
---------------------------------------------------------------------------
Open Asset Import Library (assimp)
---------------------------------------------------------------------------
Copyright (c) 2006-2019, assimp team
All rights reserved.
Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the following
conditions are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
* Neither the name of the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
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 "UnitTestPCH.h"
#include <assimp/mesh.h>
#include <assimp/scene.h>
#include <ValidateDataStructure.h>
using namespace std;
using namespace Assimp;
class ValidateDataStructureTest : public ::testing::Test
{
public:
virtual void SetUp();
virtual void TearDown();
protected:
ValidateDSProcess* vds;
aiScene* scene;
};
// ------------------------------------------------------------------------------------------------
void ValidateDataStructureTest::SetUp()
{
// setup a dummy scene with a single node
scene = new aiScene();
scene->mRootNode = new aiNode();
scene->mRootNode->mName.Set("<test>");
// add some translation
scene->mRootNode->mTransformation.a4 = 1.f;
scene->mRootNode->mTransformation.b4 = 2.f;
scene->mRootNode->mTransformation.c4 = 3.f;
// and allocate a ScenePreprocessor to operate on the scene
vds = new ValidateDSProcess();
}
// ------------------------------------------------------------------------------------------------
void ValidateDataStructureTest::TearDown()
{
delete vds;
delete scene;
}
// ------------------------------------------------------------------------------------------------
//Template
//TEST_F(ScenePreprocessorTest, test)
//{
//}
// TODO Conditions not yet checked:
//132: ReportError("aiScene::%s is NULL (aiScene::%s is %i)",
//139: ReportError("aiScene::%s[%i] is NULL (aiScene::%s is %i)",
//156: ReportError("aiScene::%s is NULL (aiScene::%s is %i)",
//163: ReportError("aiScene::%s[%i] is NULL (aiScene::%s is %i)",
//173: ReportError("aiScene::%s[%i] has the same name as "
//192: ReportError("aiScene::%s[%i] has no corresponding node in the scene graph (%s)",
//196: ReportError("aiScene::%s[%i]: there are more than one nodes with %s as name",
//217: ReportError("aiScene::mNumMeshes is 0. At least one mesh must be there");
//220: ReportError("aiScene::mMeshes is non-null although there are no meshes");
//229: ReportError("aiScene::mAnimations is non-null although there are no animations");
//238: ReportError("aiScene::mCameras is non-null although there are no cameras");
//247: ReportError("aiScene::mLights is non-null although there are no lights");
//256: ReportError("aiScene::mTextures is non-null although there are no textures");
//266: ReportError("aiScene::mNumMaterials is 0. At least one material must be there");
//270: ReportError("aiScene::mMaterials is non-null although there are no materials");
//281: ReportWarning("aiLight::mType is aiLightSource_UNDEFINED");
//286: ReportWarning("aiLight::mAttenuationXXX - all are zero");
//290: ReportError("aiLight::mAngleInnerCone is larger than aiLight::mAngleOuterCone");
//295: ReportWarning("aiLight::mColorXXX - all are black and won't have any influence");
//303: ReportError("aiCamera::mClipPlaneFar must be >= aiCamera::mClipPlaneNear");
//308: ReportWarning("%f is not a valid value for aiCamera::mHorizontalFOV",pCamera->mHorizontalFOV);
//317: ReportError("aiMesh::mMaterialIndex is invalid (value: %i maximum: %i)",
//332: ReportError("aiMesh::mFaces[%i].mNumIndices is 0",i);
//336: ReportError("aiMesh::mFaces[%i] is a POINT but aiMesh::mPrimitiveTypes "
//337: "does not report the POINT flag",i);
//343: ReportError("aiMesh::mFaces[%i] is a LINE but aiMesh::mPrimitiveTypes "
//344: "does not report the LINE flag",i);
//350: ReportError("aiMesh::mFaces[%i] is a TRIANGLE but aiMesh::mPrimitiveTypes "
//351: "does not report the TRIANGLE flag",i);
//357: this->ReportError("aiMesh::mFaces[%i] is a POLYGON but aiMesh::mPrimitiveTypes "
//358: "does not report the POLYGON flag",i);
//365: ReportError("aiMesh::mFaces[%i].mIndices is NULL",i);
//370: ReportError("The mesh %s contains no vertices", pMesh->mName.C_Str());
//374: ReportError("Mesh has too many vertices: %u, but the limit is %u",pMesh->mNumVertices,AI_MAX_VERTICES);
//377: ReportError("Mesh has too many faces: %u, but the limit is %u",pMesh->mNumFaces,AI_MAX_FACES);
//382: ReportError("If there are tangents, bitangent vectors must be present as well");
//387: ReportError("Mesh %s contains no faces", pMesh->mName.C_Str());
//398: ReportError("Face %u has too many faces: %u, but the limit is %u",i,face.mNumIndices,AI_MAX_FACE_INDICES);
//404: ReportError("aiMesh::mFaces[%i]::mIndices[%i] is out of range",i,a);
//412: ReportError("aiMesh::mVertices[%i] is referenced twice - second "
//426: ReportWarning("There are unreferenced vertices");
//439: ReportError("Texture coordinate channel %i exists "
//453: ReportError("Vertex color channel %i is exists "
//464: ReportError("aiMesh::mBones is NULL (aiMesh::mNumBones is %i)",
//480: ReportError("Bone %u has too many weights: %u, but the limit is %u",i,bone->mNumWeights,AI_MAX_BONE_WEIGHTS);
//485: ReportError("aiMesh::mBones[%i] is NULL (aiMesh::mNumBones is %i)",
//498: ReportError("aiMesh::mBones[%i], name = \"%s\" has the same name as "
//507: ReportWarning("aiMesh::mVertices[%i]: bone weight sum != 1.0 (sum is %f)",i,afSum[i]);
//513: ReportError("aiMesh::mBones is non-null although there are no bones");
//524: ReportError("aiBone::mNumWeights is zero");
//531: ReportError("aiBone::mWeights[%i].mVertexId is out of range",i);
//534: ReportWarning("aiBone::mWeights[%i].mWeight has an invalid value",i);
//549: ReportError("aiAnimation::mChannels is NULL (aiAnimation::mNumChannels is %i)",
//556: ReportError("aiAnimation::mChannels[%i] is NULL (aiAnimation::mNumChannels is %i)",
//563: ReportError("aiAnimation::mNumChannels is 0. At least one node animation channel must be there.");
//567: // if (!pAnimation->mDuration)this->ReportError("aiAnimation::mDuration is zero");
//592: ReportError("Material property %s is expected to be a string",prop->mKey.data);
//596: ReportError("%s #%i is set, but there are only %i %s textures",
//611: ReportError("Found texture property with index %i, although there "
//619: ReportError("Material property %s%i is expected to be an integer (size is %i)",
//627: ReportError("Material property %s%i is expected to be 5 floats large (size is %i)",
//635: ReportError("Material property %s%i is expected to be an integer (size is %i)",
//656: ReportWarning("Invalid UV index: %i (key %s). Mesh %i has only %i UV channels",
//676: ReportWarning("UV-mapped texture, but there are no UV coords");
//690: ReportError("aiMaterial::mProperties[%i] is NULL (aiMaterial::mNumProperties is %i)",
//694: ReportError("aiMaterial::mProperties[%i].mDataLength or "
//702: ReportError("aiMaterial::mProperties[%i].mDataLength is "
//707: ReportError("Missing null-terminator in string material property");
//713: ReportError("aiMaterial::mProperties[%i].mDataLength is "
//720: ReportError("aiMaterial::mProperties[%i].mDataLength is "
//739: ReportWarning("A specular shading model is specified but there is no "
//743: ReportWarning("A specular shading model is specified but the value of the "
//752: ReportWarning("Invalid opacity value (must be 0 < opacity < 1.0)");
//776: ReportError("aiTexture::pcData is NULL");
//781: ReportError("aiTexture::mWidth is zero (aiTexture::mHeight is %i, uncompressed texture)",
//788: ReportError("aiTexture::mWidth is zero (compressed texture)");
//791: ReportWarning("aiTexture::achFormatHint must be zero-terminated");
//794: ReportWarning("aiTexture::achFormatHint should contain a file extension "
//804: ReportError("aiTexture::achFormatHint contains non-lowercase letters");
//815: ReportError("Empty node animation channel");
//822: ReportError("aiNodeAnim::mPositionKeys is NULL (aiNodeAnim::mNumPositionKeys is %i)",
//833: ReportError("aiNodeAnim::mPositionKeys[%i].mTime (%.5f) is larger "
//840: ReportWarning("aiNodeAnim::mPositionKeys[%i].mTime (%.5f) is smaller "
//853: ReportError("aiNodeAnim::mRotationKeys is NULL (aiNodeAnim::mNumRotationKeys is %i)",
//861: ReportError("aiNodeAnim::mRotationKeys[%i].mTime (%.5f) is larger "
//868: ReportWarning("aiNodeAnim::mRotationKeys[%i].mTime (%.5f) is smaller "
//880: ReportError("aiNodeAnim::mScalingKeys is NULL (aiNodeAnim::mNumScalingKeys is %i)",
//888: ReportError("aiNodeAnim::mScalingKeys[%i].mTime (%.5f) is larger "
//895: ReportWarning("aiNodeAnim::mScalingKeys[%i].mTime (%.5f) is smaller "
//907: ReportError("A node animation channel must have at least one subtrack");
//915: ReportError("A node of the scenegraph is NULL");
//920: ReportError("Non-root node %s lacks a valid parent (aiNode::mParent is NULL) ",pNode->mName);
//928: ReportError("aiNode::mMeshes is NULL for node %s (aiNode::mNumMeshes is %i)",
//937: ReportError("aiNode::mMeshes[%i] is out of range for node %s (maximum is %i)",
//942: ReportError("aiNode::mMeshes[%i] is already referenced by this node %s (value: %i)",
//951: ReportError("aiNode::mChildren is NULL for node %s (aiNode::mNumChildren is %i)",
//965: ReportError("aiString::length is too large (%i, maximum is %lu)",
//974: ReportError("aiString::data is invalid: the terminal zero is at a wrong offset");
//979: ReportError("aiString::data is invalid. There is no terminal character");
}
| 54.08
| 116
| 0.699982
|
hporro
|
1100a400b314af4bb9223441827d9deb33da4d06
| 4,495
|
cpp
|
C++
|
src/protocols/bdx/TransferFacilitator.cpp
|
lzgrablic02/connectedhomeip
|
1581c6d9e22b07a9233392a183f5cacae50378ac
|
[
"Apache-2.0"
] | 4
|
2020-09-11T04:32:44.000Z
|
2022-03-11T09:06:07.000Z
|
src/protocols/bdx/TransferFacilitator.cpp
|
kvikrambhat/connectedhomeip
|
56f738f0725f6b4a425806293f35f6d51fe8eb52
|
[
"Apache-2.0"
] | null | null | null |
src/protocols/bdx/TransferFacilitator.cpp
|
kvikrambhat/connectedhomeip
|
56f738f0725f6b4a425806293f35f6d51fe8eb52
|
[
"Apache-2.0"
] | null | null | null |
/*
*
* Copyright (c) 2021 Project CHIP Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "TransferFacilitator.h"
#include <lib/core/CHIPError.h>
#include <lib/support/BitFlags.h>
#include <messaging/ExchangeContext.h>
#include <messaging/ExchangeDelegate.h>
#include <platform/CHIPDeviceLayer.h>
#include <protocols/bdx/BdxTransferSession.h>
#include <system/SystemClock.h>
#include <system/SystemLayer.h>
namespace chip {
namespace bdx {
constexpr System::Clock::Timeout TransferFacilitator::kDefaultPollFreq;
constexpr System::Clock::Timeout TransferFacilitator::kImmediatePollDelay;
CHIP_ERROR TransferFacilitator::OnMessageReceived(chip::Messaging::ExchangeContext * ec, const chip::PayloadHeader & payloadHeader,
chip::System::PacketBufferHandle && payload)
{
if (mExchangeCtx == nullptr)
{
mExchangeCtx = ec;
}
ChipLogDetail(BDX, "%s: message " ChipLogFormatMessageType " protocol " ChipLogFormatProtocolId, __FUNCTION__,
payloadHeader.GetMessageType(), ChipLogValueProtocolId(payloadHeader.GetProtocolID()));
CHIP_ERROR err = mTransfer.HandleMessageReceived(payloadHeader, std::move(payload));
if (err != CHIP_NO_ERROR)
{
ChipLogError(BDX, "failed to handle message: %s", ErrorStr(err));
}
// Almost every BDX message will follow up with a response on the exchange. Even messages that might signify the end of a
// transfer could necessitate a response if they are received at the wrong time.
// For this reason, it is left up to the application logic to call ExchangeContext::Close() when it has determined that the
// transfer is finished.
mExchangeCtx->WillSendMessage();
return err;
}
void TransferFacilitator::OnResponseTimeout(Messaging::ExchangeContext * ec)
{
ChipLogError(BDX, "%s, ec: " ChipLogFormatExchange, __FUNCTION__, ChipLogValueExchange(ec));
mExchangeCtx = nullptr;
mTransfer.Reset();
}
void TransferFacilitator::PollTimerHandler(chip::System::Layer * systemLayer, void * appState)
{
VerifyOrReturn(appState != nullptr);
static_cast<TransferFacilitator *>(appState)->PollForOutput();
}
void TransferFacilitator::PollForOutput()
{
TransferSession::OutputEvent outEvent;
mTransfer.PollOutput(outEvent);
HandleTransferSessionOutput(outEvent);
VerifyOrReturn(mSystemLayer != nullptr, ChipLogError(BDX, "%s mSystemLayer is null", __FUNCTION__));
mSystemLayer->StartTimer(mPollFreq, PollTimerHandler, this);
}
void TransferFacilitator::ScheduleImmediatePoll()
{
VerifyOrReturn(mSystemLayer != nullptr, ChipLogError(BDX, "%s mSystemLayer is null", __FUNCTION__));
mSystemLayer->StartTimer(System::Clock::Milliseconds32(kImmediatePollDelay), PollTimerHandler, this);
}
CHIP_ERROR Responder::PrepareForTransfer(System::Layer * layer, TransferRole role, BitFlags<TransferControlFlags> xferControlOpts,
uint16_t maxBlockSize, System::Clock::Timeout timeout, System::Clock::Timeout pollFreq)
{
VerifyOrReturnError(layer != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
mPollFreq = pollFreq;
mSystemLayer = layer;
ReturnErrorOnFailure(mTransfer.WaitForTransfer(role, xferControlOpts, maxBlockSize));
mSystemLayer->StartTimer(mPollFreq, PollTimerHandler, this);
return CHIP_NO_ERROR;
}
CHIP_ERROR Initiator::InitiateTransfer(System::Layer * layer, TransferRole role, const TransferSession::TransferInitData & initData,
System::Clock::Timeout timeout, System::Clock::Timeout pollFreq)
{
VerifyOrReturnError(layer != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
mPollFreq = pollFreq;
mSystemLayer = layer;
ReturnErrorOnFailure(mTransfer.StartTransfer(role, initData));
mSystemLayer->StartTimer(mPollFreq, PollTimerHandler, this);
return CHIP_NO_ERROR;
}
} // namespace bdx
} // namespace chip
| 37.773109
| 132
| 0.729032
|
lzgrablic02
|
1101986808b09debe5addb9e69e4028b85bf490d
| 3,191
|
cpp
|
C++
|
src/Communication/Server.cpp
|
einerfreiheit/RemoteRunnerd
|
424a2f78c4cb6afb6c089f5dff885dac50decd27
|
[
"MIT"
] | null | null | null |
src/Communication/Server.cpp
|
einerfreiheit/RemoteRunnerd
|
424a2f78c4cb6afb6c089f5dff885dac50decd27
|
[
"MIT"
] | 4
|
2021-03-29T08:03:18.000Z
|
2021-06-20T13:06:38.000Z
|
src/Communication/Server.cpp
|
einerfreiheit/RemoteRunnerd
|
424a2f78c4cb6afb6c089f5dff885dac50decd27
|
[
"MIT"
] | 1
|
2020-06-03T08:44:35.000Z
|
2020-06-03T08:44:35.000Z
|
#include "Configuration.hpp"
#include "Permissions.hpp"
#include "Server.hpp"
#include "Session.hpp"
#include "Endpoint/EndpointFactory.hpp"
#include "Endpoint/IEndpoint.hpp"
#include "Task/RemoteTask.hpp"
#include "Task/TaskRunner.hpp"
#include "Utils/TextProcessing.hpp"
#include "Utils/Utils.hpp"
#include <csignal>
#include <cstring>
#include <iostream>
#include <sys/socket.h>
#include <unistd.h>
namespace remote_runnerd {
namespace {
struct SignalContext {
std::condition_variable cv;
std::mutex mtx;
bool state{false};
} ctx;
constexpr int MAX_CONNECTIONS = 100;
} // namespace
void signalHander(int) {
std::unique_lock<std::mutex>(ctx.mtx);
ctx.state = true;
ctx.cv.notify_one();
}
Server::Server(const Configuration& configuration) : timeout_(configuration.getTimeout()) {
permissions_ = std::make_unique<Permissions>(configuration.getInstructions());
runner_ = std::make_unique<TaskRunner>();
endpoint_ = EndpointFactory().make(configuration.getProptocol(), configuration.getAddress());
signal(SIGHUP, signalHander);
}
void Server::start() {
permissions_->update();
init();
while (true) {
socklen_t peer_addr_size;
auto peer_endpoint = endpoint_->create();
int acc = ::accept(socket_, peer_endpoint->get(), &peer_addr_size);
checkError(acc, "Failed to accept connection: ");
std::string info = peer_endpoint->describe();
std::cout << "New client: " << info << std::endl;
try {
handle(acc);
} catch (const std::runtime_error& e) {
std::cerr << "Failed to execute commands for " << info << ", reason: " << e.what()
<< std::endl;
}
}
}
void Server::init() {
std::cout << "Starting on " << endpoint_->describe() << std::endl;
socket_ = socket(endpoint_->get()->sa_family, SOCK_STREAM, 0);
checkError(socket_, "Failed to create socket");
checkError(bind(socket_, endpoint_->get(), endpoint_->size()), "Failed to bind socket");
checkError(listen(socket_, MAX_CONNECTIONS), "Failed to start to listen");
signal_thread_ = std::thread([this]() {
while (true) {
std::unique_lock<std::mutex> lock(ctx.mtx);
ctx.cv.wait(lock, [this] { return stop_flag_ || ctx.state; });
if (stop_flag_) {
break;
}
if (ctx.state) {
permissions_->update();
ctx.state = false;
}
}
});
}
void Server::handle(int fd) {
std::function<void()> func = [this, fd]() {
Session session(fd);
auto message = session.read();
if (!permissions_->isAllowed(message)) {
session.write("Failed to execute task: operation is not permitted\n");
return;
}
RemoteTask task;
task.execute(message, timeout_, session);
};
runner_->add(std::move(func));
}
Server::~Server() {
{
std::lock_guard<std::mutex> lock(ctx.mtx);
stop_flag_ = true;
ctx.cv.notify_one();
}
if (signal_thread_.joinable()) {
signal_thread_.join();
}
}
} // namespace remote_runnerd
| 28.491071
| 97
| 0.6089
|
einerfreiheit
|
1104f78b37c525c52c70c4a4a9e2aa677fc61891
| 7,883
|
cpp
|
C++
|
src/queries.cpp
|
jermp/rdf_indexes
|
927139cad57c28eb8cbdbea5591e556e19abc8d5
|
[
"MIT"
] | 6
|
2019-10-20T02:44:10.000Z
|
2021-12-22T11:57:26.000Z
|
src/queries.cpp
|
jermp/rdf_indexes
|
927139cad57c28eb8cbdbea5591e556e19abc8d5
|
[
"MIT"
] | 2
|
2020-03-09T12:05:56.000Z
|
2021-06-27T21:48:38.000Z
|
src/queries.cpp
|
jermp/rdf_indexes
|
927139cad57c28eb8cbdbea5591e556e19abc8d5
|
[
"MIT"
] | 2
|
2020-07-21T16:59:42.000Z
|
2021-06-27T23:35:20.000Z
|
#include <iostream>
#include "../external/essentials/include/essentials.hpp"
#include "types.hpp"
#include "util.hpp"
#include "util_types.hpp"
using namespace rdf;
uint32_t num_runs(uint32_t runs, uint32_t n) {
static const uint32_t N = 10000;
uint32_t r = 1;
if (n * runs < N) {
r = N / n;
}
return r;
}
template <typename Index>
void queries(char const* binary_filename, char const* query_filename, int perm,
uint32_t runs, uint64_t num_queries, uint64_t num_wildcards,
bool all) {
Index index;
essentials::load(index, binary_filename);
// essentials::print_size(index);
essentials::timer_type t;
uint64_t num_triples = 0;
double elapsed = 0.0;
if (all) {
util::logger("returning all triplets");
num_queries = 1;
for (uint64_t run = 0; run != runs; ++run) {
num_triples = 0;
auto query_it = index.select_all();
t.start();
while (query_it.has_next()) {
auto t = *query_it;
essentials::do_not_optimize_away(t.first);
++num_triples;
++query_it;
}
t.stop();
}
elapsed = t.average();
} else {
util::logger("loading queries");
std::vector<triplet> queries;
queries.reserve(num_queries);
{
std::ifstream input(query_filename, std::ios_base::in);
triplets_iterator input_it(input);
for (uint64_t i = 0; i != num_queries; ++i) {
if (!input_it.has_next()) {
break;
}
auto q = *input_it;
if (perm == permutation_type::spo) {
if (num_wildcards == 1) {
q.third = global::wildcard_symbol;
} else if (num_wildcards == 2) {
q.second = global::wildcard_symbol;
q.third = global::wildcard_symbol;
}
} else if (perm == permutation_type::pos) {
if (num_wildcards == 1) {
q.first = global::wildcard_symbol;
} else if (num_wildcards == 2) {
q.first = global::wildcard_symbol;
q.third = global::wildcard_symbol;
}
} else if (perm == permutation_type::osp) {
if (num_wildcards == 1) {
q.second = global::wildcard_symbol;
} else if (num_wildcards == 2) {
q.first = global::wildcard_symbol;
q.second = global::wildcard_symbol;
}
}
queries.push_back(q);
++input_it;
}
input.close();
util::logger("loaded " + std::to_string(queries.size()) +
" queries");
}
assert(num_queries == queries.size());
util::logger("running queries");
if (num_wildcards == 0) {
for (uint64_t run = 0; run != runs; ++run) {
num_triples = num_queries;
t.start();
for (auto query : queries) {
essentials::do_not_optimize_away(index.is_member(query));
}
t.stop();
}
elapsed = t.average();
} else {
// for (uint64_t run = 0; run != runs; ++run) {
// num_triples = 0;
// t.start();
// for (auto query : queries) {
// auto query_it = index.select(query);
// while (query_it.has_next()) {
// auto t = *query_it;
// essentials::do_not_optimize_away(t.first);
// ++num_triples;
// ++query_it;
// }
// }
// t.stop();
// }
for (auto query : queries) {
uint64_t n = 0;
{
auto query_it = index.select(query);
while (query_it.has_next()) {
auto t = *query_it;
essentials::do_not_optimize_away(t.first);
++n;
++query_it;
}
}
uint32_t r = num_runs(runs, n);
t.start();
for (uint32_t run = 0; run != r; ++run) {
auto query_it = index.select(query);
while (query_it.has_next()) {
auto t = *query_it;
essentials::do_not_optimize_away(t.first);
++query_it;
}
}
t.stop();
double avg_per_query = t.elapsed() / r;
t.reset();
elapsed += avg_per_query;
num_triples += n;
}
}
}
double musecs_per_query = elapsed / num_queries;
double nanosecs_per_triplet = elapsed / num_triples * 1000;
std::cout << "\tReturned triples: " << num_triples << "\n";
std::cout << "\tMean per query: " << musecs_per_query << " [musec]\n ";
std::cout << "\tMean per triple: " << nanosecs_per_triplet << " [ns]";
std::cout << std::endl;
}
int main(int argc, char** argv) {
int mandatory = 4;
if (argc < mandatory) {
std::cout << argv[0]
<< " <type> <perm> <index_filename> [-q <query_filename> -n "
"<num_queries> -w <num_wildcards>]"
<< std::endl;
return 1;
}
bool all = true;
std::string type(argv[1]);
int perm = std::stoi(argv[2]);
char const* index_filename = argv[3];
char const* query_filename = nullptr;
uint64_t num_queries = 0;
uint64_t num_wildcards = 0;
for (int i = mandatory; i != argc; ++i) {
if (std::string(argv[i]) == "-q") {
++i;
query_filename = argv[i];
all = false;
} else if (!all and std::string(argv[i]) == "-n") {
++i;
num_queries = std::stoull(argv[i]);
} else if (!all and std::string(argv[i]) == "-w") {
++i;
num_wildcards = std::stoull(argv[i]);
}
}
static const uint32_t runs = 5;
if (type == "compact_3t") {
queries<compact_3t>(index_filename, query_filename, perm, runs,
num_queries, num_wildcards, all);
} else if (type == "ef_3t") {
queries<ef_3t>(index_filename, query_filename, perm, runs, num_queries,
num_wildcards, all);
} else if (type == "pef_3t") {
queries<pef_3t>(index_filename, query_filename, perm, runs, num_queries,
num_wildcards, all);
} else if (type == "vb_3t") {
queries<vb_3t>(index_filename, query_filename, perm, runs, num_queries,
num_wildcards, all);
} else if (type == "pef_r_3t") {
queries<pef_r_3t>(index_filename, query_filename, perm, runs,
num_queries, num_wildcards, all);
} else if (type == "pef_2to") {
queries<pef_2to>(index_filename, query_filename, perm, runs,
num_queries, num_wildcards, all);
} else if (type == "pef_2tp") {
queries<pef_2tp>(index_filename, query_filename, perm, runs,
num_queries, num_wildcards, all);
} else if (type == "vb_2tp") {
queries<vb_2tp>(index_filename, query_filename, perm, runs, num_queries,
num_wildcards, all);
} else {
building_util::unknown_type(type);
}
return 0;
}
| 34.574561
| 80
| 0.468476
|
jermp
|
1105a6d8cf76e7922477ee2ddd5bf9204cb8311e
| 334
|
cc
|
C++
|
Tests/Test.cc
|
loanselot1/IceSDK
|
3d8e554ac6ca56a890b74b5f4cc1901f073e3f64
|
[
"MIT"
] | 12
|
2020-10-16T06:23:10.000Z
|
2021-10-10T07:33:44.000Z
|
Tests/Test.cc
|
loanselot1/IceSDK
|
3d8e554ac6ca56a890b74b5f4cc1901f073e3f64
|
[
"MIT"
] | 6
|
2020-10-11T16:04:29.000Z
|
2021-05-09T11:03:08.000Z
|
Tests/Test.cc
|
loanselot1/IceSDK
|
3d8e554ac6ca56a890b74b5f4cc1901f073e3f64
|
[
"MIT"
] | 5
|
2020-10-10T19:45:20.000Z
|
2021-03-02T11:36:19.000Z
|
// used for unit tests
#include "Utils/Memory.h"
#include "GameBase.h"
static IceSDK::Memory::Ptr<IceSDK::GameBase> g_GameBase;
class TestGame : public IceSDK::GameBase
{
};
IceSDK::Memory::Ptr<IceSDK::GameBase> GetGameBase()
{
if (g_GameBase == nullptr) g_GameBase = std::make_shared<TestGame>();
return g_GameBase;
}
| 16.7
| 73
| 0.706587
|
loanselot1
|
1105be8cbff124728af7ec3394cc04f0aea14a90
| 1,001
|
hpp
|
C++
|
source code/TexRect.hpp
|
JackyC415/OpenGL-2D
|
b61b6f8049ecfc11aff6b67a744bda325b898daa
|
[
"BSD-2-Clause"
] | null | null | null |
source code/TexRect.hpp
|
JackyC415/OpenGL-2D
|
b61b6f8049ecfc11aff6b67a744bda325b898daa
|
[
"BSD-2-Clause"
] | null | null | null |
source code/TexRect.hpp
|
JackyC415/OpenGL-2D
|
b61b6f8049ecfc11aff6b67a744bda325b898daa
|
[
"BSD-2-Clause"
] | null | null | null |
//
// TexRect.hpp
// glutapp
//
// Created by Angelo Kyrilov on 4/11/17.
// Copyright © 2017 Angelo Kyrilov. All rights reserved.
//
#ifndef TexRect_hpp
#define TexRect_hpp
#if defined WIN32
#include <freeglut.h>
#elif defined __APPLE__
#include <GLUT/glut.h>
#else
#include <GL/freeglut.h>
#endif
class TexRect {
float x;
float y;
float w;
float h;
public:
TexRect (float x=0, float y=0, float w=0.5, float h=0.5){
this->x = x;
this->y = y;
this->w = w;
this->h = h;
}
void draw(){
glEnable(GL_TEXTURE_2D);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
glBegin(GL_QUADS);
glTexCoord2f(0.0, 0.0);
glVertex2f(x, y - h);
glTexCoord2f(0.0, 1.0);
glVertex2f(x, y);
glTexCoord2f(1.0, 1.0);
glVertex2f(x+w, y);
glTexCoord2f(1.0, 0.0);
glVertex2f(x+w, y - h);
glEnd();
glDisable(GL_TEXTURE_2D);
}
};
#endif
| 18.886792
| 68
| 0.563437
|
JackyC415
|
110df058e0c01eb9aa8d8bb773e5b098d0521c78
| 2,216
|
cpp
|
C++
|
particles-simulator/src/Game/StateManager.cpp
|
bartos97/particles-simulator
|
dc2fc18fbc047803b3c17d7cc7bf9dbc99b00a2b
|
[
"WTFPL"
] | null | null | null |
particles-simulator/src/Game/StateManager.cpp
|
bartos97/particles-simulator
|
dc2fc18fbc047803b3c17d7cc7bf9dbc99b00a2b
|
[
"WTFPL"
] | null | null | null |
particles-simulator/src/Game/StateManager.cpp
|
bartos97/particles-simulator
|
dc2fc18fbc047803b3c17d7cc7bf9dbc99b00a2b
|
[
"WTFPL"
] | null | null | null |
#include "pch.h"
#include "StateManager.h"
#include <fstream>
#include <algorithm>
StateManager& StateManager::getInstance()
{
static StateManager instance;
return instance;
}
bool StateManager::loadFromFile(const std::string& filePath)
{
std::ifstream fileStream(filePath, std::ios::in);
if (!fileStream.is_open())
{
PS_INFO("Could not open simulation state file: %s", filePath.c_str());
return false;
}
size_t numOfLines = std::count(std::istreambuf_iterator<char>(fileStream),
std::istreambuf_iterator<char>(), '\n');
if (numOfLines == 0)
{
PS_INFO("Simulation state file is empty: %s", filePath.c_str());
return false;
}
std::vector<ParticleState> buffer;
m_states.clear();
m_states.reserve(numOfLines);
buffer.reserve(numOfLines);
fileStream.seekg(0);
bool fail = false;
bool bad = false;
for (std::string line; std::getline(fileStream, line); )
{
buffer.emplace_back(line);
fail = fileStream.fail();
bad = fileStream.bad();
}
if (fail || bad)
{
PS_INFO("Failed when reading from file: %s", filePath.c_str());
fileStream.close();
return false;
}
m_states.swap(buffer);
PS_INFO("Simulation state read from file successfully");
return true;
}
bool StateManager::saveToFile(const std::string& filePath) const
{
std::ofstream fileStream(filePath, std::ios::out);
if (!fileStream)
{
PS_INFO("Could not open simulation state file: %s", filePath.c_str());
return false;
}
for (const auto& state : m_states)
{
fileStream << state.getState() << '\n';
}
if (!fileStream.good())
{
PS_INFO("Failed when writing to file: %s", filePath.c_str());
fileStream.close();
return false;
}
PS_INFO("Simulation state saved to file successfully");
return true;
}
void StateManager::setStates(const std::vector<Particle>& particles)
{
m_states.clear();
m_states.reserve(particles.size());
for (const auto& particle : particles)
{
m_states.push_back(particle.createState());
}
}
| 23.326316
| 78
| 0.614621
|
bartos97
|
11155a782e859920e824308e53b081bf510634ac
| 1,385
|
cpp
|
C++
|
codeforces/B - Trouble Sort/Wrong answer on pretest 2.cpp
|
kzvd4729/Problem-Solving
|
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
|
[
"MIT"
] | 1
|
2022-02-11T16:55:36.000Z
|
2022-02-11T16:55:36.000Z
|
codeforces/B - Trouble Sort/Wrong answer on pretest 2.cpp
|
kzvd4729/Problem-Solving
|
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
|
[
"MIT"
] | null | null | null |
codeforces/B - Trouble Sort/Wrong answer on pretest 2.cpp
|
kzvd4729/Problem-Solving
|
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
|
[
"MIT"
] | null | null | null |
/****************************************************************************************
* @author: * kzvd4729 created: Jun/07/2020 20:55
* solution_verdict: Wrong answer on pretest 2 language: GNU C++14
* run_time: 15 ms memory_used: 4100 KB
* problem: https://codeforces.com/contest/1365/problem/B
****************************************************************************************/
#include<iostream>
#include<vector>
#include<cstring>
#include<map>
#include<bitset>
#include<assert.h>
#include<algorithm>
#include<iomanip>
#include<cmath>
#include<set>
#include<queue>
#include<unordered_map>
#include<random>
#include<chrono>
#include<stack>
#include<deque>
#define long long long
using namespace std;
const int N=1e6;
int aa[N+2];
int main()
{
ios_base::sync_with_stdio(0);cin.tie(0);
int t;cin>>t;
while(t--)
{
int n;cin>>n;
for(int i=1;i<=n;i++)cin>>aa[i];
vector<int>a,b;
for(int i=1;i<=n;i++)
{
int x;cin>>x;
if(x)a.push_back(aa[i]);
else b.push_back(aa[i]);
}
int f=0;
for(int i=1;i<a.size();i++)if(a[i]<a[i-1])f=1;
for(int i=1;i<b.size();i++)if(b[i]<b[i-1])f=1;
if(f)cout<<"No\n";else cout<<"Yes\n";
}
return 0;
}
| 28.854167
| 111
| 0.467148
|
kzvd4729
|
1115843179e5bf72d01674ae14c979cfed6a3eba
| 3,133
|
hpp
|
C++
|
c++/src/objtools/data_loaders/blastdb/local_blastdb_adapter.hpp
|
OpenHero/gblastn
|
a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8
|
[
"MIT"
] | 31
|
2016-12-09T04:56:59.000Z
|
2021-12-31T17:19:10.000Z
|
c++/src/objtools/data_loaders/blastdb/local_blastdb_adapter.hpp
|
OpenHero/gblastn
|
a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8
|
[
"MIT"
] | 6
|
2017-03-10T17:25:13.000Z
|
2021-09-22T15:49:49.000Z
|
c++/src/objtools/data_loaders/blastdb/local_blastdb_adapter.hpp
|
OpenHero/gblastn
|
a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8
|
[
"MIT"
] | 20
|
2015-01-04T02:15:17.000Z
|
2021-12-03T02:31:43.000Z
|
#ifndef OBJTOOLS_DATA_LOADERS_BLASTDB___LOCAL_BLASTDB_ADAPTER__HPP
#define OBJTOOLS_DATA_LOADERS_BLASTDB___LOCAL_BLASTDB_ADAPTER__HPP
/* $Id: local_blastdb_adapter.hpp 368048 2012-07-02 13:25:25Z camacho $
* ===========================================================================
*
* PUBLIC DOMAIN NOTICE
* National Center for Biotechnology Information
*
* This software/database is a "United States Government Work" under the
* terms of the United States Copyright Act. It was written as part of
* the author's official duties as a United States Government employee and
* thus cannot be copyrighted. This software/database is freely available
* to the public for use. The National Library of Medicine and the U.S.
* Government have not placed any restriction on its use or reproduction.
*
* Although all reasonable efforts have been taken to ensure the accuracy
* and reliability of the software and data, the NLM and the U.S.
* Government do not and cannot warrant the performance or results that
* may be obtained by using this software or data. The NLM and the U.S.
* Government disclaim all warranties, express or implied, including
* warranties of performance, merchantability or fitness for any particular
* purpose.
*
* Please cite the author in any work or product based on this material.
*
* ===========================================================================
*
* Author: Christiam Camacho
*
* ===========================================================================
*/
/** @file local_blastdb_adapter.hpp
* Declaration of the CLocalBlastDbAdapter class.
*/
#include <objtools/data_loaders/blastdb/blastdb_adapter.hpp>
BEGIN_NCBI_SCOPE
BEGIN_SCOPE(objects)
/** This class allows retrieval of sequence data from locally installed BLAST
* databases via CSeqDB
*/
class NCBI_XLOADER_BLASTDB_EXPORT CLocalBlastDbAdapter : public IBlastDbAdapter
{
public:
/// Constructor with a CSeqDB instance
/// @param seqdb CSeqDB object to initialize this object with [in]
CLocalBlastDbAdapter(CRef<CSeqDB> seqdb) : m_SeqDB(seqdb) {}
/// Constructor with a CSeqDB instance
/// @param db_name database name [in]
/// @param db_type database molecule type [in]
CLocalBlastDbAdapter(const string& db_name, CSeqDB::ESeqType db_type)
: m_SeqDB(new CSeqDB(db_name, db_type)) {}
/** @inheritDoc */
virtual CSeqDB::ESeqType GetSequenceType();
/** @inheritDoc */
virtual int GetSeqLength(int oid);
/** @inheritDoc */
virtual TSeqIdList GetSeqIDs(int oid);
/** @inheritDoc */
virtual CRef<CBioseq> GetBioseqNoData(int oid, int target_gi = 0);
/** @inheritDoc */
virtual CRef<CSeq_data> GetSequence(int oid, int begin = 0, int end = 0);
/** @inheritDoc */
virtual bool SeqidToOid(const CSeq_id & id, int & oid);
/** @inheritDoc */
virtual int GetTaxId(const CSeq_id_Handle& id);
private:
/// The BLAST database handle
CRef<CSeqDB> m_SeqDB;
};
END_SCOPE(objects)
END_NCBI_SCOPE
#endif /* OBJTOOLS_DATA_LOADERS_BLASTDB___LOCAL_BLASTDB_ADAPTER__HPP */
| 37.746988
| 79
| 0.67571
|
OpenHero
|
111b718913e890c11f93d12c25696cfc174db700
| 1,025
|
cpp
|
C++
|
src/sys/eventtypestore.cpp
|
ajdnik/work-schedule
|
b42613aa62d991649d46defb4722690ffdbe6b7b
|
[
"MIT"
] | null | null | null |
src/sys/eventtypestore.cpp
|
ajdnik/work-schedule
|
b42613aa62d991649d46defb4722690ffdbe6b7b
|
[
"MIT"
] | null | null | null |
src/sys/eventtypestore.cpp
|
ajdnik/work-schedule
|
b42613aa62d991649d46defb4722690ffdbe6b7b
|
[
"MIT"
] | null | null | null |
#include "eventtypestore.h"
#include <QVariant>
EventTypeStore::EventTypeStore(DatabaseManager *manager, Error *error, QObject *parent)
: Store<EventType>(manager, error, parent)
{
this->addRole("id");
this->addRole("name");
this->add(EventType(1, QObject::tr("Vacation")), 1);
this->add(EventType(2, QObject::tr("Medical")), 2);
this->add(EventType(3, QObject::tr("Other")), 3);
}
QVariant EventTypeStore::data(const QModelIndex &index, int role) const
{
if (index.row() < 0 || index.row() > this->rowCount())
return QVariant();
const EventType &eventType = this->aObjects[index.row()];
if (role == this->getRoleNumber("name"))
return eventType.name();
else if(role == this->getRoleNumber("id"))
return eventType.id();
return QVariant();
}
QString EventTypeStore::getName(int id) const
{
for(int i=0;i<this->aObjects.count();i++) {
if(this->aObjects[i].id() == id)
return this->aObjects[i].name();
}
return QString();
}
| 29.285714
| 87
| 0.628293
|
ajdnik
|
111bbaabad015cadda72cecc2b22738403920e76
| 1,533
|
cpp
|
C++
|
1. Implementation of Stack using array.cpp
|
student-entrepreneur/DATA-STRUCTURE
|
83c2306c4e744f9a579102679439ec419fa4ff6f
|
[
"Apache-2.0"
] | null | null | null |
1. Implementation of Stack using array.cpp
|
student-entrepreneur/DATA-STRUCTURE
|
83c2306c4e744f9a579102679439ec419fa4ff6f
|
[
"Apache-2.0"
] | null | null | null |
1. Implementation of Stack using array.cpp
|
student-entrepreneur/DATA-STRUCTURE
|
83c2306c4e744f9a579102679439ec419fa4ff6f
|
[
"Apache-2.0"
] | null | null | null |
#include<iostream>
#include<conio.h>
#include<stdlib.h>
int max,i,n,x;
int top=-1;
class stack
{
int s[500];
public:
void push();
void pop();
void display();
void topele();
};
void stack::push()
{
int x;
if(top==(max-1))
std::cout<<"Stack is full";
else
{
std::cout<<"enter data:";
std::cin>>x;
top=top+1;
s[top]=x;
}}
void stack::pop()
{
if(top==-1)
std::cout<<"stack is empty";
else
s[top--]='\0';
std::cout<<" ** Top element deleted **\n";
}
void stack::display()
{
if(top==-1)
std::cout<<"stack is empty"<<"\n";
else
{
std::cout<<"displaying the contents of stack:\n";
for(i=0;i<=top;i++)
std::cout<<s[i]<<"\t";
std::cout<<"\n";
}}
void stack::topele()
{
if(top==-1)
{
std::cout<<"stack is empty"<<"\n";
}
else
{ i=0;
while(i<=top)
{
if(i==top)
{std::cout<<"The element at the top is: ";
std::cout<<s[i]<<"\t";
break;}
else
{i++;}
}
}
std::cout<<"\n";
}
int main()
{
std::cout<< "Programmed by AKSHAYA RAJ S A \n";
stack operation;
std::cout<<"enter the range:";
std::cin>>max;
while(1)
{
std::cout<<"\n1.push\n2.pop\n3.display\n4.top of the element\n5.exit";
std::cout<<"\n enter ur choice:";
std::cin>>n;
switch(n)
{case 1:
operation.push();
break;
case 2:
operation.pop();
break;
case 3:
operation.display();
break;
case 4:
operation.topele();
break;
case 5:
exit(0);
default:
std::cout<<"Invalid option";
}
}
return 0;
}
| 14.883495
| 71
| 0.529028
|
student-entrepreneur
|
112a531aa8cca13a371cdde63122f451b8b67d75
| 2,417
|
hpp
|
C++
|
nexxT/src/Logger.hpp
|
pfrydlewicz/nexxT
|
33616dbeee448c59201aa3009d637fe6b8d2b39c
|
[
"Apache-2.0"
] | 5
|
2020-05-03T10:52:14.000Z
|
2022-03-02T10:32:33.000Z
|
nexxT/src/Logger.hpp
|
pfrydlewicz/nexxT
|
33616dbeee448c59201aa3009d637fe6b8d2b39c
|
[
"Apache-2.0"
] | 32
|
2020-05-18T15:49:00.000Z
|
2022-02-22T20:10:56.000Z
|
nexxT/src/Logger.hpp
|
pfrydlewicz/nexxT
|
33616dbeee448c59201aa3009d637fe6b8d2b39c
|
[
"Apache-2.0"
] | 2
|
2020-03-21T15:04:46.000Z
|
2021-03-01T15:42:49.000Z
|
/*
* SPDX-License-Identifier: Apache-2.0
* Copyright (C) 2020 ifm electronic gmbh
*
* THE PROGRAM IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND.
*/
/**
\file Logger.hpp
Macros for logging from the C++ world.
*/
#ifndef NEXXT_LOGGER_HPP
#define NEXXT_LOGGER_HPP
#include "Services.hpp"
#include "NexxTLinkage.hpp"
#include <QtCore/QMetaObject>
//! @cond Doxygen_Suppress
#define NEXXT_LOG_LEVEL_NOTSET 0
#define NEXXT_LOG_LEVEL_INTERNAL 5
#define NEXXT_LOG_LEVEL_DEBUG 10
#define NEXXT_LOG_LEVEL_INFO 20
#define NEXXT_LOG_LEVEL_WARN 30
#define NEXXT_LOG_LEVEL_ERROR 40
#define NEXXT_LOG_LEVEL_CRITICAL 50
//! @endcond
/*!
Log msg using the nexxT mechanism with priority INTERNAL (lowest)
\param msg QString instance
*/
#define NEXXT_LOG_INTERNAL(msg) nexxT::Logging::log(NEXXT_LOG_LEVEL_INTERNAL, msg, __FILE__, __LINE__)
/*!
Log msg using the nexxT mechanism with priority DEBUG
\param msg QString instance
*/
#define NEXXT_LOG_DEBUG(msg) nexxT::Logging::log(NEXXT_LOG_LEVEL_DEBUG, msg, __FILE__, __LINE__)
/*!
Log msg using the nexxT mechanism with priority INFO
\param msg QString instance
*/
#define NEXXT_LOG_INFO(msg) nexxT::Logging::log(NEXXT_LOG_LEVEL_INFO, msg, __FILE__, __LINE__)
/*!
Log msg using the nexxT mechanism with priority WARNING
\param msg QString instance
*/
#define NEXXT_LOG_WARN(msg) nexxT::Logging::log(NEXXT_LOG_LEVEL_WARN, msg, __FILE__, __LINE__)
/*!
Log msg using the nexxT mechanism with priority ERROR
\param msg QString instance
*/
#define NEXXT_LOG_ERROR(msg) nexxT::Logging::log(NEXXT_LOG_LEVEL_ERROR, msg, __FILE__, __LINE__)
/*!
Log msg using the nexxT mechanism with priority CRITICAL (highest)
\param msg QString instance
*/
#define NEXXT_LOG_CRITICAL(msg) nexxT::Logging::log(NEXXT_LOG_LEVEL_CRITICAL, msg, __FILE__, __LINE__)
//! @cond Doxygen_Suppress
namespace nexxT
{
class DLLEXPORT Logging
{
static unsigned int loglevel;
static void _log(unsigned int level, const QString &message, const QString &file, unsigned int line);
public:
static void setLogLevel(unsigned int level);
static inline void log(unsigned int level, const QString &message, const QString &file, unsigned int line)
{
if( level >= loglevel )
{
_log(level, message, file, line);
}
}
};
};
//! @endcond
#endif
| 27.157303
| 114
| 0.719901
|
pfrydlewicz
|
112e731e487fd8f0581def8bc6b9893fe61ba2d9
| 4,308
|
cpp
|
C++
|
Engine/EditorUI/Panel/InspectorSubpanel/PanelTrail.cpp
|
mariofv/LittleEngine
|
38ecfdf6041a24f304c679ee3b6b589ba2040e48
|
[
"MIT"
] | 9
|
2020-04-05T07:44:38.000Z
|
2022-01-12T02:07:14.000Z
|
Engine/EditorUI/Panel/InspectorSubpanel/PanelTrail.cpp
|
mariofv/LittleEngine
|
38ecfdf6041a24f304c679ee3b6b589ba2040e48
|
[
"MIT"
] | 105
|
2020-03-13T19:12:23.000Z
|
2020-12-02T23:41:15.000Z
|
Engine/EditorUI/Panel/InspectorSubpanel/PanelTrail.cpp
|
mariofv/LittleEngine
|
38ecfdf6041a24f304c679ee3b6b589ba2040e48
|
[
"MIT"
] | 1
|
2021-04-24T16:11:49.000Z
|
2021-04-24T16:11:49.000Z
|
#include "PanelTrail.h"
#include "Component/ComponentTrail.h"
#include "EditorUI/Helper/ImGuiHelper.h"
#include "EditorUI/Panel/PanelPopups.h"
#include "EditorUI/Panel/PopupsPanel/PanelPopupResourceSelector.h"
#include "Module/ModuleActions.h"
#include "Module/ModuleEditor.h"
#include <imgui.h>
#include <imgui_internal.h>
#include <imgui_stdlib.h>
#include <FontAwesome5/IconsFontAwesome5.h>
PanelTrail::PanelTrail()
{
enabled = true;
opened = true;
window_name = "Trail Inspector";
}
void PanelTrail::Render(ComponentTrail* trail)
{
if (ImGui::CollapsingHeader(ICON_FA_SHARE " Trail Renderer", ImGuiTreeNodeFlags_DefaultOpen))
{
ImGui::Checkbox("Active", &trail->active);
ImGui::SameLine();
if (ImGui::Button("Delete"))
{
App->actions->DeleteComponentUndo(trail);
return;
}
if (ImGui::Button("Copy"))
{
App->actions->SetCopyComponent(trail);
}
if (ImGui::Button("Paste component as new"))
{
App->actions->PasteComponent(trail->owner);
}
if (ImGui::Button("Paste component values"))
{
App->actions->PasteComponentValues(trail);
}
ImGui::Separator();
ImGui::TextColored(ImVec4(0.f, 0.f, 1.f, 1.f), "Trail Properties");
trail->modified_by_user |= ImGui::DragFloat("Time", &trail->duration, 1000.0f);
trail->modified_by_user |= ImGui::DragFloat("Width", &trail->width, 0.01f);
trail->modified_by_user |= ImGui::DragInt("Curve Segments", &trail->points_in_curve, 1, 0, 100);
float trail_texture_size = 17.5f;
void* display_image;
if (trail->trail_texture.get() != nullptr)
{
display_image = (void*)(intptr_t)trail->trail_texture->opengl_texture;
}
ImGuiID element_id = ImGui::GetID(std::to_string(trail->trail_texture->GetUUID()).c_str());
if (ImGui::ImageButton(
display_image,
ImVec2(trail_texture_size, trail_texture_size),
ImVec2(0, 1),
ImVec2(1, 0),
1,
ImVec4(1.f, 1.f, 1.f, 1.f),
ImVec4(1.f, 1.f, 1.f, 1.f)
))
{
App->editor->popups->resource_selector_popup.ShowPanel(element_id, ResourceType::TEXTURE);
}
uint32_t dropped_texture_uuid = ImGui::ResourceDropper<Texture>();
if (dropped_texture_uuid != 0)
{
trail->ChangeTexture(dropped_texture_uuid);
trail->modified_by_user = true;
}
uint32_t resource_selector_texture = App->editor->popups->resource_selector_popup.GetSelectedResource(element_id);
if (resource_selector_texture != 0)
{
trail->ChangeTexture(resource_selector_texture);
trail->modified_by_user = true;
}
ImGui::SameLine();
ImGui::TextColored(ImVec4(0.f, 0.f, 1.f, 1.f), "Texture");
int mode = static_cast<int>(trail->texture_mode);
if (ImGui::Combo("TextureMode###Combo", &mode, "Stretch\0Tile\0RepeatPerSegment\0"))
{
switch (mode)
{
case 0:
trail->texture_mode = ComponentTrail::TextureMode::STRETCH;
break;
case 1:
trail->texture_mode = ComponentTrail::TextureMode::TILE;
break;
case 2:
trail->texture_mode = ComponentTrail::TextureMode::REPEAT_PER_SEGMENT;
break;
}
}
if (trail->texture_mode == ComponentTrail::TextureMode::TILE)
{
trail->modified_by_user |= ImGui::DragInt("Tile Rows", &trail->rows, 1);
trail->modified_by_user |= ImGui::DragInt("Tile Columns", &trail->columns, 1);
}
if (ImGui::CollapsingHeader("Color"))
{
ImGui::Spacing();
trail->modified_by_user |= ImGui::ColorEdit4("Color", trail->color.ptr());
trail->modified_by_user |= ImGui::DragFloat("Intensity", &trail->emissive_intensity, 0.05f, 0.01f, 10.0f);
trail->modified_by_user |= ImGui::Checkbox("Blend Two Colors", &trail->blend_colors);
if (trail->blend_colors)
{
trail->modified_by_user |= ImGui::ColorEdit4("Color Blend", trail->color_to_blend.ptr());
trail->modified_by_user |= ImGui::DragFloat("Fraction Color 2", &trail->blend_percentage, 0.1f, 0.0f, 1.0F);
ImGui::SameLine();
ImGui::TextColored(ImVec4(0.f, 0.f, 1.f, 1.f), "?");
if (ImGui::IsItemHovered())
ImGui::SetTooltip("Width Percentage of Color 2 in relation to Color 1");
trail->modified_by_user |= ImGui::DragFloat("Blending Width", &trail->smoothening_step, 0.01f, 0.1f, 1.0F);
ImGui::SameLine();
ImGui::TextColored(ImVec4(0.f, 0.f, 1.f, 1.f), "?");
if (ImGui::IsItemHovered())
ImGui::SetTooltip("Width Percentage where 2 colors are blended");
}
}
}
}
| 33.138462
| 116
| 0.690808
|
mariofv
|
113069a09eb0e96a1e8096a63938d77c99437678
| 6,755
|
cpp
|
C++
|
clangd/AST.cpp
|
jrose-apple/swift-clang-tools-extra
|
1e165857dc4f2cfd77970c42fbc345a474992a39
|
[
"Apache-2.0"
] | 16
|
2018-11-28T12:05:20.000Z
|
2021-11-08T09:47:46.000Z
|
clangd/AST.cpp
|
jrose-apple/swift-clang-tools-extra
|
1e165857dc4f2cfd77970c42fbc345a474992a39
|
[
"Apache-2.0"
] | 4
|
2018-11-30T19:12:21.000Z
|
2019-10-04T17:37:07.000Z
|
clangd/AST.cpp
|
dragon-tc-tmp/clang-tools-extra
|
e16e704b6f7d4185e55942883506c1bb9280cd2d
|
[
"Apache-2.0"
] | 15
|
2019-02-01T20:10:43.000Z
|
2022-03-26T11:52:37.000Z
|
//===--- AST.cpp - Utility AST functions -----------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "AST.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclTemplate.h"
#include "clang/AST/TemplateBase.h"
#include "clang/Basic/SourceLocation.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Index/USRGeneration.h"
#include "llvm/ADT/Optional.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/ScopedPrinter.h"
#include "llvm/Support/raw_ostream.h"
namespace clang {
namespace clangd {
namespace {
llvm::Optional<llvm::ArrayRef<TemplateArgumentLoc>>
getTemplateSpecializationArgLocs(const NamedDecl &ND) {
if (auto *Func = llvm::dyn_cast<FunctionDecl>(&ND)) {
if (const ASTTemplateArgumentListInfo *Args =
Func->getTemplateSpecializationArgsAsWritten())
return Args->arguments();
} else if (auto *Cls =
llvm::dyn_cast<ClassTemplatePartialSpecializationDecl>(&ND)) {
if (auto *Args = Cls->getTemplateArgsAsWritten())
return Args->arguments();
} else if (auto *Var = llvm::dyn_cast<VarTemplateSpecializationDecl>(&ND))
return Var->getTemplateArgsInfo().arguments();
// We return None for ClassTemplateSpecializationDecls because it does not
// contain TemplateArgumentLoc information.
return llvm::None;
}
} // namespace
// Returns true if the complete name of decl \p D is spelled in the source code.
// This is not the case for:
// * symbols formed via macro concatenation, the spelling location will
// be "<scratch space>"
// * symbols controlled and defined by a compile command-line option
// `-DName=foo`, the spelling location will be "<command line>".
bool isSpelledInSourceCode(const Decl *D) {
const auto &SM = D->getASTContext().getSourceManager();
auto Loc = D->getLocation();
// FIXME: Revisit the strategy, the heuristic is limitted when handling
// macros, we should use the location where the whole definition occurs.
if (Loc.isMacroID()) {
std::string PrintLoc = SM.getSpellingLoc(Loc).printToString(SM);
if (llvm::StringRef(PrintLoc).startswith("<scratch") ||
llvm::StringRef(PrintLoc).startswith("<command line>"))
return false;
}
return true;
}
bool isImplementationDetail(const Decl *D) { return !isSpelledInSourceCode(D); }
SourceLocation findNameLoc(const clang::Decl *D) {
const auto &SM = D->getASTContext().getSourceManager();
if (!isSpelledInSourceCode(D))
// Use the expansion location as spelling location is not interesting.
return SM.getExpansionRange(D->getLocation()).getBegin();
return SM.getSpellingLoc(D->getLocation());
}
std::string printQualifiedName(const NamedDecl &ND) {
std::string QName;
llvm::raw_string_ostream OS(QName);
PrintingPolicy Policy(ND.getASTContext().getLangOpts());
// Note that inline namespaces are treated as transparent scopes. This
// reflects the way they're most commonly used for lookup. Ideally we'd
// include them, but at query time it's hard to find all the inline
// namespaces to query: the preamble doesn't have a dedicated list.
Policy.SuppressUnwrittenScope = true;
ND.printQualifiedName(OS, Policy);
OS.flush();
assert(!StringRef(QName).startswith("::"));
return QName;
}
std::string printName(const ASTContext &Ctx, const NamedDecl &ND) {
std::string Name;
llvm::raw_string_ostream Out(Name);
PrintingPolicy PP(Ctx.getLangOpts());
// Handle 'using namespace'. They all have the same name - <using-directive>.
if (auto *UD = llvm::dyn_cast<UsingDirectiveDecl>(&ND)) {
Out << "using namespace ";
if (auto *Qual = UD->getQualifier())
Qual->print(Out, PP);
UD->getNominatedNamespaceAsWritten()->printName(Out);
return Out.str();
}
ND.getDeclName().print(Out, PP);
if (!Out.str().empty()) {
Out << printTemplateSpecializationArgs(ND);
return Out.str();
}
// The name was empty, so present an anonymous entity.
if (isa<NamespaceDecl>(ND))
return "(anonymous namespace)";
if (auto *Cls = llvm::dyn_cast<RecordDecl>(&ND))
return ("(anonymous " + Cls->getKindName() + ")").str();
if (isa<EnumDecl>(ND))
return "(anonymous enum)";
return "(anonymous)";
}
std::string printTemplateSpecializationArgs(const NamedDecl &ND) {
std::string TemplateArgs;
llvm::raw_string_ostream OS(TemplateArgs);
PrintingPolicy Policy(ND.getASTContext().getLangOpts());
if (llvm::Optional<llvm::ArrayRef<TemplateArgumentLoc>> Args =
getTemplateSpecializationArgLocs(ND)) {
printTemplateArgumentList(OS, *Args, Policy);
} else if (auto *Cls = llvm::dyn_cast<ClassTemplateSpecializationDecl>(&ND)) {
if (const TypeSourceInfo *TSI = Cls->getTypeAsWritten()) {
// ClassTemplateSpecializationDecls do not contain
// TemplateArgumentTypeLocs, they only have TemplateArgumentTypes. So we
// create a new argument location list from TypeSourceInfo.
auto STL = TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>();
llvm::SmallVector<TemplateArgumentLoc, 8> ArgLocs;
ArgLocs.reserve(STL.getNumArgs());
for (unsigned I = 0; I < STL.getNumArgs(); ++I)
ArgLocs.push_back(STL.getArgLoc(I));
printTemplateArgumentList(OS, ArgLocs, Policy);
} else {
// FIXME: Fix cases when getTypeAsWritten returns null inside clang AST,
// e.g. friend decls. Currently we fallback to Template Arguments without
// location information.
printTemplateArgumentList(OS, Cls->getTemplateArgs().asArray(), Policy);
}
}
OS.flush();
return TemplateArgs;
}
std::string printNamespaceScope(const DeclContext &DC) {
for (const auto *Ctx = &DC; Ctx != nullptr; Ctx = Ctx->getParent())
if (const auto *NS = dyn_cast<NamespaceDecl>(Ctx))
if (!NS->isAnonymousNamespace() && !NS->isInlineNamespace())
return printQualifiedName(*NS) + "::";
return "";
}
llvm::Optional<SymbolID> getSymbolID(const Decl *D) {
llvm::SmallString<128> USR;
if (index::generateUSRForDecl(D, USR))
return None;
return SymbolID(USR);
}
llvm::Optional<SymbolID> getSymbolID(const IdentifierInfo &II,
const MacroInfo *MI,
const SourceManager &SM) {
if (MI == nullptr)
return None;
llvm::SmallString<128> USR;
if (index::generateUSRForMacro(II.getName(), MI->getDefinitionLoc(), SM, USR))
return None;
return SymbolID(USR);
}
} // namespace clangd
} // namespace clang
| 38.821839
| 80
| 0.68601
|
jrose-apple
|
11335b21a019afcc255e8dfcf4198ddac289c667
| 2,147
|
cc
|
C++
|
build/X86/mem/ruby/structures/ReplacementPolicy.py.cc
|
zhoushuxin/impl_of_HPCA2018
|
594d807fb0c0712bb7766122c4efe3321d012687
|
[
"BSD-3-Clause"
] | 5
|
2019-12-12T16:26:09.000Z
|
2022-03-17T03:23:33.000Z
|
build/X86/mem/ruby/structures/ReplacementPolicy.py.cc
|
zhoushuxin/impl_of_HPCA2018
|
594d807fb0c0712bb7766122c4efe3321d012687
|
[
"BSD-3-Clause"
] | null | null | null |
build/X86/mem/ruby/structures/ReplacementPolicy.py.cc
|
zhoushuxin/impl_of_HPCA2018
|
594d807fb0c0712bb7766122c4efe3321d012687
|
[
"BSD-3-Clause"
] | null | null | null |
#include "sim/init.hh"
namespace {
const uint8_t data_m5_objects_ReplacementPolicy[] = {
120,156,181,146,77,111,211,64,16,134,103,237,56,109,211,32,
168,16,7,46,40,226,100,113,168,185,244,134,42,232,141,3,
80,37,92,154,139,181,94,15,120,131,215,142,188,99,20,247,
90,254,55,204,172,155,182,82,225,200,218,30,205,251,238,215,
179,179,54,112,219,98,254,222,47,20,248,115,78,74,126,21,
212,0,95,111,51,53,102,17,212,17,184,24,214,49,168,50,
6,140,225,155,130,114,2,191,0,110,0,174,214,19,40,19,
88,165,83,94,194,254,230,150,42,206,72,194,155,49,61,226,
176,178,238,75,177,65,67,116,194,106,137,219,90,27,116,216,
208,101,91,91,51,152,135,68,23,66,116,197,9,2,172,149,
112,173,35,1,98,0,134,225,253,48,129,205,20,240,0,54,
135,192,68,55,108,30,5,115,22,204,99,161,19,243,248,193,
200,185,80,138,57,135,229,8,187,140,4,238,37,135,15,133,
167,78,27,122,132,229,223,114,175,67,151,117,125,49,100,60,
168,55,212,119,232,179,127,206,56,173,42,255,156,39,21,117,
107,126,44,188,189,198,133,109,22,197,64,232,189,156,220,232,
173,54,150,134,59,151,158,176,171,189,111,141,213,100,127,114,
87,42,14,29,114,200,243,70,59,204,115,154,5,225,218,178,
175,69,78,100,192,176,197,80,89,179,219,229,166,230,21,194,
40,81,21,234,18,59,74,88,94,234,78,59,146,162,126,108,
136,166,163,195,176,244,52,176,152,10,243,218,54,152,11,104,
152,31,184,239,229,39,116,109,55,172,68,202,166,193,79,246,
192,169,92,216,125,240,23,28,178,170,117,152,93,87,109,239,
171,126,103,155,236,59,186,179,204,119,38,251,91,25,31,151,
111,59,132,107,121,45,235,205,57,76,85,120,162,23,252,124,
78,147,253,239,228,206,78,183,114,52,31,234,36,170,107,119,
3,205,71,113,247,179,45,213,254,158,255,15,107,216,253,221,
120,47,231,175,100,93,41,241,76,205,212,179,232,15,23,226,
212,199,
};
EmbeddedPython embedded_m5_objects_ReplacementPolicy(
"m5/objects/ReplacementPolicy.py",
"/home/zhoushuxin/gem5/src/mem/ruby/structures/ReplacementPolicy.py",
"m5.objects.ReplacementPolicy",
data_m5_objects_ReplacementPolicy,
450,
869);
} // anonymous namespace
| 46.673913
| 73
| 0.679553
|
zhoushuxin
|
1136a5ca250611fe03a305d4491b73217a3b4551
| 521
|
cpp
|
C++
|
tray/src/core/windows/icon.cpp
|
dicroce/traypp
|
ad75b76058296a647327b81e87a61887c3080fdb
|
[
"MIT"
] | 16
|
2021-04-06T10:34:53.000Z
|
2022-02-23T23:23:48.000Z
|
tray/src/core/windows/icon.cpp
|
dicroce/traypp
|
ad75b76058296a647327b81e87a61887c3080fdb
|
[
"MIT"
] | 4
|
2021-04-15T05:55:57.000Z
|
2022-03-23T00:03:27.000Z
|
tray/src/core/windows/icon.cpp
|
dicroce/traypp
|
ad75b76058296a647327b81e87a61887c3080fdb
|
[
"MIT"
] | 2
|
2021-12-06T15:52:45.000Z
|
2022-03-22T19:24:42.000Z
|
#if defined(_WIN32)
#include <core/icon.hpp>
Tray::Icon::Icon(const std::string &path)
: hIcon(reinterpret_cast<HICON>(
LoadImageA(nullptr, path.c_str(), IMAGE_ICON, 0, 0, LR_LOADFROMFILE | LR_DEFAULTSIZE)))
{
}
Tray::Icon::Icon(HICON icon) : hIcon(icon) {}
Tray::Icon::Icon(const char *path) : Icon(std::string(path)) {}
Tray::Icon::Icon(WORD icon) : hIcon(LoadIcon(GetModuleHandle(nullptr), MAKEINTRESOURCE(icon))) {} // NOLINT
Tray::Icon::operator HICON()
{
return hIcon;
}
#endif
| 28.944444
| 108
| 0.662188
|
dicroce
|
1137cb9050c8a5324a9944454e73564830fd947f
| 44,488
|
cxx
|
C++
|
osprey/be/cg/cg_gcov.cxx
|
sharugupta/OpenUH
|
daddd76858a53035f5d713f648d13373c22506e8
|
[
"BSD-2-Clause"
] | null | null | null |
osprey/be/cg/cg_gcov.cxx
|
sharugupta/OpenUH
|
daddd76858a53035f5d713f648d13373c22506e8
|
[
"BSD-2-Clause"
] | null | null | null |
osprey/be/cg/cg_gcov.cxx
|
sharugupta/OpenUH
|
daddd76858a53035f5d713f648d13373c22506e8
|
[
"BSD-2-Clause"
] | null | null | null |
/*
* Copyright (C) 2010 Advanced Micro Devices, Inc. All Rights Reserved.
*/
/*
* Copyright 2003, 2004, 2005, 2006 PathScale, Inc. All Rights Reserved.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of version 2 of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it would be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
* Further, this software is distributed without any warranty that it is
* free of the rightful claim of any third person regarding infringement
* or the like. Any license provided herein, whether implied or
* otherwise, applies only to this software file. Patent licenses, if
* any, provided herein do not apply to combinations of this program with
* other software, or any other product whatsoever.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write the Free Software Foundation, Inc., 59
* Temple Place - Suite 330, Boston MA 02111-1307, USA.
*/
/* ====================================================================
* ====================================================================
*
* Module: cg_gcov.cxx
* $Revision: 1.43 $
* $Date: 05/12/05 08:59:03-08:00 $
* $Author: bos@eng-24.pathscale.com $
* $Source: /scratch/mee/2.4-65/kpro64-pending/be/cg/SCCS/s.cg_gcov.cxx $
*
* Description:
*
* This file contains the routines for the generation of GCOV files .
*
*
* ====================================================================
* ====================================================================
*/
#include "bb.h"
#include "cg.h"
#include "cg_region.h"
#include "cg_flags.h"
#include "cgexp.h"
#include "cgexp_internals.h"
#include "cxx_memory.h"
#include "data_layout.h"
#include "defs.h"
#include "flags.h"
#include "gcov-io.h"
#include "glob.h"
#include "ir_reader.h"
#include "label_util.h"
#include "mempool.h"
#include "stblock.h"
#include "symtab.h"
#include "symtab_access.h"
#include "unistd.h"
#if defined(TARG_MIPS) && !defined(TARG_SL)
//static BOOL inline Is_Target_64bit (void) { return TRUE; }
static BOOL inline Is_Target_32bit (void) { return FALSE; }
#endif // TARG_MIPS
MEM_POOL name_pool, *name_pool_ptr = NULL;
#define MAX_COUNTER_SECTIONS 4
#define BB_TO_GCOV_INDEX(bb) BB_id(bb)
#define MAXPATHLEN 100
struct function_list
{
struct function_list *next; /* next function */
char *name; /* function name */
long cfg_checksum; /* function checksum */
#ifdef GCC_303
unsigned n_counter_sections; /* number of counter sections */
struct counter_section counter_sections[MAX_COUNTER_SECTIONS];
#else
long count_edges; /* number of intrumented edges in this function */
#endif
};
static struct function_list *functions_head = 0;
static struct function_list **functions_tail = &functions_head;
/* Name and file pointer of the output file for the basic block graph. */
static FILE *bbg_file;
static char* bbg_file_name;
#ifndef GCC_303
static FILE *bb_file;
#endif
/* Name and file pointer of the input file for the arc count data. */
static FILE *da_file;
/* Pointer of the output file for the basic block/line number map. */
static int last_bb_file_num, last_bb_line_num;
static int local_n_edges = 0;
static int local_n_a_edges = 0;
static int local_n_basic_blocks = 0;
static int n_instr_edges = 0;
/* Compute checksum for the current function. */
static int pu_flag = -1;
static int begin_id = -1, end_id = -1;
static long chksum = 0;
# define DIR_SEPARATOR '/'
# define IS_DIR_SEPARATOR(ch) ((ch) == DIR_SEPARATOR)
char *
lbasename (char *name)
{
char *base;
for (base = name; *name; name++)
if (IS_DIR_SEPARATOR (*name))
base = name + 1;
return base;
}
char *
getpwd ()
{
static char *pwd = 0;
if (!pwd)
pwd = getcwd (CXX_NEW_ARRAY(char, MAXPATHLEN + 1, name_pool_ptr), MAXPATHLEN + 1);
return pwd;
}
static ST * get_symbol(const char* sym_name)
{
ST *st;
int i;
FOREACH_SYMBOL (GLOBAL_SYMTAB, st, i) {
if (ST_class(st) == CLASS_VAR && strncmp(ST_name(st), sym_name, strlen(sym_name))==0){
return st;
break;
}
}
return NULL;
}
// Bug 3806
void Gcov_BB_Prepend_Ops(BB *bb, OPS *ops)
{
#ifdef TARG_X8664
if (OPS_first(ops) == NULL) return;
OP *op = BB_first_op(bb);
if (op && OP_opnds(op) > 0 &&
TN_is_register(OP_opnd(op, 0)) &&
TN_register(OP_opnd(op, 0)) == RAX)
BB_Insert_Ops_After(bb, op, ops);
else
BB_Prepend_Ops(bb, ops);
#else
// Will see later
return;
#endif
}
#ifdef GCC_303
void
CG_Init_Couner_Infos(ST *counter_section)
{
struct function_list *item = functions_head;
ST *st = get_symbol("LPBX2");
FmtAssert (st != NULL, ("Symbol LPBX2 should have generated before"));
TY_IDX tyi;
TY& ty = New_TY(tyi);
TY_Init(ty, n_instr_edges*8, KIND_STRUCT, MTYPE_M,
STR_IDX_ZERO);
Set_TY_align(tyi, 8);
ST* new_st = New_ST(GLOBAL_SYMTAB);
ST_Init(new_st, Save_Str("LPBX2_TMP"),
CLASS_VAR, SCLASS_PSTATIC, EXPORT_LOCAL, tyi);
//Set_ST_is_initialized(new_st);
Allocate_Object(new_st);
INITO_IDX inito_lpbx2 = New_INITO(st);
INITV_IDX initv_lpbx2;
initv_lpbx2 = New_INITV();
INITV_Init_Symoff(initv_lpbx2, new_st, 0);
Append_INITV(initv_lpbx2, inito_lpbx2, INITV_IDX_ZERO);
INITV_IDX prev_initv = INITV_IDX_ZERO;
INITO_IDX inito_counter = New_INITO(counter_section);
INITV_IDX inv_counter;
for (INT i = 0; i < item->n_counter_sections; i++)
{
inv_counter = New_INITV();
INITV_Init_Integer(inv_counter, MTYPE_I4, GCOV_TAG_ARC_COUNTS);
prev_initv = Append_INITV(inv_counter, inito_counter, prev_initv);
inito_counter = INITO_IDX_ZERO;
inv_counter = New_INITV();
INITV_Init_Integer(inv_counter, MTYPE_I4, n_instr_edges);
prev_initv = Append_INITV(inv_counter, inito_counter, prev_initv);
// LPBX2
inv_counter = New_INITV();
INITV_Init_Symoff(inv_counter, new_st, 0);
prev_initv = Append_INITV(inv_counter, inito_counter, prev_initv);
}
}
#endif
void
CG_Init_Func_Infos(ST *func_infos)
{
struct function_list *item = functions_head;
TY_IDX table;
ST *listvar;
INITO_IDX ino;
INITV_IDX inv;
INITO_IDX inito;
INITV_IDX last_aggregate_initv = INITV_IDX_ZERO;
inito = New_INITO(func_infos);
TYPE_ID rtype;
if (Is_Target_32bit())
rtype = MTYPE_I4;
else
rtype = MTYPE_I8;
for (; item != 0; item = item->next){
#ifndef GCC_303
/* checksum */
inv = New_INITV();
INITV_Init_Integer(inv, rtype, item->cfg_checksum);
last_aggregate_initv = Append_INITV(inv, inito, last_aggregate_initv);
inito = INITO_IDX_ZERO;
/* arc_count */
inv = New_INITV();
INITV_Init_Integer(inv, MTYPE_I4, item->count_edges);
last_aggregate_initv = Append_INITV(inv, inito, last_aggregate_initv);
if (Is_Target_64bit()) {
inv = New_INITV();
INITV_Init_Pad(inv, 4);
last_aggregate_initv = Append_INITV(inv, inito, last_aggregate_initv);
}
#endif
/* name */
table = Make_Array_Type(MTYPE_U2, 1, strlen(item->name)+1);
listvar = Gen_Read_Only_Symbol(table, item->name);
Set_ST_is_initialized(listvar); /* so goes in rdata section */
ino = New_INITO(listvar);
inv = New_INITV();
INITV_Init_String(inv, item->name, strlen(item->name)+1);
Append_INITV (inv, ino, INITV_IDX_ZERO);
Allocate_Object(listvar);
inv = New_INITV();
INITV_Init_Symoff (inv, listvar, 0);
last_aggregate_initv = Append_INITV (inv, inito, last_aggregate_initv);
inito = INITO_IDX_ZERO;
#ifdef GCC_303
/* checksum */
inv = New_INITV();
INITV_Init_Integer(inv, MTYPE_I4, item->cfg_checksum);
last_aggregate_initv = Append_INITV(inv, inito, last_aggregate_initv);
/* n_counter_sections */
inv = New_INITV();
INITV_Init_Integer(inv, MTYPE_I4, item->n_counter_sections);
last_aggregate_initv = Append_INITV(inv, inito, last_aggregate_initv);
/* counter_sections */
UINT32 tag_size = 4;
UINT32 n_counters_size = 4;
UINT32 counter_section_size = tag_size + n_counters_size;
TY_IDX tyi_counter;
ST *counter_section;
TY& ty_counter = New_TY(tyi_counter);
TY_Init(ty_counter, counter_section_size*item->n_counter_sections, KIND_STRUCT, MTYPE_M, STR_IDX_ZERO);
Set_TY_align(tyi_counter, 8);
counter_section = New_ST(GLOBAL_SYMTAB);
ST_Init(counter_section, STR_IDX_ZERO, CLASS_VAR, SCLASS_FSTATIC, EXPORT_LOCAL, tyi_counter);
Set_ST_is_initialized(counter_section);
Allocate_Object(counter_section);
INITV_IDX prev_initv = INITV_IDX_ZERO;
INITO_IDX inito_counter = New_INITO(counter_section);
INITV_IDX inv_counter;
for (INT i = 0; i < item->n_counter_sections; i++)
{
inv_counter = New_INITV();
INITV_Init_Integer(inv_counter, MTYPE_I4, GCOV_TAG_ARC_COUNTS);
prev_initv = Append_INITV(inv_counter, inito_counter, prev_initv);
inito_counter = INITO_IDX_ZERO;
inv_counter = New_INITV();
INITV_Init_Integer(inv_counter, MTYPE_I4, item->counter_sections[0].n_counters);
prev_initv = Append_INITV(inv_counter, inito_counter, prev_initv);
}
inv = New_INITV();
INITV_Init_Symoff (inv, counter_section, 0);
last_aggregate_initv = Append_INITV (inv, inito, last_aggregate_initv);
#endif
}
#ifndef GCC_303
inv = New_INITV();
INITV_Init_Pad(inv, Is_Target_32bit() ? 4 : 8 );
last_aggregate_initv = Append_INITV(inv, inito, last_aggregate_initv);
inito = INITO_IDX_ZERO;
inv = New_INITV();
INITV_Init_Integer(inv, MTYPE_I4, -1);
last_aggregate_initv = Append_INITV(inv, inito, last_aggregate_initv);
inv = New_INITV();
INITV_Init_Pad(inv, Is_Target_32bit() ? 4 : 12 );
last_aggregate_initv = Append_INITV(inv, inito, last_aggregate_initv);
#endif
}
void
CG_End_Final()
{
int num_nodes = 0;
struct function_list *item;
for (item = functions_head; item != 0; item = item->next)
{
num_nodes++;
}
if (num_nodes == 0) return;
ST *st = get_symbol("LPBX0");
FmtAssert (st != NULL, ("Symbol LPBX0 should have generated before"));
if ( ST_is_not_used(st) ){
Clear_ST_is_not_used(st);
Allocate_Object(st);
}
#ifdef GCC_303
/* Version ident */
INITO_IDX aggregate_inito = New_INITO(st);
INITV_IDX inv = New_INITV();
INITV_Init_Integer(inv, MTYPE_U8, GCOV_VERSION);
INITV_IDX last_aggregate_initv;
last_aggregate_initv = Append_INITV (inv, aggregate_inito, INITV_IDX_ZERO);
/* next -- NULL */
inv = New_INITV();
INITV_Init_Integer(inv, MTYPE_U8, 0);
last_aggregate_initv = Append_INITV(inv, INITO_IDX_ZERO, last_aggregate_initv);
/* Address of filename. */
char *cwd, *da_filename;
int da_filename_len;
cwd = getpwd ();
da_filename_len = strlen (Src_File_Name) + strlen (cwd) + 4 + 1;
da_filename = CXX_NEW_ARRAY(char, da_filename_len, name_pool_ptr);
strcpy (da_filename, cwd);
strcat (da_filename, "/");
strcat (da_filename, Src_File_Name);
INT i;
for (i = da_filename_len-1; i>0; i--)
if (da_filename[i] == '.')
break;
FmtAssert (da_filename[i] == '.', ("Src_File_Name should associate with the prefix"));
da_filename[i+1] = 'd';
da_filename[i+3] = da_filename[i+2];
da_filename[i+2] = 'a';
//strcat (da_filename, ".da");
TY_IDX table = Make_Array_Type(MTYPE_U2, 1, da_filename_len);
ST *listvar = Gen_Read_Only_Symbol(table, "dafilename_table");
Set_ST_is_initialized(listvar); /* so goes in rdata section */
INITO_IDX ino = New_INITO(listvar);
INITV_IDX inv_local = New_INITV();
INITV_Init_String(inv_local, da_filename, da_filename_len);
Append_INITV (inv_local, ino, INITV_IDX_ZERO);
Allocate_Object(listvar);
inv = New_INITV();
INITV_Init_Symoff (inv, listvar, 0);
last_aggregate_initv = Append_INITV(inv, INITO_IDX_ZERO, last_aggregate_initv);
/* Workspace */
inv = New_INITV();
INITV_Init_Integer(inv, MTYPE_U8, 0);
last_aggregate_initv = Append_INITV(inv, INITO_IDX_ZERO, last_aggregate_initv);
/* number of functions */
inv = New_INITV();
INITV_Init_Integer(inv, MTYPE_I4, num_nodes);
last_aggregate_initv = Append_INITV(inv, INITO_IDX_ZERO, last_aggregate_initv);
inv = New_INITV();
INITV_Init_Pad(inv, 4);
last_aggregate_initv = Append_INITV(inv, INITO_IDX_ZERO, last_aggregate_initv);
/* function_info table */
UINT32 func_name_size = 8;
UINT32 checksum_size = 4;
UINT32 n_counter_sections_size = 4;
UINT32 counter_section_size = 8;
UINT32 function_info_size = func_name_size + checksum_size + n_counter_sections_size + counter_section_size;
TY_IDX tyi_function;
TY& ty_function = New_TY(tyi_function);
TY_Init(ty_function, function_info_size * num_nodes, KIND_STRUCT, MTYPE_M,
STR_IDX_ZERO);
Set_TY_align(tyi_function, 8);
ST *func_infos = New_ST(GLOBAL_SYMTAB);
ST_Init(func_infos, Save_Str("function_infos"), CLASS_VAR, SCLASS_FSTATIC, EXPORT_LOCAL, tyi_function);
Set_ST_is_initialized(func_infos);
CG_Init_Func_Infos(func_infos);
Allocate_Object(func_infos);
inv = New_INITV();
INITV_Init_Symoff(inv, func_infos, 0);
last_aggregate_initv = Append_INITV(inv, INITO_IDX_ZERO, last_aggregate_initv);
/* n_counter_sections */
inv = New_INITV();
INITV_Init_Integer(inv, MTYPE_I4, 1);
last_aggregate_initv = Append_INITV(inv, INITO_IDX_ZERO, last_aggregate_initv);
inv = New_INITV();
INITV_Init_Pad(inv, 4);
last_aggregate_initv = Append_INITV(inv, INITO_IDX_ZERO, last_aggregate_initv);
/* counter sections */
UINT32 tag_size = 4;
UINT32 n_counters_size = 4;
UINT32 counters_size = 8;
counter_section_size = tag_size + n_counters_size + counters_size;
TY_IDX tyi_counter;
TY& ty_counter = New_TY(tyi_counter);
TY_Init(ty_counter, counter_section_size * 3, KIND_STRUCT, MTYPE_M, STR_IDX_ZERO);
Set_TY_align(tyi_counter, 8);
ST *counter_section = New_ST(GLOBAL_SYMTAB);
ST_Init(counter_section, Save_Str("counter_section"), CLASS_VAR, SCLASS_FSTATIC, EXPORT_LOCAL, tyi_counter);
Set_ST_is_initialized(counter_section);
Allocate_Object(counter_section);
inv = New_INITV();
INITV_Init_Symoff(inv, counter_section, 0);
last_aggregate_initv = Append_INITV(inv, INITO_IDX_ZERO, last_aggregate_initv);
CG_Init_Couner_Infos(counter_section);
#else
/* Output the main header, of 7 words:
0: 1 if this file is initialized, else 0.
1: address of file name (LPBX1).
2: address of table of counts (LPBX2).
3: number of counts in the table.
4: always 0, libgcc2 uses this as a pointer to next ``struct bb''
The following are GNU extensions:
5: Number of bytes in this header.
6: address of table of function checksums (LPBX7). */
TYPE_ID rtype;
INT32 ty_size;
if (Is_Target_32bit()) {
rtype = MTYPE_U4;
ty_size = 4;
}
else {
rtype = MTYPE_U8;
ty_size = 8;
}
/* The zero word. */
INITO_IDX aggregate_inito = New_INITO(st);
INITV_IDX inv = New_INITV();
INITV_Init_Integer(inv, rtype, 0);
INITV_IDX last_aggregate_initv;
last_aggregate_initv = Append_INITV (inv, aggregate_inito, INITV_IDX_ZERO);
/* Address of filename. */
char *cwd, *da_filename;
int da_filename_len,i;
cwd = getpwd ();
da_filename_len = strlen (lbasename(Src_File_Name)) + strlen (cwd) + 4 + 1;
da_filename = CXX_NEW_ARRAY(char, da_filename_len, name_pool_ptr);
strcpy (da_filename, cwd);
strcat (da_filename, "/");
strcat (da_filename, lbasename(Src_File_Name));
for (i = da_filename_len-1; i>0; i--)
if (da_filename[i] == '.')
break;
FmtAssert (da_filename[i] == '.', ("Src_File_Name should associate with the prefix"));
da_filename[i] = 0;
strcat (da_filename, ".da");
TY_IDX table = Make_Array_Type(MTYPE_U2, 1, da_filename_len);
ST *listvar = Gen_Read_Only_Symbol(table, "dafilename_table");
Set_ST_is_initialized(listvar); /* so goes in rdata section */
INITO_IDX ino = New_INITO(listvar);
INITV_IDX inv_local = New_INITV();
INITV_Init_String(inv_local, da_filename, da_filename_len);
Append_INITV (inv_local, ino, INITV_IDX_ZERO);
Allocate_Object(listvar);
inv = New_INITV();
INITV_Init_Symoff (inv, listvar, 0);
last_aggregate_initv = Append_INITV(inv, INITO_IDX_ZERO, last_aggregate_initv);
/* Table of counts. */
st = get_symbol("LPBX2");
FmtAssert (st != NULL, ("Symbol LPBX2 should have generated before"));
if ( ST_is_not_used(st) ){
Clear_ST_is_not_used(st);
Allocate_Object(st);
}
TY_IDX tyi;
TY& ty = New_TY(tyi);
TY_Init(ty, n_instr_edges*8, KIND_STRUCT, MTYPE_M,
STR_IDX_ZERO);
Set_TY_align(tyi, Is_Target_32bit() ? 4 : 32);
ST* new_st = New_ST(GLOBAL_SYMTAB);
ST_Init(new_st, Save_Str("LPBX2_TMP"),
CLASS_VAR, SCLASS_PSTATIC, EXPORT_LOCAL, tyi);
Allocate_Object(new_st);
INITO_IDX inito_lpbx2 = New_INITO(st);
INITV_IDX initv_lpbx2;
initv_lpbx2 = New_INITV();
INITV_Init_Symoff(initv_lpbx2, new_st, 0);
Append_INITV(initv_lpbx2, inito_lpbx2, INITV_IDX_ZERO);
inv = New_INITV();
INITV_Init_Symoff(inv, new_st, 0);
last_aggregate_initv = Append_INITV(inv, INITO_IDX_ZERO, last_aggregate_initv);
/* Count of the # of instrumented arcs */
inv = New_INITV();
INITV_Init_Integer(inv, rtype, n_instr_edges);
last_aggregate_initv = Append_INITV(inv, INITO_IDX_ZERO, last_aggregate_initv
);
/* Pointer to the next bb. */
inv = New_INITV();
INITV_Init_Integer(inv, rtype, 0);
last_aggregate_initv = Append_INITV(inv, INITO_IDX_ZERO, last_aggregate_initv);
/* sizeof(struct bb) */
inv = New_INITV();
INITV_Init_Integer(inv, rtype, 7*ty_size);
last_aggregate_initv = Append_INITV(inv, INITO_IDX_ZERO, last_aggregate_initv);
/* struct bb_function []. */
UINT32 checksum_size = ty_size;
UINT32 n_arcs_size = 4;
UINT32 func_name_size = ty_size;
UINT32 function_info_size = checksum_size + n_arcs_size*(Is_Target_32bit()?1:2) + func_name_size;
TY_IDX tyi_function;
TY& ty_function = New_TY(tyi_function);
TY_Init(ty_function, function_info_size * (num_nodes + 1), KIND_STRUCT, MTYPE_M,
STR_IDX_ZERO);
Set_TY_align(tyi_function, ty_size);
ST *func_infos = New_ST(GLOBAL_SYMTAB);
ST_Init(func_infos, Save_Str("function_infos"), CLASS_VAR, SCLASS_FSTATIC, EXPORT_LOCAL, tyi_function);
Set_ST_is_initialized(func_infos);
CG_Init_Func_Infos(func_infos);
Allocate_Object(func_infos);
inv = New_INITV();
INITV_Init_Symoff(inv, func_infos, 0);
last_aggregate_initv = Append_INITV(inv, INITO_IDX_ZERO, last_aggregate_initv);
#endif
}
void
CG_Compute_Checksum ()
{
#define CHSUM_HASH 500000003
#define CHSUM_SHIFT 2
if (!Cur_PU_Name || strncmp(Cur_PU_Name, "_GLOBAL__GCOV_", strlen("_GLOBAL__GCOV_"))==0)
return;
local_n_edges = 0;
local_n_a_edges = 0;
local_n_basic_blocks = 0;
chksum = 0;
BB* bb;
for (bb = REGION_First_BB; bb; bb = BB_next(bb)) {
BBLIST* bb_succs = BB_succs( bb );
if (!bb_succs) {
local_n_a_edges ++;
local_n_basic_blocks++;
chksum = ((chksum==0?1:chksum) << CHSUM_SHIFT) % CHSUM_HASH;
continue;
}
BBLIST *succ;
FOR_ALL_BBLIST_ITEMS(bb_succs, succ){
#ifdef GCC_303
unsigned value = BB_TO_GCOV_INDEX (BBLIST_item(succ));
unsigned ix;
value ^= value << 16;
value ^= value << 8;
for (ix = 8; ix--; value <<= 1)
{
unsigned feedback;
feedback = (value ^ chksum) & 0x80000000 ? 0x04c11db7 : 0;
chksum <<= 1;
chksum ^= feedback;
}
#else
chksum = ((chksum << CHSUM_SHIFT) + (BB_TO_GCOV_INDEX (BBLIST_item(succ)) + 1)) % CHSUM_HASH;
#endif
// if (BB_Fall_Thru_Successor(bb) == BBLIST_item(succ))
if (!BBLIST_on_tree(succ))
local_n_edges ++;
local_n_a_edges ++;
chksum = (chksum << CHSUM_SHIFT) % CHSUM_HASH;
}
//if (bb_succs)
local_n_basic_blocks++;
}
struct function_list *new_item = (struct function_list *)CXX_NEW_ARRAY(char, sizeof (struct function_list), name_pool_ptr);
*functions_tail = new_item;
functions_tail = &new_item->next;
new_item->next = 0;
new_item->name = CXX_NEW_ARRAY(char, strlen(Cur_PU_Name)+1, name_pool_ptr);
strcpy (new_item->name, Cur_PU_Name);
new_item->cfg_checksum = chksum;
#ifdef GCC_303
new_item->n_counter_sections = 1;
new_item->counter_sections[0].n_counters = local_n_edges;
new_item->counter_sections[0].tag = GCOV_TAG_ARC_COUNTS;
#else
new_item->count_edges = local_n_edges+1;
n_instr_edges += local_n_edges+1;
#endif
//return chksum;
}
/* Union find algorithm implementation for the basic blocks using
aux fields. */
static BB*
find_group (BB* bb)
{
BB* group = bb, *bb1;
while (group != NULL && BB_aux(group) != group)
group = BB_aux(group);
/* Compress path. */
while (bb && group && BB_aux(bb) != group)
{
bb1 = BB_aux(bb);
BB_aux(bb) = group;
bb = bb1;
}
return group;
}
static void
union_groups (BB* bb1, BB* bb2)
{
BB* bb1g = find_group (bb1);
BB* bb2g = find_group (bb2);
FmtAssert (bb1g != bb2g, ("Two group should be in one spanning tree"));
if (bb1g)
BB_aux(bb1g) = bb2g;
else
BB_aux(bb2g) = bb1g;
}
static BOOL EDGE_CRITICAL_P(BB* src, BB *dest)
{
BBLIST* bb_succs = BB_succs( src );
BBLIST* bb_preds = BB_preds( dest );
return ( (BBlist_Len(bb_succs) > 1) && (BBlist_Len(bb_preds) > 1) );
}
/* This function searches all of the edges in the program flow graph, and puts
as many bad edges as possible onto the spanning tree. Bad edges include
abnormals edges, which can't be instrumented at the moment. Since it is
possible for fake edges to form a cycle, we will have to develop some
better way in the future. Also put critical edges to the tree, since they
are more expensive to instrument. */
static void
find_spanning_tree()
{
BBLIST* bb_succs;
BBLIST *succ;
BB *bb;
for (bb = REGION_First_BB; bb; bb = BB_next(bb))
{
if (BB_entry(bb) || BB_call(bb) || BB_exit(bb))
BB_aux(bb) = NULL;
else
BB_aux(bb) = bb;
}
for (bb = REGION_First_BB; bb; bb = BB_next(bb))
{
bb_succs = BB_succs( bb );
if (!bb_succs) continue;
FOR_ALL_BBLIST_ITEMS(bb_succs, succ){
if (EDGE_CRITICAL_P (bb, BBLIST_item(succ)) && find_group (bb) != find_group (BBLIST_item(succ))){
Set_BBLIST_on_tree(succ);
Set_BBLIST_on_tree(BB_Find_Pred(BBLIST_item(succ), bb));
union_groups (bb, BBLIST_item(succ));
}
}
}
for (bb = REGION_First_BB; bb; bb = BB_next(bb))
{
bb_succs = BB_succs( bb );
if (!bb_succs) continue;
FOR_ALL_BBLIST_ITEMS(bb_succs, succ){
if (find_group (bb) != find_group (BBLIST_item(succ))){
Set_BBLIST_on_tree(succ);
Set_BBLIST_on_tree(BB_Find_Pred(BBLIST_item(succ), bb));
union_groups (bb, BBLIST_item(succ));
}
}
}
}
#ifndef GCC_303
static void
output_gcov_string (
const char *string,
long delimiter)
{
size_t temp;
/* Write a delimiter to indicate that a file name follows. */
__write_long (delimiter, bb_file, 4);
/* Write the string. */
temp = strlen (string) + 1;
fwrite (string, temp, 1, bb_file);
/* Append a few zeros, to align the output to a 4 byte boundary. */
temp = temp & 0x3;
if (temp)
{
char c[4];
c[0] = c[1] = c[2] = c[3] = 0;
fwrite (c, sizeof (char), 4 - temp, bb_file);
}
/* Store another delimiter in the .bb file, just to make it easy to find
the end of the file name. */
__write_long (delimiter, bb_file, 4);
}
#endif
/* Perform file-level initialization for gcov processing. */
void
CG_Init_Gcov ()
{
char *base_name = lbasename(Src_File_Name);
int len = strlen (base_name);
int i;
name_pool_ptr = &name_pool;
MEM_POOL_Initialize (name_pool_ptr, "Names", FALSE);
MEM_POOL_Push (name_pool_ptr);
if (flag_test_coverage == FALSE)
return;
last_bb_file_num = -1;
bbg_file_name = CXX_NEW_ARRAY(char, len + strlen (GCOV_GRAPH_SUFFIX) + 1, name_pool_ptr);
strcpy (bbg_file_name, base_name);
for (i = len + strlen (GCOV_GRAPH_SUFFIX); i>0; i--)
if (bbg_file_name[i] == '.')
break;
FmtAssert (bbg_file_name[i] == '.', ("Src_File_Name should associate with the prefix"));
bbg_file_name[i] = 0;
strcat (bbg_file_name, GCOV_GRAPH_SUFFIX);
bbg_file = fopen (bbg_file_name, "wb");
if (!bbg_file)
FmtAssert (bbg_file != 0, ("Gcov Error: can't open %s", bbg_file_name));
#ifdef GCC_303
if (gcov_write_unsigned (bbg_file, GCOV_GRAPH_MAGIC)
|| gcov_write_unsigned (bbg_file, GCOV_VERSION))
{
fclose (bbg_file);
FmtAssert (0, ("cannot write `%s'", bbg_file_name));
}
#else
char* data_file = CXX_NEW_ARRAY(char, len + 4, name_pool_ptr);
strcpy (data_file, base_name);
for (i = len + 3; i>0; i--)
if (data_file[i] == '.')
break;
FmtAssert (data_file[i] == '.', ("Src_File_Name should associate with the prefix"));
data_file[i] = 0;
strcat (data_file, ".bb");
if ((bb_file = fopen (data_file, "wb")) == 0)
FmtAssert (bb_file != 0, ("Gcov Error: can't open %s", data_file));
#endif
}
/* Performs file-level cleanup after branch-prob processing
is completed. */
void
CG_End_Gcov ()
{
if (name_pool_ptr != NULL) {
MEM_POOL_Pop (name_pool_ptr);
MEM_POOL_Delete (name_pool_ptr);
name_pool_ptr = NULL;
}
if (flag_test_coverage == FALSE)
return;
fclose (bbg_file);
#ifndef GCC_303
fclose (bb_file);
#endif
}
void
CG_Gcov_Generation ()
{
long offset;
const char *name = Cur_PU_Name;
int i;
const char *fname = NULL;
const char *dname;
int cur_bb_file_num, cur_bb_line_num;
BBLIST* bb_succs;
BBLIST *succ;
BB *bb;
OP *op;
if (!Cur_PU_Name || strncmp(Cur_PU_Name, "_GLOBAL__GCOV_", strlen("_GLOBAL__GCOV_"))==0)
return;
find_spanning_tree();
CG_Compute_Checksum();
last_bb_line_num = -1;
if (flag_test_coverage == FALSE)
return;
#ifdef GCC_303
/* Announce function */
if (gcov_write_unsigned (bbg_file, GCOV_TAG_FUNCTION)
|| !(offset = gcov_reserve_length (bbg_file))
|| gcov_write_string (bbg_file, name,
strlen (name))
|| gcov_write_unsigned (bbg_file,
chksum)
|| gcov_write_length (bbg_file, offset))
goto bbg_error;
/* Basic block flags */
if (gcov_write_unsigned (bbg_file, GCOV_TAG_BLOCKS)
|| !(offset = gcov_reserve_length (bbg_file)))
goto bbg_error;
for (i = 0; i != (unsigned) (local_n_basic_blocks); i++)
if (gcov_write_unsigned (bbg_file, 0))
goto bbg_error;
if (gcov_write_length (bbg_file, offset))
goto bbg_error;
/* Arcs */
for (bb = REGION_First_BB; bb; bb = BB_next(bb))
{
bb_succs = BB_succs( bb );
if (!bb_succs) continue;
if (gcov_write_unsigned (bbg_file, GCOV_TAG_ARCS)
|| !(offset = gcov_reserve_length (bbg_file))
|| gcov_write_unsigned (bbg_file, BB_TO_GCOV_INDEX (bb)))
goto bbg_error;
FOR_ALL_BBLIST_ITEMS(bb_succs, succ){
unsigned flag_bits = 0;
if (BB_Fall_Thru_Successor(bb) == BBLIST_item(succ))
flag_bits |= GCOV_ARC_FALLTHROUGH;
else
flag_bits |= GCOV_ARC_ON_TREE;
if (gcov_write_unsigned (bbg_file, BB_TO_GCOV_INDEX (BBLIST_item(succ)))
|| gcov_write_unsigned (bbg_file, flag_bits))
goto bbg_error;
}
if (gcov_write_length (bbg_file, offset))
goto bbg_error;
}
/* Output line number information about each basic block for
GCOV utility. */
for (bb = REGION_First_BB; bb; bb = BB_next(bb)) {
offset = 0;
for (op = BB_first_op(bb); op != NULL; op = OP_next(op)){
cur_bb_file_num = SRCPOS_filenum(OP_srcpos(op));
cur_bb_line_num = Srcpos_To_Line(OP_srcpos(op));
/* If this is a new source file, then output the
file's name to the .bb file. */
if (last_bb_file_num == -1 || cur_bb_file_num != last_bb_file_num){
IR_Srcpos_Filename(OP_srcpos(op), &fname, &dname);
if (fname == NULL)
continue;
if (offset)
;
else if (gcov_write_unsigned (bbg_file, GCOV_TAG_LINES)
|| !(offset = gcov_reserve_length (bbg_file))
|| gcov_write_unsigned (bbg_file,
BB_TO_GCOV_INDEX (bb)))
goto bbg_error;
last_bb_file_num = cur_bb_file_num;
last_bb_line_num = -1;
if (gcov_write_unsigned (bbg_file, 0)
|| gcov_write_string (bbg_file, fname,
strlen (fname)))
goto bbg_error;
}
else if (last_bb_line_num == -1 || cur_bb_line_num != last_bb_line_num){
if (offset)
;
else if (gcov_write_unsigned (bbg_file, GCOV_TAG_LINES)
|| !(offset = gcov_reserve_length (bbg_file))
|| gcov_write_unsigned (bbg_file,
BB_TO_GCOV_INDEX (bb)))
goto bbg_error;
}
if (last_bb_line_num == -1 || cur_bb_line_num != last_bb_line_num){
last_bb_line_num = cur_bb_line_num;
if (gcov_write_unsigned (bbg_file, cur_bb_line_num))
goto bbg_error;
}
}
if (offset)
{
if (gcov_write_unsigned (bbg_file, 0)
|| gcov_write_string (bbg_file, NULL, 0)
|| gcov_write_length (bbg_file, offset))
{
bbg_error:;
FmtAssert(0, ("error writing `%s'", bbg_file_name));
fclose (bbg_file);
bbg_file = NULL;
}
}
}
#else
/* Start of a function. */
output_gcov_string (name, (long) -2);
/* Output line number information about each basic block for
GCOV utility. */
for (BB* bb = REGION_First_BB; bb; bb = BB_next(bb)) {
/* Output a zero to the .bb file to indicate that a new
block list is starting. */
//BOOL first_time = TRUE;
__write_long (0, bb_file, 4);
for (OP* op = BB_first_op(bb); op != NULL; op = OP_next(op)){
cur_bb_file_num = SRCPOS_filenum(OP_srcpos(op));
cur_bb_line_num = Srcpos_To_Line(OP_srcpos(op));
if (!cur_bb_line_num)
continue;
/* If this is a new source file, then output the
file's name to the .bb file. */
if (last_bb_file_num == -1 || cur_bb_file_num != last_bb_file_num){
IR_Srcpos_Filename(OP_srcpos(op), &fname, &dname);
if (fname == NULL)
continue;
last_bb_file_num = cur_bb_file_num;
last_bb_line_num = -1;
//if (first_time == TRUE){
// __write_long (0, bb_file, 4);
// first_time = FALSE;
//}
output_gcov_string (fname,
(long)-1);
}
if (last_bb_line_num == -1 || cur_bb_line_num != last_bb_line_num){
last_bb_line_num = cur_bb_line_num;
//if (first_time == TRUE){
// __write_long (0, bb_file, 4);
// first_time = FALSE;
//}
__write_long (cur_bb_line_num, bb_file, 4);
}
}
}
__write_long (0, bb_file, 4);
/* Create a .bbg file from which gcov can reconstruct the basic block
graph. First output the number of basic blocks, and then for every
edge output the source and target basic block numbers.
NOTE: The format of this file must be compatible with gcov. */
int flag_bits;
__write_gcov_string (name, strlen (name), bbg_file, -1);
/* write checksum. */
__write_long (chksum, bbg_file, 4);
/* The plus 2 stands for entry and exit block. */
__write_long (local_n_basic_blocks+2, bbg_file, 4);
__write_long (local_n_a_edges+2, bbg_file, 4);
__write_long (1, bbg_file, 4);
__write_long (BB_TO_GCOV_INDEX (REGION_First_BB), bbg_file, 4);
__write_long (0x4, bbg_file, 4);
for (BB* bb = REGION_First_BB; bb; bb = BB_next(bb)) {
BBLIST* bb_succs = BB_succs( bb );
long count = BBlist_Len( bb_succs );
if (count == 0){
__write_long (1, bbg_file, 4);
__write_long (0, bbg_file, 4);
__write_long (0x1, bbg_file, 4);
continue;
}
__write_long (count, bbg_file, 4);
BBLIST *succ;
FOR_ALL_BBLIST_ITEMS(bb_succs, succ){
flag_bits = 0;
if (BBLIST_on_tree(succ))
flag_bits |= 0x1;
else if (BB_Fall_Thru_Successor(bb) == BBLIST_item(succ))
flag_bits |= 0x4;
__write_long (BB_TO_GCOV_INDEX (BBLIST_item(succ)), bbg_file, 4);
__write_long (flag_bits, bbg_file, 4);
}
}
/* Emit fake loopback edge for EXIT block to maintain compatibility with
old gcov format. */
__write_long (1, bbg_file, 4);
__write_long (0, bbg_file, 4);
__write_long (0x1, bbg_file, 4);
/* Emit a -1 to separate the list of all edges from the list of
loop back edges that follows. */
__write_long (-1, bbg_file, 4);
#endif
}
static BOOL
Opnd_Tn_In_BB( BB* bb, REGISTER reg, unsigned char type )
{
OP* opcode = bb->ops.first;
int i;
for( ; opcode != NULL; opcode = OP_next( opcode ) )
{
for ( i = 0; i < OP_opnds( opcode ); i++ )
{
TN *tn = OP_opnd( opcode,i );
if ( type == 0 && TN_register_class(tn) == ISA_REGISTER_CLASS_integer && TN_register(tn) == reg )
return TRUE;
else if ( type == 1 && TN_register_class(tn) == ISA_REGISTER_CLASS_float && TN_register(tn) == reg )
return TRUE;
}
}
return FALSE;
}
// Return the sum of the procedure return register in BB bb
static INT32
Get_Return_Reg_Sum(BB* bb)
{
#ifdef TARG_X8664
if ( Opnd_Tn_In_BB( bb, RDX, 0 ) )
return 2;
if ( Opnd_Tn_In_BB( bb, RAX, 0 ) )
return 1;
#endif
return 0;
}
// return the sum of the procedure return float register in BB bb
static INT32
Get_Float_Return_Reg_Sum(BB* bb)
{
#ifdef TARG_X8664
for ( int i = 1 ; i >= 0; i-- )
{
if ( Opnd_Tn_In_BB( bb,XMM0 + i, 1) )
return i + 1;
}
#endif
return 0;
}
static BOOL
Is_BB_Empty (BB *bb)
{
for (OP *op = BB_first_op(bb); op != NULL; op = OP_next(op)) {
if (OP_Real_Ops(op) != 0) return FALSE;
}
return TRUE;
}
static void
BB_Mov_Ops(BB* dest_bb, BB *src_bb, REGISTER reg, unsigned char type)
{
int i;
for (OP* op = BB_first_op(src_bb); op != NULL; op = OP_next(op))
{
for ( i = 0; i < OP_opnds( op ); i++ )
{
TN *tn = OP_opnd( op,i );
if ( ((type == 0 && TN_register_class(tn) == ISA_REGISTER_CLASS_integer) || (type == 1 && TN_register_class(tn) == ISA_REGISTER_CLASS_float)) &&
TN_register(tn) == reg )
{
BB_Remove_Op( src_bb, op);
FmtAssert( !Is_BB_Empty(src_bb), ("BB can not be empty!"));
BB_Prepend_Op (dest_bb, op);
return;
}
}
}
}
static void
Move_Save_Regs_OP(BB *instr_bb, BB *bb, INT32 ret_reg_num, INT32 f_ret_reg_num)
{
#ifdef TARG_X8664
FmtAssert (ret_reg_num == 0 || f_ret_reg_num == 0, ("cannot be both integer and floating point at the same time"));
if (ret_reg_num){
BB_Mov_Ops(instr_bb, bb, RAX, 0);
ret_reg_num --;
if (ret_reg_num){
BB_Mov_Ops(instr_bb, bb, RDX, 0);
}
}
else if (f_ret_reg_num){
int i = 0;
while ( i<f_ret_reg_num ){
BB_Mov_Ops(instr_bb, bb, XMM0+i++, 1);
}
}
#endif
}
static void
Process_Arc_Profile_Region_Options ( void )
{
OPTION_LIST *ol;
for ( ol = Arc_Profile_Region; ol != NULL; ol = OLIST_next(ol) ) {
if ( strcmp ( OLIST_opt(ol), "profile_proc" ) == 0 )
if ( strcmp (Cur_PU_Name, OLIST_val(ol) ) ==0 )
pu_flag = 1;
else
pu_flag = 0;
if ( strcmp ( OLIST_opt(ol), "profile_id1" ) == 0 )
begin_id = atoi ( OLIST_val (ol) );
if ( strcmp ( OLIST_opt(ol), "profile_id2" ) == 0 )
end_id = atoi ( OLIST_val (ol) );
}
}
static BOOL
Indirect_Branch(BB *bb)
{
OP *br_op = BB_branch_op(bb);
if (br_op) {
INT tfirst, tcount;
CGTARG_Branch_Info(br_op, &tfirst, &tcount);
if (tcount == 0)
return TRUE;
}
return FALSE;
}
static BOOL
BB_Is_Unique_Instr_Predecessor(BB *src, BB *dest)
{
if (BB_Is_Unique_Predecessor(src, dest))
return TRUE;
int instr_count = 0;
BBLIST* edge;
FOR_ALL_BB_PREDS(src, edge) {
if (!BBLIST_on_tree(edge))
instr_count ++;
}
if (instr_count > 1){
int instr_count_for_indirect_branch = 0;
FOR_ALL_BB_PREDS(src, edge) {
BB* bb_pred = BBLIST_item(edge);
if (!BBLIST_on_tree(edge) && Indirect_Branch(bb_pred))
instr_count_for_indirect_branch++;
}
FmtAssert(instr_count_for_indirect_branch <= 1, ("one indirect branch and one direct branch going to the same basic block need to be instrumented?"));
//return FALSE;
if (instr_count_for_indirect_branch == 1){
if (Indirect_Branch(dest))
return TRUE;
else
return FALSE;
}
else
return FALSE;
}
else
return TRUE;
}
void
CG_Instrument_Arcs()
{
if (!Cur_PU_Name || strncmp(Cur_PU_Name, "_GLOBAL__GCOV_", strlen("_GLOBAL__GCOV_"))==0) return;
ST *st = get_symbol("LPBX2");
if (st == NULL){
st = New_ST(GLOBAL_SYMTAB);
char* func_name = TYPE_MEM_POOL_ALLOC_N(char, name_pool_ptr, strlen("LPBX2") + strlen(lbasename(Src_File_Name)) + 1);
sprintf(func_name, "%s%s", "LPBX2", lbasename(Src_File_Name));
for(INT i = 0; func_name[i]; i++){
if( !( func_name[i] == '_'
|| ('0' <= func_name[i] && func_name[i] <= '9')
|| ('A' <= func_name[i] && func_name[i] <= 'Z')
|| ('a' <= func_name[i] && func_name[i] <= 'z')) )
func_name[i] = '_';
}
ST_Init(st, Save_Str(func_name),
CLASS_VAR, SCLASS_PSTATIC, EXPORT_PREEMPTIBLE, MTYPE_To_TY(Pointer_type));
Set_ST_is_initialized(st);
Set_ST_is_not_used(st);
}
Process_Arc_Profile_Region_Options ();
if (pu_flag == 0) return;
static int count = 0;
BBLIST *bb_succs;
BBLIST *succ;
BB *bb_succ;
BB *bb;
OP *op;
OPS new_ops;
TN *ld_result_tn;
TN *ld_2nd_result_tn;
TN *const_tn;
TN *result_tn;
TYPE_ID rtype;
if (Is_Target_32bit())
rtype = MTYPE_U4;
else
rtype = MTYPE_U8;
if ((begin_id == -1 && end_id == -1) || (begin_id <= count && count <= end_id)) {
OPS_Init(&new_ops);
ld_result_tn = Build_TN_Of_Mtype(rtype);
Exp_Load (rtype, rtype, ld_result_tn, st, 0, &new_ops, 0);
ld_2nd_result_tn = Build_TN_Of_Mtype(rtype);
#if defined(TARG_MIPS) || defined(TARG_X8664) || defined(TARG_PPC32)
Expand_Load( OPCODE_make_op (OPR_LDID, rtype, rtype),ld_2nd_result_tn, ld_result_tn, Gen_Literal_TN(count*8,4), &new_ops);
#else
Expand_Load( OPCODE_make_op (OPR_LDID, rtype, rtype),ld_2nd_result_tn, ld_result_tn, Gen_Literal_TN(count*8,4), (VARIANT)0, &new_ops);
#endif
const_tn = Gen_Literal_TN(1,4);
result_tn = Build_TN_Of_Mtype(rtype);
Exp_OP2 (OPC_U4ADD, result_tn, ld_2nd_result_tn, const_tn, &new_ops);
#if defined(TARG_MIPS) || defined(TARG_PPC32)
Expand_Store (OPCODE_desc(OPCODE_make_op(OPR_STID, MTYPE_V, rtype)),result_tn, ld_result_tn, Gen_Literal_TN(count*8,4), &new_ops);
#else
Expand_Store (OPCODE_desc(OPCODE_make_op(OPR_STID, MTYPE_V, rtype)),result_tn, ld_result_tn, Gen_Literal_TN(count*8,4), (VARIANT)0, &new_ops);
#endif
Gcov_BB_Prepend_Ops(REGION_First_BB, &new_ops);
}
count++;
BB *exit_bb = NULL;
for (bb = REGION_First_BB; bb; bb = BB_next(bb)){
if (BB_exit(bb))
exit_bb = bb;
}
// Bug 456
if (!exit_bb){
exit_bb = REGION_First_BB;
while (BB_next(exit_bb)) exit_bb = BB_next(exit_bb);
}
FmtAssert(exit_bb, ("exit bb should exist!"));
for (bb = REGION_First_BB; bb; bb = BB_next(bb))
{
bb_succs = BB_succs( bb );
if (!bb_succs) continue;
BBLIST *succ;
BBLIST *old_succ;
for (succ = bb_succs; succ!= NULL; succ = old_succ)
{
old_succ = BBLIST_next(succ);
bb_succ = BBLIST_item(succ);
if (!BBLIST_on_tree(succ))
{
if (begin_id != -1 && end_id != -1 && (begin_id > count || count > end_id)){
count ++;
continue;
}
OPS_Init(&new_ops);
ld_result_tn = Build_TN_Of_Mtype(rtype);
Exp_Load (rtype, rtype, ld_result_tn, st, 0, &new_ops, 0);
ld_2nd_result_tn = Build_TN_Of_Mtype(rtype);
#if defined(TARG_MIPS) || defined(TARG_X8664) || defined(TARG_PPC32)
Expand_Load( OPCODE_make_op (OPR_LDID, rtype, rtype),ld_2nd_result_tn, ld_result_tn, Gen_Literal_TN(count*8,4), &new_ops);
#else
Expand_Load( OPCODE_make_op (OPR_LDID, rtype, rtype),ld_2nd_result_tn, ld_result_tn, Gen_Literal_TN(count*8,4), (VARIANT)0, &new_ops);
#endif
const_tn = Gen_Literal_TN(1,4);
result_tn = Build_TN_Of_Mtype(rtype);
Exp_OP2 (OPC_U4ADD, result_tn, ld_2nd_result_tn, const_tn, &new_ops);
#if defined(TARG_MIPS) || defined(TARG_SL) || defined(TARG_PPC32)
Expand_Store (OPCODE_desc(OPCODE_make_op(OPR_STID, MTYPE_V, rtype)),result_tn, ld_result_tn, Gen_Literal_TN(count*8,4), &new_ops);
#else
Expand_Store (OPCODE_desc(OPCODE_make_op(OPR_STID, MTYPE_V, rtype)),result_tn, ld_result_tn, Gen_Literal_TN(count*8,4), (VARIANT)0, &new_ops);
#endif
if (BB_Is_Unique_Instr_Predecessor(bb_succ, bb))
{
Gcov_BB_Prepend_Ops(bb_succ, &new_ops);
count ++;
continue;
}
BB* instr_bb;
if (BB_Fall_Thru_Successor(bb) == bb_succ)
instr_bb = Gen_And_Insert_BB_After(bb);
else{
instr_bb = Gen_And_Insert_BB_After(exit_bb);
LABEL_IDX new_label = Gen_Label_For_BB(instr_bb);
OP *branch_op = BB_branch_op (bb);
INT tn_num = OP_opnds( branch_op );
TN* tgt_tn;
for( int i = 0; i<tn_num; i++ )
{
tgt_tn = OP_opnd( branch_op, i );
if( TN_is_label( tgt_tn ) )
{
Set_TN_label( tgt_tn, new_label );
break;
}
}
// tgt_label is the branch target bb's label
LABEL_IDX tgt_label;
tgt_label = Gen_Label_For_BB( bb_succ );
#ifdef TARG_X8664
Build_OP( TOP_jmp, Gen_Label_TN(tgt_label, 0), &new_ops);
#elif defined(TARG_PPC32)
Build_OP( TOP_ba, Gen_Label_TN(tgt_label, 0), &new_ops);
#elif TARG_MIPS
// mips
Build_OP( TOP_j, Gen_Label_TN(tgt_label, 0), &new_ops);
#else
#ifndef TARG_LOONGSON
// ia64
Build_OP (TOP_br, Gen_Enum_TN(ECV_ph_few), Gen_Enum_TN(ECV_dh), Gen_Label_TN(tgt_label, 0), &new_ops);
#endif
#endif
FmtAssert(TN_is_label( tgt_tn ), ("should be branch target label"));
}
Gcov_BB_Prepend_Ops(instr_bb, &new_ops);
if (BB_call( bb )){
int ret_reg_num = Get_Return_Reg_Sum( bb_succ );
int f_ret_reg_num = Get_Float_Return_Reg_Sum( bb_succ );
Move_Save_Regs_OP(instr_bb, bb_succ, ret_reg_num, f_ret_reg_num);
}
Unlink_Pred_Succ(bb, bb_succ);
Link_Pred_Succ(bb, instr_bb);
Set_BBLIST_on_tree( BBlist_Add_BB (&BB_succs(bb), instr_bb) );
Set_BBLIST_on_tree( BBlist_Add_BB (&BB_preds(instr_bb), bb) );
Link_Pred_Succ(instr_bb, bb_succ);
Set_BBLIST_on_tree( BBlist_Add_BB (&BB_succs(instr_bb), bb_succ) );
Set_BBLIST_on_tree( BBlist_Add_BB (&BB_preds(bb_succ), instr_bb) );
count++;
}
}
}
}
| 32.051873
| 157
| 0.643926
|
sharugupta
|
1138121df23dfd5b47c877a9c29c7a122eb27c78
| 9,554
|
cpp
|
C++
|
gen/blink/bindings/core/v8/V8SVGPoint.cpp
|
gergul/MiniBlink
|
7a11c52f141d54d5f8e1a9af31867cd120a2c3c4
|
[
"Apache-2.0"
] | 8
|
2019-05-05T16:38:05.000Z
|
2021-11-09T11:45:38.000Z
|
gen/blink/bindings/core/v8/V8SVGPoint.cpp
|
gergul/MiniBlink
|
7a11c52f141d54d5f8e1a9af31867cd120a2c3c4
|
[
"Apache-2.0"
] | null | null | null |
gen/blink/bindings/core/v8/V8SVGPoint.cpp
|
gergul/MiniBlink
|
7a11c52f141d54d5f8e1a9af31867cd120a2c3c4
|
[
"Apache-2.0"
] | 4
|
2018-12-14T07:52:46.000Z
|
2021-06-11T18:06:09.000Z
|
// 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.
// This file has been auto-generated by code_generator_v8.py. DO NOT MODIFY!
#include "config.h"
#include "V8SVGPoint.h"
#include "bindings/core/v8/ExceptionState.h"
#include "bindings/core/v8/V8DOMConfiguration.h"
#include "bindings/core/v8/V8ObjectConstructor.h"
#include "bindings/core/v8/V8SVGElement.h"
#include "bindings/core/v8/V8SVGMatrix.h"
#include "bindings/core/v8/V8SVGPoint.h"
#include "core/dom/ContextFeatures.h"
#include "core/dom/Document.h"
#include "core/frame/UseCounter.h"
#include "platform/RuntimeEnabledFeatures.h"
#include "platform/TraceEvent.h"
#include "wtf/GetPtr.h"
#include "wtf/RefPtr.h"
namespace blink {
// Suppress warning: global constructors, because struct WrapperTypeInfo is trivial
// and does not depend on another global objects.
#if defined(COMPONENT_BUILD) && defined(WIN32) && COMPILER(CLANG)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wglobal-constructors"
#endif
const WrapperTypeInfo V8SVGPoint::wrapperTypeInfo = { gin::kEmbedderBlink, V8SVGPoint::domTemplate, V8SVGPoint::refObject, V8SVGPoint::derefObject, V8SVGPoint::trace, 0, V8SVGPoint::visitDOMWrapper, V8SVGPoint::preparePrototypeObject, V8SVGPoint::installConditionallyEnabledProperties, "SVGPoint", 0, WrapperTypeInfo::WrapperTypeObjectPrototype, WrapperTypeInfo::ObjectClassId, WrapperTypeInfo::NotInheritFromEventTarget, WrapperTypeInfo::Dependent, WrapperTypeInfo::WillBeGarbageCollectedObject };
#if defined(COMPONENT_BUILD) && defined(WIN32) && COMPILER(CLANG)
#pragma clang diagnostic pop
#endif
// This static member must be declared by DEFINE_WRAPPERTYPEINFO in SVGPointTearOff.h.
// For details, see the comment of DEFINE_WRAPPERTYPEINFO in
// bindings/core/v8/ScriptWrappable.h.
const WrapperTypeInfo& SVGPointTearOff::s_wrapperTypeInfo = V8SVGPoint::wrapperTypeInfo;
namespace SVGPointTearOffV8Internal {
static void xAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
SVGPointTearOff* impl = V8SVGPoint::toImpl(holder);
v8SetReturnValue(info, impl->x());
}
static void xAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMGetter");
SVGPointTearOffV8Internal::xAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void xAttributeSetter(v8::Local<v8::Value> v8Value, const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
ExceptionState exceptionState(ExceptionState::SetterContext, "x", "SVGPoint", holder, info.GetIsolate());
SVGPointTearOff* impl = V8SVGPoint::toImpl(holder);
float cppValue = toFloat(info.GetIsolate(), v8Value, exceptionState);
if (exceptionState.throwIfNeeded())
return;
impl->setX(cppValue, exceptionState);
exceptionState.throwIfNeeded();
}
static void xAttributeSetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Value> v8Value = info[0];
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMSetter");
SVGPointTearOffV8Internal::xAttributeSetter(v8Value, info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void yAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
SVGPointTearOff* impl = V8SVGPoint::toImpl(holder);
v8SetReturnValue(info, impl->y());
}
static void yAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMGetter");
SVGPointTearOffV8Internal::yAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void yAttributeSetter(v8::Local<v8::Value> v8Value, const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
ExceptionState exceptionState(ExceptionState::SetterContext, "y", "SVGPoint", holder, info.GetIsolate());
SVGPointTearOff* impl = V8SVGPoint::toImpl(holder);
float cppValue = toFloat(info.GetIsolate(), v8Value, exceptionState);
if (exceptionState.throwIfNeeded())
return;
impl->setY(cppValue, exceptionState);
exceptionState.throwIfNeeded();
}
static void yAttributeSetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Value> v8Value = info[0];
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMSetter");
SVGPointTearOffV8Internal::yAttributeSetter(v8Value, info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void matrixTransformMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
if (UNLIKELY(info.Length() < 1)) {
V8ThrowException::throwException(createMinimumArityTypeErrorForMethod(info.GetIsolate(), "matrixTransform", "SVGPoint", 1, info.Length()), info.GetIsolate());
return;
}
SVGPointTearOff* impl = V8SVGPoint::toImpl(info.Holder());
SVGMatrixTearOff* matrix;
{
matrix = V8SVGMatrix::toImplWithTypeCheck(info.GetIsolate(), info[0]);
if (!matrix) {
V8ThrowException::throwTypeError(info.GetIsolate(), ExceptionMessages::failedToExecute("matrixTransform", "SVGPoint", "parameter 1 is not of type 'SVGMatrix'."));
return;
}
}
v8SetReturnValue(info, impl->matrixTransform(matrix));
}
static void matrixTransformMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMMethod");
UseCounter::countIfNotPrivateScript(info.GetIsolate(), callingExecutionContext(info.GetIsolate()), UseCounter::SVGPointMatrixTransform);
SVGPointTearOffV8Internal::matrixTransformMethod(info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
} // namespace SVGPointTearOffV8Internal
void V8SVGPoint::visitDOMWrapper(v8::Isolate* isolate, ScriptWrappable* scriptWrappable, const v8::Persistent<v8::Object>& wrapper)
{
SVGPointTearOff* impl = scriptWrappable->toImpl<SVGPointTearOff>();
v8::Local<v8::Object> creationContext = v8::Local<v8::Object>::New(isolate, wrapper);
V8WrapperInstantiationScope scope(creationContext, isolate);
SVGElement* contextElement = impl->contextElement();
if (contextElement) {
if (DOMDataStore::containsWrapper(contextElement, isolate))
DOMDataStore::setWrapperReference(wrapper, contextElement, isolate);
}
}
static const V8DOMConfiguration::AccessorConfiguration V8SVGPointAccessors[] = {
{"x", SVGPointTearOffV8Internal::xAttributeGetterCallback, SVGPointTearOffV8Internal::xAttributeSetterCallback, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder},
{"y", SVGPointTearOffV8Internal::yAttributeGetterCallback, SVGPointTearOffV8Internal::yAttributeSetterCallback, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder},
};
static const V8DOMConfiguration::MethodConfiguration V8SVGPointMethods[] = {
{"matrixTransform", SVGPointTearOffV8Internal::matrixTransformMethodCallback, 0, 1, V8DOMConfiguration::ExposedToAllScripts},
};
static void installV8SVGPointTemplate(v8::Local<v8::FunctionTemplate> functionTemplate, v8::Isolate* isolate)
{
functionTemplate->ReadOnlyPrototype();
v8::Local<v8::Signature> defaultSignature;
defaultSignature = V8DOMConfiguration::installDOMClassTemplate(isolate, functionTemplate, "SVGPoint", v8::Local<v8::FunctionTemplate>(), V8SVGPoint::internalFieldCount,
0, 0,
V8SVGPointAccessors, WTF_ARRAY_LENGTH(V8SVGPointAccessors),
V8SVGPointMethods, WTF_ARRAY_LENGTH(V8SVGPointMethods));
v8::Local<v8::ObjectTemplate> instanceTemplate = functionTemplate->InstanceTemplate();
ALLOW_UNUSED_LOCAL(instanceTemplate);
v8::Local<v8::ObjectTemplate> prototypeTemplate = functionTemplate->PrototypeTemplate();
ALLOW_UNUSED_LOCAL(prototypeTemplate);
// Custom toString template
functionTemplate->Set(v8AtomicString(isolate, "toString"), V8PerIsolateData::from(isolate)->toStringTemplate());
}
v8::Local<v8::FunctionTemplate> V8SVGPoint::domTemplate(v8::Isolate* isolate)
{
return V8DOMConfiguration::domClassTemplate(isolate, const_cast<WrapperTypeInfo*>(&wrapperTypeInfo), installV8SVGPointTemplate);
}
bool V8SVGPoint::hasInstance(v8::Local<v8::Value> v8Value, v8::Isolate* isolate)
{
return V8PerIsolateData::from(isolate)->hasInstance(&wrapperTypeInfo, v8Value);
}
v8::Local<v8::Object> V8SVGPoint::findInstanceInPrototypeChain(v8::Local<v8::Value> v8Value, v8::Isolate* isolate)
{
return V8PerIsolateData::from(isolate)->findInstanceInPrototypeChain(&wrapperTypeInfo, v8Value);
}
SVGPointTearOff* V8SVGPoint::toImplWithTypeCheck(v8::Isolate* isolate, v8::Local<v8::Value> value)
{
return hasInstance(value, isolate) ? toImpl(v8::Local<v8::Object>::Cast(value)) : 0;
}
void V8SVGPoint::refObject(ScriptWrappable* scriptWrappable)
{
#if !ENABLE(OILPAN)
scriptWrappable->toImpl<SVGPointTearOff>()->ref();
#endif
}
void V8SVGPoint::derefObject(ScriptWrappable* scriptWrappable)
{
#if !ENABLE(OILPAN)
scriptWrappable->toImpl<SVGPointTearOff>()->deref();
#endif
}
} // namespace blink
| 44.64486
| 498
| 0.765648
|
gergul
|
113d5adb558d92606bc6c637a25bcbc19a7f655e
| 2,432
|
cpp
|
C++
|
surfer_girl.cpp
|
Pumpkrin/surfer_girl
|
98af7692fd81b8fc4e11c85af43adc5d0b951874
|
[
"MIT"
] | null | null | null |
surfer_girl.cpp
|
Pumpkrin/surfer_girl
|
98af7692fd81b8fc4e11c85af43adc5d0b951874
|
[
"MIT"
] | null | null | null |
surfer_girl.cpp
|
Pumpkrin/surfer_girl
|
98af7692fd81b8fc4e11c85af43adc5d0b951874
|
[
"MIT"
] | null | null | null |
#include "utilities.hpp"
#include <iostream>
int main( int argc, char* argv[] ) {
std::string input_file, output_file{"output.root"};
if(argc < 3){ std::cerr << "surfer_girl should be called the following way: ./surfer_girl -in input_file.bin [-out output_file.root] \n"; return 1; }
else{
for(auto i{0}; i < argc; ++i) {
if( std::string( argv[i] ) == "-in" ){ input_file = std::string{ argv[++i] }; }
if( std::string( argv[i] ) == "-out") { output_file = std::string{ argv[++i]}; }
}
}
std::cout << "processing: " << input_file << '\n';
std::cout << "outputing_to: " << output_file << '\n';
auto source = sf_g::data_input< std::ifstream >{ input_file };
auto const metadata = sf_g::reader<std::ifstream, sf_g::metadata>{}( source );
std::cout << "metadata: " << metadata.channel_count << " - " << metadata.sampling_period << "\n";
auto const event_reader = sf_g::reader< std::ifstream, sf_g::event_data>{};
auto const waveform_reader = sf_g::reader< std::ifstream, sf_g::raw_waveform>{metadata.channel_count};
//add event id somewhere ? -> cross check with the waveforms
auto const m = sf_g::raw_modifier{metadata};
sf_g::data_output< TTree > sink{ output_file };
auto w = sf_g::raw_writer{ sink, metadata.channel_count };
while( !source.end_is_reached() ){
// for( auto j{event_reader( source );0} ; j < 1; ++j) {
event_reader( source );
// auto timing = event_reader( source );
// std::cout << "event: ";
// std::cout << timing.event_id << " -- ";
// std::cout << timing.epoch_time << " -- ";
// std::cout << timing.time.second << " - " << timing.time.millisecond << " -- ";
// std::cout << "tdc: " << timing.tdc << " - " << corrected_tdc << '\n';
// auto data = waveform_reader( source );
// std::cout << "channel: " << data[0].channel_id << " -- " << data[0].event_id << " -- " << data[0].fcr << " -- " << data[0].baseline << " -- " << data[0].amplitude << " -- " << data[0].charge << " -- " << data[0].leading_edge << " -- " << data[0].trailing_edge << " -- " << data[0].rate_counter << '\n';
// for( auto i{0}; i < 1024 ; ++i){
// std::cout << data[0].sample_c[i] << " ";
// }
// std::cout << '\n';
// m( std::move(data) ) | w;
waveform_reader( source) | m | w ;
}
}
| 47.686275
| 314
| 0.537418
|
Pumpkrin
|
113e4356f349715de74c426ca8529f1b3fdbfae2
| 5,286
|
ipp
|
C++
|
ecl/hqlcpp/hqlnlp.ipp
|
oxhead/HPCC-Platform
|
62e092695542a9bbea1bb3672f0d1ff572666cfc
|
[
"Apache-2.0"
] | null | null | null |
ecl/hqlcpp/hqlnlp.ipp
|
oxhead/HPCC-Platform
|
62e092695542a9bbea1bb3672f0d1ff572666cfc
|
[
"Apache-2.0"
] | 1
|
2018-03-01T18:15:12.000Z
|
2018-03-01T18:15:12.000Z
|
ecl/hqlcpp/hqlnlp.ipp
|
JamesDeFabia/HPCC-Platform
|
e10caebb70ea7aabbdef762683a78b146ec060bb
|
[
"Apache-2.0"
] | null | null | null |
/*##############################################################################
HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems®.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
############################################################################## */
#ifndef __HQLNLP_IPP_
#define __HQLNLP_IPP_
#include "thorparse.ipp"
#include "thorregex.hpp"
#include "thorralgo.ipp"
#include "hqlhtcpp.ipp"
//---------------------------------------------------------------------------
#define NO_DFA_SCORE ((unsigned)-1)
typedef MapBetween<LinkedHqlExpr, IHqlExpression *, regexid_t, regexid_t> RegexIdMapping;
class RegexIdAllocator
{
public:
RegexIdAllocator() { nextId = 0; }
regexid_t queryID(IHqlExpression * expr, IAtom * name);
void setID(IHqlExpression * expr, IAtom * name, regexid_t id);
protected:
IHqlExpression * createKey(IHqlExpression * expr, IAtom * name);
protected:
unsigned nextId;
RegexIdMapping map;
};
struct LengthLimit
{
LengthLimit() { minLength = 0; maxLength = PATTERN_UNLIMITED_LENGTH; containsAssertion = false; }
bool canBeNull() { return (minLength == 0) && !containsAssertion; }
unsigned minLength;
unsigned maxLength;
bool containsAssertion;
};
struct ParseInformation;
class MatchReference : public CInterface
{
public:
MatchReference(IHqlExpression * expr);
void compileMatched(RegexIdAllocator & idAllocator, UnsignedArray & ids, UnsignedArray & indexValues);
bool equals(const MatchReference & _other) const;
StringBuffer & getDebugText(StringBuffer & out, RegexIdAllocator & idAllocator);
void getPath(StringBuffer & path);
protected:
void expand(IHqlExpression * expr, bool isLast);
public:
HqlExprArray names;
HqlExprArray indices;
};
struct ParseInformation
{
public:
NlpInputFormat inputFormat() const
{
switch (type)
{
case type_string: return NlpAscii;
case type_utf8: return NlpUtf8;
case type_unicode: return NlpUnicode;
}
throwUnexpected();
}
public:
OwnedHqlExpr separator;
unsigned charSize;
type_t type;
bool caseSensitive;
bool expandRepeatAnyAsDfa;
unsigned dfaComplexity;
bool addedSeparators;
unsigned dfaRepeatMax;
unsigned dfaRepeatMaxScore;
unique_id_t uidBase;
};
class NlpParseContext : public CInterface
{
public:
NlpParseContext(IHqlExpression * _expr, IWorkUnit * _wu, const HqlCppOptions & options, ITimeReporter * _timeReporter);
void addAllMatched();
virtual unsigned addMatchReference(IHqlExpression * expr);
void buildProductions(HqlCppTranslator & translator, BuildCtx & classctx, BuildCtx & startctx);
void buildValidators(HqlCppTranslator & translator, BuildCtx & classctx);
void extractValidates(IHqlExpression * expr);
bool isMatched(IHqlExpression * expr, IAtom * name);
virtual void compileSearchPattern() = 0;
virtual void getDebugText(StringBuffer & s, unsigned detail) = 0;
virtual bool isGrammarAmbiguous() const = 0;
virtual INlpParseAlgorithm * queryParser() = 0;
bool isCaseSensitive() const { return info.caseSensitive; }
type_t searchType() const { return info.type; }
IWorkUnit * wu() { return workunit; }
protected:
void checkValidMatches();
void compileMatched(NlpAlgorithm & parser);
void extractMatchedSymbols(IHqlExpression * expr);
bool isValidMatch(MatchReference & match, unsigned depth, IHqlExpression * pattern);
unsigned getValidatorIndex(IHqlExpression * expr) const { return validators.find(*expr); }
IHqlExpression * queryValidateExpr(IHqlExpression * expr) const;
void setParserOptions(INlpParseAlgorithm & parser);
private:
void doExtractValidates(IHqlExpression * expr);
protected:
ParseInformation info;
OwnedHqlExpr expr;
CIArrayOf<MatchReference> matches;
RegexIdAllocator idAllocator;
HqlExprArray matchedSymbols;
HqlExprArray productions;
HqlExprArray validators;
bool allMatched;
IWorkUnit * workunit;
Linked<ITimeReporter> timeReporter;
};
void getCheckRange(IHqlExpression * range, unsigned & minLength, unsigned & maxLength, unsigned charLength);
enum ValidateKind { ValidateIsString, ValidateIsUnicode, ValidateIsEither };
ValidateKind getValidateKind(IHqlExpression * expr);
NlpParseContext * createRegexContext(IHqlExpression * expr, IWorkUnit * wu, const HqlCppOptions & options, ITimeReporter * timeReporter, byte algorithm);
NlpParseContext * createTomitaContext(IHqlExpression * expr, IWorkUnit * wu, const HqlCppOptions & options, ITimeReporter * timeReporter);
#endif
| 33.245283
| 153
| 0.687476
|
oxhead
|
113f43d43969ab16774b09d5392cde68ab36d1a3
| 45,758
|
cpp
|
C++
|
core/src/Spirit/IO.cpp
|
MSallermann/spirit
|
d3b771bcbf2f1eb4b28d48899091c17a48f12c67
|
[
"MIT"
] | 46
|
2020-08-24T22:40:15.000Z
|
2022-02-28T06:54:54.000Z
|
core/src/Spirit/IO.cpp
|
MSallermann/spirit
|
d3b771bcbf2f1eb4b28d48899091c17a48f12c67
|
[
"MIT"
] | null | null | null |
core/src/Spirit/IO.cpp
|
MSallermann/spirit
|
d3b771bcbf2f1eb4b28d48899091c17a48f12c67
|
[
"MIT"
] | 4
|
2020-09-05T13:24:41.000Z
|
2021-11-06T07:46:47.000Z
|
#include <Spirit/State.h>
#include <Spirit/IO.h>
#include <Spirit/Chain.h>
#include <Spirit/Configurations.h>
#include <data/State.hpp>
#include <data/Spin_System.hpp>
#include <data/Spin_System_Chain.hpp>
#include <io/IO.hpp>
#include <io/Filter_File_Handle.hpp>
#include <io/OVF_File.hpp>
#include <utility/Logging.hpp>
#include <utility/Version.hpp>
#include <utility/Exception.hpp>
#include <fmt/format.h>
#include <memory>
#include <string>
// helper function
std::string Get_Extension( const char *file )
{
std::string filename(file);
std::string::size_type n = filename.rfind('.');
if ( n != std::string::npos ) return filename.substr(n);
else return std::string("");
}
/*----------------------------------------------------------------------------------------------- */
/*--------------------------------- From Config File -------------------------------------------- */
/*----------------------------------------------------------------------------------------------- */
int IO_System_From_Config(State * state, const char * file, int idx_image, int idx_chain) noexcept
try
{
std::shared_ptr<Data::Spin_System> image;
std::shared_ptr<Data::Spin_System_Chain> chain;
// Fetch correct indices and pointers
from_indices( state, idx_image, idx_chain, image, chain );
// Create System (and lock it)
std::shared_ptr<Data::Spin_System> system = IO::Spin_System_from_Config(std::string(file));
system->Lock();
// Filter for unacceptable differences to other systems in the chain
for (int i = 0; i < chain->noi; ++i)
{
if (chain->images[i]->nos != system->nos) return 0;
// Currently the SettingsWidget does not support different images being isotropic AND
// anisotropic at the same time
if (chain->images[i]->hamiltonian->Name() != system->hamiltonian->Name())
return 0;
}
// Set System
image->Lock();
try
{
*image = *system;
}
catch( ... )
{
spirit_handle_exception_api(idx_image, idx_chain);
}
image->Unlock();
// Initial configuration
float defaultPos[3] = {0,0,0};
float defaultRect[3] = {-1,-1,-1};
Configuration_Random(state, defaultPos, defaultRect, -1, -1, false, false, idx_image, idx_chain);
// Return success
return 1;
}
catch( ... )
{
spirit_handle_exception_api(idx_image, idx_chain);
return 0;
}
/*----------------------------------------------------------------------------------------------- */
/*------------------------------------- Geometry ------------------------------------------------ */
/*----------------------------------------------------------------------------------------------- */
void IO_Positions_Write( State * state, const char *filename, int format,
const char *comment, int idx_image, int idx_chain ) noexcept
try
{
std::shared_ptr<Data::Spin_System> image;
std::shared_ptr<Data::Spin_System_Chain> chain;
// Fetch correct indices and pointers
from_indices( state, idx_image, idx_chain, image, chain );
// Write the data
image->Lock();
try
{
if( Get_Extension(filename) != ".ovf" )
Log( Utility::Log_Level::Warning, Utility::Log_Sender::API, fmt::format(
"The file \"{}\" is written in OVF format but has different extension. "
"It is recommend to use the appropriate \".ovf\" extension", filename ),
idx_image, idx_chain );
// helper variables
auto& geometry = *image->geometry;
auto fileformat = (IO::VF_FileFormat)format;
switch( fileformat )
{
case IO::VF_FileFormat::OVF_BIN:
case IO::VF_FileFormat::OVF_BIN4:
case IO::VF_FileFormat::OVF_BIN8:
case IO::VF_FileFormat::OVF_TEXT:
case IO::VF_FileFormat::OVF_CSV:
{
auto segment = IO::OVF_Segment(*image);
auto& spins = *image->spins;
std::string title = fmt::format( "SPIRIT Version {}", Utility::version_full );
segment.title = strdup(title.c_str());
segment.comment = strdup(comment);
segment.valuedim = 3;
segment.valuelabels = strdup("position_x position_y position_z");
segment.valueunits = strdup("none none none");
// open and write
IO::OVF_File(filename).write_segment(segment, geometry.positions[0].data(), format);
Log( Utility::Log_Level::Info, Utility::Log_Sender::API, fmt::format(
"Wrote positions to file \"{}\" with format {}", filename, format ),
idx_image, idx_chain );
break;
}
default:
{
spirit_throw( Utility::Exception_Classifier::Bad_File_Content, Utility::Log_Level::Error,
fmt::format( "Invalid file format {}", format ) );
}
}
}
catch( ... )
{
spirit_handle_exception_api(idx_image, idx_chain);
}
image->Unlock();
}
catch( ... )
{
spirit_handle_exception_api(idx_image, idx_chain);
}
/*----------------------------------------------------------------------------------------------- */
/*-------------------------------------- Images ------------------------------------------------- */
/*----------------------------------------------------------------------------------------------- */
int IO_N_Images_In_File( State * state, const char *filename, int idx_image, int idx_chain ) noexcept
try
{
auto file = IO::OVF_File(filename);
if( file.is_ovf )
return file.n_segments;
else
{
Log( Utility::Log_Level::Warning, Utility::Log_Sender::API, fmt::format(
"File \"{}\" is not OVF. Cannot measure number of images.", filename ),
idx_image, idx_chain );
return -1;
}
}
catch( ... )
{
spirit_handle_exception_api( idx_image, idx_chain );
return -1;
}
void IO_Image_Read( State *state, const char *filename, int idx_image_infile,
int idx_image_inchain, int idx_chain ) noexcept
try
{
std::shared_ptr<Data::Spin_System> image;
std::shared_ptr<Data::Spin_System_Chain> chain;
// Fetch correct indices and pointers
from_indices( state, idx_image_inchain, idx_chain, image, chain );
image->Lock();
try
{
const std::string extension = Get_Extension( filename );
// helper variables
auto& spins = *image->spins;
auto& geometry = *image->geometry;
// open
auto file = IO::OVF_File(filename, true);
if( !file.is_ovf )
{
Log( Utility::Log_Level::Error, Utility::Log_Sender::API, fmt::format(
"File \"{}\" does not seem to be in valid OVF format. Message: {}. "
"Will try to read as data column text format file.",
filename, file.latest_message()), idx_image_inchain, idx_chain );
IO::Read_NonOVF_Spin_Configuration( spins, geometry, image->nos, idx_image_infile, filename );
image->Unlock();
return;
}
// segment header
auto segment = IO::OVF_Segment();
// read header
file.read_segment_header(idx_image_infile, segment);
////////////////////////////////////////////////////////
// TODO: CHECK GEOMETRY AND WARN IF IT DOES NOT MATCH //
////////////////////////////////////////////////////////
if( segment.N < image->nos )
{
Log( Utility::Log_Level::Warning, Utility::Log_Sender::API, fmt::format(
"OVF file \"{}\": segment {}/{} contains only {} spins while the system contains {}.",
filename, idx_image_infile+1, file.n_segments, segment.N, image->nos),
idx_image_inchain, idx_chain );
segment.N = std::min(segment.N, image->nos);
}
else if( segment.N > image->nos )
{
Log( Utility::Log_Level::Warning, Utility::Log_Sender::API, fmt::format(
"OVF file \"{}\": segment {}/{} contains {} spins while the system contains only {}. "
"Reading only part of the segment data.",
filename, idx_image_infile+1, file.n_segments, segment.N, image->nos),
idx_image_inchain, idx_chain );
segment.N = std::min(segment.N, image->nos);
}
if( segment.valuedim != 3 )
{
spirit_throw( Utility::Exception_Classifier::Bad_File_Content, Utility::Log_Level::Error,
fmt::format( "Segment {}/{} in OVF file \"{}\" should have 3 columns, but only has {}. Will not read.",
idx_image_infile+1, file.n_segments, filename, segment.valuedim ) );
}
// read data
file.read_segment_data(idx_image_infile, segment, spins[0].data());/*
vectorfield test=vectorfield(256*256*64, Vector3{ 0,0,0 });;
int shift = 64;
int transl = 16;
scalar rad = 70;
for (int i = 0; i < 128; i++) {
for (int j = 0; j < 128; j++) {
for (int k = 0; k < 64; k++) {
if (((i - 64 ) * (i - 64 ) + (j - 64 ) * (j - 64) < rad * rad))
test[i +transl+ (j+transl) * 256 + k * 256 * 256] = spins [i+ shift + (j+ shift) * 256 + k * 256 * 256];
}
}
}
for (int i = 0; i < 128; i++) {
for (int j = 0; j < 128; j++) {
for (int k = 0; k < 64; k++) {
if (((i-64)* (i - 64 )+ (j - 64)* (j - 64 )<rad*rad) )
test[256 - i - transl + (256 - j - transl) * 256 + k * 256 * 256] = spins[i + shift + (j + shift) * 256 + k * 256 * 256];
//if ((test[256 - i + (256 - j) * 256 + k * 256 * 256][3] < 0.9) && (spins[i + 48 + (j + 48) * 256 + k * 256 * 256][3] < 0.9))
//test[256-i-transl + (256-j-transl) * 256 + k * 256 * 256] = (test[256-i + (256-j) * 256 + k * 256 * 256] +spins[i + shift + (j + shift) * 256 + k * 256 * 256]).normalized();
}
}
}
for (int i = 0; i < 256; i++) {
for (int j = 0; j < 256; j++) {
for (int k = 0; k < 64; k++) {
spins[i + j * 256 + k * 256 * 256] = test[i + j * 256 + k * 256 * 256];
}
}
}*/
for( int ispin=0; ispin<spins.size(); ++ispin )
{
/* if( spins[ispin].norm() < 1e-5 )
{
spins[ispin] = {0, 0, 1};
// In case of spin vector close to zero we have a vacancy
#ifdef SPIRIT_ENABLE_DEFECTS
geometry.atom_types[ispin] = -1;
#endif
}
else
spins[ispin].normalize();*/
}
Log( Utility::Log_Level::Info, Utility::Log_Sender::API, fmt::format(
"Read image from file \"{}\"", filename ), idx_image_inchain, idx_chain );
}
catch( ... )
{
spirit_handle_exception_api(idx_image_inchain, idx_chain);
}
image->Unlock();
}
catch( ... )
{
spirit_handle_exception_api(idx_image_inchain, idx_chain);
}
void IO_Image_Write( State *state, const char *filename, int format, const char* comment,
int idx_image, int idx_chain ) noexcept
try
{
std::shared_ptr<Data::Spin_System> image;
std::shared_ptr<Data::Spin_System_Chain> chain;
// Fetch correct indices and pointers
from_indices( state, idx_image, idx_chain, image, chain );
// Write the data
image->Lock();
try
{
if( Get_Extension(filename) != ".ovf" )
Log( Utility::Log_Level::Warning, Utility::Log_Sender::API, fmt::format(
"The file \"{}\" is written in OVF format but has different extension. "
"It is recommend to use the appropriate \".ovf\" extension", filename ),
idx_image, idx_chain );
switch( (IO::VF_FileFormat)format )
{
case IO::VF_FileFormat::OVF_BIN:
case IO::VF_FileFormat::OVF_BIN4:
case IO::VF_FileFormat::OVF_BIN8:
case IO::VF_FileFormat::OVF_TEXT:
case IO::VF_FileFormat::OVF_CSV:
{
auto segment = IO::OVF_Segment(*image);
auto& spins = *image->spins;
std::string title = fmt::format( "SPIRIT Version {}", Utility::version_full );
segment.title = strdup(title.c_str());
segment.comment = strdup(comment);
segment.valuedim = 3;
segment.valuelabels = strdup("spin_x spin_y spin_z");
segment.valueunits = strdup("none none none");
// open and write
IO::OVF_File(filename).write_segment(segment, spins[0].data(), format);
Log( Utility::Log_Level::Info, Utility::Log_Sender::API, fmt::format(
"Wrote spins to file \"{}\" with format {}", filename, format ),
idx_image, idx_chain );
break;
}
default:
{
spirit_throw( Utility::Exception_Classifier::Bad_File_Content, Utility::Log_Level::Error,
fmt::format( "Invalid file format {}", format ) );
}
}
}
catch( ... )
{
spirit_handle_exception_api(idx_image, idx_chain);
}
image->Unlock();
}
catch( ... )
{
spirit_handle_exception_api(idx_image, idx_chain);
}
void IO_Image_Append( State *state, const char *filename, int format, const char * comment,
int idx_image, int idx_chain ) noexcept
try
{
std::shared_ptr<Data::Spin_System> image;
std::shared_ptr<Data::Spin_System_Chain> chain;
// Fetch correct indices and pointers
from_indices( state, idx_image, idx_chain, image, chain );
// Write the data
image->Lock();
try
{
// helper variables
auto& spins = *image->spins;
auto fileformat = (IO::VF_FileFormat)format;
switch( fileformat )
{
case IO::VF_FileFormat::OVF_BIN:
case IO::VF_FileFormat::OVF_BIN4:
case IO::VF_FileFormat::OVF_BIN8:
case IO::VF_FileFormat::OVF_TEXT:
case IO::VF_FileFormat::OVF_CSV:
{
// open
auto file = IO::OVF_File(filename);
// check if the file was OVF
if( file.found && !file.is_ovf )
{
spirit_throw( Utility::Exception_Classifier::Bad_File_Content, Utility::Log_Level::Error,
fmt::format( "Cannot append to non-OVF file \"{}\"", filename ) );
}
auto segment = IO::OVF_Segment(*image);
auto& spins = *image->spins;
std::string title = fmt::format( "SPIRIT Version {}", Utility::version_full );
segment.title = strdup(title.c_str());
segment.comment = strdup(comment);
segment.valuedim = 3;
segment.valuelabels = strdup("spin_x spin_y spin_z");
segment.valueunits = strdup("none none none");
// write
file.append_segment(segment, spins[0].data(), int(fileformat));
break;
}
default:
{
spirit_throw( Utility::Exception_Classifier::Bad_File_Content, Utility::Log_Level::Error,
fmt::format( "Invalid file format {}", format ) );
}
}
Log( Utility::Log_Level::Info, Utility::Log_Sender::API, fmt::format(
"Appended spins to file \"{}\" with format {}", filename, format ), idx_image, idx_chain );
}
catch( ... )
{
spirit_handle_exception_api(idx_image, idx_chain);
}
image->Unlock();
}
catch( ... )
{
spirit_handle_exception_api(idx_image, idx_chain);
}
/*----------------------------------------------------------------------------------------------- */
/*-------------------------------------- Chains ------------------------------------------------- */
/*----------------------------------------------------------------------------------------------- */
void IO_Chain_Read( State *state, const char *filename, int start_image_infile,
int end_image_infile, int insert_idx, int idx_chain ) noexcept
try
{
std::shared_ptr<Data::Spin_System> image;
std::shared_ptr<Data::Spin_System_Chain> chain;
// Fetch correct indices and pointers
from_indices( state, insert_idx, idx_chain, image, chain );
chain->Lock();
bool success = false;
// Read the data
try
{
const std::string extension = Get_Extension( filename );
// helper variables
auto& images = chain->images;
int noi = chain->noi;
if (insert_idx < 0)
insert_idx = 0;
if( insert_idx > noi )
{
Log( Utility::Log_Level::Error, Utility::Log_Sender::API,
fmt::format( "IO_Chain_Read: Tried to start reading chain on invalid index"
"(insert_idx={}, but chain has {} images)", insert_idx, noi ),
insert_idx, idx_chain );
}
// open
IO::OVF_File file( filename, true );
if( file.is_ovf )
{
int noi_infile = file.n_segments;
if( start_image_infile < 0 )
start_image_infile = 0;
if( end_image_infile < 0 )
end_image_infile = noi_infile-1;
// Check if the ending image is valid otherwise set it to the last image infile
if( end_image_infile < start_image_infile ||
end_image_infile >= noi_infile )
{
Log( Utility::Log_Level::Warning, Utility::Log_Sender::API, fmt::format(
"IO_Chain_Read: specified invalid reading range (start_image_infile={}, end_image_infile={})."
" Set to read entire file \"{}\" ({} images).",
start_image_infile, end_image_infile, filename, noi_infile), insert_idx, idx_chain );
end_image_infile = noi_infile - 1;
}
if( start_image_infile >= noi_infile )
{
spirit_throw( Utility::Exception_Classifier::Bad_File_Content, Utility::Log_Level::Error,
fmt::format( "Specified starting index {}, but file \"{}\" contains only {} images.",
start_image_infile, filename, noi_infile ) );
}
// If the idx of the starting image is valid
int noi_to_read = end_image_infile - start_image_infile + 1;
int noi_to_add = noi_to_read - ( noi - insert_idx );
// Add the images if you need that
if( noi_to_add > 0 )
{
chain->Unlock();
Chain_Image_to_Clipboard( state, noi-1 );
Chain_Set_Length(state, noi+noi_to_add);
chain->Lock();
}
// Read the images
for( int i=insert_idx; i<noi_to_read; i++ )
{
auto& spins = *images[i]->spins;
auto& geometry = *images[i]->geometry;
// segment header
auto segment = IO::OVF_Segment();
// read header
file.read_segment_header(start_image_infile, segment);
////////////////////////////////////////////////////////
// TODO: CHECK GEOMETRY AND WARN IF IT DOES NOT MATCH //
////////////////////////////////////////////////////////
if( segment.N < image->nos )
{
Log( Utility::Log_Level::Warning, Utility::Log_Sender::API, fmt::format(
"OVF file \"{}\": segment {}/{} contains only {} spins while the system contains {}.",
filename, start_image_infile+1, file.n_segments, segment.N, image->nos),
i, idx_chain );
segment.N = std::min(segment.N, image->nos);
}
else if( segment.N > image->nos )
{
Log( Utility::Log_Level::Warning, Utility::Log_Sender::API, fmt::format(
"OVF file \"{}\": segment {}/{} contains {} spins while the system contains only {}. "
"Reading only part of the segment data.",
filename, start_image_infile+1, file.n_segments, segment.N, image->nos),
i, idx_chain );
segment.N = std::min(segment.N, image->nos);
}
if( segment.valuedim != 3 )
{
spirit_throw( Utility::Exception_Classifier::Bad_File_Content, Utility::Log_Level::Error,
fmt::format( "Segment {}/{} in OVF file \"{}\" should have 3 columns, but only has {}. Will not read.",
start_image_infile+1, file.n_segments, filename, segment.valuedim ) );
}
// read data
file.read_segment_data(start_image_infile, segment, spins[0].data());
for( int ispin=0; ispin<spins.size(); ++ispin )
{
if( spins[ispin].norm() < 1e-5 )
{
spins[ispin] = {0, 0, 1};
// In case of spin vector close to zero we have a vacancy
#ifdef SPIRIT_ENABLE_DEFECTS
geometry.atom_types[ispin] = -1;
#endif
}
else
spins[ispin].normalize();
}
start_image_infile++;
}
success = true;
}
else
{
Log( Utility::Log_Level::Warning, Utility::Log_Sender::API,
fmt::format( "IO_Chain_Read: File \"{}\" seems to not be OVF. Trying to read column data", filename ),
insert_idx, idx_chain );
int noi_to_add = 0;
int noi_to_read = 0;
IO::Check_NonOVF_Chain_Configuration( chain, filename, start_image_infile,
end_image_infile, insert_idx, noi_to_add,
noi_to_read, idx_chain );
// Add the images if you need that
if( noi_to_add > 0 )
{
chain->Unlock();
Chain_Image_to_Clipboard( state, noi-1 );
Chain_Set_Length(state, noi+noi_to_add);
chain->Lock();
}
// Read the images
if( noi_to_read > 0 )
{
for (int i=insert_idx; i<noi_to_read; i++)
{
IO::Read_NonOVF_Spin_Configuration( *chain->images[i]->spins,
*chain->images[i]->geometry,
chain->images[i]->nos,
start_image_infile, filename );
start_image_infile++;
}
success = true;
}
}
}
catch( ... )
{
spirit_handle_exception_api(insert_idx, idx_chain);
}
chain->Unlock();
if( success )
{
// Update llg simulation information array size
for (int i=state->method_image.size(); i < chain->noi; ++i)
state->method_image.push_back( std::shared_ptr<Engine::Method>( ) );
// Update state
State_Update(state);
// Update array lengths
Chain_Setup_Data(state, idx_chain);
Log( Utility::Log_Level::Info, Utility::Log_Sender::API,
fmt::format( "IO_Chain_Read: Read chain from file \"{}\"", filename ), insert_idx, idx_chain );
}
}
catch( ... )
{
spirit_handle_exception_api(insert_idx, idx_chain);
}
void IO_Chain_Write( State *state, const char *filename, int format, const char* comment,
int idx_chain ) noexcept
try
{
int idx_image = 0;
std::shared_ptr<Data::Spin_System> image;
std::shared_ptr<Data::Spin_System_Chain> chain;
// Fetch correct indices and pointers
from_indices( state, idx_image, idx_chain, image, chain );
// Read the data
chain->Lock();
try
{
auto fileformat = (IO::VF_FileFormat)format;
switch( fileformat )
{
case IO::VF_FileFormat::OVF_BIN:
case IO::VF_FileFormat::OVF_BIN4:
case IO::VF_FileFormat::OVF_BIN8:
case IO::VF_FileFormat::OVF_TEXT:
case IO::VF_FileFormat::OVF_CSV:
{
auto& images = chain->images;
// open
auto file = IO::OVF_File(filename);
auto segment = IO::OVF_Segment(*image);
auto& spins = *image->spins;
std::string title = fmt::format( "SPIRIT Version {}", Utility::version_full );
segment.title = strdup(title.c_str());
segment.valuedim = 3;
segment.valuelabels = strdup("spin_x spin_y spin_z");
segment.valueunits = strdup("none none none");
std::string comment_str = "";
comment_str = fmt::format( "Image {} of {}. {}", 1, chain->noi, comment );
segment.comment = strdup(comment_str.c_str());
// write
file.write_segment(segment, spins[0].data(), int(fileformat));
for ( int i=1; i<chain->noi; i++ )
{
comment_str = fmt::format( "Image {} of {}. {}", i+1, chain->noi, comment );
segment.comment = strdup(comment_str.c_str());
file.append_segment(segment, (*images[i]->spins)[0].data(), int(fileformat));
}
break;
}
default:
{
spirit_throw( Utility::Exception_Classifier::Bad_File_Content, Utility::Log_Level::Error,
fmt::format( "Invalid file format {}", format ) );
}
}
Log( Utility::Log_Level::Info, Utility::Log_Sender::API, fmt::format(
"Wrote chain to file \"{}\" with format {}", filename, format),
idx_image, idx_chain );
}
catch( ... )
{
spirit_handle_exception_api(idx_image, idx_chain);
}
chain->Unlock();
}
catch( ... )
{
spirit_handle_exception_api(-1, idx_chain);
}
void IO_Chain_Append( State *state, const char *filename, int format, const char* comment,
int idx_chain ) noexcept
try
{
int idx_image = 0;
std::shared_ptr<Data::Spin_System> image;
std::shared_ptr<Data::Spin_System_Chain> chain;
// Fetch correct indices and pointers
from_indices( state, idx_image, idx_chain, image, chain );
// Read the data
chain->Lock();
try
{
auto fileformat = (IO::VF_FileFormat)format;
switch( fileformat )
{
case IO::VF_FileFormat::OVF_BIN:
case IO::VF_FileFormat::OVF_BIN4:
case IO::VF_FileFormat::OVF_BIN8:
case IO::VF_FileFormat::OVF_TEXT:
case IO::VF_FileFormat::OVF_CSV:
{
auto& images = chain->images;
// open
auto file = IO::OVF_File(filename);
// check if the file was OVF
if( file.found && !file.is_ovf )
{
spirit_throw( Utility::Exception_Classifier::Bad_File_Content, Utility::Log_Level::Error,
fmt::format( "Cannot append to non-OVF file \"{}\"", filename ) );
}
auto segment = IO::OVF_Segment(*image);
auto& spins = *image->spins;
std::string title = fmt::format( "SPIRIT Version {}", Utility::version_full );
segment.title = strdup(title.c_str());
segment.valuedim = 3;
segment.valuelabels = strdup("spin_x spin_y spin_z");
segment.valueunits = strdup("none none none");
std::string comment_str = "";
comment_str = fmt::format( "Image {} of {}. {}", 0, chain->noi, comment );
segment.comment = strdup(comment_str.c_str());
// write
for ( int i=0; i<chain->noi; i++ )
{
comment_str = fmt::format( "Image {} of {}. {}", i, chain->noi, comment );
segment.comment = strdup(comment_str.c_str());
file.write_segment(segment, (*images[i]->spins)[0].data(), int(fileformat));
}
break;
}
default:
{
spirit_throw( Utility::Exception_Classifier::Bad_File_Content, Utility::Log_Level::Error,
fmt::format( "Invalid file format {}", format ) );
}
}
Log( Utility::Log_Level::Info, Utility::Log_Sender::API, fmt::format(
"Wrote chain to file \"{}\" with format {}", filename, format),
idx_image, idx_chain );
}
catch( ... )
{
spirit_handle_exception_api(idx_image, idx_chain);
}
chain->Unlock();
}
catch( ... )
{
spirit_handle_exception_api(-1, idx_chain);
}
/*----------------------------------------------------------------------------------------------- */
/*--------------------------------------- Data -------------------------------------------------- */
/*----------------------------------------------------------------------------------------------- */
// Interactions Pairs
void IO_Image_Write_Neighbours_Exchange( State * state, const char * file,
int idx_image, int idx_chain ) noexcept
try
{
std::shared_ptr<Data::Spin_System> image;
std::shared_ptr<Data::Spin_System_Chain> chain;
// Fetch correct indices and pointers
from_indices( state, idx_image, idx_chain, image, chain );
// Write the data
IO::Write_Neighbours_Exchange( *image, std::string(file) );
}
catch( ... )
{
spirit_handle_exception_api(idx_image, idx_chain);
}
void IO_Image_Write_Neighbours_DMI( State * state, const char * file,
int idx_image, int idx_chain ) noexcept
try
{
std::shared_ptr<Data::Spin_System> image;
std::shared_ptr<Data::Spin_System_Chain> chain;
// Fetch correct indices and pointers
from_indices( state, idx_image, idx_chain, image, chain );
// Write the data
IO::Write_Neighbours_DMI( *image, std::string(file) );
}
catch( ... )
{
spirit_handle_exception_api(idx_image, idx_chain);
}
//IO_Energies_Spins_Save
void IO_Image_Write_Energy_per_Spin(State * state, const char * filename, int format, int idx_image, int idx_chain) noexcept
try
{
std::shared_ptr<Data::Spin_System> image;
std::shared_ptr<Data::Spin_System_Chain> chain;
// Fetch correct indices and pointers
from_indices( state, idx_image, idx_chain, image, chain );
// Write the data
image->Lock();
auto& system = *image;
auto& spins = *image->spins;
// Gather the data
std::vector<std::pair<std::string, scalarfield>> contributions_spins(0);
system.UpdateEnergy();
system.hamiltonian->Energy_Contributions_per_Spin(spins, contributions_spins);
int datasize = (1+contributions_spins.size())*system.nos;
scalarfield data(datasize, 0);
for( int ispin=0; ispin<system.nos; ++ispin )
{
scalar E_spin=0;
int j = 1;
for( auto& contribution : contributions_spins )
{
E_spin += contribution.second[ispin];
data[ispin+j] = contribution.second[ispin];
++j;
}
data[ispin] = E_spin;
}
try
{
if ( Get_Extension(filename) != ".ovf" )
Log( Utility::Log_Level::Warning, Utility::Log_Sender::API, fmt::format(
"The file \"{}\" is written in OVF format but has different extension. "
"It is recommend to use the appropriate \".ovf\" extension", filename ),
idx_image, idx_chain );
switch( (IO::VF_FileFormat)format )
{
case IO::VF_FileFormat::OVF_BIN:
case IO::VF_FileFormat::OVF_BIN4:
case IO::VF_FileFormat::OVF_BIN8:
case IO::VF_FileFormat::OVF_TEXT:
case IO::VF_FileFormat::OVF_CSV:
{
auto segment = IO::OVF_Segment(*image);
std::string title = fmt::format( "SPIRIT Version {}", Utility::version_full );
segment.title = strdup(title.c_str());
std::string comment = fmt::format("Energy per spin. Total={}meV", system.E);
for( auto& contribution : system.E_array )
comment += fmt::format(", {}={}meV", contribution.first, contribution.second);
segment.comment = strdup(comment.c_str());
segment.valuedim = 1 + system.E_array.size();
std::string valuelabels = "Total";
std::string valueunits = "meV";
for( auto& pair : system.E_array )
{
valuelabels += fmt::format(" {}", pair.first);
valueunits += " meV";
}
segment.valuelabels = strdup(valuelabels.c_str());
// open
auto file = IO::OVF_File(filename);
// write
file.write_segment(segment, data.data(), format);
Log( Utility::Log_Level::Info, Utility::Log_Sender::API, fmt::format(
"Wrote spins to file \"{}\" with format {}", filename, format ),
idx_image, idx_chain );
break;
}
default:
{
spirit_throw( Utility::Exception_Classifier::Bad_File_Content, Utility::Log_Level::Error,
fmt::format( "Invalid file format {}", format ) );
}
}
}
catch( ... )
{
spirit_handle_exception_api(idx_image, idx_chain);
}
image->Unlock();
}
catch( ... )
{
spirit_handle_exception_api(idx_image, idx_chain);
}
//IO_Energy_Spins_Save
void IO_Image_Write_Energy(State * state, const char * file, int idx_image, int idx_chain) noexcept
try
{
std::shared_ptr<Data::Spin_System> image;
std::shared_ptr<Data::Spin_System_Chain> chain;
// Fetch correct indices and pointers
from_indices( state, idx_image, idx_chain, image, chain );
// Write the data
IO::Write_Image_Energy(*image, std::string(file));
}
catch( ... )
{
spirit_handle_exception_api(idx_image, idx_chain);
}
//IO_Energies_Save
void IO_Chain_Write_Energies(State * state, const char * file, int idx_chain) noexcept
try
{
int idx_image = -1;
std::shared_ptr<Data::Spin_System> image;
std::shared_ptr<Data::Spin_System_Chain> chain;
// Fetch correct indices and pointers
from_indices( state, idx_image, idx_chain, image, chain );
// Write the data
IO::Write_Chain_Energies(*chain, idx_chain, std::string(file));
}
catch( ... )
{
spirit_handle_exception_api(-1, idx_chain);
}
//IO_Energies_Interpolated_Save
void IO_Chain_Write_Energies_Interpolated(State * state, const char * file, int idx_chain) noexcept
try
{
int idx_image = -1;
std::shared_ptr<Data::Spin_System> image;
std::shared_ptr<Data::Spin_System_Chain> chain;
// Fetch correct indices and pointers
from_indices( state, idx_image, idx_chain, image, chain );
// Write the data
IO::Write_Chain_Energies_Interpolated(*chain, std::string(file));
}
catch( ... )
{
spirit_handle_exception_api(-1, idx_chain);
}
/*----------------------------------------------------------------------------------------------- */
/*-------------------------------------- Eigenmodes --------------------------------------------- */
/*----------------------------------------------------------------------------------------------- */
void IO_Eigenmodes_Read( State *state, const char *filename, int idx_image_inchain, int idx_chain ) noexcept
try
{
std::shared_ptr<Data::Spin_System> image;
std::shared_ptr<Data::Spin_System_Chain> chain;
// Fetch correct indices and pointers
from_indices( state, idx_image_inchain, idx_chain, image, chain );
// Read the data
image->Lock();
try
{
const std::string extension = Get_Extension( filename );
// helper variables
auto& spins = *image->spins;
auto& geometry = *image->geometry;
// open
auto file = IO::OVF_File(filename, true);
if( !file.is_ovf )
{
spirit_throw( Utility::Exception_Classifier::Bad_File_Content, Utility::Log_Level::Error,
fmt::format( "IO_Eigenmodes_Read only supports the OVF file format, "
"but \"{}\" does not seem to be valid OVF format. Message: {}",
filename, file.latest_message() ) );
}
// If the modes buffer's size is not the same as the n_segments then resize
int n_eigenmodes = file.n_segments-1;
if( image->modes.size() != n_eigenmodes )
{
Log( Utility::Log_Level::Warning, Utility::Log_Sender::IO, fmt::format(
"Resizing eigenmode buffer because the number of modes in the OVF file ({}) "
"is greater than the buffer size ({})", n_eigenmodes, image->modes.size()) );
image->modes.resize( n_eigenmodes );
image->eigenvalues.resize( n_eigenmodes );
}
Log( Utility::Log_Level::Debug, Utility::Log_Sender::IO, fmt::format(
"Reading {} eigenmodes from file \"{}\"", n_eigenmodes, filename ) );
////////// read in the eigenvalues
// segment header
auto segment = IO::OVF_Segment();
// read header
file.read_segment_header(0, segment);
// check
if( segment.valuedim != 1 )
{
spirit_throw( Utility::Exception_Classifier::Bad_File_Content, Utility::Log_Level::Error,
fmt::format( "Eigenvalue segment of OVF file \"{}\" should have 1 column, but has {}. Will not read.",
filename, segment.valuedim ) );
}
// read data
file.read_segment_data(0, segment, image->eigenvalues.data());
////////// read in the eigenmodes
for( int idx=0; idx<n_eigenmodes; idx++ )
{
// if the mode buffer is created by resizing then it needs to be allocated
if( image->modes[idx] == NULL )
image->modes[idx] = std::shared_ptr<vectorfield>(
new vectorfield( spins.size(), Vector3{1,0,0} ));
// read header
file.read_segment_header(idx+1, segment);
////////////////////////////////////////////////////////
// TODO: CHECK GEOMETRY AND WARN IF IT DOES NOT MATCH //
////////////////////////////////////////////////////////
if( segment.N < image->nos )
{
Log( Utility::Log_Level::Warning, Utility::Log_Sender::API, fmt::format(
"OVF file \"{}\": segment {}/{} contains only {} vectors while the system contains {}.",
filename, idx+1, file.n_segments, segment.N, image->nos),
idx_image_inchain, idx_chain );
segment.N = std::min(segment.N, image->nos);
}
else if( segment.N > image->nos )
{
Log( Utility::Log_Level::Warning, Utility::Log_Sender::API, fmt::format(
"OVF file \"{}\": segment {}/{} contains {} vectors while the system contains only {}. "
"Reading only part of the segment data.",
filename, idx+1, file.n_segments, segment.N, image->nos),
idx_image_inchain, idx_chain );
segment.N = std::min(segment.N, image->nos);
}
if( segment.valuedim != 3 )
{
spirit_throw( Utility::Exception_Classifier::Bad_File_Content, Utility::Log_Level::Error,
fmt::format( "OVF file \"{}\" should have 3 columns, but only has {}. Will not read.",
filename, segment.valuedim ) );
}
// read data
file.read_segment_data(idx+1, segment, (*image->modes[idx])[0].data());
}
// if the modes vector was reseized adjust the n_modes value
if( image->modes.size() != image->ema_parameters->n_modes )
image->ema_parameters->n_modes = image->modes.size();
// print the first eigenvalues
int n_log_eigenvalues = ( n_eigenmodes > 50 ) ? 50 : n_eigenmodes;
Log( Utility::Log_Level::Info, Utility::Log_Sender::IO, fmt::format(
"The first {} eigenvalues are: {}", n_log_eigenvalues,
fmt::join( image->eigenvalues.begin(), image->eigenvalues.begin() + n_log_eigenvalues, ", " ) ) );
}
catch( ... )
{
spirit_handle_exception_api(idx_image_inchain, idx_chain);
}
image->Unlock();
}
catch( ... )
{
spirit_handle_exception_api(idx_image_inchain, idx_chain);
}
void IO_Eigenmodes_Write( State *state, const char *filename, int format, const char* comment,
int idx_image, int idx_chain ) noexcept
try
{
std::shared_ptr<Data::Spin_System> image;
std::shared_ptr<Data::Spin_System_Chain> chain;
// Fetch correct indices and pointers
from_indices( state, idx_image, idx_chain, image, chain );
// Write the data
image->Lock();
try
{
if( Get_Extension(filename) != ".ovf" )
Log( Utility::Log_Level::Warning, Utility::Log_Sender::API, fmt::format(
"The file \"{}\" is written in OVF format but has different extension. "
"It is recommend to use the appropriate \".ovf\" extension", filename ),
idx_image, idx_chain );
switch( (IO::VF_FileFormat)format )
{
case IO::VF_FileFormat::OVF_BIN:
case IO::VF_FileFormat::OVF_BIN4:
case IO::VF_FileFormat::OVF_BIN8:
case IO::VF_FileFormat::OVF_TEXT:
case IO::VF_FileFormat::OVF_CSV:
{
auto& spins = *image->spins;
auto segment = IO::OVF_Segment(*image);
std::string title = fmt::format( "SPIRIT Version {}", Utility::version_full );
segment.title = strdup(title.c_str());
// Determine number of modes
int n_modes=0;
for( int i=0; i<image->modes.size(); i++ )
if( image->modes[i] != NULL )
++n_modes;
// open
auto file = IO::OVF_File(filename);
/////// Eigenspectrum
std::string comment_str = fmt::format("{}\n# Desc: eigenspectrum of {} eigenmodes", comment, n_modes);
segment.comment = strdup(comment_str.c_str());
segment.valuedim = 1;
segment.valuelabels = strdup("eigenvalue");
segment.valueunits = strdup("meV");
segment.meshunit = strdup("none");
segment.n_cells[0] = n_modes;
segment.n_cells[1] = 1;
segment.n_cells[2] = 1;
segment.N = n_modes;
segment.step_size[0] = 0;
segment.step_size[1] = 0;
segment.step_size[2] = 0;
segment.bounds_max[0] = 0;
segment.bounds_max[1] = 0;
segment.bounds_max[2] = 0;
// write
file.write_segment(segment, image->eigenvalues.data(), format);
/////// Eigenmodes
segment = IO::OVF_Segment(*image);
segment.valuedim = 3;
segment.valuelabels = strdup("mode_x mode_y mode_z");
segment.valueunits = strdup("none none none");
for( int i=0; i<n_modes; i++ )
{
std::string comment_str = fmt::format( "{}\n# Desc: eigenmode {}/{}, eigenvalue = {}",
comment, i+1, n_modes, image->eigenvalues[i]);
segment.comment = strdup(comment_str.c_str());
// write
file.append_segment(segment, (*image->modes[i])[0].data(), format);
}
Log( Utility::Log_Level::Info, Utility::Log_Sender::API, fmt::format(
"Wrote eigenmodes to file \"{}\" with format {}", filename, format ),
idx_image, idx_chain );
break;
}
default:
{
spirit_throw( Utility::Exception_Classifier::Bad_File_Content, Utility::Log_Level::Error,
fmt::format( "Invalid file format {}", format ) );
}
}
}
catch( ... )
{
spirit_handle_exception_api(idx_image, idx_chain);
}
image->Unlock();
}
catch( ... )
{
spirit_handle_exception_api(idx_image, idx_chain);
}
| 36.489633
| 203
| 0.517199
|
MSallermann
|
113f60037f9820c2f83d61170ba789b0413b3774
| 9,617
|
cpp
|
C++
|
irohad/consensus/yac/impl/yac_gate_impl.cpp
|
akshatkarani/iroha
|
5acef9dd74720c6185360d951e9b11be4ef73260
|
[
"Apache-2.0"
] | 1
|
2020-05-15T10:02:38.000Z
|
2020-05-15T10:02:38.000Z
|
irohad/consensus/yac/impl/yac_gate_impl.cpp
|
akshatkarani/iroha
|
5acef9dd74720c6185360d951e9b11be4ef73260
|
[
"Apache-2.0"
] | 2
|
2020-02-18T11:25:35.000Z
|
2020-02-20T04:09:45.000Z
|
irohad/consensus/yac/impl/yac_gate_impl.cpp
|
akshatkarani/iroha
|
5acef9dd74720c6185360d951e9b11be4ef73260
|
[
"Apache-2.0"
] | 1
|
2020-07-25T11:15:16.000Z
|
2020-07-25T11:15:16.000Z
|
/**
* Copyright Soramitsu Co., Ltd. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
#include "consensus/yac/impl/yac_gate_impl.hpp"
#include <boost/range/adaptor/transformed.hpp>
#include <rxcpp/operators/rx-flat_map.hpp>
#include "common/visitor.hpp"
#include "consensus/yac/cluster_order.hpp"
#include "consensus/yac/outcome_messages.hpp"
#include "consensus/yac/storage/yac_common.hpp"
#include "consensus/yac/yac_hash_provider.hpp"
#include "consensus/yac/yac_peer_orderer.hpp"
#include "cryptography/public_key.hpp"
#include "interfaces/common_objects/signature.hpp"
#include "interfaces/iroha_internal/block.hpp"
#include "logger/logger.hpp"
#include "simulator/block_creator.hpp"
namespace {
auto getPublicKeys(
const std::vector<iroha::consensus::yac::VoteMessage> &votes) {
return boost::copy_range<
shared_model::interface::types::PublicKeyCollectionType>(
votes | boost::adaptors::transformed([](auto &vote) {
return vote.signature->publicKey();
}));
}
} // namespace
namespace iroha {
namespace consensus {
namespace yac {
YacGateImpl::YacGateImpl(
std::shared_ptr<HashGate> hash_gate,
std::shared_ptr<YacPeerOrderer> orderer,
boost::optional<ClusterOrdering> alternative_order,
std::shared_ptr<YacHashProvider> hash_provider,
std::shared_ptr<simulator::BlockCreator> block_creator,
std::shared_ptr<consensus::ConsensusResultCache>
consensus_result_cache,
logger::LoggerPtr log)
: log_(std::move(log)),
current_hash_(),
alternative_order_(std::move(alternative_order)),
published_events_(hash_gate->onOutcome()
.flat_map([this](auto message) {
return visit_in_place(
message,
[this](const CommitMessage &msg) {
return this->handleCommit(msg);
},
[this](const RejectMessage &msg) {
return this->handleReject(msg);
},
[this](const FutureMessage &msg) {
return this->handleFuture(msg);
});
})
.publish()
.ref_count()),
orderer_(std::move(orderer)),
hash_provider_(std::move(hash_provider)),
block_creator_(std::move(block_creator)),
consensus_result_cache_(std::move(consensus_result_cache)),
hash_gate_(std::move(hash_gate)) {
block_creator_->onBlock().subscribe(
[this](const auto &event) { this->vote(event); });
}
void YacGateImpl::vote(const simulator::BlockCreatorEvent &event) {
if (current_hash_.vote_round >= event.round) {
log_->info(
"Current round {} is greater than or equal to vote round {}, "
"skipped",
current_hash_.vote_round,
event.round);
return;
}
current_ledger_state_ = event.ledger_state;
current_hash_ = hash_provider_->makeHash(event);
assert(current_hash_.vote_round.block_round
== current_ledger_state_->top_block_info.height + 1);
if (not event.round_data) {
current_block_ = boost::none;
// previous block is committed to block storage, it is safe to clear
// the cache
// TODO 2019-03-15 andrei: IR-405 Subscribe BlockLoaderService to
// BlockCreator::onBlock
consensus_result_cache_->release();
log_->debug("Agreed on nothing to commit");
} else {
current_block_ = event.round_data->block;
// insert the block we voted for to the consensus cache
consensus_result_cache_->insert(event.round_data->block);
log_->info("vote for (proposal: {}, block: {})",
current_hash_.vote_hashes.proposal_hash,
current_hash_.vote_hashes.block_hash);
}
auto order = orderer_->getOrdering(current_hash_,
event.ledger_state->ledger_peers);
if (not order) {
log_->error("ordering doesn't provide peers => pass round");
return;
}
hash_gate_->vote(current_hash_, *order, std::move(alternative_order_));
alternative_order_.reset();
}
rxcpp::observable<YacGateImpl::GateObject> YacGateImpl::onOutcome() {
return published_events_;
}
void YacGateImpl::copySignatures(const CommitMessage &commit) {
for (const auto &vote : commit.votes) {
auto sig = vote.hash.block_signature;
current_block_.value()->addSignature(sig->signedData(),
sig->publicKey());
}
}
rxcpp::observable<YacGateImpl::GateObject> YacGateImpl::handleCommit(
const CommitMessage &msg) {
const auto hash = getHash(msg.votes).value();
if (hash.vote_round < current_hash_.vote_round) {
log_->info(
"Current round {} is greater than commit round {}, skipped",
current_hash_.vote_round,
hash.vote_round);
return rxcpp::observable<>::empty<GateObject>();
}
assert(hash.vote_round.block_round
== current_hash_.vote_round.block_round);
if (hash == current_hash_ and current_block_) {
// if node has voted for the committed block
// append signatures of other nodes
this->copySignatures(msg);
auto &block = current_block_.value();
log_->info("consensus: commit top block: height {}, hash {}",
block->height(),
block->hash().hex());
return rxcpp::observable<>::just<GateObject>(PairValid(
current_hash_.vote_round, current_ledger_state_, block));
}
auto public_keys = getPublicKeys(msg.votes);
if (hash.vote_hashes.proposal_hash.empty()) {
// if consensus agreed on nothing for commit
log_->info("Consensus skipped round, voted for nothing");
current_block_ = boost::none;
return rxcpp::observable<>::just<GateObject>(AgreementOnNone(
hash.vote_round, current_ledger_state_, std::move(public_keys)));
}
log_->info("Voted for another block, waiting for sync");
current_block_ = boost::none;
auto model_hash = hash_provider_->toModelHash(hash);
return rxcpp::observable<>::just<GateObject>(
VoteOther(hash.vote_round,
current_ledger_state_,
std::move(public_keys),
std::move(model_hash)));
}
rxcpp::observable<YacGateImpl::GateObject> YacGateImpl::handleReject(
const RejectMessage &msg) {
const auto hash = getHash(msg.votes).value();
auto public_keys = getPublicKeys(msg.votes);
if (hash.vote_round < current_hash_.vote_round) {
log_->info(
"Current round {} is greater than reject round {}, skipped",
current_hash_.vote_round,
hash.vote_round);
return rxcpp::observable<>::empty<GateObject>();
}
assert(hash.vote_round.block_round
== current_hash_.vote_round.block_round);
auto has_same_proposals =
std::all_of(std::next(msg.votes.begin()),
msg.votes.end(),
[first = msg.votes.begin()](const auto ¤t) {
return first->hash.vote_hashes.proposal_hash
== current.hash.vote_hashes.proposal_hash;
});
if (not has_same_proposals) {
log_->info("Proposal reject since all hashes are different");
return rxcpp::observable<>::just<GateObject>(ProposalReject(
hash.vote_round, current_ledger_state_, std::move(public_keys)));
}
log_->info("Block reject since proposal hashes match");
return rxcpp::observable<>::just<GateObject>(BlockReject(
hash.vote_round, current_ledger_state_, std::move(public_keys)));
}
rxcpp::observable<YacGateImpl::GateObject> YacGateImpl::handleFuture(
const FutureMessage &msg) {
const auto hash = getHash(msg.votes).value();
auto public_keys = getPublicKeys(msg.votes);
if (hash.vote_round.block_round
<= current_hash_.vote_round.block_round) {
log_->info(
"Current block round {} is not lower than future block round {}, "
"skipped",
current_hash_.vote_round.block_round,
hash.vote_round.block_round);
return rxcpp::observable<>::empty<GateObject>();
}
assert(hash.vote_round.block_round
> current_hash_.vote_round.block_round);
log_->info("Message from future, waiting for sync");
return rxcpp::observable<>::just<GateObject>(Future(
hash.vote_round, current_ledger_state_, std::move(public_keys)));
}
} // namespace yac
} // namespace consensus
} // namespace iroha
| 41.632035
| 80
| 0.577415
|
akshatkarani
|
1140924ee363de3318b9f2b566ac9513058e5fd1
| 46,384
|
cpp
|
C++
|
tests/Unit/ApparentHorizons/Test_StrahlkorperGr.cpp
|
kidder/spectre
|
97ae95f72320f9f67895d3303824e64de6fd9077
|
[
"MIT"
] | 1
|
2021-03-31T05:22:18.000Z
|
2021-03-31T05:22:18.000Z
|
tests/Unit/ApparentHorizons/Test_StrahlkorperGr.cpp
|
kidder/spectre
|
97ae95f72320f9f67895d3303824e64de6fd9077
|
[
"MIT"
] | 9
|
2021-09-02T19:53:22.000Z
|
2021-11-02T02:41:16.000Z
|
tests/Unit/ApparentHorizons/Test_StrahlkorperGr.cpp
|
kidder/spectre
|
97ae95f72320f9f67895d3303824e64de6fd9077
|
[
"MIT"
] | null | null | null |
// Distributed under the MIT License.
// See LICENSE.txt for details.
#include "Framework/TestingFramework.hpp"
#include <algorithm>
#include <array>
#include <cmath>
#include <cstddef>
#include <random>
#include "ApparentHorizons/Strahlkorper.hpp"
#include "ApparentHorizons/StrahlkorperGr.hpp"
#include "ApparentHorizons/Tags.hpp" // IWYU pragma: keep
#include "DataStructures/DataBox/DataBox.hpp"
#include "DataStructures/DataBox/Prefixes.hpp" // IWYU pragma: keep
#include "DataStructures/DataVector.hpp"
#include "DataStructures/Tensor/EagerMath/DeterminantAndInverse.hpp"
#include "DataStructures/Tensor/EagerMath/DotProduct.hpp" // IWYU pragma: keep
#include "DataStructures/Tensor/EagerMath/Magnitude.hpp" // IWYU prgma: keep
#include "DataStructures/Tensor/Tensor.hpp"
#include "Framework/TestHelpers.hpp"
#include "Helpers/ApparentHorizons/StrahlkorperGrTestHelpers.hpp"
#include "Helpers/DataStructures/MakeWithRandomValues.hpp"
#include "NumericalAlgorithms/LinearOperators/PartialDerivatives.hpp"
#include "NumericalAlgorithms/SphericalHarmonics/YlmSpherepack.hpp"
#include "PointwiseFunctions/AnalyticSolutions/GeneralRelativity/KerrHorizon.hpp"
#include "PointwiseFunctions/AnalyticSolutions/GeneralRelativity/KerrSchild.hpp"
#include "PointwiseFunctions/AnalyticSolutions/GeneralRelativity/Minkowski.hpp"
#include "PointwiseFunctions/GeneralRelativity/Christoffel.hpp"
#include "PointwiseFunctions/GeneralRelativity/ExtrinsicCurvature.hpp"
#include "PointwiseFunctions/GeneralRelativity/IndexManipulation.hpp"
#include "PointwiseFunctions/GeneralRelativity/Tags.hpp"
#include "Utilities/ConstantExpressions.hpp"
#include "Utilities/Gsl.hpp"
#include "Utilities/MakeWithValue.hpp"
#include "Utilities/StdArrayHelpers.hpp"
#include "Utilities/StdHelpers.hpp"
#include "Utilities/TMPL.hpp"
#include "Utilities/TaggedTuple.hpp"
// IWYU pragma: no_forward_declare Tags::deriv
// IWYU pragma: no_forward_declare Tensor
namespace {
template <typename Solution, typename Fr, typename ExpectedLambda>
void test_expansion(const Solution& solution,
const Strahlkorper<Fr>& strahlkorper,
const ExpectedLambda& expected) {
// Make databox from surface
const auto box = db::create<
db::AddSimpleTags<StrahlkorperTags::items_tags<Frame::Inertial>>,
db::AddComputeTags<
StrahlkorperTags::compute_items_tags<Frame::Inertial>>>(strahlkorper);
const double t = 0.0;
const auto& cart_coords =
db::get<StrahlkorperTags::CartesianCoords<Frame::Inertial>>(box);
const auto vars = solution.variables(
cart_coords, t, typename Solution::template tags<DataVector>{});
const auto& spatial_metric =
get<gr::Tags::SpatialMetric<3, Frame::Inertial, DataVector>>(vars);
const auto& deriv_spatial_metric =
get<Tags::deriv<gr::Tags::SpatialMetric<3, Frame::Inertial, DataVector>,
tmpl::size_t<3>, Frame::Inertial>>(vars);
const auto inverse_spatial_metric =
determinant_and_inverse(spatial_metric).second;
const DataVector one_over_one_form_magnitude =
1.0 / get(magnitude(
db::get<StrahlkorperTags::NormalOneForm<Frame::Inertial>>(box),
inverse_spatial_metric));
const auto unit_normal_one_form = StrahlkorperGr::unit_normal_one_form(
db::get<StrahlkorperTags::NormalOneForm<Frame::Inertial>>(box),
one_over_one_form_magnitude);
const auto grad_unit_normal_one_form =
StrahlkorperGr::grad_unit_normal_one_form(
db::get<StrahlkorperTags::Rhat<Frame::Inertial>>(box),
db::get<StrahlkorperTags::Radius<Frame::Inertial>>(box),
unit_normal_one_form,
db::get<StrahlkorperTags::D2xRadius<Frame::Inertial>>(box),
one_over_one_form_magnitude,
raise_or_lower_first_index(
gr::christoffel_first_kind(deriv_spatial_metric),
inverse_spatial_metric));
const auto inverse_surface_metric = StrahlkorperGr::inverse_surface_metric(
raise_or_lower_index(unit_normal_one_form, inverse_spatial_metric),
inverse_spatial_metric);
const auto residual = StrahlkorperGr::expansion(
grad_unit_normal_one_form, inverse_surface_metric,
gr::extrinsic_curvature(
get<gr::Tags::Lapse<DataVector>>(vars),
get<gr::Tags::Shift<3, Frame::Inertial, DataVector>>(vars),
get<Tags::deriv<gr::Tags::Shift<3, Frame::Inertial, DataVector>,
tmpl::size_t<3>, Frame::Inertial>>(vars),
spatial_metric,
get<Tags::dt<
gr::Tags::SpatialMetric<3, Frame::Inertial, DataVector>>>(vars),
deriv_spatial_metric));
Approx custom_approx = Approx::custom().epsilon(1.e-12).scale(1.0);
CHECK_ITERABLE_CUSTOM_APPROX(get(residual), expected(get(residual).size()),
custom_approx);
}
namespace TestExtrinsicCurvature {
void test_minkowski() {
// Make surface of radius 2.
const auto box = db::create<
db::AddSimpleTags<StrahlkorperTags::items_tags<Frame::Inertial>>,
db::AddComputeTags<
StrahlkorperTags::compute_items_tags<Frame::Inertial>>>(
Strahlkorper<Frame::Inertial>(8, 8, 2.0, {{0.0, 0.0, 0.0}}));
const double t = 0.0;
const auto& cart_coords =
db::get<StrahlkorperTags::CartesianCoords<Frame::Inertial>>(box);
gr::Solutions::Minkowski<3> solution{};
const auto deriv_spatial_metric =
get<Tags::deriv<gr::Tags::SpatialMetric<3, Frame::Inertial, DataVector>,
tmpl::size_t<3>, Frame::Inertial>>(
solution.variables(
cart_coords, t,
tmpl::list<Tags::deriv<
gr::Tags::SpatialMetric<3, Frame::Inertial, DataVector>,
tmpl::size_t<3>, Frame::Inertial>>{}));
const auto inverse_spatial_metric =
get<gr::Tags::InverseSpatialMetric<3, Frame::Inertial, DataVector>>(
solution.variables(
cart_coords, t,
tmpl::list<gr::Tags::InverseSpatialMetric<3, Frame::Inertial,
DataVector>>{}));
const DataVector one_over_one_form_magnitude =
1.0 / get(magnitude(
db::get<StrahlkorperTags::NormalOneForm<Frame::Inertial>>(box),
inverse_spatial_metric));
const auto unit_normal_one_form = StrahlkorperGr::unit_normal_one_form(
db::get<StrahlkorperTags::NormalOneForm<Frame::Inertial>>(box),
one_over_one_form_magnitude);
const auto grad_unit_normal_one_form =
StrahlkorperGr::grad_unit_normal_one_form(
db::get<StrahlkorperTags::Rhat<Frame::Inertial>>(box),
db::get<StrahlkorperTags::Radius<Frame::Inertial>>(box),
unit_normal_one_form,
db::get<StrahlkorperTags::D2xRadius<Frame::Inertial>>(box),
one_over_one_form_magnitude,
raise_or_lower_first_index(
gr::christoffel_first_kind(deriv_spatial_metric),
inverse_spatial_metric));
const auto unit_normal_vector =
raise_or_lower_index(unit_normal_one_form, inverse_spatial_metric);
const auto extrinsic_curvature = StrahlkorperGr::extrinsic_curvature(
grad_unit_normal_one_form, unit_normal_one_form, unit_normal_vector);
const auto extrinsic_curvature_minkowski =
TestHelpers::Minkowski::extrinsic_curvature_sphere(cart_coords);
CHECK_ITERABLE_APPROX(extrinsic_curvature, extrinsic_curvature_minkowski);
}
} // namespace TestExtrinsicCurvature
template <typename Solution, typename SpatialRicciScalar,
typename ExpectedLambda>
void test_ricci_scalar(const Solution& solution,
const SpatialRicciScalar& spatial_ricci_scalar,
const ExpectedLambda& expected) {
// Make surface of radius 2.
const auto box = db::create<
db::AddSimpleTags<StrahlkorperTags::items_tags<Frame::Inertial>>,
db::AddComputeTags<
StrahlkorperTags::compute_items_tags<Frame::Inertial>>>(
Strahlkorper<Frame::Inertial>(8, 8, 2.0, {{0.0, 0.0, 0.0}}));
const double t = 0.0;
const auto& cart_coords =
db::get<StrahlkorperTags::CartesianCoords<Frame::Inertial>>(box);
const auto vars = solution.variables(
cart_coords, t, typename Solution::template tags<DataVector>{});
const auto& spatial_metric =
get<gr::Tags::SpatialMetric<3, Frame::Inertial, DataVector>>(vars);
const auto& deriv_spatial_metric =
get<Tags::deriv<gr::Tags::SpatialMetric<3, Frame::Inertial, DataVector>,
tmpl::size_t<3>, Frame::Inertial>>(vars);
const auto inverse_spatial_metric =
determinant_and_inverse(spatial_metric).second;
const DataVector one_over_one_form_magnitude =
1.0 / get(magnitude(
db::get<StrahlkorperTags::NormalOneForm<Frame::Inertial>>(box),
inverse_spatial_metric));
const auto unit_normal_one_form = StrahlkorperGr::unit_normal_one_form(
db::get<StrahlkorperTags::NormalOneForm<Frame::Inertial>>(box),
one_over_one_form_magnitude);
const auto grad_unit_normal_one_form =
StrahlkorperGr::grad_unit_normal_one_form(
db::get<StrahlkorperTags::Rhat<Frame::Inertial>>(box),
db::get<StrahlkorperTags::Radius<Frame::Inertial>>(box),
unit_normal_one_form,
db::get<StrahlkorperTags::D2xRadius<Frame::Inertial>>(box),
one_over_one_form_magnitude,
raise_or_lower_first_index(
gr::christoffel_first_kind(deriv_spatial_metric),
inverse_spatial_metric));
const auto unit_normal_vector =
raise_or_lower_index(unit_normal_one_form, inverse_spatial_metric);
const auto ricci_scalar = StrahlkorperGr::ricci_scalar(
spatial_ricci_scalar(cart_coords), unit_normal_vector,
StrahlkorperGr::extrinsic_curvature(
grad_unit_normal_one_form, unit_normal_one_form, unit_normal_vector),
inverse_spatial_metric);
CHECK_ITERABLE_APPROX(get(ricci_scalar), expected(get(ricci_scalar).size()));
}
template <typename Solution, typename ExpectedLambda>
void test_area_element(const Solution& solution, const double surface_radius,
const ExpectedLambda& expected) {
const auto box = db::create<
db::AddSimpleTags<StrahlkorperTags::items_tags<Frame::Inertial>>,
db::AddComputeTags<
StrahlkorperTags::compute_items_tags<Frame::Inertial>>>(
Strahlkorper<Frame::Inertial>(8, 8, surface_radius, {{0.0, 0.0, 0.0}}));
const double t = 0.0;
const auto& cart_coords =
db::get<StrahlkorperTags::CartesianCoords<Frame::Inertial>>(box);
const auto vars = solution.variables(
cart_coords, t, typename Solution::template tags<DataVector>{});
const auto& spatial_metric =
get<gr::Tags::SpatialMetric<3, Frame::Inertial, DataVector>>(vars);
const auto& normal_one_form =
db::get<StrahlkorperTags::NormalOneForm<Frame::Inertial>>(box);
const auto& r_hat = db::get<StrahlkorperTags::Rhat<Frame::Inertial>>(box);
const auto& radius = db::get<StrahlkorperTags::Radius<Frame::Inertial>>(box);
const auto& jacobian =
db::get<StrahlkorperTags::Jacobian<Frame::Inertial>>(box);
const auto area_element = StrahlkorperGr::area_element(
spatial_metric, jacobian, normal_one_form, radius, r_hat);
CHECK_ITERABLE_APPROX(get(area_element), expected(get(area_element).size()));
}
void test_euclidean_surface_integral_of_vector(
const Strahlkorper<Frame::Inertial>& strahlkorper) {
const auto box = db::create<
db::AddSimpleTags<StrahlkorperTags::items_tags<Frame::Inertial>>,
db::AddComputeTags<
StrahlkorperTags::compute_items_tags<Frame::Inertial>>>(strahlkorper);
const auto& normal_one_form =
db::get<StrahlkorperTags::NormalOneForm<Frame::Inertial>>(box);
const auto& r_hat = db::get<StrahlkorperTags::Rhat<Frame::Inertial>>(box);
const auto& radius = db::get<StrahlkorperTags::Radius<Frame::Inertial>>(box);
const auto& jacobian =
db::get<StrahlkorperTags::Jacobian<Frame::Inertial>>(box);
const auto euclidean_area_element = StrahlkorperGr::euclidean_area_element(
jacobian, normal_one_form, radius, r_hat);
// Create arbitrary vector
MAKE_GENERATOR(generator);
std::uniform_real_distribution<> dist(-1., 1.);
const auto test_vector = make_with_random_values<tnsr::I<DataVector, 3>>(
make_not_null(&generator), make_not_null(&dist), radius);
// Test against integrating this scalar.
const auto scalar = Scalar<DataVector>(
get(dot_product(test_vector, normal_one_form)) /
sqrt(get(dot_product(normal_one_form, normal_one_form))));
const auto integral_1 = StrahlkorperGr::surface_integral_of_scalar(
euclidean_area_element, scalar, strahlkorper);
const auto integral_2 = StrahlkorperGr::euclidean_surface_integral_of_vector(
euclidean_area_element, test_vector, normal_one_form, strahlkorper);
Approx custom_approx = Approx::custom().epsilon(1.e-13).scale(1.0);
CHECK(integral_1 == custom_approx(integral_2));
}
template <typename Solution, typename Frame>
void test_euclidean_surface_integral_of_vector_2(
const Solution& solution, const Strahlkorper<Frame>& strahlkorper,
double expected_area) {
// Another test: Integrate (assuming Euclidean metric) the vector
// V^i = s_j \delta^{ij} (s_k s_l \delta^{kl})^{-1/2} A A_euclid^{-1}
// where s_j is the unnormalized Strahlkorper normal one-form,
// A is the correct (curved) area element in Kerr,
// and A_euclid is the euclidean area element.
// This integral should give the area of the horizon, which is
// 16 pi M_irr^2 = 8 pi M^2 (1 + sqrt(1-chi^2))
const auto box = db::create<
db::AddSimpleTags<StrahlkorperTags::items_tags<Frame>>,
db::AddComputeTags<StrahlkorperTags::compute_items_tags<Frame>>>(
strahlkorper);
// Get spatial metric
const double t = 0.0;
const auto& cart_coords =
db::get<StrahlkorperTags::CartesianCoords<Frame>>(box);
const auto vars = solution.variables(
cart_coords, t, typename Solution::template tags<DataVector>{});
const auto& spatial_metric =
get<gr::Tags::SpatialMetric<3, Frame, DataVector>>(vars);
// Get everything we need for the integral
const auto& normal_one_form =
db::get<StrahlkorperTags::NormalOneForm<Frame>>(box);
const auto& r_hat = db::get<StrahlkorperTags::Rhat<Frame>>(box);
const auto& radius = db::get<StrahlkorperTags::Radius<Frame>>(box);
const auto& jacobian = db::get<StrahlkorperTags::Jacobian<Frame>>(box);
const auto euclidean_area_element = StrahlkorperGr::euclidean_area_element(
jacobian, normal_one_form, radius, r_hat);
// Make the test vector
// V^i = s_j \delta^{ij} (s_k s_l \delta^{kl})^{-1/2} A A_euclid^{-1}
// where A is the area element and A_euclid is the euclidean area element.
const auto area_element = StrahlkorperGr::area_element(
spatial_metric, jacobian, normal_one_form, radius, r_hat);
const auto test_vector_factor = Scalar<DataVector>(
get(area_element) / get(euclidean_area_element) /
sqrt(get(dot_product(normal_one_form, normal_one_form))));
auto test_vector = make_with_value<tnsr::I<DataVector, 3, Frame>>(r_hat, 0.0);
for (size_t i = 0; i < 3; ++i) {
test_vector.get(i) = normal_one_form.get(i) * get(test_vector_factor);
}
const auto area_integral =
StrahlkorperGr::euclidean_surface_integral_of_vector(
euclidean_area_element, test_vector, normal_one_form, strahlkorper);
// approx here because we are integrating over a Strahlkorper
// at finite resolution.
CHECK(area_integral == approx(expected_area));
}
void test_euclidean_area_element(
const Strahlkorper<Frame::Inertial>& strahlkorper) {
const auto box = db::create<
db::AddSimpleTags<StrahlkorperTags::items_tags<Frame::Inertial>>,
db::AddComputeTags<
StrahlkorperTags::compute_items_tags<Frame::Inertial>>>(strahlkorper);
// Create a Minkowski metric.
const gr::Solutions::Minkowski<3> solution{};
const double t = 0.0;
const auto& cart_coords =
db::get<StrahlkorperTags::CartesianCoords<Frame::Inertial>>(box);
const auto vars = solution.variables(
cart_coords, t, gr::Solutions::Minkowski<3>::tags<DataVector>{});
const auto& spatial_metric =
get<gr::Tags::SpatialMetric<3, Frame::Inertial, DataVector>>(vars);
const auto& normal_one_form =
db::get<StrahlkorperTags::NormalOneForm<Frame::Inertial>>(box);
const auto& r_hat = db::get<StrahlkorperTags::Rhat<Frame::Inertial>>(box);
const auto& radius = db::get<StrahlkorperTags::Radius<Frame::Inertial>>(box);
const auto& jacobian =
db::get<StrahlkorperTags::Jacobian<Frame::Inertial>>(box);
// We are using a flat metric, so area_element and euclidean_area_element
// should be the same, and this is what we test.
const auto area_element = StrahlkorperGr::area_element(
spatial_metric, jacobian, normal_one_form, radius, r_hat);
const auto euclidean_area_element = StrahlkorperGr::euclidean_area_element(
jacobian, normal_one_form, radius, r_hat);
CHECK_ITERABLE_APPROX(get(euclidean_area_element), get(area_element));
}
template <typename Solution, typename Fr>
void test_area(const Solution& solution, const Strahlkorper<Fr>& strahlkorper,
const double expected, const double expected_irreducible_mass,
const double dimensionful_spin_magnitude,
const double expected_christodoulou_mass) {
const auto box = db::create<
db::AddSimpleTags<StrahlkorperTags::items_tags<Frame::Inertial>>,
db::AddComputeTags<
StrahlkorperTags::compute_items_tags<Frame::Inertial>>>(strahlkorper);
const double t = 0.0;
const auto& cart_coords =
db::get<StrahlkorperTags::CartesianCoords<Frame::Inertial>>(box);
const auto vars = solution.variables(
cart_coords, t, typename Solution::template tags<DataVector>{});
const auto& spatial_metric =
get<gr::Tags::SpatialMetric<3, Frame::Inertial, DataVector>>(vars);
const auto& normal_one_form =
db::get<StrahlkorperTags::NormalOneForm<Frame::Inertial>>(box);
const auto& r_hat = db::get<StrahlkorperTags::Rhat<Frame::Inertial>>(box);
const auto& radius = db::get<StrahlkorperTags::Radius<Frame::Inertial>>(box);
const auto& jacobian =
db::get<StrahlkorperTags::Jacobian<Frame::Inertial>>(box);
const auto area_element = StrahlkorperGr::area_element(
spatial_metric, jacobian, normal_one_form, radius, r_hat);
const double area =
strahlkorper.ylm_spherepack().definite_integral(get(area_element).data());
CHECK_ITERABLE_APPROX(area, expected);
const double irreducible_mass = StrahlkorperGr::irreducible_mass(area);
CHECK(irreducible_mass == approx(expected_irreducible_mass));
const double christodoulou_mass = StrahlkorperGr::christodoulou_mass(
dimensionful_spin_magnitude, irreducible_mass);
CHECK(christodoulou_mass == approx(expected_christodoulou_mass));
}
// Let I_1 = surface_integral_of_scalar(J^i \tilde{s}_i \sqrt(-g))
// where J^i is some arbitrary vector (representing a flux through the
// surface), g is the determinant of the spacetime metric,
// \tilde{s}_i is the spatial unit one-form to the Strahlkorper,
// normalized with the flat metric \tilde{s}_i \tilde{s}_j \delta^{ij} = 1,
// and where euclidean_area_element is passed into surface_integral_of_scalar.
//
// Let I_2 = surface_integral_of_scalar(J^i s_i \alpha), where \alpha is the
// lapse, s_i is the spatial unit one-form to the Strahlkorper,
// normalized with the spatial metric s_i s_j \gamma^{ij} = 1, and where
// the area_element computed with $\gamma_{ij}$ is passed into
// surface_integral_of_scalar.
//
// This tests that I_1==I_2 for an arbitrary 3-vector J^i.
template <typename Solution, typename Frame>
void test_integral_correspondence(const Solution& solution,
const Strahlkorper<Frame>& strahlkorper) {
const auto box = db::create<
db::AddSimpleTags<StrahlkorperTags::items_tags<Frame>>,
db::AddComputeTags<StrahlkorperTags::compute_items_tags<Frame>>>(
strahlkorper);
const double t = 0.0;
const auto& cart_coords =
db::get<StrahlkorperTags::CartesianCoords<Frame>>(box);
const auto vars = solution.variables(
cart_coords, t, typename Solution::template tags<DataVector>{});
const auto& spatial_metric =
get<gr::Tags::SpatialMetric<3, Frame, DataVector>>(vars);
const auto& lapse = get<gr::Tags::Lapse<DataVector>>(vars);
const auto det_and_inverse_spatial_metric =
determinant_and_inverse(spatial_metric);
const auto& det_spatial_metric = det_and_inverse_spatial_metric.first;
const auto& inverse_spatial_metric = det_and_inverse_spatial_metric.second;
const auto& normal_one_form =
db::get<StrahlkorperTags::NormalOneForm<Frame>>(box);
const auto& r_hat = db::get<StrahlkorperTags::Rhat<Frame>>(box);
const auto& radius = db::get<StrahlkorperTags::Radius<Frame>>(box);
const auto& jacobian = db::get<StrahlkorperTags::Jacobian<Frame>>(box);
const auto area_element = StrahlkorperGr::area_element(
spatial_metric, jacobian, normal_one_form, radius, r_hat);
const auto euclidean_area_element = StrahlkorperGr::euclidean_area_element(
jacobian, normal_one_form, radius, r_hat);
const auto normal_one_form_euclidean_magnitude =
dot_product(normal_one_form, normal_one_form);
const auto normal_one_form_magnitude =
dot_product(normal_one_form, normal_one_form, inverse_spatial_metric);
auto unit_normal_one_form_flat = normal_one_form;
auto unit_normal_one_form_curved = normal_one_form;
for (size_t i = 0; i < 3; ++i) {
unit_normal_one_form_flat.get(i) /=
sqrt(get(normal_one_form_euclidean_magnitude));
unit_normal_one_form_curved.get(i) /= sqrt(get(normal_one_form_magnitude));
}
// Set up random values for test_vector
MAKE_GENERATOR(generator);
std::uniform_real_distribution<> dist(-1., 1.);
const auto test_vector = make_with_random_values<tnsr::I<DataVector, 3>>(
make_not_null(&generator), make_not_null(&dist), lapse);
const auto scalar_1 = Scalar<DataVector>(
get(dot_product(test_vector, unit_normal_one_form_flat)) * get(lapse) *
sqrt(get(det_spatial_metric)));
const auto scalar_2 = Scalar<DataVector>(
get(dot_product(test_vector, unit_normal_one_form_curved)) * get(lapse));
const double integral_1 = StrahlkorperGr::surface_integral_of_scalar(
euclidean_area_element, scalar_1, strahlkorper);
const double integral_2 = StrahlkorperGr::surface_integral_of_scalar(
area_element, scalar_2, strahlkorper);
Approx custom_approx = Approx::custom().epsilon(1.e-13).scale(1.0);
CHECK(integral_1 == custom_approx(integral_2));
}
template <typename Solution, typename Fr>
void test_surface_integral_of_scalar(const Solution& solution,
const Strahlkorper<Fr>& strahlkorper,
const double expected) {
const auto box =
db::create<db::AddSimpleTags<StrahlkorperTags::items_tags<Fr>>,
db::AddComputeTags<StrahlkorperTags::compute_items_tags<Fr>>>(
strahlkorper);
const double t = 0.0;
const auto& cart_coords = db::get<StrahlkorperTags::CartesianCoords<Fr>>(box);
const auto vars = solution.variables(
cart_coords, t, typename Solution::template tags<DataVector>{});
const auto& spatial_metric =
get<gr::Tags::SpatialMetric<3, Fr, DataVector>>(vars);
const auto& normal_one_form =
db::get<StrahlkorperTags::NormalOneForm<Fr>>(box);
const auto& r_hat = db::get<StrahlkorperTags::Rhat<Fr>>(box);
const auto& radius = db::get<StrahlkorperTags::Radius<Fr>>(box);
const auto& jacobian = db::get<StrahlkorperTags::Jacobian<Fr>>(box);
const auto area_element = StrahlkorperGr::area_element(
spatial_metric, jacobian, normal_one_form, radius, r_hat);
auto scalar = make_with_value<Scalar<DataVector>>(radius, 0.0);
get(scalar) = square(get<0>(cart_coords));
const double integral = StrahlkorperGr::surface_integral_of_scalar(
area_element, scalar, strahlkorper);
CHECK_ITERABLE_APPROX(integral, expected);
}
template <typename Solution, typename Fr>
void test_spin_function(const Solution& solution,
const Strahlkorper<Fr>& strahlkorper,
const double expected) {
const auto box = db::create<
db::AddSimpleTags<StrahlkorperTags::items_tags<Frame::Inertial>>,
db::AddComputeTags<
StrahlkorperTags::compute_items_tags<Frame::Inertial>>>(strahlkorper);
const double t = 0.0;
const auto& cart_coords =
db::get<StrahlkorperTags::CartesianCoords<Frame::Inertial>>(box);
const auto vars = solution.variables(
cart_coords, t, typename Solution::template tags<DataVector>{});
const auto& spatial_metric =
get<gr::Tags::SpatialMetric<3, Frame::Inertial, DataVector>>(vars);
const auto inverse_spatial_metric =
determinant_and_inverse(spatial_metric).second;
const auto& normal_one_form =
db::get<StrahlkorperTags::NormalOneForm<Frame::Inertial>>(box);
const DataVector one_over_one_form_magnitude =
1.0 / get(magnitude(
db::get<StrahlkorperTags::NormalOneForm<Frame::Inertial>>(box),
inverse_spatial_metric));
const auto unit_normal_one_form = StrahlkorperGr::unit_normal_one_form(
db::get<StrahlkorperTags::NormalOneForm<Frame::Inertial>>(box),
one_over_one_form_magnitude);
const auto unit_normal_vector =
raise_or_lower_index(unit_normal_one_form, inverse_spatial_metric);
const auto& r_hat = db::get<StrahlkorperTags::Rhat<Frame::Inertial>>(box);
const auto& radius = db::get<StrahlkorperTags::Radius<Frame::Inertial>>(box);
const auto& jacobian =
db::get<StrahlkorperTags::Jacobian<Frame::Inertial>>(box);
const auto area_element = StrahlkorperGr::area_element(
spatial_metric, jacobian, normal_one_form, radius, r_hat);
const auto& ylm = strahlkorper.ylm_spherepack();
const auto& deriv_spatial_metric =
get<Tags::deriv<gr::Tags::SpatialMetric<3, Frame::Inertial, DataVector>,
tmpl::size_t<3>, Frame::Inertial>>(vars);
const auto extrinsic_curvature = gr::extrinsic_curvature(
get<gr::Tags::Lapse<DataVector>>(vars),
get<gr::Tags::Shift<3, Frame::Inertial, DataVector>>(vars),
get<Tags::deriv<gr::Tags::Shift<3, Frame::Inertial, DataVector>,
tmpl::size_t<3>, Frame::Inertial>>(vars),
spatial_metric,
get<Tags::dt<gr::Tags::SpatialMetric<3, Frame::Inertial, DataVector>>>(
vars),
deriv_spatial_metric);
const auto& tangents =
db::get<StrahlkorperTags::Tangents<Frame::Inertial>>(box);
const auto spin_function =
StrahlkorperGr::spin_function(tangents, strahlkorper, unit_normal_vector,
area_element, extrinsic_curvature);
auto integrand = spin_function;
get(integrand) *= get(area_element) * get(spin_function);
const double integral = ylm.definite_integral(get(integrand).data());
Approx custom_approx = Approx::custom().epsilon(1.e-12).scale(1.0);
CHECK_ITERABLE_CUSTOM_APPROX(integral, expected, custom_approx);
}
template <typename Solution, typename Fr>
void test_dimensionful_spin_magnitude(
const Solution& solution, const Strahlkorper<Fr>& strahlkorper,
const double mass, const std::array<double, 3> dimensionless_spin,
const Scalar<DataVector>& horizon_radius_with_spin_on_z_axis,
const YlmSpherepack& ylm_with_spin_on_z_axis, const double expected,
const double tolerance) {
const auto box = db::create<
db::AddSimpleTags<StrahlkorperTags::items_tags<Frame::Inertial>>,
db::AddComputeTags<
StrahlkorperTags::compute_items_tags<Frame::Inertial>>>(strahlkorper);
const double t = 0.0;
const auto& cart_coords =
db::get<StrahlkorperTags::CartesianCoords<Frame::Inertial>>(box);
const auto vars = solution.variables(
cart_coords, t, typename Solution::template tags<DataVector>{});
const auto& spatial_metric =
get<gr::Tags::SpatialMetric<3, Frame::Inertial, DataVector>>(vars);
const auto inverse_spatial_metric =
determinant_and_inverse(spatial_metric).second;
const auto& normal_one_form =
db::get<StrahlkorperTags::NormalOneForm<Frame::Inertial>>(box);
const DataVector one_over_one_form_magnitude =
1.0 / get(magnitude(
db::get<StrahlkorperTags::NormalOneForm<Frame::Inertial>>(box),
inverse_spatial_metric));
const auto unit_normal_one_form = StrahlkorperGr::unit_normal_one_form(
db::get<StrahlkorperTags::NormalOneForm<Frame::Inertial>>(box),
one_over_one_form_magnitude);
const auto unit_normal_vector =
raise_or_lower_index(unit_normal_one_form, inverse_spatial_metric);
const auto& r_hat = db::get<StrahlkorperTags::Rhat<Frame::Inertial>>(box);
const auto& radius = db::get<StrahlkorperTags::Radius<Frame::Inertial>>(box);
const auto& jacobian =
db::get<StrahlkorperTags::Jacobian<Frame::Inertial>>(box);
const auto area_element = StrahlkorperGr::area_element(
spatial_metric, jacobian, normal_one_form, radius, r_hat);
const auto& ylm = strahlkorper.ylm_spherepack();
const auto& deriv_spatial_metric =
get<Tags::deriv<gr::Tags::SpatialMetric<3, Frame::Inertial, DataVector>,
tmpl::size_t<3>, Frame::Inertial>>(vars);
const auto extrinsic_curvature = gr::extrinsic_curvature(
get<gr::Tags::Lapse<DataVector>>(vars),
get<gr::Tags::Shift<3, Frame::Inertial, DataVector>>(vars),
get<Tags::deriv<gr::Tags::Shift<3, Frame::Inertial, DataVector>,
tmpl::size_t<3>, Frame::Inertial>>(vars),
spatial_metric,
get<Tags::dt<gr::Tags::SpatialMetric<3, Frame::Inertial, DataVector>>>(
vars),
deriv_spatial_metric);
const auto& tangents =
db::get<StrahlkorperTags::Tangents<Frame::Inertial>>(box);
const auto spin_function =
StrahlkorperGr::spin_function(tangents, strahlkorper, unit_normal_vector,
area_element, extrinsic_curvature);
const auto grad_unit_normal_one_form =
StrahlkorperGr::grad_unit_normal_one_form(
db::get<StrahlkorperTags::Rhat<Frame::Inertial>>(box),
db::get<StrahlkorperTags::Radius<Frame::Inertial>>(box),
unit_normal_one_form,
db::get<StrahlkorperTags::D2xRadius<Frame::Inertial>>(box),
one_over_one_form_magnitude,
raise_or_lower_first_index(
gr::christoffel_first_kind(deriv_spatial_metric),
inverse_spatial_metric));
const auto ricci_scalar = TestHelpers::Kerr::horizon_ricci_scalar(
horizon_radius_with_spin_on_z_axis, ylm_with_spin_on_z_axis, ylm, mass,
dimensionless_spin);
const double spin_magnitude = StrahlkorperGr::dimensionful_spin_magnitude(
ricci_scalar, spin_function, spatial_metric, tangents, ylm, area_element);
Approx custom_approx = Approx::custom().epsilon(tolerance).scale(1.0);
CHECK_ITERABLE_CUSTOM_APPROX(spin_magnitude, expected, custom_approx);
}
template <typename Solution, typename Fr>
void test_spin_vector(
const Solution& solution, const Strahlkorper<Fr>& strahlkorper,
const double mass, const std::array<double, 3> dimensionless_spin,
const Scalar<DataVector>& horizon_radius_with_spin_on_z_axis,
const YlmSpherepack& ylm_with_spin_on_z_axis) {
const auto box = db::create<
db::AddSimpleTags<StrahlkorperTags::items_tags<Frame::Inertial>>,
db::AddComputeTags<
StrahlkorperTags::compute_items_tags<Frame::Inertial>>>(strahlkorper);
const double t = 0.0;
const auto& cart_coords =
db::get<StrahlkorperTags::CartesianCoords<Frame::Inertial>>(box);
const auto vars = solution.variables(
cart_coords, t, typename Solution::template tags<DataVector>{});
const auto& spatial_metric =
get<gr::Tags::SpatialMetric<3, Frame::Inertial, DataVector>>(vars);
const auto inverse_spatial_metric =
determinant_and_inverse(spatial_metric).second;
const auto& normal_one_form =
db::get<StrahlkorperTags::NormalOneForm<Frame::Inertial>>(box);
const DataVector one_over_one_form_magnitude =
1.0 / get(magnitude(
db::get<StrahlkorperTags::NormalOneForm<Frame::Inertial>>(box),
inverse_spatial_metric));
const auto unit_normal_one_form = StrahlkorperGr::unit_normal_one_form(
db::get<StrahlkorperTags::NormalOneForm<Frame::Inertial>>(box),
one_over_one_form_magnitude);
const auto unit_normal_vector =
raise_or_lower_index(unit_normal_one_form, inverse_spatial_metric);
const auto& r_hat = db::get<StrahlkorperTags::Rhat<Frame::Inertial>>(box);
const auto& radius = db::get<StrahlkorperTags::Radius<Frame::Inertial>>(box);
const auto& jacobian =
db::get<StrahlkorperTags::Jacobian<Frame::Inertial>>(box);
const auto area_element = StrahlkorperGr::area_element(
spatial_metric, jacobian, normal_one_form, radius, r_hat);
const auto& ylm = strahlkorper.ylm_spherepack();
const auto& deriv_spatial_metric =
get<Tags::deriv<gr::Tags::SpatialMetric<3, Frame::Inertial, DataVector>,
tmpl::size_t<3>, Frame::Inertial>>(vars);
const auto extrinsic_curvature = gr::extrinsic_curvature(
get<gr::Tags::Lapse<DataVector>>(vars),
get<gr::Tags::Shift<3, Frame::Inertial, DataVector>>(vars),
get<Tags::deriv<gr::Tags::Shift<3, Frame::Inertial, DataVector>,
tmpl::size_t<3>, Frame::Inertial>>(vars),
spatial_metric,
get<Tags::dt<gr::Tags::SpatialMetric<3, Frame::Inertial, DataVector>>>(
vars),
deriv_spatial_metric);
const auto& tangents =
db::get<StrahlkorperTags::Tangents<Frame::Inertial>>(box);
const auto spin_function =
StrahlkorperGr::spin_function(tangents, strahlkorper, unit_normal_vector,
area_element, extrinsic_curvature);
const auto ricci_scalar = TestHelpers::Kerr::horizon_ricci_scalar(
horizon_radius_with_spin_on_z_axis, ylm_with_spin_on_z_axis, ylm, mass,
dimensionless_spin);
const auto spin_vector = StrahlkorperGr::spin_vector(
magnitude(dimensionless_spin), area_element, std::move(radius), r_hat,
ricci_scalar, spin_function, strahlkorper);
CHECK_ITERABLE_APPROX(spin_vector, dimensionless_spin);
}
SPECTRE_TEST_CASE("Unit.ApparentHorizons.StrahlkorperGr.Expansion",
"[ApparentHorizons][Unit]") {
const auto sphere =
Strahlkorper<Frame::Inertial>(8, 8, 2.0, {{0.0, 0.0, 0.0}});
test_expansion(
gr::Solutions::KerrSchild{1.0, {{0.0, 0.0, 0.0}}, {{0.0, 0.0, 0.0}}},
sphere, [](const size_t size) { return DataVector(size, 0.0); });
test_expansion(gr::Solutions::Minkowski<3>{}, sphere,
[](const size_t size) { return DataVector(size, 1.0); });
constexpr int l_max = 20;
const double mass = 4.444;
const std::array<double, 3> spin{{0.3, 0.4, 0.5}};
const std::array<double, 3> center{{0.0, 0.0, 0.0}};
const auto horizon_radius = gr::Solutions::kerr_horizon_radius(
Strahlkorper<Frame::Inertial>(l_max, l_max, 2.0, center)
.ylm_spherepack()
.theta_phi_points(),
mass, spin);
const auto kerr_horizon =
Strahlkorper<Frame::Inertial>(l_max, l_max, get(horizon_radius), center);
test_expansion(gr::Solutions::KerrSchild{mass, spin, center}, kerr_horizon,
[](const size_t size) { return DataVector(size, 0.0); });
}
SPECTRE_TEST_CASE("Unit.ApparentHorizons.StrahlkorperGr.ExtrinsicCurvature",
"[ApparentHorizons][Unit]") {
// N.B.: test_minkowski() fully tests the extrinsic curvature function.
// All components of extrinsic curvature of a sphere in flat space
// are nontrivial; cf. extrinsic_curvature_sphere()
// in StrahlkorperGrTestHelpers.cpp).
TestExtrinsicCurvature::test_minkowski();
}
SPECTRE_TEST_CASE("Unit.ApparentHorizons.StrahlkorperGr.RicciScalar",
"[ApparentHorizons][Unit]") {
const double mass = 1.0;
test_ricci_scalar(
gr::Solutions::KerrSchild(mass, {{0.0, 0.0, 0.0}}, {{0.0, 0.0, 0.0}}),
[&mass](const auto& cartesian_coords) {
return TestHelpers::Schwarzschild::spatial_ricci(cartesian_coords,
mass);
},
[&mass](const size_t size) {
return DataVector(size, 0.5 / square(mass));
});
test_ricci_scalar(
gr::Solutions::Minkowski<3>{},
[](const auto& cartesian_coords) {
return make_with_value<tnsr::ii<DataVector, 3, Frame::Inertial>>(
cartesian_coords, 0.0);
},
[](const size_t size) { return DataVector(size, 0.5); });
}
} // namespace
SPECTRE_TEST_CASE("Unit.ApparentHorizons.StrahlkorperGr.AreaElement",
"[ApparentHorizons][Unit]") {
// Check value of dA for a Schwarzschild horizon and a sphere in flat space
test_area_element(
gr::Solutions::KerrSchild{4.0, {{0.0, 0.0, 0.0}}, {{0.0, 0.0, 0.0}}}, 8.0,
[](const size_t size) { return DataVector(size, 64.0); });
test_area_element(gr::Solutions::Minkowski<3>{}, 2.0,
[](const size_t size) { return DataVector(size, 4.0); });
// Check the area of a Kerr horizon
constexpr int l_max = 22;
const double mass = 4.444;
const std::array<double, 3> spin{{0.4, 0.33, 0.22}};
const std::array<double, 3> center{{0.0, 0.0, 0.0}};
const double kerr_horizon_radius =
mass * (1.0 + sqrt(1.0 - square(magnitude(spin))));
// Eq. (26.84a) of Thorne and Blandford
const double expected_area = 8.0 * M_PI * mass * kerr_horizon_radius;
const double expected_irreducible_mass =
sqrt(0.5 * mass * kerr_horizon_radius);
const auto horizon_radius = gr::Solutions::kerr_horizon_radius(
Strahlkorper<Frame::Inertial>(l_max, l_max, 2.0, center)
.ylm_spherepack()
.theta_phi_points(),
mass, spin);
const auto kerr_horizon =
Strahlkorper<Frame::Inertial>(l_max, l_max, get(horizon_radius), center);
test_area(gr::Solutions::KerrSchild{mass, spin, center}, kerr_horizon,
expected_area, expected_irreducible_mass,
square(mass) * magnitude(spin), mass);
test_euclidean_area_element(kerr_horizon);
test_integral_correspondence(gr::Solutions::Minkowski<3>{}, kerr_horizon);
test_integral_correspondence(gr::Solutions::KerrSchild{mass, spin, center},
kerr_horizon);
// Check that the two methods of computing the surface integral are
// still equal for a surface inside and outside the horizon
// (that is, for spacelike and timelike Strahlkorpers).
const auto inside_kerr_horizon = Strahlkorper<Frame::Inertial>(
l_max, l_max, 0.9 * get(horizon_radius), center);
const auto outside_kerr_horizon = Strahlkorper<Frame::Inertial>(
l_max, l_max, 2.0 * get(horizon_radius), center);
test_integral_correspondence(gr::Solutions::KerrSchild{mass, spin, center},
inside_kerr_horizon);
test_integral_correspondence(gr::Solutions::KerrSchild{mass, spin, center},
outside_kerr_horizon);
test_euclidean_surface_integral_of_vector(kerr_horizon);
test_euclidean_surface_integral_of_vector_2(
gr::Solutions::KerrSchild{mass, spin, center}, kerr_horizon,
expected_area);
}
SPECTRE_TEST_CASE(
"Unit.ApparentHorizons.StrahlkorperGr.SurfaceIntegralOfScalar",
"[ApparentHorizons][Unit]") {
// Check the surface integral of a Schwarzschild horizon, using the radius
// as the scalar
constexpr int l_max = 20;
const double mass = 4.444;
const std::array<double, 3> spin{{0.0, 0.0, 0.0}};
const std::array<double, 3> center{{0.0, 0.0, 0.0}};
const double radius = 2.0 * mass;
// The test will integrate x^2 on a Schwarzschild horizon.
// This is the analytic result.
const double expected_integral = 4.0 * M_PI * square(square(radius)) / 3.0;
const auto horizon =
Strahlkorper<Frame::Inertial>(l_max, l_max, radius, center);
test_surface_integral_of_scalar(gr::Solutions::KerrSchild{mass, spin, center},
horizon, expected_integral);
}
SPECTRE_TEST_CASE("Unit.ApparentHorizons.StrahlkorperGr.SpinFunction",
"[ApparentHorizons][Unit]") {
// Set up Kerr horizon
constexpr int l_max = 24;
const double mass = 4.444;
const std::array<double, 3> spin{{0.4, 0.33, 0.22}};
const std::array<double, 3> center{{0.0, 0.0, 0.0}};
const auto horizon_radius = gr::Solutions::kerr_horizon_radius(
Strahlkorper<Frame::Inertial>(l_max, l_max, 2.0, center)
.ylm_spherepack()
.theta_phi_points(),
mass, spin);
const auto kerr_horizon =
Strahlkorper<Frame::Inertial>(l_max, l_max, get(horizon_radius), center);
// Check value of SpinFunction^2 integrated over the surface for
// Schwarzschild. Expected result is zero.
test_spin_function(gr::Solutions::KerrSchild{mass, {{0.0, 0.0, 0.0}}, center},
Strahlkorper<Frame::Inertial>(l_max, l_max, 8.888, center),
0.0);
// Check value of SpinFunction^2 integrated over the surface for
// Kerr. Derive this by integrating the square of the imaginary
// part of Newman-Penrose Psi^2 on the Kerr horizon using the Kinnersley
// null tetrad. For example, this integral is set up in the section
// ``Spin function for Kerr'' of Geoffrey Lovelace's overleaf note:
// https://v2.overleaf.com/read/twdtxchyrtyv
// The integral does not have a simple, closed form, so just
// enter the expected numerical value for this test.
const double expected_spin_function_sq_integral = 4.0 * 0.0125109627941394;
test_spin_function(gr::Solutions::KerrSchild{mass, spin, center},
kerr_horizon, expected_spin_function_sq_integral);
}
SPECTRE_TEST_CASE(
"Unit.ApparentHorizons.StrahlkorperGr.DimensionfulSpinMagnitude",
"[ApparentHorizons][Unit]") {
const double mass = 2.0;
const std::array<double, 3> generic_dimensionless_spin = {{0.12, 0.08, 0.04}};
const double expected_dimensionless_spin_magnitude =
magnitude(generic_dimensionless_spin);
const double expected_spin_magnitude =
expected_dimensionless_spin_magnitude * square(mass);
const std::array<double, 3> center{{0.0, 0.0, 0.0}};
const double aligned_tolerance = 1.e-13;
const double aligned_l_max = 12;
const std::array<double, 3> aligned_dimensionless_spin = {
{0.0, 0.0, expected_dimensionless_spin_magnitude}};
const auto aligned_horizon_radius = gr::Solutions::kerr_horizon_radius(
Strahlkorper<Frame::Inertial>(aligned_l_max, aligned_l_max, 2.0, center)
.ylm_spherepack()
.theta_phi_points(),
mass, aligned_dimensionless_spin);
const auto aligned_kerr_horizon = Strahlkorper<Frame::Inertial>(
aligned_l_max, aligned_l_max, get(aligned_horizon_radius), center);
test_dimensionful_spin_magnitude(
gr::Solutions::KerrSchild{mass, aligned_dimensionless_spin, center},
aligned_kerr_horizon, mass, aligned_dimensionless_spin,
aligned_horizon_radius, aligned_kerr_horizon.ylm_spherepack(),
expected_spin_magnitude, aligned_tolerance);
const double generic_tolerance = 1.e-13;
const int generic_l_max = 12;
const double expected_generic_dimensionless_spin_magnitude =
magnitude(generic_dimensionless_spin);
const double expected_generic_spin_magnitude =
expected_generic_dimensionless_spin_magnitude * square(mass);
const auto generic_horizon_radius = gr::Solutions::kerr_horizon_radius(
Strahlkorper<Frame::Inertial>(generic_l_max, generic_l_max, 2.0, center)
.ylm_spherepack()
.theta_phi_points(),
mass, generic_dimensionless_spin);
const auto generic_kerr_horizon = Strahlkorper<Frame::Inertial>(
generic_l_max, generic_l_max, get(generic_horizon_radius), center);
// Create rotated horizon radius, Strahlkorper, with same spin magnitude
// but with spin on the z axis
const auto rotated_horizon_radius = gr::Solutions::kerr_horizon_radius(
Strahlkorper<Frame::Inertial>(generic_l_max, generic_l_max, 2.0, center)
.ylm_spherepack()
.theta_phi_points(),
mass, aligned_dimensionless_spin);
const auto rotated_kerr_horizon = Strahlkorper<Frame::Inertial>(
generic_l_max, generic_l_max, get(rotated_horizon_radius), center);
test_dimensionful_spin_magnitude(
gr::Solutions::KerrSchild{mass, generic_dimensionless_spin, center},
generic_kerr_horizon, mass, generic_dimensionless_spin,
rotated_horizon_radius, rotated_kerr_horizon.ylm_spherepack(),
expected_generic_spin_magnitude, generic_tolerance);
}
SPECTRE_TEST_CASE("Unit.ApparentHorizons.StrahlkorperGr.SpinVector",
"[ApparentHorizons][Unit]") {
// Set up Kerr horizon
constexpr int l_max = 20;
const double mass = 2.0;
const std::array<double, 3> spin{{0.04, 0.08, 0.12}};
const auto spin_magnitude = magnitude(spin);
const std::array<double, 3> center{{0.0, 0.0, 0.0}};
const auto horizon_radius = gr::Solutions::kerr_horizon_radius(
Strahlkorper<Frame::Inertial>(l_max, l_max, 2.0, center)
.ylm_spherepack()
.theta_phi_points(),
mass, spin);
const auto kerr_horizon =
Strahlkorper<Frame::Inertial>(l_max, l_max, get(horizon_radius), center);
const auto horizon_radius_with_spin_on_z_axis =
gr::Solutions::kerr_horizon_radius(
Strahlkorper<Frame::Inertial>(l_max, l_max, 2.0, center)
.ylm_spherepack()
.theta_phi_points(),
mass, {{0.0, 0.0, spin_magnitude}});
const auto kerr_horizon_with_spin_on_z_axis = Strahlkorper<Frame::Inertial>(
l_max, l_max, get(horizon_radius_with_spin_on_z_axis), center);
// Check that the StrahlkorperGr::spin_vector() correctly recovers the
// chosen dimensionless spin
test_spin_vector(gr::Solutions::KerrSchild{mass, spin, center}, kerr_horizon,
mass, spin, horizon_radius_with_spin_on_z_axis,
kerr_horizon_with_spin_on_z_axis.ylm_spherepack());
}
| 44.386603
| 81
| 0.709857
|
kidder
|
11410e1b98a4b57d80e25385964a1af4a2220a56
| 2,207
|
cpp
|
C++
|
samples/snippets/cpp/VS_Snippets_WebNet/HtmlTextWriter_Properties/CPP/htmltextwriter_properties1.cpp
|
hamarb123/dotnet-api-docs
|
6aeb55784944a2f1f5e773b657791cbd73a92dd4
|
[
"CC-BY-4.0",
"MIT"
] | 421
|
2018-04-01T01:57:50.000Z
|
2022-03-28T15:24:42.000Z
|
samples/snippets/cpp/VS_Snippets_WebNet/HtmlTextWriter_Properties/CPP/htmltextwriter_properties1.cpp
|
hamarb123/dotnet-api-docs
|
6aeb55784944a2f1f5e773b657791cbd73a92dd4
|
[
"CC-BY-4.0",
"MIT"
] | 5,797
|
2018-04-02T21:12:23.000Z
|
2022-03-31T23:54:38.000Z
|
samples/snippets/cpp/VS_Snippets_WebNet/HtmlTextWriter_Properties/CPP/htmltextwriter_properties1.cpp
|
hamarb123/dotnet-api-docs
|
6aeb55784944a2f1f5e773b657791cbd73a92dd4
|
[
"CC-BY-4.0",
"MIT"
] | 1,482
|
2018-03-31T11:26:20.000Z
|
2022-03-30T22:36:45.000Z
|
#using <System.dll>
#using <System.Drawing.dll>
#using <System.Web.dll>
using namespace System;
using namespace System::IO;
using namespace System::Web::UI;
using namespace System::Web::UI::WebControls;
public ref class FirstControl: public WebControl
{
private:
// The message property.
String^ myMessage;
public:
FirstControl()
{
myMessage = "Hello";
}
property String^ Message
{
// Accessors for the message property.
virtual String^ get()
{
return myMessage;
}
virtual void set( String^ value )
{
myMessage = value;
}
}
protected:
// <snippet1>
// Override a control's Render method to determine what it
// displays when included in a Web Forms page.
virtual void Render( HtmlTextWriter^ writer ) override
{
// <snippet2>
// Get the value of the current markup writer's
// Encoding property, convert it to a string, and
// write it to the markup stream.
writer->Write( String::Concat( "Encoding : ", writer->Encoding, "<br>" ) );
// </snippet2>
// <snippet3>
// Write the opening tag of a Font element.
writer->WriteBeginTag( "font" );
// Write a Color style attribute to the opening tag
// of the Font element and set its value to red.
writer->WriteAttribute( "color", "red" );
// Write the closing character for the opening tag of
// the Font element.
writer->Write( '>' );
// Use the InnerWriter property to create a TextWriter
// object that will write the content found between
// the opening and closing tags of the Font element.
// Message is a string property of the control that
// overrides the Render method.
TextWriter^ innerTextWriter = writer->InnerWriter;
innerTextWriter->Write( String::Concat( Message, "<br> The time on the server : ", System::DateTime::Now.ToLongTimeString() ) );
// Write the closing tag of the Font element.
writer->WriteEndTag( "font" );
}
// </snippet3>
};
// </snippet1>
| 26.914634
| 135
| 0.598097
|
hamarb123
|
1142775d284a7f7bc5f56c16a829232f6b3f267a
| 665
|
cpp
|
C++
|
src/main.cpp
|
Dcbaas/DAVID_BAAS-SANTIAGO_QUIROGA-Sudoku-Project
|
d9db5a5db1cacd86b08fd766dc9c4ea41e0efb7c
|
[
"MIT"
] | null | null | null |
src/main.cpp
|
Dcbaas/DAVID_BAAS-SANTIAGO_QUIROGA-Sudoku-Project
|
d9db5a5db1cacd86b08fd766dc9c4ea41e0efb7c
|
[
"MIT"
] | null | null | null |
src/main.cpp
|
Dcbaas/DAVID_BAAS-SANTIAGO_QUIROGA-Sudoku-Project
|
d9db5a5db1cacd86b08fd766dc9c4ea41e0efb7c
|
[
"MIT"
] | null | null | null |
#include "sudoku_solver.h"
#include <iostream>
int main(int argc, char** argv){
int board[9][9] = {{ 0, 3, 0, 0, 0, 0, 0, 2, 0 },
{ 0, 9, 0, 0, 0, 0, 0, 8, 5 },
{ 5, 0, 0, 0, 8, 0, 4, 0, 0 },
{ 4, 0, 7, 2, 0, 6, 8, 9, 0 },
{ 0, 1, 0, 8, 0, 9, 0, 4, 0 },
{ 0, 8, 9, 5, 0, 1, 3, 0, 2 },
{ 0, 0, 3, 0, 1, 0, 0, 0, 9 },
{ 9, 4, 0, 0, 0, 0, 0, 1, 0 },
{ 0, 7, 0, 0, 0, 0, 0, 3, 0 }
};
bool out = sudoku_solver(board);
if(out)
std::cout << "true" << std::endl;
return 0;
}
| 31.666667
| 51
| 0.306767
|
Dcbaas
|
11437d745b979f374de8be1040638f7cb3af4b89
| 2,409
|
cc
|
C++
|
src/SoftMaxLoss.cc
|
wylqq312715289/N3LDG-plus
|
26069aaa877359d6a5838d085187957655027d7e
|
[
"Apache-2.0"
] | null | null | null |
src/SoftMaxLoss.cc
|
wylqq312715289/N3LDG-plus
|
26069aaa877359d6a5838d085187957655027d7e
|
[
"Apache-2.0"
] | null | null | null |
src/SoftMaxLoss.cc
|
wylqq312715289/N3LDG-plus
|
26069aaa877359d6a5838d085187957655027d7e
|
[
"Apache-2.0"
] | null | null | null |
#include "SoftMaxLoss.h"
dtype softMaxLoss(PNode x, const vector<dtype> &answer, Metric &eval,
dtype batchsize) {
int nDim = x->getDim();
int labelsize = answer.size();
if (labelsize != nDim) {
std::cerr << "softmax_loss error: dim size invalid" << std::endl;
return -1.0;
}
NRVec<dtype> scores(nDim);
dtype cost = 0.0;
int optLabel = -1;
for (int i = 0; i < nDim; ++i) {
if (answer[i] >= 0) {
if (optLabel < 0 || x->val()[i] > x->val()[optLabel])
optLabel = i;
}
}
dtype sum1 = 0, sum2 = 0, maxScore = x->val()[optLabel];
for (int i = 0; i < nDim; ++i) {
scores[i] = -1e10;
if (answer[i] >= 0) {
scores[i] = exp(x->val()[i] - maxScore);
if (answer[i] == 1)
sum1 += scores[i];
sum2 += scores[i];
}
}
cost += (log(sum2) - log(sum1)) / batchsize;
if (answer[optLabel] == 1)
eval.correct_label_count++;
eval.overall_label_count++;
for (int i = 0; i < nDim; ++i) {
if (answer[i] >= 0) {
x->loss()[i] = (scores[i] / sum2 - answer[i]) / batchsize;
}
}
return cost;
}
dtype softMaxLoss(Node &node, int answer, Metric &metric, int batchsize) {
std::vector<dtype> fit_answer;
for (int i = 0; i < node.getDim(); ++i) {
fit_answer.push_back(i == answer);
}
return softMaxLoss(&node, fit_answer, metric, batchsize);
}
#if USE_GPU
dtype softMaxLoss(const std::vector<PNode> &x, const std::vector<int> &answers,
n3ldg_cuda::DeviceInt &correct,
int batchsize = 1) {
cerr << "unsupported operation" << endl;
abort();
}
#endif
dtype cost(PNode x, const vector<dtype> &answer, int batchsize) {
int nDim = x->getDim();
int labelsize = answer.size();
if (labelsize != nDim) {
std::cerr << "softmax_loss error: dim size invalid" << std::endl;
return -1.0;
}
NRVec<dtype> scores(nDim);
dtype cost = 0.0;
int optLabel = -1;
for (int i = 0; i < nDim; ++i) {
if (answer[i] >= 0) {
if (optLabel < 0 || x->val()[i] > x->val()[optLabel])
optLabel = i;
}
}
dtype sum1 = 0, sum2 = 0, maxScore = x->val()[optLabel];
for (int i = 0; i < nDim; ++i) {
scores[i] = -1e10;
if (answer[i] >= 0) {
scores[i] = exp(x->val()[i] - maxScore);
if (answer[i] == 1)
sum1 += scores[i];
sum2 += scores[i];
}
}
cost += (log(sum2) - log(sum1)) / batchsize;
return cost;
}
| 24.333333
| 79
| 0.54587
|
wylqq312715289
|
1146566402db3f28041a2eaaa861eb708cb2a02d
| 10,207
|
cc
|
C++
|
src/main/window.cc
|
sp-nitech/SPTK
|
d571e4d23be1fa8c15846da3165a10746ef7c421
|
[
"Apache-2.0"
] | 91
|
2017-12-25T14:13:17.000Z
|
2022-03-15T14:33:23.000Z
|
src/main/window.cc
|
sp-nitech/SPTK
|
d571e4d23be1fa8c15846da3165a10746ef7c421
|
[
"Apache-2.0"
] | 4
|
2020-09-28T03:58:29.000Z
|
2021-12-14T01:23:13.000Z
|
src/main/window.cc
|
sp-nitech/SPTK
|
d571e4d23be1fa8c15846da3165a10746ef7c421
|
[
"Apache-2.0"
] | 16
|
2018-03-12T07:08:09.000Z
|
2022-03-22T02:38:13.000Z
|
// ------------------------------------------------------------------------ //
// Copyright 2021 SPTK Working Group //
// //
// Licensed under the Apache License, Version 2.0 (the "License"); //
// you may not use this file except in compliance with the License. //
// You may obtain a copy of the License at //
// //
// http://www.apache.org/licenses/LICENSE-2.0 //
// //
// Unless required by applicable law or agreed to in writing, software //
// distributed under the License is distributed on an "AS IS" BASIS, //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and //
// limitations under the License. //
// ------------------------------------------------------------------------ //
#include <getopt.h> // getopt_long
#include <fstream> // std::ifstream
#include <iomanip> // std::setw
#include <iostream> // std::cerr, std::cin, std::cout, std::endl, etc.
#include <sstream> // std::ostringstream
#include <vector> // std::vector
#include "SPTK/utils/sptk_utils.h"
#include "SPTK/window/data_windowing.h"
#include "SPTK/window/standard_window.h"
namespace {
const int kDefaultFrameLength(256);
const sptk::DataWindowing::NormalizationType kDefaultNormalizationType(
sptk::DataWindowing::NormalizationType::kPower);
const sptk::StandardWindow::WindowType kDefaultWindowType(
sptk::StandardWindow::WindowType::kBlackman);
void PrintUsage(std::ostream* stream) {
// clang-format off
*stream << std::endl;
*stream << " window - data windowing" << std::endl;
*stream << std::endl;
*stream << " usage:" << std::endl;
*stream << " window [ options ] [ infile ] > stdout" << std::endl;
*stream << " options:" << std::endl;
*stream << " -l l : frame length of input ( int)[" << std::setw(5) << std::right << kDefaultFrameLength << "][ 0 < l <= L ]" << std::endl; // NOLINT
*stream << " -L L : frame length of output ( int)[" << std::setw(5) << std::right << "l" << "][ l <= L <= ]" << std::endl; // NOLINT
*stream << " -n n : normalization type ( int)[" << std::setw(5) << std::right << kDefaultNormalizationType << "][ 0 <= n <= 2 ]" << std::endl; // NOLINT
*stream << " 0 (none)" << std::endl;
*stream << " 1 (power)" << std::endl;
*stream << " 2 (magnitude)" << std::endl;
*stream << " -w w : window type ( int)[" << std::setw(5) << std::right << kDefaultWindowType << "][ 0 <= w <= 5 ]" << std::endl; // NOLINT
*stream << " 0 (Blackman)" << std::endl;
*stream << " 1 (Hamming)" << std::endl;
*stream << " 2 (Hanning)" << std::endl;
*stream << " 3 (Bartlett)" << std::endl;
*stream << " 4 (trapezoidal)" << std::endl;
*stream << " 5 (rectangular)" << std::endl;
*stream << " -h : print this message" << std::endl;
*stream << " infile:" << std::endl;
*stream << " data sequence (double)[stdin]" << std::endl; // NOLINT
*stream << " stdout:" << std::endl;
*stream << " windowed data sequence (double)" << std::endl;
*stream << std::endl;
*stream << " SPTK: version " << sptk::kVersion << std::endl;
*stream << std::endl;
// clang-format on
}
} // namespace
/**
* @a window [ @e option ] [ @e infile ]
*
* - @b -l @e int
* - input length @f$(1 \le L_1)@f$
* - @b -L @e int
* - output length @f$(1 \le L_2)@f$
* - @b -n @e int
* - normalization type
* \arg @c 0 none
* \arg @c 1 power
* \arg @c 2 magnitude
* - @b -w @e int
* - window type
* \arg @c 0 Blackman
* \arg @c 1 Hamming
* \arg @c 2 Hanning
* \arg @c 3 Bartlett
* \arg @c 4 Trapezoidal
* \arg @c 5 Rectangular
* - @b infile @e str
* - double-type data sequence
* - @b stdout
* - double-type windowed data sequence
*
* The below example performs spectral analysis with Blackman window.
*
* @code{.sh}
* frame -l 400 -p 80 data.d | window -l 400 -L 512 | spec -l 512 > data.spec
* @endcode
*
* @param[in] argc Number of arguments.
* @param[in] argv Argument vector.
* @return 0 on success, 1 on failure.
*/
int main(int argc, char* argv[]) {
int input_length(kDefaultFrameLength);
int output_length(kDefaultFrameLength);
bool is_output_length_specified(false);
sptk::DataWindowing::NormalizationType normalization_type(
kDefaultNormalizationType);
sptk::StandardWindow::WindowType window_type(kDefaultWindowType);
for (;;) {
const int option_char(getopt_long(argc, argv, "l:L:n:w:h", NULL, NULL));
if (-1 == option_char) break;
switch (option_char) {
case 'l': {
if (!sptk::ConvertStringToInteger(optarg, &input_length) ||
input_length <= 0) {
std::ostringstream error_message;
error_message
<< "The argument for the -l option must be a positive integer";
sptk::PrintErrorMessage("window", error_message);
return 1;
}
break;
}
case 'L': {
if (!sptk::ConvertStringToInteger(optarg, &output_length) ||
output_length <= 0) {
std::ostringstream error_message;
error_message
<< "The argument for the -L option must be a positive integer";
sptk::PrintErrorMessage("window", error_message);
return 1;
}
is_output_length_specified = true;
break;
}
case 'n': {
const int min(0);
const int max(static_cast<int>(sptk::DataWindowing::NormalizationType::
kNumNormalizationTypes) -
1);
int tmp;
if (!sptk::ConvertStringToInteger(optarg, &tmp) ||
!sptk::IsInRange(tmp, min, max)) {
std::ostringstream error_message;
error_message << "The argument for the -n option must be an integer "
<< "in the range of " << min << " to " << max;
sptk::PrintErrorMessage("window", error_message);
return 1;
}
normalization_type =
static_cast<sptk::DataWindowing::NormalizationType>(tmp);
break;
}
case 'w': {
const int min(0);
const int max(5);
int tmp;
if (!sptk::ConvertStringToInteger(optarg, &tmp) ||
!sptk::IsInRange(tmp, min, max)) {
std::ostringstream error_message;
error_message << "The argument for the -w option must be an integer "
<< "in the range of " << min << " to " << max;
sptk::PrintErrorMessage("window", error_message);
return 1;
}
if (0 == tmp) {
window_type = sptk::StandardWindow::kBlackman;
} else if (1 == tmp) {
window_type = sptk::StandardWindow::kHamming;
} else if (2 == tmp) {
window_type = sptk::StandardWindow::kHanning;
} else if (3 == tmp) {
window_type = sptk::StandardWindow::kBartlett;
} else if (4 == tmp) {
window_type = sptk::StandardWindow::kTrapezoidal;
} else if (5 == tmp) {
window_type = sptk::StandardWindow::kRectangular;
}
break;
}
case 'h': {
PrintUsage(&std::cout);
return 0;
}
default: {
PrintUsage(&std::cerr);
return 1;
}
}
}
if (!is_output_length_specified) {
output_length = input_length;
} else if (output_length < input_length) {
std::ostringstream error_message;
error_message << "The length of data sequence " << input_length
<< " must be equal to or less than that of windowed one "
<< output_length;
sptk::PrintErrorMessage("window", error_message);
return 1;
}
const int num_input_files(argc - optind);
if (1 < num_input_files) {
std::ostringstream error_message;
error_message << "Too many input files";
sptk::PrintErrorMessage("window", error_message);
return 1;
}
const char* input_file(0 == num_input_files ? NULL : argv[optind]);
std::ifstream ifs;
ifs.open(input_file, std::ios::in | std::ios::binary);
if (ifs.fail() && NULL != input_file) {
std::ostringstream error_message;
error_message << "Cannot open file " << input_file;
sptk::PrintErrorMessage("window", error_message);
return 1;
}
std::istream& input_stream(ifs.fail() ? std::cin : ifs);
sptk::StandardWindow standard_window(input_length, window_type, false);
sptk::DataWindowing data_windowing(&standard_window, output_length,
normalization_type);
if (!data_windowing.IsValid()) {
std::ostringstream error_message;
error_message << "Failed to initialize DataWindowing";
sptk::PrintErrorMessage("window", error_message);
return 1;
}
std::vector<double> data_sequence(input_length);
std::vector<double> windowed_data_sequence(output_length);
while (sptk::ReadStream(false, 0, 0, input_length, &data_sequence,
&input_stream, NULL)) {
if (!data_windowing.Run(data_sequence, &windowed_data_sequence)) {
std::ostringstream error_message;
error_message << "Failed to apply a window function";
sptk::PrintErrorMessage("window", error_message);
return 1;
}
if (!sptk::WriteStream(0, output_length, windowed_data_sequence, &std::cout,
NULL)) {
std::ostringstream error_message;
error_message << "Failed to write windowed data sequence";
sptk::PrintErrorMessage("window", error_message);
return 1;
}
}
return 0;
}
| 39.10728
| 168
| 0.548153
|
sp-nitech
|
114a2e7213cd5ba6f890343424905fea6979c0dc
| 12,908
|
cpp
|
C++
|
src/jpeg.imageio/jpegoutput.cpp
|
ndubey/oiio
|
fb00e178be048c31f478076977d17434c310472c
|
[
"BSD-3-Clause"
] | 1
|
2016-09-05T01:16:09.000Z
|
2016-09-05T01:16:09.000Z
|
src/jpeg.imageio/jpegoutput.cpp
|
Alexander-Murashko/oiio
|
2cb95cf674e6cb085eb14614c428535ed2b8989b
|
[
"BSD-3-Clause"
] | null | null | null |
src/jpeg.imageio/jpegoutput.cpp
|
Alexander-Murashko/oiio
|
2cb95cf674e6cb085eb14614c428535ed2b8989b
|
[
"BSD-3-Clause"
] | null | null | null |
/*
Copyright 2008 Larry Gritz and the other authors and contributors.
All Rights Reserved.
Based on BSD-licensed software Copyright 2004 NVIDIA Corp.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the software's owners nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(This is the Modified BSD License)
*/
#include <cassert>
#include <cstdio>
#include <vector>
#include <boost/algorithm/string.hpp>
using boost::algorithm::iequals;
extern "C" {
#include "jpeglib.h"
}
#include "imageio.h"
#include "fmath.h"
#include "jpeg_pvt.h"
OIIO_PLUGIN_NAMESPACE_BEGIN
#define DBG if(0)
// See JPEG library documentation in /usr/share/doc/libjpeg-devel-6b
class JpgOutput : public ImageOutput {
public:
JpgOutput () { init(); }
virtual ~JpgOutput () { close(); }
virtual const char * format_name (void) const { return "jpeg"; }
virtual bool supports (const std::string &property) const { return false; }
virtual bool open (const std::string &name, const ImageSpec &spec,
OpenMode mode=Create);
virtual bool write_scanline (int y, int z, TypeDesc format,
const void *data, stride_t xstride);
virtual bool close ();
virtual bool copy_image (ImageInput *in);
private:
FILE *m_fd;
std::string m_filename;
int m_next_scanline; // Which scanline is the next to write?
std::vector<unsigned char> m_scratch;
struct jpeg_compress_struct m_cinfo;
struct jpeg_error_mgr c_jerr;
jvirt_barray_ptr *m_copy_coeffs;
struct jpeg_decompress_struct *m_copy_decompressor;
void init (void) {
m_fd = NULL;
m_copy_coeffs = NULL;
m_copy_decompressor = NULL;
}
};
OIIO_PLUGIN_EXPORTS_BEGIN
DLLEXPORT ImageOutput *jpeg_output_imageio_create () {
return new JpgOutput;
}
DLLEXPORT const char *jpeg_output_extensions[] = {
"jpg", "jpe", "jpeg", "jif", "jfif", ".jfi", NULL
};
OIIO_PLUGIN_EXPORTS_END
bool
JpgOutput::open (const std::string &name, const ImageSpec &newspec,
OpenMode mode)
{
if (mode != Create) {
error ("%s does not support subimages or MIP levels", format_name());
return false;
}
// Save name and spec for later use
m_filename = name;
m_spec = newspec;
// Check for things this format doesn't support
if (m_spec.width < 1 || m_spec.height < 1) {
error ("Image resolution must be at least 1x1, you asked for %d x %d",
m_spec.width, m_spec.height);
return false;
}
if (m_spec.depth < 1)
m_spec.depth = 1;
if (m_spec.depth > 1) {
error ("%s does not support volume images (depth > 1)", format_name());
return false;
}
if (m_spec.nchannels != 1 && m_spec.nchannels != 3 &&
m_spec.nchannels != 4) {
error ("%s does not support %d-channel images\n",
format_name(), m_spec.nchannels);
return false;
}
m_fd = fopen (name.c_str(), "wb");
if (m_fd == NULL) {
error ("Unable to open file \"%s\"", name.c_str());
return false;
}
int quality = 98;
const ImageIOParameter *qual = newspec.find_attribute ("CompressionQuality",
TypeDesc::INT);
if (qual)
quality = * (const int *)qual->data();
m_cinfo.err = jpeg_std_error (&c_jerr); // set error handler
jpeg_create_compress (&m_cinfo); // create compressor
jpeg_stdio_dest (&m_cinfo, m_fd); // set output stream
// Set image and compression parameters
m_cinfo.image_width = m_spec.width;
m_cinfo.image_height = m_spec.height;
if (m_spec.nchannels == 3 || m_spec.nchannels == 4) {
m_cinfo.input_components = 3;
m_cinfo.in_color_space = JCS_RGB;
} else if (m_spec.nchannels == 1) {
m_cinfo.input_components = 1;
m_cinfo.in_color_space = JCS_GRAYSCALE;
}
m_cinfo.density_unit = 2; // RESUNIT_INCH;
m_cinfo.X_density = 72;
m_cinfo.Y_density = 72;
m_cinfo.write_JFIF_header = true;
if (m_copy_coeffs) {
// Back door for copy()
jpeg_copy_critical_parameters (m_copy_decompressor, &m_cinfo);
DBG std::cout << "out open: copy_critical_parameters\n";
jpeg_write_coefficients (&m_cinfo, m_copy_coeffs);
DBG std::cout << "out open: write_coefficients\n";
} else {
// normal write of scanlines
jpeg_set_defaults (&m_cinfo); // default compression
DBG std::cout << "out open: set_defaults\n";
jpeg_set_quality (&m_cinfo, quality, TRUE); // baseline values
DBG std::cout << "out open: set_quality\n";
jpeg_start_compress (&m_cinfo, TRUE); // start working
DBG std::cout << "out open: start_compress\n";
}
m_next_scanline = 0; // next scanline we'll write
// Write JPEG comment, if sent an 'ImageDescription'
ImageIOParameter *comment = m_spec.find_attribute ("ImageDescription",
TypeDesc::STRING);
if (comment && comment->data()) {
const char **c = (const char **) comment->data();
jpeg_write_marker (&m_cinfo, JPEG_COM, (JOCTET*)*c, strlen(*c) + 1);
}
if (iequals (m_spec.get_string_attribute ("oiio:ColorSpace"), "sRGB"))
m_spec.attribute ("Exif:ColorSpace", 1);
// Write EXIF info
std::vector<char> exif;
// Start the blob with "Exif" and two nulls. That's how it
// always is in the JPEG files I've examined.
exif.push_back ('E');
exif.push_back ('x');
exif.push_back ('i');
exif.push_back ('f');
exif.push_back (0);
exif.push_back (0);
encode_exif (m_spec, exif);
jpeg_write_marker (&m_cinfo, JPEG_APP0+1, (JOCTET*)&exif[0], exif.size());
// Write IPTC IIM metadata tags, if we have anything
std::vector<char> iptc;
encode_iptc_iim (m_spec, iptc);
if (iptc.size()) {
static char photoshop[] = "Photoshop 3.0";
std::vector<char> head (photoshop, photoshop+strlen(photoshop)+1);
static char _8BIM[] = "8BIM";
head.insert (head.end(), _8BIM, _8BIM+4);
head.push_back (4); // 0x0404
head.push_back (4);
head.push_back (0); // four bytes of zeroes
head.push_back (0);
head.push_back (0);
head.push_back (0);
head.push_back ((char)(iptc.size() >> 8)); // size of block
head.push_back ((char)(iptc.size() & 0xff));
iptc.insert (iptc.begin(), head.begin(), head.end());
jpeg_write_marker (&m_cinfo, JPEG_APP0+13, (JOCTET*)&iptc[0], iptc.size());
}
// Write XMP packet, if we have anything
std::string xmp = encode_xmp (m_spec, true);
if (! xmp.empty()) {
static char prefix[] = "http://ns.adobe.com/xap/1.0/";
std::vector<char> block (prefix, prefix+strlen(prefix)+1);
block.insert (block.end(), xmp.c_str(), xmp.c_str()+xmp.length()+1);
jpeg_write_marker (&m_cinfo, JPEG_APP0+1, (JOCTET*)&block[0], block.size());
}
m_spec.set_format (TypeDesc::UINT8); // JPG is only 8 bit
return true;
}
bool
JpgOutput::write_scanline (int y, int z, TypeDesc format,
const void *data, stride_t xstride)
{
y -= m_spec.y;
if (y != m_next_scanline) {
error ("Attempt to write scanlines out of order to %s",
m_filename.c_str());
return false;
}
if (y >= (int)m_cinfo.image_height) {
error ("Attempt to write too many scanlines to %s", m_filename.c_str());
return false;
}
assert (y == (int)m_cinfo.next_scanline);
// It's so common to want to write RGBA data out as JPEG (which only
// supports RGB) than it would be too frustrating to reject it.
// Instead, we just silently drop the alpha. Here's where we do the
// dirty work, temporarily doctoring the spec so that
// to_native_scanline properly contiguizes the first three channels,
// then we restore it. The call to to_native_scanline below needs
// m_spec.nchannels to be set to the true number of channels we're
// writing, or it won't arrange the data properly. But if we
// doctored m_spec.nchannels = 3 permanently, then subsequent calls
// to write_scanline (including any surrounding call to write_image)
// with stride=AutoStride would screw up the strides since the
// user's stride is actually not 3 channels.
int save_nchannels = m_spec.nchannels;
m_spec.nchannels = m_cinfo.input_components;
data = to_native_scanline (format, data, xstride, m_scratch);
m_spec.nchannels = save_nchannels;
jpeg_write_scanlines (&m_cinfo, (JSAMPLE**)&data, 1);
++m_next_scanline;
return true;
}
bool
JpgOutput::close ()
{
if (! m_fd) // Already closed
return true;
if (m_next_scanline < spec().height && m_copy_coeffs == NULL) {
// But if we've only written some scanlines, write the rest to avoid
// errors
std::vector<char> buf (spec().scanline_bytes(), 0);
char *data = &buf[0];
while (m_next_scanline < spec().height) {
jpeg_write_scanlines (&m_cinfo, (JSAMPLE **)&data, 1);
// DBG std::cout << "out close: write_scanlines\n";
++m_next_scanline;
}
}
if (m_next_scanline >= spec().height || m_copy_coeffs) {
DBG std::cout << "out close: about to finish_compress\n";
jpeg_finish_compress (&m_cinfo);
DBG std::cout << "out close: finish_compress\n";
} else {
DBG std::cout << "out close: about to abort_compress\n";
jpeg_abort_compress (&m_cinfo);
DBG std::cout << "out close: abort_compress\n";
}
DBG std::cout << "out close: about to destroy_compress\n";
jpeg_destroy_compress (&m_cinfo);
fclose (m_fd);
m_fd = NULL;
init();
return true;
}
bool
JpgOutput::copy_image (ImageInput *in)
{
if (in && !strcmp(in->format_name(), "jpeg")) {
JpgInput *jpg_in = dynamic_cast<JpgInput *> (in);
std::string in_name = jpg_in->filename ();
DBG std::cout << "JPG copy_image from " << in_name << "\n";
// Save the original input spec and close it
ImageSpec orig_in_spec = in->spec();
in->close ();
DBG std::cout << "Closed old file\n";
// Re-open the input spec, with special request that the JpgInput
// will recognize as a request to merely open, but not start the
// decompressor.
ImageSpec in_spec;
ImageSpec config_spec;
config_spec.attribute ("_jpeg:raw", 1);
in->open (in_name, in_spec, config_spec);
// Re-open the output
std::string out_name = m_filename;
ImageSpec orig_out_spec = spec();
close ();
m_copy_coeffs = (jvirt_barray_ptr *)jpg_in->coeffs();
m_copy_decompressor = &jpg_in->m_cinfo;
open (out_name, orig_out_spec);
// Strangeness -- the write_coefficients somehow sets things up
// so that certain writes only happen in close(), which MUST
// happen while the input file is still open. So we go ahead
// and close() now, so that the caller of copy_image() doesn't
// close the input file first and then wonder why they crashed.
close ();
return true;
}
return ImageOutput::copy_image (in);
}
OIIO_PLUGIN_NAMESPACE_END
| 35.076087
| 84
| 0.633096
|
ndubey
|
114ae27168d01b04fcd2e2dbff9447045aff7309
| 1,988
|
cpp
|
C++
|
test/wiztk/gui/gles2-backend/test-gles2-backend.cpp
|
wiztk/framework
|
179baf8a24406b19d3f4ea28e8405358b21f8446
|
[
"Apache-2.0"
] | 37
|
2017-11-22T14:15:33.000Z
|
2021-11-25T20:39:39.000Z
|
test/wiztk/gui/gles2-backend/test-gles2-backend.cpp
|
wiztk/framework
|
179baf8a24406b19d3f4ea28e8405358b21f8446
|
[
"Apache-2.0"
] | 3
|
2018-03-01T12:44:22.000Z
|
2021-01-04T23:14:41.000Z
|
test/wiztk/gui/gles2-backend/test-gles2-backend.cpp
|
wiztk/framework
|
179baf8a24406b19d3f4ea28e8405358b21f8446
|
[
"Apache-2.0"
] | 10
|
2017-11-25T19:09:11.000Z
|
2020-12-02T02:05:47.000Z
|
/*
* Copyright 2017 - 2018 The WizTK Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "test-gles2-backend.hpp"
#include "wiztk/gui/application.hpp"
#include "wiztk/gui/window.hpp"
#include "wiztk/gui/push-button.hpp"
#include "wiztk/gui/gles2-backend.hpp"
using namespace wiztk::gui;
using namespace wiztk::graphics;
class Responder : public wiztk::base::Trackable {
public:
Responder() = default;
~Responder() override = default;
void OnCheckGLES2Backend(__SLOT__);
};
void Responder::OnCheckGLES2Backend(wiztk::base::SLOT slot) {
GLES2Backend backend1;
ASSERT_TRUE(backend1.IsValid());
GLES2Backend backend2;
ASSERT_TRUE(backend2.IsValid());
fprintf(stdout, "1: major: %d, minor: %d\n", backend1.GetVersionMajor(), backend1.GetVersionMinor());
fprintf(stdout, "2: major: %d, minor: %d\n", backend2.GetVersionMajor(), backend2.GetVersionMinor());
}
/**
* @brief Show a default empty window
*
* Expected result: display and resize a default window
*/
TEST_F(TestGLES2Backend, show) {
int argc = 1;
char argv1[] = "show"; // to avoid compile warning
char *argv[] = {argv1};
Application app(argc, argv);
Responder responder;
wiztk::gui::Window win(400, 300, "Test GLES2Backend");
auto *button = PushButton::Create("Click to Run");
button->clicked().Connect(&responder, &Responder::OnCheckGLES2Backend);
win.SetContentView(button);
win.Show();
int result = app.Run();
ASSERT_TRUE(result == 0);
}
| 27.611111
| 103
| 0.716298
|
wiztk
|
114c81042213b6ff7909f38fcd363c7c426cfb3c
| 1,107
|
cpp
|
C++
|
Simple++/Time/Tick.cpp
|
Oriode/Simpleplusplus
|
2ba44eeab5078d6dab66bdefdf73617696b8cb2e
|
[
"Apache-2.0"
] | null | null | null |
Simple++/Time/Tick.cpp
|
Oriode/Simpleplusplus
|
2ba44eeab5078d6dab66bdefdf73617696b8cb2e
|
[
"Apache-2.0"
] | null | null | null |
Simple++/Time/Tick.cpp
|
Oriode/Simpleplusplus
|
2ba44eeab5078d6dab66bdefdf73617696b8cb2e
|
[
"Apache-2.0"
] | null | null | null |
#include "Tick.h"
namespace Time {
Time::Tick operator-( const Tick & t1, const Tick & t2 ) {
return Tick( t1.getValue() - t2.getValue() );
}
Tick getClock() {
return Tick( clock() );
}
Tick::Tick() {
}
Tick::Tick( const Tick & tick ) :
c( tick.c ) {
}
Tick::Tick( ClockT tick ) :
c( tick ) {
}
Tick::Tick( ctor ) {
}
void Tick::setNow() {
this -> c = clock();
}
Tick & Tick::operator-=( const Tick & tick ) {
this -> c -= tick.c;
return *this;
}
const ClockT & Tick::getValue() const {
return this -> c;
}
Tick & Tick::operator=( const Tick & tick ) {
this -> c = tick.c;
return *this;
}
bool Tick::operator==( const Tick & tick ) const {
return tick.c == this -> c;
}
bool Tick::operator<( const Tick & tick ) const {
return tick.c < this -> c;
}
bool Tick::operator>( const Tick & tick ) const {
return tick.c > this -> c;
}
bool Tick::operator<=( const Tick & tick ) const {
return tick.c <= this -> c;
}
bool Tick::operator>=( const Tick & tick ) const {
return tick.c >= this -> c;
}
Tick::~Tick() {
}
}
| 12.872093
| 59
| 0.550136
|
Oriode
|
114cb841c10c9ffaf18f367b830bc21586533714
| 6,147
|
cpp
|
C++
|
Incursion/Code/Game/Player.cpp
|
yixuan-wei/Incursion
|
fa76fd30d1867cd05ffbc165d3577bc45cfde7ba
|
[
"MIT"
] | null | null | null |
Incursion/Code/Game/Player.cpp
|
yixuan-wei/Incursion
|
fa76fd30d1867cd05ffbc165d3577bc45cfde7ba
|
[
"MIT"
] | null | null | null |
Incursion/Code/Game/Player.cpp
|
yixuan-wei/Incursion
|
fa76fd30d1867cd05ffbc165d3577bc45cfde7ba
|
[
"MIT"
] | null | null | null |
#include "Game/Player.hpp"
#include "Game/GameCommon.hpp"
#include "Game/Map.hpp"
#include "Engine/Input/InputSystem.hpp"
#include "Engine/Input/XboxController.hpp"
#include "Engine/Math/MathUtils.hpp"
#include "Engine/Math/AABB2.hpp"
#include "Engine/Core/Vertex_PCU.hpp"
#include "Engine/Renderer/RenderContext.hpp"
#include "Engine/Renderer/Texture.hpp"
#include "Engine/Audio/AudioSystem.hpp"
//////////////////////////////////////////////////////////////////////////
Player::Player( Map* map, const Vec2& startPos, EntityFaction faction, EntityType type )
:Entity(map, startPos,faction, type)
,m_controllerID(0)
{
m_speedLimit = PLAYER_SPEED;
m_physicsRadius = PLAYER_PHYSICS_RADIUS;
m_cosmeticRadius = PLAYER_COSMETIC_RADIUS;
m_pushesEntities = true;
m_isPushedByEntities = true;
m_isHitByBullets = true;
m_isPushedByWalls = true;
m_health = PLAYER_HEALTH;
m_healthLimit = m_health;
float halfBaseSize = m_cosmeticRadius;
AABB2 bounds( Vec2( -halfBaseSize, -halfBaseSize ), Vec2( halfBaseSize, halfBaseSize ) );
AppendVertsForAABB2D( m_verts, bounds );
}
//////////////////////////////////////////////////////////////////////////
void Player::Update( float deltaSeconds )
{
if( m_vibrationCounter > 0 )
{
m_vibrationCounter -= deltaSeconds;
}
else
{
g_theInput->SetVibrationValue( m_controllerID, 0, 0 );
}
if( !IsAlive() )
return;
m_thrustFraction = 0.f;
UpdateFromController(deltaSeconds);
m_velocity = Vec2( 0.f, 0.f );
if( m_thrustFraction > 0.f )
{
m_velocity = Vec2::MakeFromPolarDegrees( m_orientationDegrees, m_thrustFraction );
}
Entity::Update( deltaSeconds );
}
//////////////////////////////////////////////////////////////////////////
void Player::Render() const
{
//base
Texture* baseTank = g_theRenderer->CreateOrGetTextureFromFile( "Data/Images/PlayerTankBase.png" );
g_theRenderer->BindDiffuseTexture( baseTank );
Entity::Render();
//turret
Texture* turretTank = g_theRenderer->CreateOrGetTextureFromFile( "Data/Images/PlayerTankTop.png" );
g_theRenderer->BindDiffuseTexture( turretTank );
std::vector<Vertex_PCU> turretVerts = m_verts;
TransformVertexArray( (int)turretVerts.size(), &turretVerts[0], 1.f, m_orientationDegrees + m_gunRelativeOrientation, m_position );
g_theRenderer->DrawVertexArray( turretVerts );
//health bar
g_theRenderer->BindDiffuseTexture((Texture*)nullptr );
Vec2 healthBarLeft = m_position + Vec2( -HEALTH_BAR_LENGTH * .5f, m_cosmeticRadius );
float healthRate = (float)m_health / (float)PLAYER_HEALTH;
g_theRenderer->DrawLine2D( healthBarLeft, healthBarLeft + Vec2( HEALTH_BAR_LENGTH * healthRate, 0.f ), 5 * LINE_THICKNESS, Rgba8( 255, 0, 0 ) );
}
//////////////////////////////////////////////////////////////////////////
void Player::DebugRender() const
{
Entity::DebugRender();
Vec2 forward = Vec2::MakeFromPolarDegrees( m_orientationDegrees + m_gunRelativeOrientation );
RaycastResult result = m_theMap->Raycast( m_position, forward, 100.f );
g_theRenderer->DrawLine2D( m_position, result.m_impactPos, LINE_THICKNESS, Rgba8( 255, 0, 0 ) );
}
//////////////////////////////////////////////////////////////////////////
void Player::TakeDamage( int damage )
{
Entity::TakeDamage( damage );
SoundID hitSound = g_theAudio->CreateOrGetSound( "Data/Audio/PlayerHit.wav" );
g_theAudio->PlaySound( hitSound );
g_theInput->SetVibrationValue( m_controllerID, .3f, .3f );
m_vibrationCounter = PLAYER_HIT_VIBRATION_TIME;
}
//////////////////////////////////////////////////////////////////////////
void Player::Die()
{
Entity::Die();
m_theMap->SpawnExplosion( m_position, 2.f*m_cosmeticRadius, EXPLOSION_MAX_DURATION );
SoundID dieSound = g_theAudio->CreateOrGetSound( "Data/Audio/PlayerDied.wav" );
g_theAudio->PlaySound( dieSound );
}
//////////////////////////////////////////////////////////////////////////
void Player::UpdateFromController(float deltaSeconds)
{
if( m_controllerID < 0 )
return;
const XboxController controller = g_theInput->GetXboxController( m_controllerID );
if( !controller.IsConnected() )
return;
//movement
const AnalogJoystick leftJoystick = controller.GetLeftJoystick();
float leftMagnitude = leftJoystick.GetMagnitude();
if( leftMagnitude > 0.f )
{
m_thrustFraction = leftMagnitude;
m_orientationDegrees = GetTurnedToward( m_orientationDegrees, leftJoystick.GetAngleDegrees(), PLAYER_TURN_SPEED * deltaSeconds );
}
//gun movement
const AnalogJoystick rightJoystick = controller.GetRightJoystick();
float magnitude = rightJoystick.GetMagnitude();
if( magnitude > 0.f )
{
float turnedAbsolute = GetTurnedToward( m_orientationDegrees + m_gunRelativeOrientation,
rightJoystick.GetAngleDegrees(), PLAYER_GUN_TURN_SPEED * deltaSeconds );
m_gunRelativeOrientation = turnedAbsolute - m_orientationDegrees;
}
//shoot bullet
const KeyButtonState aButton = controller.GetButtonState( XBOX_BUTTON_ID_RSHOULDER );
if( aButton.WasJustPressed() )
{
ShootBullet();
}
//shoot bomb
const KeyButtonState bButton = controller.GetButtonState( XBOX_BUTTON_ID_LSHOULDER );
if( bButton.WasJustPressed() )
{
ShootBomb();
}
}
//////////////////////////////////////////////////////////////////////////
void Player::ShootBullet()
{
float absoluteBulletOrientation = m_orientationDegrees + m_gunRelativeOrientation;
m_theMap->SpawnBullet( ENTITY_TYPE_GOOD_BULLET, FACTION_GOOD,
m_position + Vec2::MakeFromPolarDegrees(absoluteBulletOrientation, m_cosmeticRadius ), absoluteBulletOrientation );
SoundID shootSound = g_theAudio->CreateOrGetSound( "Data/Audio/PlayerShootNormal.ogg" );
g_theAudio->PlaySound( shootSound );
}
//////////////////////////////////////////////////////////////////////////
void Player::ShootBomb()
{
if( m_factionBombNum <= 0 )
return;
float absoluteBulletOrientation = m_orientationDegrees + m_gunRelativeOrientation;
m_theMap->SpawnBomb( m_faction,
m_position + Vec2::MakeFromPolarDegrees( absoluteBulletOrientation, m_cosmeticRadius ), absoluteBulletOrientation );
SoundID shootSound = g_theAudio->CreateOrGetSound( "Data/Audio/PlayerShootNormal.ogg" );
g_theAudio->PlaySound( shootSound );
m_factionBombNum--;
}
| 32.52381
| 145
| 0.684724
|
yixuan-wei
|
114e0965901bdcc26728553f33709f1291dd3ed3
| 408
|
cpp
|
C++
|
Paddle.cpp
|
jaguile6/almost-pong
|
48dbd1049868bb46df37285a74da1eaaef6f8fd6
|
[
"MIT"
] | null | null | null |
Paddle.cpp
|
jaguile6/almost-pong
|
48dbd1049868bb46df37285a74da1eaaef6f8fd6
|
[
"MIT"
] | null | null | null |
Paddle.cpp
|
jaguile6/almost-pong
|
48dbd1049868bb46df37285a74da1eaaef6f8fd6
|
[
"MIT"
] | null | null | null |
#include "Paddle.h"
#include "Globals.h"
#include <Arduboy2.h>
void Paddle::updatePaddle(){
if(this->y < this->destination){
this->y += vy;
}
if(this->y > this->destination){
this->y -= vy;
}
}
void Paddle::drawPaddle(){
arduboy.drawRect(this->x,this->y, 2, 18, WHITE);
}
void Paddle::resetPaddle(){
this->y = random(3,45);
this->destination = random(3,45);
}
| 18.545455
| 51
| 0.580882
|
jaguile6
|
1152b9eba5d90524a7597fd5db7683bd1b859ca9
| 960
|
cpp
|
C++
|
Dynamic_Programming/minimizing_coins.cpp
|
DannyAntonelli/CSES-Problem-Set
|
599b5efb2d7efb9b7e1bfde3142702dc5d0c3988
|
[
"MIT"
] | null | null | null |
Dynamic_Programming/minimizing_coins.cpp
|
DannyAntonelli/CSES-Problem-Set
|
599b5efb2d7efb9b7e1bfde3142702dc5d0c3988
|
[
"MIT"
] | null | null | null |
Dynamic_Programming/minimizing_coins.cpp
|
DannyAntonelli/CSES-Problem-Set
|
599b5efb2d7efb9b7e1bfde3142702dc5d0c3988
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
#define FOR(i, a, b) for (int i = (a); i < (b); ++i)
#define RFOR(i, a, b) for (int i = (a); i > (b); --i)
#define ALL(x) x.begin(), x.end()
#define F first
#define S second
#define PB push_back
#define MP make_pair
using namespace std;
using ll = long long;
using ld = long double;
typedef vector<int> vi;
typedef pair<int, int> pi;
void fast_io() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
}
int main() {
fast_io();
int n, x;
cin >> n >> x;
int nums[n];
FOR (i, 0, n) cin >> nums[i];
const int INF = 1000001;
int dp[x+1];
FOR (i, 0, x+1) dp[i] = INF;
dp[0] = 0;
int curr = INF, k;
FOR (i, 1, x+1) {
curr = INF;
FOR (j, 0, n) {
k = i - nums[j];
if (k >= 0) {
curr = min(curr, dp[k]);
}
}
dp[i] = 1 + curr;
}
cout << (dp[x] >= INF ? -1 : dp[x]);
return 0;
}
| 18.823529
| 53
| 0.464583
|
DannyAntonelli
|
11545f6273e19ab895feeb080af8ab8445dbf737
| 18,371
|
cpp
|
C++
|
XControl/src/xcOleControlContain.cpp
|
qianxj/XExplorer
|
00e326da03ffcaa21115a2345275452607c6bab5
|
[
"MIT"
] | null | null | null |
XControl/src/xcOleControlContain.cpp
|
qianxj/XExplorer
|
00e326da03ffcaa21115a2345275452607c6bab5
|
[
"MIT"
] | null | null | null |
XControl/src/xcOleControlContain.cpp
|
qianxj/XExplorer
|
00e326da03ffcaa21115a2345275452607c6bab5
|
[
"MIT"
] | null | null | null |
#include "StdAfx.h"
#include "..\include\xcOleControlContain.hpp"
namespace Hxsoft{ namespace XFrame
{
xcOleControlContain::xcOleControlContain(void): m_pOleControl(NULL)
{
m_pClientSite = new CComObject<COleClientSite>();
m_pInPlaceSite = new CComObject<COleInPlaceSite>();
m_pInPlaceFrame = new CComObject<COleInPlaceFrame>();
m_pDocHostUIHandler = new CComObject<CDocHostUIHandler>();
m_pServiceProvider = new CComObject<CServiceProvider>();
m_pInternetSecurityManager = new CComObject<CInternetSecurityManager>();
m_pClientSite->m_pT = this;
m_pInPlaceSite->m_pT = this;
m_pInPlaceFrame->m_pT = this;
m_pDocHostUIHandler->m_pT = this;
m_pServiceProvider->m_pT = this;
m_pInternetSecurityManager->m_pT = this;
}
xcOleControlContain::~xcOleControlContain(void)
{
/*
if(m_pClientSite) delete m_pClientSite;
if(m_pInPlaceSite) delete m_pInPlaceSite;
if(m_pInPlaceFrame) delete m_pInPlaceFrame;
if(m_pDocHostUIHandler) delete m_pDocHostUIHandler;
if(m_pServiceProvider) delete m_pServiceProvider;
if(m_pInternetSecurityManager) delete m_pInternetSecurityManager;
*/
//if(m_pClientSite) delete m_pClientSite;
//if(m_pInPlaceSite) delete m_pInPlaceSite;
//if(m_pInPlaceFrame) delete m_pInPlaceFrame;
//if(m_pDocHostUIHandler) delete m_pDocHostUIHandler;
//if(m_pServiceProvider) delete m_pServiceProvider;
//if(m_pInternetSecurityManager) delete m_pInternetSecurityManager;
}
int xcOleControlContain::OnClose()
{
if(m_pOleControl)
{
m_pOleControl->SetClientSite(NULL);
m_pOleControl->Close(OLECLOSE_NOSAVE);
m_pOleControl->Release();
m_pOleControl = NULL;
}
return 1;
}
int xcOleControlContain::AdjustControlRect(RECT rect,bool redraw)
{
xfControl::AdjustControlRect(rect,redraw);
RECT rc={0,0,0,0};
rc.right = rect.right - rect.left ;
rc.bottom = rect.bottom - rect.top;
IOleInPlaceObject *inplace;
if(m_pOleControl)
{
if (!m_pOleControl->QueryInterface(IID_IOleInPlaceObject, (void**)&inplace))
{
inplace->SetObjectRects( &rc, &rc);
inplace->Release();
}
}
return 1;
}
HWND xcOleControlContain::CreateControl(LPTSTR pszWndTitle, RECT & rtPos, HWND hWndParent, UINT uID,HINSTANCE hInstance,HMENU hMenu,LPVOID lpParam )
{
HWND m_hWnd = xfControl::CreateControl(pszWndTitle, rtPos, hWndParent,uID,hInstance,hMenu,lpParam);
if(!m_hWnd) return NULL;
_variant_t var;
m_pxfNode->m_pElement->getAttribute(L"clsid",&var);
if(var.bstrVal)
{
CLSID clsid;
HRESULT hr;
if(var.bstrVal[0]=='{')
hr = CLSIDFromString(var.bstrVal,&clsid);
else
hr = CLSIDFromProgIDEx(var.bstrVal,&clsid);
if(hr ==S_OK)
{
LPCLASSFACTORY pClassFactory;
IWebBrowser2 *webBrowser2;
RECT rect;
pClassFactory = 0;
if (!CoGetClassObject(clsid/*CLSID_WebBrowser*/, CLSCTX_INPROC_SERVER | CLSCTX_INPROC_HANDLER, NULL, IID_IClassFactory, (void **)&pClassFactory) && pClassFactory)
{
if (!pClassFactory->CreateInstance(0, IID_IOleObject, (void **)&m_pOleControl))
{
pClassFactory->Release();
if (!m_pOleControl->SetClientSite(m_pClientSite))
{
m_pOleControl->SetHostNames(L"XExplorer", 0);
::GetClientRect(m_hWnd, &rect);
if (!OleSetContainedObject((struct IUnknown *)m_pOleControl, TRUE) &&
!m_pOleControl->DoVerb(OLEIVERB_SHOW, NULL, m_pClientSite, -1, m_hWnd, &rect) &&
!m_pOleControl->QueryInterface(IID_IWebBrowser2, (void**)&webBrowser2))
{
webBrowser2->put_Left(0);
webBrowser2->put_Top(0);
webBrowser2->put_Width(rect.right);
webBrowser2->put_Height(rect.bottom);
VARIANT myURL;
VariantInit(&myURL);
myURL.vt = VT_BSTR;
this->m_pxfNode->m_pElement->getAttribute(L"url",&myURL);
if(!myURL.bstrVal)
{
myURL.vt = VT_BSTR;
myURL.bstrVal = SysAllocString(L"about:blank");
}
webBrowser2->Navigate2( &myURL, 0, 0, 0, 0);
VariantClear(&myURL);
webBrowser2->Release();
// Success
return m_hWnd;
}
}
}
}
}
}
return m_hWnd;
}
int xcOleControlContain::DoDraw(HDC hPaintDC,RECT * pDrawRect)
{
return 1;
}
template<class T>
HRESULT STDMETHODCALLTYPE xcOleControlContain::CComObject<T>::QueryInterface(REFIID riid, LPVOID FAR* ppvObj)
{
if (InlineIsEqualGUID(riid, IID_IUnknown)||InlineIsEqualGUID(riid,IID_IOleClientSite))
*ppvObj = m_pT->m_pClientSite;
else if (InlineIsEqualGUID(riid, IID_IOleInPlaceSite))
*ppvObj = m_pT->m_pInPlaceSite;
else if (InlineIsEqualGUID(riid, IID_IDocHostUIHandler))
*ppvObj = m_pT->m_pDocHostUIHandler;
else if (InlineIsEqualGUID(riid, IID_IInternetSecurityManager))
*ppvObj = m_pT->m_pInternetSecurityManager;
else if (InlineIsEqualGUID(riid, IID_IServiceProvider))
*ppvObj = m_pT->m_pServiceProvider;
else
{
*ppvObj = 0;
return(E_NOINTERFACE);
}
return(S_OK);
}
template<class T>
ULONG STDMETHODCALLTYPE xcOleControlContain::CComObject<T>::AddRef( )
{
return 1;
}
template<class T>
ULONG STDMETHODCALLTYPE xcOleControlContain::CComObject<T>::Release( )
{
return 1;
}
HRESULT STDMETHODCALLTYPE xcOleControlContain::CDocHostUIHandler::ShowContextMenu( DWORD dwID, POINT __RPC_FAR *ppt, IUnknown __RPC_FAR *pcmdtReserved, IDispatch __RPC_FAR *pdispReserved)
{
return(S_OK);
}
HRESULT STDMETHODCALLTYPE xcOleControlContain::CDocHostUIHandler::GetHostInfo( DOCHOSTUIINFO __RPC_FAR *pInfo)
{
pInfo->cbSize = sizeof(DOCHOSTUIINFO);
pInfo->dwFlags = DOCHOSTUIFLAG_NO3DBORDER|DOCHOSTUIFLAG_DISABLE_SCRIPT_INACTIVE|DOCHOSTUIFLAG_LOCAL_MACHINE_ACCESS_CHECK|DOCHOSTUIFLAG_DISABLE_UNTRUSTEDPROTOCOL;
pInfo->dwDoubleClick = DOCHOSTUIDBLCLK_DEFAULT;
return(S_OK);
}
HRESULT STDMETHODCALLTYPE xcOleControlContain::CDocHostUIHandler::ShowUI( DWORD dwID, IOleInPlaceActiveObject __RPC_FAR *pActiveObject, IOleCommandTarget __RPC_FAR *pCommandTarget, IOleInPlaceFrame __RPC_FAR *pFrame, IOleInPlaceUIWindow __RPC_FAR *pDoc)
{
return(S_OK);
}
HRESULT STDMETHODCALLTYPE xcOleControlContain::CDocHostUIHandler::HideUI()
{
return(S_OK);
}
HRESULT STDMETHODCALLTYPE xcOleControlContain::CDocHostUIHandler::UpdateUI()
{
return(S_OK);
}
HRESULT STDMETHODCALLTYPE xcOleControlContain::CDocHostUIHandler::EnableModeless( BOOL fEnable)
{
return(S_OK);
}
HRESULT STDMETHODCALLTYPE xcOleControlContain::CDocHostUIHandler::OnDocWindowActivate( BOOL fActivate)
{
return(S_OK);
}
HRESULT STDMETHODCALLTYPE xcOleControlContain::CDocHostUIHandler::OnFrameWindowActivate( BOOL fActivate)
{
return(S_OK);
}
HRESULT STDMETHODCALLTYPE xcOleControlContain::CDocHostUIHandler::ResizeBorder( LPCRECT prcBorder, IOleInPlaceUIWindow __RPC_FAR *pUIWindow, BOOL fRameWindow)
{
return(S_OK);
}
// Called from the browser object's TranslateAccelerator routines to translate key strokes to commands.
HRESULT STDMETHODCALLTYPE xcOleControlContain::CDocHostUIHandler::TranslateAccelerator( LPMSG lpMsg, const GUID __RPC_FAR *pguidCmdGroup, DWORD nCmdID)
{
return(S_FALSE);
}
HRESULT STDMETHODCALLTYPE xcOleControlContain::CDocHostUIHandler::GetOptionKeyPath( LPOLESTR __RPC_FAR *pchKey, DWORD dw)
{
return(S_FALSE);
}
HRESULT STDMETHODCALLTYPE xcOleControlContain::CDocHostUIHandler::GetDropTarget( IDropTarget __RPC_FAR *pDropTarget, IDropTarget __RPC_FAR *__RPC_FAR *ppDropTarget)
{
return(S_FALSE);
}
HRESULT STDMETHODCALLTYPE xcOleControlContain::CDocHostUIHandler::GetExternal( IDispatch __RPC_FAR *__RPC_FAR *ppDispatch)
{
*ppDispatch = 0;
return(S_FALSE);
}
HRESULT STDMETHODCALLTYPE xcOleControlContain::CDocHostUIHandler::TranslateUrl( DWORD dwTranslate, OLECHAR __RPC_FAR *pchURLIn, OLECHAR __RPC_FAR *__RPC_FAR *ppchURLOut)
{
*ppchURLOut = 0;
return(S_FALSE);
}
HRESULT STDMETHODCALLTYPE xcOleControlContain::CDocHostUIHandler::FilterDataObject( IDataObject __RPC_FAR *pDO, IDataObject __RPC_FAR *__RPC_FAR *ppDORet)
{
*ppDORet = 0;
return(S_FALSE);
}
HRESULT STDMETHODCALLTYPE xcOleControlContain::COleClientSite::SaveObject()
{
return(E_NOINTERFACE);
//NOTIMPLEMENTED;
}
HRESULT STDMETHODCALLTYPE xcOleControlContain::COleClientSite::GetMoniker( DWORD dwAssign, DWORD dwWhichMoniker, IMoniker ** ppmk)
{
return(E_NOINTERFACE);
//NOTIMPLEMENTED;
}
HRESULT STDMETHODCALLTYPE xcOleControlContain::COleClientSite::GetContainer( LPOLECONTAINER FAR* ppContainer)
{
*ppContainer = 0;
return(E_NOINTERFACE);
}
HRESULT STDMETHODCALLTYPE xcOleControlContain::COleClientSite::ShowObject()
{
return(NOERROR);
}
HRESULT STDMETHODCALLTYPE xcOleControlContain::COleClientSite::OnShowWindow( BOOL fShow)
{
return(E_NOINTERFACE);
//NOTIMPLEMENTED;
}
HRESULT STDMETHODCALLTYPE xcOleControlContain::COleClientSite::RequestNewObjectLayout()
{
return(E_NOINTERFACE);
//NOTIMPLEMENTED;
}
HRESULT STDMETHODCALLTYPE xcOleControlContain::COleInPlaceSite::GetWindow( HWND FAR* lphwnd)
{
*lphwnd = m_pT->m_hWnd;
return(S_OK);
}
HRESULT STDMETHODCALLTYPE xcOleControlContain::COleInPlaceSite::ContextSensitiveHelp( BOOL fEnterMode)
{
return(E_NOINTERFACE);
//NOTIMPLEMENTED;
}
HRESULT STDMETHODCALLTYPE xcOleControlContain::COleInPlaceSite::CanInPlaceActivate()
{
return(S_OK);
}
HRESULT STDMETHODCALLTYPE xcOleControlContain::COleInPlaceSite::OnInPlaceActivate()
{
return(S_OK);
}
HRESULT STDMETHODCALLTYPE xcOleControlContain::COleInPlaceSite::OnUIActivate()
{
return(S_OK);
}
HRESULT STDMETHODCALLTYPE xcOleControlContain::COleInPlaceSite::GetWindowContext( LPOLEINPLACEFRAME FAR* lplpFrame, LPOLEINPLACEUIWINDOW FAR* lplpDoc, LPRECT lprcPosRect, LPRECT lprcClipRect, LPOLEINPLACEFRAMEINFO lpFrameInfo)
{
*lplpFrame = m_pT->m_pInPlaceFrame;
*lplpDoc = 0;
if(lpFrameInfo)
{
lpFrameInfo->fMDIApp = FALSE;
lpFrameInfo->hwndFrame = m_pT->GetWin()->m_hWnd;;
lpFrameInfo->haccel = 0;
lpFrameInfo->cAccelEntries = 0;
}
//GetClientRect(lpFrameInfo->hwndFrame, lprcPosRect);
//GetClientRect(lpFrameInfo->hwndFrame, lprcClipRect);
return(S_OK);
}
HRESULT STDMETHODCALLTYPE xcOleControlContain::COleInPlaceSite::Scroll( SIZE scrollExtent)
{
NOTIMPLEMENTED;
}
HRESULT STDMETHODCALLTYPE xcOleControlContain::COleInPlaceSite::OnUIDeactivate( BOOL fUndoable)
{
return(S_OK);
}
HRESULT STDMETHODCALLTYPE xcOleControlContain::COleInPlaceSite::OnInPlaceDeactivate()
{
return(S_OK);
}
HRESULT STDMETHODCALLTYPE xcOleControlContain::COleInPlaceSite::DiscardUndoState()
{
return(E_NOINTERFACE);
//NOTIMPLEMENTED;
}
HRESULT STDMETHODCALLTYPE xcOleControlContain::COleInPlaceSite::DeactivateAndUndo()
{
return(E_NOINTERFACE);
//NOTIMPLEMENTED;
}
HRESULT STDMETHODCALLTYPE xcOleControlContain::COleInPlaceSite::OnPosRectChange( LPCRECT lprcPosRect)
{
IOleInPlaceObject *inplace;
if(m_pT->m_pOleControl)
{
if (!m_pT->m_pOleControl->QueryInterface(IID_IOleInPlaceObject, (void**)&inplace))
{
inplace->SetObjectRects( lprcPosRect, lprcPosRect);
inplace->Release();
}
}
return(S_OK);
}
HRESULT STDMETHODCALLTYPE xcOleControlContain::COleInPlaceFrame::GetWindow( HWND FAR* lphwnd)
{
*lphwnd = m_pT->GetWin()->m_hWnd;
return(S_OK);
}
HRESULT STDMETHODCALLTYPE xcOleControlContain::COleInPlaceFrame::ContextSensitiveHelp( BOOL fEnterMode)
{
NOTIMPLEMENTED;
}
HRESULT STDMETHODCALLTYPE xcOleControlContain::COleInPlaceFrame::GetBorder( LPRECT lprectBorder)
{
NOTIMPLEMENTED;
}
HRESULT STDMETHODCALLTYPE xcOleControlContain::COleInPlaceFrame::RequestBorderSpace( LPCBORDERWIDTHS pborderwidths)
{
return(E_NOTIMPL);
//NOTIMPLEMENTED;
}
HRESULT STDMETHODCALLTYPE xcOleControlContain::COleInPlaceFrame::SetBorderSpace( LPCBORDERWIDTHS pborderwidths)
{
return(E_NOTIMPL);
//NOTIMPLEMENTED;
}
HRESULT STDMETHODCALLTYPE xcOleControlContain::COleInPlaceFrame::SetActiveObject( IOleInPlaceActiveObject *pActiveObject, LPCOLESTR pszObjName)
{
return(S_OK);
}
HRESULT STDMETHODCALLTYPE xcOleControlContain::COleInPlaceFrame::InsertMenus( HMENU hmenuShared, LPOLEMENUGROUPWIDTHS lpMenuWidths)
{
return(E_NOTIMPL);
//NOTIMPLEMENTED;
}
HRESULT STDMETHODCALLTYPE xcOleControlContain::COleInPlaceFrame::SetMenu( HMENU hmenuShared, HOLEMENU holemenu, HWND hwndActiveObject)
{
return(S_OK);
}
HRESULT STDMETHODCALLTYPE xcOleControlContain::COleInPlaceFrame::RemoveMenus( HMENU hmenuShared)
{
NOTIMPLEMENTED;
}
HRESULT STDMETHODCALLTYPE xcOleControlContain::COleInPlaceFrame::SetStatusText( LPCOLESTR pszStatusText)
{
return(S_OK);
}
HRESULT STDMETHODCALLTYPE xcOleControlContain::COleInPlaceFrame::EnableModeless( BOOL fEnable)
{
return(S_OK);
}
HRESULT STDMETHODCALLTYPE xcOleControlContain::COleInPlaceFrame::TranslateAccelerator( LPMSG lpmsg, WORD wID)
{
NOTIMPLEMENTED;
}
HRESULT xcOleControlContain::CInternetSecurityManager::SetSecuritySite (IInternetSecurityMgrSite *pSite)
{
return INET_E_DEFAULT_ACTION;
}
HRESULT xcOleControlContain::CInternetSecurityManager::GetSecuritySite(IInternetSecurityMgrSite **ppSite)
{
return INET_E_DEFAULT_ACTION;
}
HRESULT xcOleControlContain::CInternetSecurityManager::MapUrlToZone(LPCWSTR pwszUrl,DWORD *pdwZone,DWORD dwFlags)
{
return INET_E_DEFAULT_ACTION;
}
HRESULT xcOleControlContain::CInternetSecurityManager::GetSecurityId(LPCWSTR pwszUrl,
BYTE *pbSecurityId,
DWORD *pcbSecurityId,
DWORD dwReserved)
{
return INET_E_DEFAULT_ACTION;
}
STDMETHODIMP xcOleControlContain::CInternetSecurityManager
::ProcessUrlAction( /* [in] */ LPCWSTR pwszUrl,
/* [in] */ DWORD dwAction,
/* [size_is][out] */ BYTE __RPC_FAR *pPolicy,
/* [in] */ DWORD cbPolicy,
/* [in] */ BYTE __RPC_FAR *pContext,
/* [in] */ DWORD cbContext,
/* [in] */ DWORD dwFlags,
/* [in] */ DWORD dwReserved)
{
DWORD dwPolicy=URLPOLICY_ALLOW;
if (dwAction <= URLACTION_ACTIVEX_MAX && dwAction >= URLACTION_ACTIVEX_MIN)
dwPolicy = false ? URLPOLICY_DISALLOW : URLPOLICY_ALLOW;
else if ((dwAction <= URLACTION_JAVA_MAX && dwAction >= URLACTION_JAVA_MIN) ||
URLACTION_HTML_JAVA_RUN == dwAction)
if (true)
dwPolicy = URLPOLICY_JAVA_PROHIBIT;
else
return INET_E_DEFAULT_ACTION;
else if (dwAction <= URLACTION_SCRIPT_MAX && dwAction >= URLACTION_SCRIPT_MIN)
dwPolicy = false ? URLPOLICY_DISALLOW : URLPOLICY_ALLOW;
else if (URLACTION_CROSS_DOMAIN_DATA == dwAction)
dwPolicy = false ? URLPOLICY_ALLOW : URLPOLICY_DISALLOW;
else
return INET_E_DEFAULT_ACTION;
if ( cbPolicy >= sizeof (DWORD))
{
*(DWORD*) pPolicy = dwPolicy;
return S_OK;
}
else
{
return S_FALSE;
}
}
HRESULT xcOleControlContain::CInternetSecurityManager
::QueryCustomPolicy(LPCWSTR pwszUrl,
REFGUID guidKey,
BYTE **ppPolicy,
DWORD *pcbPolicy,
BYTE *pContext,
DWORD cbContext,
DWORD dwReserved)
{
return INET_E_DEFAULT_ACTION;
}
HRESULT xcOleControlContain::CInternetSecurityManager
::SetZoneMapping(DWORD dwZone,
LPCWSTR lpszPattern,
DWORD dwFlags)
{
return INET_E_DEFAULT_ACTION;
}
HRESULT xcOleControlContain::CInternetSecurityManager
::GetZoneMappings(DWORD dwZone,
IEnumString **ppenumString,
DWORD dwFlags)
{
return INET_E_DEFAULT_ACTION;
}
/////////////////////////////////////////////////////////////
STDMETHODIMP xcOleControlContain::CServiceProvider
::QueryService(REFGUID guidService,
REFIID riid,
void** ppvObject)
{
if (guidService == SID_SInternetSecurityManager &&
riid == IID_IInternetSecurityManager)
{
HRESULT hr = QueryInterface(riid, ppvObject);
return hr;
}
else
{
*ppvObject = NULL;
}
return E_NOINTERFACE;
}
int xcOleControlContain::ExecWB(int cmdID, int cmdexecopt)
{
IWebBrowser2 *webBrowser2;
xcOleControlContain* pControl = this;
if(!pControl->m_pOleControl->QueryInterface(IID_IWebBrowser2, (void**)&webBrowser2))
{
webBrowser2->ExecWB((OLECMDID)cmdID, (OLECMDEXECOPT)cmdexecopt, NULL, NULL);
}
return 1;
}
int xcOleControlContain::LoadHtml(LPTSTR pStrHtml)
{
IWebBrowser2 *webBrowser2;
LPDISPATCH lpDispatch;
IHTMLDocument2 *htmlDoc2;
SAFEARRAY *sfArray;
VARIANT *pVar;
BSTR bstr = NULL;
SAFEARRAYBOUND ArrayBound = {1, 0};
xcOleControlContain* pControl = this;
if(!pControl->m_pOleControl->QueryInterface(IID_IWebBrowser2, (void**)&webBrowser2))
{
if (!webBrowser2->get_Document(&lpDispatch))
{
if (!lpDispatch->QueryInterface(IID_IHTMLDocument2, (void**)&htmlDoc2))
{
//htmlDoc2->put_designMode(L"on");
if ((sfArray = SafeArrayCreate(VT_VARIANT, 1, (SAFEARRAYBOUND *)&ArrayBound)))
{
if (!SafeArrayAccessData(sfArray, (void**)&pVar))
{
pVar->vt = VT_BSTR;
bstr = SysAllocString(pStrHtml);
if ((pVar->bstrVal = bstr))
{
htmlDoc2->write(sfArray);
htmlDoc2->close();
}
}
SafeArrayDestroy(sfArray);
}
IHTMLElement *pElement;
htmlDoc2->get_body(&pElement);
if(pElement)
{
BSTR str;
pElement->get_innerText(&str);
int i=1;
pElement->Release();
}
htmlDoc2->Release();
}
lpDispatch->Release();
}
}
return 1;
}
int xcOleControlContain::LoadText(LPTSTR pStrText)
{
IWebBrowser2 *webBrowser2;
LPDISPATCH lpDispatch;
IHTMLDocument2 *htmlDoc2;
xcOleControlContain* pControl = this;
if(!pControl->m_pOleControl->QueryInterface(IID_IWebBrowser2, (void**)&webBrowser2))
{
if (!webBrowser2->get_Document(&lpDispatch))
{
if (!lpDispatch->QueryInterface(IID_IHTMLDocument2, (void**)&htmlDoc2))
{
IHTMLElement *pElement;
htmlDoc2->get_body(&pElement);
if(pElement)
{
pElement->put_innerText(pStrText);
pElement->Release();
}
}
}
}
return 1;
}
IHTMLDocument2 * xcOleControlContain::GetHtmlDocument()
{
IWebBrowser2 *webBrowser2;
LPDISPATCH lpDispatch;
IHTMLDocument2 *htmlDoc2;
xcOleControlContain* pControl = this;
if(!pControl->m_pOleControl->QueryInterface(IID_IWebBrowser2, (void**)&webBrowser2))
{
if (!webBrowser2->get_Document(&lpDispatch))
{
if (!lpDispatch->QueryInterface(IID_IHTMLDocument2, (void**)&htmlDoc2))
{
return htmlDoc2;
}
lpDispatch->Release();
}
webBrowser2->Release();
}
return NULL;
}
}}
| 26.858187
| 254
| 0.735888
|
qianxj
|
1156994f878b98e57ba26c0906acd95023bb49a4
| 15,293
|
cpp
|
C++
|
src/metadata/domain.cpp
|
blumf/flamerobin
|
3b442c6786d916383f885d81f0303171fd8ce7c2
|
[
"MIT"
] | 2
|
2019-05-29T08:32:18.000Z
|
2021-02-17T08:19:00.000Z
|
src/metadata/domain.cpp
|
blumf/flamerobin
|
3b442c6786d916383f885d81f0303171fd8ce7c2
|
[
"MIT"
] | null | null | null |
src/metadata/domain.cpp
|
blumf/flamerobin
|
3b442c6786d916383f885d81f0303171fd8ce7c2
|
[
"MIT"
] | 1
|
2020-06-15T06:49:18.000Z
|
2020-06-15T06:49:18.000Z
|
/*
Copyright (c) 2004-2016 The FlameRobin Development Team
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.
*/
// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"
// for all others, include the necessary headers (this file is usually all you
// need because it includes almost all "standard" wxWindows headers
#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif
#include "core/FRError.h"
#include "core/ProgressIndicator.h"
#include "core/StringUtils.h"
#include "engine/MetadataLoader.h"
#include "frutils.h"
#include "metadata/database.h"
#include "metadata/domain.h"
#include "metadata/MetadataItemVisitor.h"
#include "sql/SqlTokenizer.h"
/*static*/
std::string Domain::getLoadStatement(bool list)
{
std::string stmt("select "
" f.rdb$field_name," // 1
" f.rdb$field_type," // 2
" f.rdb$field_sub_type," // 3
" f.rdb$field_length," // 4
" f.rdb$field_precision," // 5
" f.rdb$field_scale," // 6
" c.rdb$character_set_name," // 7
" f.rdb$character_length," // 8
" f.rdb$null_flag," // 9
" f.rdb$default_source," // 10
" l.rdb$collation_name," // 11
" f.rdb$validation_source," // 12
" f.rdb$computed_blr," // 13
" c.rdb$bytes_per_character" // 14
" from rdb$fields f"
" left outer join rdb$character_sets c"
" on c.rdb$character_set_id = f.rdb$character_set_id"
" left outer join rdb$collations l"
" on l.rdb$collation_id = f.rdb$collation_id"
" and l.rdb$character_set_id = f.rdb$character_set_id"
" left outer join rdb$types t on f.rdb$field_type=t.rdb$type"
" where t.rdb$field_name='RDB$FIELD_TYPE' and f.rdb$field_name ");
if (list) {
stmt += "not starting with 'RDB$' ";
//if (db->getInfo().getODSVersionIsHigherOrEqualTo(12, 0)) //If Firebird 3 ODS, remove SEC$DOMAINs, this is a static method, so I wont be able to get ODS
stmt += "and f.RDB$SYSTEM_FLAG=0 ";//Need to test on Firebird 1
stmt += "order by 1";
}
else
stmt += "= ?";
return stmt;
}
Domain::Domain(DatabasePtr database, const wxString& name)
: MetadataItem((hasSystemPrefix(name) ? ntSysDomain : ntDomain),
database.get(), name)
{
}
void Domain::loadProperties()
{
setPropertiesLoaded(false);
DatabasePtr db = getDatabase();
MetadataLoader* loader = db->getMetadataLoader();
MetadataLoaderTransaction tr(loader);
wxMBConv* converter = db->getCharsetConverter();
IBPP::Statement& st1 = loader->getStatement(getLoadStatement(false));
st1->Set(1, wx2std(getName_(), converter));
st1->Execute();
if (!st1->Fetch())
throw FRError(_("Domain not found: ") + getName_());
loadProperties(st1, converter);
}
/*static*/
wxString Domain::trimDefaultValue(const wxString& value)
{
// Some users reported two spaces before DEFAULT word in source
// Also, equals sign is also allowed in newer FB versions
// Trim(false) is trim-left
wxString defValue(value);
defValue.Trim(false);
if (defValue.Upper().StartsWith("DEFAULT"))
defValue.Remove(0, 7);
else if (defValue.StartsWith("="))
defValue.Remove(0, 1);
defValue.Trim(false);
return defValue;
}
void Domain::loadProperties(IBPP::Statement& statement, wxMBConv* converter)
{
setPropertiesLoaded(false);
statement->Get(2, &datatypeM);
if (statement->IsNull(3))
subtypeM = 0;
else
statement->Get(3, &subtypeM);
// determine the (var)char field length
// - system tables use field_len and char_len is null
// - computed columns have field_len/bytes_per_char, char_len is 0
// - view columns have field_len/bytes_per_char, char_len is null
// - regular table columns and SP params have field_len/bytes_per_char
// they also have proper char_len, but we don't use it now
statement->Get(4, &lengthM);
int bpc = 0; // bytes per char
if (!statement->IsNull(14))
statement->Get(14, &bpc);
if (bpc && (!statement->IsNull(8) || !statement->IsNull(13)))
lengthM /= bpc;
if (statement->IsNull(5))
precisionM = 0;
else
statement->Get(5, &precisionM);
if (statement->IsNull(6))
scaleM = 0;
else
statement->Get(6, &scaleM);
if (statement->IsNull(7))
charsetM = "";
else
{
std::string s;
statement->Get(7, s);
charsetM = std2wxIdentifier(s, converter);
}
bool notNull = false;
if (!statement->IsNull(9))
{
statement->Get(9, notNull);
}
nullableM = !notNull;
hasDefaultM = !statement->IsNull(10);
if (hasDefaultM)
{
readBlob(statement, 10, defaultM, converter);
defaultM = trimDefaultValue(defaultM);
}
else
defaultM = wxEmptyString;
if (statement->IsNull(11))
collationM = wxEmptyString;
else
{
std::string s;
statement->Get(11, s);
collationM = std2wxIdentifier(s, converter);
}
readBlob(statement, 12, checkM, converter);
setPropertiesLoaded(true);
}
bool Domain::isString()
{
ensurePropertiesLoaded();
return (datatypeM == 14 || datatypeM == 10 || datatypeM == 37);
}
bool Domain::isSystem() const
{
wxString prefix(getName_().substr(0, 4));
if (prefix == "MON$" || prefix == "SEC$" || prefix == "RDB$")
return true;
if (prefix != "RDB$")
return false;
long l;
return getName_().Mid(4).ToLong(&l); // numeric = system
}
//! returns column's datatype as human readable wxString.
wxString Domain::getDatatypeAsString()
{
ensurePropertiesLoaded();
return dataTypeToString(datatypeM, scaleM, precisionM, subtypeM, lengthM);
}
/* static*/
wxString Domain::dataTypeToString(short datatype, short scale, short precision,
short subtype, short length)
{
wxString retval;
// special case (mess that some tools (ex. IBExpert) make by only
// setting scale and not changing type)
if (datatype == 27 && scale < 0)
{
retval = SqlTokenizer::getKeyword(kwNUMERIC);
retval << "(15," << -scale << ")";
return retval;
}
// INTEGER(prec=0), DECIMAL(sub_type=2), NUMERIC(sub_t=1), BIGINT(sub_t=0)
if (datatype == 7 || datatype == 8 || datatype == 16)
{
if (scale == 0)
{
if (datatype == 7)
return SqlTokenizer::getKeyword(kwSMALLINT);
if (datatype == 8)
return SqlTokenizer::getKeyword(kwINTEGER);
}
if (scale == 0 && subtype == 0)
return SqlTokenizer::getKeyword(kwBIGINT);
retval = SqlTokenizer::getKeyword(
(subtype == 2) ? kwDECIMAL : kwNUMERIC);
retval << "(";
if (precision <= 0 || precision > 18)
retval << 18;
else
retval << precision;
retval << "," << -scale << ")";
return retval;
}
switch (datatype)
{
case 10:
return SqlTokenizer::getKeyword(kwFLOAT);
case 27:
return SqlTokenizer::getKeyword(kwDOUBLE) + " "
+ SqlTokenizer::getKeyword(kwPRECISION);
case 12:
return SqlTokenizer::getKeyword(kwDATE);
case 13:
return SqlTokenizer::getKeyword(kwTIME);
case 35:
return SqlTokenizer::getKeyword(kwTIMESTAMP);
// add subtype for blob
case 261:
retval = SqlTokenizer::getKeyword(kwBLOB) + " "
+ SqlTokenizer::getKeyword(kwSUB_TYPE) + " ";
retval << subtype;
return retval;
case 23: // Firebird v3
return SqlTokenizer::getKeyword(kwBOOLEAN);
// add length for char, varchar and cstring
case 14:
retval = SqlTokenizer::getKeyword(kwCHAR);
break;
case 37:
retval = SqlTokenizer::getKeyword(kwVARCHAR);
break;
case 40:
retval = SqlTokenizer::getKeyword(kwCSTRING);
break;
}
retval << "(" << length << ")";
return retval;
}
wxString Domain::getCollation()
{
ensurePropertiesLoaded();
return collationM;
}
wxString Domain::getCheckConstraint()
{
ensurePropertiesLoaded();
return checkM;
}
bool Domain::getDefault(wxString& value)
{
ensurePropertiesLoaded();
if (hasDefaultM)
{
value = defaultM;
return true;
}
value = wxEmptyString;
return false;
}
bool Domain::isNullable()
{
ensurePropertiesLoaded();
return nullableM;
}
void Domain::getDatatypeParts(wxString& type, wxString& size, wxString& scale)
{
size = scale = wxEmptyString;
wxString datatype = getDatatypeAsString();
wxString::size_type p1 = datatype.find("(");
if (p1 != wxString::npos)
{
type = datatype.substr(0, p1);
wxString::size_type p2 = datatype.find(",");
if (p2 == wxString::npos)
p2 = datatype.find(")");
else
{
wxString::size_type p3 = datatype.find(")");
scale = datatype.substr(p2 + 1, p3 - p2 - 1);
}
size = datatype.substr(p1 + 1, p2 - p1 - 1);
}
else
{
type = datatype;
// HACK ALERT: some better fix needed, but we don't want the subtype
if (datatypeM == 261)
type = SqlTokenizer::getKeyword(kwBLOB);
}
}
wxString Domain::getCharset()
{
ensurePropertiesLoaded();
return charsetM;
}
wxString Domain::getAlterSqlTemplate() const
{
return "ALTER DOMAIN " + getQuotedName() + "\n"
" SET DEFAULT { literal | NULL | USER }\n"
" | DROP DEFAULT\n"
" | ADD [CONSTRAINT] CHECK (condition)\n"
" | DROP CONSTRAINT\n"
" | new_name\n"
" | TYPE new_datatype;\n";
}
const wxString Domain::getTypeName() const
{
return "DOMAIN";
}
void Domain::acceptVisitor(MetadataItemVisitor* visitor)
{
visitor->visitDomain(*this);
}
std::vector<Privilege>* Domain::getPrivileges()
{
// load privileges from database and return the pointer to collection
DatabasePtr db = getDatabase();
MetadataLoader* loader = db->getMetadataLoader();
privilegesM.clear();
// first start a transaction for metadata loading, then lock the relation
// when objects go out of scope and are destroyed, object will be unlocked
// before the transaction is committed - any update() calls on observers
// can possibly use the same transaction
MetadataLoaderTransaction tr(loader);
SubjectLocker lock(this);
wxMBConv* converter = db->getCharsetConverter();
IBPP::Statement& st1 = loader->getStatement(
"select RDB$USER, RDB$USER_TYPE, RDB$GRANTOR, RDB$PRIVILEGE, "
"RDB$GRANT_OPTION, RDB$FIELD_NAME "
"from RDB$USER_PRIVILEGES "
"where RDB$RELATION_NAME = ? and rdb$object_type = 9 "
"order by rdb$user, rdb$user_type, rdb$grant_option, rdb$privilege"
);
st1->Set(1, wx2std(getName_(), converter));
st1->Execute();
std::string lastuser;
int lasttype = -1;
Privilege* pr = 0;
while (st1->Fetch())
{
std::string user, grantor, privilege, field;
int usertype, grantoption = 0;
st1->Get(1, user);
st1->Get(2, usertype);
st1->Get(3, grantor);
st1->Get(4, privilege);
if (!st1->IsNull(5))
st1->Get(5, grantoption);
st1->Get(6, field);
if (!pr || user != lastuser || usertype != lasttype)
{
Privilege p(this, wxString(user.c_str(), *converter).Strip(), usertype);
privilegesM.push_back(p);
pr = &privilegesM.back();
lastuser = user;
lasttype = usertype;
}
pr->addPrivilege(privilege[0], std2wxIdentifier(grantor, converter),
grantoption == 1, std2wxIdentifier(field, converter));
}
return &privilegesM;
}
// DomainCollectionBase
DomainCollectionBase::DomainCollectionBase(NodeType type,
DatabasePtr database, const wxString& name)
: MetadataCollection<Domain>(type, database, name)
{
}
DomainPtr DomainCollectionBase::getDomain(const wxString& name)
{
DomainPtr domain = findByName(name);
if (!domain)
{
SubjectLocker lock(this);
DatabasePtr db = getDatabase();
MetadataLoader* loader = db->getMetadataLoader();
MetadataLoaderTransaction tr(loader);
wxMBConv* converter = db->getCharsetConverter();
IBPP::Statement& st1 = loader->getStatement(
Domain::getLoadStatement(false));
st1->Set(1, wx2std(name, converter));
st1->Execute();
if (st1->Fetch())
{
domain = insert(name);
domain->loadProperties(st1, converter);
}
}
return domain;
}
// Domains collection
Domains::Domains(DatabasePtr database)
: DomainCollectionBase(ntDomains, database, _("Domains"))
{
}
void Domains::acceptVisitor(MetadataItemVisitor* visitor)
{
visitor->visitDomains(*this);
}
void Domains::load(ProgressIndicator* progressIndicator)
{
wxString stmt = "select rdb$field_name from rdb$fields "
" where rdb$system_flag = 0 and rdb$field_name not starting 'RDB$' "
" order by 1";
setItems(getDatabase()->loadIdentifiers(stmt, progressIndicator));
}
void Domains::loadChildren()
{
load(0);
}
const wxString Domains::getTypeName() const
{
return "DOMAIN_COLLECTION";
}
// System domains collection
SysDomains::SysDomains(DatabasePtr database)
: DomainCollectionBase(ntSysDomains, database, _("System Domains"))
{
}
void SysDomains::acceptVisitor(MetadataItemVisitor* visitor)
{
visitor->visitSysDomains(*this);
}
void SysDomains::load(ProgressIndicator* progressIndicator)
{
wxString stmt = "select rdb$field_name from rdb$fields "
" where rdb$system_flag = 1 "
" order by 1";
setItems(getDatabase()->loadIdentifiers(stmt, progressIndicator));
}
const wxString SysDomains::getTypeName() const
{
return "SYSDOMAIN_COLLECTION";
}
| 29.752918
| 155
| 0.620088
|
blumf
|
115be4f3f2bf95b78f44b020595eab8a5576a24f
| 7,234
|
inl
|
C++
|
Library/Sources/Stroika/Frameworks/Led/StyledTextEmbeddedObjects.inl
|
SophistSolutions/Stroika
|
f4e5d84767903a054fba0a6b9c7c4bd1aaefd105
|
[
"MIT"
] | 28
|
2015-09-22T21:43:32.000Z
|
2022-02-28T01:35:01.000Z
|
Library/Sources/Stroika/Frameworks/Led/StyledTextEmbeddedObjects.inl
|
SophistSolutions/Stroika
|
f4e5d84767903a054fba0a6b9c7c4bd1aaefd105
|
[
"MIT"
] | 98
|
2015-01-22T03:21:27.000Z
|
2022-03-02T01:47:00.000Z
|
Library/Sources/Stroika/Frameworks/Led/StyledTextEmbeddedObjects.inl
|
SophistSolutions/Stroika
|
f4e5d84767903a054fba0a6b9c7c4bd1aaefd105
|
[
"MIT"
] | 4
|
2019-02-21T16:45:25.000Z
|
2022-02-18T13:40:04.000Z
|
/*
* Copyright(c) Sophist Solutions, Inc. 1990-2021. All rights reserved
*/
#ifndef _Stroika_Framework_Led_StyledTextEmbeddedObjects_inl_
#define _Stroika_Framework_Led_StyledTextEmbeddedObjects_inl_ 1
/*
********************************************************************************
***************************** Implementation Details ***************************
********************************************************************************
*/
namespace Stroika::Frameworks::Led {
/*
********************************************************************************
*********************** EmbeddedObjectCreatorRegistry::Assoc *******************
********************************************************************************
*/
inline Led_ClipFormat EmbeddedObjectCreatorRegistry::Assoc::GetIthFormat (size_t i) const
{
Assert (fFormatTagCount >= 1);
Require (i < fFormatTagCount);
return (fFormatTagCount == 1) ? fFormatTag : fFormatTags[i];
}
// class EmbeddedObjectCreatorRegistry
inline EmbeddedObjectCreatorRegistry::EmbeddedObjectCreatorRegistry ()
: fAssocList ()
{
}
inline EmbeddedObjectCreatorRegistry& EmbeddedObjectCreatorRegistry::Get ()
{
if (sThe == nullptr) {
sThe = new EmbeddedObjectCreatorRegistry ();
}
return *sThe;
}
inline void EmbeddedObjectCreatorRegistry::AddAssoc (Assoc assoc)
{
fAssocList.push_back (assoc);
}
inline void EmbeddedObjectCreatorRegistry::AddAssoc (const char* embeddingTag,
SimpleEmbeddedObjectStyleMarker* (*memReader) (const char* embeddingTag, const void* data, size_t len))
{
Assoc assoc;
assoc.fFormatTagCount = 0;
memcpy (assoc.fEmbeddingTag, embeddingTag, sizeof (assoc.fEmbeddingTag));
assoc.fReadFromMemory = memReader;
assoc.fReadFromFlavorPackage = nullptr;
AddAssoc (assoc);
}
inline void EmbeddedObjectCreatorRegistry::AddAssoc (Led_ClipFormat clipFormat, const char* embeddingTag,
SimpleEmbeddedObjectStyleMarker* (*memReader) (const char* embeddingTag, const void* data, size_t len),
SimpleEmbeddedObjectStyleMarker* (*packageReader) (ReaderFlavorPackage& flavorPackage))
{
Assoc assoc;
assoc.fFormatTag = clipFormat;
assoc.fFormatTagCount = 1;
memcpy (assoc.fEmbeddingTag, embeddingTag, sizeof (assoc.fEmbeddingTag));
assoc.fReadFromMemory = memReader;
assoc.fReadFromFlavorPackage = packageReader;
AddAssoc (assoc);
}
inline void EmbeddedObjectCreatorRegistry::AddAssoc (const Led_ClipFormat* clipFormats, size_t clipFormatCount, const char* embeddingTag,
SimpleEmbeddedObjectStyleMarker* (*memReader) (const char* embeddingTag, const void* data, size_t len),
SimpleEmbeddedObjectStyleMarker* (*packageReader) (ReaderFlavorPackage& flavorPackage))
{
Assoc assoc;
assoc.fFormatTags = clipFormats;
assoc.fFormatTagCount = clipFormatCount;
memcpy (assoc.fEmbeddingTag, embeddingTag, sizeof (assoc.fEmbeddingTag));
assoc.fReadFromMemory = memReader;
assoc.fReadFromFlavorPackage = packageReader;
AddAssoc (assoc);
}
inline const vector<EmbeddedObjectCreatorRegistry::Assoc>& EmbeddedObjectCreatorRegistry::GetAssocList () const
{
return fAssocList;
}
inline void EmbeddedObjectCreatorRegistry::SetAssocList (const vector<Assoc>& assocList)
{
fAssocList = assocList;
}
// class SimpleEmbeddedObjectStyleMarker
/*
@METHOD: SimpleEmbeddedObjectStyleMarker::GetCommandNames
@DESCRIPTION: <p>Returns command name for each of the user-visible commands produced by this module.</p>
<p>See also @'TextInteractor::CommandNames'.</p>
*/
inline const SimpleEmbeddedObjectStyleMarker::CommandNames& SimpleEmbeddedObjectStyleMarker::GetCommandNames ()
{
return sCommandNames;
}
/*
@METHOD: SimpleEmbeddedObjectStyleMarker::SetCommandNames
@DESCRIPTION: <p>See @'SimpleEmbeddedObjectStyleMarker::GetCommandNames'.</p>
*/
inline void SimpleEmbeddedObjectStyleMarker::SetCommandNames (const SimpleEmbeddedObjectStyleMarker::CommandNames& cmdNames)
{
sCommandNames = cmdNames;
}
#if qPlatform_MacOS || qPlatform_Windows
// class StandardMacPictureStyleMarker
inline StandardMacPictureStyleMarker::PictureHandle StandardMacPictureStyleMarker::GetPictureHandle () const
{
EnsureNotNull (fPictureHandle);
return fPictureHandle;
}
inline size_t StandardMacPictureStyleMarker::GetPictureByteSize () const
{
#if qPlatform_MacOS
return ::GetHandleSize (Handle (fPictureHandle));
#elif qPlatform_Windows
return fPictureSize; // cannot use ::GlobalSize () since that sometimes returns result larger than
// actual picture size (rounds up)
#endif
}
#endif
// class StandardDIBStyleMarker
inline const Led_DIB* StandardDIBStyleMarker::GetDIBData () const
{
EnsureNotNull (fDIBData);
return (fDIBData);
}
#if qPlatform_MacOS || qPlatform_Windows
// class StandardMacPictureWithURLStyleMarker
inline StandardMacPictureStyleMarker::PictureHandle StandardMacPictureWithURLStyleMarker::GetPictureHandle () const
{
EnsureNotNull (fPictureHandle);
return fPictureHandle;
}
inline size_t StandardMacPictureWithURLStyleMarker::GetPictureByteSize () const
{
#if qPlatform_MacOS
return ::GetHandleSize (Handle (fPictureHandle));
#elif qPlatform_Windows
return fPictureSize; // cannot use ::GlobalSize () since that sometimes returns result larger than
// actual picture size (rounds up)
#endif
}
#endif
// class StandardDIBWithURLStyleMarker
inline const Led_DIB* StandardDIBWithURLStyleMarker::GetDIBData () const
{
EnsureNotNull (fDIBData);
return (fDIBData);
}
// class StandardUnknownTypeStyleMarker
/*
@METHOD: StandardUnknownTypeStyleMarker::GetShownSize
@DESCRIPTION: <p>Return the size in TWIPS
of this embeddings display. Defaults to some size appropriate for the picture drawn. But sometimes
(like in reading RTF files which contain size annotations), we select an appropriate size.</p>
<p>See @'StandardUnknownTypeStyleMarker::SetShownSize'
*/
inline TWIPS_Point StandardUnknownTypeStyleMarker::GetShownSize () const
{
return fShownSize;
}
inline const void* StandardUnknownTypeStyleMarker::GetData () const
{
return fData;
}
inline size_t StandardUnknownTypeStyleMarker::GetDataLength () const
{
return fLength;
}
}
#endif /*_Stroika_Framework_Led_StyledTextEmbeddedObjects_inl_*/
| 40.413408
| 160
| 0.632568
|
SophistSolutions
|
115ce087e64662c8859b9df75e73999b620b53da
| 1,916
|
hpp
|
C++
|
src/glShaderUtil.hpp
|
Cyberunner23/OpenGLFun
|
ccc6c240d9f63f9421e9505a40d1eacd0db8185b
|
[
"Apache-2.0",
"MIT"
] | null | null | null |
src/glShaderUtil.hpp
|
Cyberunner23/OpenGLFun
|
ccc6c240d9f63f9421e9505a40d1eacd0db8185b
|
[
"Apache-2.0",
"MIT"
] | null | null | null |
src/glShaderUtil.hpp
|
Cyberunner23/OpenGLFun
|
ccc6c240d9f63f9421e9505a40d1eacd0db8185b
|
[
"Apache-2.0",
"MIT"
] | null | null | null |
// Copyright 2017 Alex Frappier Lachapelle
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according to those terms.
#pragma once
#include <fstream>
#include <optional>
#include <string>
#include <variant>
#include <vector>
#include "GL/glew.h"
template<GLenum shaderType>
std::string loadShader(GLuint &shaderID, const char* fileName) {
std::ifstream file(fileName);
std::streampos fileSize;
//Read file
file.seekg(0, std::ios::end);
fileSize = file.tellg();
file.seekg(0, std::ios::beg);
if (fileSize == 0) {
file.close();
return "Shader file is empty, most definitely is invalid.";
}
std::string shaderData;
const char* shaderDataPtr;
shaderData.reserve(fileSize);
shaderData.assign(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>());
shaderDataPtr = shaderData.c_str();
//Compile shader
GLint shaderCompiled = GL_FALSE;
shaderID = glCreateShader(shaderType);
glShaderSource(shaderID, 1, &shaderDataPtr,NULL);
glCompileShader(shaderID);
//Check for errors
glGetShaderiv(shaderID, GL_COMPILE_STATUS, &shaderCompiled);
if (shaderCompiled != GL_TRUE) {
std::string logMsg;
GLint logLength = 0;
glGetShaderiv(shaderID, GL_INFO_LOG_LENGTH, &logLength);
logMsg.reserve((GLuint)logLength + 1);
glGetShaderInfoLog(shaderID, logLength, NULL, &logMsg[0]);
return logMsg;
}
return "";
}
std::string linkShaders(GLuint &programID);
std::string setupGenericShaders(GLuint &ProgramID, const char* vertFileName, const char* fragFileName);
| 26.611111
| 103
| 0.665449
|
Cyberunner23
|
115da421a59cc35d22f54ab8944865f759020f34
| 759
|
cc
|
C++
|
muduo/net/protorpc/RpcCodec.cc
|
Fuyi-Huang/muduo-study
|
84b5f4f672123ffe5eb376d53263247c3ba942e8
|
[
"BSD-3-Clause"
] | 2
|
2018-11-09T16:34:39.000Z
|
2018-11-09T16:34:44.000Z
|
muduo/net/protorpc/RpcCodec.cc
|
Fuyi-Huang/muduo-study
|
84b5f4f672123ffe5eb376d53263247c3ba942e8
|
[
"BSD-3-Clause"
] | 1
|
2019-07-03T14:42:53.000Z
|
2019-08-07T01:43:17.000Z
|
muduo/net/protorpc/RpcCodec.cc
|
Fuyi-Huang/muduo-study
|
84b5f4f672123ffe5eb376d53263247c3ba942e8
|
[
"BSD-3-Clause"
] | 1
|
2020-09-15T03:27:22.000Z
|
2020-09-15T03:27:22.000Z
|
// Copyright 2010, Shuo Chen. All rights reserved.
// http://code.google.com/p/muduo/
//
// Use of this source code is governed by a BSD-style license
// that can be found in the License file.
// Author: Shuo Chen (chenshuo at chenshuo dot com)
#include <muduo/net/protorpc/RpcCodec.h>
#include <muduo/base/Logging.h>
#include <muduo/net/Endian.h>
#include <muduo/net/TcpConnection.h>
#include <muduo/net/protorpc/rpc.pb.h>
#include <muduo/net/protorpc/google-inl.h>
using namespace muduo;
using namespace muduo::net;
namespace
{
int ProtobufVersionCheck()
{
GOOGLE_PROTOBUF_VERIFY_VERSION;
return 0;
}
int dummy __attribute__ ((unused)) = ProtobufVersionCheck();
}
namespace muduo
{
namespace net
{
const char rpctag [] = "RPC0";
}
}
| 19.973684
| 62
| 0.720685
|
Fuyi-Huang
|
1164d2ef6dae08fcf5de985fcecc9839b5d71f18
| 4,082
|
hpp
|
C++
|
include/libp2p/protocol/kademlia/impl/get_value_executor.hpp
|
vvarma/cpp-libp2p
|
4953f30bc087de42637640eef929acfd102ef895
|
[
"Apache-2.0",
"MIT"
] | null | null | null |
include/libp2p/protocol/kademlia/impl/get_value_executor.hpp
|
vvarma/cpp-libp2p
|
4953f30bc087de42637640eef929acfd102ef895
|
[
"Apache-2.0",
"MIT"
] | null | null | null |
include/libp2p/protocol/kademlia/impl/get_value_executor.hpp
|
vvarma/cpp-libp2p
|
4953f30bc087de42637640eef929acfd102ef895
|
[
"Apache-2.0",
"MIT"
] | null | null | null |
/**
* Copyright Soramitsu Co., Ltd. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef LIBP2P_PROTOCOL_KADEMLIA_GETVALUEEXECUTOR
#define LIBP2P_PROTOCOL_KADEMLIA_GETVALUEEXECUTOR
#include <libp2p/protocol/kademlia/impl/response_handler.hpp>
#include <boost/multi_index/hashed_index_fwd.hpp>
#include <boost/multi_index/member.hpp>
#include <boost/multi_index_container_fwd.hpp>
#include <memory>
#include <queue>
#include <unordered_set>
#include <libp2p/common/types.hpp>
#include <libp2p/host/host.hpp>
#include <libp2p/protocol/common/sublogger.hpp>
#include <libp2p/protocol/kademlia/common.hpp>
#include <libp2p/protocol/kademlia/config.hpp>
#include <libp2p/protocol/kademlia/impl/content_routing_table.hpp>
#include <libp2p/protocol/kademlia/impl/executors_factory.hpp>
#include <libp2p/protocol/kademlia/impl/peer_id_with_distance.hpp>
#include <libp2p/protocol/kademlia/impl/peer_routing_table.hpp>
#include <libp2p/protocol/kademlia/impl/session.hpp>
#include <libp2p/protocol/kademlia/impl/session_host.hpp>
#include <libp2p/protocol/kademlia/peer_routing.hpp>
#include <libp2p/protocol/kademlia/validator.hpp>
namespace libp2p::protocol::kademlia {
class GetValueExecutor
: public ResponseHandler,
public std::enable_shared_from_this<GetValueExecutor> {
public:
GetValueExecutor(
const Config &config, std::shared_ptr<Host> host,
std::shared_ptr<Scheduler> scheduler,
std::shared_ptr<SessionHost> session_host,
std::shared_ptr<PeerRouting> peer_routing,
std::shared_ptr<ContentRoutingTable> content_routing_table,
const std::shared_ptr<PeerRoutingTable> &peer_routing_table,
std::shared_ptr<ExecutorsFactory> executor_factory,
std::shared_ptr<Validator> validator, ContentId key,
FoundValueHandler handler);
~GetValueExecutor() override;
outcome::result<void> start();
/// @see ResponseHandler::responseTimeout
scheduler::Ticks responseTimeout() const override;
/// @see ResponseHandler::match
bool match(const Message &msg) const override;
/// @see ResponseHandler::onResult
void onResult(const std::shared_ptr<Session> &session,
outcome::result<Message> msg_res) override;
private:
/// Spawns new request
void spawn();
/// Handles result of connection
void onConnected(
outcome::result<std::shared_ptr<connection::Stream>> stream_res);
static std::atomic_size_t instance_number;
// Primary
const Config &config_;
std::shared_ptr<Host> host_;
std::shared_ptr<Scheduler> scheduler_;
std::shared_ptr<SessionHost> session_host_;
std::shared_ptr<PeerRouting> peer_routing_;
std::shared_ptr<ContentRoutingTable> content_routing_table_;
std::shared_ptr<ExecutorsFactory> executor_factory_;
std::shared_ptr<Validator> validator_;
const ContentId key_;
FoundValueHandler handler_;
// Secondary
const NodeId target_;
std::unordered_set<PeerId> nearest_peer_ids_;
// Auxiliary
std::shared_ptr<std::vector<uint8_t>> serialized_request_;
std::priority_queue<PeerIdWithDistance> queue_;
size_t requests_in_progress_ = 0;
struct ByPeerId;
struct ByValue;
struct Record {
PeerId peer;
Value value;
};
/// Table of Record indexed by peer and value
using Table = boost::multi_index_container<
Record,
boost::multi_index::indexed_by<
boost::multi_index::hashed_unique<
boost::multi_index::tag<ByPeerId>,
boost::multi_index::member<Record, PeerId, &Record::peer>,
std::hash<PeerId>>,
boost::multi_index::ordered_non_unique<
boost::multi_index::tag<ByValue>,
boost::multi_index::member<Record, Value, &Record::value>>>>;
std::unique_ptr<Table> received_records_;
bool started_ = false;
bool done_ = false;
SubLogger log_;
};
} // namespace libp2p::protocol::kademlia
#endif // LIBP2P_PROTOCOL_KADEMLIA_GETVALUEEXECUTOR
| 32.919355
| 77
| 0.71999
|
vvarma
|
116e6bd56e33fe32a4a6fc2f0cec80bcf05abed6
| 262
|
cpp
|
C++
|
acm/shuoj/1199.cpp
|
xiaohuihuigh/cpp
|
c28bdb79ecb86f44a92971ac259910546dba29a7
|
[
"MIT"
] | 17
|
2016-01-01T12:57:25.000Z
|
2022-02-06T09:55:12.000Z
|
acm/shuoj/1199.cpp
|
xiaohuihuigh/cpp
|
c28bdb79ecb86f44a92971ac259910546dba29a7
|
[
"MIT"
] | null | null | null |
acm/shuoj/1199.cpp
|
xiaohuihuigh/cpp
|
c28bdb79ecb86f44a92971ac259910546dba29a7
|
[
"MIT"
] | 8
|
2018-12-27T01:31:49.000Z
|
2022-02-06T09:55:12.000Z
|
#include<bits/stdc++.h>
using namespace std;
int main(){
int n,m;
while(cin>>n>>m&&n&&m){
int a;
int yn = 0;
for(int i = 0;i<n;i++){
if(i != 0)cout<<" ";
cin>>a;
if(yn == 0&&m<a){
cout<<m<<" ";yn = 1;
}
cout<<a;
}
cout<<endl;
}
}
| 13.789474
| 25
| 0.450382
|
xiaohuihuigh
|
1176d493da82fd3ec95b0d0adfd9d1011a875d55
| 1,768
|
hpp
|
C++
|
include/SAMPCpp/Core/String.hpp
|
PoetaKodu/samp-cpp
|
dbd5170efe0c799d1ec902e2b8a385596a5303a8
|
[
"MIT"
] | null | null | null |
include/SAMPCpp/Core/String.hpp
|
PoetaKodu/samp-cpp
|
dbd5170efe0c799d1ec902e2b8a385596a5303a8
|
[
"MIT"
] | null | null | null |
include/SAMPCpp/Core/String.hpp
|
PoetaKodu/samp-cpp
|
dbd5170efe0c799d1ec902e2b8a385596a5303a8
|
[
"MIT"
] | 1
|
2021-06-10T22:59:53.000Z
|
2021-06-10T22:59:53.000Z
|
#pragma once
#include SAMPCPP_PCH
namespace samp_cpp
{
template <size_t MaxChars>
class InplaceStr
: public std::array<char, MaxChars>
{
public:
// Use the same constructors.
using std::array<char, MaxChars>::array;
std::string str(size_t maxLen = MaxChars) const
{
if ((*this)[0] == 0)
return {};
size_t numChars = strnlen_s(this->data(), std::min(maxLen, MaxChars));
return std::string{ this->data(), this->data() + numChars };
}
std::string_view view(size_t maxLen = MaxChars) const
{
if ((*this)[0] == 0)
return {};
size_t numChars = strnlen_s(this->data(), std::min(maxLen, MaxChars));
return std::string_view{ this->data(), numChars };
}
};
template <typename OutputIt>
constexpr inline OutputIt byteToChars(uint8_t byte_, OutputIt it_)
{
constexpr const char* digits = "0123456789ABCDEF";
*it_++ = byte_ > 0x0F ? digits[(byte_ >> 4)] : '0';
*it_++ = digits[byte_ & 0x0F];
return it_;
}
template <size_t MaxChars, typename OutputIt>
struct FormatNResult
{
InplaceStr<MaxChars> string;
fmt::format_to_n_result<OutputIt> formatResult;
};
template <size_t MaxChars, typename TFormat, typename... TArgs>
auto inplaceFormat(TFormat&& format_, TArgs&&... args_)
{
FormatNResult<MaxChars, char*> result;
result.formatResult = fmt::format_to_n(
result.string.data(), MaxChars - 1,
std::forward<TFormat>(format_),
std::forward<TArgs>(args_)...
);
*result.formatResult.out = '\0';
return result;
}
}
namespace fmt
{
template <size_t MaxChars>
struct formatter< samp_cpp::InplaceStr<MaxChars> > : formatter<std::string_view>
{
template <typename Context>
auto format(samp_cpp::InplaceStr<MaxChars> const & str_, Context& ctx_)
{
return formatter<std::string_view>::format(str_.view(), ctx_);
}
};
}
| 21.560976
| 80
| 0.694005
|
PoetaKodu
|
1177e23c507cf4e9101c51e2396f358cc002663a
| 1,177
|
hpp
|
C++
|
manager.hpp
|
inspur-bmc/sfp-manager
|
8ad235bc55aaeedfc0919f5dfb43621b77a8fe71
|
[
"Apache-2.0"
] | null | null | null |
manager.hpp
|
inspur-bmc/sfp-manager
|
8ad235bc55aaeedfc0919f5dfb43621b77a8fe71
|
[
"Apache-2.0"
] | null | null | null |
manager.hpp
|
inspur-bmc/sfp-manager
|
8ad235bc55aaeedfc0919f5dfb43621b77a8fe71
|
[
"Apache-2.0"
] | 2
|
2019-02-11T02:35:27.000Z
|
2019-09-29T09:02:51.000Z
|
#include "sfp.hpp"
#include "types.hpp"
#include <experimental/filesystem>
#include <iostream>
#include <memory>
#include <sdbusplus/sdbus.hpp>
#include <sdeventplus/event.hpp>
#include <vector>
#include <xyz/openbmc_project/Sfp/Manager/server.hpp>
namespace phosphor
{
namespace sfp
{
using ManagerObject = sdbusplus::server::object_t<
sdbusplus::xyz::openbmc_project::Sfp::server::Manager>;
class Manager : public ManagerObject
{
public:
Manager(sdbusplus::bus::bus& bus, const std::string& path,sdeventplus::Event &event) :
ManagerObject(bus, path.c_str()),event(event)
{
using namespace std::string_literals;
for (const auto& sfpDef : sfpDefinitions)
{
auto name = std::get<nameField>(sfpDef);
auto realpath = path + "/"s + name;
auto sfp = std::make_shared<Sfp>(bus, realpath,sfpDef,event);
sfps.push_back(sfp);
}
ManagerObject::count(sfpDefinitions.size());
}
private:
std::vector<std::shared_ptr<Sfp>> sfps;
static const std::vector<SfpDefinition> sfpDefinitions;
sdeventplus::Event &event;
};
} // namespace sfp
} // namespace phosphor
| 26.75
| 90
| 0.667799
|
inspur-bmc
|
117a014946d00ac43c6dcd04ef66ddf853938c46
| 1,404
|
cpp
|
C++
|
Modules/MatchPointRegistration/src/Rendering/mitkRegEvalStyleProperty.cpp
|
zhaomengxiao/MITK
|
a09fd849a4328276806008bfa92487f83a9e2437
|
[
"BSD-3-Clause"
] | 1
|
2022-03-03T12:03:32.000Z
|
2022-03-03T12:03:32.000Z
|
Modules/MatchPointRegistration/src/Rendering/mitkRegEvalStyleProperty.cpp
|
zhaomengxiao/MITK
|
a09fd849a4328276806008bfa92487f83a9e2437
|
[
"BSD-3-Clause"
] | 1
|
2021-12-22T10:19:02.000Z
|
2021-12-22T10:19:02.000Z
|
Modules/MatchPointRegistration/src/Rendering/mitkRegEvalStyleProperty.cpp
|
zhaomengxiao/MITK_lancet
|
a09fd849a4328276806008bfa92487f83a9e2437
|
[
"BSD-3-Clause"
] | 1
|
2020-11-27T09:41:18.000Z
|
2020-11-27T09:41:18.000Z
|
/*============================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.
Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.
============================================================================*/
#include "mitkRegEvalStyleProperty.h"
mitk::RegEvalStyleProperty::RegEvalStyleProperty( )
{
AddTypes();
SetValue( 0 );
}
mitk::RegEvalStyleProperty::RegEvalStyleProperty( const IdType& value )
{
AddTypes();
if ( IsValidEnumerationValue( value ) )
{
SetValue( value ) ;
}
else
{
SetValue( 0 );
}
}
mitk::RegEvalStyleProperty::RegEvalStyleProperty( const std::string& value )
{
AddTypes();
if ( IsValidEnumerationValue( value ) )
{
SetValue( value );
}
else
{
SetValue( 0 );
}
}
void mitk::RegEvalStyleProperty::AddTypes()
{
AddEnum( "Blend", static_cast<IdType>( 0 ) );
AddEnum( "Color Blend", static_cast<IdType>( 1 ) );
AddEnum( "Checkerboard", static_cast<IdType>( 2 ) );
AddEnum( "Wipe", static_cast<IdType>( 3 ) );
AddEnum( "Difference", static_cast<IdType>( 4 ) );
AddEnum( "Contour", static_cast<IdType>( 5 ) );
}
bool mitk::RegEvalStyleProperty::AddEnum( const std::string& name, const IdType& id )
{
return Superclass::AddEnum( name, id );
}
| 21.6
| 85
| 0.603989
|
zhaomengxiao
|
117a4d1ade18a400a257bd928a18da2a126092b0
| 4,545
|
cc
|
C++
|
tests/test_anasazi.cc
|
Rombur/mfmg
|
b7c66dfb58bc880b04f52ce22b454047f82d69ea
|
[
"BSD-3-Clause"
] | 8
|
2017-11-03T15:13:24.000Z
|
2021-04-27T19:33:10.000Z
|
tests/test_anasazi.cc
|
Rombur/mfmg
|
b7c66dfb58bc880b04f52ce22b454047f82d69ea
|
[
"BSD-3-Clause"
] | 199
|
2017-11-03T13:33:23.000Z
|
2019-10-07T22:46:18.000Z
|
tests/test_anasazi.cc
|
Rombur/mfmg
|
b7c66dfb58bc880b04f52ce22b454047f82d69ea
|
[
"BSD-3-Clause"
] | 7
|
2017-11-03T12:44:11.000Z
|
2020-12-16T05:51:23.000Z
|
/*************************************************************************
* Copyright (c) 2017-2019 by the mfmg authors *
* All rights reserved. *
* *
* This file is part of the mfmg libary. mfmg is distributed under a BSD *
* 3-clause license. For the licensing terms see the LICENSE file in the *
* top-level directory *
* *
* SPDX-License-Identifier: BSD-3-Clause *
*************************************************************************/
#define BOOST_TEST_MODULE anasazi
#include <mfmg/dealii/anasazi.templates.hpp>
#include <boost/test/data/test_case.hpp>
#include <cmath>
#include <cstdio>
#include "lanczos_simpleop.templates.hpp"
#include "main.cc"
namespace bdata = boost::unit_test::data;
namespace tt = boost::test_tools;
namespace Anasazi
{
template <typename VectorType>
class OperatorTraits<double, mfmg::MultiVector<VectorType>,
mfmg::SimpleOperator<VectorType>>
{
using MultiVectorType = mfmg::MultiVector<VectorType>;
using OperatorType = mfmg::SimpleOperator<VectorType>;
public:
static void Apply(const OperatorType &op, const MultiVectorType &x,
MultiVectorType &y)
{
auto n_vectors = x.n_vectors();
ASSERT(x.size() == y.size(), "");
ASSERT(y.n_vectors() == n_vectors, "");
for (int i = 0; i < n_vectors; i++)
op.vmult(*y[i], *x[i]);
}
};
} // namespace Anasazi
BOOST_DATA_TEST_CASE(anasazi,
bdata::make({1, 2}) * bdata::make({1, 2, 3, 5, 10}) *
bdata::make({false, true}),
multiplicity, n_distinct_eigenvalues,
multiple_initial_guesses)
{
using namespace mfmg;
using VectorType = dealii::Vector<double>;
using OperatorType = SimpleOperator<VectorType>;
int const n = 1000;
int const n_eigenvectors = n_distinct_eigenvalues * multiplicity;
int const n_initial_guess = multiple_initial_guesses ? n_eigenvectors : 1;
OperatorType op(n, multiplicity);
boost::property_tree::ptree anasazi_params;
anasazi_params.put("number of eigenvectors", n_eigenvectors);
anasazi_params.put("max_iterations", 1000);
anasazi_params.put("tolerance", 1e-2);
mfmg::AnasaziSolver<OperatorType, VectorType> solver(op);
VectorType initial_guess_vector(n);
initial_guess_vector = 1.;
// Add random noise to the guess
std::mt19937 gen(0);
std::uniform_real_distribution<double> dist(0, 1);
std::transform(initial_guess_vector.begin(), initial_guess_vector.end(),
initial_guess_vector.begin(),
[&](auto &v) { return v + dist(gen); });
std::vector<std::shared_ptr<VectorType>> initial_guess(n_initial_guess);
for (int i = 0; i < n_initial_guess; ++i)
{
initial_guess[i] = std::make_shared<VectorType>(initial_guess_vector);
}
std::vector<double> computed_evals;
std::vector<VectorType> computed_evecs;
std::tie(computed_evals, computed_evecs) =
solver.solve(anasazi_params, initial_guess);
auto ref_evals = op.get_evals();
BOOST_TEST(computed_evals.size() == n_eigenvectors);
// Loop to ensure each Ritz value is near an eigenvalue.
const double tolerance =
anasazi_params.get<double>("tolerance"); // this may need adjustment
std::sort(ref_evals.begin(), ref_evals.end());
std::sort(computed_evals.begin(), computed_evals.end());
for (int i = 0; i < n_eigenvectors; i++)
BOOST_TEST(computed_evals[i] == ref_evals[i], tt::tolerance(tolerance));
// Testing eigenvectors is tricky. Specifically, when multiplicity > 1, one
// gets a subspace of possible solutions. One way to test that is to
// a) test that each eigenvector is indeed an eigenvector corresponding to
// the eigenvalue
// b) test that the eigenvectors corresponding to the same eigenvalue are
// orthogonal
// In addition, from the numerical perspective, one should also care about
// scaling/normalization things. It is also unclear what tolerance should be
// used here. For now, we are just happy to have something here.
for (int i = 0; i < n_eigenvectors; i++)
{
VectorType result(n);
op.vmult(result, computed_evecs[i]);
result.add(-computed_evals[i], computed_evecs[i]);
BOOST_TEST(result.l2_norm() < tolerance);
}
}
| 35.232558
| 78
| 0.621122
|
Rombur
|
117dcf56073f5a3fdbbf4ace7d8d50af5207fc98
| 903
|
cpp
|
C++
|
N1359-Count-All-Valid-Pickup-and-Delivery-Options/solution1.cpp
|
loyio/leetcode
|
366393c29a434a621592ef6674a45795a3086184
|
[
"CC0-1.0"
] | null | null | null |
N1359-Count-All-Valid-Pickup-and-Delivery-Options/solution1.cpp
|
loyio/leetcode
|
366393c29a434a621592ef6674a45795a3086184
|
[
"CC0-1.0"
] | null | null | null |
N1359-Count-All-Valid-Pickup-and-Delivery-Options/solution1.cpp
|
loyio/leetcode
|
366393c29a434a621592ef6674a45795a3086184
|
[
"CC0-1.0"
] | 2
|
2022-01-25T05:31:31.000Z
|
2022-02-26T07:22:23.000Z
|
//
// main.cpp
// LeetCode-Solution
//
// Created by Loyio Hex on 3/6/22.
//
#include <iostream>
#include <chrono>
using namespace std;
using namespace std::chrono;
using LL = long long;
class Solution{
private:
static constexpr int mod = 1000000007;
public:
int countOrders(int n){
if (n == 1){
return 1;
}
int ans = 1;
for (int i = 2; i <= n; ++i) {
ans = (LL)ans * (i*2-1) %mod *i % mod;
}
return ans;
}
};
int main(int argc, const char * argv[]) {
auto start = high_resolution_clock::now();
// Main Start
int n = 3;
Solution solution;
cout << solution.countOrders(n);
// Main End
auto stop = high_resolution_clock::now();
auto duration = duration_cast<microseconds>(stop - start);
cout << endl << "Runnig time : " << duration.count() << "ms;" << endl;
return 0;
}
| 19.212766
| 74
| 0.557032
|
loyio
|
117e95e35defaaf760ca9db8acd8ca470a4ff91f
| 11,037
|
cpp
|
C++
|
src/Factory/Simulation/BFER/BFER.cpp
|
WilliamMajor/aff3ct
|
4e71ab99f33a040ec06336d3e1d50bd2c0d6a579
|
[
"MIT"
] | 1
|
2022-02-15T23:31:53.000Z
|
2022-02-15T23:31:53.000Z
|
src/Factory/Simulation/BFER/BFER.cpp
|
WilliamMajor/aff3ct
|
4e71ab99f33a040ec06336d3e1d50bd2c0d6a579
|
[
"MIT"
] | null | null | null |
src/Factory/Simulation/BFER/BFER.cpp
|
WilliamMajor/aff3ct
|
4e71ab99f33a040ec06336d3e1d50bd2c0d6a579
|
[
"MIT"
] | 1
|
2021-11-24T01:54:41.000Z
|
2021-11-24T01:54:41.000Z
|
#include <sstream>
#include <utility>
#include <thread>
#include "Tools/Documentation/documentation.h"
#include "Tools/Math/utils.h"
#include "Factory/Simulation/BFER/BFER.hpp"
using namespace aff3ct;
using namespace aff3ct::factory;
const std::string aff3ct::factory::BFER_name = "Simulation BFER";
const std::string aff3ct::factory::BFER_prefix = "sim";
BFER::parameters
::parameters(const std::string &name, const std::string &prefix)
: Simulation::parameters(name, prefix)
{
}
BFER::parameters* BFER::parameters
::clone() const
{
return new BFER::parameters(*this);
// if (src != nullptr) { clone->src = src ->clone(); }
// if (crc != nullptr) { clone->crc = crc ->clone(); }
// if (cdc != nullptr) { clone->cdc = cdc ->clone(); }
// if (mdm != nullptr) { clone->mdm = mdm ->clone(); }
// if (chn != nullptr) { clone->chn = chn ->clone(); }
// if (qnt != nullptr) { clone->qnt = qnt ->clone(); }
// if (mnt_mi != nullptr) { clone->mnt_mi = mnt_mi->clone(); }
// if (mnt_er != nullptr) { clone->mnt_er = mnt_er->clone(); }
// if (ter != nullptr) { clone->ter = ter ->clone(); }
// return clone;
}
std::vector<std::string> BFER::parameters
::get_names() const
{
auto n = Simulation::parameters::get_names();
if (src != nullptr) { auto nn = src ->get_names(); for (auto &x : nn) n.push_back(x); }
if (crc != nullptr) { auto nn = crc ->get_names(); for (auto &x : nn) n.push_back(x); }
if (cdc != nullptr) { auto nn = cdc ->get_names(); for (auto &x : nn) n.push_back(x); }
if (mdm != nullptr) { auto nn = mdm ->get_names(); for (auto &x : nn) n.push_back(x); }
if (chn != nullptr) { auto nn = chn ->get_names(); for (auto &x : nn) n.push_back(x); }
if (qnt != nullptr) { auto nn = qnt ->get_names(); for (auto &x : nn) n.push_back(x); }
if (mnt_mi != nullptr) { auto nn = mnt_mi->get_names(); for (auto &x : nn) n.push_back(x); }
if (mnt_er != nullptr) { auto nn = mnt_er->get_names(); for (auto &x : nn) n.push_back(x); }
if (ter != nullptr) { auto nn = ter ->get_names(); for (auto &x : nn) n.push_back(x); }
return n;
}
std::vector<std::string> BFER::parameters
::get_short_names() const
{
auto sn = Factory::parameters::get_short_names();
if (src != nullptr) { auto nn = src ->get_short_names(); for (auto &x : nn) sn.push_back(x); }
if (crc != nullptr) { auto nn = crc ->get_short_names(); for (auto &x : nn) sn.push_back(x); }
if (cdc != nullptr) { auto nn = cdc ->get_short_names(); for (auto &x : nn) sn.push_back(x); }
if (mdm != nullptr) { auto nn = mdm ->get_short_names(); for (auto &x : nn) sn.push_back(x); }
if (chn != nullptr) { auto nn = chn ->get_short_names(); for (auto &x : nn) sn.push_back(x); }
if (qnt != nullptr) { auto nn = qnt ->get_short_names(); for (auto &x : nn) sn.push_back(x); }
if (mnt_mi != nullptr) { auto nn = mnt_mi->get_short_names(); for (auto &x : nn) sn.push_back(x); }
if (mnt_er != nullptr) { auto nn = mnt_er->get_short_names(); for (auto &x : nn) sn.push_back(x); }
if (ter != nullptr) { auto nn = ter ->get_short_names(); for (auto &x : nn) sn.push_back(x); }
return sn;
}
std::vector<std::string> BFER::parameters
::get_prefixes() const
{
auto p = Factory::parameters::get_prefixes();
if (src != nullptr) { auto nn = src ->get_prefixes(); for (auto &x : nn) p.push_back(x); }
if (crc != nullptr) { auto nn = crc ->get_prefixes(); for (auto &x : nn) p.push_back(x); }
if (cdc != nullptr) { auto nn = cdc ->get_prefixes(); for (auto &x : nn) p.push_back(x); }
if (mdm != nullptr) { auto nn = mdm ->get_prefixes(); for (auto &x : nn) p.push_back(x); }
if (chn != nullptr) { auto nn = chn ->get_prefixes(); for (auto &x : nn) p.push_back(x); }
if (qnt != nullptr) { auto nn = qnt ->get_prefixes(); for (auto &x : nn) p.push_back(x); }
if (mnt_mi != nullptr) { auto nn = mnt_mi->get_prefixes(); for (auto &x : nn) p.push_back(x); }
if (mnt_er != nullptr) { auto nn = mnt_er->get_prefixes(); for (auto &x : nn) p.push_back(x); }
if (ter != nullptr) { auto nn = ter ->get_prefixes(); for (auto &x : nn) p.push_back(x); }
return p;
}
void BFER::parameters
::get_description(tools::Argument_map_info &args) const
{
Simulation::parameters::get_description(args);
auto p = this->get_prefix();
const std::string class_name = "factory::BFER::parameters::";
tools::add_arg(args, p, class_name+"p+coset,c",
tools::None());
tools::add_arg(args, p, class_name+"p+err-trk",
tools::None(),
tools::arg_rank::ADV);
tools::add_arg(args, p, class_name+"p+err-trk-rev",
tools::None(),
tools::arg_rank::ADV);
tools::add_arg(args, p, class_name+"p+err-trk-path",
tools::File(tools::openmode::read_write),
tools::arg_rank::ADV);
tools::add_arg(args, p, class_name+"p+err-trk-thold",
tools::Integer(tools::Positive(), tools::Non_zero()),
tools::arg_rank::ADV);
tools::add_arg(args, p, class_name+"p+coded",
tools::None());
auto pter = ter->get_prefix();
tools::add_arg(args, pter, class_name+"p+sigma",
tools::None());
auto pmnt = mnt_er->get_prefix();
tools::add_arg(args, pmnt, class_name+"p+mutinfo",
tools::None());
#ifdef AFF3CT_MPI
tools::add_arg(args, pmnt, class_name+"p+mpi-comm-freq",
tools::Integer(tools::Positive(), tools::Non_zero()));
#else
tools::add_arg(args, pmnt, class_name+"p+red-lazy",
tools::None());
tools::add_arg(args, pmnt, class_name+"p+red-lazy-freq",
tools::Integer(tools::Positive(), tools::Non_zero()));
#endif
}
void BFER::parameters
::store(const tools::Argument_map_value &vals)
{
using namespace std::chrono;
#if !defined(AFF3CT_SYSTEMC_SIMU)
this->n_threads = std::thread::hardware_concurrency() ? std::thread::hardware_concurrency() : 1;
#endif
Simulation::parameters::store(vals);
auto p = this->get_prefix();
if(vals.exist({p+"-err-trk-path" })) this->err_track_path = vals.at ({p+"-err-trk-path" });
if(vals.exist({p+"-err-trk-thold"})) this->err_track_threshold = vals.to_int({p+"-err-trk-thold"});
if(vals.exist({p+"-err-trk-rev" })) this->err_track_revert = true;
if(vals.exist({p+"-err-trk" })) this->err_track_enable = true;
if(vals.exist({p+"-coset", "c"})) this->coset = true;
if(vals.exist({p+"-coded", })) this->coded_monitoring = true;
if (this->err_track_revert)
{
this->err_track_enable = false;
this->n_threads = 1;
}
auto pter = ter->get_prefix();
if(vals.exist({pter+"-sigma"})) this->ter_sigma = true;
auto pmnt = mnt_er->get_prefix();
if(vals.exist({pmnt+"-mutinfo"})) this->mnt_mutinfo = true;
#ifdef AFF3CT_MPI
if(vals.exist({pmnt+"-mpi-comm-freq"})) this->mnt_mpi_comm_freq = milliseconds(vals.to_int({pmnt+"-mpi-comm-freq"}));
#else
if(vals.exist({pmnt+"-red-lazy"})) this->mnt_red_lazy = true;
if(vals.exist({pmnt+"-red-lazy-freq"}))
{
this->mnt_red_lazy = true;
this->mnt_red_lazy_freq = milliseconds(vals.to_int({pmnt+"-red-lazy-freq"}));
}
#endif
}
void BFER::parameters
::get_headers(std::map<std::string,header_list>& headers, const bool full) const
{
Simulation::parameters::get_headers(headers, full);
auto p = this->get_prefix();
if (this->noise.get() != nullptr && (this->noise.get()->type == "EBN0" || this->noise.get()->type == "ESN0"))
{
std::string pter = ter->get_prefix();
headers[pter].push_back(std::make_pair("Show Sigma", this->ter_sigma ? "on" : "off"));
}
std::string pmnt = mnt_er->get_prefix();
#ifdef AFF3CT_MPI
headers[pmnt].push_back(std::make_pair("MPI comm. freq. (ms)", std::to_string(this->mnt_mpi_comm_freq.count())));
#else
headers[pmnt].push_back(std::make_pair("Lazy reduction", this->mnt_red_lazy ? "on" : "off"));
if (this->mnt_red_lazy)
headers[pmnt].push_back(std::make_pair("Lazy reduction freq. (ms)",
std::to_string(this->mnt_red_lazy_freq.count())));
#endif
headers[p].push_back(std::make_pair("Coset approach (c)", this->coset ? "yes" : "no"));
headers[p].push_back(std::make_pair("Coded monitoring", this->coded_monitoring ? "yes" : "no"));
std::string enable_track = (this->err_track_enable) ? "on" : "off";
headers[p].push_back(std::make_pair("Bad frames tracking", enable_track));
std::string enable_rev_track = (this->err_track_revert) ? "on" : "off";
headers[p].push_back(std::make_pair("Bad frames replay", enable_rev_track));
if (this->err_track_threshold)
headers[p].push_back(std::make_pair("Bad frames threshold", std::to_string(this->err_track_threshold)));
if (this->err_track_enable || this->err_track_revert)
{
std::string path = this->err_track_path + std::string("_$noise.[src,enc,chn]");
headers[p].push_back(std::make_pair("Bad frames base path", path));
}
if (this->src != nullptr && this->cdc != nullptr)
{
const auto bit_rate = (float)this->src->K / (float)this->cdc->N;
// find the greatest common divisor of K and N
auto gcd = tools::greatest_common_divisor(this->src->K, this->cdc->N);
std::stringstream br_str;
br_str << bit_rate << " (" << this->src->K/gcd << "/" << this->cdc->N/gcd << ")";
headers[p].push_back(std::make_pair("Bit rate", br_str.str()));
}
if (this->src != nullptr)
headers[p].push_back(std::make_pair("Inter frame level", std::to_string(this->src->n_frames)));
if (this->src != nullptr) { this->src->get_headers(headers, full); }
if (this->crc != nullptr) { this->crc->get_headers(headers, full); }
if (this->cdc != nullptr) { this->cdc->get_headers(headers, full); }
if (this->mdm != nullptr) { this->mdm->get_headers(headers, full); }
if (this->chn != nullptr) { this->chn->get_headers(headers, full); }
if (this->qnt != nullptr) { this->qnt->get_headers(headers, full); }
if (this->mnt_er != nullptr) { this->mnt_er->get_headers(headers, full); }
headers[this->mnt_er->get_prefix()].push_back(std::make_pair("Compute mutual info",
this->mnt_mutinfo ? "yes" : "no"));
if (this->mnt_mutinfo)
if (this->mnt_er != nullptr) { this->mnt_er->get_headers(headers, full); }
if (this->ter != nullptr) { this->ter->get_headers(headers, full); }
}
void BFER::parameters
::set_src(Source::parameters *src)
{
this->src.reset(src);
}
void BFER::parameters
::set_crc(CRC::parameters *crc)
{
this->crc.reset(crc);
}
void BFER::parameters
::set_cdc(Codec::parameters *cdc)
{
this->cdc.reset(cdc);
}
void BFER::parameters
::set_mdm(Modem::parameters *mdm)
{
this->mdm.reset(mdm);
}
void BFER::parameters
::set_chn(Channel::parameters *chn)
{
this->chn.reset(chn);
}
void BFER::parameters
::set_qnt(Quantizer::parameters *qnt)
{
this->qnt.reset(qnt);
}
void BFER::parameters
::set_mnt_mi(Monitor_MI::parameters *mnt)
{
this->mnt_mi.reset(mnt);
}
void BFER::parameters
::set_mnt_er(Monitor_BFER::parameters *mnt)
{
this->mnt_er.reset(mnt);
}
void BFER::parameters
::set_ter(Terminal::parameters *ter)
{
this->ter.reset(ter);
}
const Codec::parameters* BFER::parameters
::get_cdc() const
{
return this->cdc.get();
}
| 34.707547
| 118
| 0.637583
|
WilliamMajor
|
117eb61f5058db2ea54693269b1dc634d0070958
| 6,050
|
cpp
|
C++
|
src/sections/TablesSection.cpp
|
pmjoniak/dime
|
07aa5f12b009604dd820c561832e4fcc35984c59
|
[
"BSD-3-Clause"
] | 1
|
2022-03-01T09:03:40.000Z
|
2022-03-01T09:03:40.000Z
|
src/sections/TablesSection.cpp
|
pmjoniak/dime
|
07aa5f12b009604dd820c561832e4fcc35984c59
|
[
"BSD-3-Clause"
] | null | null | null |
src/sections/TablesSection.cpp
|
pmjoniak/dime
|
07aa5f12b009604dd820c561832e4fcc35984c59
|
[
"BSD-3-Clause"
] | 1
|
2022-03-01T09:03:42.000Z
|
2022-03-01T09:03:42.000Z
|
/**************************************************************************\
* Copyright (c) Kongsberg Oil & Gas Technologies AS
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
\**************************************************************************/
/*!
\class dimeTablesSection dime/sections/TablesSection.h
\brief The dimeTablesSection class handles a TABLES \e section.
*/
#include <dime/sections/TablesSection.h>
#include <dime/tables/Table.h>
#include <dime/Input.h>
#include <dime/Output.h>
#include <dime/util/MemHandler.h>
#include <dime/Model.h>
#include <dime/util/Array.h>
static const char sectionName[] = "TABLES";
/*!
Constructor.
*/
dimeTablesSection::dimeTablesSection(dimeMemHandler * const memhandler)
: dimeSection( memhandler )
{
}
/*!
Destructor.
*/
dimeTablesSection::~dimeTablesSection()
{
for (int i = 0; i < this->tables.count(); i++)
delete this->tables[i];
}
//!
dimeSection *
dimeTablesSection::copy(dimeModel * const model) const
{
dimeMemHandler *memh = model->getMemHandler();
dimeTablesSection *ts = new dimeTablesSection(memh);
int n = this->tables.count();
if (n) {
int i;
ts->tables.makeEmpty(n);
for (i = 0; i < n; i++) {
dimeTable *cp = this->tables[i]->copy(model);
if (!cp) break;
ts->tables.append(cp);
}
if (i < n) {
fprintf(stderr,"Error copying TABLES section.\n");
// sim_warning("Error copying TABLES section.\n");
return NULL;
}
}
return ts;
}
/*!
Will read a dxf TABLES section.
*/
bool
dimeTablesSection::read(dimeInput * const file)
{
int32 groupcode;
const char *string;
bool ok = true;
dimeTable *table = NULL;
dimeMemHandler *memhandler = file->getMemHandler();
// sim_trace("Reading section: TABLES\n");
while (true) {
if (!file->readGroupCode(groupcode) || groupcode != 0) {
fprintf(stderr,"Error reading groupcode: %d\n", groupcode);
// sim_warning("Error reading groupcode: %d\n", groupcode);
ok = false;
break;
}
string = file->readString();
if (!strcmp(string, "ENDSEC")) break;
if (strcmp(string, "TABLE")) {
fprintf(stderr,"unexpected string.\n");
// sim_warning("unexpected string.\n");
ok = false;
break;
}
table = new dimeTable(memhandler);
if (table == NULL) {
fprintf(stderr,"error creating table: %s\n", string);
// sim_warning("error creating table: %s\n", string);
ok = false;
break;
}
if (!table->read(file)) {
fprintf(stderr,"error reading table: %s.\n", string);
// sim_warning("error reading table: %s.\n", string);
ok = false;
break;
}
this->tables.append(table);
}
return ok;
}
//!
bool
dimeTablesSection::write(dimeOutput * const file)
{
if (file->writeGroupCode(2) && file->writeString(sectionName)) {
int i, n = this->tables.count();
for (i = 0; i < n; i++) {
if (!this->tables[i]->write(file)) break;
}
if (i == n) {
return file->writeGroupCode(0) && file->writeString("ENDSEC");
}
}
return false;
}
//!
int
dimeTablesSection::typeId() const
{
return dimeBase::dimeTablesSectionType;
}
//!
int
dimeTablesSection::countRecords() const
{
int cnt = 0;
int i, n = this->tables.count();
for (i = 0; i < n; i++)
cnt += this->tables[i]->countRecords();
return cnt + 2; // two records are written in write()
}
//!
const char *
dimeTablesSection::getSectionName() const
{
return sectionName;
}
/*!
Returns the number of tables in this section.
*/
int
dimeTablesSection::getNumTables() const
{
return this->tables.count();
}
/*!
Returns the table at index \a idx.
*/
dimeTable *
dimeTablesSection::getTable(const int idx)
{
assert(idx >= 0 && idx < this->tables.count());
return this->tables[idx];
}
/*!
Removes (and deletes if no memhandler is used) the table at index \a idx.
*/
void
dimeTablesSection::removeTable(const int idx)
{
assert(idx >= 0 && idx < this->tables.count());
if (!this->memHandler) delete this->tables[idx];
this->tables.removeElem(idx);
}
/*!
Inserts a new table at index \a idx. If \a idx is negative, the
table will be inserted at the end of the list of tables.
Be aware that the order of the tables might be important.
For instance, the LTYPE table should always precede the LAYER table.
*/
void
dimeTablesSection::insertTable(dimeTable * const table, const int idx)
{
if (idx < 0) this->tables.append(table);
else {
assert(idx <= this->tables.count());
this->tables.insertElem(idx, table);
}
}
| 25.635593
| 76
| 0.656364
|
pmjoniak
|
118404e35f7181d7c943e99847fc30aeebb6da04
| 7,594
|
cpp
|
C++
|
compiler/src/core/CodeBuilder.cpp
|
d08ble/acpu
|
fb7b809ada746ecc3d1dbbe1096b120ac8f63256
|
[
"Unlicense"
] | 2
|
2021-08-28T14:45:13.000Z
|
2021-11-15T12:24:03.000Z
|
compiler/src/core/CodeBuilder.cpp
|
d08ble/acpu
|
fb7b809ada746ecc3d1dbbe1096b120ac8f63256
|
[
"Unlicense"
] | null | null | null |
compiler/src/core/CodeBuilder.cpp
|
d08ble/acpu
|
fb7b809ada746ecc3d1dbbe1096b120ac8f63256
|
[
"Unlicense"
] | null | null | null |
//
// Another CPU Language - ACPUL - a{};
//
// THIS SOFTWARE IS PROVIDED BY THE FREEBSD PROJECT ``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 FREEBSD PROJECT 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.
//
// Made by d08ble, thanks for watching.
//
#include <iostream>
#include <string>
#include <sstream>
#include "CodeBuilder.h"
#include "Name.h"
#include "Processor.h"
#include "Compiler.h"
#include "CoreData.h"
#include "ErrorNumbers.h"
using namespace acpul;
extern CoreData *acpulCoreData;
std::string CodeBuilder::build(Compiler *compiler, outtree &tree, outtree::iterator node)
{
_processor = compiler->map()->processor();
std::wstringstream stream(L"");
// stream.seekp(0, std::ios::end);
// stream << 12345;
processExpressionNode(stream, tree, node);
// std::wcout << L"L:" << stream.str() << L'\n';
std::string s = ToNarrow(stream.str().c_str());
// std::cout << "s:" << s << '\n';
info(L"> %s\n", s.c_str());
return s;//stream.str();
}
/*
void CodeBuilder::processExpressionMultipleNodes(stree &tree, stree::iterator node)
{
stree::sibling_iterator i;
i = tree.begin(node);
for (; i != tree.end(node); i++)
{
processExpressionNode(tree, i);
printf(";\n");
}
}
*/
void CodeBuilder::processExpressionNode(std::wstringstream &stream, stree &tree, stree::iterator node)
{
stype type = (*node)->type;
if ((*node)->sign)
stream << "-";
int childCount = node.number_of_children();
if (type == stype_function)
{
processFunctionNode(stream, tree, node);
return;
}
else if (type == stype_expressions)
{
stree::sibling_iterator i = tree.begin(node);
for (; i != tree.end(node); i++)
{
processExpressionNode(stream, tree, i);
}
return;
}
if (childCount <= 1)
{
if (type == stype_name)
{
Name *name = acpulCoreData->readname(tree, node);
processName(stream, name);
}
else if (type == stype_number)
{
stream << (*node)->val();
}
else if (type == stype_operator)
{
const wchar_t *s = (*node)->val(); // can be '+'
if (!wcscmp(s, L"+="))
{
stream << L"+";
}
else if (!wcscmp(s, L"-="))
{
stream << L"-";
}
else if (!wcscmp(s, L"*="))
{
stream << L"*";
}
else if (!wcscmp(s, L"/="))
{
stream << L"/";
}
else if (!wcscmp(s, L"%="))
{
stream << L"%";
}
else
{
stream << s; //s[0]
}
}
else if (type == stype_expression_simple)
{
// stream << "(";
processExpressionNode(stream, tree, tree.begin(node));
// stream << ")";
return;
}
else
{
error(L"UNKNOWN %i", type);
}
}
else
{
// bool single = false;
/*
stree::sibling_iterator i;
i = tree.begin(node);
for (; i != tree.end(node); i++)
{
stype t = (*i)->type;
if (t == stype_operator)
{
// single = true;
break;
}
}
*/
stree::sibling_iterator i;
i = tree.begin(node);
if (type == stype_expression_assign)
{
Name *name = acpulCoreData->readname(tree, i);
i++;
processName(stream, name);
stream << ":=";
// single = true;
}
else if (type == stype_expression_compound)
{
Name *name = acpulCoreData->readname(tree, i);
i++;
processName(stream, name);
Name *name1 = acpulCoreData->newName();
name1->addIdent(L"if");
if (name->isEqual(*name1))
{
// statment: IF(a, b, c)
stream << "(";
processExpressionNode(stream, tree, i);
i++;
stream << ",";
processExpressionNode(stream, tree, i);
i++;
stream << ", 0";
stream << ")";
}
else
{
// statment: WHILE(a){b}
stream << "(";
processExpressionNode(stream, tree, i);
i++;
stream << ")";
stream << "{";
processExpressionNode(stream, tree, i);
i++;
stream << "}";
}
return;
}
for (; i != tree.end(node); i++)
{
stype t = (*i)->type;
if (t == stype_expression_simple)
{
stream << "(";
}
processExpressionNode(stream, tree, i);
if (t == stype_expression_simple)
{
stream << ")";
}
// if (!single)
// printf(";");
}
}
}
void CodeBuilder::processFunctionNode(std::wstringstream &stream, stree &tree, stree::iterator node)
{
stree::sibling_iterator i;
i = tree.begin(node);
Name *name = acpulCoreData->readname(tree, i);
processName(stream, name);
stream << "(";
for (i++; i != tree.end(node); i++)
{
processExpressionNode(stream, tree, i);
outtree::sibling_iterator i1 = i;
i1++;
if (i1 != tree.end(node))
stream << ",";
}
stream << ")";
}
void CodeBuilder::processName(std::wstringstream &stream, Name *name)
{
if (name)
{
if (name->count() == 1)
{
const wchar_t *s = (*name)[0];
stream << s;
return;
}
}
stream << L"NULLNAME";
error(L"Name is undefined");
}
void CodeBuilder::info(const wchar_t *s, ...)
{
va_list ap;
va_start(ap, s);
acpulCoreData->error(EN_EXE_INFO, s, ap);
va_end(ap);
}
void CodeBuilder::error(const wchar_t *s, ...)
{
va_list ap;
va_start(ap, s);
acpulCoreData->error(EN_EXE_ERR, s, ap);
va_end(ap);
}
#include <locale>
#include <sstream>
#include <string>
std::string CodeBuilder::ToNarrow(const wchar_t *s, char dfault,
const std::locale& loc)
{
std::ostringstream stm;
while( *s != L'\0' ) {
stm << std::use_facet< std::ctype<wchar_t> >( loc ).narrow( *s++, dfault );
}
return stm.str();
}
| 24.980263
| 102
| 0.469713
|
d08ble
|
11906c8c1e645e7e9e8332985a46cb821d66b124
| 2,589
|
cpp
|
C++
|
debian/passenger-2.2.15/test/oxt/backtrace_test.cpp
|
brightbox/nginx-brightbox
|
cbb27b979ff8de2a6d3f57cebb214f0cde348d3f
|
[
"BSD-2-Clause"
] | 4
|
2016-05-09T12:50:34.000Z
|
2020-10-08T07:28:46.000Z
|
test/oxt/backtrace_test.cpp
|
chad/passenger
|
74fb3cf821d5b5d5bae37e03ba7ccaffc13ce9d0
|
[
"MIT"
] | null | null | null |
test/oxt/backtrace_test.cpp
|
chad/passenger
|
74fb3cf821d5b5d5bae37e03ba7ccaffc13ce9d0
|
[
"MIT"
] | 1
|
2020-10-08T07:51:20.000Z
|
2020-10-08T07:51:20.000Z
|
#include "tut.h"
#include <oxt/backtrace.hpp>
#include <oxt/tracable_exception.hpp>
#include <oxt/thread.hpp>
using namespace oxt;
using namespace std;
namespace tut {
struct backtrace_test {
};
DEFINE_TEST_GROUP(backtrace_test);
TEST_METHOD(1) {
// Test TRACE_POINT() and tracable_exception.
struct {
void foo() {
TRACE_POINT();
bar();
}
void bar() {
TRACE_POINT();
baz();
}
void baz() {
TRACE_POINT();
throw tracable_exception();
}
} object;
try {
object.foo();
fail("tracable_exception expected.");
} catch (const tracable_exception &e) {
ensure("Backtrace contains foo()",
e.backtrace().find("foo()") != string::npos);
ensure("Backtrace contains bar()",
e.backtrace().find("bar()") != string::npos);
ensure("Backtrace contains baz()",
e.backtrace().find("baz()") != string::npos);
}
}
struct QuitEvent {
bool is_done;
boost::mutex mutex;
boost::condition_variable cond;
QuitEvent() {
is_done = false;
}
void wait() {
boost::unique_lock<boost::mutex> l(mutex);
while (!is_done) {
cond.wait(l);
}
}
void done() {
is_done = true;
cond.notify_all();
}
};
struct FooCaller {
QuitEvent *quit_event;
static void foo(QuitEvent *quit_event) {
TRACE_POINT();
quit_event->wait();
}
void operator()() {
foo(quit_event);
}
};
struct BarCaller {
QuitEvent *quit_event;
static void bar(QuitEvent *quit_event) {
TRACE_POINT();
quit_event->wait();
}
void operator()() {
bar(quit_event);
}
};
TEST_METHOD(2) {
// Test whether oxt::thread's backtrace support works.
FooCaller foo;
QuitEvent foo_quit;
foo.quit_event = &foo_quit;
BarCaller bar;
QuitEvent bar_quit;
bar.quit_event = &bar_quit;
oxt::thread foo_thread(foo);
oxt::thread bar_thread(bar);
usleep(20000);
ensure("Foo thread's backtrace contains foo()",
foo_thread.backtrace().find("foo") != string::npos);
ensure("Foo thread's backtrace doesn't contain bar()",
foo_thread.backtrace().find("bar") == string::npos);
ensure("Bar thread's backtrace contains bar()",
bar_thread.backtrace().find("bar") != string::npos);
ensure("Bar thread's backtrace doesn't contain foo()",
bar_thread.backtrace().find("foo") == string::npos);
string all_backtraces(oxt::thread::all_backtraces());
ensure(all_backtraces.find("foo") != string::npos);
ensure(all_backtraces.find("bar") != string::npos);
foo_quit.done();
bar_quit.done();
foo_thread.join();
bar_thread.join();
}
}
| 20.069767
| 56
| 0.634994
|
brightbox
|
119124f14d9b4bc95891af19ae84d0f56d029970
| 1,642
|
cpp
|
C++
|
src/eepp/system/iostreamzip.cpp
|
jayrulez/eepp
|
09c5c1b6b4c0306bb0a188474778c6949b5df3a7
|
[
"MIT"
] | 37
|
2020-01-20T06:21:24.000Z
|
2022-03-21T17:44:50.000Z
|
src/eepp/system/iostreamzip.cpp
|
jayrulez/eepp
|
09c5c1b6b4c0306bb0a188474778c6949b5df3a7
|
[
"MIT"
] | null | null | null |
src/eepp/system/iostreamzip.cpp
|
jayrulez/eepp
|
09c5c1b6b4c0306bb0a188474778c6949b5df3a7
|
[
"MIT"
] | 9
|
2019-03-22T00:33:07.000Z
|
2022-03-01T01:35:59.000Z
|
#include <eepp/system/iostreamzip.hpp>
#include <eepp/system/zip.hpp>
#include <libzip/zip.h>
#include <libzip/zipint.h>
namespace EE { namespace System {
IOStreamZip* IOStreamZip::New( Zip* pack, const std::string& path ) {
return eeNew( IOStreamZip, ( pack, path ) );
}
IOStreamZip::IOStreamZip( Zip* pack, const std::string& path ) :
mPath( path ), mZip( pack->getZip() ), mFile( NULL ), mPos( 0 ) {
struct zip_stat zs;
int err = zip_stat( mZip, path.c_str(), 0, &zs );
if ( !err ) {
mFile = zip_fopen_index( mZip, zs.index, 0 );
}
}
IOStreamZip::~IOStreamZip() {
if ( isOpen() ) {
zip_fclose( mFile );
}
}
ios_size IOStreamZip::read( char* data, ios_size size ) {
int res = -1;
if ( isOpen() ) {
res = zip_fread( mFile, reinterpret_cast<void*>( &data[0] ), size );
if ( -1 != res ) {
mPos += size;
}
}
return -1 != res ? res : 0;
}
ios_size IOStreamZip::write( const char* data, ios_size size ) {
return 0;
}
ios_size IOStreamZip::seek( ios_size position ) {
if ( isOpen() && mPos != position ) {
zip_fclose( mFile );
struct zip_stat zs;
int err = zip_stat( mZip, mPath.c_str(), 0, &zs );
if ( !err ) {
mFile = zip_fopen_index( mZip, zs.index, 0 );
if ( 0 != position ) {
ScopedBuffer ptr( position );
read( (char*)ptr.get(), position );
}
mPos = position;
return position;
}
}
return 0;
}
ios_size IOStreamZip::tell() {
return mPos;
}
ios_size IOStreamZip::getSize() {
struct zip_stat zs;
int err = zip_stat( mZip, mPath.c_str(), 0, &zs );
return !err ? zs.size : 0;
}
bool IOStreamZip::isOpen() {
return NULL != mFile;
}
}} // namespace EE::System
| 19.317647
| 70
| 0.620585
|
jayrulez
|
11995aa1b83bfa5041c249482672af9c7a08e59a
| 3,587
|
hxx
|
C++
|
src/engine/ivp/ivp_physics/ivp_cache_object.hxx
|
cstom4994/SourceEngineRebuild
|
edfd7f8ce8af13e9d23586318350319a2e193c08
|
[
"MIT"
] | 6
|
2022-01-23T09:40:33.000Z
|
2022-03-20T20:53:25.000Z
|
src/engine/ivp/ivp_physics/ivp_cache_object.hxx
|
cstom4994/SourceEngineRebuild
|
edfd7f8ce8af13e9d23586318350319a2e193c08
|
[
"MIT"
] | null | null | null |
src/engine/ivp/ivp_physics/ivp_cache_object.hxx
|
cstom4994/SourceEngineRebuild
|
edfd7f8ce8af13e9d23586318350319a2e193c08
|
[
"MIT"
] | 1
|
2022-02-06T21:05:23.000Z
|
2022-02-06T21:05:23.000Z
|
// Copyright (C) Ipion Software GmbH 1999-2000. All rights reserved.
//IVP_EXPORT_PUBLIC
// Note:
// freeze object must update update_cache_object + set cache_ledge_point->valid_until_time_code
// delete object: must call invalid_cache_object
#ifndef _IVP_CACHE_OBJECT_INCLUDED
#define _IVP_CACHE_OBJECT_INCLUDED
class IVP_Cache_Object {
friend class IVP_Real_Object;
friend class IVP_Cache_Object_Manager;
friend class IVP_U_Matrix_Cache;
IVP_Time_CODE valid_until_time_code; // compared to environment->get_current_time_code() !
int reference_count; // number of references to this
IVP_Real_Object *object; // backlink to object
public:
void remove_reference() {
IVP_ASSERT(reference_count == 1);
reference_count--;
};
IVP_U_Quat q_world_f_object;
IVP_U_Matrix m_world_f_object;
IVP_U_Point core_pos;
void update_cache_object();
void transform_vector_to_world_coords(const IVP_U_Point *P_object, IVP_U_Point *P_world_out) const;
void transform_vector_to_world_coords(const IVP_U_Float_Point *P_object, IVP_U_Float_Point *P_world_out) const;
void transform_vector_to_object_coords(const IVP_U_Point *P_world, IVP_U_Point *P_object_out) const;
void transform_vector_to_object_coords(const IVP_U_Float_Point *P_world, IVP_U_Float_Point *P_object_out) const;
void transform_position_to_world_coords(const IVP_U_Float_Point *P_object, IVP_U_Point *P_world_out) const;
void transform_position_to_object_coords(const IVP_U_Point *P_world, IVP_U_Float_Point *P_object_out) const;
void transform_position_to_object_coords(const IVP_U_Point *P_world, IVP_U_Point *P_object_out) const;
};
class IVP_Cache_Object_Manager {
int n_cache_objects;
int reuse_loop_index; // rotates through the array
char *cache_objects_buffer; // IVP_Cache_Object
public:
static void invalid_cache_object(IVP_Real_Object *object);
inline IVP_Cache_Object *cache_object_at(int i) {
const int size = (sizeof(IVP_Cache_Object) + 0xf) & ~0xf;
return (IVP_Cache_Object *) (cache_objects_buffer + size * i);
}
IVP_Cache_Object *get_cache_object(IVP_Real_Object *object);
#ifdef DEBUG
void check(); // check when no locks are set
#endif
IVP_Cache_Object_Manager(int number_of_cache_elements); // number_of_cache_elements is 2**x
~IVP_Cache_Object_Manager();
};
IVP_Cache_Object *IVP_Real_Object::get_cache_object() {
// get cache from object manager
if (!this->cache_object) {
IVP_Environment *env = get_environment();
this->cache_object = env->get_cache_object_manager()->get_cache_object(this);
}
this->cache_object->reference_count++;
if (IVP_MTIS_SIMULATED(this->flags.object_movement_state)) {
IVP_Environment *env = get_environment();
if (env->get_current_time_code() > cache_object->valid_until_time_code) {
cache_object->update_cache_object();
}
}
return cache_object;
}
IVP_Cache_Object *IVP_Real_Object::get_cache_object_no_lock() {
// get cache from object manager
if (!this->cache_object) {
IVP_Environment *env = get_environment();
this->cache_object = env->get_cache_object_manager()->get_cache_object(this);
}
if (IVP_MTIS_SIMULATED(this->flags.object_movement_state)) {
IVP_Environment *env = get_environment();
if (env->get_current_time_code() > cache_object->valid_until_time_code) {
cache_object->update_cache_object();
}
}
return cache_object;
}
#endif
| 32.908257
| 116
| 0.740452
|
cstom4994
|
119ed0a1cea831ff87438dff83fc3257aebc65ac
| 3,074
|
cc
|
C++
|
qa/common/busy_op_kernel.cc
|
wilwang-nv/tensorrt-inference-server
|
a99ab7b1320f06a2ebce6088f2ecc31faf10e13e
|
[
"BSD-3-Clause"
] | 2,159
|
2020-08-26T06:21:38.000Z
|
2022-03-31T16:13:46.000Z
|
qa/common/busy_op_kernel.cc
|
wilwang-nv/tensorrt-inference-server
|
a99ab7b1320f06a2ebce6088f2ecc31faf10e13e
|
[
"BSD-3-Clause"
] | 1,482
|
2020-08-26T08:26:36.000Z
|
2022-03-31T23:11:19.000Z
|
qa/common/busy_op_kernel.cc
|
wilwang-nv/tensorrt-inference-server
|
a99ab7b1320f06a2ebce6088f2ecc31faf10e13e
|
[
"BSD-3-Clause"
] | 592
|
2020-08-26T06:09:25.000Z
|
2022-03-31T00:37:41.000Z
|
// Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``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 <time.h>
#include "tensorflow/core/framework/device_base.h"
#include "tensorflow/core/framework/op.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/tensor_shape.h"
using namespace tensorflow; // NOLINT(build/namespaces)
REGISTER_OP("BusyLoop").Input("input: int32").Output("output: int32").Doc(R"doc(
Busy waits for input number of clock cycles
)doc");
void BusyLoopKernelLauncher(
const Eigen::GpuDevice& device, const int* num_delay_cycles, int* out);
class BusyLoopOp : public OpKernel {
public:
explicit BusyLoopOp(OpKernelConstruction* context) : OpKernel(context) {}
void Compute(OpKernelContext* context) override
{
// Grab the input
const Tensor& input_tensor = context->input(0);
auto num_delay_cycles = input_tensor.flat<int32>();
// Create dummy output
Tensor* output_tensor = nullptr;
OP_REQUIRES_OK(
context,
context->allocate_output(0, input_tensor.shape(), &output_tensor));
auto output = output_tensor->template flat<int32>();
// Verify input dimension
OP_REQUIRES(
context, TensorShapeUtils::IsVector(input_tensor.shape()),
errors::InvalidArgument(
"BusyLoop expects a single value as a 1-D Vector"));
// Call the cuda kernel launcher
BusyLoopKernelLauncher(
context->eigen_device<Eigen::GpuDevice>(), num_delay_cycles.data(),
output.data());
}
};
REGISTER_KERNEL_BUILDER(Name("BusyLoop").Device(DEVICE_GPU), BusyLoopOp);
| 41.540541
| 80
| 0.742355
|
wilwang-nv
|
119efa207150b8f6f4d792add3e0629dcfbeb2a8
| 3,705
|
hpp
|
C++
|
src/include/containers/List.hpp
|
a093050472/PX4-Auotopilot
|
177da1f92324dcb98b23643b73cfe5cb342ba32f
|
[
"BSD-3-Clause"
] | 6
|
2020-01-04T08:18:35.000Z
|
2021-12-24T09:11:53.000Z
|
src/include/containers/List.hpp
|
BazookaJoe1900/Firmware
|
b827a04b288844767701fb7922600e3bd193d9e9
|
[
"BSD-3-Clause"
] | 4
|
2020-11-07T12:08:43.000Z
|
2021-06-18T15:16:17.000Z
|
src/include/containers/List.hpp
|
BazookaJoe1900/Firmware
|
b827a04b288844767701fb7922600e3bd193d9e9
|
[
"BSD-3-Clause"
] | 20
|
2020-07-09T03:11:03.000Z
|
2021-12-21T13:01:18.000Z
|
/****************************************************************************
*
* Copyright (C) 2012-2019 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/**
* @file List.hpp
*
* An intrusive linked list.
*/
#pragma once
#include <stdlib.h>
template<class T>
class ListNode
{
public:
void setSibling(T sibling) { _list_node_sibling = sibling; }
const T getSibling() const { return _list_node_sibling; }
protected:
T _list_node_sibling{nullptr};
};
template<class T>
class List
{
public:
void add(T newNode)
{
newNode->setSibling(getHead());
_head = newNode;
}
bool remove(T removeNode)
{
if (removeNode == nullptr) {
return false;
}
// base case
if (removeNode == _head) {
if (_head != nullptr) {
_head = _head->getSibling();
}
return true;
}
for (T node = getHead(); node != nullptr; node = node->getSibling()) {
// is sibling the node to remove?
if (node->getSibling() == removeNode) {
// replace sibling
if (node->getSibling() != nullptr) {
node->setSibling(node->getSibling()->getSibling());
} else {
node->setSibling(nullptr);
}
return true;
}
}
return false;
}
struct Iterator {
T node;
Iterator(T v) : node(v) {}
operator T() const { return node; }
operator T &() { return node; }
T operator* () const { return node; }
Iterator &operator++ ()
{
if (node) {
node = node->getSibling();
};
return *this;
}
};
Iterator begin() { return Iterator(getHead()); }
Iterator end() { return Iterator(nullptr); }
const T getHead() const { return _head; }
bool empty() const { return getHead() == nullptr; }
size_t size() const
{
size_t sz = 0;
for (auto node = getHead(); node != nullptr; node = node->getSibling()) {
sz++;
}
return sz;
}
void deleteNode(T node)
{
if (remove(node)) {
// only delete if node was successfully removed
delete node;
}
}
void clear()
{
auto node = getHead();
while (node != nullptr) {
auto next = node->getSibling();
delete node;
node = next;
}
_head = nullptr;
}
protected:
T _head{nullptr};
};
| 22.87037
| 78
| 0.645074
|
a093050472
|
119fe669f1aa79816581003c7dcbf963541f1ef0
| 3,334
|
cpp
|
C++
|
module.cpp
|
UniversalDataTool/autoseg
|
dfeffe332f558171bac62a92e5a1d07f8ec2e96c
|
[
"MIT"
] | 6
|
2020-07-27T15:15:01.000Z
|
2022-01-06T08:19:09.000Z
|
module.cpp
|
UniversalDataTool/autoseg
|
dfeffe332f558171bac62a92e5a1d07f8ec2e96c
|
[
"MIT"
] | 4
|
2020-07-27T15:14:56.000Z
|
2021-08-31T20:56:14.000Z
|
module.cpp
|
UniversalDataTool/autoseg
|
dfeffe332f558171bac62a92e5a1d07f8ec2e96c
|
[
"MIT"
] | 2
|
2020-10-04T22:26:34.000Z
|
2021-07-26T10:12:12.000Z
|
#define _LIBCPP_ENABLE_CXX17_REMOVED_AUTO_PTR
#include "globals.hpp"
#include "min_cut.cpp"
#include "polygon_fill.cpp"
#include "super_pixel.cpp"
#include <emscripten/bind.h>
#include <emscripten/val.h>
#include <stdio.h>
#include <vector>
using namespace emscripten;
std::shared_ptr<std::vector<uint8_t>> image;
bool loggedVersion = false;
bool polygonImpliedClassPoints = true;
bool simpleMode = false;
void setImageSize(int w, int h) {
if (!loggedVersion) {
printf("autoseg_0.1\n");
loggedVersion = true;
}
image = std::make_shared<std::vector<uint8_t>>(w * h * 4);
width = w;
height = h;
}
void setVerboseMode(bool trueForOn) { verboseMode = trueForOn; }
void setSimpleMode(bool trueForOn) { simpleMode = trueForOn; }
void setPolygonImpliedClassPoints(bool trueForOn) {
polygonImpliedClassPoints = trueForOn;
}
void clearClassElements() {
classPoints.clear();
polygons.clear();
}
void setMaxClusters(int newMaxClusters) { maxClusters = newMaxClusters; }
void setWeightFactor(int newWeightFactor) { weightFactor = newWeightFactor; }
void setClassColor(int cls, uint32_t color) {
while (classToColor.size() <= cls) {
classToColor.push_back(0xFFFF00FF);
}
classToColor[cls] = color;
}
void addClassPoint(int cls, int ri, int ci) {
classPoints.push_back(ClassPoint{cls, ri, ci});
}
void computeSuperPixels() {
if (!simpleMode) {
superpixel(*image);
}
}
void computeMasks() {
if (!simpleMode) {
if (polygonImpliedClassPoints) {
addPolygonImpliedClassPoints();
}
prepareForMinCuts();
for (int i = 0; i < totalClasses; i++) {
if (verboseMode) {
printf("running min cut for cls: %d\n", i);
}
minCutCls(i);
}
if (verboseMode) {
for (int clsi = 0; clsi < totalClasses; clsi++) {
for (int cci = 0; cci < numClusters; cci++) {
printf("clsi: %4d cci: %4d (ri: %4.0f, ci: %4.0f), on: %d\n",
clsi, cci, centers[cci][0], centers[cci][1],
clsMasks[cci][clsi]);
}
}
}
resolveMasks();
} else {
coloredMask = std::vector<uint32_t>(width * height);
}
overlayPolygonsOnColoredMask();
}
// This is definitely not the right way to do this
int getColoredMask() { return reinterpret_cast<int>(&coloredMask[0]); }
int getImageAddr() { return reinterpret_cast<int>(&(*image)[0]); }
EMSCRIPTEN_BINDINGS(my_module) {
register_vector<ClassPoint>("vector<ClassPoint>");
value_object<ClassPoint>("ClassPoint")
.field("cls", &ClassPoint::cls)
.field("ri", &ClassPoint::ri)
.field("ci", &ClassPoint::ci);
function("setImageSize", &setImageSize);
function("clearClassElements", &clearClassElements);
function("addClassPoint", &addClassPoint);
function("setClassColor", &setClassColor);
function("getImageAddr", &getImageAddr, allow_raw_pointers());
function("getColoredMask", &getColoredMask, allow_raw_pointers());
function("computeSuperPixels", &computeSuperPixels);
function("computeMasks", &computeMasks);
function("setVerboseMode", &setVerboseMode);
function("setSimpleMode", &setSimpleMode);
function("setMaxClusters", &setMaxClusters);
function("addPolygon", &addPolygon);
function("addLineToPolygon", &addLineToPolygon);
function("setPolygonImpliedClassPoints", &setPolygonImpliedClassPoints);
}
| 28.991304
| 77
| 0.687163
|
UniversalDataTool
|
11a0e59ee3f3c37b151d5cc5bde2c24c358a4bee
| 12,828
|
cpp
|
C++
|
src/caffe/greentea/greentea_im2col.cpp
|
abhiTronix/caffe-opencl-windows-amd
|
1de97750d3c97756f39899d3b158120971a8a5da
|
[
"BSD-2-Clause"
] | 8
|
2019-06-29T14:51:28.000Z
|
2021-07-25T04:10:38.000Z
|
src/caffe/greentea/greentea_im2col.cpp
|
KorJeongHyeonLee/Caffe-CL-Origin
|
430344adbb3a05b4611b1b821a68c82d6480ba26
|
[
"Intel",
"BSD-2-Clause"
] | 1
|
2018-12-12T11:57:27.000Z
|
2019-06-30T03:31:09.000Z
|
src/caffe/greentea/greentea_im2col.cpp
|
KorJeongHyeonLee/Caffe-CL-Origin
|
430344adbb3a05b4611b1b821a68c82d6480ba26
|
[
"Intel",
"BSD-2-Clause"
] | 2
|
2018-08-31T20:13:22.000Z
|
2019-06-29T14:51:33.000Z
|
/*
* greentea_im2col.cpp
*
* Created on: Apr 8, 2015
* Author: Fabian Tschopp
*/
#include "caffe/common.hpp"
#ifdef USE_GREENTEA
#include "caffe/greentea/greentea_im2col.hpp"
namespace caffe {
template<typename Dtype>
void greentea_im2col_gpu(viennacl::ocl::program *prog,
viennacl::ocl::context *ctx, const cl_mem data_im,
const int_tp data_offset, const int_tp channels,
const int_tp height, const int_tp width,
const int_tp kernel_h, const int_tp kernel_w,
const int_tp pad_h, const int_tp pad_w,
const int_tp stride_h, const int_tp stride_w,
const int_tp dilation_h, const int_tp dilation_w,
cl_mem data_col, const int_tp data_col_off) {
int_tp height_col = (height + 2 * pad_h - (dilation_h * (kernel_h - 1) + 1))
/ stride_h + 1;
int_tp width_col = (width + 2 * pad_w - (dilation_w * (kernel_w - 1) + 1))
/ stride_w + 1;
int_tp num_kernels = channels * height_col * width_col;
viennacl::ocl::kernel &kernel = prog->get_kernel(CL_KERNEL_SELECT("im2col"));
viennacl::ocl::enqueue(
kernel(num_kernels, WrapHandle(data_im, ctx), data_offset, height, width,
kernel_h, kernel_w, pad_h, pad_w, stride_h, stride_w, dilation_h,
dilation_w, height_col, width_col, WrapHandle(data_col, ctx),
data_col_off),
ctx->get_queue());
}
// Explicit instantiation
template void greentea_im2col_gpu<float>(viennacl::ocl::program *prog,
viennacl::ocl::context *ctx,
const cl_mem data_im,
const int_tp data_offset,
const int_tp channels,
const int_tp height,
const int_tp width,
const int_tp kernel_h,
const int_tp kernel_w,
const int_tp pad_h, const int_tp pad_w,
const int_tp stride_h,
const int_tp stride_w,
const int_tp dilation_h,
const int_tp dilation_w,
cl_mem data_col,
const int_tp data_col_off);
template void greentea_im2col_gpu<double>(viennacl::ocl::program *prog,
viennacl::ocl::context *ctx,
const cl_mem data_im,
const int_tp data_offset,
const int_tp channels,
const int_tp height,
const int_tp width,
const int_tp kernel_h,
const int_tp kernel_w,
const int_tp pad_h,
const int_tp pad_w,
const int_tp stride_h,
const int_tp stride_w,
const int_tp dilation_h,
const int_tp dilation_w,
cl_mem data_col,
const int_tp data_col_off);
template<typename Dtype>
void greentea_col2im_gpu(viennacl::ocl::program *prog,
viennacl::ocl::context *ctx, const cl_mem data_col,
const int_tp data_col_off, const int_tp channels,
const int_tp height, const int_tp width,
const int_tp kernel_h, const int_tp kernel_w,
const int_tp pad_h, const int_tp pad_w,
const int_tp stride_h, const int_tp stride_w,
const int_tp dilation_h, const int_tp dilation_w,
cl_mem data_im, const int_tp data_offset) {
int_tp height_col = (height + 2 * pad_h - (dilation_h * (kernel_h - 1) + 1))
/ stride_h + 1;
int_tp width_col = (width + 2 * pad_w - (dilation_w * (kernel_w - 1) + 1))
/ stride_w + 1;
int_tp num_kernels = channels * height * width;
viennacl::ocl::kernel &kernel = prog->get_kernel(CL_KERNEL_SELECT("col2im"));
viennacl::ocl::enqueue(
kernel(num_kernels, WrapHandle(data_col, ctx), data_col_off, height,
width, channels, kernel_h, kernel_w, pad_h, pad_w, stride_h,
stride_w, dilation_h, dilation_w, height_col, width_col,
WrapHandle(data_im, ctx), data_offset),
ctx->get_queue());
}
template void greentea_col2im_gpu<float>(viennacl::ocl::program *prog,
viennacl::ocl::context *ctx,
const cl_mem data_col,
const int_tp data_col_off,
const int_tp channels,
const int_tp height,
const int_tp width,
const int_tp patch_h,
const int_tp patch_w,
const int_tp pad_h, const int_tp pad_w,
const int_tp stride_h,
const int_tp stride_w,
const int_tp dilation_h,
const int_tp dilation_w,
cl_mem data_im,
const int_tp data_offset);
template void greentea_col2im_gpu<double>(viennacl::ocl::program *prog,
viennacl::ocl::context *ctx,
const cl_mem data_col,
const int_tp data_col_off,
const int_tp channels,
const int_tp height,
const int_tp width,
const int_tp patch_h,
const int_tp patch_w,
const int_tp pad_h,
const int_tp pad_w,
const int_tp stride_h,
const int_tp stride_w,
const int_tp dilation_h,
const int_tp dilation_w,
cl_mem data_im,
const int_tp data_offset);
template<typename Dtype>
void greentea_im2col_nd_gpu(viennacl::ocl::program *prog,
viennacl::ocl::context *ctx, cl_mem data_im,
const int_tp data_off,
const int_tp num_spatial_axes,
const int_tp channel_axis, const int_tp num_kernels,
cl_mem im_shape, cl_mem col_shape,
cl_mem kernel_shape, cl_mem pad, cl_mem stride,
cl_mem dilation, cl_mem data_col,
const int_tp data_col_off) {
viennacl::ocl::kernel &kernel = prog->get_kernel(
CL_KERNEL_SELECT("im2col_nd"));
viennacl::ocl::enqueue(
kernel(num_kernels, num_spatial_axes, channel_axis,
WrapHandle(data_im, ctx), data_off, WrapHandle(im_shape, ctx),
WrapHandle(col_shape, ctx), WrapHandle(kernel_shape, ctx),
WrapHandle(pad, ctx), WrapHandle(stride, ctx),
WrapHandle(dilation, ctx), WrapHandle(data_col, ctx),
data_col_off),
ctx->get_queue());
}
// Explicit instantiation
template void greentea_im2col_nd_gpu<float>(viennacl::ocl::program *prog,
viennacl::ocl::context *ctx,
cl_mem data_im,
const int_tp data_off,
const int_tp num_spatial_axes,
const int_tp channel_axis,
const int_tp num_kernels,
cl_mem im_shape, cl_mem col_shape,
cl_mem kernel_shape, cl_mem pad,
cl_mem stride, cl_mem dilation,
cl_mem data_col,
const int_tp data_col_off);
template void greentea_im2col_nd_gpu<double>(viennacl::ocl::program *prog,
viennacl::ocl::context *ctx,
cl_mem data_im,
const int_tp data_off,
const int_tp num_spatial_axes,
const int_tp channel_axis,
const int_tp num_kernels,
cl_mem im_shape, cl_mem col_shape,
cl_mem kernel_shape, cl_mem pad,
cl_mem stride, cl_mem dilation,
cl_mem data_col,
const int_tp data_col_off);
template<typename Dtype>
void greentea_col2im_nd_gpu(viennacl::ocl::program *prog,
viennacl::ocl::context *ctx, cl_mem data_col,
const int_tp data_col_off,
const int_tp num_spatial_axes,
const int_tp channel_axis, const int_tp im_size,
cl_mem im_shape, cl_mem col_shape,
cl_mem kernel_shape, cl_mem pad, cl_mem stride,
cl_mem dilation, cl_mem data_im,
const int_tp data_im_off) {
viennacl::ocl::kernel &kernel = prog->get_kernel(
CL_KERNEL_SELECT("col2im_nd"));
viennacl::ocl::enqueue(
kernel(im_size, num_spatial_axes, channel_axis,
WrapHandle(data_col, ctx), data_col_off,
WrapHandle(im_shape, ctx),
WrapHandle(col_shape, ctx),
WrapHandle(kernel_shape, ctx), WrapHandle(pad, ctx),
WrapHandle(stride, ctx), WrapHandle(dilation, ctx),
WrapHandle(data_im, ctx), data_im_off),
ctx->get_queue());
}
// Explicit instantiation
template void greentea_col2im_nd_gpu<float>(viennacl::ocl::program *prog,
viennacl::ocl::context *ctx,
cl_mem data_col,
const int_tp data_col_off,
const int_tp num_spatial_axes,
const int_tp channel_axis,
const int_tp im_size,
cl_mem im_shape, cl_mem col_shape,
cl_mem kernel_shape, cl_mem pad,
cl_mem stride, cl_mem dilation,
cl_mem data_im, int_tp data_off);
template void greentea_col2im_nd_gpu<double>(viennacl::ocl::program *prog,
viennacl::ocl::context *ctx,
cl_mem data_col,
const int_tp data_col_off,
const int_tp num_spatial_axes,
const int_tp channel_axis,
const int_tp im_size,
cl_mem im_shape, cl_mem col_shape,
cl_mem kernel_shape, cl_mem pad,
cl_mem stride, cl_mem dilation,
cl_mem data_im, int_tp data_off);
} // namespace caffe
#endif
| 54.355932
| 80
| 0.444029
|
abhiTronix
|
11a450eb30d6d8172cb2113072134a26a4e73ee3
| 17,379
|
cpp
|
C++
|
src/demos/core/demo_CH_solver.cpp
|
chfeller/chrono
|
652d5a6ed433611f2d335cf33b7da5658bf6f620
|
[
"BSD-3-Clause"
] | 1
|
2015-03-19T16:48:13.000Z
|
2015-03-19T16:48:13.000Z
|
src/demos/core/demo_CH_solver.cpp
|
chfeller/chrono
|
652d5a6ed433611f2d335cf33b7da5658bf6f620
|
[
"BSD-3-Clause"
] | null | null | null |
src/demos/core/demo_CH_solver.cpp
|
chfeller/chrono
|
652d5a6ed433611f2d335cf33b7da5658bf6f620
|
[
"BSD-3-Clause"
] | null | null | null |
// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Alessandro Tasora, Radu Serban
// =============================================================================
// Include some headers used by this tutorial...
#include "chrono/physics/ChGlobal.h"
#include "chrono/core/ChLinearAlgebra.h"
#include "chrono/core/ChLinkedListMatrix.h"
#include "chrono/solver/ChVariablesGeneric.h"
#include "chrono/solver/ChVariablesBodyOwnMass.h"
#include "chrono/solver/ChConstraintTwoGeneric.h"
#include "chrono/solver/ChConstraintTwoBodies.h"
#include "chrono/solver/ChKblockGeneric.h"
#include "chrono/solver/ChSystemDescriptor.h"
#include "chrono/solver/ChSolverSOR.h"
#include "chrono/solver/ChSolverPMINRES.h"
#include "chrono/solver/ChSolverBB.h"
#include "chrono_thirdparty/filesystem/path.h"
// Remember to use the namespace 'chrono' because all classes
// of Chrono::Engine belong to this namespace and its children...
using namespace chrono;
// The HyperOCTANT solver is aimed at solving linear problems and
// VI/LCP/CCP complementarity problems, as those arising
// from QP optimization problems.
// The problem is described by a variational inequality VI(Z*x-d,K):
//
// | M -Cq'|*|q|- | f|= |0| , l \in Y, C \in Ny, normal cone to Y
// | Cq -E | |l| |-b| |c|
//
// Also w.symmetric Z by flipping sign of l_i: |M Cq'|*| q|-| f|=|0|
// |Cq E | |-l| |-b| |c|
// * case linear problem: all Y_i = R, Ny=0, ex. all bilateral constr.
// * case LCP: all Y_i = R+: c>=0, l>=0, l*c=0 ex. unilateral constr.
// * case CCP: Y_i are friction cones, etc.
//
// The HyperOCTANT technology is mostly targeted
// at solving multibody problems in Chrono::Engine
// so it offers optimizations for the case where the M matrix
// is diagonal or block-diagonal: each block refers to a
// ChVariables object, and each line of jacobian Cq belongs
// to a ChConstraint object.
//
// NOTE: the frictional contact problem is a special type of nonlinear
// complementarity, called Cone Complementary (CCP) and this is
// solved as well by HyperOctant, using the same framework.
// Test 1
// First example: how to manage the data structures of
// the solver, and how to get results after the solution.
// All systems are made of two types of items: the
// VARIABLES (unknowns q in the scheme below) and
// CONSTRAINTS (unknowns reactions 'l' in the scheme).
// As an example, let's solve the following mixed LCP:
//
// | 10 0 0 . 1 0 | |q_a0| | 1| | 0|
// | 0 10 0 . 2 1 | |q_a1| | 2| | 0|
// | 0 0 10 . -1 0 | |q_a2| | 0| | 0|
// | 20 0 0 . 1 0 | |q_b0| | 0| | 0|
// | 0 20 0 . -2 -1 | |q_b1| - | 0| = | 0|
// | 0 0 20 . 0 0 | |q_b2| | 0| | 0|
// | ..........................| |....| |...| |...|
// | 1 2 -1 1 -2 0 . | |-l_1| | 5| |c_1|
// | 0 1 0 0 -1 0 . | |-l_2| | -1| |c_2|
void test_1(const std::string& out_dir) {
GetLog() << "\n-------------------------------------------------\n";
GetLog() << "TEST: generic system with two constraints \n\n";
// Important: create a 'system descriptor' object that
// contains variables and constraints:
ChSystemDescriptor mdescriptor;
// Now let's add variables and constraints, as sparse data:
mdescriptor.BeginInsertion(); // ----- system description starts here
// create C++ objects representing 'variables':
ChVariablesGeneric mvarA(3);
mvarA.GetMass().SetIdentity();
mvarA.GetMass() *= 10;
ChLinearAlgebra::Invert(mvarA.GetInvMass(), &mvarA.GetMass());
mvarA.Get_fb()(0) = 1;
mvarA.Get_fb()(1) = 2;
ChVariablesGeneric mvarB(3);
mvarB.GetMass().SetIdentity();
mvarB.GetMass() *= 20;
ChLinearAlgebra::Invert(mvarB.GetInvMass(), &mvarB.GetMass());
mdescriptor.InsertVariables(&mvarA);
mdescriptor.InsertVariables(&mvarB);
// create C++ objects representing 'constraints' between variables:
ChConstraintTwoGeneric mca(&mvarA, &mvarB);
mca.Set_b_i(-5);
mca.Get_Cq_a()->ElementN(0) = 1;
mca.Get_Cq_a()->ElementN(1) = 2;
mca.Get_Cq_a()->ElementN(2) = -1;
mca.Get_Cq_b()->ElementN(0) = 1;
mca.Get_Cq_b()->ElementN(1) = -2;
mca.Get_Cq_b()->ElementN(2) = 0;
ChConstraintTwoGeneric mcb(&mvarA, &mvarB);
mcb.Set_b_i(1);
mcb.Get_Cq_a()->ElementN(0) = 0;
mcb.Get_Cq_a()->ElementN(1) = 1;
mcb.Get_Cq_a()->ElementN(2) = 0;
mcb.Get_Cq_b()->ElementN(0) = 0;
mcb.Get_Cq_b()->ElementN(1) = -2;
mcb.Get_Cq_b()->ElementN(2) = 0;
mdescriptor.InsertConstraint(&mca);
mdescriptor.InsertConstraint(&mcb);
mdescriptor.EndInsertion(); // ----- system description ends here
// Solve the problem with an iterative fixed-point solver, for an
// approximate (but very fast) solution:
//
// .. create the solver
ChSolverSOR msolver_iter(1, // max iterations
false, // don't use warm start
0.0, // termination tolerance
0.8); // omega
// .. pass the constraint and the variables to the solver
// to solve - that's all.
msolver_iter.Solve(mdescriptor);
// Ok, now present the result to the user, with some
// statistical information:
double max_res, max_LCPerr;
mdescriptor.ComputeFeasabilityViolation(max_res, max_LCPerr);
// If needed, dump the full system M and Cq matrices
// on disk, in Matlab sparse format:
ChLinkedListMatrix matrM;
ChLinkedListMatrix matrCq;
mdescriptor.ConvertToMatrixForm(&matrCq, &matrM, 0, 0, 0, 0, false, false);
try {
std::string filename = out_dir + "/dump_M_1.dat";
ChStreamOutAsciiFile fileM(filename.c_str());
filename = out_dir + "/dump_Cq_1.dat";
ChStreamOutAsciiFile fileCq(filename.c_str());
matrM.StreamOUTsparseMatlabFormat(fileM);
matrCq.StreamOUTsparseMatlabFormat(fileCq);
} catch (ChException myex) {
GetLog() << "FILE ERROR: " << myex.what();
}
matrM.StreamOUT(GetLog());
matrCq.StreamOUT(GetLog());
GetLog() << "**** Using ChSolverSOR ********** \n\n";
GetLog() << "METRICS: max residual: " << max_res << " max LCP error: " << max_LCPerr << " \n\n";
GetLog() << "vars q_a and q_b -------------------\n";
GetLog() << mvarA.Get_qb();
GetLog() << mvarB.Get_qb() << " \n";
GetLog() << "multipliers l_1 and l_2 ------------\n\n";
GetLog() << mca.Get_l_i() << " \n";
GetLog() << mcb.Get_l_i() << " \n\n";
GetLog() << "constraint residuals c_1 and c_2 ---\n";
GetLog() << mca.Get_c_i() << " \n";
GetLog() << mcb.Get_c_i() << " \n\n\n";
// reset variables
mvarA.Get_qb().FillElem(0.);
mvarB.Get_qb().FillElem(0.);
}
// Test 2
// Create a bunch of monodimensional vars and simple
// constraints between them, using 'for' loops, as a benchmark that
// represents, from a physical point of view, a long inverted multipendulum.
void test_2(const std::string& out_dir) {
GetLog() << "\n-------------------------------------------------\n";
GetLog() << "TEST: 1D vertical pendulum - ChSolverPMINRES \n\n";
ChSystemDescriptor mdescriptor;
mdescriptor.BeginInsertion(); // ----- system description starts here
int n_masses = 11;
std::vector<ChVariablesGeneric*> vars;
std::vector<ChConstraintTwoGeneric*> constraints;
for (int im = 0; im < n_masses; im++) {
vars.push_back(new ChVariablesGeneric(1));
vars[im]->GetMass()(0) = 10;
vars[im]->GetInvMass()(0) = 1. / vars[im]->GetMass()(0);
vars[im]->Get_fb()(0) = -9.8 * vars[im]->GetMass()(0) * 0.01;
// if (im==5) vars[im]->Get_fb()(0)= 50;
mdescriptor.InsertVariables(vars[im]);
if (im > 0) {
constraints.push_back(new ChConstraintTwoGeneric(vars[im], vars[im - 1]));
constraints[im - 1]->Set_b_i(0);
constraints[im - 1]->Get_Cq_a()->ElementN(0) = 1;
constraints[im - 1]->Get_Cq_b()->ElementN(0) = -1;
mdescriptor.InsertConstraint(constraints[im - 1]);
}
}
// First variable of 1st domain is 'fixed' like in a hanging chain
vars[0]->SetDisabled(true);
mdescriptor.EndInsertion(); // ----- system description is finished
try {
std::string filename;
chrono::ChLinkedListMatrix mdM;
chrono::ChLinkedListMatrix mdCq;
chrono::ChLinkedListMatrix mdE;
chrono::ChMatrixDynamic<double> mdf;
chrono::ChMatrixDynamic<double> mdb;
chrono::ChMatrixDynamic<double> mdfric;
mdescriptor.ConvertToMatrixForm(&mdCq, &mdM, &mdE, &mdf, &mdb, &mdfric);
filename = out_dir + "/dump_M_2.dat";
chrono::ChStreamOutAsciiFile file_M(filename.c_str());
mdM.StreamOUTsparseMatlabFormat(file_M);
filename = out_dir + "/dump_Cq_2.dat";
chrono::ChStreamOutAsciiFile file_Cq(filename.c_str());
mdCq.StreamOUTsparseMatlabFormat(file_Cq);
filename = out_dir + "/dump_E_2.dat";
chrono::ChStreamOutAsciiFile file_E(filename.c_str());
mdE.StreamOUTsparseMatlabFormat(file_E);
filename = out_dir + "/dump_f_2.dat";
chrono::ChStreamOutAsciiFile file_f(filename.c_str());
mdf.StreamOUTdenseMatlabFormat(file_f);
filename = out_dir + "/dump_b_2.dat";
chrono::ChStreamOutAsciiFile file_b(filename.c_str());
mdb.StreamOUTdenseMatlabFormat(file_b);
filename = out_dir + "/dump_fric_2.dat";
chrono::ChStreamOutAsciiFile file_fric(filename.c_str());
mdfric.StreamOUTdenseMatlabFormat(file_fric);
} catch (chrono::ChException myexc) {
chrono::GetLog() << myexc.what();
}
// Create a solver of Krylov type
ChSolverPMINRES msolver_krylov(20, // max iterations
false, // warm start
0.00001); // tolerance
// .. pass the constraint and the variables to the solver
// to solve - that's all.
msolver_krylov.Solve(mdescriptor);
// Output values
GetLog() << "VARIABLES: \n";
for (int im = 0; im < vars.size(); im++)
GetLog() << " " << vars[im]->Get_qb()(0) << "\n";
GetLog() << "CONSTRAINTS: \n";
for (int ic = 0; ic < constraints.size(); ic++)
GetLog() << " " << constraints[ic]->Get_l_i() << "\n";
}
// Test 3
// Create three variables, with some mass, and also add a stiffness item
// that connects two of these variables with random stiffness.
// Also use the ChSystemDescriptor functions FromUnknownsToVector
// and FromVectorToUnknowns for doing checks.
//
// | M+K K . Cq' | |q_a | |f_a| | 0|
// | K M+K . Cq' | |q_b | |f_b| | 0|
// | M . | |q_c | |f_c| = | 0|
// | ....................| |... | |...| |...|
// | Cq Cq . | |-l_1| | 5| |c_1|
void test_3(const std::string& out_dir) {
GetLog() << "\n-------------------------------------------------\n";
GetLog() << "TEST: generic system with stiffness blocks \n\n";
// Important: create a 'system descriptor' object that
// contains variables and constraints:
ChSystemDescriptor mdescriptor;
// Now let's add variables, constraints and stiffness, as sparse data:
mdescriptor.BeginInsertion(); // ----- system description
// Create C++ objects representing 'variables', set their M blocks
// (the masses) and set their known terms 'fb'
ChMatrix33<> minertia;
minertia.FillDiag(6);
ChVariablesBodyOwnMass mvarA;
mvarA.SetBodyMass(5);
mvarA.SetBodyInertia(minertia);
mvarA.Get_fb().FillRandom(-3, 5);
ChVariablesBodyOwnMass mvarB;
mvarB.SetBodyMass(4);
mvarB.SetBodyInertia(minertia);
mvarB.Get_fb().FillRandom(1, 3);
ChVariablesBodyOwnMass mvarC;
mvarC.SetBodyMass(5.5);
mvarC.SetBodyInertia(minertia);
mvarC.Get_fb().FillRandom(-8, 3);
mdescriptor.InsertVariables(&mvarA);
mdescriptor.InsertVariables(&mvarB);
mdescriptor.InsertVariables(&mvarC);
// Create two C++ objects representing 'constraints' between variables
// and set the jacobian to random values;
// Also set cfm term (E diagonal = -cfm)
ChConstraintTwoBodies mca(&mvarA, &mvarB);
mca.Set_b_i(3);
mca.Get_Cq_a()->FillRandom(-1, 1);
mca.Get_Cq_b()->FillRandom(-1, 1);
mca.Set_cfm_i(0.2);
ChConstraintTwoBodies mcb(&mvarA, &mvarB);
mcb.Set_b_i(5);
mcb.Get_Cq_a()->FillRandom(-1, 1);
mcb.Get_Cq_b()->FillRandom(-1, 1);
mcb.Set_cfm_i(0.1);
mdescriptor.InsertConstraint(&mca);
mdescriptor.InsertConstraint(&mcb);
// Create two C++ objects representing 'stiffness' between variables:
ChKblockGeneric mKa;
// set the affected variables (so this K is a 12x12 matrix, relative to 4 6x6 blocks)
std::vector<ChVariables*> mvarsa;
mvarsa.push_back(&mvarA);
mvarsa.push_back(&mvarB);
mKa.SetVariables(mvarsa);
// just fill K with random values (but symmetric, by making a product of matr*matrtransposed)
ChMatrixDynamic<> mtempA = *mKa.Get_K(); // easy init to same size of K
mtempA.FillRandom(-0.3, 0.3);
ChMatrixDynamic<> mtempB;
mtempB.CopyFromMatrixT(mtempA);
*mKa.Get_K() = -mtempA * mtempB;
mdescriptor.InsertKblock(&mKa);
ChKblockGeneric mKb;
// set the affected variables (so this K is a 12x12 matrix, relative to 4 6x6 blocks)
std::vector<ChVariables*> mvarsb;
mvarsb.push_back(&mvarB);
mvarsb.push_back(&mvarC);
mKb.SetVariables(mvarsb);
*mKb.Get_K() = *mKa.Get_K();
mdescriptor.InsertKblock(&mKb);
mdescriptor.EndInsertion(); // ----- system description ends here
// SOLVE the problem with an iterative Krylov solver.
// In this case we use a MINRES-like solver, that features
// very good convergence, it supports indefinite cases (ex.
// redundant constraints) and also supports the presence
// of ChStiffness blocks (other solvers cannot cope with this!)
// .. create the solver
ChSolverPMINRES msolver_mr(80, // max iterations
false, // don't use warm start
1e-12); // termination tolerance
// .. set optional parameters of solver
msolver_mr.SetDiagonalPreconditioning(true);
msolver_mr.SetVerbose(true);
// .. solve the system (passing variables, constraints, stiffness
// blocks with the ChSystemDescriptor that we populated above)
msolver_mr.Solve(mdescriptor);
// .. optional: get the result as a single vector (it collects all q_i and l_i
// solved values stored in variables and constraints), just for check.
chrono::ChMatrixDynamic<double> mx;
mdescriptor.FromUnknownsToVector(mx); // x ={q,-l}
// CHECK. Test if, with the solved x, we really have Z*x-d=0 ...
// to this end do the multiplication with the special function
// SystemProduct() that is 'sparse-friendly' and does not build Z explicitly:
chrono::ChMatrixDynamic<double> md;
mdescriptor.BuildDiVector(md); // d={f;-b}
chrono::ChMatrixDynamic<double> mZx;
mdescriptor.SystemProduct(mZx, &mx); // Zx = Z*x
GetLog() << "CHECK: norm of solver residual: ||Z*x-d|| -------------------\n";
GetLog() << (mZx - md).NormInf() << "\n";
/*
// Alternatively, instead of using FromUnknownsToVector, to fetch
// result, you could just loop over the variables (q values) and
// over the constraints (l values), as already shown in previous examples:
for (int im = 0; im < mdescriptor.GetVariablesList().size(); im++)
GetLog() << " " << mdescriptor.GetVariablesList()[im]->Get_qb()(0) << "\n";
for (int ic = 0; ic < mdescriptor.GetConstraintsList().size(); ic++)
GetLog() << " " << mdescriptor.GetConstraintsList()[ic]->Get_l_i() << "\n";
*/
}
// Do some tests in a single run, inside the main() function.
// Results will be simply text-formatted outputs in the console..
int main(int argc, char* argv[]) {
GetLog() << "Copyright (c) 2017 projectchrono.org\nChrono version: " << CHRONO_VERSION << "\n\n";
GetLog() << " Example: the HyperOCTANT technology for solving LCP\n\n\n";
// Create (if needed) output directory
const std::string out_dir = GetChronoOutputPath() + "DEMO_SOLVER";
if (!filesystem::create_directory(filesystem::path(out_dir))) {
std::cout << "Error creating directory " << out_dir << std::endl;
return 1;
}
// Test: an introductory problem:
test_1(out_dir);
// Test: the 'inverted pendulum' benchmark (compute reactions with Krylov solver)
test_2(out_dir);
// Test: the stiffness benchmark (add also sparse stiffness blocks over M)
test_3(out_dir);
return 0;
}
| 37.293991
| 102
| 0.61068
|
chfeller
|
11aa8f8a138414549695d523c0367ebc2afff9ea
| 6,750
|
hpp
|
C++
|
viennacl/linalg/host_based/scalar_operations.hpp
|
bollig/viennacl
|
6dac70e558ed42abe63d8c5bfd08465aafeda859
|
[
"MIT"
] | 1
|
2020-09-21T08:33:10.000Z
|
2020-09-21T08:33:10.000Z
|
viennacl/linalg/host_based/scalar_operations.hpp
|
bollig/viennacl
|
6dac70e558ed42abe63d8c5bfd08465aafeda859
|
[
"MIT"
] | null | null | null |
viennacl/linalg/host_based/scalar_operations.hpp
|
bollig/viennacl
|
6dac70e558ed42abe63d8c5bfd08465aafeda859
|
[
"MIT"
] | null | null | null |
#ifndef VIENNACL_LINALG_HOST_BASED_SCALAR_OPERATIONS_HPP_
#define VIENNACL_LINALG_HOST_BASED_SCALAR_OPERATIONS_HPP_
/* =========================================================================
Copyright (c) 2010-2012, Institute for Microelectronics,
Institute for Analysis and Scientific Computing,
TU Wien.
Portions of this software are copyright by UChicago Argonne, LLC.
-----------------
ViennaCL - The Vienna Computing Library
-----------------
Project Head: Karl Rupp rupp@iue.tuwien.ac.at
(A list of authors and contributors can be found in the PDF manual)
License: MIT (X11), see file LICENSE in the base directory
============================================================================= */
/** @file viennacl/linalg/host_based/scalar_operations.hpp
@brief Implementations of scalar operations using a plain single-threaded or OpenMP-enabled execution on CPU
*/
#include "viennacl/forwards.h"
#include "viennacl/scalar.hpp"
#include "viennacl/tools/tools.hpp"
#include "viennacl/meta/predicate.hpp"
#include "viennacl/meta/enable_if.hpp"
#include "viennacl/traits/size.hpp"
#include "viennacl/traits/start.hpp"
#include "viennacl/traits/stride.hpp"
#include "viennacl/linalg/host_based/common.hpp"
namespace viennacl
{
namespace linalg
{
namespace host_based
{
template <typename S1,
typename S2, typename ScalarType1>
typename viennacl::enable_if< viennacl::is_scalar<S1>::value
&& viennacl::is_scalar<S2>::value
&& viennacl::is_any_scalar<ScalarType1>::value
>::type
as(S1 & s1,
S2 const & s2, ScalarType1 const & alpha, std::size_t /*len_alpha*/, bool reciprocal_alpha, bool flip_sign_alpha)
{
typedef typename viennacl::result_of::cpu_value_type<S1>::type value_type;
value_type * data_s1 = detail::extract_raw_pointer<value_type>(s1);
value_type const * data_s2 = detail::extract_raw_pointer<value_type>(s2);
value_type data_alpha = alpha;
if (flip_sign_alpha)
data_alpha = -data_alpha;
if (reciprocal_alpha)
data_alpha = static_cast<value_type>(1) / data_alpha;
*data_s1 = *data_s2 * data_alpha;
}
template <typename S1,
typename S2, typename ScalarType1,
typename S3, typename ScalarType2>
typename viennacl::enable_if< viennacl::is_scalar<S1>::value
&& viennacl::is_scalar<S2>::value
&& viennacl::is_scalar<S3>::value
&& viennacl::is_any_scalar<ScalarType1>::value
&& viennacl::is_any_scalar<ScalarType2>::value
>::type
asbs(S1 & s1,
S2 const & s2, ScalarType1 const & alpha, std::size_t /*len_alpha*/, bool reciprocal_alpha, bool flip_sign_alpha,
S3 const & s3, ScalarType2 const & beta, std::size_t /*len_beta*/, bool reciprocal_beta, bool flip_sign_beta)
{
typedef typename viennacl::result_of::cpu_value_type<S1>::type value_type;
value_type * data_s1 = detail::extract_raw_pointer<value_type>(s1);
value_type const * data_s2 = detail::extract_raw_pointer<value_type>(s2);
value_type const * data_s3 = detail::extract_raw_pointer<value_type>(s3);
value_type data_alpha = alpha;
if (flip_sign_alpha)
data_alpha = -data_alpha;
if (reciprocal_alpha)
data_alpha = static_cast<value_type>(1) / data_alpha;
value_type data_beta = beta;
if (flip_sign_beta)
data_beta = -data_beta;
if (reciprocal_beta)
data_beta = static_cast<value_type>(1) / data_beta;
*data_s1 = *data_s2 * data_alpha + *data_s3 * data_beta;
}
template <typename S1,
typename S2, typename ScalarType1,
typename S3, typename ScalarType2>
typename viennacl::enable_if< viennacl::is_scalar<S1>::value
&& viennacl::is_scalar<S2>::value
&& viennacl::is_scalar<S3>::value
&& viennacl::is_any_scalar<ScalarType1>::value
&& viennacl::is_any_scalar<ScalarType2>::value
>::type
asbs_s(S1 & s1,
S2 const & s2, ScalarType1 const & alpha, std::size_t /*len_alpha*/, bool reciprocal_alpha, bool flip_sign_alpha,
S3 const & s3, ScalarType2 const & beta, std::size_t /*len_beta*/, bool reciprocal_beta, bool flip_sign_beta)
{
typedef typename viennacl::result_of::cpu_value_type<S1>::type value_type;
value_type * data_s1 = detail::extract_raw_pointer<value_type>(s1);
value_type const * data_s2 = detail::extract_raw_pointer<value_type>(s2);
value_type const * data_s3 = detail::extract_raw_pointer<value_type>(s3);
value_type data_alpha = alpha;
if (flip_sign_alpha)
data_alpha = -data_alpha;
if (reciprocal_alpha)
data_alpha = static_cast<value_type>(1) / data_alpha;
value_type data_beta = beta;
if (flip_sign_beta)
data_beta = -data_beta;
if (reciprocal_beta)
data_beta = static_cast<value_type>(1) / data_beta;
*data_s1 += *data_s2 * data_alpha + *data_s3 * data_beta;
}
/** @brief Swaps the contents of two scalars, data is copied
*
* @param s1 The first scalar
* @param s2 The second scalar
*/
template <typename S1, typename S2>
typename viennacl::enable_if< viennacl::is_scalar<S1>::value
&& viennacl::is_scalar<S2>::value
>::type
swap(S1 & s1, S2 & s2)
{
typedef typename viennacl::result_of::cpu_value_type<S1>::type value_type;
value_type * data_s1 = detail::extract_raw_pointer<value_type>(s1);
value_type const * data_s2 = detail::extract_raw_pointer<value_type>(s2);
value_type temp = *data_s2;
*data_s2 = *data_s1;
*data_s1 = temp;
}
} //namespace host_based
} //namespace linalg
} //namespace viennacl
#endif
| 41.158537
| 126
| 0.56563
|
bollig
|
11ae64b4ba531b009d0f35934d1d547b28767e1b
| 8,417
|
cpp
|
C++
|
Tests/TestApp/src/TestShaderResArrays.cpp
|
SCrusader/DiligentEngine
|
3081e9165ae8d931e75f9aa8f825d72fbb0e8cdb
|
[
"Apache-2.0"
] | null | null | null |
Tests/TestApp/src/TestShaderResArrays.cpp
|
SCrusader/DiligentEngine
|
3081e9165ae8d931e75f9aa8f825d72fbb0e8cdb
|
[
"Apache-2.0"
] | null | null | null |
Tests/TestApp/src/TestShaderResArrays.cpp
|
SCrusader/DiligentEngine
|
3081e9165ae8d931e75f9aa8f825d72fbb0e8cdb
|
[
"Apache-2.0"
] | null | null | null |
/* Copyright 2015-2018 Egor Yusov
*
* 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
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PROPRIETARY RIGHTS.
*
* In no event and under no legal theory, whether in tort (including negligence),
* contract, or otherwise, unless required by applicable law (such as deliberate
* and grossly negligent acts) or agreed to in writing, shall any Contributor be
* liable for any damages, including any direct, indirect, special, incidental,
* or consequential damages of any character arising as a result of this License or
* out of the use or inability to use the software (including but not limited to damages
* for loss of goodwill, work stoppage, computer failure or malfunction, or any and
* all other commercial damages or losses), even if such Contributor has been advised
* of the possibility of such damages.
*/
// EngineSandbox.cpp : Defines the entry point for the application.
//
#include "pch.h"
#include "TestShaderResArrays.h"
#include "GraphicsUtilities.h"
#include "BasicShaderSourceStreamFactory.h"
#include "TestTexturing.h"
using namespace Diligent;
TestShaderResArrays::TestShaderResArrays(IRenderDevice *pDevice, IDeviceContext *pDeviceContext, bool bUseOpenGL, float fMinXCoord, float fMinYCoord, float fXExtent, float fYExtent) :
UnitTestBase("Shader resource array test")
{
m_pRenderDevice = pDevice;
m_pDeviceContext = pDeviceContext;
ShaderCreationAttribs CreationAttrs;
BasicShaderSourceStreamFactory BasicSSSFactory;
CreationAttrs.pShaderSourceStreamFactory = &BasicSSSFactory;
CreationAttrs.Desc.TargetProfile = SHADER_PROFILE_DX_5_0;
RefCntAutoPtr<Diligent::IShader> pVS, pPS;
{
CreationAttrs.FilePath = "Shaders\\ShaderResArrayTest.vsh";
CreationAttrs.Desc.ShaderType = SHADER_TYPE_VERTEX;
CreationAttrs.SourceLanguage = SHADER_SOURCE_LANGUAGE_HLSL;
m_pRenderDevice->CreateShader( CreationAttrs, &pVS );
}
{
CreationAttrs.FilePath = "Shaders\\ShaderResArrayTest.psh";
StaticSamplerDesc StaticSampler;
StaticSampler.Desc.MinFilter = FILTER_TYPE_LINEAR;
StaticSampler.Desc.MagFilter = FILTER_TYPE_LINEAR;
StaticSampler.Desc.MipFilter = FILTER_TYPE_LINEAR;
StaticSampler.TextureName = "g_tex2DTest";
CreationAttrs.Desc.NumStaticSamplers = 1;
CreationAttrs.Desc.StaticSamplers = &StaticSampler;
CreationAttrs.Desc.ShaderType = SHADER_TYPE_PIXEL;
CreationAttrs.SourceLanguage = SHADER_SOURCE_LANGUAGE_HLSL;
ShaderVariableDesc Vars[] =
{
{"g_tex2DTest", SHADER_VARIABLE_TYPE_MUTABLE},
{"g_tex2DTest2", SHADER_VARIABLE_TYPE_STATIC},
{"g_tex2D", SHADER_VARIABLE_TYPE_DYNAMIC}
};
CreationAttrs.Desc.VariableDesc = Vars;
CreationAttrs.Desc.NumVariables = _countof(Vars);
m_pRenderDevice->CreateShader( CreationAttrs, &pPS );
}
PipelineStateDesc PSODesc;
PSODesc.GraphicsPipeline.DepthStencilDesc.DepthEnable = False;
PSODesc.GraphicsPipeline.RasterizerDesc.CullMode = CULL_MODE_NONE;
PSODesc.GraphicsPipeline.BlendDesc.IndependentBlendEnable = False;
PSODesc.GraphicsPipeline.BlendDesc.RenderTargets[0].BlendEnable = False;
PSODesc.GraphicsPipeline.RTVFormats[0] = TEX_FORMAT_RGBA8_UNORM_SRGB;
PSODesc.GraphicsPipeline.NumRenderTargets = 1;
PSODesc.GraphicsPipeline.pVS = pVS;
PSODesc.GraphicsPipeline.pPS = pPS;
LayoutElement Elems[] =
{
LayoutElement( 0, 0, 3, Diligent::VT_FLOAT32, false, 0 ),
LayoutElement( 1, 0, 2, Diligent::VT_FLOAT32, false, sizeof( float ) * 3 )
};
PSODesc.GraphicsPipeline.InputLayout.LayoutElements = Elems;
PSODesc.GraphicsPipeline.InputLayout.NumElements = _countof( Elems );
pDevice->CreatePipelineState(PSODesc, &m_pPSO);
m_pPSO->CreateShaderResourceBinding(&m_pSRB);
float Vertices[] =
{
0, 0, 0, 0,1,
0, 1, 0, 0,0,
1, 0, 0, 1,1,
1, 1, 0, 1,0
};
for(int v=0; v < 4; ++v)
{
Vertices[v*5+0] = Vertices[v*5+0] * fXExtent + fMinXCoord;
Vertices[v*5+1] = Vertices[v*5+1] * fYExtent + fMinYCoord;
}
{
Diligent::BufferDesc BuffDesc;
BuffDesc.uiSizeInBytes = sizeof(Vertices);
BuffDesc.BindFlags = BIND_VERTEX_BUFFER;
BuffDesc.Usage = USAGE_STATIC;
Diligent::BufferData BuffData;
BuffData.pData = Vertices;
BuffData.DataSize = BuffDesc.uiSizeInBytes;
m_pRenderDevice->CreateBuffer(BuffDesc, BuffData, &m_pVertexBuff);
}
RefCntAutoPtr<ISampler> pSampler;
SamplerDesc SamDesc;
pDevice->CreateSampler(SamDesc, &pSampler);
for(auto t=0; t < _countof(m_pTextures); ++t)
{
TextureDesc TexDesc;
TexDesc.Type = RESOURCE_DIM_TEX_2D;
TexDesc.Width = 256;
TexDesc.Height = 256;
TexDesc.MipLevels = 8;
TexDesc.Usage = USAGE_STATIC;
TexDesc.Format = TEX_FORMAT_RGBA8_UNORM;
TexDesc.BindFlags = BIND_SHADER_RESOURCE;
TexDesc.Name = "Test Texture";
std::vector<Uint8> Data;
std::vector<TextureSubResData> SubResouces;
float ColorOffset[4] = {(float)t*0.13f, (float)t*0.21f, (float)t*0.29f, 0};
TestTexturing::GenerateTextureData(m_pRenderDevice, Data, SubResouces, TexDesc, ColorOffset);
TextureData TexData;
TexData.pSubResources = SubResouces.data();
TexData.NumSubresources = (Uint32)SubResouces.size();
m_pRenderDevice->CreateTexture( TexDesc, TexData, &m_pTextures[t] );
m_pTextures[t]->GetDefaultView(TEXTURE_VIEW_SHADER_RESOURCE)->SetSampler(pSampler);
}
ResourceMappingEntry ResMpEntries [] =
{
ResourceMappingEntry("g_tex2DTest", m_pTextures[0]->GetDefaultView(TEXTURE_VIEW_SHADER_RESOURCE), 0),
ResourceMappingEntry("g_tex2DTest", m_pTextures[1]->GetDefaultView(TEXTURE_VIEW_SHADER_RESOURCE), 1),
ResourceMappingEntry("g_tex2DTest", m_pTextures[2]->GetDefaultView(TEXTURE_VIEW_SHADER_RESOURCE), 2),
ResourceMappingEntry("g_tex2DTest2", m_pTextures[5]->GetDefaultView(TEXTURE_VIEW_SHADER_RESOURCE), 0),
ResourceMappingEntry("g_tex2D", m_pTextures[6]->GetDefaultView(TEXTURE_VIEW_SHADER_RESOURCE), 0),
ResourceMappingEntry()
};
ResourceMappingDesc ResMappingDesc;
ResMappingDesc.pEntries = ResMpEntries;
RefCntAutoPtr<IResourceMapping> pResMapping;
m_pRenderDevice->CreateResourceMapping(ResMappingDesc, &pResMapping);
//pVS->BindResources(m_pResourceMapping, 0);
IDeviceObject *ppSRVs[] = {m_pTextures[3]->GetDefaultView(TEXTURE_VIEW_SHADER_RESOURCE)};
pPS->BindResources(pResMapping, BIND_SHADER_RESOURCES_RESET_BINDINGS | BIND_SHADER_RESOURCES_UPDATE_UNRESOLVED);
pPS->GetShaderVariable("g_tex2DTest2")->SetArray( ppSRVs, 1, 1);
m_pSRB->BindResources(SHADER_TYPE_PIXEL, pResMapping, BIND_SHADER_RESOURCES_RESET_BINDINGS | BIND_SHADER_RESOURCES_UPDATE_UNRESOLVED);
ppSRVs[0] = m_pTextures[4]->GetDefaultView(TEXTURE_VIEW_SHADER_RESOURCE);
m_pSRB->GetVariable(SHADER_TYPE_PIXEL, "g_tex2DTest")->SetArray(ppSRVs, 3, 1);
}
void TestShaderResArrays::Draw()
{
m_pDeviceContext->SetPipelineState(m_pPSO);
IDeviceObject *ppSRVs[] = {m_pTextures[7]->GetDefaultView(TEXTURE_VIEW_SHADER_RESOURCE)};
m_pSRB->GetVariable(SHADER_TYPE_PIXEL, "g_tex2D")->SetArray(ppSRVs, 1, 1);
m_pDeviceContext->CommitShaderResources(m_pSRB, COMMIT_SHADER_RESOURCES_FLAG_TRANSITION_RESOURCES);
IBuffer *pBuffs[] = {m_pVertexBuff};
Uint32 Strides[] = {sizeof(float)*5};
Uint32 Offsets[] = {0};
m_pDeviceContext->SetVertexBuffers( 0, 1, pBuffs, Strides, Offsets, SET_VERTEX_BUFFERS_FLAG_RESET );
Diligent::DrawAttribs DrawAttrs;
DrawAttrs.Topology = Diligent::PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP;
DrawAttrs.NumVertices = 4; // Draw quad
m_pDeviceContext->Draw( DrawAttrs );
SetStatus(TestResult::Succeeded);
}
| 43.386598
| 183
| 0.717239
|
SCrusader
|
11b19b31835a9aec2bc44d789c934fade5af16eb
| 479
|
cpp
|
C++
|
examples/ex2_percolation.cpp
|
pvnuffel/test_repos
|
c0d957265608b15f216ece67363c827d01122102
|
[
"BSD-3-Clause"
] | null | null | null |
examples/ex2_percolation.cpp
|
pvnuffel/test_repos
|
c0d957265608b15f216ece67363c827d01122102
|
[
"BSD-3-Clause"
] | null | null | null |
examples/ex2_percolation.cpp
|
pvnuffel/test_repos
|
c0d957265608b15f216ece67363c827d01122102
|
[
"BSD-3-Clause"
] | null | null | null |
#include <Percolation_Sim.h>
int main() {
// Construct Network
Network net("name", Network::Undirected);
net.populate(10000);
net.erdos_renyi(5);
for (int i = 0; i < 100; i++){
// Choose and run simulation
Percolation_Sim sim(&net);
sim.set_transmissibility(0.25);
sim.rand_infect(10);
sim.run_simulation();
cout << sim.epidemic_size() << endl;
sim.reset();
}
return 0;
}
| 22.809524
| 49
| 0.546973
|
pvnuffel
|
11b2285a9e7fb8b2aa484c62bc5ccdb0db03fef1
| 863
|
cpp
|
C++
|
Editor/ParticleEditor/Engine/fcontroller.cpp
|
ixray-team/xray-vss-archive
|
b245c8601dcefb505b4b51f58142da6769d4dc92
|
[
"Linux-OpenIB"
] | 1
|
2022-03-26T17:00:19.000Z
|
2022-03-26T17:00:19.000Z
|
Editor/ActorEditor/Engine/fcontroller.cpp
|
ixray-team/xray-vss-archive
|
b245c8601dcefb505b4b51f58142da6769d4dc92
|
[
"Linux-OpenIB"
] | null | null | null |
Editor/ActorEditor/Engine/fcontroller.cpp
|
ixray-team/xray-vss-archive
|
b245c8601dcefb505b4b51f58142da6769d4dc92
|
[
"Linux-OpenIB"
] | 1
|
2022-03-26T17:00:21.000Z
|
2022-03-26T17:00:21.000Z
|
#include "stdafx.h"
#pragma hdrstop
#include "xr_input.h"
#include "fcontroller.h"
void CController::iCapture (void)
{
VERIFY(pInput);
pInput->iCapture(this);
}
void CController::iRelease (void)
{
VERIFY(pInput);
pInput->iRelease(this);
}
void CController::iGetLastMouseDelta (Ipoint& p)
{
VERIFY(pInput);
pInput->iGetLastMouseDelta( p );
}
void CController::OnInputDeactivate (void)
{
int i;
for (i = 0; i < COUNT_KB_BUTTONS; i++ )
OnKeyboardRelease( i );
for (i = 0; i < COUNT_MOUSE_BUTTONS; i++ )
OnMouseRelease( i );
OnMouseStop ( DIMOFS_X, 0 );
OnMouseStop ( DIMOFS_Y, 0 );
}
BOOL CController::iGetKeyState(int dik)
{
VERIFY(pInput);
return pInput->iGetAsyncKeyState(dik);
}
BOOL CController::iGetBtnState(int btn)
{
VERIFY(pInput);
return pInput->iGetAsyncBtnState(btn);
}
| 18.361702
| 51
| 0.659328
|
ixray-team
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.