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
sequencelengths 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
sequencelengths 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
sequencelengths 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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a5b236b6cb8db861e5fde0f54ae936edf0c32709 | 4,375 | hpp | C++ | experiments/util/benchmark_util.hpp | keszocze/abo | 2d59ac20832b308ef5f90744fc98752797a4f4ba | [
"MIT"
] | null | null | null | experiments/util/benchmark_util.hpp | keszocze/abo | 2d59ac20832b308ef5f90744fc98752797a4f4ba | [
"MIT"
] | null | null | null | experiments/util/benchmark_util.hpp | keszocze/abo | 2d59ac20832b308ef5f90744fc98752797a4f4ba | [
"MIT"
] | 1 | 2020-03-11T14:50:31.000Z | 2020-03-11T14:50:31.000Z | #ifndef BENCHMARK_UTIL_H
#define BENCHMARK_UTIL_H
#include <cudd/cplusplus/cuddObj.hh>
#include <string>
#include <vector>
namespace abo::benchmark {
enum class ErrorMetric
{
WORST_CASE,
WORST_CASE_RELATIVE_APPROX,
WORST_CASE_RELATIVE_BINARY_SEARCH,
WORST_CASE_RELATIVE_RANDOMIZED,
WORST_CASE_RELATIVE_ADD,
WORST_CASE_RELATIVE_SYMBOLIC,
APPROXIMATE_WORST_CASE_5,
AVERAGE_CASE,
AVERAGE_RELATIVE_APPROX,
AVERAGE_RELATIVE_ADD,
MEAN_SQUARED,
ERROR_RATE,
AVERAGE_BIT_FLIP,
WORST_CASE_BIT_FLIP,
};
/**
* Returns a human readable string containing the name of the error metric that is given as the enum
*/
std::string error_metric_name(ErrorMetric metric);
/**
* @brief Computes the error metric for the given functions
* @param mgr The BDD object manager
* @param original The original function. As most metrics are symmetric, it can be swapped with the
* approximated function for them. The only exceptions are the average case relative and worst case
* relative error
* @param approx The approximated function. Must be an unsigned integer.
* @param metric The metric to evaluate
* @return The metric value. For the approximate metrics, it is the average between the lower and
* upper bound on the error
*/
double compute_error_metric(const Cudd& mgr, const std::vector<BDD>& original,
const std::vector<BDD>& approx, ErrorMetric metric);
/**
* @brief Collection of all supported ISCAS'85 benchmark files for easy access
*/
enum class ISCAS85File
{
// the numbering is done by hand to ensure that we can use this as array index
C17 = 0,
C432 = 1,
C499 = 2,
C880 = 3,
C1355 = 4,
C1908 = 5,
C2670 = 6,
C3540 = 7,
C5315 = 8,
C6288 = 9,
C7552 = 10
};
/**
* Returns the filename of the iscas'85 file identified the the enum input
*/
std::string iscas_85_filename_by_id(ISCAS85File file);
/*
* Returns the full path of the iscas'85 benchmark
*/
std::string iscas_85_filepath_by_id(ISCAS85File file);
/**
* @brief Loads an iscas 85 benchmark and returns it as a BDD vector
* @param mgr The BDD object manager
* @param file The file to load
* @return The iscas 85 benchmark
*/
std::vector<BDD> load_iscas_85_file(Cudd& mgr, ISCAS85File file);
/**
* @brief Collection of all supported EPFL benchmark files for easy access
*/
enum class EPFLFile
{
// the numbering is done by hand to ensure that we can use this as array index
Adder = 0,
Bar = 1,
Div = 2,
Hyp = 3,
Log2 = 4,
Max = 5,
Mul = 6,
Sin = 7,
Sqrt = 8,
Square = 9
};
/**
* Returns the filename of the EPFL file identified the the enum input
*/
std::string epfl_filename_by_id(EPFLFile file);
/*
* Returns the full path of the EPFL benchmark
*/
std::string epfl_filepath_by_id(EPFLFile file);
std::vector<BDD> load_epfl_benchmark_file(Cudd& mgr, EPFLFile file);
enum class ApproximateAdder
{
ACA1,
ACA2,
GDA,
GEAR
};
/**
* @brief Returns a shorthand form of the name of the approximate adder and its exact configuration
* @param adder The adder to use
* @param bits The number of bits the adder should have
* @param par1 The first parameter of the approximate adder. This has different meanings for
* different adders
* @param par2 (optional) The second parameter of the approximate adder. This has different meanings
* for different adders
* @return A string containing the name of the configuration
*/
std::string approximate_adder_name(ApproximateAdder adder, std::size_t bits, std::size_t par1,
std::size_t par2 = 0);
/**
* @brief Creates the approximate adder specified by the parameters
* @param mgr The BDD object manager
* @param adder The approximate adder type to create
* @param bits The number of bits the adder should have
* @param par1 The first parameter of the approximate adder. This has different meanings for
* different adders
* @param par2 par2 (optional) The second parameter of the approximate adder. This has different
* meanings for different adders
* @return The approximate adder
*/
std::vector<BDD> get_approximate_adder(Cudd& mgr, ApproximateAdder adder, std::size_t bits,
std::size_t par1, std::size_t par2 = 0);
} // namespace abo::benchmark
#endif // BENCHMARK_UTIL_H
| 28.782895 | 100 | 0.709257 | keszocze |
a5b3bfd9a2e0f91548f241f2dfab0c95df20e437 | 615 | cpp | C++ | DearPyGui/src/ui/AppItems/widget_handlers/mvToggledOpenHandler.cpp | BadSugar/DearPyGui | 95f3f86e2efb7fbe31d76c52a1a7965d96ee9151 | [
"MIT"
] | 7,471 | 2020-08-12T13:36:38.000Z | 2022-03-31T14:50:37.000Z | DearPyGui/src/ui/AppItems/widget_handlers/mvToggledOpenHandler.cpp | BadSugar/DearPyGui | 95f3f86e2efb7fbe31d76c52a1a7965d96ee9151 | [
"MIT"
] | 922 | 2020-08-12T21:03:42.000Z | 2022-03-31T01:19:10.000Z | DearPyGui/src/ui/AppItems/widget_handlers/mvToggledOpenHandler.cpp | BadSugar/DearPyGui | 95f3f86e2efb7fbe31d76c52a1a7965d96ee9151 | [
"MIT"
] | 550 | 2020-08-12T21:58:55.000Z | 2022-03-30T09:09:58.000Z | #include "mvToggledOpenHandler.h"
#include "mvLog.h"
#include "mvItemRegistry.h"
#include "mvPythonExceptions.h"
#include "mvUtilities.h"
namespace Marvel {
mvToggledOpenHandler::mvToggledOpenHandler(mvUUID uuid)
:
mvAppItem(uuid)
{
}
void mvToggledOpenHandler::customAction(void* data)
{
if (static_cast<mvAppItemState*>(data)->toggledOpen)
{
mvSubmitCallback([=]()
{
if(config.alias.empty())
mvRunCallback(getCallback(false), uuid, GetPyNone(), config.user_data);
else
mvRunCallback(getCallback(false), config.alias, GetPyNone(), config.user_data);
});
}
}
} | 19.83871 | 85 | 0.700813 | BadSugar |
a5b5f6c80e4282aaa7efc01261996209d533ca83 | 10 | cpp | C++ | greedy-algorithms/basic-principles/tempCodeRunnerFile.cpp | dushimsam/deep-dive-in-algorithms | 0c6a04b3115ba789ab4aca68cce51c9a3c3a075a | [
"MIT"
] | null | null | null | greedy-algorithms/basic-principles/tempCodeRunnerFile.cpp | dushimsam/deep-dive-in-algorithms | 0c6a04b3115ba789ab4aca68cce51c9a3c3a075a | [
"MIT"
] | null | null | null | greedy-algorithms/basic-principles/tempCodeRunnerFile.cpp | dushimsam/deep-dive-in-algorithms | 0c6a04b3115ba789ab4aca68cce51c9a3c3a075a | [
"MIT"
] | null | null | null | int min(){ | 10 | 10 | 0.6 | dushimsam |
a5b6f00b1d7d88b4738a8210393a59c3b0c44b3a | 7,048 | cpp | C++ | tests/unit/SummaryBuilder.cpp | keithmendozasr/mimeographer | 84a2b99b27830b8679d4f35f8cc913bf69be842a | [
"Apache-2.0"
] | 1 | 2021-05-01T14:49:09.000Z | 2021-05-01T14:49:09.000Z | tests/unit/SummaryBuilder.cpp | keithmendozasr/mimeographer | 84a2b99b27830b8679d4f35f8cc913bf69be842a | [
"Apache-2.0"
] | null | null | null | tests/unit/SummaryBuilder.cpp | keithmendozasr/mimeographer | 84a2b99b27830b8679d4f35f8cc913bf69be842a | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2017 Keith Mendoza
*
* 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 <functional>
#include "SummaryBuilder.h"
#include "gtest/gtest.h"
using namespace std;
namespace mimeographer
{
TEST(SummaryBuilderTest, buildTitleClean)
{
string expectText = "Test Title";
string markdown = "# " + expectText;
unique_ptr<cmark_node, function<void(cmark_node*)>> rootNode(
cmark_parse_document(markdown.c_str(), markdown.size(),
CMARK_OPT_DEFAULT),
[](cmark_node *node)
{
if(node)
cmark_node_free(node);
}
);
SummaryBuilder obj;
obj.iterator = move(
shared_ptr<cmark_iter>(cmark_iter_new(rootNode.get()),
[](cmark_iter *iter)
{
if(iter)
cmark_iter_free(iter);
}
));
EXPECT_EQ(cmark_iter_next(obj.iterator.get()), CMARK_EVENT_ENTER);
EXPECT_NO_THROW({
obj.buildTitle();
EXPECT_EQ(obj.title, expectText);
});
}
TEST(SummaryBuilderTest, buildTitleWithInlines)
{
string expectText = "Test Title with inlines and link";
string markdown =
"# Test Title *with* **inlines** [and link](/randomspot)";
unique_ptr<cmark_node, function<void(cmark_node*)>> rootNode(
cmark_parse_document(markdown.c_str(), markdown.size(),
CMARK_OPT_DEFAULT),
[](cmark_node *node)
{
if(node)
cmark_node_free(node);
}
);
SummaryBuilder obj;
obj.iterator = move(
shared_ptr<cmark_iter>(cmark_iter_new(rootNode.get()),
[](cmark_iter *iter)
{
if(iter)
cmark_iter_free(iter);
}
));
EXPECT_EQ(cmark_iter_next(obj.iterator.get()), CMARK_EVENT_ENTER);
EXPECT_NO_THROW({
obj.buildTitle();
EXPECT_EQ(obj.title, expectText);
});
}
TEST(SummaryBuilderTest, buildPreviewClean)
{
string expectedText =
"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis pulvinar"
"pellentesque fringilla. Vestibulum ante ipsum primis in faucibus orci "
"luctus et ultrices posuere cubilia Curae; Nunc maximus augue magna, ve"
"l euismod purus efficitur eu. Nunc massa nunc.";
unique_ptr<cmark_node, function<void(cmark_node*)>> rootNode(
cmark_parse_document(expectedText.c_str(), expectedText.size(),
CMARK_OPT_DEFAULT),
[](cmark_node *node)
{
if(node)
cmark_node_free(node);
}
);
SummaryBuilder obj;
obj.iterator = move(
shared_ptr<cmark_iter>(cmark_iter_new(rootNode.get()),
[](cmark_iter *iter)
{
if(iter)
cmark_iter_free(iter);
}
));
EXPECT_EQ(cmark_iter_next(obj.iterator.get()), CMARK_EVENT_ENTER);
EXPECT_NO_THROW({
obj.buildPreview();
EXPECT_EQ(obj.preview, expectedText);
});
}
TEST(SummaryBuilderTest, buildPreviewWithInlines)
{
string markdown =
"Lorem ipsum dolor,  consectetur "
"**adipiscing elit**. Duis pulvinar *pellentesque* fringilla. Vestibulum "
"ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia "
"Curae; Nunc maximus augue magna, vel euismod purus efficitur eu. Nunc "
"massa nunc.\n\n"
"Fusce egestas sem ac metus mollis egestas. Donec ultrices turpis sed ex aliquam";
string expectText =
"Lorem ipsum dolor, random image consectetur adipiscing elit. Duis pulvinar pellen"
"tesque fringilla. Vestibulum ante ipsum primis in faucibus orci luctu"
"s et ultrices posuere cubilia Curae; Nunc maximus augue magna, vel eu"
"ismod purus efficitur eu. Nunc massa ";
unique_ptr<cmark_node, function<void(cmark_node*)>> rootNode(
cmark_parse_document(markdown.c_str(), markdown.size(),
CMARK_OPT_DEFAULT),
[](cmark_node *node)
{
if(node)
cmark_node_free(node);
}
);
SummaryBuilder obj;
obj.iterator = move(
shared_ptr<cmark_iter>(cmark_iter_new(rootNode.get()),
[](cmark_iter *iter)
{
if(iter)
cmark_iter_free(iter);
}
));
EXPECT_EQ(cmark_iter_next(obj.iterator.get()), CMARK_EVENT_ENTER);
EXPECT_NO_THROW({
obj.buildPreview();
EXPECT_EQ(obj.preview, expectText);
});
}
TEST(SummaryBuilderTest, build)
{
string markdown =
"# Test Title\n"
"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur vi"
"tae dictum sem. Cras a lorem sed felis dictum elementum eu vel risus."
" Donec pretium lobortis pulvinar. Donec eu sodales mi. Aenean id elem"
"entum ante. Nam id urna hendrerit, mattis neque ut, faucibus purus. N"
"am scelerisque vulputate blandit. Proin euismod viverra mollis. Donec"
"auctor porta libero, in mollis enim vulputate eu. Sed rutrum mollis u"
"rna nec facilisis. Aliquam vel neque posuere, vestibulum tellus id, b"
"landit leo.\n\n"
"Fusce egestas sem ac metus mollis egestas. Donec ultrices turpis sed "
"ex aliquam, sed porttitor lectus porttitor. Integer pellentesque tris"
"tique dolor, a tincidunt nisl rhoncus sit amet. Donec at risus quam. "
"Proin vehicula nibh vel quam viverra bibendum. Proin eu libero sem. P"
"roin ultricies neque nec leo convallis dignissim. Vestibulum sagittis"
" neque dui, sit amet eleifend purus mattis vitae. Sed fermentum enim "
"ligula, in cursus nisl semper non. Aenean a pulvinar purus, sit amet "
"malesuada ante. In sed euismod lorem. Maecenas scelerisque bibendum n"
"isi, vitae condimentum arcu viverra id. Integer augue est, molestie q"
"uis semper lobortis, consequat eget quam.";
string expectedTitle = "Test Title";
string expectedPreview =
"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur vi"
"tae dictum sem. Cras a lorem sed felis dictum elementum eu vel risus."
" Donec pretium lobortis pulvinar. Donec eu sodales mi. Aenean id elem"
"entum ante. Nam id urna hendrerit, mattis neque u";
SummaryBuilder obj;
EXPECT_NO_THROW({
obj.build(markdown);
EXPECT_EQ(obj.getTitle(), expectedTitle);
EXPECT_EQ(obj.getPreview(), expectedPreview);
});
}
} // namespace
| 33.722488 | 94 | 0.644296 | keithmendozasr |
a5bf5522e582265fcf94446cc08e82e5bceec868 | 4,397 | cpp | C++ | Mirror/event.cpp | Maxul/sgx_vmx_protocol | b18dcdd6cbbf10c7d609649295676f0163dd9a5e | [
"MIT"
] | null | null | null | Mirror/event.cpp | Maxul/sgx_vmx_protocol | b18dcdd6cbbf10c7d609649295676f0163dd9a5e | [
"MIT"
] | null | null | null | Mirror/event.cpp | Maxul/sgx_vmx_protocol | b18dcdd6cbbf10c7d609649295676f0163dd9a5e | [
"MIT"
] | null | null | null | /*
* event.cpp
* This file is part of SVMOS
*
* Copyright (C) 2017 - Ecular, Maxul
*
* VmOs is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* VmOs 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 VmOs. If not, see <http://www.gnu.org/licenses/>.
*/
#include "svmos.h"
static void input_event_enqueue(Item item) {
pthread_mutex_lock(&mutex_queue);
event_queue.push_back(item);
pthread_mutex_unlock(&mutex_queue);
}
void *input_event_queue(void *arg) {
XEvent host_event;
Time last_move_time = 0;
Item item;
Display *dpy_wnd = ((struct event_arg *)(arg))->dpy;
Node *find_result;
pthread_mutex_lock(&mutex_link);
item.source_wid = getGuestID(((struct event_arg *)(arg))->wnd);
pthread_mutex_unlock(&mutex_link);
for (;;) {
XNextEvent(dpy_wnd, &host_event);
switch (host_event.type) {
case ButtonPress: // code 0
item.x = host_event.xbutton.x - color_border;
item.y = host_event.xbutton.y - color_border;
item.button = host_event.xbutton.button;
item.event_type = '0';
input_event_enqueue(item);
break;
case ButtonRelease: // code 2
item.x = host_event.xbutton.x - color_border;
item.y = host_event.xbutton.y - color_border;
item.button = host_event.xbutton.button;
item.event_type = '2';
input_event_enqueue(item);
break;
case MotionNotify: // code 1
/* 控制传输频率 */
if (host_event.xbutton.time - last_move_time >= 120) {
item.x = host_event.xbutton.x;
item.y = host_event.xbutton.y;
item.event_type = '1';
input_event_enqueue(item);
last_move_time = host_event.xbutton.time;
}
break;
case KeyPress: // code 3
item.x = host_event.xbutton.x - color_border;
item.y = host_event.xbutton.y - color_border;
item.button = host_event.xkey.keycode;
item.event_type = '3';
input_event_enqueue(item);
// printf("press %d\n", item.button);
break;
case KeyRelease: // code 4
item.x = host_event.xbutton.x - color_border;
item.y = host_event.xbutton.y - color_border;
item.button = host_event.xkey.keycode;
item.event_type = '4';
input_event_enqueue(item);
break;
/* windows resize */
case ConfigureNotify: // code 5
#if 0
pthread_mutex_lock(&mutex_link);
find_result = FindNodeBySwinValue(head, host_event.xconfigure.window);
if (find_result == NULL) {
printf("swid=0x%lx. not find Node!\n", host_event.xconfigure.window);
pthread_mutex_unlock(&mutex_link);
goto input_event_exit;
}
/* only in this case it's called "RESIZE" */
if (host_event.xconfigure.width - color_border * 2 !=
find_result->width ||
host_event.xconfigure.height - color_border * 2 !=
find_result->height) {
item.x = host_event.xconfigure.width - color_border * 2;
item.y = host_event.xconfigure.height - color_border * 2;
item.event_type = '5';
input_event_enqueue(item);
find_result->width = item.x;
find_result->height = item.y;
find_result->resize = 1;
}
pthread_mutex_unlock(&mutex_link);
#endif
break;
/* window close */
case ClientMessage: // code 6
item.x = 0;
item.y = 0;
item.button = 0;
item.event_type = '6';
input_event_enqueue(item);
break;
case Expose: // code 7
if (host_event.xexpose.count != 0)
break;
item.x = 0;
item.y = 0;
item.button = 0;
item.event_type = '7';
input_event_enqueue(item);
break;
case DestroyNotify:
goto input_event_exit;
default:
// printf("event %d\n", host_event.type);
break;
}
/* MUST KNOW: We'd better not sleep or miss the hit */
}
input_event_exit:
free(arg);
return NULL;
}
| 24.292818 | 77 | 0.634069 | Maxul |
a5c5a1dab21e48bf25ebd79c6dfe1a7301bca52c | 226 | hpp | C++ | examples/05_with_textureManager_and_gameObject/TextureManager.hpp | nathandaven/sdl-vscode-template | 098125e250ede58eeaa6cd06738d76c2983cdb58 | [
"MIT"
] | null | null | null | examples/05_with_textureManager_and_gameObject/TextureManager.hpp | nathandaven/sdl-vscode-template | 098125e250ede58eeaa6cd06738d76c2983cdb58 | [
"MIT"
] | null | null | null | examples/05_with_textureManager_and_gameObject/TextureManager.hpp | nathandaven/sdl-vscode-template | 098125e250ede58eeaa6cd06738d76c2983cdb58 | [
"MIT"
] | null | null | null | #ifndef TextureManager_hpp
#define TextureManager_hpp
#include "Game.hpp"
class TextureManager
{
public:
static SDL_Texture *LoadTexture(const char *textureFile, SDL_Renderer *renderer);
};
#endif /* TextureManager_hpp */ | 18.833333 | 83 | 0.787611 | nathandaven |
a5cb7df08d1faf5661ca2d65b58cc93300724f23 | 2,150 | cpp | C++ | tests/DataHelpers.cpp | michaelwillis/sfizz | 0461f6e5e288da71aeccf7b7dfd71302bf0ba175 | [
"BSD-2-Clause"
] | 281 | 2019-06-06T05:58:59.000Z | 2022-03-06T12:20:09.000Z | tests/DataHelpers.cpp | michaelwillis/sfizz | 0461f6e5e288da71aeccf7b7dfd71302bf0ba175 | [
"BSD-2-Clause"
] | 590 | 2019-09-22T00:26:10.000Z | 2022-03-31T19:21:58.000Z | tests/DataHelpers.cpp | michaelwillis/sfizz | 0461f6e5e288da71aeccf7b7dfd71302bf0ba175 | [
"BSD-2-Clause"
] | 44 | 2019-10-08T08:24:20.000Z | 2022-02-26T04:21:44.000Z | // SPDX-License-Identifier: BSD-2-Clause
// This code is part of the sfizz library and is licensed under a BSD 2-clause
// license. You should have receive a LICENSE.md file along with the code.
// If not, contact the sfizz maintainers at https://github.com/sfztools/sfizz
#include "DataHelpers.h"
#include <string>
#include <vector>
#include <iostream>
#include <sstream>
#include <cstring>
#include <fstream>
void load_txt(DataPoints& dp, std::istream& in)
{
struct RawValue {
bool rowJump;
float value;
};
std::vector<RawValue> raw;
raw.reserve(1024);
// read raw value data
{
std::string line;
line.reserve(256);
while (std::getline(in, line)) {
size_t commentPos = line.find('#');
if (commentPos == line.npos)
line = line.substr(0, commentPos);
std::istringstream lineIn(line);
RawValue rv;
rv.rowJump = true;
while (lineIn >> rv.value) {
raw.push_back(rv);
rv.rowJump = false;
}
}
}
if (raw.empty()) {
dp.rows = 0;
dp.cols = 0;
dp.data.reset();
return;
}
// count rows and columns
size_t numRows = 0;
size_t numCols = 0;
{
size_t c = 0;
for (const RawValue& rv : raw) {
if (!rv.rowJump)
++c;
else {
numRows += c != 0;
c = 1;
}
numCols = std::max(numCols, c);
}
numRows += c != 0;
}
// fill the data
float* data = new float[numRows * numCols];
dp.rows = numRows;
dp.cols = numCols;
dp.data.reset(data);
for (size_t i = 0, j = 0; i < numRows * numCols; ) {
size_t c = 1;
data[i++] = raw[j++].value;
for (; j < raw.size() && !raw[j].rowJump; ++c)
data[i++] = raw[j++].value;
for ( ; c < numCols; ++c)
data[i++] = 0.0f;
}
}
bool load_txt_file(DataPoints& dp, const fs::path& path)
{
fs::ifstream in(path);
load_txt(dp, in);
return !in.bad();
}
| 23.626374 | 78 | 0.506977 | michaelwillis |
a5cf9abc34ce8a74718244dfcdc33bf6f4554973 | 281 | cpp | C++ | OJ/PT/PT23.cpp | doan201203/truong_doan | 68350b7a24ea266320cd41e1a4878e8a58b3f707 | [
"Apache-2.0"
] | null | null | null | OJ/PT/PT23.cpp | doan201203/truong_doan | 68350b7a24ea266320cd41e1a4878e8a58b3f707 | [
"Apache-2.0"
] | null | null | null | OJ/PT/PT23.cpp | doan201203/truong_doan | 68350b7a24ea266320cd41e1a4878e8a58b3f707 | [
"Apache-2.0"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
#define ll long long
int main(){
int n;
cin>>n;
for(int i =1 ; i<= n ; i++){
int le = 1 , chan = 0;
for(int j = i-1 ; j >= 0 ; j--){
if(j%2 ==0){
cout<<le;
}else{
cout<<chan;
}
}cout<<"\n";
}
} | 16.529412 | 37 | 0.448399 | doan201203 |
a5d1707ea6bea6172e65ca2ecb1fe489760f3d30 | 8,011 | cpp | C++ | msj_archives/code/MSJApr97.src/MSN Case Study/container/events.cpp | sarangbaheti/misc-code | d47a8d1cc41f19701ce628c9f15976bb5baa239d | [
"Unlicense"
] | 1 | 2020-10-22T12:58:55.000Z | 2020-10-22T12:58:55.000Z | msj_archives/code/MSJApr97.src/MSN Case Study/container/events.cpp | sarangbaheti/misc-code | d47a8d1cc41f19701ce628c9f15976bb5baa239d | [
"Unlicense"
] | null | null | null | msj_archives/code/MSJApr97.src/MSN Case Study/container/events.cpp | sarangbaheti/misc-code | d47a8d1cc41f19701ce628c9f15976bb5baa239d | [
"Unlicense"
] | 2 | 2020-10-19T23:36:26.000Z | 2020-10-22T12:59:37.000Z | #define STRICT
#include <windows.h>
#include <windowsx.h>
#include <crtdbg.h>
#include <olectl.h>
#include <docobj.h>
#include <servprov.h>
#include <exdisp.h>
#include <exdispid.h>
#include "winmain.h"
#include "events.h"
#include "ctr.h"
//+---------------------------------------------------------------------------
//
// Member: CEventMap::~CEventMap
//
// Synopsis: unhooks the event sink from the WebBrowser OC.
//
//----------------------------------------------------------------------------
CEventMap::~CEventMap(VOID)
{
UnhookEvents();
}
//+---------------------------------------------------------------------------
//
// Member: CEventMap::UnhookEvents
//
// Synopsis: plumbing to unhook us from event source.
//
//----------------------------------------------------------------------------
VOID
CEventMap::UnhookEvents(VOID)
{
if (m_pConnPt)
{
m_pConnPt->Unadvise(m_dwCookie);
m_pConnPt->Release();
m_pConnPt = 0;
}
}
//+---------------------------------------------------------------------------
//
// Member: CEventMap::GetEventsFromCtrl
//
// Synopsis: Loads the typelib, gets the typeinfo for the eventset,
// and uses IConnectionPointContainer protocol for hooking
// up our implementation of IDispatch so it gets called
// when events are fired.
//
// Arguments: [pOleCtl] -- the WebBrowser OC.
//
// Returns: HRESULT
//
//----------------------------------------------------------------------------
HRESULT
CEventMap::GetEventsFromCtrl(LPOLECONTROL pOleCtl)
{
HRESULT hr;
LPCONNECTIONPOINTCONTAINER pConnCtr = 0;
_ASSERTE(pOleCtl);
// HOOKING UP EVENTS - let's get find the connection point and
// set up the connection for events to be fired.
hr = pOleCtl->QueryInterface(
IID_IConnectionPointContainer,
(LPVOID *) &pConnCtr);
if (hr)
goto Cleanup;
// find the connectionpoint for us to hook up event sink
hr = pConnCtr->FindConnectionPoint(DIID_DWebBrowserEvents, &m_pConnPt);
if (hr)
goto Cleanup;
// hook up the event sink
hr = m_pConnPt->Advise((LPUNKNOWN) this, &m_dwCookie);
if (hr)
goto Cleanup;
// if we got this far, we should be receiving events now.
Cleanup:
if (pConnCtr)
pConnCtr->Release();
return hr;
}
//+---------------------------------------------------------------------------
//
// Member: CEventMap::Invoke
//
// Synopsis: This is our mondo event set handler, the thing the
// WebBrowser OC calls when it fires an event.
//
// Arguments: standard IDispatch args per-spec.
//
// Returns: HRESULT - currently, all the members return S_OK
// no matter what - probably the right thing to do in
// an event handler.
//
//----------------------------------------------------------------------------
STDMETHODIMP
CEventMap::Invoke(
DISPID dispidMember,
REFIID riid,
LCID lcid,
WORD wFlags,
DISPPARAMS FAR * pdispparams,
VARIANT FAR * pvarResult,
EXCEPINFO FAR * pexcepinfo,
UINT FAR * puArgErr)
{
switch (dispidMember)
{
case DISPID_BEFORENAVIGATE:
{
return _OnBeginNavigate(pdispparams, puArgErr);
break;
}
case DISPID_NAVIGATECOMPLETE:
{
return _OnNavigate(pdispparams, puArgErr);
break;
}
case DISPID_STATUSTEXTCHANGE:
{
return _OnStatusTextChange(pdispparams, puArgErr);
break;
}
case DISPID_PROGRESSCHANGE:
{
return _OnProgress(pdispparams, puArgErr);
break;
}
case DISPID_DOWNLOADCOMPLETE:
{
return m_pCtr->OnDownloadComplete();
break;
}
case DISPID_COMMANDSTATECHANGE:
{
return _OnCommandStateChange(pdispparams, puArgErr);
break;
}
case DISPID_DOWNLOADBEGIN:
{
return m_pCtr->OnDownloadBegin();
break;
}
case DISPID_NEWWINDOW:
{
return m_pCtr->OnNewWindow();
break;
}
case DISPID_QUIT:
{
return m_pCtr->OnQuit();
break;
}
default:
return S_OK;
break;
}
}
//+---------------------------------------------------------------------------
//
// Member: CEventMap::_OnBeginNavigate
//
// Synopsis: a little wrapper to get the argument passing
// code out of the Invoke() above. It extracts args
// and calls CMSJOCCtr::OnBeginNavigate().
//
// Arguments: [pDP] -- pointer to argument block
// [puArgErr] -- on DispGetParam error, returns index to
// argument that caused the error.
//
// Returns: HRESULT
//
//----------------------------------------------------------------------------
HRESULT
CEventMap::_OnBeginNavigate(DISPPARAMS * pDP, PUINT puArgErr)
{
VARIANT varURL;
HRESULT hr;
::VariantInit(&varURL);
hr = ::DispGetParam(pDP, 0, VT_BSTR, &varURL, puArgErr);
if (hr)
return hr;
hr = m_pCtr->OnBeginNavigate(V_BSTR(&varURL));
::VariantClear(&varURL);
return hr;
}
//+---------------------------------------------------------------------------
//
// Member: CEventMap::_OnBeginNavigate
//
// Synopsis: a little wrapper to get the argument passing
// code out of the Invoke() above. It extracts args
// and calls CMSJOCCtr::OnNavigate().
//
// Arguments: [pDP] -- pointer to argument block
// [puArgErr] -- on DispGetParam error, returns index to
// argument that caused the error.
//
// Returns: HRESULT
//
//----------------------------------------------------------------------------
HRESULT
CEventMap::_OnNavigate(DISPPARAMS * pDP, PUINT puArgErr)
{
// ByVal URL As String, ByVal Flags As Long,
// ByVal TargetFrameName As String,
// PostData As Variant, ByVal Headers As String,
// ByVal Referrer As String
VARIANT varURL;
HRESULT hr;
::VariantInit(&varURL);
hr = ::DispGetParam(pDP, 0, VT_BSTR, &varURL, puArgErr);
if (hr)
return hr;
hr = m_pCtr->OnNavigate(V_BSTR(&varURL));
::VariantClear(&varURL);
return hr;
}
//+---------------------------------------------------------------------------
//
// Member: CEventMap::_OnCommandStateChange
//
// Synopsis: lets us determine whether and how to update the navbar
//
// Arguments: [pDP] -- args
// [puArgErr] -- err index returned from DispGetParam
//
// Returns: HRESULT
//
//----------------------------------------------------------------------------
HRESULT
CEventMap::_OnCommandStateChange(DISPPARAMS * pDP, PUINT puArgErr)
{
HRESULT hr;
VARIANT varlValue;
VARIANT varfEnable;
// get the arguments.
// this init is necessary for DispGetParam
::VariantInit(&varlValue);
::VariantInit(&varfEnable);
hr = ::DispGetParam(pDP, 1, VT_BOOL, &varfEnable, puArgErr);
if (hr)
return hr;
hr = ::DispGetParam(pDP, 0, VT_I4, &varlValue, puArgErr);
if (hr)
return hr;
// pass them to the container
return m_pCtr->OnCommandStateChange(V_BOOL(&varfEnable), V_I4(&varlValue));
}
HRESULT
CEventMap::_OnStatusTextChange(DISPPARAMS * pDP, PUINT puArgErr)
{
_ASSERTE(pDP);
if (pDP->cArgs != 1 || VT_BSTR != V_VT(&pDP->rgvarg[0]))
{
puArgErr = 0; // zeroth arg had the error.
return DISP_E_PARAMNOTFOUND; // we didn't find the arg we expected.
}
return m_pCtr->OnStatusTextChange(V_BSTR(&pDP->rgvarg[0]));
}
HRESULT
CEventMap::_OnProgress(DISPPARAMS * pDP, PUINT puArgErr)
{
_ASSERTE(V_VT(&pDP->rgvarg[0]) == VT_I4);
_ASSERTE(V_VT(&pDP->rgvarg[1]) == VT_I4);
return m_pCtr->OnProgress(V_I4(&pDP->rgvarg[1]), V_I4(&pDP->rgvarg[0]));
}
| 25.676282 | 79 | 0.524154 | sarangbaheti |
a5d862c6542161b62284ad873485e857d51b4428 | 280 | cpp | C++ | Kreator/implementation/GUI/ImguiBuild.cpp | ashish1009/Kreator | 68ff5073faef22ade314772a5127dd1cc98060b7 | [
"Apache-2.0"
] | null | null | null | Kreator/implementation/GUI/ImguiBuild.cpp | ashish1009/Kreator | 68ff5073faef22ade314772a5127dd1cc98060b7 | [
"Apache-2.0"
] | null | null | null | Kreator/implementation/GUI/ImguiBuild.cpp | ashish1009/Kreator | 68ff5073faef22ade314772a5127dd1cc98060b7 | [
"Apache-2.0"
] | null | null | null | //
// ImguiBuild.cpp
// Kreator
//
// Created by iKan on 10/04/22.
//
/// Include the Imgui example .cpp files for implementation of Imgui functionality
#define IMGUI_IMPL_OPENGL_LOADER_GLAD
#include <examples/imgui_impl_opengl3.cpp>
#include <examples/imgui_impl_glfw.cpp>
| 20 | 82 | 0.757143 | ashish1009 |
a5da5baa671dd355d2e84acfa11c54bd792d1e61 | 302 | cpp | C++ | mod.cpp | Soliders-in-Arms-Arma-3-Group/-SIA-Additional-Factions-V2 | 3631a42eb51e7296d8da40b9b9d088c03ba29dca | [
"MIT"
] | null | null | null | mod.cpp | Soliders-in-Arms-Arma-3-Group/-SIA-Additional-Factions-V2 | 3631a42eb51e7296d8da40b9b9d088c03ba29dca | [
"MIT"
] | 5 | 2022-01-23T01:26:54.000Z | 2022-03-07T21:54:25.000Z | mod.cpp | Soliders-in-Arms-Arma-3-Group/-SIA-Additional-Factions-V2 | 3631a42eb51e7296d8da40b9b9d088c03ba29dca | [
"MIT"
] | null | null | null | name = "SIA Additional Factions v2 (DEV)";
author = "Solders in Arms";
picture = "picture.paa";
logoSmall = "LogoSmall.paa";
logo = "Logo.paa";
logoOver = "LogoOver.paa";
action = "https://github.com/Soliders-in-Arms-Arma-3-Group/SIA-Additional-Factions-V2.git";
overview = "Adds additional factions."; | 37.75 | 91 | 0.718543 | Soliders-in-Arms-Arma-3-Group |
777c4dd8526447fc554e07d6a8d0984956084ba7 | 2,878 | hpp | C++ | csf_workspace/ec/src/device_io/ec_device_io/hi/conf/hisys_conf.hpp | Kitty-Kitty/csf_library | 011e56fb8b687818d20b9998a0cdb72332375534 | [
"BSD-2-Clause"
] | 2 | 2019-12-17T13:16:48.000Z | 2019-12-17T13:16:51.000Z | csf_workspace/ec/src/device_io/ec_device_io/hi/conf/hisys_conf.hpp | Kitty-Kitty/csf_library | 011e56fb8b687818d20b9998a0cdb72332375534 | [
"BSD-2-Clause"
] | null | null | null | csf_workspace/ec/src/device_io/ec_device_io/hi/conf/hisys_conf.hpp | Kitty-Kitty/csf_library | 011e56fb8b687818d20b9998a0cdb72332375534 | [
"BSD-2-Clause"
] | null | null | null | /*******************************************************************************
*
*Copyright: [email protected]
*
*Author: f
*
*File name: hisys_conf.hpp
*
*Version: 1.0
*
*Date: 03-12月-2019 13:31:48
*
*Description: Class(hisys_conf) 表示海思系统配置信息
*
*Others:
*
*History:
*
*******************************************************************************/
#if !defined(HISYS_CONF_H_INCLUDED_)
#define HISYS_CONF_H_INCLUDED_
#include <iostream>
#include <map>
namespace ec
{
namespace core
{
/**
* 表示海思系统配置信息
* @author f
* @version 1.0
* @created 03-12月-2019 13:31:48
*/
class hisys_conf
{
public:
/**
* 平台的功耗场景类型
* @author f
* @version 1.0
* @updated 05-12月-2019 10:27:05
*/
enum hiprofile_type
{
/**
* 表示未知的功耗场景类型
*/
hiprofile_type_none = 0x00,
/**
* 表示1080p@30的功耗场景类型
*/
hiprofile_type_1080p_30 = 0x01,
/**
* 表示1080p@60的功耗场景类型
*/
hiprofile_type_1080p_60 = 0x02,
/**
* 表示3m@30的功耗场景类型
*/
hiprofile_type_3m_30 = 0x03,
/**
* 表示5m@30的功耗场景类型
*/
hiprofile_type_5m_30 = 0x04
};
public:
hisys_conf();
virtual ~hisys_conf();
/**
* 表示系统内存的对齐方式
*/
inline int get_align_width() {
return m_align_width;
}
/**
* 表示系统内存的对齐方式
*
* @param newVal
*/
inline void set_align_width(int newVal) {
m_align_width = newVal;
}
/**
* 最大内存池数量
*/
inline int get_max_pool_count() {
return m_max_pool_count;
}
/**
* 最大内存池数量
*
* @param newVal
*/
inline void set_max_pool_count(int newVal) {
m_max_pool_count = newVal;
}
/**
* 表示硬件平台的功耗场景类型
*/
inline std::string get_profile() {
return m_profile;
}
/**
* 表示硬件平台的功耗场景类型名称与索引的对应表
*/
inline const std::map<std::string, hiprofile_type>& get_profile_map() {
return m_profile_map;
}
/**
* 表示硬件平台的功耗场景类型
*
* @param newVal
*/
inline void set_profile(std::string newVal) {
m_profile = newVal;
}
/**
* 功能:
* 获取当前对象的功耗场景类型索引
* 返回:
* 索引数值
*/
inline hiprofile_type get_profile_index() {
return get_profile(get_profile());
}
/**
* 功能:
* 根据配置文件名称获取类型索引数值
* 返回:
* 索引数值
*
* @param name 表示功耗场景类型名称
*/
inline hiprofile_type get_profile(std::string name) {
auto tmp_iter = get_profile_map().find(name);
if (tmp_iter != get_profile_map().end()) {
return tmp_iter->second;
}
return hiprofile_type_none;
}
private:
/**
* 表示系统内存的对齐方式
*/
int m_align_width = 16;
/**
* 最大内存池数量
*/
int m_max_pool_count = 128;
/**
* 表示硬件平台的功耗场景类型
*/
std::string m_profile = "";
/**
* 表示硬件平台的功耗场景类型名称与索引的对应表
*/
static const std::map<std::string, hiprofile_type> m_profile_map;
};
}
}
#endif // !defined(HISYS_CONF_H_INCLUDED_)
| 16.078212 | 81 | 0.548297 | Kitty-Kitty |
777c52e72ebed23d33736a4dcd95a1cf838aaf70 | 1,655 | cc | C++ | src/utils/cpputils/cxxutils.cc | Apraso/iSulad_test | c9bb9b9e2787275f6147c9353f279e49f6a4a086 | [
"MulanPSL-1.0"
] | 34 | 2020-03-09T11:57:08.000Z | 2022-03-29T12:18:33.000Z | src/utils/cpputils/cxxutils.cc | Apraso/iSulad_test | c9bb9b9e2787275f6147c9353f279e49f6a4a086 | [
"MulanPSL-1.0"
] | null | null | null | src/utils/cpputils/cxxutils.cc | Apraso/iSulad_test | c9bb9b9e2787275f6147c9353f279e49f6a4a086 | [
"MulanPSL-1.0"
] | 8 | 2020-03-21T02:36:22.000Z | 2021-11-13T18:15:43.000Z | /******************************************************************************
* Copyright (c) Huawei Technologies Co., Ltd. 2019. All rights reserved.
* iSulad licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
* http://license.coscl.org.cn/MulanPSL2
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
* PURPOSE.
* See the Mulan PSL v2 for more details.
* Author: wujing
* Create: 2019-05-17
* Description: provide c++ common utils functions
*******************************************************************************/
#include "cxxutils.h"
#include <algorithm>
#include <numeric>
namespace CXXUtils {
std::vector<std::string> Split(const std::string &str, char delimiter)
{
std::vector<std::string> ret_vec;
std::string tmpstr;
std::istringstream istream(str);
while (std::getline(istream, tmpstr, delimiter)) {
ret_vec.push_back(tmpstr);
}
return ret_vec;
}
// Join concatenates the elements of a to create a single string. The separator string
// sep is placed between elements in the resulting string.
std::string StringsJoin(const std::vector<std::string> &vec, const std::string &sep)
{
auto func = [&sep](const std::string & a, const std::string & b) -> std::string {
return a + (a.length() > 0 ? sep : "") + b;
};
return std::accumulate(vec.begin(), vec.end(), std::string(), func);
}
} // namespace CXXUtils
| 38.488372 | 99 | 0.626586 | Apraso |
777e920a31b860baa3c65afb6739afcd33ca9ad9 | 15,689 | cpp | C++ | Source/API/Vulkan/RenderPassVk.cpp | KawBuma/Buma3D | 73b1c7a99c979492f072d4ead89f2d357d5e048a | [
"MIT"
] | 5 | 2020-11-25T05:05:13.000Z | 2022-02-09T09:35:21.000Z | Source/API/Vulkan/RenderPassVk.cpp | KawBuma/Buma3D | 73b1c7a99c979492f072d4ead89f2d357d5e048a | [
"MIT"
] | 5 | 2020-11-11T09:52:59.000Z | 2021-12-15T13:27:37.000Z | Source/API/Vulkan/RenderPassVk.cpp | KawBuma/Buma3D | 73b1c7a99c979492f072d4ead89f2d357d5e048a | [
"MIT"
] | null | null | null | #include "Buma3DPCH.h"
#include "RenderPassVk.h"
namespace buma3d
{
B3D_APIENTRY RenderPassVk::RenderPassVk()
: ref_count { 1 }
, name {}
, device {}
, desc {}
, vkdevice {}
, inspfn {}
, devpfn {}
, render_pass{}
{
}
B3D_APIENTRY RenderPassVk::~RenderPassVk()
{
Uninit();
}
BMRESULT
B3D_APIENTRY RenderPassVk::Init(DeviceVk* _device, const RENDER_PASS_DESC& _desc)
{
(device = _device)->AddRef();
vkdevice = device->GetVkDevice();
inspfn = &device->GetInstancePFN();
devpfn = &device->GetDevicePFN();
CopyDesc(_desc);
B3D_RET_IF_FAILED(CreateRenderPass());
return BMRESULT_SUCCEED;
}
void
B3D_APIENTRY RenderPassVk::CopyDesc(const RENDER_PASS_DESC& _desc)
{
desc = _desc;
auto Create = [](auto _src, auto _count, auto& _vec, auto& _dst)
{
if (_count != 0)
{
_vec.resize(_count);
util::MemCopyArray(_vec.data(), _src, _count);
_dst = _vec.data();
}
else
{
_dst = nullptr;
}
};
Create(_desc.attachments , _desc.num_attachments , desc_data.attachments , desc.attachments);
Create(_desc.dependencies , _desc.num_dependencies , desc_data.dependencies , desc.dependencies);
Create(_desc.correlated_view_masks, _desc.num_correlated_view_masks, desc_data.correlated_view_masks, desc.correlated_view_masks);
Create(_desc.subpasses , _desc.num_subpasses , desc_data.subpasses , desc.subpasses);
desc_data.subpasses_data.resize(desc.num_subpasses);
for (uint32_t i = 0; i < desc.num_subpasses; i++)
{
auto&& dst_data = desc_data.subpasses_data[i];
auto&& dst_desc = desc_data.subpasses[i];
auto&& _src = _desc.subpasses[i];
Create(_src.input_attachments , _src.num_input_attachments , dst_data.input_attachments , dst_desc.input_attachments);
Create(_src.color_attachments , _src.num_color_attachments , dst_data.color_attachments , dst_desc.color_attachments);
if (_src.resolve_attachments)// 解決アタッチメントが存在すると定義されるのは、nullptrでない場合のみです。
Create(_src.resolve_attachments, _src.num_color_attachments, dst_data.resolve_attachments, dst_desc.resolve_attachments);
if (_src.depth_stencil_attachment)
{
dst_data.depth_stencil_attachment = B3DMakeUniqueArgs(ATTACHMENT_REFERENCE, *_src.depth_stencil_attachment);
dst_desc.depth_stencil_attachment = dst_data.depth_stencil_attachment.get();
}
Create(_src.preserve_attachments, _src.num_preserve_attachment , dst_data.preserve_attachments , dst_desc.preserve_attachments);
if (_src.shading_rate_attachment)
{
dst_data.shading_rate_attachment = B3DMakeUniqueArgs(SHADING_RATE_ATTACHMENT, *_src.shading_rate_attachment);
dst_desc.shading_rate_attachment = dst_data.shading_rate_attachment.get();
if (_src.shading_rate_attachment->shading_rate_attachment)
{
dst_data.shading_rate_attachment_ref = B3DMakeUniqueArgs(ATTACHMENT_REFERENCE, *_src.shading_rate_attachment->shading_rate_attachment);
dst_data.shading_rate_attachment->shading_rate_attachment = dst_data.shading_rate_attachment_ref.get();
}
}
}
}
BMRESULT
B3D_APIENTRY RenderPassVk::PrepareCreateInfo(VkRenderPassCreateInfo2* _ci, DESC_DATA_VK* _ci_data)
{
auto&& ci = *_ci;
auto&& ci_data = *_ci_data;
auto Create = [](auto _count, auto& _vec, auto& _dst_count, auto& _dst, auto _stype_or_preserve)
{
if (_count != 0)
{
if constexpr (std::is_same_v<decltype(_stype_or_preserve), VkStructureType>)
_vec.resize(_count, { _stype_or_preserve });
else
_vec.resize(_count);
_dst = _vec.data();
_dst_count = _count;
}
else
{
_dst_count = 0;
_dst = nullptr;
}
};
// ビューマスクは流用
ci.correlatedViewMaskCount = desc.num_correlated_view_masks;
ci.pCorrelatedViewMasks = desc_data.correlated_view_masks.data();
Create(desc.num_attachments , ci_data.attachments , ci.attachmentCount , ci.pAttachments , VK_STRUCTURE_TYPE_ATTACHMENT_DESCRIPTION_2);
Create(desc.num_dependencies , ci_data.dependencies , ci.dependencyCount , ci.pDependencies , VK_STRUCTURE_TYPE_SUBPASS_DEPENDENCY_2);
Create(desc.num_subpasses , ci_data.subpasses , ci.subpassCount , ci.pSubpasses , VK_STRUCTURE_TYPE_SUBPASS_DESCRIPTION_2);
ci_data.subpasses_data.resize(desc.num_subpasses);
for (uint32_t i = 0; i < desc.num_subpasses; i++)
{
auto&& dst_data = ci_data.subpasses_data[i];
auto&& dst_desc = ci_data.subpasses[i];
auto&& src = desc.subpasses[i];
Create(src.num_input_attachments , dst_data.input_attachments , dst_desc.inputAttachmentCount , dst_desc.pInputAttachments , VK_STRUCTURE_TYPE_ATTACHMENT_REFERENCE_2);
Create(src.num_color_attachments , dst_data.color_attachments , dst_desc.colorAttachmentCount , dst_desc.pColorAttachments , VK_STRUCTURE_TYPE_ATTACHMENT_REFERENCE_2);
if (src.resolve_attachments)// 解決アタッチメントが存在すると定義されるのは、nullptrでない場合のみです。
Create(src.num_color_attachments , dst_data.resolve_attachments , dst_desc.colorAttachmentCount , dst_desc.pColorAttachments , VK_STRUCTURE_TYPE_ATTACHMENT_REFERENCE_2);
Create(src.num_preserve_attachment , dst_data.preserve_attachments , dst_desc.preserveAttachmentCount , dst_desc.pPreserveAttachments , 0/*uint32_t*/);
if (src.depth_stencil_attachment)
{
dst_data.depth_stencil_attachment = B3DMakeUniqueArgs(VkAttachmentReference2, VkAttachmentReference2{ VK_STRUCTURE_TYPE_ATTACHMENT_REFERENCE_2 });
dst_desc.pDepthStencilAttachment = dst_data.depth_stencil_attachment.get();
}
if (src.shading_rate_attachment)
{
auto&& sravk = *(dst_data.shading_rate_attachment = B3DMakeUniqueArgs(VkFragmentShadingRateAttachmentInfoKHR, { VK_STRUCTURE_TYPE_FRAGMENT_SHADING_RATE_ATTACHMENT_INFO_KHR }));
util::ConnectPNextChains(dst_desc, sravk);
if (src.shading_rate_attachment->shading_rate_attachment)
{
dst_data.shading_rate_attachment_ref = B3DMakeUniqueArgs(VkAttachmentReference2, { VK_STRUCTURE_TYPE_ATTACHMENT_REFERENCE_2 });
sravk.pFragmentShadingRateAttachment = dst_data.shading_rate_attachment_ref.get();
}
}
}
// VK_RENDER_PASS_CREATE_TRANSFORM_BIT_QCOM
ci.flags = 0;
// ATTACHMENT_DESC => VkAttachmentDescription2
for (uint32_t i = 0; i < ci.attachmentCount; i++)
{
auto&& at = desc_data.attachments[i];
auto&& atvk = ci_data.attachments[i];
atvk.flags = util::GetNativeAttachmentFlags (at.flags);
atvk.format = util::GetNativeFormat (at.format);
atvk.samples = util::GetNativeSampleCount (at.sample_count);
atvk.loadOp = util::GetNativeLoadOp (at.load_op);
atvk.storeOp = util::GetNativeStoreOp (at.store_op);
atvk.stencilLoadOp = util::GetNativeLoadOp (at.stencil_load_op);
atvk.stencilStoreOp = util::GetNativeStoreOp (at.stencil_store_op);
if (util::IsDepthStencilFormat(at.format))
{
// 深度、またはステンシルプレーンどちらかのみをアタッチメントとして扱った場合に必要です(各プレーンのレイアウトをそれぞれ決める必要があるため)。
if (at.stencil_begin_state != RESOURCE_STATE_UNDEFINED)
{
atvk.initialLayout = util::GetNativeResourceStateForLayout(at.begin_state, TEXTURE_ASPECT_FLAG_DEPTH);
atvk.finalLayout = util::GetNativeResourceStateForLayout(at.end_state , TEXTURE_ASPECT_FLAG_DEPTH);
auto&& atsvk = *ci_data.attachments_stencil_layout.emplace_back(B3DMakeUniqueArgs(VkAttachmentDescriptionStencilLayout, { VK_STRUCTURE_TYPE_ATTACHMENT_DESCRIPTION_STENCIL_LAYOUT }));
atsvk.stencilInitialLayout = util::GetNativeResourceStateForLayout(at.stencil_begin_state, TEXTURE_ASPECT_FLAG_STENCIL);
atsvk.stencilFinalLayout = util::GetNativeResourceStateForLayout(at.stencil_end_state , TEXTURE_ASPECT_FLAG_STENCIL);
util::ConnectPNextChains(atvk, atsvk);
}
else
{
atvk.initialLayout = util::GetNativeResourceStateForLayout(at.begin_state, TEXTURE_ASPECT_FLAG_DEPTH | TEXTURE_ASPECT_FLAG_STENCIL);
atvk.finalLayout = util::GetNativeResourceStateForLayout(at.end_state , TEXTURE_ASPECT_FLAG_DEPTH | TEXTURE_ASPECT_FLAG_STENCIL);
}
}
else
{
atvk.initialLayout = util::GetNativeResourceStateForLayout(at.begin_state);
atvk.finalLayout = util::GetNativeResourceStateForLayout(at.end_state);
}
}
// SUBPASS_DESC => VkSubpassDescription2
for (uint32_t i = 0; i < ci.subpassCount; i++)
{
auto&& sp = desc_data.subpasses_data[i];
auto&& spvk = ci_data.subpasses_data[i];
uint32_t count;
auto SetReferenceStencilLayout = [&](const ATTACHMENT_REFERENCE& _ar, VkAttachmentReference2& _arvk)
{
auto&& arsvk = *spvk.stencil_layout.emplace_back(B3DMakeUniqueArgs(VkAttachmentReferenceStencilLayout, { VK_STRUCTURE_TYPE_ATTACHMENT_REFERENCE_STENCIL_LAYOUT }));
arsvk.stencilLayout = util::GetNativeResourceStateForLayout(_ar.stencil_state_at_pass, TEXTURE_ASPECT_FLAG_STENCIL);
util::ConnectPNextChains(_arvk, arsvk);
};
auto SetReference = [&](const ATTACHMENT_REFERENCE& _ar, VkAttachmentReference2& _arvk)
{
_arvk.aspectMask = util::GetNativeAspectFlags(_ar.input_attachment_aspect_mask);
_arvk.attachment = _ar.attachment_index;
_arvk.layout = util::GetNativeResourceStateForLayout(_ar.state_at_pass);
};
auto SetReferences = [&](const ATTACHMENT_REFERENCE& _ar, VkAttachmentReference2& _arvk)
{
SetReference(_ar, _arvk);
if (util::IsDepthStencilFormat(desc_data.attachments[i].format))
{
if (_ar.stencil_state_at_pass != RESOURCE_STATE_UNDEFINED)
{
_arvk.layout = util::GetNativeResourceStateForLayout(_ar.state_at_pass, TEXTURE_ASPECT_FLAG_DEPTH);
SetReferenceStencilLayout(_ar, _arvk);
}
}
};
count = 0;
for (auto& ia : sp.input_attachments)
{
auto&& iavk = spvk.input_attachments[count++];
SetReferences(ia, iavk);
}
count = 0;
for (auto& ca : sp.color_attachments)
{
auto&& cavk = spvk.color_attachments[count++];
SetReferences(ca, cavk);
}
count = 0;
for (auto& ra : sp.resolve_attachments)
{
auto&& ravk = spvk.resolve_attachments[count++];
SetReferences(ra, ravk);
}
if (sp.depth_stencil_attachment)
{
auto&& dsa = *sp.depth_stencil_attachment;
auto&& dsavk = *spvk.depth_stencil_attachment;
SetReferences(dsa, dsavk);
}
count = 0;
for (auto& pa : sp.preserve_attachments)
{
auto&& pavk = spvk.preserve_attachments[count++];
pavk = pa;
}
if (sp.shading_rate_attachment)
{
auto&& sra = *sp.shading_rate_attachment;
auto&& sravk = *spvk.shading_rate_attachment;
sravk.shadingRateAttachmentTexelSize.width = sra.shading_rate_attachment_texel_size.width;
sravk.shadingRateAttachmentTexelSize.height = sra.shading_rate_attachment_texel_size.height;
if (sra.shading_rate_attachment)
{
SetReferences(*sra.shading_rate_attachment, *spvk.shading_rate_attachment_ref);
}
}
}
// SUBPASS_DEPENDENCY => VkSubpassDependency2
for (uint32_t i = 0; i < ci.dependencyCount; i++)
{
auto&& dp = desc_data.dependencies[i];
auto&& dpvk = ci_data.dependencies[i];
dpvk.srcSubpass = dp.src_subpass;
dpvk.dstSubpass = dp.dst_subpass;
dpvk.srcStageMask = util::GetNativePipelineStageFlags(dp.src_stage_mask);
dpvk.dstStageMask = util::GetNativePipelineStageFlags(dp.dst_stage_mask);
dpvk.srcAccessMask = util::GetNativeResourceAccessFlags(dp.src_access);
dpvk.dstAccessMask = util::GetNativeResourceAccessFlags(dp.dst_access);
dpvk.dependencyFlags = dp.dependency_flags;
dpvk.viewOffset = dp.view_offset;
// TODO: D3D12と違い、ViewportArrayIndexが指定出来ないが、shaderOutputLayer機能が有効な場合、頂点バッファからSV_ViewportArrayIndexと同等の値を指定出来るので互換性があるか検証。(SV_ViewportArrayIndexの仕様上、そもそもDXC側で対応してくれない気はする。)
}
return BMRESULT_SUCCEED;
}
BMRESULT
B3D_APIENTRY RenderPassVk::CreateRenderPass()
{
VkRenderPassCreateInfo2 ci { VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO_2 };
DESC_DATA_VK ci_data{};
B3D_RET_IF_FAILED(PrepareCreateInfo(&ci, &ci_data));
auto vkr = vkCreateRenderPass2(vkdevice, &ci, B3D_VK_ALLOC_CALLBACKS, &render_pass);
B3D_RET_IF_FAILED(VKR_TRACE_IF_FAILED(vkr));
return BMRESULT_SUCCEED;
}
void
B3D_APIENTRY RenderPassVk::Uninit()
{
name.reset();
desc = {};
if (render_pass)
vkDestroyRenderPass(vkdevice, render_pass, B3D_VK_ALLOC_CALLBACKS);
render_pass = VK_NULL_HANDLE;
hlp::SafeRelease(device);
}
BMRESULT
B3D_APIENTRY RenderPassVk::Create(DeviceVk* _device, const RENDER_PASS_DESC& _desc, RenderPassVk** _dst)
{
util::Ptr<RenderPassVk> ptr;
ptr.Attach(B3DCreateImplementationClass(RenderPassVk));
B3D_RET_IF_FAILED(ptr->Init(_device, _desc));
*_dst = ptr.Detach();
return BMRESULT_SUCCEED;
}
void
B3D_APIENTRY RenderPassVk::AddRef()
{
++ref_count;
B3D_REFCOUNT_DEBUG(ref_count);
}
uint32_t
B3D_APIENTRY RenderPassVk::Release()
{
B3D_REFCOUNT_DEBUG(ref_count - 1);
auto count = --ref_count;
if (count == 0)
B3DDestroyImplementationClass(this);
return count;
}
uint32_t
B3D_APIENTRY RenderPassVk::GetRefCount() const
{
return ref_count;
}
const char*
B3D_APIENTRY RenderPassVk::GetName() const
{
return name ? name->c_str() : nullptr;
}
BMRESULT
B3D_APIENTRY RenderPassVk::SetName(const char* _name)
{
if (!util::IsEnabledDebug(this))
return BMRESULT_FAILED;
if (render_pass)
B3D_RET_IF_FAILED(device->SetVkObjectName(render_pass, _name));
if (name && !_name)
name.reset();
else
name = B3DMakeUniqueArgs(util::NameableObjStr, _name);
return BMRESULT_SUCCEED;
}
IDevice*
B3D_APIENTRY RenderPassVk::GetDevice() const
{
return device;
}
const VkAllocationCallbacks*
B3D_APIENTRY RenderPassVk::GetVkAllocationCallbacks() const
{
return device->GetVkAllocationCallbacks();
}
const InstancePFN&
B3D_APIENTRY RenderPassVk::GetIsntancePFN() const
{
return *inspfn;
}
const DevicePFN&
B3D_APIENTRY RenderPassVk::GetDevicePFN() const
{
return *devpfn;
}
const RENDER_PASS_DESC&
B3D_APIENTRY RenderPassVk::GetDesc() const
{
return desc;
}
VkRenderPass
B3D_APIENTRY RenderPassVk::GetVkRenderPass() const
{
return render_pass;
}
}// namespace buma3d
| 36.401392 | 198 | 0.668494 | KawBuma |
7780a2bb3fadcf96cff5553681afeb03cd2d908c | 4,260 | hpp | C++ | include/doll/Core/Defs.hpp | axia-sw/Doll | a5846a6553d9809e9a0ea50db2dc18b95eb21921 | [
"Zlib"
] | 1 | 2021-07-19T14:40:15.000Z | 2021-07-19T14:40:15.000Z | include/doll/Core/Defs.hpp | axia-sw/Doll | a5846a6553d9809e9a0ea50db2dc18b95eb21921 | [
"Zlib"
] | null | null | null | include/doll/Core/Defs.hpp | axia-sw/Doll | a5846a6553d9809e9a0ea50db2dc18b95eb21921 | [
"Zlib"
] | null | null | null | #pragma once
#include "../AxlibConfig.h"
#include "ax_intdatetime.h"
#include "ax_platform.h"
#include "ax_types.h"
#include "ax_printf.h"
#include "ax_string.h"
#include "ax_logger.h"
#include "ax_assert.h"
#include "ax_thread.h"
#include "ax_memory.h"
#include "ax_time.h"
#include "ax_thread.h"
//#include "ax_fiber.h"
#include "ax_config.h"
#include "ax_typetraits.hpp"
#include "ax_manager.hpp"
#include "ax_list.hpp"
#include "ax_array.hpp"
#include "ax_dictionary.hpp"
#ifdef DOLL__BUILD
# include "Private/Variants.hpp"
# ifndef DOLL__SECURE_LIB
# if defined( _MSC_VER ) && defined( __STDC_WANT_SECURE_LIB__ )
# define DOLL__SECURE_LIB __STDC_WANT_SECURE_LIB__
# else
# define DOLL__SECURE_LIB 0
# endif
# endif
// When building we use a different internal logging channel
# ifndef DOLL_TRACE_FACILITY
# define DOLL_TRACE_FACILITY doll::kLog_Internal
# endif
#endif
// Temporary hack
#ifndef DOLL__USE_GLFW
# ifdef _WIN32
# define DOLL__USE_GLFW 0
# else
# define DOLL__USE_GLFW 1
# endif
#endif
#define DOLL_RGBA(R_,G_,B_,A_)\
(\
( U32((A_)&0xFF)<<24 ) |\
( U32((B_)&0xFF)<<16 ) |\
( U32((G_)&0xFF)<< 8 ) |\
( U32((R_)&0xFF)<< 0 )\
)
#define DOLL_RGB(R_,G_,B_)\
DOLL_RGBA((R_),(G_),(B_),0xFF)
#define DOLL_COLOR_R(RGBA_)\
( ( U32(RGBA_)&0x000000FF )>>0 )
#define DOLL_COLOR_G(RGBA_)\
( ( U32(RGBA_)&0x0000FF00 )>>8 )
#define DOLL_COLOR_B(RGBA_)\
( ( U32(RGBA_)&0x00FF0000 )>>16 )
#define DOLL_COLOR_A(RGBA_)\
( ( U32(RGBA_)&0xFF000000 )>>24 )
#ifndef DOLL_DX_AVAILABLE
# if defined( _WIN32 ) || defined( _XBOX )
# define DOLL_DX_AVAILABLE 1
# else
# define DOLL_DX_AVAILABLE 0
# endif
#endif
namespace doll
{
using namespace ax;
enum EResult
{
kSuccess = 1,
kError_OutOfMemory = -4096,
kError_InvalidParameter,
kError_InvalidOperation,
kError_Overflow,
kError_Underflow
};
DOLL_FUNC Bool DOLL_API app_getPath( Str &dst );
inline Str DOLL_API app_getPath()
{
Str r;
return app_getPath( r ), r;
}
inline Str DOLL_API app_getDir()
{
return app_getPath().getDirectory();
}
inline Str DOLL_API app_getName()
{
const Str x = app_getPath().getBasename();
if( x.caseEndsWith( "dbg" ) ) {
return x.drop( 3 );
}
return x;
}
AX_CONSTEXPR_INLINE U32 doll_rgb( F32 r, F32 g, F32 b, F32 a = 1.0f )
{
return
DOLL_RGBA
(
U32((r < 0.0f ? 0.0f : r > 1.0f ? 1.0f : r)*255.0f),
U32((g < 0.0f ? 0.0f : g > 1.0f ? 1.0f : g)*255.0f),
U32((b < 0.0f ? 0.0f : b > 1.0f ? 1.0f : b)*255.0f),
U32((a < 0.0f ? 0.0f : a > 1.0f ? 1.0f : a)*255.0f)
);
}
template< typename T, UPtr tNum >
inline Bool isOneOf( const T x, const T( &buf )[ tNum ] )
{
for( const T &y : buf ) {
if( x == y ) {
return true;
}
}
return false;
}
template< typename T, typename... Args >
inline Bool isOneOf( const T &x, Args... args ) {
const T buf[] = { args... };
for( const T &y : buf ) {
if( x == y ) {
return true;
}
}
return false;
}
template< typename T >
inline U16 countBits( T x )
{
U16 n = 0;
while( x ) {
++n;
x &= x - 1;
}
return n;
}
inline Bool takeFlag( U32 &uFlags, U32 uCheck )
{
if( ~uFlags & uCheck ) {
return false;
}
uFlags &= ~uCheck;
return true;
}
template< class Functor >
class TScopeGuard
{
public:
inline TScopeGuard( const Functor &func )
: mFunc( func )
, mState( EState::Valid )
{
}
inline TScopeGuard( TScopeGuard< Functor > &&r )
: mFunc( r.mFunc )
, mState( r.mState )
{
r.commit();
}
inline ~TScopeGuard()
{
call();
}
inline void commit()
{
mState = EState::Committed;
}
inline void call()
{
if( mState != EState::Valid ) {
return;
}
mFunc();
commit();
}
inline void operator()()
{
call();
}
private:
enum class EState
{
Valid,
Committed
};
const Functor mFunc;
EState mState;
};
template< class Functor >
inline TScopeGuard< Functor > makeScopeGuard( const Functor &func )
{
return forward< TScopeGuard< Functor > >( func );
}
}
| 18.283262 | 71 | 0.594131 | axia-sw |
7781058b8b8d65e96ddce388b2d90d175d7d9928 | 2,858 | hpp | C++ | include/core/p_render/PRender.hpp | jabronicus/P-Engine | 7786c2f97d19bd2913b706f6afe5087a392b1a3c | [
"MIT"
] | null | null | null | include/core/p_render/PRender.hpp | jabronicus/P-Engine | 7786c2f97d19bd2913b706f6afe5087a392b1a3c | [
"MIT"
] | null | null | null | include/core/p_render/PRender.hpp | jabronicus/P-Engine | 7786c2f97d19bd2913b706f6afe5087a392b1a3c | [
"MIT"
] | 1 | 2021-08-24T05:43:01.000Z | 2021-08-24T05:43:01.000Z | #pragma once
#include "./backend/wsi/WindowSystem.hpp"
#include "../../core/thread_pool/job_queue/JobQueue.hpp"
// gui
#include "./backend/gui/VulkanGUIHandler.hpp"
// render graph
#include "./render_graph/RenderGraph.hpp"
// scene (TODO)
#include "./scene/Scene.hpp"
#include "../../imgui/imgui.h"
#include "../../imgui/imgui_impl_vulkan.h"
#include "../../imgui/imgui_impl_win32.h"
#include "../../core/p_render/backend/Context.hpp"
// VMA
#include "../../vulkan_memory_allocator/vk_mem_alloc.h"
// GLM
#define GLM_FORCE_RADIANS
#define GLM_FORCE_DEPTH_ZERO_TO_ONE
#include "../../glm/glm.hpp"
#include "../../glm/gtc/quaternion.hpp"
#include "../../glm/gtc/matrix_transform.hpp"
#include "../../glm/vec3.hpp"
// VULKAN LIMITS
// should probably move these elsewhere
// just gonna use the limits that Themaister's Granite uses, since i don't know how to judge
// what reasonable limits are, and i also like the idea of keeping things compact
#define VULKAN_NUM_DESCRIPTOR_SETS 4
#define VULKAN_NUM_ATTACHMENTS 8
#define VULKAN_NUM_BINDINGS 32
#define VULKAN_NUM_VERTEX_ATTRIBUTES 16
#define VULKAN_NUM_VERTEX_BUFFERS 4
#define VULKAN_PUSH_CONSTANT_SIZE 128
#define VULKAN_MAX_UBO_SIZE 16 * 1024
#pragma region PRENDER_DEFINITION
class PEngine;
class VulkanGUIHandler;
namespace backend {
class Context;
class FrameContext;
}
namespace scene {
class Scene;
}
class PRender {
public:
PRender(PEngine *engineCore);
~PRender();
/* RENDER INTERFACE */
std::shared_ptr<backend::Context> &renderContext();
// render graph interface
std::shared_ptr<RenderGraph> registerRenderGraph(const std::string &name);
std::shared_ptr<RenderGraph> getRenderGraph(const std::string &name);
VmaAllocator &getVMAllocator() {
return allocator_;
}
// gui interface
void registerGUIComponent(std::function<void()> call);
void clearGUIComponents();
/* RENDER INTERFACE */
void renderFrame(const std::string &renderGraphName = "default");
private:
/* render state */
PEngine *core_ = nullptr;
VmaAllocator allocator_;
/* RENDER STATE */
// SCENES (TODO)
// GRAPHS
std::vector<std::shared_ptr<RenderGraph>> renderGraphs_;
std::unordered_map<std::string, unsigned int> renderGraphNames_;
// maintain a simple vector of FrameContexts, which should manage all the data for rendering one frame in one particular swapchain image
std::vector<std::shared_ptr<backend::FrameContext>> frameContexts_;
unsigned int activeFrameContext_;
// gui handler
std::shared_ptr<VulkanGUIHandler> gui_;
/* BACKEND */
std::shared_ptr<backend::Context> context_;
void setupImGui();
void setupIMGUIResources();
void submitCommandBuffers(backend::FrameContext &frameContext);
};
#pragma endregion PRENDER_DEFINITION
| 25.070175 | 140 | 0.719384 | jabronicus |
77865066b102246f82e4fae912b640f51938294d | 5,145 | cpp | C++ | src/PihaTime.cpp | jbitoniau/Piha | 9f346066bf09a93abc5753b5dd996c7f598c9d38 | [
"MIT"
] | null | null | null | src/PihaTime.cpp | jbitoniau/Piha | 9f346066bf09a93abc5753b5dd996c7f598c9d38 | [
"MIT"
] | null | null | null | src/PihaTime.cpp | jbitoniau/Piha | 9f346066bf09a93abc5753b5dd996c7f598c9d38 | [
"MIT"
] | null | null | null | #include "PihaTime.h"
#ifdef _WIN32
#include <Windows.h>
#else
#include <cstddef> // For NULL
//#include <sys/time.h>
#include <time.h>
#endif
#include <assert.h>
namespace Piha
{
#ifdef _WIN32
/*
TimeInternals (Windows platform)
On Windows, there are many time functions available.
- the standard ftime function (sys/timeb.h). Millisecond resolution but 15ms accuracy
- GetSystemTimeAsFileTime(). Millisecond resolution but 15ms accuracy
- GetTickCount(). Millisecond resolution but up to 50 ms accuracy (to double check)
The only high resolution/accuracy one I found is the Performance counter but it seems not
very reliable on multi-core machines see http:www.virtualdub.org/blog/pivot/entry.php?id=106
Anyway, I'm using it for now. I think this can be improved:
http:msdn.microsoft.com/en-us/magazine/cc163996.aspx
*/
class TimeInternals
{
public:
TimeInternals();
unsigned long long int getTickFrequency() const { return mTickFrequency; }
unsigned long long int getTickCount() const;
unsigned int getTimeAsMilliseconds() const;
static TimeInternals& getInstance() { return mTimeInternals; }
private:
static unsigned long long int internalGetTickFrequency();
static unsigned long long int internalGetTickCount();
unsigned long long int mTickFrequency;
unsigned long long int mInitialTickCount;
static TimeInternals mTimeInternals;
};
/*
TimeInternals (Windows platform)
*/
TimeInternals TimeInternals::mTimeInternals;
TimeInternals::TimeInternals()
{
mTickFrequency = internalGetTickFrequency(); // Cache the tick frequency as it doesn't change during the application lifetime
mInitialTickCount = internalGetTickCount();
}
unsigned long long int TimeInternals::getTickCount() const
{
unsigned long long int tickCount = internalGetTickCount();
tickCount -= mInitialTickCount;
return tickCount;
}
unsigned int TimeInternals::getTimeAsMilliseconds() const
{
unsigned int time = static_cast<unsigned int>( (getTickCount()*1000) / getTickFrequency() );
return time;
}
unsigned long long int TimeInternals::internalGetTickFrequency()
{
LARGE_INTEGER frequency;
QueryPerformanceFrequency(&frequency);
return frequency.QuadPart;
}
unsigned long long int TimeInternals::internalGetTickCount()
{
LARGE_INTEGER counter;
QueryPerformanceCounter(&counter);
return counter.QuadPart;
}
#else
/*
TimeInternals (non-Windows platform)
This implementation relies on the monotonic version of clock_gettime() function.
Changing the system date/time won't affect this time.
See http://code-factor.blogspot.fr/2009/11/monotonic-timers.html
*/
class TimeInternals
{
public:
TimeInternals();
unsigned int getTimeAsMilliseconds() const;
static TimeInternals& getInstance() { return mTimeInternals; }
private:
struct timespec mInitialTime;
static TimeInternals mTimeInternals;
};
/*
TimeInternals (non-Windows platform)
*/
TimeInternals TimeInternals::mTimeInternals;
TimeInternals::TimeInternals()
{
int ret = clock_gettime( CLOCK_MONOTONIC, &mInitialTime );
assert( ret==0 );
}
unsigned int TimeInternals::getTimeAsMilliseconds() const
{
struct timespec theTime;
int ret = clock_gettime( CLOCK_MONOTONIC, &theTime );
assert( ret==0 );
time_t numSeconds = theTime.tv_sec;
long numNanoSeconds = theTime.tv_nsec; // 1ns = 10^-9 seconds
unsigned int milliseconds = static_cast<unsigned int>(numSeconds - mInitialTime.tv_sec) * 1000 +
static_cast<unsigned int>(numNanoSeconds / 1000000) -
static_cast<unsigned int>(mInitialTime.tv_nsec / 1000000);
return milliseconds;
}
/*
TimeInternals (non-Windows platform)
This is obsolete!
Here we use the gettimeofday function (http://man7.org/linux/man-pages/man2/gettimeofday.2.html)
This can lead to dramatic results if the system time is changed behind the application's back!
See
http://tldp.org/HOWTO/Clock-2.html
http://linuxcommand.org/man_pages/adjtimex8.html
http://stackoverflow.com/questions/588307/c-obtaining-milliseconds-time-on-linux-clock-doesnt-seem-to-work-properl
http://linux.die.net/man/3/clock_gettime
*/
/*
class TimeInternals
{
public:
TimeInternals();
unsigned int getTimeAsMilliseconds() const;
static TimeInternals& getInstance() { return mTimeInternals; }
private:
timeval mInitialTime;
static TimeInternals mTimeInternals;
};
*/
/*
TimeInternals (non-Windows platform)
*/
/*
TimeInternals TimeInternals::mTimeInternals;
TimeInternals::TimeInternals()
{
gettimeofday( &mInitialTime, NULL );
}
unsigned int TimeInternals::getTimeAsMilliseconds() const
{
struct timeval theTime;
gettimeofday(&theTime, NULL);
time_t numSeconds = theTime.tv_sec;
suseconds_t numMicroSeconds = theTime.tv_usec;
unsigned int milliseconds = static_cast<unsigned int>(numSeconds - mInitialTime.tv_sec) * 1000 +
static_cast<unsigned int>(numMicroSeconds) / 1000 -
static_cast<unsigned int>(mInitialTime.tv_usec) / 1000;
return milliseconds;
}
*/
#endif
/*
Time
*/
unsigned int Time::getTimeAsMilliseconds()
{
unsigned int milliseconds = TimeInternals::getInstance().getTimeAsMilliseconds();
return milliseconds;
}
}
| 25.097561 | 126 | 0.762488 | jbitoniau |
778ac59364ca39996a94bab0a60e012c55311fb2 | 3,865 | cc | C++ | build/x86/mem/ruby/network/garnet/fixed-pipeline/GarnetLink_d.py.cc | billionshang/gem5 | 18cc4294f32315595f865d07d1f33434e92b06b2 | [
"BSD-3-Clause"
] | null | null | null | build/x86/mem/ruby/network/garnet/fixed-pipeline/GarnetLink_d.py.cc | billionshang/gem5 | 18cc4294f32315595f865d07d1f33434e92b06b2 | [
"BSD-3-Clause"
] | null | null | null | build/x86/mem/ruby/network/garnet/fixed-pipeline/GarnetLink_d.py.cc | billionshang/gem5 | 18cc4294f32315595f865d07d1f33434e92b06b2 | [
"BSD-3-Clause"
] | null | null | null | #include "sim/init.hh"
namespace {
const uint8_t data_m5_objects_GarnetLink_d[] = {
120,156,205,86,89,111,211,64,16,30,59,247,1,173,80,27,
110,225,7,30,44,164,96,14,21,132,4,8,81,33,132,132,
0,185,8,137,188,88,142,119,147,56,241,17,121,183,77,242,
192,83,249,13,252,93,152,25,219,105,10,5,193,83,201,49,
153,253,118,215,187,243,205,183,179,9,160,120,85,240,251,194,
2,80,223,208,17,248,49,32,2,248,88,120,70,238,153,16,
153,16,155,48,48,193,160,118,5,162,10,196,85,24,84,33,
174,193,160,134,104,21,164,9,35,3,68,13,190,2,28,3,
124,30,212,65,212,65,214,25,109,172,209,6,136,38,200,42,
163,173,53,218,4,209,6,89,99,180,179,70,91,32,186,112,
96,95,192,173,133,223,241,101,27,232,105,50,119,114,151,122,
246,163,52,152,73,241,126,56,149,129,182,77,130,187,104,94,
250,42,12,222,36,250,109,152,204,78,128,87,203,28,160,137,
239,164,94,164,217,140,218,158,8,54,9,121,73,132,124,65,
71,2,12,12,162,5,35,71,62,6,21,218,249,180,70,81,
77,27,196,203,49,146,210,96,176,201,96,139,200,33,176,189,
49,178,3,72,15,129,157,13,176,75,84,17,120,97,3,188,
72,148,17,184,5,238,129,221,192,29,184,85,52,234,49,154,
88,198,78,118,56,92,57,73,190,111,103,236,103,232,58,163,
112,41,69,127,30,206,101,20,38,210,57,21,213,221,201,68,
209,83,176,103,102,133,66,117,75,63,242,181,76,130,149,186,
141,192,81,152,233,67,63,178,130,137,159,36,50,82,214,92,
102,86,9,22,139,169,107,56,48,57,140,135,216,149,142,126,
233,229,238,98,190,181,8,133,158,88,207,158,89,195,133,53,
242,3,157,102,246,54,101,165,137,198,243,18,63,150,158,167,
219,220,136,83,113,24,81,147,162,212,171,185,100,60,88,46,
189,137,244,133,204,116,13,155,31,252,204,143,53,229,5,211,
169,235,57,34,209,45,35,243,112,65,130,247,87,65,36,85,
14,231,241,233,50,96,111,19,56,10,148,135,49,122,71,184,
125,125,18,152,151,142,188,34,48,175,12,76,183,10,130,8,
81,154,226,24,250,137,224,16,189,60,56,214,82,17,187,199,
29,54,233,232,196,168,41,26,39,78,180,51,25,143,148,115,
48,193,221,31,76,100,226,140,101,188,215,79,179,112,28,38,
125,165,253,97,36,251,15,238,221,223,235,63,233,63,116,84,
22,56,127,153,241,215,140,22,9,159,175,88,49,148,87,181,
131,166,110,208,123,23,223,93,163,85,124,153,132,253,76,138,
80,255,36,126,163,20,255,206,153,226,71,77,210,249,114,119,
233,233,143,254,94,147,155,107,161,36,109,218,161,75,169,117,
41,109,46,235,188,121,138,179,115,33,142,194,186,71,235,86,
11,226,244,22,58,249,168,162,146,156,85,40,190,158,201,213,
24,168,60,174,143,54,214,179,99,3,140,95,218,13,152,214,
105,84,81,75,154,60,175,5,178,197,227,218,235,113,63,183,
113,94,155,70,21,229,166,67,185,97,90,123,255,152,155,83,
36,96,185,32,53,143,210,108,225,103,194,162,147,163,212,117,
22,125,48,99,104,20,165,139,126,144,38,58,75,163,188,223,
238,254,38,155,124,100,147,72,241,217,244,231,115,153,8,214,
166,238,160,249,36,233,236,228,71,155,150,44,54,233,241,35,
121,102,16,41,206,8,171,53,96,5,229,189,231,172,18,34,
120,239,212,241,170,212,205,109,115,219,184,100,230,191,27,170,
41,174,155,255,95,53,55,255,27,213,184,151,201,92,41,175,
62,247,42,25,42,210,238,245,178,244,184,55,206,191,86,16,
97,111,254,164,130,119,54,93,101,124,127,196,123,119,231,36,
116,197,87,32,181,178,116,185,114,141,178,159,255,153,208,163,
93,174,174,149,117,236,187,229,129,230,229,206,55,98,222,251,
211,252,194,126,126,139,214,191,136,166,109,180,141,109,163,103,
246,186,189,90,111,231,7,183,171,114,78,
};
EmbeddedPython embedded_m5_objects_GarnetLink_d(
"m5/objects/GarnetLink_d.py",
"/mnt/hgfs/ShareShen/gem5-origin-stable-2015-9-3/src/mem/ruby/network/garnet/fixed-pipeline/GarnetLink_d.py",
"m5.objects.GarnetLink_d",
data_m5_objects_GarnetLink_d,
891,
2646);
} // anonymous namespace
| 52.945205 | 113 | 0.670634 | billionshang |
778af2c718d92503d298664a4dc92c936eed001b | 7,306 | cpp | C++ | tests/AnimationManagerTests.cpp | longhorndude08/dhorn | d5a4c26ad1ee5f461fffe6db625d652cd94472cd | [
"MIT"
] | null | null | null | tests/AnimationManagerTests.cpp | longhorndude08/dhorn | d5a4c26ad1ee5f461fffe6db625d652cd94472cd | [
"MIT"
] | null | null | null | tests/AnimationManagerTests.cpp | longhorndude08/dhorn | d5a4c26ad1ee5f461fffe6db625d652cd94472cd | [
"MIT"
] | 1 | 2019-06-22T02:39:23.000Z | 2019-06-22T02:39:23.000Z | /*
* Duncan Horn
*
* UnitsTests.cpp
*
* Tests for the animation_manager.h types/functions
*/
#include "stdafx.h"
#include <dhorn/experimental/animation_manager.h>
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace dhorn
{
namespace tests
{
TEST_CLASS(AnimationManagerTests)
{
// Test animation instance
class test_animation :
public dhorn::experimental::animation
{
public:
test_animation() :
_nextState(dhorn::experimental::animation_state::running)
{
}
virtual ~test_animation()
{
if (this->_onDestroy)
{
this->_onDestroy();
}
}
// animation
virtual dhorn::experimental::animation_state on_update(duration /*delta*/) override
{
if (this->_onUpdate)
{
this->_onUpdate();
}
return this->_nextState;
}
// Test functions
void set_next_state(dhorn::experimental::animation_state state)
{
this->_nextState = state;
}
void on_destroy(std::function<void(void)> fn)
{
this->_onDestroy = std::move(fn);
}
void on_update(std::function<void(void)> fn)
{
this->_onUpdate = std::move(fn);
}
private:
dhorn::experimental::animation_state _nextState;
std::function<void(void)> _onDestroy;
std::function<void(void)> _onUpdate;
};
TEST_METHOD(QueryStateFailureTest)
{
dhorn::experimental::animation_manager mgr;
test_animation *anim = new test_animation();
auto handle = mgr.submit(anim);
// Querying the animation state on a different animation_manager instance should throw
try
{
dhorn::experimental::animation_manager mgr2;
mgr2.query_state(handle.get());
Assert::Fail(L"Expected an exception");
}
catch (std::out_of_range& /*e*/)
{
}
}
TEST_METHOD(CancelTest)
{
dhorn::experimental::animation_manager mgr;
test_animation *anim = new test_animation();
auto handle = mgr.submit(anim);
mgr.cancel(handle.get());
// Should either be in the canceled or completed state; we don't really care
ASSERT_TRUE(dhorn::experimental::details::is_complete(mgr.query_state(handle.get())));
// After update, it should definitely be completed
mgr.update();
ASSERT_TRUE(mgr.query_state(handle.get()) == dhorn::experimental::animation_state::completed);
// Animations should be able to cancel themselves (and immediately transition to completed
anim = new test_animation();
anim->set_next_state(dhorn::experimental::animation_state::canceled);
handle = mgr.submit(anim);
mgr.update();
ASSERT_TRUE(mgr.query_state(handle.get()) == dhorn::experimental::animation_state::completed);
}
TEST_METHOD(DestroyTest)
{
dhorn::experimental::animation_manager mgr;
test_animation *anim = new test_animation();
anim->set_next_state(dhorn::experimental::animation_state::completed);
int x = 0;
anim->on_destroy([&]()
{
x = 42;
});
{ // Let the handle fall out of scope
auto handle = mgr.submit(anim);
ASSERT_EQ(0, x);
}
// Handle is destroyed; shouldn't destroy the animation yet since it is still running
ASSERT_EQ(0, x);
// After update, the animation will complete and will be destroyed
mgr.update();
ASSERT_EQ(42, x);
x = 0;
anim = new test_animation();
anim->set_next_state(dhorn::experimental::animation_state::completed);
anim->on_destroy([&]()
{
x = 42;
});
{ // Let the handle fall out of scope
auto handle = mgr.submit(anim);
mgr.update();
// Animation is complete, but hasn't fallen out of scope
ASSERT_EQ(0, x);
}
// NOTE: The animation won't be destroyed yet since we defer the remove until the next call to update
mgr.update();
ASSERT_EQ(42, x);
}
TEST_METHOD(PauseResumeTest)
{
dhorn::experimental::animation_manager mgr;
test_animation *anim = new test_animation();
auto handle = mgr.submit(anim);
mgr.pause(handle.get());
ASSERT_TRUE(mgr.query_state(handle.get()) == dhorn::experimental::animation_state::paused);
// Update shouldn't impact animations
int x = 0;
anim->on_update([&]() { x = 42; });
mgr.update();
ASSERT_EQ(0, x);
ASSERT_TRUE(mgr.query_state(handle.get()) == dhorn::experimental::animation_state::paused);
mgr.resume(handle.get());
ASSERT_TRUE(mgr.query_state(handle.get()) == dhorn::experimental::animation_state::running);
// Animations should be able to transition themselves to paused
anim->set_next_state(dhorn::experimental::animation_state::paused);
mgr.update();
ASSERT_TRUE(mgr.query_state(handle.get()) == dhorn::experimental::animation_state::paused);
}
TEST_METHOD(DestructorTest)
{
// There's not much that we can easily test here, so just go with the simplest and make sure the
// animation instance is cleaned up. Go ahead and test the std::shared_ptr version of submit too
int x = 0;
int y = 0;
test_animation *anim = new test_animation();
std::shared_ptr<test_animation> anim2 = std::make_shared<test_animation>();
{
anim->on_destroy([&]() { x = 42; });
anim2->on_destroy([&]() { y = 8;} );
dhorn::experimental::animation_manager mgr;
auto handle = mgr.submit(anim);
auto handle2 = mgr.submit(anim2);
}
ASSERT_EQ(42, x);
ASSERT_EQ(0, y);
}
};
}
}
| 35.294686 | 117 | 0.48905 | longhorndude08 |
7792740acaea29b5e23cd242afb692f3945686af | 498 | hpp | C++ | visualisation/sensors/gyroscope.hpp | kwikius/ArduIMU | e741d2896425fa398c9a7ee19b986d1f6b31418f | [
"CC0-1.0"
] | null | null | null | visualisation/sensors/gyroscope.hpp | kwikius/ArduIMU | e741d2896425fa398c9a7ee19b986d1f6b31418f | [
"CC0-1.0"
] | null | null | null | visualisation/sensors/gyroscope.hpp | kwikius/ArduIMU | e741d2896425fa398c9a7ee19b986d1f6b31418f | [
"CC0-1.0"
] | 1 | 2021-12-22T07:01:16.000Z | 2021-12-22T07:01:16.000Z | #ifndef ARDUIMU_VISUALISATION_GYROSCOPE_HPP_INCLUDED
#define ARDUIMU_VISUALISATION_GYROSCOPE_HPP_INCLUDED
#include <quan/three_d/vect.hpp>
#include <quan/reciprocal_time.hpp>
#include <quan/angle.hpp>
quan::three_d::vect<
quan::reciprocal_time_<
quan::angle::deg
>::per_s
> get_gyroscope();
void set_gyroscope(
quan::three_d::vect<
quan::reciprocal_time_<
quan::angle::deg
>::per_s
> const & v
);
#endif // ARDUIMU_VISUALISATION_GYROSCOPE_HPP_INCLUDED
| 21.652174 | 54 | 0.726908 | kwikius |
7792a1082bf8019894311fd989b4766c94970307 | 1,963 | cpp | C++ | src/Platform.Cocoa/MouseCocoa.cpp | bis83/pomdog | 133a9262958d539ae6d93664e6cb2207b5b6c7ff | [
"MIT"
] | null | null | null | src/Platform.Cocoa/MouseCocoa.cpp | bis83/pomdog | 133a9262958d539ae6d93664e6cb2207b5b6c7ff | [
"MIT"
] | null | null | null | src/Platform.Cocoa/MouseCocoa.cpp | bis83/pomdog | 133a9262958d539ae6d93664e6cb2207b5b6c7ff | [
"MIT"
] | null | null | null | // Copyright (c) 2013-2015 mogemimi.
// Distributed under the MIT license. See LICENSE.md file for details.
#include "MouseCocoa.hpp"
#include <type_traits>
namespace Pomdog {
namespace Detail {
namespace Cocoa {
//-----------------------------------------------------------------------
MouseCocoa::MouseCocoa()
: scrollWheel(0)
{}
//-----------------------------------------------------------------------
MouseState MouseCocoa::GetState() const
{
return state;
}
//-----------------------------------------------------------------------
void MouseCocoa::Position(Point2D const& position)
{
state.Position = position;
}
//-----------------------------------------------------------------------
void MouseCocoa::WheelDelta(double wheelDelta)
{
scrollWheel += wheelDelta;
static_assert(std::is_same<double, decltype(scrollWheel)>::value, "");
static_assert(std::is_same<std::int32_t, decltype(state.ScrollWheel)>::value, "");
state.ScrollWheel = this->scrollWheel;
}
//-----------------------------------------------------------------------
void MouseCocoa::LeftButton(ButtonState buttonState)
{
state.LeftButton = buttonState;
}
//-----------------------------------------------------------------------
void MouseCocoa::RightButton(ButtonState buttonState)
{
state.RightButton = buttonState;
}
//-----------------------------------------------------------------------
void MouseCocoa::MiddleButton(ButtonState buttonState)
{
state.MiddleButton = buttonState;
}
//-----------------------------------------------------------------------
void MouseCocoa::XButton1(ButtonState buttonState)
{
state.XButton1 = buttonState;
}
//-----------------------------------------------------------------------
void MouseCocoa::XButton2(ButtonState buttonState)
{
state.XButton2 = buttonState;
}
//-----------------------------------------------------------------------
} // namespace Cocoa
} // namespace Detail
} // namespace Pomdog
| 32.180328 | 86 | 0.464086 | bis83 |
77953649de1f1064d89f8c61642717fe310407f2 | 11,224 | cpp | C++ | engine/cl_splitscreen.cpp | DannyParker0001/Kisak-Strike | 99ed85927336fe3aff2efd9b9382b2b32eb1d05d | [
"Unlicense"
] | 252 | 2020-12-16T15:34:43.000Z | 2022-03-31T23:21:37.000Z | cstrike15_src/engine/cl_splitscreen.cpp | bahadiraraz/Counter-Strike-Global-Offensive | 9a0534100cb98ffa1cf0c32e138f0e7971e910d3 | [
"MIT"
] | 23 | 2020-12-20T18:02:54.000Z | 2022-03-28T16:58:32.000Z | cstrike15_src/engine/cl_splitscreen.cpp | bahadiraraz/Counter-Strike-Global-Offensive | 9a0534100cb98ffa1cf0c32e138f0e7971e910d3 | [
"MIT"
] | 42 | 2020-12-19T04:32:33.000Z | 2022-03-30T06:00:28.000Z | #include "client_pch.h"
#include "cl_splitscreen.h"
#if defined( _PS3 )
#include "tls_ps3.h"
#define m_SplitSlot reinterpret_cast< SplitSlot_t *& >(GetTLSGlobals()->pEngineSplitSlot)
#endif // _PS3
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
class CSplitScreen : public ISplitScreen
{
public:
CSplitScreen();
virtual bool Init();
virtual void Shutdown();
virtual bool AddSplitScreenUser( int nSlot, int nPlayerIndex );
virtual bool AddBaseUser( int nSlot, int nPlayerIndex );
virtual bool RemoveSplitScreenUser( int nSlot, int nPlayerIndex );
virtual int GetActiveSplitScreenPlayerSlot();
virtual int SetActiveSplitScreenPlayerSlot( int slot );
virtual bool IsValidSplitScreenSlot( int nSlot );
virtual int FirstValidSplitScreenSlot(); // -1 == invalid
virtual int NextValidSplitScreenSlot( int nPreviousSlot ); // -1 == invalid
virtual int GetNumSplitScreenPlayers();
virtual int GetSplitScreenPlayerEntity( int nSlot );
virtual INetChannel *GetSplitScreenPlayerNetChan( int nSlot );
virtual bool IsDisconnecting( int nSlot );
virtual void SetDisconnecting( int nSlot, bool bState );
virtual bool SetLocalPlayerIsResolvable( char const *pchContext, int nLine, bool bResolvable );
virtual bool IsLocalPlayerResolvable();
CClientState &GetLocalPlayer( int nSlot = -1 );
struct SplitSlot_t
{
SplitSlot_t() : m_nActiveSplitScreenPlayer( 0 ), m_bLocalPlayerResolvable( false ), m_bMainThread( false ) { }
short m_nActiveSplitScreenPlayer;
// Can a call to C_BasePlayer::GetLocalPlayer be resolved in client .dll (inside a setactivesplitscreenuser scope?)
unsigned short m_bLocalPlayerResolvable : 1;
unsigned short m_bMainThread : 1;
unsigned short pad : 14;
};
private:
int FindSplitPlayerSlot( int nPlayerEntityIndex );
struct SplitPlayer_t
{
SplitPlayer_t() :
m_bActive( false )
{
}
bool m_bActive;
CClientState m_Client;
};
SplitPlayer_t *m_SplitScreenPlayers[ MAX_SPLITSCREEN_CLIENTS ];
int m_nActiveSplitScreenUserCount;
#if defined( _PS3 )
#elif !defined( _X360 )
// Each thread (mainly an issue in the client .dll) can have it's own "active" context. The per thread data is allocated as needed
#else
// xbox uses 12 bit thread id key to do direct lookup
SplitSlot_t m_SplitSlotTable[0x1000];
#endif
SplitSlot_t *GetSplitSlot();
bool m_bInitialized;
};
static CTHREADLOCALPTR( CSplitScreen::SplitSlot_t ) s_SplitSlot;
static CSplitScreen g_SplitScreenMgr;
ISplitScreen *splitscreen = &g_SplitScreenMgr;
CSplitScreen::CSplitScreen()
{
m_bInitialized = false;
}
#if defined( _X360 )
inline int BucketForThreadId()
{
DWORD id = GetCurrentThreadId();
// e.g.: 0xF9000028 -- or's the 9 and the 28 to give 12 bits (slot array is 0x1000 in size), the first nibble is(appears to be) always F so is masked off (0x0F00)
return ( ( id >> 16 ) & 0x00000F00 ) | ( id & 0x000000FF );
}
#endif
CSplitScreen::SplitSlot_t *CSplitScreen::GetSplitSlot()
{
#if defined( _X360 )
// pix shows this function to be enormously expensive due to high frequency of inner loop calls
// avoid conditionals and TLS, use a direct lookup instead
return &m_SplitSlotTable[ BucketForThreadId() ];
#else
if ( !s_SplitSlot )
{
s_SplitSlot = new SplitSlot_t();
}
return s_SplitSlot;
#endif
}
bool CSplitScreen::Init()
{
m_bInitialized = true;
Assert( ThreadInMainThread() );
SplitSlot_t *pSlot = GetSplitSlot();
pSlot->m_bLocalPlayerResolvable = false;
pSlot->m_nActiveSplitScreenPlayer = 0;
pSlot->m_bMainThread = true;
m_nActiveSplitScreenUserCount = 1;
for ( int i = 0 ; i < MAX_SPLITSCREEN_CLIENTS; ++i )
{
MEM_ALLOC_CREDIT();
m_SplitScreenPlayers[ i ] = new SplitPlayer_t();
SplitPlayer_t *sp = m_SplitScreenPlayers[ i ];
sp->m_bActive = ( i == 0 ) ? true : false;
sp->m_Client.m_bSplitScreenUser = ( i != 0 ) ? true : false;
}
return true;
}
void CSplitScreen::Shutdown()
{
Assert( ThreadInMainThread() );
for ( int i = 0; i < MAX_SPLITSCREEN_CLIENTS; ++i )
{
delete m_SplitScreenPlayers[ i ];
m_SplitScreenPlayers[ i ] = NULL;
}
}
bool CSplitScreen::AddBaseUser( int nSlot, int nPlayerIndex )
{
Assert( ThreadInMainThread() );
SplitPlayer_t *sp = m_SplitScreenPlayers[ nSlot ];
sp->m_bActive = true;
sp->m_Client.m_nSplitScreenSlot = nSlot;
return true;
}
bool CSplitScreen::AddSplitScreenUser( int nSlot, int nPlayerEntityIndex )
{
Assert( ThreadInMainThread() );
SplitPlayer_t *sp = m_SplitScreenPlayers[ nSlot ];
if ( sp->m_bActive == true )
{
Assert( sp->m_Client.m_nSplitScreenSlot == nSlot );
Assert( sp->m_Client.m_nPlayerSlot == nPlayerEntityIndex - 1 );
return true;
}
// Msg( "Attached %d to slot %d\n", nPlayerEntityIndex, nSlot );
// 0.0.0.0:0 signifies a bot. It'll plumb all the way down to winsock calls but it won't make them.
ns_address adr;
adr.SetAddrType( NSAT_NETADR );
adr.m_adr.SetIPAndPort( 0, 0 );
char szName[ 256 ];
Q_snprintf( szName, sizeof( szName), "SPLIT%d", nSlot );
sp->m_bActive = true;
sp->m_Client.Clear();
sp->m_Client.m_nPlayerSlot = nPlayerEntityIndex - 1;
sp->m_Client.m_nSplitScreenSlot = nSlot;
sp->m_Client.m_NetChannel = NET_CreateNetChannel( NS_CLIENT, &adr, szName, &sp->m_Client, NULL, true );
GetBaseLocalClient().m_NetChannel->AttachSplitPlayer( nSlot, sp->m_Client.m_NetChannel );
sp->m_Client.m_nViewEntity = nPlayerEntityIndex;
++m_nActiveSplitScreenUserCount;
SetDisconnecting( nSlot, false );
ClientDLL_OnSplitScreenStateChanged();
return true;
}
bool CSplitScreen::RemoveSplitScreenUser( int nSlot, int nPlayerIndex )
{
Assert( ThreadInMainThread() );
// Msg( "Detached %d from slot %d\n", nPlayerIndex, nSlot );
int idx = FindSplitPlayerSlot( nPlayerIndex );
if ( idx != -1 )
{
SplitPlayer_t *sp = m_SplitScreenPlayers[ idx ];
if ( sp->m_Client.m_NetChannel )
{
GetBaseLocalClient().m_NetChannel->DetachSplitPlayer( idx );
sp->m_Client.m_NetChannel->Shutdown( "RemoveSplitScreenUser" );
sp->m_Client.m_NetChannel = NULL;
}
sp->m_Client.m_nPlayerSlot = -1;
sp->m_bActive = false;
SetDisconnecting( nSlot, true );
--m_nActiveSplitScreenUserCount;
ClientDLL_OnSplitScreenStateChanged();
}
return true;
}
int CSplitScreen::GetActiveSplitScreenPlayerSlot()
{
#if !defined( SPLIT_SCREEN_STUBS )
SplitSlot_t *pSlot = GetSplitSlot();
int nSlot = pSlot->m_nActiveSplitScreenPlayer;
#if defined( _DEBUG )
if ( nSlot >= host_state.max_splitscreen_players_clientdll )
{
static bool warned = false;
if ( !warned )
{
warned = true;
Warning( "GetActiveSplitScreenPlayerSlot() returning bogus slot #%d\n", nSlot );
}
}
#endif
return nSlot;
#else
return 0;
#endif
}
int CSplitScreen::SetActiveSplitScreenPlayerSlot( int slot )
{
#if !defined( SPLIT_SCREEN_STUBS )
Assert( m_bInitialized );
slot = clamp( slot, 0, host_state.max_splitscreen_players_clientdll - 1 );
SplitSlot_t *pSlot = GetSplitSlot();
Assert( pSlot );
int old = pSlot->m_nActiveSplitScreenPlayer;
if ( slot == old )
return slot;
pSlot->m_nActiveSplitScreenPlayer = slot;
// Only change netchannel in main thread and only change vgui message context id in main thread (for now)
if ( pSlot->m_bMainThread )
{
if ( m_SplitScreenPlayers[ slot ] && m_SplitScreenPlayers[ 0 ] )
{
INetChannel *nc = m_SplitScreenPlayers[ slot ]->m_Client.m_NetChannel;
CBaseClientState &bcs = m_SplitScreenPlayers[ 0 ]->m_Client;
if ( bcs.m_NetChannel && nc )
{
bcs.m_NetChannel->SetActiveChannel( nc );
}
}
}
return old;
#else
return 0;
#endif
}
int CSplitScreen::GetNumSplitScreenPlayers()
{
return m_nActiveSplitScreenUserCount;
}
int CSplitScreen::GetSplitScreenPlayerEntity( int nSlot )
{
Assert( nSlot >= 0 && nSlot < host_state.max_splitscreen_players );
Assert( host_state.max_splitscreen_players <= MAX_SPLITSCREEN_CLIENTS );
if ( nSlot < 0 || nSlot >= host_state.max_splitscreen_players )
return -1;
if ( !m_SplitScreenPlayers[ nSlot ]->m_bActive )
return -1;
return m_SplitScreenPlayers[ nSlot ]->m_Client.m_nPlayerSlot + 1;
}
INetChannel *CSplitScreen::GetSplitScreenPlayerNetChan( int nSlot )
{
Assert( nSlot >= 0 && nSlot < host_state.max_splitscreen_players );
Assert( host_state.max_splitscreen_players <= MAX_SPLITSCREEN_CLIENTS );
if ( nSlot < 0 || nSlot >= host_state.max_splitscreen_players )
return NULL;
if ( !m_SplitScreenPlayers[ nSlot ]->m_bActive )
return NULL;
return m_SplitScreenPlayers[ nSlot ]->m_Client.m_NetChannel;
}
bool CSplitScreen::IsValidSplitScreenSlot( int nSlot )
{
Assert( host_state.max_splitscreen_players <= MAX_SPLITSCREEN_CLIENTS );
if ( nSlot < 0 || nSlot >= host_state.max_splitscreen_players )
return false;
return m_SplitScreenPlayers[ nSlot ]->m_bActive;
}
int CSplitScreen::FirstValidSplitScreenSlot()
{
return 0;
}
int CSplitScreen::NextValidSplitScreenSlot( int nPreviousSlot )
{
for ( ;; )
{
++nPreviousSlot;
if ( nPreviousSlot >= host_state.max_splitscreen_players )
{
return -1;
}
if ( m_SplitScreenPlayers[ nPreviousSlot ]->m_bActive )
{
break;
}
}
return nPreviousSlot;
}
int CSplitScreen::FindSplitPlayerSlot( int nPlayerEntityIndex )
{
int nPlayerSlot = nPlayerEntityIndex - 1;
Assert( host_state.max_splitscreen_players <= MAX_SPLITSCREEN_CLIENTS );
for ( int i = 1 ; i < host_state.max_splitscreen_players ; ++i )
{
if ( m_SplitScreenPlayers[ i ]->m_Client.m_nPlayerSlot == nPlayerSlot )
{
return i;
}
}
return -1;
}
bool CSplitScreen::IsDisconnecting( int nSlot )
{
Assert( nSlot >= 0 && nSlot < host_state.max_splitscreen_players );
Assert( host_state.max_splitscreen_players <= MAX_SPLITSCREEN_CLIENTS );
if ( nSlot < 0 || nSlot >= host_state.max_splitscreen_players )
return false;
return ( m_SplitScreenPlayers[ nSlot ]->m_Client.m_nSignonState == SIGNONSTATE_NONE ) ? true : false;
}
void CSplitScreen::SetDisconnecting( int nSlot, bool bState )
{
Assert( nSlot >= 0 && nSlot < host_state.max_splitscreen_players );
Assert( host_state.max_splitscreen_players <= MAX_SPLITSCREEN_CLIENTS );
if ( nSlot < 0 || nSlot >= host_state.max_splitscreen_players )
return;
Assert( nSlot != 0 );
m_SplitScreenPlayers[ nSlot ]->m_Client.m_nSignonState = bState ? SIGNONSTATE_NONE : SIGNONSTATE_FULL;
}
CClientState &CSplitScreen::GetLocalPlayer( int nSlot /*= -1*/ )
{
if ( nSlot == -1 )
{
Assert( IsLocalPlayerResolvable() );
return m_SplitScreenPlayers[ GetActiveSplitScreenPlayerSlot() ]->m_Client;
}
return m_SplitScreenPlayers[ nSlot ]->m_Client;
}
bool CSplitScreen::SetLocalPlayerIsResolvable( char const *pchContext, int line, bool bResolvable )
{
SplitSlot_t *pSlot = GetSplitSlot();
Assert( pSlot );
bool bPrev = pSlot->m_bLocalPlayerResolvable;
pSlot->m_bLocalPlayerResolvable = bResolvable;
return bPrev;
}
bool CSplitScreen::IsLocalPlayerResolvable()
{
#if defined( SPLIT_SCREEN_STUBS )
return true;
#else
SplitSlot_t *pSlot = GetSplitSlot();
return pSlot->m_bLocalPlayerResolvable;
#endif
}
// Singleton client state
CClientState &GetLocalClient( int nSlot /*= -1*/ )
{
return g_SplitScreenMgr.GetLocalPlayer( nSlot );
}
CClientState &GetBaseLocalClient()
{
return g_SplitScreenMgr.GetLocalPlayer( 0 );
}
| 26.787589 | 164 | 0.733428 | DannyParker0001 |
7798421161971d4c29008ced6e9b718cfc0ff5ca | 679 | cpp | C++ | day06/part2.cpp | Moremar/advent_of_code_2016 | dea264671fc2c31baa42b1282751dfd1ae071a7d | [
"Apache-2.0"
] | null | null | null | day06/part2.cpp | Moremar/advent_of_code_2016 | dea264671fc2c31baa42b1282751dfd1ae071a7d | [
"Apache-2.0"
] | null | null | null | day06/part2.cpp | Moremar/advent_of_code_2016 | dea264671fc2c31baa42b1282751dfd1ae071a7d | [
"Apache-2.0"
] | null | null | null | #include "part1.hpp"
#include "part2.hpp"
using namespace std;
string Part2::solve(const vector<string> &signals) {
vector<map<char, int>> freqs = Part1::getFreqs(signals);
// pick the least popular letter for each position
string corrected = "";
for (const auto freq : freqs) {
vector<pair<char, int>> toSort(freq.cbegin(), freq.cend());
// sort in the opposite order from part 1
sort(toSort.begin(), toSort.end(), [](pair<char, int> v1, pair<char, int> v2) {
return (v1.second < v2.second) || (v1.second == v2.second && v1.first > v2.first);
});
corrected += toSort[0].first;
}
return corrected;
}
| 32.333333 | 94 | 0.60972 | Moremar |
7799a55d53c8ef71110728812322ddeb84cd0ec8 | 1,910 | hpp | C++ | SpaceWars2/skills/Laser.hpp | su8ru/SpaceWars2 | 1aa9ecd7ab8217ae5df8c6499597c8cbc7ab9f40 | [
"Apache-2.0"
] | 2 | 2020-02-01T08:47:10.000Z | 2020-02-01T08:51:05.000Z | SpaceWars2/skills/Laser.hpp | subaru2003/SpaceWars2 | 1aa9ecd7ab8217ae5df8c6499597c8cbc7ab9f40 | [
"Apache-2.0"
] | 44 | 2019-06-03T11:46:56.000Z | 2019-08-06T16:20:15.000Z | SpaceWars2/skills/Laser.hpp | su8ru/SpaceWars2 | 1aa9ecd7ab8217ae5df8c6499597c8cbc7ab9f40 | [
"Apache-2.0"
] | 3 | 2019-06-13T17:42:12.000Z | 2019-06-14T23:36:45.000Z | #pragma once
#include <Siv3D.hpp>
#include "Bullet.hpp"
#include "../Scenes/Game.hpp"
class Laser final : public Bullet {
private:
bool isCharging = true;
int energy = 1;
Vec2 myPos;
bool isLeft;
bool isLInvalid = false;
bool isRInvalid = false;
static bool isLShooting;
static bool isRShooting;
static Optional<Sound> chargeSound[2];
static Optional<Sound> laserSound[2];
const static int CHARGE_TIME_LIMIT = 1000; // charge時間の上限
const static int WAITING_TIME = 100; // 実行までにかかるwaiting時間
const static int COOLDOWN_TIME = 1000; // 実行後のクールダウン時間(要検討)
RectF getShapeShotten(){
if(isLeft) return RectF(myPos - Vec2(0, energy), Config::WIDTH, energy * 2);
else return RectF(myPos - Vec2(Config::WIDTH, energy), Config::WIDTH, energy * 2);
}
Circle getShapeCharging(){
if(isLeft) return Circle(myPos + Vec2( 25 + energy, 0), energy);
else return Circle(myPos + Vec2(-25 - energy, 0), energy);
}
public:
Laser(Vec2 _pos, bool _isLeft) : Bullet(_pos, _isLeft) {
isLeft = _isLeft;
if (isLeft ? isLShooting : isRShooting) { // if another instance is already created and still alive...
(isLeft ? isLInvalid : isRInvalid) = true; // this laser is disabled
}
else {
(isLeft ? isLShooting : isRShooting) = true;
++(isLeft ? Data::LPlayer : Data::RPlayer).mainSkillCnt;
if (!chargeSound[0]) {
for (int i = 0; i < 2; i++ ) {
chargeSound[i].emplace(L"/8203");
laserSound[i].emplace(L"/8204");
}
}
chargeSound[isLeft]->setVolume(Config::MASTER_VOLUME * Config::CURSOR_VOLUME);
chargeSound[isLeft]->play();
}
}
~Laser() override {
if (!(isLeft ? isLInvalid : isRInvalid))
(isLeft ? isLShooting : isRShooting) = false;
laserSound[isLeft]->stop(1s);
};
bool update(Vec2 _myPos, Vec2 _oppPos) override;
void draw() override;
bool isVisible() override;
int getDamage(Circle _circle) override;
const static int bulletSpeed = 10;
};
| 28.507463 | 104 | 0.68534 | su8ru |
779a7d4470804b9abcde7bb29dd24179ad47b79d | 1,112 | hpp | C++ | contrib/autoboost/autoboost/context/fcontext.hpp | CaseyCarter/autowiring | 48e95a71308318c8ffb7ed1348e034fd9110f70c | [
"Apache-2.0"
] | 87 | 2015-01-18T00:43:06.000Z | 2022-02-11T17:40:50.000Z | contrib/autoboost/autoboost/context/fcontext.hpp | CaseyCarter/autowiring | 48e95a71308318c8ffb7ed1348e034fd9110f70c | [
"Apache-2.0"
] | 274 | 2015-01-03T04:50:49.000Z | 2021-03-08T09:01:09.000Z | contrib/autoboost/autoboost/context/fcontext.hpp | CaseyCarter/autowiring | 48e95a71308318c8ffb7ed1348e034fd9110f70c | [
"Apache-2.0"
] | 15 | 2015-09-30T20:58:43.000Z | 2020-12-19T21:24:56.000Z |
// Copyright Oliver Kowalke 2009.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef AUTOBOOST_CONTEXT_FCONTEXT_H
#define AUTOBOOST_CONTEXT_FCONTEXT_H
#if defined(__PGI)
#include <stdint.h>
#endif
#if defined(_WIN32_WCE)
typedef int intptr_t;
#endif
#include <autoboost/config.hpp>
#include <autoboost/cstdint.hpp>
#include <autoboost/context/detail/config.hpp>
#ifdef AUTOBOOST_HAS_ABI_HEADERS
# include AUTOBOOST_ABI_PREFIX
#endif
namespace autoboost {
namespace context {
typedef void* fcontext_t;
extern "C" AUTOBOOST_CONTEXT_DECL
intptr_t AUTOBOOST_CONTEXT_CALLDECL jump_fcontext( fcontext_t * ofc, fcontext_t nfc,
intptr_t vp, bool preserve_fpu = true);
extern "C" AUTOBOOST_CONTEXT_DECL
fcontext_t AUTOBOOST_CONTEXT_CALLDECL make_fcontext( void * sp, std::size_t size, void (* fn)( intptr_t) );
}}
#ifdef AUTOBOOST_HAS_ABI_HEADERS
# include AUTOBOOST_ABI_SUFFIX
#endif
#endif // AUTOBOOST_CONTEXT_FCONTEXT_H
| 24.173913 | 107 | 0.747302 | CaseyCarter |
77a0048f0fe674428e66ebd07ce03d67b0051e93 | 970 | hpp | C++ | src/afk/renderer/Model.hpp | christocs/ModelAnimation | d32941dec8f2ef54e96086319a00ca5cf783e2fa | [
"0BSD"
] | null | null | null | src/afk/renderer/Model.hpp | christocs/ModelAnimation | d32941dec8f2ef54e96086319a00ca5cf783e2fa | [
"0BSD"
] | null | null | null | src/afk/renderer/Model.hpp | christocs/ModelAnimation | d32941dec8f2ef54e96086319a00ca5cf783e2fa | [
"0BSD"
] | null | null | null | #pragma once
#include <filesystem>
#include <glob.h>
#include <vector>
#include <assimp/scene.h>
#include "afk/renderer/Animation.hpp"
#include "afk/renderer/Bone.hpp"
#include "afk/renderer/Mesh.hpp"
#include "afk/renderer/ModelNode.hpp"
#include "afk/renderer/Texture.hpp"
namespace Afk {
struct Model {
using Meshes = std::vector<Mesh>;
using Nodes = std::vector<ModelNode>;
using NodeMap = std::unordered_map<std::string, unsigned int>;
using Animations = std::unordered_map<std::string, Animation>;
Nodes nodes = {};
NodeMap node_map = {};
Animations animations = {};
Meshes meshes = {};
Bones bones = {};
BoneStringMap bone_map = {};
glm::mat4 global_inverse;
size_t root_node_index = 0;
std::filesystem::path file_path = {};
std::filesystem::path file_dir = {};
Model() = default;
Model(const std::filesystem::path &_file_path);
};
}
| 23.658537 | 69 | 0.630928 | christocs |
77a095bceba23eb22b7c337086cacc6130a19a8d | 2,177 | cc | C++ | history_gtest.cc | doj/few | cdaa53b08f73a901cd07022b92e20f02e9b7b91b | [
"MIT"
] | 2 | 2015-04-05T20:15:31.000Z | 2021-07-14T19:36:03.000Z | history_gtest.cc | doj/few | cdaa53b08f73a901cd07022b92e20f02e9b7b91b | [
"MIT"
] | null | null | null | history_gtest.cc | doj/few | cdaa53b08f73a901cd07022b92e20f02e9b7b91b | [
"MIT"
] | null | null | null | /* -*- mode: C++; c-basic-offset: 4; tab-width: 8; -*-
* vi: set shiftwidth=4 tabstop=8:
* :indentSize=4:tabSize=8:
*/
#include "gtest/gtest.h"
#include "history.h"
#if defined(_WIN32)
#include <io.h>
#include <stdio.h>
namespace {
int unlink(const std::string& fn)
{
return _unlink(fn.c_str());
}
int unlink(const std::wstring& fn)
{
return _wunlink(fn.c_str());
}
}
#else
#include <unistd.h>
#endif
TEST(History, can_cycle_through_history)
{
auto h = std::make_shared<History>();
const std::string eins = "1";
h->add(eins);
const std::string zwei = "2";
h->add(zwei);
const std::string drei = "3";
h->add(drei);
const std::string c = "c";
auto i = h->begin(c);
ASSERT_TRUE(i->atEnd());
ASSERT_EQ(c, i->next());
ASSERT_EQ(c, i->next());
ASSERT_TRUE(i->atEnd());
ASSERT_EQ(drei, i->prev());
ASSERT_FALSE(i->atEnd());
ASSERT_EQ(zwei, i->prev());
ASSERT_EQ(eins, i->prev());
ASSERT_EQ(eins, i->prev());
ASSERT_EQ(eins, i->prev());
ASSERT_FALSE(i->atEnd());
ASSERT_EQ(zwei, i->next());
ASSERT_EQ(drei, i->next());
ASSERT_EQ(c, i->next());
ASSERT_TRUE(i->atEnd());
ASSERT_EQ(c, i->next());
ASSERT_TRUE(i->atEnd());
}
TEST(History, can_save_and_load)
{
const std::string filename = "history.test";
unlink(filename.c_str());
auto h = std::make_shared<History>(filename);
const std::string eins = "1";
h->add(eins);
const std::string zwei = "2";
h->add(zwei);
const std::string drei = "3";
h->add(drei);
h = nullptr;
h = std::make_shared<History>(filename);
auto i = h->begin("");
ASSERT_EQ(drei, i->prev());
ASSERT_EQ(zwei, i->prev());
ASSERT_EQ(eins, i->prev());
auto fn = h->filename();
h = nullptr;
i = nullptr;
ASSERT_EQ(0, unlink(fn.c_str()));
}
TEST(History, empty_history_only_returns_initial_iterator_value)
{
auto h = std::make_shared<History>();
const std::string s = "s";
auto i = h->begin(s);
ASSERT_EQ(s, i->prev());
ASSERT_EQ(s, i->prev());
ASSERT_EQ(s, i->next());
ASSERT_EQ(s, i->prev());
ASSERT_TRUE(i->atEnd());
}
| 22.915789 | 64 | 0.582912 | doj |
77a2348dafc26ce71fc4ba976e5697322317c65e | 2,067 | cpp | C++ | src/draw/ArcProgress.cpp | charanyaarvind/StratifyAPI | adfd1bc8354489378d53c6acd77ebedad5790b4f | [
"BSD-3-Clause"
] | null | null | null | src/draw/ArcProgress.cpp | charanyaarvind/StratifyAPI | adfd1bc8354489378d53c6acd77ebedad5790b4f | [
"BSD-3-Clause"
] | null | null | null | src/draw/ArcProgress.cpp | charanyaarvind/StratifyAPI | adfd1bc8354489378d53c6acd77ebedad5790b4f | [
"BSD-3-Clause"
] | null | null | null | /*! \file */ //Copyright 2011-2018 Tyler Gilbert; All Rights Reserved
#include <cmath>
#include "sgfx.hpp"
#include "draw/ArcProgress.hpp"
using namespace draw;
ArcProgress::ArcProgress() {
m_offset = 0;
m_direction = 1;
}
void ArcProgress::draw_to_scale(const DrawingScaledAttr & attr){
//draw the progress bar on the bitmap with x, y at the top left corner
sg_point_t p = attr.point();
Dim d = attr.dim();
sg_region_t bounds;
s8 dir;
float xf, yf;
float xf_inner, yf_inner;
Point center(p.x + d.width()/2, p.y + d.height()/2);
sg_size_t rx = d.width()/2;
sg_size_t ry = d.height()/2;
sg_size_t rx_inner = rx*2/3;
sg_size_t ry_inner = ry*2/3;
Point arc;
Point arc_inner;
Point first_point;
u32 i;
sg_int_t x_max;
u32 progress;
u32 points = 4 * (d.width() + d.height())/2;
float two_pi = 2.0 * M_PI;
float half_pi = M_PI / 2.0;
float theta;
float offset = m_offset * two_pi / 360;
progress = (points * value()) / max();
if( progress > points ){
progress = points;
}
if( m_direction > 0 ){
dir = 1;
} else {
dir = -1;
}
x_max = 0;
i = 0;
do {
theta = (two_pi * i*dir / points - half_pi) + offset;
xf = rx * cosf(theta);
yf = ry * sinf(theta);
xf_inner = rx_inner * cosf(theta);
yf_inner = ry_inner * sinf(theta);
arc.set(xf, yf);
arc = arc + center;
if( arc.x() > x_max ){
x_max = arc.x();
}
arc_inner.set(xf_inner, yf_inner);
arc_inner = arc_inner + center;
if( i == 0 ){
attr.bitmap().draw_line(arc_inner, arc);
}
if( i == 1 ){
first_point = arc;
}
attr.bitmap().draw_pixel(arc);
attr.bitmap().draw_pixel(arc_inner);
i++;
} while( i < progress );
attr.bitmap().draw_line(arc_inner, arc);
if( progress > 0 && (attr.bitmap().pen_flags() & Pen::FLAG_IS_FILL) ){
theta = (two_pi * progress / (2*points) - half_pi) + offset;
xf = ((rx + rx_inner)/2) * cosf(theta);
yf = ((ry + ry_inner)/2)* sinf(theta);
arc.set(xf, yf);
arc = arc + center;
bounds = attr.region();
//attr.bitmap().draw_pixel(arc);
attr.bitmap().draw_pour(arc, bounds);
}
}
| 19.5 | 71 | 0.62119 | charanyaarvind |
77aa54d0679caf80d7343fbd65cd3b94af1a8b13 | 3,063 | cpp | C++ | src/oems/oems_sorter.cpp | ref2401/oems | 00a295d01280211c3298ddacda0e0937471917ab | [
"MIT"
] | 3 | 2019-12-10T05:53:40.000Z | 2021-09-13T17:54:30.000Z | src/oems/oems_sorter.cpp | ref2401/oems | 00a295d01280211c3298ddacda0e0937471917ab | [
"MIT"
] | 1 | 2017-10-23T12:12:22.000Z | 2017-10-23T12:12:22.000Z | src/oems/oems_sorter.cpp | ref2401/oems | 00a295d01280211c3298ddacda0e0937471917ab | [
"MIT"
] | null | null | null | #include "oems/oems_sorter.h"
#include <cassert>
namespace {
using namespace oems;
void copy_data_from_gpu(ID3D11Device* p_device, ID3D11DeviceContext* p_ctx,
ID3D11Buffer* p_buffer_src, float* p_dest, size_t byte_count)
{
assert(p_device);
assert(p_ctx);
assert(p_buffer_src);
assert(p_dest);
assert(byte_count > 0);
const UINT bc = UINT(byte_count);
assert(size_t(bc) == byte_count);
// create stagint buffer and fill it with p_buffer_src's contents ---
com_ptr<ID3D11Buffer >p_buffer_staging = make_buffer(p_device, bc,
D3D11_USAGE_STAGING, 0, D3D11_CPU_ACCESS_READ);
p_ctx->CopyResource(p_buffer_staging, p_buffer_src);
// fill p_dest using the staging buffer ---
D3D11_MAPPED_SUBRESOURCE map;
HRESULT hr = p_ctx->Map(p_buffer_staging, 0, D3D11_MAP_READ, 0, &map);
THROW_IF_DX_DEVICE_ERROR(hr, p_device);
std::memcpy(p_dest, map.pData, byte_count);
p_ctx->Unmap(p_buffer_staging, 0);
}
com_ptr<ID3D11Buffer> copy_data_to_gpu(ID3D11Device* p_device, const float* p_list, size_t byte_count)
{
assert(p_device);
assert(p_list);
assert(byte_count > 0);
const UINT bc = UINT(byte_count);
assert(size_t(bc) == byte_count);
const D3D11_SUBRESOURCE_DATA data = { p_list, 0, 0 };
return make_buffer(p_device, &data, bc, D3D11_USAGE_DEFAULT, D3D11_BIND_UNORDERED_ACCESS);
}
} // namespace
namespace oems {
// ---- oems_sorter ----
oems_sorter::oems_sorter(ID3D11Device* p_device, ID3D11DeviceContext* p_ctx, ID3D11Debug* p_debug)
: p_device_(p_device), p_ctx_(p_ctx), p_debug_(p_debug)
{
assert(p_device);
assert(p_ctx);
assert(p_debug); // p_debug == nullptr in Release mode.
oems_shader_ = hlsl_compute(p_device, "../../data/oems.compute.hlsl");
}
void oems_sorter::sort(std::vector<float>& list)
{
assert(list.size() > 4);
const size_t byte_count = sizeof(float) * list.size();
const UINT item_count = UINT(list.size());
// copy list to the gpu & set uav ---
com_ptr<ID3D11Buffer> p_buffer = copy_data_to_gpu(p_device_, list.data(), byte_count);
com_ptr<ID3D11UnorderedAccessView> p_buffer_uav;
D3D11_UNORDERED_ACCESS_VIEW_DESC uav_desc = {};
uav_desc.Format = DXGI_FORMAT_R32_FLOAT;
uav_desc.ViewDimension = D3D11_UAV_DIMENSION_BUFFER;
uav_desc.Buffer.FirstElement = 0;
uav_desc.Buffer.NumElements = item_count;
HRESULT hr = p_device_->CreateUnorderedAccessView(p_buffer.ptr, &uav_desc, &p_buffer_uav.ptr);
THROW_IF_DX_ERROR(hr);
// (sort) setup compute pipeline & dispatch work ---
p_ctx_->CSSetShader(oems_shader_.p_shader, nullptr, 0);
p_ctx_->CSSetUnorderedAccessViews(0, 1, &p_buffer_uav.ptr, nullptr);
#ifdef OEMS_DEBUG
hr = p_debug_->ValidateContextForDispatch(p_ctx_);
THROW_IF_DX_ERROR(hr);
#endif
p_ctx_->Dispatch(1, 1, 1);
ID3D11UnorderedAccessView* uav_list[1] = { nullptr };
p_ctx_->CSSetUnorderedAccessViews(0, 1, uav_list, nullptr);
// copy list from the gpu ---
copy_data_from_gpu(p_device_, p_ctx_, p_buffer, list.data(), byte_count);
}
} // namespace oems
| 29.737864 | 103 | 0.726086 | ref2401 |
77acf87696718a89aa33813c79f6336f94a157d4 | 508 | hpp | C++ | src/ir/nodes.hpp | traplol/malang | 3c02f4f483b7580a557841c31a65bf190fd1228f | [
"MIT"
] | 4 | 2017-10-31T14:01:58.000Z | 2019-07-16T04:53:32.000Z | src/ir/nodes.hpp | traplol/malang | 3c02f4f483b7580a557841c31a65bf190fd1228f | [
"MIT"
] | null | null | null | src/ir/nodes.hpp | traplol/malang | 3c02f4f483b7580a557841c31a65bf190fd1228f | [
"MIT"
] | 2 | 2018-01-23T12:59:07.000Z | 2019-07-16T04:53:39.000Z | #ifndef MALANG_IR_NODES_HPP
#define MALANG_IR_NODES_HPP
#include "ir.hpp"
#include "ir_noop.hpp"
#include "ir_block.hpp"
#include "ir_assignment.hpp"
#include "ir_binary_ops.hpp"
#include "ir_branch.hpp"
#include "ir_call.hpp"
#include "ir_label.hpp"
#include "ir_memory.hpp"
#include "ir_primitives.hpp"
#include "ir_return.hpp"
#include "ir_symbol.hpp"
#include "ir_unary_ops.hpp"
#include "ir_values.hpp"
#include "ir_discard_result.hpp"
#include "ir_member_access.hpp"
#endif /* MALANG_IR_NODES_HPP */
| 23.090909 | 32 | 0.777559 | traplol |
77bee52477c3f9529bafa7fafcfe5311d8d08699 | 5,391 | cpp | C++ | tests/unit/offload/OffloadFreeListTest.cpp | gjerecze/daqdb | ebab10f3ef2a64d541043b7378a951af294d44cb | [
"Apache-2.0"
] | 22 | 2019-02-08T17:23:12.000Z | 2021-10-12T06:35:37.000Z | tests/unit/offload/OffloadFreeListTest.cpp | gjerecze/daqdb | ebab10f3ef2a64d541043b7378a951af294d44cb | [
"Apache-2.0"
] | 8 | 2019-02-11T06:30:47.000Z | 2020-04-22T09:49:44.000Z | tests/unit/offload/OffloadFreeListTest.cpp | gjerecze/daqdb | ebab10f3ef2a64d541043b7378a951af294d44cb | [
"Apache-2.0"
] | 10 | 2019-02-11T10:26:52.000Z | 2019-09-16T20:49:25.000Z | /**
* Copyright (c) 2019 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cstdint>
#include "../../lib/offload/OffloadFreeList.cpp"
#include "../../lib/pmem/RTree.h"
#define BOOST_TEST_MAIN
#include <boost/filesystem.hpp>
#include <boost/test/unit_test.hpp>
#include <fakeit.hpp>
namespace ut = boost::unit_test;
using namespace fakeit;
#define BOOST_TEST_DETECT_MEMORY_LEAK 1
#define TEST_POOL_FREELIST_FILENAME "test_file.pm"
#define TEST_POOL_FREELIST_SIZE 10ULL * 1024 * 1024
#define LAYOUT "queue"
#define CREATE_MODE_RW (S_IWUSR | S_IRUSR)
#define FREELIST_MAX_LBA 512
pool<DaqDB::OffloadFreeList> *g_offloadFreeList = nullptr;
bool txAbortPred(const pmem::manual_tx_abort &ex) { return true; }
struct OffloadFreeListGlobalFixture {
OffloadFreeListGlobalFixture() {
if (boost::filesystem::exists(TEST_POOL_FREELIST_FILENAME))
boost::filesystem::remove(TEST_POOL_FREELIST_FILENAME);
offloadFreeList = pool<DaqDB::OffloadFreeList>::create(
TEST_POOL_FREELIST_FILENAME, LAYOUT, TEST_POOL_FREELIST_SIZE,
CREATE_MODE_RW);
g_offloadFreeList = &offloadFreeList;
}
~OffloadFreeListGlobalFixture() {
if (boost::filesystem::exists(TEST_POOL_FREELIST_FILENAME))
boost::filesystem::remove(TEST_POOL_FREELIST_FILENAME);
}
pool<DaqDB::OffloadFreeList> offloadFreeList;
};
BOOST_GLOBAL_FIXTURE(OffloadFreeListGlobalFixture);
struct OffloadFreeListTestFixture {
OffloadFreeListTestFixture() {
freeLbaList = g_offloadFreeList->get_root().get();
}
~OffloadFreeListTestFixture() {
if (freeLbaList != nullptr)
freeLbaList->clear(*g_offloadFreeList);
freeLbaList->maxLba = 0;
}
DaqDB::OffloadFreeList *freeLbaList = nullptr;
};
BOOST_FIXTURE_TEST_CASE(GetLbaInit, OffloadFreeListTestFixture) {
freeLbaList->push(*g_offloadFreeList, -1);
freeLbaList->maxLba = FREELIST_MAX_LBA;
auto firstLBA = freeLbaList->get(*g_offloadFreeList);
BOOST_CHECK_EQUAL(firstLBA, 1);
}
BOOST_FIXTURE_TEST_CASE(GetLbaInitPhase, OffloadFreeListTestFixture) {
freeLbaList->push(*g_offloadFreeList, -1);
freeLbaList->maxLba = FREELIST_MAX_LBA;
const int lbaCount = 100;
uint8_t index;
long lba = 0;
for (index = 0; index < lbaCount; index++)
lba = freeLbaList->get(*g_offloadFreeList);
BOOST_CHECK_EQUAL(lba, lbaCount);
}
BOOST_FIXTURE_TEST_CASE(GetLbaAfterInit_MaxLba_NotSet,
OffloadFreeListTestFixture) {
freeLbaList->push(*g_offloadFreeList, -1);
BOOST_CHECK_EXCEPTION(freeLbaList->get(*g_offloadFreeList),
pmem::manual_tx_abort, txAbortPred);
}
BOOST_FIXTURE_TEST_CASE(GetLastInitLba, OffloadFreeListTestFixture) {
freeLbaList->push(*g_offloadFreeList, -1);
freeLbaList->maxLba = FREELIST_MAX_LBA;
long lba = 0;
unsigned int index;
for (index = 0; index < FREELIST_MAX_LBA - 1; index++)
lba = freeLbaList->get(*g_offloadFreeList);
BOOST_CHECK_EQUAL(lba, index);
}
BOOST_FIXTURE_TEST_CASE(GetLbaAfterInit_FirstLba, OffloadFreeListTestFixture) {
freeLbaList->push(*g_offloadFreeList, -1);
freeLbaList->maxLba = FREELIST_MAX_LBA;
long lba = 0;
unsigned int index;
for (index = 0; index < FREELIST_MAX_LBA; index++)
lba = freeLbaList->get(*g_offloadFreeList);
BOOST_CHECK_EQUAL(lba, 0);
}
BOOST_FIXTURE_TEST_CASE(GetLbaAfterInit_CheckRemoved,
OffloadFreeListTestFixture) {
freeLbaList->push(*g_offloadFreeList, -1);
freeLbaList->maxLba = FREELIST_MAX_LBA;
const long freeElementLba = 100;
long lba = 0;
unsigned int index;
for (index = 0; index < FREELIST_MAX_LBA; index++)
lba = freeLbaList->get(*g_offloadFreeList);
freeLbaList->push(*g_offloadFreeList, freeElementLba);
lba = freeLbaList->get(*g_offloadFreeList);
BOOST_CHECK_EQUAL(lba, freeElementLba);
freeLbaList->push(*g_offloadFreeList, freeElementLba + 1);
lba = freeLbaList->get(*g_offloadFreeList);
BOOST_CHECK_EQUAL(lba, freeElementLba + 1);
freeLbaList->push(*g_offloadFreeList, freeElementLba);
freeLbaList->push(*g_offloadFreeList, freeElementLba + 1);
lba = freeLbaList->get(*g_offloadFreeList);
BOOST_CHECK_EQUAL(lba, freeElementLba);
lba = freeLbaList->get(*g_offloadFreeList);
BOOST_CHECK_EQUAL(lba, freeElementLba + 1);
}
BOOST_FIXTURE_TEST_CASE(GetLbaAfterInit_FullDisk, OffloadFreeListTestFixture) {
freeLbaList->push(*g_offloadFreeList, -1);
freeLbaList->maxLba = FREELIST_MAX_LBA;
unsigned int index;
for (index = 0; index < FREELIST_MAX_LBA; index++)
freeLbaList->get(*g_offloadFreeList);
BOOST_CHECK_EXCEPTION(freeLbaList->get(*g_offloadFreeList),
pmem::manual_tx_abort, txAbortPred);
}
| 32.089286 | 79 | 0.717863 | gjerecze |
77cbbdd518320c2ccef95b126826213b3f82d59e | 14,526 | cpp | C++ | src/terrain/sources/proland/dem/ResidualProducer.cpp | stormbirds/Proland-4.0 | fdff3642e36c56af8ec5f9299166a3d4bf36d33a | [
"Unlicense"
] | 99 | 2015-01-14T21:18:20.000Z | 2021-12-01T09:42:15.000Z | src/terrain/sources/proland/dem/ResidualProducer.cpp | stormbirds/Proland-4.0 | fdff3642e36c56af8ec5f9299166a3d4bf36d33a | [
"Unlicense"
] | null | null | null | src/terrain/sources/proland/dem/ResidualProducer.cpp | stormbirds/Proland-4.0 | fdff3642e36c56af8ec5f9299166a3d4bf36d33a | [
"Unlicense"
] | 46 | 2015-04-03T12:38:31.000Z | 2021-09-26T02:38:56.000Z | /*
* Proland: a procedural landscape rendering library.
* Copyright (c) 2008-2011 INRIA
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* Proland is distributed under a dual-license scheme.
* You can obtain a specific license from Inria: [email protected].
*/
/*
* Authors: Eric Bruneton, Antoine Begault, Guillaume Piolat.
*/
#include "proland/dem/ResidualProducer.h"
#include <fstream>
#include <sstream>
#include "tiffio.h"
#include "ork/core/Logger.h"
#include "ork/resource/ResourceTemplate.h"
#include "proland/producer/CPUTileStorage.h"
#include "proland/util/mfs.h"
#include <pthread.h>
#include <cstring>
using namespace std;
using namespace ork;
namespace proland
{
//#define SINGLE_FILE
#define MAX_TILE_SIZE 256
void *ResidualProducer::key = NULL;
void residualDelete(void* data)
{
delete[] (unsigned char*) data;
}
ResidualProducer::ResidualProducer(ptr<TileCache> cache, const char *name, int deltaLevel, float zscale) :
TileProducer("ResidualProducer", "CreateResidualTile")
{
init(cache, name, deltaLevel, zscale);
}
ResidualProducer::ResidualProducer() : TileProducer("ResidualProducer", "CreateResidualTile")
{
}
void ResidualProducer::init(ptr<TileCache> cache, const char *name, int deltaLevel, float zscale)
{
TileProducer::init(cache, false);
this->name = name;
if (strlen(name) == 0) {
this->tileFile = NULL;
this->minLevel = 0;
this->maxLevel = 32;
this->rootLevel = 0;
this->deltaLevel = 0;
this->rootTx = 0;
this->rootTy = 0;
this->scale = 1.0;
} else {
fopen(&tileFile, name, "rb");
if (tileFile == NULL) {
if (Logger::ERROR_LOGGER != NULL) {
Logger::ERROR_LOGGER->log("DEM", "Cannot open file '" + string(name) + "'");
}
maxLevel = -1;
scale = 1.0;
} else {
fread(&minLevel, sizeof(int), 1, tileFile);
fread(&maxLevel, sizeof(int), 1, tileFile);
fread(&tileSize, sizeof(int), 1, tileFile);
fread(&rootLevel, sizeof(int), 1, tileFile);
fread(&rootTx, sizeof(int), 1, tileFile);
fread(&rootTy, sizeof(int), 1, tileFile);
fread(&scale, sizeof(float), 1, tileFile);
}
this->deltaLevel = rootLevel == 0 ? deltaLevel : 0;
scale = scale * zscale;
int ntiles = minLevel + ((1 << (max(maxLevel - minLevel, 0) * 2 + 2)) - 1) / 3;
header = sizeof(float) + sizeof(int) * (6 + ntiles * 2);
offsets = new unsigned int[ntiles * 2];
if (tileFile != NULL) {
fread(offsets, sizeof(unsigned int) * ntiles * 2, 1, tileFile);
#ifndef SINGLE_FILE
fclose(tileFile);
tileFile = NULL;
#endif
}
if (key == NULL) {
key = new pthread_key_t;
pthread_key_create((pthread_key_t*) key, residualDelete);
}
assert(tileSize + 5 < MAX_TILE_SIZE);
assert(deltaLevel <= minLevel);
#ifdef SINGLE_FILE
mutex = new pthread_mutex_t;
pthread_mutex_init((pthread_mutex_t*) mutex, NULL);
#endif
}
}
ResidualProducer::~ResidualProducer()
{
#ifdef SINGLE_FILE
fclose(tileFile);
pthread_mutex_destroy((pthread_mutex_t*) mutex);
delete (pthread_mutex_t*) mutex;
#endif
delete[] offsets;
}
int ResidualProducer::getBorder()
{
return 2;
}
int ResidualProducer::getMinLevel()
{
return minLevel;
}
int ResidualProducer::getDeltaLevel()
{
return deltaLevel;
}
void ResidualProducer::addProducer(ptr<ResidualProducer> p)
{
producers.push_back(p);
}
bool ResidualProducer::hasTile(int level, int tx, int ty)
{
int l = level + deltaLevel - rootLevel;
if (l >= 0 && (tx >> l) == rootTx && (ty >> l) == rootTy) {
if (l <= maxLevel) {
return true;
}
for (unsigned int i = 0; i < producers.size(); ++i) {
if (producers[i]->hasTile(level + deltaLevel, tx, ty)) {
return true;
}
}
}
return false;
}
bool ResidualProducer::doCreateTile(int level, int tx, int ty, TileStorage::Slot *data)
{
int l = level + deltaLevel - rootLevel;
if (l >= 0 && (tx >> l) == rootTx && (ty >> l) == rootTy) {
if (l > maxLevel) {
for (unsigned int i = 0; i < producers.size(); ++i) {
producers[i]->doCreateTile(level + deltaLevel, tx, ty, data);
}
return true;
}
} else {
return true;
}
if (Logger::DEBUG_LOGGER != NULL) {
ostringstream oss;
oss << "Residual tile " << getId() << " " << level << " " << tx << " " << ty;
Logger::DEBUG_LOGGER->log("DEM", oss.str());
}
level = l;
tx = tx - (rootTx << level);
ty = ty - (rootTy << level);
CPUTileStorage<float>::CPUSlot *cpuData = dynamic_cast<CPUTileStorage<float>::CPUSlot*>(data);
assert(cpuData != NULL);
assert(dynamic_cast<CPUTileStorage<float>*>(cpuData->getOwner())->getChannels() == 1);
if ((int) name.size() == 0) {
tileSize = cpuData->getOwner()->getTileSize() - 5;
readTile(level, tx, ty, NULL, NULL, NULL, cpuData->data);
} else {
assert(cpuData->getOwner()->getTileSize() == tileSize + 5);
unsigned char *tsData = (unsigned char*) pthread_getspecific(*((pthread_key_t*) key));
if (tsData == NULL) {
tsData = new unsigned char[MAX_TILE_SIZE * MAX_TILE_SIZE * 4];
pthread_setspecific(*((pthread_key_t*) key), tsData);
}
unsigned char *compressedData = tsData;
unsigned char *uncompressedData = tsData + MAX_TILE_SIZE * MAX_TILE_SIZE * 2;
if (deltaLevel > 0 && level == deltaLevel) {
float *tmp = new float[(tileSize + 5) * (tileSize + 5)];
readTile(0, 0, 0, compressedData, uncompressedData, NULL, cpuData->data);
for (int i = 1; i <= deltaLevel; ++i) {
upsample(i, 0, 0, cpuData->data, tmp);
readTile(i, 0, 0, compressedData, uncompressedData, tmp, cpuData->data);
}
delete[] tmp;
} else {
readTile(level, tx, ty, compressedData, uncompressedData, NULL, cpuData->data);
}
}
return true;
}
void ResidualProducer::swap(ptr<ResidualProducer> p)
{
TileProducer::swap(p);
std::swap(name, p->name);
std::swap(tileSize, p->tileSize);
std::swap(rootLevel, p->rootLevel);
std::swap(deltaLevel, p->deltaLevel);
std::swap(rootTx, p->rootTx);
std::swap(rootTy, p->rootTy);
std::swap(minLevel, p->minLevel);
std::swap(maxLevel, p->maxLevel);
std::swap(scale, p->scale);
std::swap(header, p->header);
std::swap(offsets, p->offsets);
std::swap(mutex, p->mutex);
std::swap(tileFile, p->tileFile);
std::swap(producers, p->producers);
}
int ResidualProducer::getTileSize(int level)
{
return level < minLevel ? tileSize >> (minLevel - level) : tileSize;
}
int ResidualProducer::getTileId(int level, int tx, int ty)
{
if (level < minLevel) {
return level;
} else {
int l = max(level - minLevel, 0);
return minLevel + tx + ty * (1 << l) + ((1 << (2 * l)) - 1) / 3;
}
}
void ResidualProducer::readTile(int level, int tx, int ty,
unsigned char* compressedData, unsigned char *uncompressedData,
float *tile, float *result)
{
int tilesize = getTileSize(level) + 5;
if ((int) name.size() == 0) {
if (tile != NULL) {
for (int j = 0; j < tilesize; ++j) {
for (int i = 0; i < tilesize; ++i) {
result[i + j * (tileSize + 5)] = tile[i + j * (tileSize + 5)];
}
}
} else {
for (int j = 0; j < tilesize; ++j) {
for (int i = 0; i < tilesize; ++i) {
result[i + j * (tileSize + 5)] = 0.f;
}
}
}
} else {
int tileid = getTileId(level, tx, ty);
int fsize = offsets[2 * tileid + 1] - offsets[2 * tileid];
assert(fsize < (tileSize + 5) * (tileSize + 5) * 2);
#ifdef SINGLE_FILE
pthread_mutex_lock((pthread_mutex_t*) mutex);
fseek64(tileFile, header + offsets[2 * tileid], SEEK_SET);
fread(compressedData, fsize, 1, tileFile);
pthread_mutex_unlock((pthread_mutex_t*) mutex);
#else
FILE *file;
fopen(&file, name.c_str(), "rb");
fseek64(file, header + offsets[2 * tileid], SEEK_SET);
fread(compressedData, fsize, 1, file);
fclose(file);
#endif
/*ifstream fs(name.c_str(), ios::binary);
fs.seekg(header + offsets[2 * tileid], ios::beg);
fs.read((char*) compressedData, fsize);
fs.close();*/
// TODO compare perfs FILE vs ifstream vs mmap
mfs_file fd;
mfs_open(compressedData, fsize, (char *)"r", &fd);
TIFF* tf = TIFFClientOpen("name", "r", &fd,
(TIFFReadWriteProc) mfs_read, (TIFFReadWriteProc) mfs_write, (TIFFSeekProc) mfs_lseek,
(TIFFCloseProc) mfs_close, (TIFFSizeProc) mfs_size, (TIFFMapFileProc) mfs_map,
(TIFFUnmapFileProc) mfs_unmap);
TIFFReadEncodedStrip(tf, 0, uncompressedData, (tsize_t) -1);
TIFFClose(tf);
if (tile != NULL) {
for (int j = 0; j < tilesize; ++j) {
for (int i = 0; i < tilesize; ++i) {
int off = 2 * (i + j * tilesize);
int toff = i + j * (tileSize + 5);
short z = short(uncompressedData[off + 1]) << 8 | short(uncompressedData[off]);
result[toff] = tile[toff] + z * scale;
}
}
} else {
for (int j = 0; j < tilesize; ++j) {
for (int i = 0; i < tilesize; ++i) {
int off = 2 * (i + j * tilesize);
short z = short(uncompressedData[off + 1]) << 8 | short(uncompressedData[off]);
result[i + j * (tileSize + 5)] = z * scale;
}
}
}
}
}
void ResidualProducer::upsample(int level, int tx, int ty, float *parentTile, float *result)
{
int n = tileSize + 5;
int tilesize = getTileSize(level);
int px = 1 + (tx % 2) * tilesize / 2;
int py = 1 + (ty % 2) * tilesize / 2;
for (int j = 0; j <= tilesize + 4; ++j) {
for (int i = 0; i <= tilesize + 4; ++i) {
float z;
if (j%2 == 0) {
if (i%2 == 0) {
z = parentTile[i/2+px + (j/2+py)*n];
} else {
float z0 = parentTile[i/2+px-1 + (j/2+py)*n];
float z1 = parentTile[i/2+px + (j/2+py)*n];
float z2 = parentTile[i/2+px+1 + (j/2+py)*n];
float z3 = parentTile[i/2+px+2 + (j/2+py)*n];
z = ((z1+z2)*9-(z0+z3))/16;
}
} else {
if (i%2 == 0) {
float z0 = parentTile[i/2+px + (j/2-1+py)*n];
float z1 = parentTile[i/2+px + (j/2+py)*n];
float z2 = parentTile[i/2+px + (j/2+1+py)*n];
float z3 = parentTile[i/2+px + (j/2+2+py)*n];
z = ((z1+z2)*9-(z0+z3))/16;
} else {
int di, dj;
z = 0.0;
for (dj = -1; dj <= 2; ++dj) {
float f = dj == -1 || dj == 2 ? -1/16.0f : 9/16.0f;
for (di = -1; di <= 2; ++di) {
float g = di == -1 || di == 2 ? -1/16.0f : 9/16.0f;
z += f*g*parentTile[i/2+di+px + (j/2+dj+py)*n];
}
}
}
}
int off = i + j * n;
result[off] = z;
}
}
}
void ResidualProducer::init(ptr<ResourceManager> manager, Resource *r, const string &name, ptr<ResourceDescriptor> desc, const TiXmlElement *e)
{
e = e == NULL ? desc->descriptor : e;
ptr<TileCache> cache;
string file;
int deltaLevel = 0;
float zscale = 1.0;
cache = manager->loadResource(r->getParameter(desc, e, "cache")).cast<TileCache>();
if (e->Attribute("file") != NULL) {
file = r->getParameter(desc, e, "file");
file = manager->getLoader()->findResource(file);
}
if (e->Attribute("scale") != NULL) {
r->getFloatParameter(desc, e, "scale", &zscale);
}
if (e->Attribute("delta") != NULL) {
r->getIntParameter(desc, e, "delta", &deltaLevel);
}
init(cache, file.c_str(), deltaLevel, zscale);
const TiXmlNode *n = e->FirstChild();
while (n != NULL) {
const TiXmlElement *f = n->ToElement();
if (f != NULL) {
if (strncmp(f->Value(), "residualProducer", 16) == 0) {
addProducer(ResourceFactory::getInstance()->create(manager, f->Value(), desc, f).cast<ResidualProducer>());
} else {
if (Logger::ERROR_LOGGER != NULL) {
Resource::log(Logger::ERROR_LOGGER, desc, f, "Invalid subelement");
}
throw exception();
}
}
n = n->NextSibling();
}
}
class ResidualProducerResource : public ResourceTemplate<2, ResidualProducer>
{
public:
ResidualProducerResource(ptr<ResourceManager> manager, const string &name, ptr<ResourceDescriptor> desc, const TiXmlElement *e = NULL) :
ResourceTemplate<2, ResidualProducer>(manager, name, desc)
{
e = e == NULL ? desc->descriptor : e;
checkParameters(desc, e, "name,cache,file,delta,scale,");
init(manager, this, name, desc, e);
}
};
extern const char residualProducer[] = "residualProducer";
static ResourceFactory::Type<residualProducer, ResidualProducerResource> ResidualProducerType;
}
| 33.088838 | 143 | 0.547226 | stormbirds |
77d413c3e92109973099b4dd060302a7b5cece06 | 1,366 | cpp | C++ | Src/Source/GoToLineWindow.cpp | Sylvain78/BeTeX | 4624602987dd0f2790280c69f380661a03a03180 | [
"MIT"
] | null | null | null | Src/Source/GoToLineWindow.cpp | Sylvain78/BeTeX | 4624602987dd0f2790280c69f380661a03a03180 | [
"MIT"
] | null | null | null | Src/Source/GoToLineWindow.cpp | Sylvain78/BeTeX | 4624602987dd0f2790280c69f380661a03a03180 | [
"MIT"
] | null | null | null | #include "GoToLineWindow.h"
using namespace InterfaceConstants;
GoToLineWindow::GoToLineWindow(BRect r,BMessenger* messenger) : BWindow(r,"Go To Line...",B_FLOATING_WINDOW,B_NOT_ZOOMABLE|B_NOT_RESIZABLE)
{
SetFeel(B_NORMAL_WINDOW_FEEL);
parent = new BView(Bounds(),"parent",B_FOLLOW_ALL_SIDES,B_WILL_DRAW);
parent->SetViewColor(ui_color(B_PANEL_BACKGROUND_COLOR));
AddChild(parent);
msgr = messenger;
r = Bounds();
num = new BTextControl(BRect(5,10,40,30),"num",NULL,NULL,NULL);
parent->AddChild(num);
num->MakeFocus(true);
go = new BButton(BRect(55,8,95,28),"gogogadgetbutton","Go",new BMessage(K_GTL_WINDOW_GO));
parent->AddChild(go);
go->MakeDefault(true);
}
GoToLineWindow::~GoToLineWindow()
{
delete msgr;
}
void GoToLineWindow::MessageReceived(BMessage* msg)
{
switch(msg->what)
{
case K_GTL_WINDOW_GO:
{
BMessage* linemsg = new BMessage(K_GTL_WINDOW_GO);
BString text;
text << num->Text();
bool IsNumeric=true;
for(int i=0;i<text.Length();i++)
{
if(!isdigit(text[i]))
{
IsNumeric = false;
}
}
if(IsNumeric && linemsg->AddInt32("line",atoi(text.String())-1) == B_OK)
{
msgr->SendMessage(linemsg);
Quit();
}
}break;
default:
BWindow::MessageReceived(msg);
}
}
void GoToLineWindow::Quit()
{
msgr->SendMessage(new BMessage(K_GTL_WINDOW_QUIT));
BWindow::Quit();
}
| 22.032258 | 139 | 0.691069 | Sylvain78 |
77e18c4760e88a5beeacc54db569ee874a580847 | 1,501 | cpp | C++ | leetcode/Array Pair Sum Divisibility Problem.cpp | vkashkumar/Competitive-Programming | c457e745208c0ca3e45b1ffce254a21504533f51 | [
"MIT"
] | 2 | 2019-01-30T12:45:18.000Z | 2021-05-06T19:02:51.000Z | leetcode/Array Pair Sum Divisibility Problem.cpp | vkashkumar/Competitive-Programming | c457e745208c0ca3e45b1ffce254a21504533f51 | [
"MIT"
] | null | null | null | leetcode/Array Pair Sum Divisibility Problem.cpp | vkashkumar/Competitive-Programming | c457e745208c0ca3e45b1ffce254a21504533f51 | [
"MIT"
] | 3 | 2020-10-02T15:42:04.000Z | 2022-03-27T15:14:16.000Z | // https://practice.geeksforgeeks.org/problems/array-pair-sum-divisibility-problem/0
#include<bits/stdc++.h>
using namespace std;
#define fast ios::sync_with_stdio(false);cin.tie(0)
#define pb push_back
#define digit(x) floor(log10(x))+1
#define mod 1000000007
#define endl "\n"
#define int long long
#define matrix vector<vector<int> >
#define vi vector<int>
#define pii pair<int,int>
#define vs vector<string>
#define vp vector<pii>
#define test() int t;cin>>t;while(t--)
#define all(x) x.begin(),x.end()
#define debug(x) cerr << #x << " is " << x << endl;
int dx[] = {0, 0, 1, -1};
int dy[] = {1, -1, 0, 0};
const int sz = 100005;
void showArr(int *arr, int n){for(int i=0;i<n;i++) cout<<arr[i]<<" ";}
//=================================================================//
int32_t main(){
fast;
test() {
int n;
cin>>n;
int a[n];
for(int i=0;i<n;i++) cin>>a[i];
int k;
cin>>k;
for(int i=0;i<n;i++) a[i]%=k;
unordered_map<int,int> hm;
for(int i=0;i<n;i++) hm[a[i]]++;
int cnt = 0, ans = 0;
for(int i=0;i<n;i++) {
if(a[i]==0) {
ans++;
continue;
}
if(hm[k-a[i]]>0) {
cnt++;
hm[a[i]]--;
hm[k-a[i]]--;
}
}
cnt+=(ans/2);
if(n&1) cout<<"False"<<endl;
else if(cnt==n/2) cout<<"True"<<endl;
else cout<<"False"<<endl;
}
return 0;
} | 26.803571 | 84 | 0.471019 | vkashkumar |
77eeb386d98a76d27a7d0f3e4f754033926db7a4 | 1,703 | cpp | C++ | ae5b2.cpp | ohmyjons/SPOJ-1 | 870ae3b072a3fbc89149b35fe5649a74512a8f60 | [
"Unlicense"
] | 264 | 2015-01-08T10:07:01.000Z | 2022-03-26T04:11:51.000Z | ae5b2.cpp | ohmyjons/SPOJ-1 | 870ae3b072a3fbc89149b35fe5649a74512a8f60 | [
"Unlicense"
] | 17 | 2016-04-15T03:38:07.000Z | 2020-10-30T00:33:57.000Z | ae5b2.cpp | ohmyjons/SPOJ-1 | 870ae3b072a3fbc89149b35fe5649a74512a8f60 | [
"Unlicense"
] | 127 | 2015-01-08T04:56:44.000Z | 2022-02-25T18:40:37.000Z | // 2009-12-30
//Dynamic max prefix sum query with segment tree. O((n+m) lg n)
#include <iostream>
#include <algorithm>
#include <functional>
using namespace std;
static int sum[1000000];
static int max_psum[1000000];
void recalc(int root)
{
sum[root]=sum[root<<1]+sum[1+(root<<1)];
max_psum[root]=max(max_psum[root<<1],
sum[root<<1]+max_psum[1+(root<<1)]);
}
void atomic_upd(int root,int val)
{
sum[root]=val;
max_psum[root]=val>0?val:0;
}
template<class RAI>
void upd(int root,RAI begin,RAI end,RAI pos,int val)
{
if (end-begin==1)
atomic_upd(root,val);
else
{
RAI mid=begin+(end-begin)/2;
if (pos<mid)
upd(root<<1,begin,mid,pos,val);
else
upd(1+(root<<1),mid,end,pos,val);
recalc(root);
}
}
template<class RAI>
void build_tree(int root,RAI begin,RAI end)
{
if (end-begin==1)
atomic_upd(root,*begin);
else
{
RAI mid=begin+(end-begin)/2;
build_tree(root<<1,begin,mid);
build_tree(1+(root<<1),mid,end);
recalc(root);
}
}
int in()
{
int res=0;
char c;
do
c=getchar_unlocked();
while (c<=32);
do
{
res=(res<<1)+(res<<3)+c-'0';
c=getchar_unlocked();
}
while (c>32);
return res;
}
int main()
{
int N,i,m,idx,val;
static int a[200001],b[200001],c[200001],d[200001];
N=in();
for (i=1; i<=N; i++)
b[i]=a[i]=in();
sort(b+1,b+N+1);
c[0]=0;
for (i=1; i<=N; i++)
c[b[i]]=i;
for (i=1; i<=N; i++)
if (!c[i])
c[i]=c[i-1];
for (i=1; i<=N; i++)
d[i]=c[i]-c[i-1]-1;
build_tree(1,d,d+N+1);
printf(max_psum[1]>0?"NIE\n":"TAK\n");
m=in();
while (m--)
{
idx=in(); val=in();
upd(1,d,d+N+1,d+val,d[val]+1);
upd(1,d,d+N+1,d+a[idx],d[a[idx]]-1);
d[val]++;
d[a[idx]]--;
a[idx]=val;
printf(max_psum[1]>0?"NIE\n":"TAK\n");
}
return 0;
}
| 18.117021 | 63 | 0.590722 | ohmyjons |
77efb79e999805f6584f5ca06d8ee4d49512a27d | 4,299 | cpp | C++ | TDD/tdd_instance_json.cpp | gxhblues/TDD | a1f0dce58a5caeb67e21cf79513df10879a7926a | [
"MIT"
] | null | null | null | TDD/tdd_instance_json.cpp | gxhblues/TDD | a1f0dce58a5caeb67e21cf79513df10879a7926a | [
"MIT"
] | null | null | null | TDD/tdd_instance_json.cpp | gxhblues/TDD | a1f0dce58a5caeb67e21cf79513df10879a7926a | [
"MIT"
] | null | null | null | #include "pch.h"
#include "tdd_instance.h"
#include "tdd_shape_box.h"
#include "tdd_shape_connection.h"
#include "tdd_shape_text.h"
#include "tdd_shape_free.h"
#include "tdd_shape_table.h"
#include "tdd_shape_qrcode.h"
#include "tdd_instance_action.h"
using namespace std;
namespace TDD
{
void to_json(json& j, const Instance& instance)
{
if (!instance.shapes.empty())
{
json js;
for (auto& s : instance.shapes)
{
json jj;
s->to_json(jj);
js.push_back(jj);
}
j["shapes"] = js;
}
if (!instance.groups.empty())
{
json jgs;
for (auto& g : instance.groups)
{
json jg;
for (auto& s : g)
{
jg.push_back(s->GetID());
}
jgs.push_back(jg);
}
j["groups"] = jgs;
}
}
void from_json(const json& j, Instance& instance)
{
if (!j.contains("shapes"))
{
return;
}
vector<json> lines;
for (auto& sj : j.at("shapes"))
{
auto t = sj.at("type").get<string>();
if (t == "Line")
{
if (sj["from"].contains("id") || sj["to"].contains("id"))
lines.emplace_back(sj);
else
{
//standalone line do not have reference shape, so it can construct directly.
auto s = make_shared<Shape::Connection>();
s->from_json(sj, instance);
instance.AppendConnection(s, false);
}
}
else
{
shared_ptr<Shape::Shape> s;
if (t == "Box")
{
s = make_shared<Shape::Box>();
}
else if (t == "Free")
{
s = make_shared<Shape::Free>();
}
else if (t == "Table")
{
s = make_shared<Shape::Table>();
}
else if (t == "Text")
{
s = make_shared<Shape::Text>();
}
else if (t == "QRCode")
{
s = make_shared<Shape::QRCode>();
}
if (s)
{
s->from_json(sj, instance);
instance.AppendShape(s, false);
}
}
}
for (auto& sj : lines)
{
auto s = make_shared<Shape::Connection>();
s->from_json(sj, instance);
instance.AppendConnection(s, false);
}
//load groups
if (j.contains("groups"))
{
for (auto& jg : j.at("groups"))
{
std::unordered_set<std::shared_ptr<Shape::Shape>> sg;
for (auto sid : jg)
{
if (sid.is_number_unsigned())
{
auto id = sid.get<u32>();
auto s = instance.GetShapeFromID(id);
if (s)
{
sg.insert(s);
}
}
}
if (sg.size() < 2) continue; //dummy group
//find if any duplicate group
bool is_duplicate = false;
for (auto& g : instance.groups)
{
if (g == sg)
{
is_duplicate = true;
break;
}
}
if (!is_duplicate)
instance.groups.emplace_back(move(sg));
}
}
instance.selected_shapes.clear();
instance.selected_shapes_extended.clear();
instance.BuildSelectionCache();
}
json Instance::DumpSelectedShapes()
{
if (selected_shapes.empty()) return {};
auto tmp_instance = make_shared<TDD::Instance>();
for (auto& s : selected_shapes)
{
tmp_instance->shapes.push_back(s);
}
unordered_set<shared_ptr<Shape::Shape>> sss;
sss.insert(selected_shapes.begin(), selected_shapes.end());
for (auto& g : groups)
{
bool hit_group = true;
for (auto s : g)
{
if (!sss.count(s))
{
hit_group = false;
break;
}
}
if (hit_group)
{
tmp_instance->groups.push_back(g);
}
}
json j = *tmp_instance;
return j;
}
} | 23.883333 | 92 | 0.442661 | gxhblues |
77f07abc258021fb1166525aaa4eef7de6d406ca | 453 | hh | C++ | cc/data-fix-guile.hh | acorg/acmacs-whocc | af508bd4651ffb565cd4cf771200540918b1b2bd | [
"MIT"
] | null | null | null | cc/data-fix-guile.hh | acorg/acmacs-whocc | af508bd4651ffb565cd4cf771200540918b1b2bd | [
"MIT"
] | null | null | null | cc/data-fix-guile.hh | acorg/acmacs-whocc | af508bd4651ffb565cd4cf771200540918b1b2bd | [
"MIT"
] | null | null | null | #pragma once
#include "acmacs-base/guile.hh"
// ----------------------------------------------------------------------
namespace acmacs::data_fix::inline v1
{
// pass pointer to this function to guile::init()
void guile_defines();
} // namespace acmacs::data_fix::inline v1
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
| 25.166667 | 73 | 0.456954 | acorg |
77f375dc872dc2f4556b13a9381d538524984220 | 2,280 | hpp | C++ | tests/testServer/ServiceComplexTypeRpcs.hpp | hermannolafs/gWhisper | 2c7efe80337fad6d7ebe65597d97b2e430ab4cb6 | [
"Apache-2.0"
] | 47 | 2019-03-07T18:49:09.000Z | 2022-03-16T17:02:20.000Z | tests/testServer/ServiceComplexTypeRpcs.hpp | hermannolafs/gWhisper | 2c7efe80337fad6d7ebe65597d97b2e430ab4cb6 | [
"Apache-2.0"
] | 97 | 2019-03-06T15:10:50.000Z | 2022-03-16T16:30:18.000Z | tests/testServer/ServiceComplexTypeRpcs.hpp | hermannolafs/gWhisper | 2c7efe80337fad6d7ebe65597d97b2e430ab4cb6 | [
"Apache-2.0"
] | 13 | 2019-03-07T18:49:13.000Z | 2022-02-03T07:22:13.000Z | // Copyright 2019 IBM Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include "examples.grpc.pb.h"
class ServiceComplexTypeRpcs final : public examples::ComplexTypeRpcs::Service
{
virtual ::grpc::Status echoColorEnum(
::grpc::ServerContext* context,
const ::examples::ColorEnum* request,
::examples::ColorEnum* response
) override;
virtual ::grpc::Status getNumberOrStringOneOf(
::grpc::ServerContext* context,
const ::examples::NumberOrStringChoice* request,
::examples::NumberOrStringOneOf* response
) override;
virtual ::grpc::Status sendNumberOrStringOneOf(
::grpc::ServerContext* context,
const ::examples::NumberOrStringOneOf* request,
::examples::NumberOrStringChoice* response
) override;
virtual ::grpc::Status addAllNumbers(
::grpc::ServerContext* context,
const ::examples::RepeatedNumbers* request,
::examples::Uint32* response
) override;
virtual ::grpc::Status getLastColor(
::grpc::ServerContext* context,
const ::examples::RepeatedColors* request,
::examples::ColorEnum* response
) override;
virtual ::grpc::Status echoNumberAndStrings(
::grpc::ServerContext* context,
const ::examples::RepeatedNumberAndString* request,
::examples::RepeatedNumberAndString* response
) override;
virtual ::grpc::Status mapNumbersToString(
::grpc::ServerContext* context,
const ::examples::RepeatedNumbers* request,
::examples::NumberMap* response
) override;
};
| 36.190476 | 78 | 0.644298 | hermannolafs |
77f4a89af8b7d867e75c778ec1916caf14ee76a4 | 2,668 | cc | C++ | cefclient/browser/window_test_win.cc | githubzhaoliang/sdkdemoapp_windows | e267ea8ec91f7101f323a6b72ad32bedbb1f034b | [
"BSD-3-Clause"
] | 27 | 2015-01-20T10:25:14.000Z | 2018-11-30T08:42:13.000Z | cef/tests/cefclient/browser/window_test_win.cc | lovewitty/miniblink49 | c8cb0b50636915d748235eea95a57e24805dc43e | [
"Apache-2.0"
] | 2 | 2019-01-14T00:17:19.000Z | 2019-02-03T08:18:49.000Z | cef/tests/cefclient/browser/window_test_win.cc | lovewitty/miniblink49 | c8cb0b50636915d748235eea95a57e24805dc43e | [
"Apache-2.0"
] | 23 | 2015-01-09T10:51:00.000Z | 2021-01-06T13:06:20.000Z | // Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
#include "cefclient/browser/window_test.h"
namespace client {
namespace window_test {
namespace {
HWND GetRootHwnd(CefRefPtr<CefBrowser> browser) {
return ::GetAncestor(browser->GetHost()->GetWindowHandle(), GA_ROOT);
}
// Toggles the current display state.
void Toggle(HWND root_hwnd, UINT nCmdShow) {
// Retrieve current window placement information.
WINDOWPLACEMENT placement;
::GetWindowPlacement(root_hwnd, &placement);
if (placement.showCmd == nCmdShow)
::ShowWindow(root_hwnd, SW_RESTORE);
else
::ShowWindow(root_hwnd, nCmdShow);
}
} // namespace
void SetPos(CefRefPtr<CefBrowser> browser,
int x, int y, int width, int height) {
HWND root_hwnd = GetRootHwnd(browser);
// Retrieve current window placement information.
WINDOWPLACEMENT placement;
::GetWindowPlacement(root_hwnd, &placement);
// Retrieve information about the display that contains the window.
HMONITOR monitor = MonitorFromRect(&placement.rcNormalPosition,
MONITOR_DEFAULTTONEAREST);
MONITORINFO info;
info.cbSize = sizeof(info);
GetMonitorInfo(monitor, &info);
// Make sure the window is inside the display.
CefRect display_rect(
info.rcWork.left,
info.rcWork.top,
info.rcWork.right - info.rcWork.left,
info.rcWork.bottom - info.rcWork.top);
CefRect window_rect(x, y, width, height);
ModifyBounds(display_rect, window_rect);
if (placement.showCmd == SW_MINIMIZE || placement.showCmd == SW_MAXIMIZE) {
// The window is currently minimized or maximized. Restore it to the desired
// position.
placement.rcNormalPosition.left = window_rect.x;
placement.rcNormalPosition.right = window_rect.x + window_rect.width;
placement.rcNormalPosition.top = window_rect.y;
placement.rcNormalPosition.bottom = window_rect.y + window_rect.height;
::SetWindowPlacement(root_hwnd, &placement);
::ShowWindow(root_hwnd, SW_RESTORE);
} else {
// Set the window position.
::SetWindowPos(root_hwnd, NULL, window_rect.x, window_rect.y,
window_rect.width, window_rect.height, SWP_NOZORDER);
}
}
void Minimize(CefRefPtr<CefBrowser> browser) {
Toggle(GetRootHwnd(browser), SW_MINIMIZE);
}
void Maximize(CefRefPtr<CefBrowser> browser) {
Toggle(GetRootHwnd(browser), SW_MAXIMIZE);
}
void Restore(CefRefPtr<CefBrowser> browser) {
::ShowWindow(GetRootHwnd(browser), SW_RESTORE);
}
} // namespace window_test
} // namespace client
| 31.761905 | 80 | 0.723763 | githubzhaoliang |
af90d3a5e6bbf5d6bb27288b8c1db00e0520d99f | 143 | cpp | C++ | GoFish/Card.cpp | uaineteine/GoFish | 8140428e8ebb4a2cdb07b65c4e2f90a2236b0cca | [
"MIT"
] | null | null | null | GoFish/Card.cpp | uaineteine/GoFish | 8140428e8ebb4a2cdb07b65c4e2f90a2236b0cca | [
"MIT"
] | null | null | null | GoFish/Card.cpp | uaineteine/GoFish | 8140428e8ebb4a2cdb07b65c4e2f90a2236b0cca | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include "Card.h"
Card::Card(int value, int suit)
{
Num = value;
Suit = suit;
}
Card::~Card()
{
}
int Num;
int Suit; | 8.411765 | 31 | 0.601399 | uaineteine |
af90fcc67631fc6346ca4ef1f70c0e6b5d069d23 | 331 | cpp | C++ | Difficulty 3/alex_and_barb.cpp | BrynjarGeir/Kattis | a151972cbae3db04a8e6764d5fa468d0146c862b | [
"MIT"
] | null | null | null | Difficulty 3/alex_and_barb.cpp | BrynjarGeir/Kattis | a151972cbae3db04a8e6764d5fa468d0146c862b | [
"MIT"
] | null | null | null | Difficulty 3/alex_and_barb.cpp | BrynjarGeir/Kattis | a151972cbae3db04a8e6764d5fa468d0146c862b | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
int main() {
int k, m, n;
bool alexs_turn = true;
cin >> k >> m >> n;
while(k) {
if(k >= m + n) k -= m;
else if(k > n) k -= n;
else k = 0;
alexs_turn = !alexs_turn;
}
if(!alexs_turn) cout << "Barb";
else cout << "Alex";
} | 16.55 | 35 | 0.453172 | BrynjarGeir |
af96a56d2b84496b743017abe3f9e85dd8052cd3 | 11,760 | ipp | C++ | include/External/stlib/packages/numerical/random/discrete/DiscreteGeneratorBinned.ipp | bxl295/m4extreme | 2a4a20ebb5b4e971698f7c981de140d31a5e550c | [
"BSD-3-Clause"
] | null | null | null | include/External/stlib/packages/numerical/random/discrete/DiscreteGeneratorBinned.ipp | bxl295/m4extreme | 2a4a20ebb5b4e971698f7c981de140d31a5e550c | [
"BSD-3-Clause"
] | null | null | null | include/External/stlib/packages/numerical/random/discrete/DiscreteGeneratorBinned.ipp | bxl295/m4extreme | 2a4a20ebb5b4e971698f7c981de140d31a5e550c | [
"BSD-3-Clause"
] | null | null | null | // -*- C++ -*-
#if !defined(__numerical_random_DiscreteGeneratorBinned_ipp__)
#error This file is an implementation detail of DiscreteGeneratorBinned.
#endif
namespace numerical {
template<class Generator>
inline
typename DiscreteGeneratorBinned<Generator>::result_type
DiscreteGeneratorBinned<Generator>::
operator()() {
const Number efficiency = computeEfficiency();
// If the efficiency is very low (it has fallen below the minimum allow
// efficiency) or if the efficiency is low (below the target efficiency)
// and it is time for a rebuild.
if (efficiency < getMinimumEfficiency() ||
(efficiency < getTargetEfficiency() && _stepsUntilNextRebuild <= 0)) {
rebuild();
}
// If it is time for a repair.
else if (_stepsUntilNextRepair <= 0) {
repair();
}
// Loop until the point is not rejected.
for (;;) {
unsigned random = (*_discreteUniformGenerator)();
// Use the first bits for indexing.
unsigned index = random & IndexMask();
// Use the remaining bits for the height deviate.
unsigned heightGenerator = random >> IndexBits();
Number height = heightGenerator * _heightUpperBound * MaxHeightInverse();
// If we have a hit for the PMF's in this bin.
if (height < _binnedPmf[index]) {
// Do a linear search to find the PMF that we hit.
std::size_t pmfIndex = _deviateIndices[index];
for (; pmfIndex < _deviateIndices[index + 1] - 1; ++pmfIndex) {
height -= _pmf[pmfIndex];
if (height <= 0) {
break;
}
}
return _permutation[pmfIndex];
}
}
}
// Initialize the probability mass function.
template<class Generator>
template<typename ForwardIterator>
inline
void
DiscreteGeneratorBinned<Generator>::
initialize(ForwardIterator begin, ForwardIterator end) {
// Build the array for the PMF.
_pmf.resize(std::distance(begin, end));
std::copy(begin, end, _pmf.begin());
_permutation.resize(_pmf.size());
_rank.resize(_pmf.size());
_binIndices.resize(_pmf.size() + 1);
// Initialize so the efficiency appears to be zero.
_pmfSum = 0;
_heightUpperBound = 1;
// Rebuild the data structure by sorting the PMF and packing them into bins.
rebuild();
}
// Rebuild the bins.
template<class Generator>
inline
void
DiscreteGeneratorBinned<Generator>::
rebuild() {
_stepsUntilNextRebuild = _stepsBetweenRebuilds;
// Rebuilding also repairs the data structure, so we reset that counter
// as well.
_stepsUntilNextRepair = _stepsBetweenRepairs;
//
// Sort the PMF array in descending order.
//
_pmfSum = sum(_pmf);
for (std::size_t i = 0; i != _permutation.size(); ++i) {
_permutation[i] = i;
}
// Sort in descending order.
ads::sortTogether(_pmf.begin(), _pmf.end(), _permutation.begin(),
_permutation.end(), std::greater<Number>());
// Compute the ranks.
for (std::size_t i = 0; i != _permutation.size(); ++i) {
_rank[_permutation[i]] = i;
}
packIntoBins();
_heightUpperBound = *std::max_element(_binnedPmf.begin(), _binnedPmf.end());
}
// Set the probability mass function with the specified index.
template<class Generator>
inline
void
DiscreteGeneratorBinned<Generator>::
setPmf(const std::size_t index, const Number value) {
// The index in the re-ordered PMF.
const std::size_t i = _rank[index];
// If the value has not changed, do nothing. I need this check; otherwise
// the following branch could be expensive.
if (_pmf[i] == value) {
return;
}
// If the PMF has become zero. (It was not zero before.)
if (value == 0) {
// Set the PMF to zero.
_pmf[i] = 0;
// Repair the data structure. This is necessary to ensure that the
// binned PMF are correct. They must be exactly zero. Likewize, the
// sum of the PMF may have become zero.
repair();
return;
}
// The remainder of this function is the standard case. Update the data
// structure using the difference between the new and old values.
const Number difference = value - _pmf[i];
// Update the sum of the PMF.
_pmfSum += difference;
// Update the PMF array.
_pmf[i] = value;
//
// Update the binned PMF.
//
const std::size_t binIndex = _binIndices[i];
_binnedPmf[binIndex] += difference;
// Update the upper bound on the bin height.
if (_binnedPmf[binIndex] > _heightUpperBound) {
_heightUpperBound = _binnedPmf[binIndex];
}
// Fix the bin if necessary.
if (i < _splittingEnd && _binnedPmf[binIndex] < 0) {
fixBin(binIndex);
}
--_stepsUntilNextRepair;
--_stepsUntilNextRebuild;
}
// Update the data structure following calls to setPmfWithoutUpdating() .
template<class Generator>
inline
void
DiscreteGeneratorBinned<Generator>::
updatePmf() {
//
// Compute the binned PMF.
//
std::fill(_binnedPmf.begin(), _binnedPmf.end(), 0);
// First do the PMF's that are split over multiple bins.
for (std::size_t i = 0; i != _splittingEnd; ++i) {
// Split the PMF over a number of bins.
const Number height = _pmf[i] / (_binIndices[i + 1] - _binIndices[i]);
for (std::size_t j = _binIndices[i]; j != _binIndices[i + 1]; ++j) {
_binnedPmf[j] = height;
}
}
// Then do the PMF's that sit in a single bin.
for (std::size_t i = _splittingEnd; i != _pmf.size(); ++i) {
_binnedPmf[_binIndices[i]] += _pmf[i];
}
// Compute the sum of the PMF.
// Choose the more efficient method.
if (_pmf.size() < _binnedPmf.size()) {
_pmfSum = std::accumulate(_pmf.begin(), _pmf.end(), 0.0);
}
else {
// Sum over the bins.
_pmfSum = std::accumulate(_binnedPmf.begin(), _binnedPmf.end(), 0.0);
}
// Compute the upper bound on the bin height.
_heightUpperBound = *std::max_element(_binnedPmf.begin(), _binnedPmf.end());
}
// Count the number of required bins for the given maximum height.
template<typename T, typename ForwardIterator>
inline
std::size_t
countBins(ForwardIterator begin, ForwardIterator end, const T height) {
const T inverse = 1.0 / height;
std::size_t count = 0;
// Count the splitting bins.
while (begin != end && *begin > height) {
count += std::size_t(*begin * inverse) + 1;
++begin;
}
// Count the stacking bins.
// The following loop is a little complicated because I must allow for the
// possibility of blocks with zero height.
T currentHeight = -1;
while (begin != end) {
// If we are starting a new bin.
if (currentHeight == -1) {
// Add the first block to the bin.
currentHeight = *begin;
// We are using a new bin.
++count;
// Move to the next block.
++begin;
}
else {
// Try adding a block to the current bin.
currentHeight += *begin;
// If we can fit it in the current bin.
if (currentHeight <= height) {
// Move to the next block.
++begin;
}
else {
// Start a new bin.
currentHeight = -1;
}
}
}
return count;
}
// Compute a bin height such that all the blocks will fit in the bins.
template<typename T, typename ForwardIterator>
inline
T
computeBinHeight(ForwardIterator begin, ForwardIterator end,
const std::size_t NumberOfBins) {
const T content = std::accumulate(begin, end, T(0));
T factor = 1;
T height;
do {
factor += 0.1;
height = factor * content / NumberOfBins;
}
while (countBins(begin, end, height) > NumberOfBins);
return height;
}
// Pack the block into bins.
template<class Generator>
inline
void
DiscreteGeneratorBinned<Generator>::
packIntoBins() {
const Number height = computeBinHeight<Number>(_pmf.begin(), _pmf.end(),
NumberOfBins);
const Number inverse = 1.0 / height;
// Empty the bins.
std::fill(_binnedPmf.begin(), _binnedPmf.end(), 0);
std::fill(_deviateIndices.begin(), _deviateIndices.end(), _pmf.size());
// Pack the blocks that are split across multiple bins.
std::size_t pmfIndex = 0, binIndex = 0;
for (; pmfIndex != _pmf.size() && _pmf[pmfIndex] > height; ++pmfIndex) {
_binIndices[pmfIndex] = binIndex;
const std::size_t count = std::size_t(_pmf[pmfIndex] * inverse) + 1;
const Number binHeight = _pmf[pmfIndex] / count;
for (std::size_t i = 0; i != count; ++i) {
_deviateIndices[binIndex] = pmfIndex;
_binnedPmf[binIndex] = binHeight;
++binIndex;
}
}
// Record the end of the PMF's that are split accross multiple bins.
_splittingEnd = pmfIndex;
//
// Pack the stacking bins.
//
// If there are blocks left to stack.
if (pmfIndex != _pmf.size()) {
// Put a block in the current bin.
_binIndices[pmfIndex] = binIndex;
_deviateIndices[binIndex] = pmfIndex;
_binnedPmf[binIndex] = _pmf[pmfIndex];
++pmfIndex;
// Pack the rest of the blocks.
Number newHeight;
while (pmfIndex != _pmf.size()) {
// Try adding a block to the current bin.
newHeight = _binnedPmf[binIndex] + _pmf[pmfIndex];
// If we can fit it in the current bin.
if (newHeight <= height) {
// Add the block to the bin.
_binIndices[pmfIndex] = binIndex;
_binnedPmf[binIndex] = newHeight;
// Move to the next block.
++pmfIndex;
}
else {
// Put the block in the next bin.
++binIndex;
_binIndices[pmfIndex] = binIndex;
_deviateIndices[binIndex] = pmfIndex;
_binnedPmf[binIndex] = _pmf[pmfIndex];
++pmfIndex;
}
}
// Move to an empty bin.
++binIndex;
}
// The guard value.
_binIndices[pmfIndex] = binIndex;
}
template<class Generator>
inline
void
DiscreteGeneratorBinned<Generator>::
fixBin(const std::size_t binIndex) {
for (std::size_t j = binIndex + 1;
_deviateIndices[binIndex] == _deviateIndices[j] &&
_binnedPmf[binIndex] < 0; ++j) {
_binnedPmf[binIndex] += _binnedPmf[j];
_binnedPmf[j] = 0;
}
}
// Print information about the data structure.
template<class Generator>
inline
void
DiscreteGeneratorBinned<Generator>::
print(std::ostream& out) const {
out << "Bin data:\n\n"
<< "Height upper bound = " << _heightUpperBound << "\n"
<< "Binned PMF = " << _binnedPmf << "\n"
<< "Deviate indices = " << _deviateIndices << "\n"
<< "\nPMF data:\n\n"
<< "PMF sum = " << _pmfSum << "\n"
<< "Splitting end = " << _splittingEnd << "\n"
<< "PMF = \n" << _pmf << '\n'
<< "Permutation = \n" << _permutation << '\n'
<< "Rank = \n" << _rank << '\n'
<< "Bin indices = " << _binIndices << '\n'
<< "Steps between repairs = " << _stepsBetweenRepairs << "\n"
<< "Steps until next repair = " << _stepsUntilNextRepair << "\n"
<< "Steps between rebuilds = " << _stepsBetweenRebuilds << "\n"
<< "Steps until next rebuild = " << _stepsUntilNextRebuild << "\n"
<< "Target efficiency = " << _targetEfficiency << "\n"
<< "Minimum efficiency = " << _minimumEfficiency << "\n";
}
} // namespace numerical
| 31.36 | 80 | 0.597789 | bxl295 |
af97bbd12365e535c1e9f5f1944b6c55bb3b4b92 | 1,375 | cpp | C++ | LeetCode/Problems/0145_Binary_Tree_Postorder_Traversal/binary_tree_postorder_traversal.cpp | jocodoma/coding-interview-prep | f7f06be0bc5687c376b753ba3fa46b07412eeb80 | [
"MIT"
] | null | null | null | LeetCode/Problems/0145_Binary_Tree_Postorder_Traversal/binary_tree_postorder_traversal.cpp | jocodoma/coding-interview-prep | f7f06be0bc5687c376b753ba3fa46b07412eeb80 | [
"MIT"
] | null | null | null | LeetCode/Problems/0145_Binary_Tree_Postorder_Traversal/binary_tree_postorder_traversal.cpp | jocodoma/coding-interview-prep | f7f06be0bc5687c376b753ba3fa46b07412eeb80 | [
"MIT"
] | null | null | null | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
// return recursiveTraversal(root);
return iterativeTraversal(root);
}
// time complexity: O(n)
// space complexity: in average is O(log n), but the worst case is O(n)
vector<int> recursiveTraversal(TreeNode* root){
recursiveHelper(root);
return sol;
}
void recursiveHelper(TreeNode* node){
if(!node) return;
recursiveHelper(node->left);
recursiveHelper(node->right);
sol.push_back(node->val);
}
// time complexity: O(2n) = O(n), space complexity: O(2n) = O(n)
vector<int> iterativeTraversal(TreeNode* root){
if(!root) return {};
std::stack<TreeNode*> s1, s2;
s1.push(root);
while(!s1.empty()){
TreeNode *node = s1.top();s1.pop();
s2.push(node);
if(node->left) s1.push(node->left);
if(node->right) s1.push(node->right);
}
while(!s2.empty()){
TreeNode *node = s2.top();s2.pop();
sol.push_back(node->val);
}
return sol;
}
private:
vector<int> sol;
};
| 24.553571 | 75 | 0.550545 | jocodoma |
af9e5c8a0b386c5ed63691799377fca378e9db67 | 4,648 | cpp | C++ | src/prod/src/Management/healthmanager/IHealthJobItem.cpp | vishnuk007/service-fabric | d0afdea185ae932cc3c9eacf179692e6fddbc630 | [
"MIT"
] | 2,542 | 2018-03-14T21:56:12.000Z | 2019-05-06T01:18:20.000Z | src/prod/src/Management/healthmanager/IHealthJobItem.cpp | vishnuk007/service-fabric | d0afdea185ae932cc3c9eacf179692e6fddbc630 | [
"MIT"
] | 994 | 2019-05-07T02:39:30.000Z | 2022-03-31T13:23:04.000Z | src/prod/src/Management/healthmanager/IHealthJobItem.cpp | vishnuk007/service-fabric | d0afdea185ae932cc3c9eacf179692e6fddbc630 | [
"MIT"
] | 300 | 2018-03-14T21:57:17.000Z | 2019-05-06T20:07:00.000Z | // ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#include "stdafx.h"
using namespace Common;
using namespace Federation;
using namespace std;
using namespace Store;
using namespace Management::HealthManager;
IHealthJobItem::IHealthJobItem(HealthEntityKind::Enum entityKind)
: entityKind_(entityKind)
, state_(EntityJobItemState::NotStarted)
, pendingAsyncOperation_()
, sequenceNumber_(0)
{
}
IHealthJobItem::~IHealthJobItem()
{
}
bool IHealthJobItem::operator > (IHealthJobItem const & other) const
{
// ReadOnly jobs have already written their info to store, so they should be quick to complete.
// Give read only job items priority.
if (this->CanExecuteOnStoreThrottled != other.CanExecuteOnStoreThrottled)
{
return other.CanExecuteOnStoreThrottled;
}
if (this->JobPriority < other.JobPriority)
{
return true;
}
else if (this->JobPriority == other.JobPriority)
{
return this->SequenceNumber > other.SequenceNumber;
}
else
{
return false;
}
}
void IHealthJobItem::ProcessCompleteResult(Common::ErrorCode const & error)
{
this->OnComplete(error);
}
// Called when work is done, either sync or async
void IHealthJobItem::OnWorkComplete()
{
ASSERT_IF(
state_ == EntityJobItemState::NotStarted || state_ == EntityJobItemState::Completed,
"{0}: OnWorkComplete can't be called in this state",
*this);
state_ = EntityJobItemState::Completed;
// The pending async operation keeps the job item alive.
// Release the reference to it here to avoid creating a circular reference.
pendingAsyncOperation_.reset();
}
AsyncOperationSPtr IHealthJobItem::OnWorkCanceled()
{
state_ = EntityJobItemState::Completed;
AsyncOperationSPtr temp;
pendingAsyncOperation_.swap(temp);
return temp;
}
void IHealthJobItem::OnAsyncWorkStarted()
{
ASSERT_IF(
state_ == EntityJobItemState::NotStarted,
"{0}: OnAsyncWorkStarted can't be called in this state",
*this);
// Mark that async work is started and return
// When the work is done, the entity will call OnAsyncWorkComplete
if (state_ == EntityJobItemState::Started)
{
state_ = EntityJobItemState::AsyncPending;
}
}
void IHealthJobItem::OnAsyncWorkReadyToComplete(
Common::AsyncOperationSPtr const & operation)
{
// Accepted states: AsyncPending and Started (in rare situations,
// when the callback is executed quickly and raises method before the async is started)
ASSERT_IF(
state_ == EntityJobItemState::NotStarted || state_ == EntityJobItemState::Completed,
"{0}: OnAsyncWorkReadyToComplete can't be called in this state",
*this);
// Remember the operation that completed to be executed on post-processing
pendingAsyncOperation_ = operation;
if (state_ == EntityJobItemState::Started)
{
state_ = EntityJobItemState::AsyncPending;
}
}
bool IHealthJobItem::ProcessJob(IHealthJobItemSPtr const & thisSPtr, HealthManagerReplica & root)
{
UNREFERENCED_PARAMETER(root);
switch (state_)
{
case EntityJobItemState::NotStarted:
{
// Start actual processing, done in derived classes
state_ = EntityJobItemState::Started;
this->ProcessInternal(thisSPtr);
break;
}
case EntityJobItemState::AsyncPending:
{
// The result error is already set
this->FinishAsyncWork();
break;
}
default:
Assert::CodingError("{0}: ProcessJob can't be called in this state", *this);
}
return true;
}
std::wstring IHealthJobItem::ToString() const
{
return wformatString(*this);
}
void IHealthJobItem::WriteTo(__in Common::TextWriter & w, Common::FormatOptions const &) const
{
w.Write(
"{0}({1},id={2},{3},JI lsn={4},priority={5})",
this->TypeString,
this->ReplicaActivityId.TraceId,
this->JobId,
this->State,
this->SequenceNumber,
this->JobPriority);
}
void IHealthJobItem::WriteToEtw(uint16 contextSequenceId) const
{
HMCommonEvents::Trace->JobItemTrace(
contextSequenceId,
this->TypeString,
this->ReplicaActivityId.TraceId,
this->JobId,
this->State,
this->SequenceNumber,
this->JobPriority);
}
| 28.169697 | 99 | 0.655336 | vishnuk007 |
afa2e52436d604e6dc03ea87d6e467a6820e18ef | 799 | cpp | C++ | luogu/codes/P1051.cpp | Tony031218/OI | 562f5f45d0448f4eab77643b99b825405a123d92 | [
"MIT"
] | 1 | 2021-02-22T03:39:24.000Z | 2021-02-22T03:39:24.000Z | luogu/codes/P1051.cpp | Tony031218/OI | 562f5f45d0448f4eab77643b99b825405a123d92 | [
"MIT"
] | null | null | null | luogu/codes/P1051.cpp | Tony031218/OI | 562f5f45d0448f4eab77643b99b825405a123d92 | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
struct node
{
string xm;
int qm, bj;
char bgb, xb;
int lw;
int ans;
int sum;
}a[101];
int n, tot = 0;
bool cmp(node x, node y)
{
if(x.ans == y.ans) return x.sum < y.sum;
else return x.ans > y.ans;
}
int main()
{
scanf("%d",&n);
for (int i = 1; i <= n; i++)
{
cin>>a[i].xm>>a[i].qm>>a[i].bj>>a[i].bgb>>a[i].xb>>a[i].lw;
if(a[i].qm>80&&a[i].lw>=1)a[i].ans+=8000;
if(a[i].qm>85&&a[i].bj>80)a[i].ans+=4000;
if(a[i].qm>90)a[i].ans+=2000;
if(a[i].xb=='Y'&&a[i].qm>85)a[i].ans+=1000;
if(a[i].bj>80&&a[i].bgb=='Y')a[i].ans+=850;
a[i].sum=i;
tot+=a[i].ans;
}
sort(a+1,a+n+1,cmp);
cout<<a[1].xm<<endl<<a[1].ans<<endl<<tot;
return 0;
}
| 19.975 | 67 | 0.46433 | Tony031218 |
afa4ab28c45c8aeeaaafca429fff5b40960c5361 | 4,595 | cpp | C++ | src/asset-archiver/asset-archiver.cpp | scp-studios/scp-game-framework | 17ffb68a50d834e490d387028f05add9f5391ea5 | [
"MIT"
] | 1 | 2022-01-31T22:20:01.000Z | 2022-01-31T22:20:01.000Z | src/asset-archiver/asset-archiver.cpp | scp-studios/scp-game-framework | 17ffb68a50d834e490d387028f05add9f5391ea5 | [
"MIT"
] | null | null | null | src/asset-archiver/asset-archiver.cpp | scp-studios/scp-game-framework | 17ffb68a50d834e490d387028f05add9f5391ea5 | [
"MIT"
] | null | null | null | #include <fstream>
#include <iostream>
#include <vector>
#include <string>
#include <filesystem>
#include <sstream>
// Hello. This is a simple command line utility for packaging assets into a si-
// ngle file. It works recursively.
namespace stdfs = std::filesystem;
// Unused argument suppressor
#define UNUSED_ARG(x) (void)x
// Simple function to put all of the command line arguments into a single vect-
// or of strings, which is easier to work with.
#if 0
static std::vector<std::string> preprocessCommandLineArguments(int argc, char** argv)
{
std::vector<std::string> result(argc);
for (uint32_t i = 0; i < argc; i++)
{
result[i] = argv[i];
}
return result;
}
#endif
static std::vector<std::string> splitString(std::string_view host, std::string_view separator)
{
std::vector<std::string> result;
size_t start = 0;
size_t end = host.find(separator, start);
while (end != std::string::npos)
{
result.push_back(std::string(host.substr(start, end - start)));
start = end + separator.length();
end = host.find(separator, start);
}
result.push_back(std::string(host.substr(start)));
return result;
}
// Obtain the files within the target directory.
static std::vector<std::string> getFiles(std::string_view directory, bool recursive)
{
std::vector<std::string> files;
for (const auto& file: stdfs::directory_iterator(directory))
{
#ifdef _WIN32
files.push_back(file.path().string());
#else
files.push_back(file.path());
#endif
if (recursive && file.is_directory())
{
#ifdef _WIN32
std::vector<std::string> subdirectoryFiles = getFiles(file.path().string(), recursive);
#else
std::vector<std::string> subdirectoryFiles = getFiles(file.path().c_str(), recursive);
#endif
files.insert(files.end(), subdirectoryFiles.begin(), subdirectoryFiles.end());
}
}
return files;
}
int main(int argc, char** argv)
{
// We are not using these arguments yet.
UNUSED_ARG(argc);
UNUSED_ARG(argv);
// I'll use command line arguments later. For now, they are just constants.
const std::string targetDir = "./assets";
const std::string contentOutput = "mardikar.jay";
const std::string configOutput = "neng.li";
// Obtain all of the files within the asset directory.
std::vector<std::string> assetFiles = getFiles(targetDir, true);
// This file is the file in which we output the content of the assets into.
// They will be linked together into a single binary file.
std::ofstream contentOutputFile(contentOutput, std::ofstream::binary);
if (!contentOutputFile)
{
std::cerr << "[FATAL ERROR]: Failed to open " << contentOutput << " for writing.\n";
return -1;
}
// This is the file in which we output the configuration file. It is where
// the reader can then lookup the location of the assets within the content
// file.
std::ofstream configOutputFile(configOutput);
if (!configOutputFile)
{
std::cerr << "[FATAL ERROR]: Failed to open " << configOutput << "for writing.\n";
return -2;
}
// We need to keep track of where the file is.
uint32_t startingMarker = 0;
uint32_t endingMarker = 0;
// We iterate through all of the assets.
for (const auto& asset: assetFiles)
{
// At the start of each iteration, the starting marker is set to the p-
// oint in which the last file ends.
startingMarker = endingMarker;
// We open the asset file for reading in binary mode.
std::ifstream file(asset, std::ifstream::binary);
if (!file)
{
std::cerr << "[WARNING]: Skipping " << asset << " due to an error in opening the file.\n";
continue;
}
// Next, we iterate through the whole file.
while (file)
{
// Read a character
char character;
file.read(&character, 1);
// Push that character to the content file.
contentOutputFile.write(&character, 1);
// Increase the ending marker.
endingMarker++;
}
// Finally, we add an entry in the configuration file
configOutputFile << asset << ":" << startingMarker << ":" << endingMarker << "\n";
}
// Okay, now we're done.
return 0;
} | 30.838926 | 102 | 0.605658 | scp-studios |
afae263cd3a9e957a7500eb9a1e18a3b3adea3f3 | 2,053 | cpp | C++ | tests/swats_test.cpp | ElianeBriand/ensmallen | 0f634056d054d100b2a70cb8f15ea9fa38680d10 | [
"BSL-1.0",
"BSD-3-Clause"
] | null | null | null | tests/swats_test.cpp | ElianeBriand/ensmallen | 0f634056d054d100b2a70cb8f15ea9fa38680d10 | [
"BSL-1.0",
"BSD-3-Clause"
] | null | null | null | tests/swats_test.cpp | ElianeBriand/ensmallen | 0f634056d054d100b2a70cb8f15ea9fa38680d10 | [
"BSL-1.0",
"BSD-3-Clause"
] | 1 | 2019-01-16T16:21:59.000Z | 2019-01-16T16:21:59.000Z | /**
* @file swats_test.cpp
* @author Marcus Edel
*
* Test file for the SWATS optimizer.
*
* ensmallen is free software; you may redistribute it and/or modify it under
* the terms of the 3-clause BSD license. You should have received a copy of
* the 3-clause BSD license along with ensmallen. If not, see
* http://www.opensource.org/licenses/BSD-3-Clause for more information.
*/
#include <ensmallen.hpp>
#include "catch.hpp"
#include "test_function_tools.hpp"
using namespace ens;
using namespace ens::test;
/**
* Run SWATS on logistic regression and make sure the results are acceptable.
*/
TEST_CASE("SWATSLogisticRegressionTestFunction", "[SWATSTest]")
{
SWATS optimizer(1e-3, 10, 0.9, 0.999, 1e-6, 600000, 1e-9, true);
// We allow a few trials in case of poor convergence.
LogisticRegressionFunctionTest(optimizer, 0.003, 0.006, 5);
}
/**
* Test the SWATS optimizer on the Sphere function.
*/
TEST_CASE("SWATSSphereFunctionTest", "[SWATSTest]")
{
SWATS optimizer(1e-3, 2, 0.9, 0.999, 1e-6, 500000, 1e-9, true);
FunctionTest<SphereFunction>(optimizer, 1.0, 0.1);
}
/**
* Test the SWATS optimizer on the Styblinski-Tang function.
*/
TEST_CASE("SWATSStyblinskiTangFunctionTest", "[SWATSTest]")
{
SWATS optimizer(1e-3, 2, 0.9, 0.999, 1e-6, 500000, 1e-9, true);
FunctionTest<StyblinskiTangFunction>(optimizer, 0.3, 0.03);
}
/**
* Test the SWATS optimizer on the Styblinski-Tang function. Use arma::fmat.
*/
TEST_CASE("SWATSStyblinskiTangFunctionFMatTest", "[SWATSTest]")
{
SWATS optimizer(1e-3, 2, 0.9, 0.999, 1e-6, 500000, 1e-9, true);
FunctionTest<StyblinskiTangFunction, arma::fmat>(optimizer, 3.0, 0.3);
}
#if ARMA_VERSION_MAJOR > 9 ||\
(ARMA_VERSION_MAJOR == 9 && ARMA_VERSION_MINOR >= 400)
/**
* Test the SWATS optimizer on the Styblinski-Tang function. Use arma::sp_mat.
*/
TEST_CASE("SWATSStyblinskiTangFunctionSpMatTest", "[SWATSTest]")
{
SWATS optimizer(1e-3, 2, 0.9, 0.999, 1e-6, 500000, 1e-9, true);
FunctionTest<StyblinskiTangFunction, arma::sp_mat>(optimizer, 0.3, 0.03);
}
#endif
| 29.328571 | 79 | 0.71018 | ElianeBriand |
afafe01bc52f52d0237b360d94f7692b8943bb7d | 1,233 | cpp | C++ | src/bounce/Bounce.cpp | Gigi1237/Bounce | 6e674dd7babda0192b930cc532f692c75219d1fd | [
"MIT"
] | null | null | null | src/bounce/Bounce.cpp | Gigi1237/Bounce | 6e674dd7babda0192b930cc532f692c75219d1fd | [
"MIT"
] | 2 | 2015-02-11T02:46:15.000Z | 2015-02-26T14:41:30.000Z | src/bounce/Bounce.cpp | Gigi1237/Bounce | 6e674dd7babda0192b930cc532f692c75219d1fd | [
"MIT"
] | null | null | null | #include "Bounce.h"
#include <iostream>
//#include <intrin.h> - Not needed on linux
World *world;
void ClearScreen()
{
std::cout << std::string(100, '\n');
}
void handleUp(int action)
{
//if (action == 1){
ClearScreen();
World::setGravity(World::getGravity() + 0.5f);
std::cout << World::getGravity();
//}
}
void handleDown(int action)
{
//if (action == 1){
ClearScreen();
World::setGravity(World::getGravity() - 0.5f);
std::cout << World::getGravity();
//}
}
void handleSpace(int action)
{
if (action == 1){
world->loadFromXml(XML_PATH"world.xml", TEXTURE_PATH);
}
}
int main()
{
ClearScreen();
IFade2D *graphics = new_IFade2d(1280, 720, "Bounce!");
world = new World(graphics);
World::setGravity(9.81f);
world->loadFromXml(XML_PATH"world.xml", TEXTURE_PATH);
graphics->setKeyPressHandler(up, &handleUp);
graphics->setKeyPressHandler(down, &handleDown);
graphics->setKeyPressHandler(space, &handleSpace);
world->initClock();
while (graphics->windowShouldClose()){
graphics->prepareScene();
world->update();
world->draw();
graphics->swapBuffer();
}
delete graphics;
delete world;
return 0;
}
| 20.55 | 62 | 0.622871 | Gigi1237 |
afb142fff97a1c2d73ccad2dabee4c031dd69a8f | 991 | cpp | C++ | luogu/codes/P1311.cpp | Tony031218/OI | 562f5f45d0448f4eab77643b99b825405a123d92 | [
"MIT"
] | 1 | 2021-02-22T03:39:24.000Z | 2021-02-22T03:39:24.000Z | luogu/codes/P1311.cpp | Tony031218/OI | 562f5f45d0448f4eab77643b99b825405a123d92 | [
"MIT"
] | null | null | null | luogu/codes/P1311.cpp | Tony031218/OI | 562f5f45d0448f4eab77643b99b825405a123d92 | [
"MIT"
] | null | null | null | /*************************************************************
* > File Name : P1311.cpp
* > Author : Tony
* > Created Time : 2019/10/20 19:31:08
* > Algorithm :
**************************************************************/
#include <bits/stdc++.h>
using namespace std;
inline int read() {
int x = 0; int f = 1; char ch = getchar();
while (!isdigit(ch)) {if (ch == '-') f = -1; ch = getchar();}
while (isdigit(ch)) {x = x * 10 + ch - 48; ch = getchar();}
return x * f;
}
const int maxn = 200010;
int n, k, p, las[maxn], sum[maxn], vis[maxn];
int main() {
n = read(); k = read(); p = read();
int now = 0, ans = 0;
for (int i = 1; i <= n; ++i) {
int col = read(), pri = read();
if (pri <= p) {
now = i;
}
if (now >= las[col]) {
sum[col] = vis[col];
}
las[col] = i; vis[col]++;
ans += sum[col];
}
printf("%d\n", ans);
return 0;
} | 26.078947 | 65 | 0.379415 | Tony031218 |
afb258add685e6ea7e2995fbc57674ba17d6b48f | 677 | hpp | C++ | TheMachine/include/TheMachine/utils.hpp | adepierre/TheMachine | 96df7775a4a6745802ab76649a63a4d16641a54b | [
"MIT"
] | 1 | 2021-09-24T10:05:52.000Z | 2021-09-24T10:05:52.000Z | TheMachine/include/TheMachine/utils.hpp | adepierre/TheMachine | 96df7775a4a6745802ab76649a63a4d16641a54b | [
"MIT"
] | null | null | null | TheMachine/include/TheMachine/utils.hpp | adepierre/TheMachine | 96df7775a4a6745802ab76649a63a4d16641a54b | [
"MIT"
] | null | null | null | #pragma once
#include <opencv2/core.hpp>
struct Detection
{
float x1, y1, x2, y2;
float score;
int cls;
};
void DrawRectangle(cv::Mat& img, const Detection& d, const cv::Scalar& color);
void DrawDetection(cv::Mat& img, const Detection& d, const cv::Scalar& color);
void DrawPerson(cv::Mat& img, const Detection& d, const cv::Scalar& color);
void DrawCar(cv::Mat& img, const Detection& d, const cv::Scalar& color);
cv::Point2f RotatePoint(const cv::Point2f& inPoint, const cv::Point2f& center, const float& angDeg);
void DrawTrain(cv::Mat& img, const Detection& d, const cv::Scalar& color);
void DrawPlane(cv::Mat& img, const Detection& d, const cv::Scalar& color);
| 27.08 | 100 | 0.713442 | adepierre |
afbeb2766cd84485a0e217549e064cb65b22fda5 | 109 | hpp | C++ | inc/receive_msg.hpp | os-chat/Chat | 71d4750030a285fe5dab466d52f6d18f8f70ef07 | [
"MIT"
] | null | null | null | inc/receive_msg.hpp | os-chat/Chat | 71d4750030a285fe5dab466d52f6d18f8f70ef07 | [
"MIT"
] | null | null | null | inc/receive_msg.hpp | os-chat/Chat | 71d4750030a285fe5dab466d52f6d18f8f70ef07 | [
"MIT"
] | null | null | null | #ifndef RECEIVE_MSG_HPP
#define RECEIVE_MSG_HPP
#include "common.hpp"
void *receive_msg(void *ptr);
#endif | 13.625 | 29 | 0.779817 | os-chat |
afc0d98a7d0cbb89cdb834e40f8505129adeb8d5 | 4,137 | tpp | C++ | base/serialization.tpp | BowenforGit/Grasper | 268468d6eb0a56e9a4815c0c1d7660b06bf8a1f7 | [
"Apache-2.0"
] | 29 | 2019-11-18T14:25:05.000Z | 2022-02-10T07:21:48.000Z | base/serialization.tpp | BowenforGit/Grasper | 268468d6eb0a56e9a4815c0c1d7660b06bf8a1f7 | [
"Apache-2.0"
] | 2 | 2021-03-17T03:17:38.000Z | 2021-04-11T04:06:23.000Z | base/serialization.tpp | BowenforGit/Grasper | 268468d6eb0a56e9a4815c0c1d7660b06bf8a1f7 | [
"Apache-2.0"
] | 6 | 2019-11-21T18:04:15.000Z | 2022-03-01T02:48:50.000Z | /* Copyright 2019 Husky Data Lab, CUHK
Authors: Created by Hongzhi Chen ([email protected])
*/
template <class T>
ibinstream& operator<<(ibinstream& m, const T* p) {
return m << *p;
}
template <class T>
ibinstream& operator<<(ibinstream& m, const vector<T>& v) {
m << v.size();
for (typename vector<T>::const_iterator it = v.begin(); it != v.end(); ++it) {
m << *it;
}
return m;
}
template <class T>
ibinstream& operator<<(ibinstream& m, const list<T>& v) {
m << v.size();
for (typename list<T>::const_iterator it = v.begin(); it != v.end(); ++it) {
m << *it;
}
return m;
}
template <class T>
ibinstream& operator<<(ibinstream& m, const set<T>& v) {
m << v.size();
for (typename set<T>::const_iterator it = v.begin(); it != v.end(); ++it) {
m << *it;
}
return m;
}
template <class T1, class T2>
ibinstream& operator<<(ibinstream& m, const pair<T1, T2>& v) {
m << v.first;
m << v.second;
return m;
}
template <class KeyT, class ValT>
ibinstream& operator<<(ibinstream& m, const map<KeyT, ValT>& v) {
m << v.size();
for (typename map<KeyT, ValT>::const_iterator it = v.begin(); it != v.end(); ++it) {
m << it->first;
m << it->second;
}
return m;
}
template <class KeyT, class ValT>
ibinstream& operator<<(ibinstream& m, const hash_map<KeyT, ValT>& v) {
m << v.size();
for (typename hash_map<KeyT, ValT>::const_iterator it = v.begin(); it != v.end(); ++it) {
m << it->first;
m << it->second;
}
return m;
}
template <class T>
ibinstream& operator<<(ibinstream& m, const hash_set<T>& v) {
m << v.size();
for (typename hash_set<T>::const_iterator it = v.begin(); it != v.end(); ++it) {
m << *it;
}
return m;
}
template <class T, class _HashFcn, class _EqualKey >
ibinstream& operator<<(ibinstream& m, const hash_set<T, _HashFcn, _EqualKey>& v) {
m << v.size();
for (typename hash_set<T, _HashFcn, _EqualKey>::const_iterator it = v.begin(); it != v.end(); ++it) {
m << *it;
}
return m;
}
template <class T>
obinstream& operator>>(obinstream& m, T*& p) {
p = new T;
return m >> (*p);
}
template <class T>
obinstream& operator>>(obinstream& m, vector<T>& v) {
size_t size;
m >> size;
v.resize(size);
for (typename vector<T>::iterator it = v.begin(); it != v.end(); ++it) {
m >> *it;
}
return m;
}
template <class T>
obinstream& operator>>(obinstream& m, list<T>& v) {
v.clear();
size_t size;
m >> size;
for (size_t i = 0; i < size; i++) {
T tmp;
m >> tmp;
v.push_back(tmp);
}
return m;
}
template <class T>
obinstream& operator>>(obinstream& m, set<T>& v) {
v.clear();
size_t size;
m >> size;
for (size_t i = 0; i < size; i++) {
T tmp;
m >> tmp;
v.insert(v.end(), tmp);
}
return m;
}
template <class T1, class T2>
obinstream& operator>>(obinstream& m, pair<T1, T2>& v) {
m >> v.first;
m >> v.second;
return m;
}
template <class KeyT, class ValT>
obinstream& operator>>(obinstream& m, map<KeyT, ValT>& v) {
v.clear();
size_t size;
m >> size;
for (size_t i = 0; i < size; i++) {
KeyT key;
m >> key;
m >> v[key];
}
return m;
}
template <class KeyT, class ValT>
obinstream& operator>>(obinstream& m, hash_map<KeyT, ValT>& v) {
v.clear();
size_t size;
m >> size;
for (size_t i = 0; i < size; i++) {
KeyT key;
m >> key;
m >> v[key];
}
return m;
}
template <class T>
obinstream& operator>>(obinstream& m, hash_set<T>& v) {
v.clear();
size_t size;
m >> size;
for (size_t i = 0; i < size; i++) {
T key;
m >> key;
v.insert(key);
}
return m;
}
template <class T, class _HashFcn, class _EqualKey >
obinstream& operator>>(obinstream& m, hash_set<T, _HashFcn, _EqualKey>& v) {
v.clear();
size_t size;
m >> size;
for (size_t i = 0; i < size; i++) {
T key;
m >> key;
v.insert(key);
}
return m;
}
| 22.483696 | 105 | 0.539521 | BowenforGit |
afc86f98606a6be02eecf6dc0f15664affe8a493 | 841 | cc | C++ | libmat/test/src/test_cr_cColItr_all.cc | stiegerc/winterface | b6d501df1d0c015f2cd7126ac6b4e746d541c80c | [
"BSD-2-Clause"
] | 2 | 2020-10-06T09:14:23.000Z | 2020-11-25T06:08:54.000Z | libmat/test/src/test_cr_cColItr_all.cc | stiegerc/Winterface | b6d501df1d0c015f2cd7126ac6b4e746d541c80c | [
"BSD-2-Clause"
] | 1 | 2020-12-23T04:20:33.000Z | 2020-12-23T04:20:33.000Z | libmat/test/src/test_cr_cColItr_all.cc | stiegerc/Winterface | b6d501df1d0c015f2cd7126ac6b4e746d541c80c | [
"BSD-2-Clause"
] | 1 | 2020-07-14T13:53:32.000Z | 2020-07-14T13:53:32.000Z | // 2014-2019, ETH Zurich, Integrated Systems Laboratory
// Authors: Christian Stieger
#include "testTools.h"
#include "test_cr_tVecItr_all.h"
#include "test_cr_tVecItr_all.cc"
template<>
void test_cr_tVecItr_all<CPX__,RE__,CPX__,lm_tCol<CPX__,RE__,CPX__>>::test_dereference() {
const size_t M = genRndST();
const size_t N = genRndST();
const auto tMat1 = rnd<cMat>(M,N);
cr_tVecItr tItr1(&tMat1,N-1);
for (size_t n=0; n!=tMat1.N(); ++n)
CPPUNIT_ASSERT(tMat1.cAt(N-1-n)==tItr1[n]);
for (size_t n=0; n!=tMat1.N(); ++n,++tItr1)
CPPUNIT_ASSERT(tMat1.cAt(N-1-n)==*tItr1);
}
// test id
template<>
const char* test_cr_tVecItr_all<CPX__,RE__,CPX__,lm_tCol<CPX__,RE__,CPX__>>::test_id() noexcept {
return "test_cr_cColItr_all";
}
// instantiation
template class test_cr_tVecItr_all<CPX__,RE__,CPX__,lm_tCol<CPX__,RE__,CPX__>>;
| 24.735294 | 97 | 0.72176 | stiegerc |
afcc23ae27949774542c6cb63d9a826e503cce32 | 7,678 | cpp | C++ | 2/second-lab/second-lab/app.cpp | i582/HLProgramming | 4d2da80c69f8e1014cbf7be9087bdec6b2c05d45 | [
"MIT"
] | null | null | null | 2/second-lab/second-lab/app.cpp | i582/HLProgramming | 4d2da80c69f8e1014cbf7be9087bdec6b2c05d45 | [
"MIT"
] | null | null | null | 2/second-lab/second-lab/app.cpp | i582/HLProgramming | 4d2da80c69f8e1014cbf7be9087bdec6b2c05d45 | [
"MIT"
] | null | null | null | #include "app.h"
App::App()
{
this->window = nullptr;
this->renderer = nullptr;
this->e = {};
this->running = true;
}
App::~App()
{
SDL_RemoveTimer(repeatOnceFunctionTimer);
SDL_RemoveTimer(customEventFunctionTimer);
SDL_Log("Старт разрушения окна");
SDL_DestroyWindow(window);
SDL_Log("разрушение окна успешно завершено");
SDL_Quit();
}
bool App::init()
{
SDL_Log("Начало создания окна");
this->window = SDL_CreateWindow("SDL2: Магические события",
SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED,
480, 640, SDL_WINDOW_ALLOW_HIGHDPI | SDL_WINDOW_RESIZABLE);
if (window == nullptr)
{
SDL_Log("Ошибка создания окна: %s\n", SDL_GetError());
return false;
}
this->renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
if (renderer == nullptr)
{
SDL_Log("Ошибка создания renderer! SDL Error: %s\n", SDL_GetError());
return false;
}
SDL_SetEventFilter(eventFilter, nullptr);
createTimers();
return true;
}
void App::setup()
{
}
void App::update()
{
}
void App::on_event()
{
SDL_WaitEvent(nullptr);
}
void App::quit()
{
running = false;
}
int App::run()
{
if (!init())
return -1;
setup();
update();
on_event();
return 0;
}
bool App::createTimers()
{
customEventFunctionTimer = SDL_AddTimer(2000 /* 2 sec */, customEventFunction, window);
if (customEventFunctionTimer == 0)
{
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Ошибка", "Невозможно создать кастомный событийный таймер. Расширенная информация в лог-файле.", window);
SDL_LogCritical(SDL_LOG_CATEGORY_APPLICATION, "Невозможно создать кастомный событийный таймер, ошибка: %s", SDL_GetError());
return false;
}
repeatOnceFunctionTimer = SDL_AddTimer(10000 /* 10 sec */, repeatOnceFunction, window);
if (repeatOnceFunctionTimer == 0)
{
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Ошибка", "Невозможно создать кастомный одноразовый таймер. Расширенная информация в лог-файле.", window);
SDL_LogCritical(SDL_LOG_CATEGORY_APPLICATION, "Невозможно создать кастомный одноразовый таймер, ошибка: %s", SDL_GetError());
return false;
}
return true;
}
void App::clearScreen(SDL_Window* window)
{
SDL_Surface* screen = SDL_GetWindowSurface(window);
SDL_FillRect(screen, nullptr, SDL_MapRGB(screen->format, rand() % 255, rand() % 255, rand() % 255));
SDL_UpdateWindowSurface(window);
}
Uint32 App::repeatOnceFunction(Uint32 interval, void* param)
{
SDL_Event exitEvent = { SDL_QUIT };
SDL_Log("Таймер работает с следующим интервалом %d мс", interval);
if (asmFunction() != 0)
{
SDL_HideWindow((SDL_Window*)param);
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_INFORMATION, "Что-то пошло не так", "Найди меня! Я потерялся!", nullptr);
SDL_Delay(15000); /* 15 sec */
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "Ты не нашел меня! Я расстроен тобою... я ухожу.");
SDL_PushEvent(&exitEvent);
}
return 0;
}
Uint32 App::customEventFunction(Uint32 interval, void* param)
{
SDL_Event event = { SDL_WINDOWEVENT };
SDL_Log("Таймер работает с следующим интервалом %d мс", interval);
event.window.windowID = SDL_GetWindowID((SDL_Window*)param);
event.window.event = SDL_WINDOWEVENT_EXPOSED;
SDL_PushEvent(&event);
return interval;
}
int App::asmFunction()
{
static int internalValue = 1;
#ifdef __GNUC__
__asm__("movl %0, %%eax\n\t"
"add %%eax, %0"
: "=r" (internalValue)
: "r" (internalValue));
#elif _MSC_VER
_asm {
mov eax, internalValue
add internalValue, eax
};
#endif
return internalValue;
}
int App::eventFilter(void* userdata, SDL_Event* event)
{
switch (event->type)
{
case SDL_KEYDOWN:
if (event->key.keysym.sym == SDLK_q && event->key.keysym.mod == KMOD_CTRL)
{
SDL_Event exitEvent = { SDL_QUIT };
SDL_PushEvent(&exitEvent);
}
SDL_Log("нажатие кнопки %d", event->key.keysym.sym);
break;
case SDL_KEYUP:
SDL_Log("отжатие кнопки %d", event->key.keysym.sym);
break;
case SDL_TEXTEDITING:
SDL_Log("Клавиатурное исправление (композиция). Композия: '%s', курсор начал с %d и выбрал длину в %d", event->edit.text, event->edit.start, event->edit.length);
break;
case SDL_TEXTINPUT:
SDL_Log("Клавиатурный ввод. Текст: '%s'", event->text.text);
break;
case SDL_FINGERMOTION:
SDL_Log("Пальчик водится: %lld, x: %f, y: %f", event->tfinger.fingerId, event->tfinger.x, event->tfinger.y);
break;
case SDL_FINGERDOWN:
SDL_Log("Пальчик: %lld вниз - x: %f, y: %f",
event->tfinger.fingerId, event->tfinger.x, event->tfinger.y);
return 1;
case SDL_FINGERUP:
SDL_Log("Пальчик: %lld вверх - x: %f, y: %f", event->tfinger.fingerId, event->tfinger.x, event->tfinger.y);
break;
case SDL_MULTIGESTURE:
SDL_Log("Мульти тач: x = %f, y = %f, dAng = %f, dR = %f", event->mgesture.x, event->mgesture.y, event->mgesture.dTheta, event->mgesture.dDist);
SDL_Log("Мульти тач: нажатие пальца = %i", event->mgesture.numFingers);
break;
case SDL_DOLLARGESTURE:
SDL_Log("Записываемый %lld получен, ошибка: %f", event->dgesture.gestureId, event->dgesture.error);
break;
case SDL_DOLLARRECORD:
SDL_Log("Записываемый черт: %lld", event->dgesture.gestureId);
break;
case SDL_MOUSEMOTION:
SDL_Log("Мышинный сдвиг. X=%d, Y=%d, ИзмененияX=%d, ИзмененияY=%d", event->motion.x, event->motion.y, event->motion.xrel, event->motion.yrel);
break;
case SDL_MOUSEBUTTONDOWN:
if (event->button.button == SDL_BUTTON_LEFT)
asmFunction();
SDL_Log("Мышинный Кнопка Вниз %u", event->button.button);
break;
case SDL_MOUSEBUTTONUP:
SDL_Log("Мышинный Кнопка Вверх %u", event->button.button);
break;
case SDL_MOUSEWHEEL:
SDL_Log("Мышинный Колесо X=%d, Y=%d", event->wheel.x, event->wheel.y);
break;
case SDL_QUIT:
SDL_Log("Пользовательский выход");
return 1;
case SDL_WINDOWEVENT:
switch (event->window.event)
{
case SDL_WINDOWEVENT_SHOWN:
SDL_Log("Окно %d показано", event->window.windowID);
break;
case SDL_WINDOWEVENT_HIDDEN:
SDL_Log("Окно %d скрыто", event->window.windowID);
break;
case SDL_WINDOWEVENT_EXPOSED:
clearScreen(SDL_GetWindowFromID(event->window.windowID));
SDL_Log("Окно %d сдвинуто", event->window.windowID);
break;
case SDL_WINDOWEVENT_MOVED:
SDL_Log("Окно %d перемещенно в %d,%d", event->window.windowID, event->window.data1, event->window.data2);
break;
case SDL_WINDOWEVENT_RESIZED:
SDL_Log("Окно %d изменено до %dx%d", event->window.windowID, event->window.data1, event->window.data2);
break;
case SDL_WINDOWEVENT_SIZE_CHANGED:
SDL_Log("Окно %d изменила размер до %dx%d", event->window.windowID, event->window.data1, event->window.data2);
break;
case SDL_WINDOWEVENT_MINIMIZED:
SDL_Log("Окно %d свернуто", event->window.windowID);
break;
case SDL_WINDOWEVENT_MAXIMIZED:
SDL_Log("Окно %d развернуто", event->window.windowID);
break;
case SDL_WINDOWEVENT_RESTORED:
SDL_Log("Окно %d восстановленно", event->window.windowID);
break;
case SDL_WINDOWEVENT_ENTER:
SDL_Log("Мышь пришла к окну %d", event->window.windowID);
break;
case SDL_WINDOWEVENT_LEAVE:
SDL_Log("Мышь покинула окна %d", event->window.windowID);
break;
case SDL_WINDOWEVENT_FOCUS_GAINED:
SDL_Log("Окно %d получило фокус клавиатуры", event->window.windowID);
break;
case SDL_WINDOWEVENT_FOCUS_LOST:
SDL_Log("Окно %d потеряла фокус клавиатуры", event->window.windowID);
break;
case SDL_WINDOWEVENT_CLOSE:
SDL_Log("Окно %d закрыто", event->window.windowID);
break;
default:
SDL_Log("Окно %d получило неизвестное событие %d", event->window.windowID, event->window.event);
break;
}
break;
default:
SDL_Log("Получен неизвестное событие %d", event->type);
break;
}
return 0;
}
| 23.057057 | 163 | 0.711383 | i582 |
afcdcc50e1f4f31417bb60aa43ec84ee85e55e0b | 2,779 | hpp | C++ | src/CAghostnodes.hpp | streeve/ExaCA | f6bd298d9719edfe948ce629369f02ac7c18c65b | [
"MIT"
] | 13 | 2021-06-04T14:50:33.000Z | 2022-03-26T03:21:17.000Z | src/CAghostnodes.hpp | streeve/ExaCA | f6bd298d9719edfe948ce629369f02ac7c18c65b | [
"MIT"
] | 30 | 2021-07-21T23:13:34.000Z | 2022-03-29T18:37:19.000Z | src/CAghostnodes.hpp | streeve/ExaCA | f6bd298d9719edfe948ce629369f02ac7c18c65b | [
"MIT"
] | 5 | 2021-07-21T23:36:12.000Z | 2022-03-11T00:52:15.000Z | // Copyright 2021 Lawrence Livermore National Security, LLC and other ExaCA Project Developers.
// See the top-level LICENSE file for details.
//
// SPDX-License-Identifier: MIT
#ifndef EXACA_GHOST_HPP
#define EXACA_GHOST_HPP
#include "CAtypes.hpp"
#include <Kokkos_Core.hpp>
void GhostNodesInit(int, int, int DecompositionStrategy, int NeighborRank_North, int NeighborRank_South,
int NeighborRank_East, int NeighborRank_West, int NeighborRank_NorthEast,
int NeighborRank_NorthWest, int NeighborRank_SouthEast, int NeighborRank_SouthWest, int MyXSlices,
int MyYSlices, int MyXOffset, int MyYOffset, int ZBound_Low, int nzActive,
int LocalActiveDomainSize, int NGrainOrientations, ViewI NeighborX, ViewI NeighborY,
ViewI NeighborZ, ViewF GrainUnitVector, ViewI GrainOrientation, ViewI GrainID, ViewI CellType,
ViewF DOCenter, ViewF DiagonalLength, ViewF CritDiagonalLength);
void GhostNodes2D(int, int, int NeighborRank_North, int NeighborRank_South, int NeighborRank_East,
int NeighborRank_West, int NeighborRank_NorthEast, int NeighborRank_NorthWest,
int NeighborRank_SouthEast, int NeighborRank_SouthWest, int MyXSlices, int MyYSlices, int MyXOffset,
int MyYOffset, ViewI NeighborX, ViewI NeighborY, ViewI NeighborZ, ViewI CellType, ViewF DOCenter,
ViewI GrainID, ViewF GrainUnitVector, ViewI GrainOrientation, ViewF DiagonalLength,
ViewF CritDiagonalLength, int NGrainOrientations, Buffer2D BufferWestSend, Buffer2D BufferEastSend,
Buffer2D BufferNorthSend, Buffer2D BufferSouthSend, Buffer2D BufferNorthEastSend,
Buffer2D BufferNorthWestSend, Buffer2D BufferSouthEastSend, Buffer2D BufferSouthWestSend,
Buffer2D BufferWestRecv, Buffer2D BufferEastRecv, Buffer2D BufferNorthRecv, Buffer2D BufferSouthRecv,
Buffer2D BufferNorthEastRecv, Buffer2D BufferNorthWestRecv, Buffer2D BufferSouthEastRecv,
Buffer2D BufferSouthWestRecv, int BufSizeX, int BufSizeY, int BufSizeZ, int ZBound_Low);
void GhostNodes1D(int, int, int NeighborRank_North, int NeighborRank_South, int MyXSlices, int MyYSlices, int MyXOffset,
int MyYOffset, ViewI NeighborX, ViewI NeighborY, ViewI NeighborZ, ViewI CellType, ViewF DOCenter,
ViewI GrainID, ViewF GrainUnitVector, ViewI GrainOrientation, ViewF DiagonalLength,
ViewF CritDiagonalLength, int NGrainOrientations, Buffer2D BufferNorthSend, Buffer2D BufferSouthSend,
Buffer2D BufferNorthRecv, Buffer2D BufferSouthRecv, int BufSizeX, int, int BufSizeZ, int ZBound_Low);
#endif
| 73.131579 | 120 | 0.732997 | streeve |
afd03638568c09eb7f19f3eaa4843bdc98beca12 | 10,745 | hpp | C++ | include/Library/Astrodynamics/Trajectory/Orbit/Models/Kepler.hpp | cowlicks/library-astrodynamics | aec161a1e5a1294820a90e1a74633b5a71d59a33 | [
"Apache-2.0"
] | null | null | null | include/Library/Astrodynamics/Trajectory/Orbit/Models/Kepler.hpp | cowlicks/library-astrodynamics | aec161a1e5a1294820a90e1a74633b5a71d59a33 | [
"Apache-2.0"
] | null | null | null | include/Library/Astrodynamics/Trajectory/Orbit/Models/Kepler.hpp | cowlicks/library-astrodynamics | aec161a1e5a1294820a90e1a74633b5a71d59a33 | [
"Apache-2.0"
] | null | null | null | ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @project Library/Astrodynamics
/// @file Library/Astrodynamics/Trajectory/Orbit/Models/Kepler.hpp
/// @author Lucas Brémond <[email protected]>
/// @license Apache License 2.0
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#ifndef __Library_Astrodynamics_Trajectory_Orbit_Models_Kepler__
#define __Library_Astrodynamics_Trajectory_Orbit_Models_Kepler__
#include <Library/Astrodynamics/Trajectory/Orbit/Models/Kepler/COE.hpp>
#include <Library/Astrodynamics/Trajectory/Orbit/Model.hpp>
#include <Library/Astrodynamics/Trajectory/State.hpp>
#include <Library/Physics/Environment/Objects/Celestial.hpp>
#include <Library/Physics/Units/Derived.hpp>
#include <Library/Physics/Units/Length.hpp>
#include <Library/Physics/Time/Instant.hpp>
#include <Library/Core/Types/String.hpp>
#include <Library/Core/Types/Real.hpp>
#include <Library/Core/Types/Integer.hpp>
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
namespace library
{
namespace astro
{
namespace trajectory
{
namespace orbit
{
namespace models
{
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
using library::core::types::Integer ;
using library::core::types::Real ;
using library::core::types::String ;
using library::physics::time::Instant ;
using library::physics::units::Length ;
using library::physics::units::Derived ;
using library::physics::env::obj::Celestial ;
using library::astro::trajectory::State ;
using library::astro::trajectory::orbit::models::kepler::COE ;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
class Kepler : public library::astro::trajectory::orbit::Model
{
public:
enum class PerturbationType
{
None,
J2
} ;
Kepler ( const COE& aClassicalOrbitalElementSet,
const Instant& anEpoch,
const Derived& aGravitationalParameter,
const Length& anEquatorialRadius,
const Real& aJ2,
const Kepler::PerturbationType& aPerturbationType ) ;
Kepler ( const COE& aClassicalOrbitalElementSet,
const Instant& anEpoch,
const Celestial& aCelestialObject,
const Kepler::PerturbationType& aPerturbationType,
const bool inFixedFrame = false ) ;
virtual Kepler* clone ( ) const override ;
bool operator == ( const Kepler& aKeplerianModel ) const ;
bool operator != ( const Kepler& aKeplerianModel ) const ;
friend std::ostream& operator << ( std::ostream& anOutputStream,
const Kepler& aKeplerianModel ) ;
virtual bool isDefined ( ) const override ;
COE getClassicalOrbitalElements ( ) const ;
virtual Instant getEpoch ( ) const override ;
virtual Integer getRevolutionNumberAtEpoch ( ) const override ;
Derived getGravitationalParameter ( ) const ;
Length getEquatorialRadius ( ) const ;
Real getJ2 ( ) const ;
Kepler::PerturbationType getPerturbationType ( ) const ;
virtual State calculateStateAt ( const Instant& anInstant ) const override ;
virtual Integer calculateRevolutionNumberAt ( const Instant& anInstant ) const override ; // [TBR] ?
virtual void print ( std::ostream& anOutputStream,
bool displayDecorator = true ) const override ;
static String StringFromPerturbationType ( const Kepler::PerturbationType& aPerturbationType ) ;
protected:
virtual bool operator == ( const trajectory::Model& aModel ) const override ;
virtual bool operator != ( const trajectory::Model& aModel ) const override ;
private:
COE coe_ ;
Instant epoch_ ;
Derived gravitationalParameter_ ;
Length equatorialRadius_ ;
Real j2_ ;
Kepler::PerturbationType perturbationType_ ;
static COE InertialCoeFromFixedCoe ( const COE& aClassicalOrbitalElementSet,
const Instant& anEpoch,
const Celestial& aCelestialObject ) ;
static State CalculateNoneStateAt ( const COE& aClassicalOrbitalElementSet,
const Instant& anEpoch,
const Derived& aGravitationalParameter,
const Instant& anInstant ) ;
static Integer CalculateNoneRevolutionNumberAt ( const COE& aClassicalOrbitalElementSet,
const Instant& anEpoch,
const Derived& aGravitationalParameter,
const Instant& anInstant ) ;
static State CalculateJ2StateAt ( const COE& aClassicalOrbitalElementSet,
const Instant& anEpoch,
const Derived& aGravitationalParameter,
const Instant& anInstant,
const Length& anEquatorialRadius,
const Real& aJ2 ) ;
static Integer CalculateJ2RevolutionNumberAt ( const COE& aClassicalOrbitalElementSet,
const Instant& anEpoch,
const Derived& aGravitationalParameter,
const Instant& anInstant,
const Length& anEquatorialRadius,
const Real& aJ2 ) ;
} ;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
}
}
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#endif
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// | 62.47093 | 189 | 0.304514 | cowlicks |
afd146c0ac57d6534ef3fe0cfe39762f126d39fb | 6,793 | cpp | C++ | frameworks/lua/libs/kernel/dmzLuaKernelHandle.cpp | ashok/dmz | 2f8d4bced646f25abf2e98bdc0d378dafb4b32ed | [
"MIT"
] | 1 | 2015-11-05T03:03:31.000Z | 2015-11-05T03:03:31.000Z | frameworks/lua/libs/kernel/dmzLuaKernelHandle.cpp | ashok/dmz | 2f8d4bced646f25abf2e98bdc0d378dafb4b32ed | [
"MIT"
] | null | null | null | frameworks/lua/libs/kernel/dmzLuaKernelHandle.cpp | ashok/dmz | 2f8d4bced646f25abf2e98bdc0d378dafb4b32ed | [
"MIT"
] | null | null | null | #include <dmzLuaKernel.h>
#include "dmzLuaKernelPrivate.h"
#include <dmzLuaKernelValidate.h>
#include <dmzRuntimeDefinitions.h>
#include <dmzSystem.h>
#include <dmzTypesHashTableHandleTemplate.h>
#include <dmzTypesString.h>
#include <luacpp.h>
using namespace dmz;
namespace {
static const char HandleName[] = "dmz.types.handle";
static const char HandleTableName[] = "dmz.types.handle.table";
static const char HandleTableKey = 'h';
static const char LuaHandleTableKey = 'l';
typedef HashTableHandleTemplate<int> HandleTable;
static HandleTable *
get_handle_table (lua_State *L) {
lua_pushlightuserdata (L, (void *)&HandleTableKey);
lua_rawget(L, LUA_REGISTRYINDEX);
HandleTable **ptr = (HandleTable **)lua_touserdata (L, -1);
lua_pop (L, 1); // pop user data
return ptr ? *ptr : 0;
}
static int
handle_table_delete (lua_State *L) {
HandleTable **ptr = (HandleTable **)lua_touserdata (L, 1);
if (ptr && *ptr) { delete (*ptr); *ptr = 0; }
return 0;
}
inline Handle*
handle_check (lua_State *L, int index) {
LUA_START_VALIDATE (L);
if (index < 0) { index = lua_gettop (L) + index + 1; }
Handle *result (0);
if (lua_isnumber (L, index)) {
Handle value = (Handle)lua_tonumber (L, index);
if (value) {
result = lua_create_handle (L, value);
lua_replace (L, index); // Replace string with handle
}
}
else if (lua_isstring (L, index)) {
String name = lua_tostring (L, index);
if (name) {
Definitions def (lua_get_runtime_context (L));
Handle value = def.create_named_handle (name);
result = lua_create_handle (L, value);
lua_replace (L, index); // Replace string with handle
}
else {
lua_pushstring (L, "Empty string can not be converted to named handle");
lua_error (L);
}
}
else { result = (Handle *)luaL_checkudata (L, index, HandleName); }
LUA_END_VALIDATE (L, 0);
return result;
}
static int
handle_new (lua_State *L) {
lua_pushvalue (L, 1);
return handle_check (L, -1) ? 1 : 0;
}
static int
handle_is_a (lua_State *L) {
if (lua_to_handle (L, 1)) { lua_pushvalue (L, 1); }
else { lua_pushnil (L); }
return 1;
}
static const luaL_Reg arrayFunc [] = {
{"new", handle_new},
{"is_a", handle_is_a},
{NULL, NULL},
};
static int
handle_to_string (lua_State *L) {
LUA_START_VALIDATE (L);
int result (0);
Handle *handle = handle_check (L, 1);
if (handle) {
String str;
str << *handle;
lua_pushstring (L, str.get_buffer ());
result = 1;
}
LUA_END_VALIDATE (L, result);
return result;
}
static int
handle_equal (lua_State *L) {
int result (0);
Handle *handle1 = handle_check (L, 1);
Handle *handle2 = handle_check (L, 2);
if (handle1 && handle2) {
lua_pushboolean (L, (handle1 == handle2 ? 1 : 0));
result = 1;
}
return result;
}
static int
handle_delete (lua_State *L) {
LUA_START_VALIDATE (L);
Handle *ptr = handle_check (L, 1);
HandleTable *ht = get_handle_table (L);
if (ptr && ht) {
lua_pushlightuserdata (L, (void *)&LuaHandleTableKey);
lua_rawget (L, LUA_REGISTRYINDEX);
const int Table (lua_gettop (L));
if (lua_istable (L, Table)) {
int *indexPtr = ht->lookup (*ptr);
if (indexPtr) {
lua_rawgeti (L, Table, *indexPtr);
Handle *found = (Handle *)lua_touserdata (L, -1);
if (!found) {
if (ht->remove (*ptr)) { delete indexPtr; indexPtr = 0; }
}
lua_pop (L, 1); // pop Handle;
}
}
lua_pop (L, 1); // pop Handle table
}
LUA_END_VALIDATE (L, 0);
return 0;
}
static const luaL_Reg arrayMembers [] = {
{"__tostring", handle_to_string},
{"__eq", handle_equal},
{"__gc", handle_delete},
{NULL, NULL},
};
};
//! \cond
void
dmz::open_lua_kernel_handle_lib (lua_State *L) {
LUA_START_VALIDATE (L);
lua_pushlightuserdata (L, (void *)&HandleTableKey);
HandleTable **htPtr = (HandleTable **)lua_newuserdata (L, sizeof (HandleTable *));
if (htPtr) {
lua_set_gc (L, -1, handle_table_delete);
*htPtr = new HandleTable;
lua_rawset (L, LUA_REGISTRYINDEX);
}
else { lua_pop (L, 1); } // pop light user data
lua_pushlightuserdata (L, (void *)&LuaHandleTableKey);
lua_newtable (L);
lua_set_weak_table (L, -1, "v");
lua_rawset (L, LUA_REGISTRYINDEX);
luaL_newmetatable (L, HandleName);
luaL_register (L, NULL, arrayMembers);
lua_pushvalue (L, -1);
lua_setfield (L, -2, "__index");
lua_create_dmz_namespace (L, "handle");
luaL_register (L, NULL, arrayFunc);
lua_make_readonly (L, -1); // make handle read only.
lua_pop (L, 2); // pops meta table and dmz.handle table.
LUA_END_VALIDATE (L, 0);
}
//! \endcond
//! \addtogroup Lua
//! @{
//! Creates a Handle on the Lua stack.
dmz::Handle *
dmz::lua_create_handle (lua_State *L, const Handle Value) {
LUA_START_VALIDATE (L);
Handle *result = 0;
if (Value) {
HandleTable *ht (get_handle_table (L));
lua_pushlightuserdata (L, (void *)&LuaHandleTableKey);
lua_rawget (L, LUA_REGISTRYINDEX);
const int Table (lua_gettop (L));
if (lua_istable (L, Table) && ht) {
int *indexPtr = ht->lookup (Value);
if (indexPtr) {
lua_rawgeti (L, Table, *indexPtr);
result = (Handle *)lua_touserdata (L, -1);
if (!result) { lua_pop (L, 1); }
else if (*result != Value) {
lua_pop (L, 1); // pop invalid Handle;
result = 0;
}
}
if (!result) {
if (indexPtr && ht->remove (Value)) { delete indexPtr; indexPtr = 0; }
result = (Handle *)lua_newuserdata (L, sizeof (Handle));
if (result) {
lua_pushvalue (L, -1);
int index = luaL_ref (L, Table);
indexPtr = new int (index);
if (!ht->store (Value, indexPtr)) { delete indexPtr; indexPtr = 0; }
*result = Value;
luaL_getmetatable (L, HandleName);
lua_setmetatable (L, -2);
}
}
}
lua_remove (L, Table); // Remove Table;
}
if (!result) { lua_pushnil (L); }
LUA_END_VALIDATE (L, 1);
return result;
}
//! Attempts to convert the specified object on the Lua stack to a Handle.
dmz::Handle *
dmz::lua_to_handle (lua_State *L, int narg) {
return (Handle *) lua_is_object (L, narg, HandleName);
}
//! Raises and error if the specified object on the stack is not a Handle.
dmz::Handle *
dmz::lua_check_handle (lua_State *L, int narg) { return handle_check (L, narg); }
//! @}
| 20.901538 | 85 | 0.596055 | ashok |
afdafc445a97e97903270769867114615ec67fd1 | 268 | cpp | C++ | timus/2100.cpp | y-wan/OJ | 5dea140dbaaec98e440ad4b1c10fa5072f1ceea7 | [
"MIT"
] | null | null | null | timus/2100.cpp | y-wan/OJ | 5dea140dbaaec98e440ad4b1c10fa5072f1ceea7 | [
"MIT"
] | null | null | null | timus/2100.cpp | y-wan/OJ | 5dea140dbaaec98e440ad4b1c10fa5072f1ceea7 | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
using namespace std;
int main() {
int n;
string s;
cin >> n;
int sum = n + 2;
for (int i = 0; i < n; i++) {
cin >> s;
if (s[s.size() - 4] == '+') sum++;
}
if (sum == 13) sum++;
cout << 100 * sum << endl;
return 0;
}
| 14.888889 | 36 | 0.496269 | y-wan |
afdc73c0e5a987e35e16416b60dd714a5847b7ee | 1,657 | cpp | C++ | test/src/MISC/Common/LongRunningOperation.cpp | theoremprover/cpp-parser | 543cd50acc9e08aadf278b9c970d4db6c332887a | [
"BSD-3-Clause"
] | 18 | 2018-05-10T18:50:06.000Z | 2022-01-11T17:11:34.000Z | test/src/MISC/Common/LongRunningOperation.cpp | theoremprover/cpp-parser | 543cd50acc9e08aadf278b9c970d4db6c332887a | [
"BSD-3-Clause"
] | 24 | 2018-06-14T17:54:17.000Z | 2022-03-11T23:21:29.000Z | test/src/MISC/Common/LongRunningOperation.cpp | theoremprover/cpp-parser | 543cd50acc9e08aadf278b9c970d4db6c332887a | [
"BSD-3-Clause"
] | 4 | 2019-04-02T16:04:34.000Z | 2022-01-10T11:44:43.000Z | // This file is part of Notepad++ project
// Copyright (C)2003 Don HO <[email protected]>
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// Note that the GPL places important restrictions on "derived works", yet
// it does not provide a detailed definition of that term. To avoid
// misunderstandings, we consider an application to constitute a
// "derivative work" for the purpose of this license if it does any of the
// following:
// 1. Integrates source code from Notepad++.
// 2. Integrates/includes/aggregates Notepad++ into a proprietary executable
// installer, such as those produced by InstallShield.
// 3. Links to a library or executes a program that does any of the above.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#include "LongRunningOperation.h"
#include "mutex.h"
using namespace Yuni;
LongRunningOperation::LongRunningOperation()
{
Mutex::ClassLevelLockable<LongRunningOperation>::mutex.lock();
}
LongRunningOperation::~LongRunningOperation()
{
Mutex::ClassLevelLockable<LongRunningOperation>::mutex.unlock();
}
| 33.816327 | 76 | 0.754375 | theoremprover |
afe2e3508b335766c62fc986f31dba7fb2f00ecf | 911 | cpp | C++ | cppPrime/cppBrowse_c02/test_10.cpp | ilvcr/cpplgproject | d3dc492b37c3754e35669eee2dd96d83de63ead4 | [
"Apache-2.0"
] | null | null | null | cppPrime/cppBrowse_c02/test_10.cpp | ilvcr/cpplgproject | d3dc492b37c3754e35669eee2dd96d83de63ead4 | [
"Apache-2.0"
] | null | null | null | cppPrime/cppBrowse_c02/test_10.cpp | ilvcr/cpplgproject | d3dc492b37c3754e35669eee2dd96d83de63ead4 | [
"Apache-2.0"
] | null | null | null | /*************************************************************************
> File Name: test_10.cpp
> Author: @Yoghourt->ilvcr, Cn,Sx,Ty
> Mail: [email protected] || [email protected]
> Created Time: 2018年06月21日 星期四 23时30分40秒
> Description: 将泛型算法应用到vector类对象上
************************************************************************/
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int ia[10] = {51, 23, 7, 88, 41, 98, 12, 103, 37, 6};
int main()
{
vector<int> vec(ia, ia+10);
//排序数组
sort(vec.begin(), vec.end());
//获取值
int search_value;
cin >> search_value;
//搜索元素
vector<int>::iterator found;
found = find(vec.begin(), vec.end(), search_value);
if(found != vec.end())
cout << "search_value found!\n";
else cout << "search_value not found!\n";
//反转数组
reverse(vec.begin(), vec.end());
return 0;
}
| 23.358974 | 74 | 0.512623 | ilvcr |
afedea283c5bfd25ca1256f4f676b4c187dc5e08 | 7,233 | cpp | C++ | src/lz4mt_result.cpp | 1shekhar/lz4mt-cpp | a01631c2a5496c8d6335801d270b3d8688da078d | [
"BSD-2-Clause"
] | 140 | 2015-01-08T03:42:50.000Z | 2022-02-15T13:08:27.000Z | src/lz4mt_result.cpp | 1shekhar/lz4mt-cpp | a01631c2a5496c8d6335801d270b3d8688da078d | [
"BSD-2-Clause"
] | 15 | 2015-01-29T21:00:39.000Z | 2021-11-25T14:20:12.000Z | src/lz4mt_result.cpp | 1shekhar/lz4mt-cpp | a01631c2a5496c8d6335801d270b3d8688da078d | [
"BSD-2-Clause"
] | 40 | 2015-01-13T07:19:05.000Z | 2022-01-12T18:24:30.000Z | #include "lz4mt.h"
extern "C" const char*
lz4mtResultToString(Lz4MtResult result)
{
const char* s = "???";
switch(result) {
case LZ4MT_RESULT_OK:
s = "OK";
break;
case LZ4MT_RESULT_ERROR:
s = "ERROR";
break;
case LZ4MT_RESULT_INVALID_MAGIC_NUMBER:
s = "INVALID_MAGIC_NUMBER";
break;
case LZ4MT_RESULT_INVALID_HEADER:
s = "INVALID_HEADER";
break;
case LZ4MT_RESULT_PRESET_DICTIONARY_IS_NOT_SUPPORTED_YET:
s = "PRESET_DICTIONARY_IS_NOT_SUPPORTED_YET";
break;
case LZ4MT_RESULT_BLOCK_DEPENDENCE_IS_NOT_SUPPORTED_YET:
s = "BLOCK_DEPENDENCE_IS_NOT_SUPPORTED_YET";
break;
case LZ4MT_RESULT_INVALID_VERSION:
s = "INVALID_VERSION";
break;
case LZ4MT_RESULT_INVALID_HEADER_CHECKSUM:
s = "INVALID_HEADER_CHECKSUM";
break;
case LZ4MT_RESULT_INVALID_BLOCK_MAXIMUM_SIZE:
s = "INVALID_BLOCK_MAXIMUM_SIZE";
break;
case LZ4MT_RESULT_CANNOT_WRITE_HEADER:
s = "CANNOT_WRITE_HEADER";
break;
case LZ4MT_RESULT_CANNOT_WRITE_EOS:
s = "CANNOT_WRITE_EOS";
break;
case LZ4MT_RESULT_CANNOT_WRITE_STREAM_CHECKSUM:
s = "CANNOT_WRITE_STREAM_CHECKSUM";
break;
case LZ4MT_RESULT_CANNOT_READ_BLOCK_SIZE:
s = "CANNOT_READ_BLOCK_SIZE";
break;
case LZ4MT_RESULT_CANNOT_READ_BLOCK_DATA:
s = "CANNOT_READ_BLOCK_DATA";
break;
case LZ4MT_RESULT_CANNOT_READ_BLOCK_CHECKSUM:
s = "CANNOT_READ_BLOCK_CHECKSUM";
break;
case LZ4MT_RESULT_CANNOT_READ_STREAM_CHECKSUM:
s = "CANNOT_READ_STREAM_CHECKSUM";
break;
case LZ4MT_RESULT_STREAM_CHECKSUM_MISMATCH:
s = "STREAM_CHECKSUM_MISMATCH";
break;
case LZ4MT_RESULT_DECOMPRESS_FAIL:
s = "DECOMPRESS_FAIL";
break;
case LZ4MT_RESULT_BAD_ARG:
s = "BAD_ARG";
break;
case LZ4MT_RESULT_INVALID_BLOCK_SIZE:
s = "INVALID_BLOCK_SIZE";
break;
case LZ4MT_RESULT_INVALID_HEADER_RESERVED1:
s = "INVALID_HEADER_RESERVED1";
break;
case LZ4MT_RESULT_INVALID_HEADER_RESERVED2:
s = "INVALID_HEADER_RESERVED2";
break;
case LZ4MT_RESULT_INVALID_HEADER_RESERVED3:
s = "INVALID_HEADER_RESERVED3";
break;
case LZ4MT_RESULT_CANNOT_WRITE_DATA_BLOCK:
s = "CANNOT_WRITE_DATA_BLOCK";
break;
case LZ4MT_RESULT_CANNOT_WRITE_DECODED_BLOCK:
s = "CANNOT_WRITE_DECODED_BLOCK";
break;
default:
s = "Unknown code";
break;
}
return s;
}
extern "C" int
lz4mtResultToLz4cExitCode(Lz4MtResult result) {
int e = 1;
switch(result) {
case LZ4MT_RESULT_OK:
e = 0;
break;
case LZ4MT_RESULT_ERROR:
e = 1;
break;
case LZ4MT_RESULT_INVALID_MAGIC_NUMBER:
// selectDecoder()
// if (ftell(finput) == MAGICNUMBER_SIZE) EXM_THROW(44,"Unrecognized header : file cannot be decoded"); // Wrong magic number at the beginning of 1st stream
e = 44;
break;
case LZ4MT_RESULT_INVALID_HEADER_SKIPPABLE_SIZE_UNREADABLE:
// selectDecoder()
// if (nbReadBytes != 4) EXM_THROW(42, "Stream error : skippable size unreadable");
e = 42;
break;
case LZ4MT_RESULT_INVALID_HEADER_CANNOT_SKIP_SKIPPABLE_AREA:
// selectDecoder()
// if (errorNb != 0) EXM_THROW(43, "Stream error : cannot skip skippable area");
e = 43;
break;
case LZ4MT_RESULT_BLOCK_DEPENDENCE_IS_NOT_SUPPORTED_YET:
e = 1;
break;
case LZ4MT_RESULT_CANNOT_WRITE_HEADER:
// compress_file_blockDependency()
// LZ4IO_compressFilename()
// if (sizeCheck!=header_size) EXM_THROW(32, "Write error : cannot write header");
//
e = 32;
break;
case LZ4MT_RESULT_CANNOT_WRITE_EOS:
// compress_file_blockDependency()
// LZ4IO_compressFilename()
// if (sizeCheck!=(size_t)(4)) EXM_THROW(37, "Write error : cannot write end of stream");
//
e = 37;
break;
case LZ4MT_RESULT_CANNOT_WRITE_STREAM_CHECKSUM:
// compress_file_blockDependency()
// LZ4IO_compressFilename()
// if (sizeCheck!=(size_t)(4)) EXM_THROW(37, "Write error : cannot write stream checksum");
e = 37;
break;
case LZ4MT_RESULT_INVALID_HEADER:
// decodeLZ4S()
// if (nbReadBytes != 3) EXM_THROW(61, "Unreadable header");
e = 61;
break;
case LZ4MT_RESULT_INVALID_VERSION:
//decodeLZ4S()
// if (version != 1) EXM_THROW(62, "Wrong version number");
e = 62;
break;
case LZ4MT_RESULT_INVALID_HEADER_RESERVED1:
//decodeLZ4S()
// if (reserved1 != 0) EXM_THROW(65, "Wrong value for reserved bits");
e = 65;
break;
case LZ4MT_RESULT_PRESET_DICTIONARY_IS_NOT_SUPPORTED_YET:
// decodeLZ4S()
// if (dictionary == 1) EXM_THROW(66, "Does not support dictionary");
e = 66;
break;
case LZ4MT_RESULT_INVALID_HEADER_RESERVED2:
//decodeLZ4S()
// if (reserved2 != 0) EXM_THROW(67, "Wrong value for reserved bits");
e = 67;
break;
case LZ4MT_RESULT_INVALID_HEADER_RESERVED3:
//decodeLZ4S()
// if (reserved3 != 0) EXM_THROW(67, "Wrong value for reserved bits");
e = 67;
break;
case LZ4MT_RESULT_INVALID_BLOCK_MAXIMUM_SIZE:
// decodeLZ4S()
// if (blockSizeId < 4) EXM_THROW(68, "Unsupported block size");
e = 68;
break;
case LZ4MT_RESULT_INVALID_HEADER_CHECKSUM:
// decodeLZ4S()
// if (checkBits != checkBits_xxh32) EXM_THROW(69, "Stream descriptor error detected");
e = 69;
break;
case LZ4MT_RESULT_CANNOT_READ_BLOCK_SIZE:
// decodeLZ4S()
// if( nbReadBytes != 4 ) EXM_THROW(71, "Read error : cannot read next block size");
e = 71;
break;
case LZ4MT_RESULT_INVALID_BLOCK_SIZE:
// decodeLZ4S()
// if (blockSize > maxBlockSize) EXM_THROW(72, "Error : invalid block size");
e = 72;
break;
case LZ4MT_RESULT_CANNOT_READ_BLOCK_DATA:
// decodeLZ4S()
// if( nbReadBytes != blockSize ) EXM_THROW(73, "Read error : cannot read data block" );
e = 73;
break;
case LZ4MT_RESULT_CANNOT_READ_BLOCK_CHECKSUM:
// decodeLZ4S()
// if( sizeCheck != 4 ) EXM_THROW(74, "Read error : cannot read next block size");
e = 74;
break;
case LZ4MT_RESULT_BLOCK_CHECKSUM_MISMATCH:
// decodeLZ4S()
// if (checksum != readChecksum) EXM_THROW(75, "Error : invalid block checksum detected");
e = 75;
break;
case LZ4MT_RESULT_CANNOT_READ_STREAM_CHECKSUM:
// decodeLZ4S()
// if (sizeCheck != 4) EXM_THROW(74, "Read error : cannot read stream checksum");
e = 74;
break;
case LZ4MT_RESULT_STREAM_CHECKSUM_MISMATCH:
// decodeLZ4S()
// if (checksum != readChecksum) EXM_THROW(75, "Error : invalid stream checksum detected");
e = 75;
break;
case LZ4MT_RESULT_CANNOT_WRITE_DATA_BLOCK:
// cannot write incompressible block
// decodeLZ4S()
// if (sizeCheck != (size_t)blockSize) EXM_THROW(76, "Write error : cannot write data block");
e = 76;
break;
case LZ4MT_RESULT_DECOMPRESS_FAIL:
// decodeLZ4S()
// if (decodedBytes < 0) EXM_THROW(77, "Decoding Failed ! Corrupted input detected !");
e = 77;
break;
case LZ4MT_RESULT_CANNOT_WRITE_DECODED_BLOCK:
// decodeLZ4S()
// if (sizeCheck != (size_t)decodedBytes) EXM_THROW(78, "Write error : cannot write decoded block\n");
e = 78;
break;
default:
// LZ4IO_compressFilename_Legacy()
// if (!in_buff || !out_buff) EXM_THROW(21, "Allocation error : not enough memory");
// if (sizeCheck!=MAGICNUMBER_SIZE) EXM_THROW(22, "Write error : cannot write header");
//
// decodeLZ4S()
// if (streamSize == 1) EXM_THROW(64, "Does not support stream size");
// NOTE : lz4mt support the streamSize header flag.
e = 1;
break;
}
return e;
}
| 26.690037 | 161 | 0.718651 | 1shekhar |
aff3322e251c03dea97c9a0bedf81187344ccea0 | 475 | cc | C++ | actions.cc | amadio/g4run | 05dbfd0ec30567d0a60513d3002994094cd51af3 | [
"BSD-2-Clause"
] | 2 | 2020-08-18T12:22:13.000Z | 2022-03-12T17:01:05.000Z | actions.cc | amadio/g4run | 05dbfd0ec30567d0a60513d3002994094cd51af3 | [
"BSD-2-Clause"
] | null | null | null | actions.cc | amadio/g4run | 05dbfd0ec30567d0a60513d3002994094cd51af3 | [
"BSD-2-Clause"
] | null | null | null | #include "actions.h"
G4Run* RunAction::GenerateRun() { return nullptr; }
void RunAction::BeginOfRunAction(const G4Run*) { }
void RunAction::EndOfRunAction(const G4Run*) { }
void EventAction::BeginOfEventAction(const G4Event*) { }
void EventAction::EndOfEventAction(const G4Event*) { }
void TrackingAction::PreUserTrackingAction(const G4Track*) { }
void TrackingAction::PostUserTrackingAction(const G4Track*) { }
void SteppingAction::UserSteppingAction(const G4Step*) { }
| 33.928571 | 63 | 0.772632 | amadio |
aff434f15dd46c9df3ed72ad489bfa072dcf1e37 | 3,332 | cpp | C++ | src/poll.cpp | TheClonerx/cppnet | 1d282824d227542a3b130c37ef068ebddb212fa5 | [
"MIT"
] | 7 | 2019-03-03T05:43:52.000Z | 2021-08-28T01:24:44.000Z | src/poll.cpp | TheClonerx/cppnet | 1d282824d227542a3b130c37ef068ebddb212fa5 | [
"MIT"
] | null | null | null | src/poll.cpp | TheClonerx/cppnet | 1d282824d227542a3b130c37ef068ebddb212fa5 | [
"MIT"
] | 1 | 2020-01-02T05:47:12.000Z | 2020-01-02T05:47:12.000Z | #include <cppnet/poll.hpp>
#include <algorithm>
bool net::poll::add(socket::native_handle_type fd, int eventmask)
{
if (fd < 0)
return false;
auto it = std::find_if(fds.begin(), fds.end(), [fd](const pollfd& p) {
return p.fd == fd;
});
if (it != fds.end())
return false;
fds.push_back(pollfd { fd, static_cast<short>(eventmask), 0 });
return true;
}
bool net::poll::modify(socket::native_handle_type fd, int eventmask)
{
if (fd < 0)
return false;
auto it = std::find_if(fds.begin(), fds.end(), [fd](const pollfd& p) {
return p.fd == fd;
});
if (it == fds.end())
return false;
it->events = eventmask;
return true;
}
bool net::poll::remove(socket::native_handle_type fd)
{
if (fd < 0)
return false;
auto it = std::find_if(fds.begin(), fds.end(), [fd](const pollfd& p) {
return p.fd == fd;
});
if (it == fds.end())
return false;
fds.erase(it);
return true;
}
size_t net::poll::execute(std::optional<std::chrono::milliseconds> timeout)
{
for (pollfd& fd : fds)
fd.revents = 0;
#ifdef _WIN32
int ret = ::WSAPoll(fds.data(), static_cast<ULONG>(fds.size()), static_cast<INT>(timeout ? timeout->count() : -1));
if (ret < 0)
throw std::system_error(WSAGetLastError(), std::system_category());
#else
int ret = ::poll(fds.data(), fds.size(), timeout ? timeout->count() : -1);
if (ret < 0)
throw std::system_error(errno, std::system_category());
#endif
return ret;
}
size_t net::poll::execute(std::optional<std::chrono::milliseconds> timeout, std::error_code& e) noexcept
{
for (pollfd& fd : fds)
fd.revents = 0;
#ifdef _WIN32
int ret = ::WSAPoll(fds.data(), static_cast<ULONG>(fds.size()), static_cast<INT>(timeout ? timeout->count() : -1));
if (ret < 0)
e.assign(WSAGetLastError(), std::system_category());
#else
int ret = ::poll(fds.data(), fds.size(), timeout ? timeout->count() : -1);
if (ret < 0)
e.assign(errno, std::system_category());
#endif
return ret;
}
#ifdef _GNU_SOURCE
size_t net::poll::execute(std::optional<std::chrono::nanoseconds> timeout, const sigset_t& sigmask)
{
timespec tm;
if (timeout) {
tm.tv_sec = std::chrono::duration_cast<std::chrono::seconds>(*timeout).count();
tm.tv_nsec = timeout->count() % std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::seconds(1)).count();
}
for (pollfd& fd : fds)
fd.revents = 0;
int ret = ::ppoll(fds.data(), fds.size(), timeout ? &tm : nullptr, &sigmask);
if (ret < 0)
throw std::system_error(errno, std::system_category());
return ret;
}
size_t net::poll::execute(std::optional<std::chrono::nanoseconds> timeout, const sigset_t& sigmask, std::error_code& e) noexcept
{
timespec tm;
if (timeout) {
tm.tv_sec = std::chrono::duration_cast<std::chrono::seconds>(*timeout).count();
tm.tv_nsec = timeout->count() % std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::seconds(1)).count();
}
for (pollfd& fd : fds)
fd.revents = 0;
int ret = ::ppoll(fds.data(), fds.size(), timeout ? &tm : nullptr, &sigmask);
if (ret < 0)
e.assign(errno, std::system_category());
return ret;
}
#endif
| 28.724138 | 128 | 0.604142 | TheClonerx |
aff5a97359496a813dfb2ec91f1506e5a4b269e0 | 537 | hpp | C++ | src/Enclave/binary/logic.hpp | dove-project/dove-backend | e9f4f6211181ccc9072416816d65793dc137444b | [
"MIT"
] | null | null | null | src/Enclave/binary/logic.hpp | dove-project/dove-backend | e9f4f6211181ccc9072416816d65793dc137444b | [
"MIT"
] | null | null | null | src/Enclave/binary/logic.hpp | dove-project/dove-backend | e9f4f6211181ccc9072416816d65793dc137444b | [
"MIT"
] | null | null | null | #ifndef _LOGIC_HPP
#define _LOGIC_HPP
#include "../binary_op.hpp"
#ifdef LIB_FTFP
class BitwiseAndOp: public BinaryOp {
void call(fixed scalar1, fixed scalar2, fixed *result);
};
class BitwiseOrOp: public BinaryOp {
void call(fixed scalar1, fixed scalar2, fixed *result);
};
#else
class BitwiseAndOp: public BinaryOp {
void call(double scalar1, double scalar2, double *result);
};
class BitwiseOrOp: public BinaryOp {
void call(double scalar1, double scalar2, double *result);
};
#endif /* LIB_FTFP */
#endif /* _LOGIC_HPP */
| 23.347826 | 60 | 0.73743 | dove-project |
aff78f49864e880352a13d5671ccc2629f72f429 | 742 | hpp | C++ | TypeTraits/IsMemberPointer.hpp | jlandess/LandessDevCore | 3319c36c3232415d6bdba7da8b4896c0638badf2 | [
"BSD-3-Clause"
] | 2 | 2021-06-09T00:38:46.000Z | 2021-09-04T21:55:33.000Z | TypeTraits/IsMemberPointer.hpp | jlandess/LandessDevCore | 3319c36c3232415d6bdba7da8b4896c0638badf2 | [
"BSD-3-Clause"
] | null | null | null | TypeTraits/IsMemberPointer.hpp | jlandess/LandessDevCore | 3319c36c3232415d6bdba7da8b4896c0638badf2 | [
"BSD-3-Clause"
] | 1 | 2021-08-30T00:46:12.000Z | 2021-08-30T00:46:12.000Z | //
// Created by phoenixflower on 10/12/19.
//
#ifndef LANDESSDEVDATASTRUCTURES_ISMEMBERPOINTER_H
#define LANDESSDEVDATASTRUCTURES_ISMEMBERPOINTER_H
//#include "Definitions/Common.hpp"
namespace LD
{
namespace Detail
{
template< class T >
struct is_member_pointer_helper : LD::FalseType{};
template< class T, class U >
struct is_member_pointer_helper<T U::*> : LD::TrueType {};
template< class T >
struct is_member_pointer :
is_member_pointer_helper<typename LD::Detail::RemoveCV<T>::type> {};
}
template<typename T>
constexpr bool IsMemberPointer = LD::Detail::is_member_pointer<T>::value;
}
#endif //LANDESSDEVDATASTRUCTURES_ISMEMBERPOINTER_H
| 26.5 | 84 | 0.685984 | jlandess |
affad5f7b825cc3df186ffecf55dc0b8ae2b88d8 | 1,513 | cpp | C++ | arduino-libs/Pacman/src/AmbushState.cpp | taylorsmithatnominet/BSidesCBR-2021-Badge | df3f13d780d6fb1b6d03d08e9bdd72f507f69aa6 | [
"MIT"
] | null | null | null | arduino-libs/Pacman/src/AmbushState.cpp | taylorsmithatnominet/BSidesCBR-2021-Badge | df3f13d780d6fb1b6d03d08e9bdd72f507f69aa6 | [
"MIT"
] | null | null | null | arduino-libs/Pacman/src/AmbushState.cpp | taylorsmithatnominet/BSidesCBR-2021-Badge | df3f13d780d6fb1b6d03d08e9bdd72f507f69aa6 | [
"MIT"
] | null | null | null | #include "AmbushState.h"
#include "Level.h"
#include "MovementModule.h"
#include "Player.h"
#include "PathFinderModule.h"
#include "Config.h"
namespace pacman {
Vect2 AmbushState::GetNextTarget()
{
Vect2 next = *m_playerwPtr->GetPos();
m_datawPtr->m_levelwPtr->NextIntersection(next, m_playerwPtr->GetDirection());
// if ghost is on target it will stop, so it sets the target to the player
if (next == m_datawPtr->m_pos->Round()) {
return m_playerwPtr->GetPos()->Round();
}
return next;
}
void AmbushState::UpdatePath()
{
m_currentTarget = GetNextTarget();
m_pathfinder->UpdatePath(m_currentTarget, *m_playerwPtr->GetPos());
}
AmbushState::AmbushState(GameObjectData* p_data, Player* p_player)
: IGhostState(p_data), m_playerwPtr(p_player)
{
m_pathfinder = new PathFinderModule(m_datawPtr->m_levelwPtr);
UpdatePath();
}
AmbushState::~AmbushState()
{
delete m_pathfinder;
m_pathfinder = nullptr;
}
bool AmbushState::Update(float p_delta)
{
Vect2* pos = m_datawPtr->m_pos;
Vect2 nextDir = Vect2::ZERO;
if (m_datawPtr->m_movement->SteppedOnTile()) {
Vect2 currentDir = m_datawPtr->m_movement->GetDirection();
Vect2 back = Vect2(-currentDir.x, -currentDir.y);
nextDir = m_pathfinder->GetNextDir(*pos, back);
}
m_datawPtr->m_movement->Update(p_delta, nextDir, float(Config::MOVEMENT_SPEED), false);
if (m_pathfinder->ReachedGoal(*m_datawPtr->m_pos)) {
UpdatePath();
return false;
}
return true;
}
void AmbushState::Enter()
{
UpdatePath();
}
}; // namespace pacman
| 20.445946 | 88 | 0.727693 | taylorsmithatnominet |
affb2458f5b7d83a31f0e74be076cbaf4cb652fa | 3,405 | cpp | C++ | Source/DemoScene/DX9Vector3.cpp | ookumaneko/PC-Psp-Cross-Platform-Demoscene | 0c192f9ecf5a4fd9db3c9a2c9998b365bf480c1e | [
"MIT"
] | null | null | null | Source/DemoScene/DX9Vector3.cpp | ookumaneko/PC-Psp-Cross-Platform-Demoscene | 0c192f9ecf5a4fd9db3c9a2c9998b365bf480c1e | [
"MIT"
] | null | null | null | Source/DemoScene/DX9Vector3.cpp | ookumaneko/PC-Psp-Cross-Platform-Demoscene | 0c192f9ecf5a4fd9db3c9a2c9998b365bf480c1e | [
"MIT"
] | null | null | null | #ifndef _PSP_VER
#include "Vector3.h"
Vector3& Vector3::operator =(const Vector3 &rhs)
{
_vec = rhs._vec;
return *this;
}
Vector3 Vector3::operator +(const Vector3& rhs) const
{
Vector3 ret;
D3DXVec3Add( &ret._vec, &_vec, &rhs._vec );
return ret;
}
Vector3 Vector3::operator- (const Vector3& rhs) const
{
Vector3 ret;
D3DXVec3Subtract( &ret._vec, &_vec, &rhs._vec );
return ret;
}
Vector3 Vector3::operator* (const float scalar) const
{
Vector3 ret;
D3DXVec3Scale( &ret._vec, &_vec, scalar );
return ret;
}
Vector3& Vector3::operator+= (const Vector3& rhs)
{
D3DXVec3Add( &_vec, &_vec, &rhs._vec );
return *this;
}
Vector3& Vector3::operator-= (const Vector3& rhs)
{
D3DXVec3Subtract( &_vec, &_vec, &rhs._vec );
return *this;
}
Vector3& Vector3::operator*= (const float scalar)
{
D3DXVec3Scale( &_vec, &_vec, scalar );
return *this;
}
bool Vector3::operator== (const Vector3& rhs)
{
if ( _vec == rhs._vec )
return true;
else
return false;
}
bool Vector3::operator!= (const Vector3& rhs)
{
return !( *this == rhs );
}
void Vector3::Add(const Vector3& rhs)
{
_vec += rhs._vec;
}
void Vector3::Add(const Vector3& vec1, const Vector3& vec2, Vector3& out)
{
D3DXVec3Add( &out._vec, &vec1._vec, &vec2._vec );
}
void Vector3::Subtract(const Vector3& rhs)
{
_vec = _vec - rhs._vec;
}
void Vector3::Subtract(const Vector3& vec1, const Vector3& vec2, Vector3& out)
{
D3DXVec3Subtract( &out._vec, &vec1._vec, &vec2._vec );
}
void Vector3::Multiply(const Vector3& rhs)
{
_vec.x *= rhs._vec.x;
_vec.y *= rhs._vec.y;
_vec.z *= rhs._vec.z;
}
void Vector3::Multiply(float scalar)
{
_vec *= scalar;
}
void Vector3::Multiply(const Vector3& vec1, const Vector3& vec2, Vector3& out)
{
out._vec.x = vec1._vec.x * vec2._vec.x;
out._vec.y = vec1._vec.y * vec2._vec.y;
out._vec.z = vec1._vec.z * vec2._vec.z;
}
void Vector3::Multiply(float scalar, Vector3& in, Vector3& out)
{
out._vec = in._vec * scalar;
}
void Vector3::Divide(const Vector3& rhs)
{
_vec.x /= rhs._vec.x;
_vec.y /= rhs._vec.y;
_vec.z /= rhs._vec.z;
}
void Vector3::Divide(const Vector3& vec1, const Vector3& vec2, Vector3& out)
{
out._vec.x = vec1._vec.x / vec2._vec.x;
out._vec.y = vec1._vec.y / vec2._vec.y;
out._vec.z = vec1._vec.z / vec2._vec.z;
}
void Vector3::Normalize()
{
D3DXVec3Normalize( &_vec, &_vec );
}
void Vector3::Normalize(const Vector3& in, Vector3& out)
{
D3DXVec3Normalize( &out._vec, &in._vec );
}
float Vector3::MagnitudeSquare(void)
{
return D3DXVec3LengthSq( &_vec );
}
float Vector3::MagnitudeSquare(const Vector3& rhs)
{
return D3DXVec3LengthSq( &rhs._vec );
}
Vector3 Vector3::Lerp(Vector3 &start, Vector3 &end, float amount)
{
Vector3 ret;
D3DXVec3Lerp( &ret._vec, &start._vec, &end._vec, amount );
return ret;
}
void Vector3::Lerp(Vector3 &start, Vector3 &end, float amount, Vector3 &out)
{
D3DXVec3Lerp( &out._vec, &start._vec, &end._vec, amount );
}
float Vector3::DotProduct(const Vector3& rhs)
{
return D3DXVec3Dot( &_vec, &rhs._vec );
}
float Vector3::DotProduct(const Vector3& vec1, const Vector3& vec2)
{
return D3DXVec3Dot( &vec1._vec, &vec2._vec );
}
Vector3 Vector3::CrossProduct(const Vector3& rhs, const Vector3& rhs2)
{
D3DXVec3Cross( &_vec, &rhs._vec, &rhs2._vec );
return *this;
}
void Vector3::CrossProduct(const Vector3& vec1, const Vector3& vec2, Vector3& out)
{
D3DXVec3Cross( &out._vec, &vec1._vec, &vec2._vec );
}
#endif | 19.346591 | 82 | 0.684288 | ookumaneko |
9b7c242e21a2a00dc1e56060aba426bdbd26aa2f | 884 | cpp | C++ | src/npf/layout/rows.cpp | yeSpud/Tumblr-cpp | 0f69846abf47495384077488fda49a2b17dfc439 | [
"MIT"
] | 1 | 2021-07-16T04:25:02.000Z | 2021-07-16T04:25:02.000Z | src/npf/layout/rows.cpp | yeSpud/Tumblr-cpp | 0f69846abf47495384077488fda49a2b17dfc439 | [
"MIT"
] | 4 | 2021-09-16T08:46:40.000Z | 2022-03-12T05:12:20.000Z | src/npf/layout/rows.cpp | yeSpud/Tumblr-cpp | 0f69846abf47495384077488fda49a2b17dfc439 | [
"MIT"
] | null | null | null | //
// Created by Spud on 7/16/21.
//
#include "npf/layout/rows.hpp"
void Rows::populateBlocks(const JSON_ARRAY &array) { // TODO Comments
display = std::vector<std::vector<int>>(array.Size());
for (JSON_ARRAY_ENTRY &entry : array) {
if (entry.IsObject()) {
JSON_OBJECT object = entry.GetObj();
POPULATE_ARRAY(object, "blocks", JSON_ARRAY intArray = object["blocks"].GetArray();
std::vector<int> block = std::vector<int>(intArray.Size());
for (JSON_ARRAY_ENTRY &blockEntry : intArray) {
if (blockEntry.IsInt()) {
block.push_back(blockEntry.GetInt());
}
}
display.push_back(block);)
}
}
}
void Rows::populateNPF(JSON_OBJECT entry) { // TODO Comments
POPULATE_ARRAY(entry, "display", populateBlocks(entry["display"].GetArray());)
objectHasValue(entry, "truncate_after", truncate_after);
// TODO Mode (when implemented)
}
| 23.891892 | 86 | 0.670814 | yeSpud |
9b805aa696c8ec98cb29950c14711a0a32d847bd | 433 | cpp | C++ | competitive_programming/programming_contests/uri/handball.cpp | LeandroTk/Algorithms | 569ed68eba3eeff902f8078992099c28ce4d7cd6 | [
"MIT"
] | 205 | 2018-12-01T17:49:49.000Z | 2021-12-22T07:02:27.000Z | competitive_programming/programming_contests/uri/handball.cpp | LeandroTk/Algorithms | 569ed68eba3eeff902f8078992099c28ce4d7cd6 | [
"MIT"
] | 2 | 2020-01-01T16:34:29.000Z | 2020-04-26T19:11:13.000Z | competitive_programming/programming_contests/uri/handball.cpp | LeandroTk/Algorithms | 569ed68eba3eeff902f8078992099c28ce4d7cd6 | [
"MIT"
] | 50 | 2018-11-28T20:51:36.000Z | 2021-11-29T04:08:25.000Z | // https://www.urionlinejudge.com.br/judge/en/problems/view/1715
#include <iostream>
using namespace std;
int main() {
int players, matches, p;
while (cin >> players >> matches) {
int counter = 0;
for (int i = 0; i < players; i++) {
bool scored = true;
for (int j = 0; j < matches; j++) {
cin >> p;
if (p == 0) scored = false;
}
if (scored) counter++;
}
cout << counter << endl;
}
return 0;
} | 16.037037 | 64 | 0.56351 | LeandroTk |
9b8245efdb7e9da180d5eab0976e5c7db2a2d9b3 | 1,903 | cpp | C++ | example-Sprite/src/CustomSpriteA.cpp | selflash/ofxSelflash | 087a263b2d4de970edd75ecab2c2a48b7b58e62d | [
"MIT"
] | 19 | 2015-05-14T09:57:38.000Z | 2022-01-10T23:32:28.000Z | example-Sprite/src/CustomSpriteA.cpp | selflash/ofxSelflash | 087a263b2d4de970edd75ecab2c2a48b7b58e62d | [
"MIT"
] | 3 | 2015-08-04T09:07:26.000Z | 2018-01-18T07:14:35.000Z | example-Sprite/src/CustomSpriteA.cpp | selflash/ofxSelflash | 087a263b2d4de970edd75ecab2c2a48b7b58e62d | [
"MIT"
] | 1 | 2015-08-04T09:05:22.000Z | 2015-08-04T09:05:22.000Z | #include "CustomSpriteA.h"
//==============================================================
// Constructor / Destructor
//==============================================================
//--------------------------------------------------------------
CustomSpriteA::CustomSpriteA() {
ofLog() << "[CustomSpriteA]CustomSpriteA()";
_target = this;
buttonMode(true);
// visible(false);
//--------------------------------------
flGraphics* g;
g = graphics();
g->clear();
g->lineStyle(1, 0xff0000);
g->beginFill(0xffffff);
g->drawRect(0, 0, 100, 100);
g->endFill();
//--------------------------------------
}
//--------------------------------------------------------------
CustomSpriteA::~CustomSpriteA() {
ofLog() << "[CustomSpriteA]~CustomSpriteA()";
}
//==============================================================
// Setup / Update / Draw
//==============================================================
//--------------------------------------------------------------
void CustomSpriteA::_setup() {
// ofLog() << "[CustomSpriteA]_setup()";
}
//--------------------------------------------------------------
void CustomSpriteA::_update() {
// ofLog() << "[CustomSpriteA]_update()";
}
//--------------------------------------------------------------
void CustomSpriteA::_draw() {
// ofLog() << "[CustomSpriteA]_draw()";
}
//==============================================================
// Public Method
//==============================================================
//==============================================================
// Protected / Private Method
//==============================================================
//==============================================================
// Private Event Handler
//==============================================================
| 29.276923 | 64 | 0.257488 | selflash |
9b85c208fc178f98f0861559d9f07fda788d569f | 702 | cpp | C++ | TriviallyCopyable.cpp | haxpor/cpp_st | 43d1492266c6e01e6e243c834fba26eedf1ab9f3 | [
"MIT"
] | 2 | 2021-06-10T22:05:01.000Z | 2021-09-17T08:21:20.000Z | TriviallyCopyable.cpp | haxpor/cpp_st | 43d1492266c6e01e6e243c834fba26eedf1ab9f3 | [
"MIT"
] | null | null | null | TriviallyCopyable.cpp | haxpor/cpp_st | 43d1492266c6e01e6e243c834fba26eedf1ab9f3 | [
"MIT"
] | 1 | 2020-02-25T04:26:52.000Z | 2020-02-25T04:26:52.000Z | /**
* Testbed on checking whether std::vector<scalar-type> is trivially copyable or not via
* type traits.
*
* Read more about trivially copyable at Notes section in https://en.cppreference.com/w/cpp/types/is_trivially_copyable
*/
#include <type_traits>
#include <iostream>
#include <vector>
std::vector<unsigned int> vec;
int main()
{
unsigned int arr[10];
// std::vector is not trivially copyable
std::cout << std::boolalpha << std::is_trivially_copyable<std::vector<unsigned int>>::value << std::endl;
// arr is a pointer, and pointer is trivially copyable
std::cout << std::boolalpha << std::is_trivially_copyable<unsigned int[10]>::value << std::endl;
return 0;
}
| 30.521739 | 119 | 0.702279 | haxpor |
9b8833ba7e7bdfcedd0db0682b215621dc48e04b | 14,489 | cpp | C++ | src/gtirb_pprinter/AArch64PrettyPrinter.cpp | binrats/gtirb-pprinter | 864640a62fe41068a80e0ef295da9d0522402aab | [
"MIT"
] | null | null | null | src/gtirb_pprinter/AArch64PrettyPrinter.cpp | binrats/gtirb-pprinter | 864640a62fe41068a80e0ef295da9d0522402aab | [
"MIT"
] | null | null | null | src/gtirb_pprinter/AArch64PrettyPrinter.cpp | binrats/gtirb-pprinter | 864640a62fe41068a80e0ef295da9d0522402aab | [
"MIT"
] | null | null | null | //===- AArch64PrettyPrinter.cpp ---------------------------------*- C++ -*-===//
//
// Copyright (c) 2020, The Binrat Developers.
//
// This code is licensed under the GNU Affero General Public License
// as published by the Free Software Foundation, either version 3 of
// the License, or (at your option) any later version. See the
// LICENSE.txt file in the project root for license terms or visit
// https://www.gnu.org/licenses/agpl.txt.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
//===----------------------------------------------------------------------===//
#include "AArch64PrettyPrinter.hpp"
#include "AuxDataSchema.hpp"
#include <capstone/capstone.h>
namespace gtirb_pprint {
AArch64PrettyPrinter::AArch64PrettyPrinter(gtirb::Context& context_,
gtirb::Module& module_, const ElfSyntax& syntax_,
const PrintingPolicy& policy_)
: ElfPrettyPrinter(context_, module_, syntax_, policy_, CS_ARCH_ARM64, CS_MODE_ARM) {}
void AArch64PrettyPrinter::printHeader(std::ostream& os) {
this->printBar(os);
// header
this->printBar(os);
os << '\n';
for (int i = 0; i < 8; i++) {
os << syntax.nop() << '\n';
}
}
std::string AArch64PrettyPrinter::getRegisterName(unsigned int reg) const {
return reg == ARM64_REG_INVALID ? "" : cs_reg_name(this->csHandle, reg);
}
void AArch64PrettyPrinter::printOperandList(std::ostream& os,
const cs_insn& inst) {
cs_arm64& detail = inst.detail->arm64;
uint8_t opCount = detail.op_count;
for (int i = 0; i < opCount; i++) {
if (i != 0) {
os << ',';
}
printOperand(os, inst, i);
}
}
void AArch64PrettyPrinter::printOperand(std::ostream& os,
const cs_insn& inst, uint64_t index) {
gtirb::Addr ea(inst.address);
const cs_arm64_op& op = inst.detail->arm64.operands[index];
const gtirb::SymbolicExpression* symbolic = nullptr;
bool finalOp = (index + 1 == inst.detail->arm64.op_count);
switch (op.type) {
case ARM64_OP_REG:
printOpRegdirect(os, inst, op.reg);
// add extender if needed
if (op.ext != ARM64_EXT_INVALID) {
os << ", ";
printExtender(os, op.ext, op.shift.type, op.shift.value);
}
return;
case ARM64_OP_IMM:
if (finalOp) {
auto pos = module.findSymbolicExpressionsAt(ea);
if (!pos.empty()) {
symbolic = &pos.begin()->getSymbolicExpression();
}
}
printOpImmediate(os, symbolic, inst, index);
return;
case ARM64_OP_MEM:
if (finalOp) {
auto pos = module.findSymbolicExpressionsAt(ea);
if (!pos.empty()) {
symbolic = &pos.begin()->getSymbolicExpression();
}
}
printOpIndirect(os, symbolic, inst, index);
return;
case ARM64_OP_FP:
os << "#" << op.fp;
return;
case ARM64_OP_CIMM:
case ARM64_OP_REG_MRS:
case ARM64_OP_REG_MSR:
case ARM64_OP_PSTATE:
case ARM64_OP_SYS:
// print the operand directly
printOpRawValue(os, inst, index);
return;
case ARM64_OP_PREFETCH:
printOpPrefetch(os, op.prefetch);
return;
case ARM64_OP_BARRIER:
printOpBarrier(os, op.barrier);
return;
case ARM64_OP_INVALID:
default:
std::cerr << "invalid operand\n";
exit(1);
}
}
void AArch64PrettyPrinter::printPrefix(std::ostream& os,
const cs_insn& inst, uint64_t index) {
auto* symbolicOperandInfo = module.getAuxData<gtirb::schema::SymbolicOperandInfoAD>();
for (const auto& pair : *symbolicOperandInfo) {
const auto& symbolInfo = pair.second;
if (pair.first == gtirb::Addr(inst.address) && index == std::get<0>(symbolInfo)) {
os << std::get<1>(symbolInfo);
}
}
}
void AArch64PrettyPrinter::printOpRegdirect(std::ostream& os,
const cs_insn& /* inst */, unsigned int reg) {
os << getRegisterName(reg);
}
void AArch64PrettyPrinter::printOpImmediate(std::ostream& os,
const gtirb::SymbolicExpression* symbolic,
const cs_insn& inst, uint64_t index) {
const cs_arm64_op& op = inst.detail->arm64.operands[index];
assert(op.type == ARM64_OP_IMM &&
"printOpImmediate called without an immediate operand");
bool is_jump = cs_insn_group(this->csHandle, &inst, ARM64_GRP_JUMP);
if (const gtirb::SymAddrConst* s = this->getSymbolicImmediate(symbolic)) {
if (!is_jump) {
os << ' ';
}
printPrefix(os, inst, index);
this->printSymbolicExpression(os, s, !is_jump);
} else {
os << "#" << op.imm;
if (op.shift.type != ARM64_SFT_INVALID && op.shift.value != 0) {
os << ",";
printShift(os, op.shift.type, op.shift.value);
}
}
}
void AArch64PrettyPrinter::printOpIndirect(std::ostream& os,
const gtirb::SymbolicExpression* symbolic,
const cs_insn& inst, uint64_t index) {
const cs_arm64& detail = inst.detail->arm64;
const cs_arm64_op& op = detail.operands[index];
assert(op.type == ARM64_OP_MEM &&
"printOpIndirect called without a memory operand");
bool first = true;
os << "[";
// base register
if (op.mem.base != ARM64_REG_INVALID) {
first = false;
os << getRegisterName(op.mem.base);
}
// displacement (constant)
if (op.mem.disp != 0) {
if (!first) {
os << ",";
}
if (const auto* s = std::get_if<gtirb::SymAddrConst>(symbolic)) {
printPrefix(os, inst, index);
printSymbolicExpression(os, s, false);
} else {
os << "#" << op.mem.disp;
}
first = false;
}
// index register
if (op.mem.index != ARM64_REG_INVALID) {
if (!first) {
os << ",";
}
first = false;
os << getRegisterName(op.mem.index);
}
// add shift
if (op.shift.type != ARM64_SFT_INVALID && op.shift.value != 0) {
os << ",";
assert(!first && "unexpected shift operator");
printShift(os, op.shift.type, op.shift.value);
}
os << "]";
if (detail.writeback && index + 1 == detail.op_count) {
os << "!";
}
}
void AArch64PrettyPrinter::printOpRawValue(std::ostream& os, const cs_insn& inst, uint64_t index) {
// grab the full operand string
const char* opStr = inst.op_str;
// flick through to the start of the operand
unsigned int currOperand = 0;
bool inBlock = false;
const char* pos;
for (pos = opStr; *pos != '\0' && currOperand != index; pos++) {
char cur = *pos;
if (cur == '[') {
// entering an indirect memory access
assert(!inBlock && "nested blocks should not be possible");
inBlock = true;
} else if (cur == ']') {
// exiting an indirect memory access
assert(inBlock && "Closing unopened memory access");
inBlock = false;
} else if (!inBlock && cur == ',') {
// hit a new operand
currOperand++;
}
}
assert(currOperand == index && "unexpected end of operands");
const char* operandStart = pos;
// find the end of the operand
while (*pos != '\0') {
char cur = *pos;
if (cur == '[') {
inBlock = true;
} else if (cur == ']') {
inBlock = false;
} else if (!inBlock && cur == ',') {
// found end of operand
break;
}
pos++;
}
const char* operandEnd = pos;
// skip leading whitespace
while (isspace(*operandStart)) operandStart++;
// print every character in the operand
for (const char* cur = operandStart; cur < operandEnd; cur++) {
os << *cur;
}
}
void AArch64PrettyPrinter::printOpBarrier(std::ostream& os, const arm64_barrier_op barrier) {
switch (barrier) {
case ARM64_BARRIER_OSHLD:
os << "oshld";
return;
case ARM64_BARRIER_OSHST:
os << "oshst";
return;
case ARM64_BARRIER_OSH:
os << "osh";
return;
case ARM64_BARRIER_NSHLD:
os << "nshld";
return;
case ARM64_BARRIER_NSHST:
os << "nshst";
return;
case ARM64_BARRIER_NSH:
os << "nsh";
return;
case ARM64_BARRIER_ISHLD:
os << "ishld";
return;
case ARM64_BARRIER_ISHST:
os << "ishst";
return;
case ARM64_BARRIER_ISH:
os << "ish";
return;
case ARM64_BARRIER_LD:
os << "ld";
return;
case ARM64_BARRIER_ST:
os << "st";
return;
case ARM64_BARRIER_SY:
os << "sy";
return;
case ARM64_BARRIER_INVALID:
default:
std::cerr << "invalid operand\n";
exit(1);
}
}
void AArch64PrettyPrinter::printOpPrefetch(std::ostream& os, const arm64_prefetch_op prefetch) {
switch (prefetch) {
case ARM64_PRFM_PLDL1KEEP:
os << "pldl1keep";
return;
case ARM64_PRFM_PLDL1STRM:
os << "pldl1strm";
return;
case ARM64_PRFM_PLDL2KEEP:
os << "pldl2keep";
return;
case ARM64_PRFM_PLDL2STRM:
os << "pldl2strm";
return;
case ARM64_PRFM_PLDL3KEEP:
os << "pldl3keep";
return;
case ARM64_PRFM_PLDL3STRM:
os << "pldl3strm";
return;
case ARM64_PRFM_PLIL1KEEP:
os << "plil1keep";
return;
case ARM64_PRFM_PLIL1STRM:
os << "plil1strm";
return;
case ARM64_PRFM_PLIL2KEEP:
os << "plil2keep";
return;
case ARM64_PRFM_PLIL2STRM:
os << "plil2strm";
return;
case ARM64_PRFM_PLIL3KEEP:
os << "plil3keep";
return;
case ARM64_PRFM_PLIL3STRM:
os << "plil3strm";
return;
case ARM64_PRFM_PSTL1KEEP:
os << "pstl1keep";
return;
case ARM64_PRFM_PSTL1STRM:
os << "pstl1strm";
return;
case ARM64_PRFM_PSTL2KEEP:
os << "pstl2keep";
return;
case ARM64_PRFM_PSTL2STRM:
os << "pstl2strm";
return;
case ARM64_PRFM_PSTL3KEEP:
os << "pstl3keep";
return;
case ARM64_PRFM_PSTL3STRM:
os << "pstl3strm";
return;
case ARM64_PRFM_INVALID:
default:
std::cerr << "invalid operand\n";
exit(1);
}
}
void AArch64PrettyPrinter::printShift(std::ostream& os, const arm64_shifter type, unsigned int value) {
switch (type) {
case ARM64_SFT_LSL:
os << "lsl";
break;
case ARM64_SFT_MSL:
os << "msl";
break;
case ARM64_SFT_LSR:
os << "lsr";
break;
case ARM64_SFT_ASR:
os << "asr";
break;
case ARM64_SFT_ROR:
os << "ror";
break;
default:
assert(false && "unexpected case");
}
os << " #" << value;
}
void AArch64PrettyPrinter::printExtender(std::ostream& os, const arm64_extender& ext, const arm64_shifter shiftType, uint64_t shiftValue) {
switch (ext) {
case ARM64_EXT_UXTB:
os << "uxtb";
break;
case ARM64_EXT_UXTH:
os << "uxth";
break;
case ARM64_EXT_UXTW:
os << "uxtw";
break;
case ARM64_EXT_UXTX:
os << "uxtx";
break;
case ARM64_EXT_SXTB:
os << "sxtb";
break;
case ARM64_EXT_SXTH:
os << "sxth";
break;
case ARM64_EXT_SXTW:
os << "sxtw";
break;
case ARM64_EXT_SXTX:
os << "sxtx";
break;
default:
assert(false && "unexpected case");
}
if (shiftType != ARM64_SFT_INVALID) {
assert(shiftType == ARM64_SFT_LSL && "unexpected shift type in extender");
os << " #" << shiftValue;
}
}
std::optional<std::string> AArch64PrettyPrinter::getForwardedSymbolName(const gtirb::Symbol* symbol, bool /* inData */) const {
const auto* symbolForwarding =
module.getAuxData<gtirb::schema::SymbolForwarding>();
if (symbolForwarding) {
auto found = symbolForwarding->find(symbol->getUUID());
if (found != symbolForwarding->end()) {
gtirb::Node* destSymbol = gtirb::Node::getByUUID(context, found->second);
return cast<gtirb::Symbol>(destSymbol)->getName();
}
}
return {};
}
const PrintingPolicy& AArch64PrettyPrinterFactory::defaultPrintingPolicy() const {
static PrintingPolicy DefaultPolicy{
/// Sections to avoid printing.
{".comment", ".plt", ".init", ".fini", ".got", ".plt.got", ".got.plt",
".plt.sec", ".eh_frame_hdr"},
/// Functions to avoid printing.
{"_start", "deregister_tm_clones", "register_tm_clones",
"__do_global_dtors_aux", "frame_dummy", "__libc_csu_fini",
"__libc_csu_init", "_dl_relocate_static_pie", "call_weak_fn"},
/// Sections with possible data object exclusion.
{".init_array", ".fini_array"},
};
return DefaultPolicy;
}
std::unique_ptr<PrettyPrinterBase>
AArch64PrettyPrinterFactory::create(gtirb::Context& gtirb_context,
gtirb::Module& module, const PrintingPolicy& policy) {
static const ElfSyntax syntax{};
return std::make_unique<AArch64PrettyPrinter>(gtirb_context,
module, syntax, policy);
}
volatile bool AArch64PrettyPrinter::registered = registerPrinter(
{"elf"}, {"aarch64"},
std::make_shared<AArch64PrettyPrinterFactory>(), true);
}
| 30.697034 | 139 | 0.549934 | binrats |
9b8a17ad719aea690882161969571456622fe051 | 864 | cpp | C++ | microsoft/15.cpp | 19yetnoob/-6Companies30days | 93f8dc6370cae7a8907d02b3ac8de610b73b8d9f | [
"MIT"
] | null | null | null | microsoft/15.cpp | 19yetnoob/-6Companies30days | 93f8dc6370cae7a8907d02b3ac8de610b73b8d9f | [
"MIT"
] | null | null | null | microsoft/15.cpp | 19yetnoob/-6Companies30days | 93f8dc6370cae7a8907d02b3ac8de610b73b8d9f | [
"MIT"
] | null | null | null | void dfs(int node,set<int>s[],vector<int>&visit,string &ans){
visit[node]=1;
for(auto a:s[node]){
if(visit[a]==-1)
dfs(a,s,visit,ans);
}
ans=(char)('a'+node)+ans;
}
string findOrder(string dict[], int N, int K) {
set<int>v[26];
for(int i=0;i<N-1;i++){
string a=dict[i];
string b=dict[i+1];
int m=min(a.size(),b.size());
for(int j=0;j<m;j++){
if(a[j]!=b[j])
{
v[a[j]-'a'].insert(b[j]-'a');
break;
}
}
}
string ans="";
vector<int>visit(26,-1);
for(int i=0;i<26;i++){
if(visit[i]==-1&&v[i].size()>0){
dfs(i,v,visit,ans);
}
}
return ans;
} | 27.870968 | 62 | 0.359954 | 19yetnoob |
9b8fe593b7c252f51a2afe8fca6f8835d8851af0 | 9,551 | cpp | C++ | src/Task.cpp | tehilinski/MTBMPI | 5d8fa590c6708c6ef412c6d2959f04e125f2d9e0 | [
"Apache-2.0"
] | null | null | null | src/Task.cpp | tehilinski/MTBMPI | 5d8fa590c6708c6ef412c6d2959f04e125f2d9e0 | [
"Apache-2.0"
] | null | null | null | src/Task.cpp | tehilinski/MTBMPI | 5d8fa590c6708c6ef412c6d2959f04e125f2d9e0 | [
"Apache-2.0"
] | null | null | null | /*------------------------------------------------------------------------------------------------------------
file Task.cpp
class mtbmpi::Task
brief Class to control a single concurrent task.
details
Tasks are created by the TaskFactory and owns
a work task object as a TaskAdapter.
The work tasks are derived from TaskAdapterBase.
The task knows its state, and can perform these actions:
Initialize, Start, Stop, Pause, Resume, AcceptData.
A task has its own arc, argv pair, so that the task can be an adapter
to a command-line application. In this implementation, the master
will initialize a task with command-line arguments for its job
as though that particular task were run from the command-line.
project Master-Task-Blackboard MPI Framework
author Thomas E. Hilinski <https://github.com/tehilinski>
copyright Copyright 2020 Thomas E. Hilinski. All rights reserved.
This software library, including source code and documentation,
is licensed under the Apache License version 2.0.
See "LICENSE.md" for more information.
------------------------------------------------------------------------------------------------------------*/
#include "Task.h"
#include "Master.h"
#include "MsgTags.h"
#include "UtilitiesMPI.h"
// define the following to write diagnostics to std::cout
// #define DBG_MPI_TASK
#ifdef DBG_MPI_TASK
#include <iostream>
using std::cout;
using std::endl;
#endif
namespace mtbmpi {
Task::Task (
Master & useParent, // parent of task
std::string const & taskName, // name of this task
IDNum const myID, // task mpi task rank
IDNum const controllerID, // controller task rank
IDNum const blackBoardID, // blackboard task rank
TaskFactoryPtr pTaskFactory, // task factory
ArgPair args)
: SendsMsgsToLog (myID, blackBoardID),
parent (useParent),
name ( taskName ),
idController (controllerID),
argPair (args),
state (State_Unknown),
action (NoAction)
{
// string with Tracker index: 1-based
idStr = ToString ( myID - parent.GetFirstTaskID() + 1 );
bufferState[0] = myID; // constant
#ifdef DBG_MPI_TASK
cout << "Tracker ID " << idStr << ": " << "constructor" << endl;
#endif
// get cmd-line args
StrVec cmdLineArgs (
GetArgs().second,
GetArgs().second + GetArgs().first );
// create and start task
pTaskAdapter = pTaskFactory->Create (*this, name, cmdLineArgs);
SetState( State_Created );
// Master decides when to activate this class
// so that derived Task class can do things after this constructor
// Activate ();
}
Task::~Task ()
{
#ifdef DBG_MPI_TASK
cout << "Tracker ID " << idStr << ": ~Task" << endl;
#endif
SetState( State_Terminated );
}
void Task::Activate ()
{
#ifdef DBG_MPI_TASK
cout << "Tracker ID " << idStr << ": " << "Activate: enter" << endl;
#endif
// Handle messages
while ( !( IsCompleted(state) ||
IsTerminated(state) ||
IsError(state) ) )
{
#ifdef DBG_MPI_TASK
cout << "Tracker ID " << idStr << ": "
<< "Activate: PI::COMM_WORLD.Probe: start"
<< ": state = " << AsString(state)
<< endl;
#endif
// Wait for messages
MPI::Status status;
mtbmpi::comm.Probe ( idController, MPI_ANY_TAG, status );
#ifdef DBG_MPI_TASK
cout << "Tracker ID " << idStr << ": "
<< "Activate: PI::COMM_WORLD.Probe: done"
<< endl;
static int probeCount = 0;
if ( !IsMsgTagValid( status.Get_tag() ) )
{
if ( probeCount < 10 )
{
std::ostringstream os;
os << "Task::Activate: Probe error."
<< " Error: " << status.Get_error()
<< " Tag: " << status.Get_tag()
<< " Source: " << status.Get_source()
<< " MPI::ERRORS_RETURN: " << MPI::ERRORS_RETURN;
Log().Error( os.str() );
cout << os.str() << endl;
++probeCount;
}
}
#endif
action = ProcessMessage (status);
#ifdef DBG_MPI_TASK
if ( IsMsgTagValid( status.Get_tag() ) )
{
cout << "Tracker ID " << idStr << ": "
<< "Activate: ProcessMessage: "
<< " Tag: " << status.Get_tag()
<< " Source: " << status.Get_source()
<< " Action = " << action
<< endl;
}
#endif
switch (action)
{
case ActionInitialize: DoActionInitialize (); break;
case ActionStart: DoActionStart (); break;
case ActionStop: DoActionStop (); break;
case ActionPause: DoActionPause (); break;
case ActionResume: DoActionResume (); break;
case ActionAcceptData: DoActionAcceptData(); break;
case NoAction:
default:
break;
}
} // while
#ifdef DBG_MPI_TASK
cout << "Tracker ID " << idStr << ": " << "Activate: done" << endl;
#endif
}
/// @cond SKIP_PRIVATE
void Task::DoActionInitialize ()
{
#ifdef DBG_MPI_TASK
cout << "Tracker ID " << idStr << ": "
<< "Activate: ActionInitialize" << endl;
#endif
if ( IsError(state) )
{
LogState();
return;
}
SetState( pTaskAdapter->InitializeTask () );
LogState();
}
void Task::DoActionStart ()
{
#ifdef DBG_MPI_TASK
cout << "Tracker ID " << idStr << ": "
<< "Activate: ActionStart: enter" << endl;
#endif
if ( IsError(state) )
{
LogState();
return;
}
if ( !IsInitialized(state) )
{
// handle failed initialization
SendMsgToLog ("initialization failed");
SetState( State_Error );
LogState();
return;
}
SetState( pTaskAdapter->StartTask() ); // returns state after start
LogState();
#ifdef DBG_MPI_TASK
cout << "Task " << idStr << ": "
<< "Activate: ActionStart: done" << endl;
#endif
}
void Task::DoActionStop ()
{
#ifdef DBG_MPI_TASK
cout << "Tracker ID " << idStr << ": "
<< "Activate: ActionStop: enter" << endl;
#endif
SetState( pTaskAdapter->StopTask() );
if ( !IsCompleted(state) && !IsTerminated(state) ) // not stopped?
{
// force stop - ouch!
pTaskAdapter.reset();
SetState( State_Terminated );
}
else // if ( IsCompleted(state) || IsTerminated(state) )
{
action = NoAction;
}
LogState();
// check for and discard any remaining msgs
short count = 0;
while ( count < 10 ) // number of checks
{
if ( mtbmpi::comm.Iprobe ( idController, MPI_ANY_TAG ) )
{
// cout << "Task " << idStr << ": discarding msg" << endl;
mtbmpi::comm.Recv ( 0, 0, MPI::BYTE, idController, MPI_ANY_TAG );
}
else // wait a bit
{
Sleep();
}
++count;
}
#ifdef DBG_MPI_TASK
cout << "Tracker ID " << idStr << ": "
<< "Activate: ActionStop: done" << endl;
#endif
}
void Task::DoActionPause ()
{
SetState( pTaskAdapter->PauseTask() );
LogState();
if ( IsPaused(state) )
action = NoAction; // wait for resume msg
}
void Task::DoActionResume ()
{
if ( IsError(state) )
{
LogState();
return;
}
SetState( pTaskAdapter->ResumeTask() );
LogState();
if ( IsRunning(state) || IsCompleted(state) )
action = NoAction;
}
void Task::DoActionAcceptData ()
{
if ( IsError(state) )
{
LogState();
return;
}
/// @todo DoActionAcceptData
}
void Task::SendStateToController ()
{
#ifdef DBG_MPI_TASK
cout << "Tracker ID " << idStr << ": "
<< "SendStateToController: "
<< "state = " << AsString(state)
<< endl;
#endif
// bufferState[0] = GetID(); // always
bufferState[1] = static_cast<int>(state);
mtbmpi::comm.Send (
&bufferState, // [0] = ID, [2] = enum State
2, // size of bufferState
MPI::INT, // data type
idController, // destination
Tag_State ); // msg type
}
void Task::LogState ()
{
std::string msg = "Tracker ID ";
msg += idStr;
msg += ": state = ";
msg += AsString(state);
Log().Message( msg );
}
Task::ActionNeeded Task::ProcessMessage (
MPI::Status const & status)
{
ActionNeeded newAction = NoAction;
switch ( status.Get_tag() )
{
case Tag_InitializeTask:
{
mtbmpi::comm.Recv ( 0, 0, MPI::BYTE, idController, Tag_InitializeTask );
newAction = ActionInitialize;
break;
}
case Tag_StartTask:
{
mtbmpi::comm.Recv ( 0, 0, MPI::BYTE, idController, Tag_StartTask );
newAction = ActionStart;
break;
}
case Tag_RequestStopTask:
{
mtbmpi::comm.Recv ( 0, 0, MPI::BYTE, idController, Tag_RequestStopTask );
newAction = ActionStop;
break;
}
case Tag_RequestStop:
{
mtbmpi::comm.Recv ( 0, 0, MPI::BYTE, idController, Tag_RequestStop );
newAction = ActionStop;
break;
}
case Tag_RequestPauseTask:
{
mtbmpi::comm.Recv ( &bufferState, 2, MPI::INT, idController, Tag_RequestPauseTask );
newAction = ActionPause;
break;
}
case Tag_RequestResumeTask:
{
mtbmpi::comm.Recv ( &bufferState, 2, MPI::INT, idController, Tag_RequestResumeTask );
newAction = ActionResume;
break;
}
case Tag_Data:
{
/// @todo Tag_Data
newAction = ActionAcceptData;
break;
}
default:
{
// unknown message - mark as received but discard
// mtbmpi::comm.Recv ( 0, 0, MPI::BYTE, idController, MPI_ANY_TAG );
break;
}
}
return newAction;
}
/// @endcond
void Task::SetState (State const newState)
{
state = newState;
SendStateToController ();
}
void Task::SendMsgToLog ( std::string const & logMsg )
{
Log().Message( logMsg, idStr );
}
void Task::SendMsgToLog ( char const * const logMsg )
{
Log().Message( logMsg, idStr );
}
} // namespace mtbmpi
| 23.8775 | 110 | 0.597424 | tehilinski |
9b91494bfc8e3d744f2c88529dcbe3779ce83d77 | 4,158 | cpp | C++ | ChangeJournal/VolumeOptions.cpp | ambray/Ntfs | c610315b007d0d0d1666d878e4f9c955deb86077 | [
"MIT"
] | 20 | 2016-02-04T12:23:39.000Z | 2021-12-30T04:17:49.000Z | ChangeJournal/VolumeOptions.cpp | c3358/Ntfs | c610315b007d0d0d1666d878e4f9c955deb86077 | [
"MIT"
] | null | null | null | ChangeJournal/VolumeOptions.cpp | c3358/Ntfs | c610315b007d0d0d1666d878e4f9c955deb86077 | [
"MIT"
] | 6 | 2015-07-15T04:29:07.000Z | 2020-12-21T22:35:17.000Z | #include "VolumeOptions.hpp"
ntfs::VolOps::VolOps(std::shared_ptr<void> volHandle) : vhandle(volHandle)
{
}
void ntfs::VolOps::setVolHandle(std::shared_ptr<void> vh)
{
if(vhandle)
vhandle.reset();
vhandle = vh;
}
std::shared_ptr<void> ntfs::VolOps::getVolHandle()
{
return vhandle;
}
std::tuple<std::string, std::string, unsigned long> ntfs::VolOps::getVolInfo()
{
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> conv;
wchar_t volNameBuf[MAX_PATH + 1] = { 0 };
wchar_t fsNameBuf[MAX_PATH + 1] = { 0 };
std::string volName;
std::string fsName;
unsigned long maxCompLen = 0;
unsigned long serial = 0;
unsigned long fsFlags = 0;
if (!GetVolumeInformationByHandleW(vhandle.get(), volNameBuf, MAX_PATH, &serial, &maxCompLen, &fsFlags, fsNameBuf, MAX_PATH)) {
throw VOL_API_INTERACTION_LASTERROR("Unable to query volume information!");
}
volName = conv.to_bytes(volNameBuf);
fsName = conv.to_bytes(fsNameBuf);
return std::make_tuple(volName, fsName, maxCompLen);
}
std::unique_ptr<NTFS_VOLUME_DATA_BUFFER> ntfs::VolOps::getVolData()
{
unsigned long bytesRead = 0;
auto tmp = std::unique_ptr<NTFS_VOLUME_DATA_BUFFER>(reinterpret_cast<PNTFS_VOLUME_DATA_BUFFER>(new unsigned char [vol_data_size]));
if (!DeviceIoControl(vhandle.get(), FSCTL_GET_NTFS_VOLUME_DATA, nullptr, 0, tmp.get(), vol_data_size, &bytesRead, nullptr)) {
throw VOL_API_INTERACTION_LASTERROR("Failed to get volume data!");
}
return tmp;
}
unsigned long ntfs::VolOps::getDriveType()
{
std::string volname;
std::tie(volname,
std::ignore,
std::ignore) = getVolInfo();
return GetDriveTypeA(volname.c_str());
}
uint64_t ntfs::VolOps::getFileCount()
{
uint64_t bytesPerSeg = 0;
auto data = getVolData();
if (!data)
throw VOL_API_INTERACTION_ERROR("Bad data pointer returned!", ERROR_INVALID_PARAMETER);
bytesPerSeg = data->BytesPerFileRecordSegment;
if (0 == bytesPerSeg)
throw VOL_API_INTERACTION_ERROR("Bad data returned... bytes per segment is 0!", ERROR_BUFFER_ALL_ZEROS);
return uint64_t(data->MftValidDataLength.QuadPart / bytesPerSeg);
}
std::vector<uint8_t> ntfs::VolOps::getMftRecord(uint64_t recNum)
{
NTFS_FILE_RECORD_INPUT_BUFFER inBuf = { 0 };
std::vector<uint8_t> vec;
size_t recSize = sizeof(NTFS_FILE_RECORD_OUTPUT_BUFFER);
unsigned long bytesReturned = 0;
auto data = getVolData();
if (!data)
throw VOL_API_INTERACTION_ERROR("Bad data pointer returned when querying MFT record!", ERROR_INVALID_PARAMETER);
recSize += data->BytesPerFileRecordSegment;
auto tmpbuf = std::unique_ptr<NTFS_FILE_RECORD_OUTPUT_BUFFER>(reinterpret_cast<PNTFS_FILE_RECORD_OUTPUT_BUFFER>(new unsigned char[recSize]));
inBuf.FileReferenceNumber.QuadPart = recNum;
if (!DeviceIoControl(vhandle.get(), FSCTL_GET_NTFS_FILE_RECORD, &inBuf, sizeof(inBuf), tmpbuf.get(), recSize, &bytesReturned, nullptr)) {
throw VOL_API_INTERACTION_LASTERROR("Unable to retrieve file record!");
}
vec.resize(tmpbuf->FileRecordLength);
memcpy(vec.data(), tmpbuf->FileRecordBuffer, tmpbuf->FileRecordLength);
return vec;
}
std::vector<uint8_t> ntfs::VolOps::processMftAttributes(uint64_t recNum, std::function<void(NTFS_ATTRIBUTE*)> func)
{
std::vector<uint8_t> vec;
try {
vec = getMftRecord(recNum);
processMftAttributes(vec, func);
}
catch (const std::exception& e) {
throw std::runtime_error(std::string("[VolOps] An exception occurred while processing the requested MFT record! Error: ") + e.what());
}
return vec;
}
void ntfs::VolOps::processMftAttributes(std::vector<uint8_t>& record, std::function<void(NTFS_ATTRIBUTE*)> func)
{
NTFS_FILE_RECORD_HEADER* header = reinterpret_cast<NTFS_FILE_RECORD_HEADER*>(record.data());
NTFS_ATTRIBUTE* current = nullptr;
unsigned long frecSize = 0;
if (!record.size() || !func)
throw VOL_API_INTERACTION_ERROR("Unable to process MFT record! Bad parameters provided.", ERROR_INVALID_PARAMETER);
for (current = (NTFS_ATTRIBUTE*)((unsigned char*)header + header->AttributeOffset);
current->AttributeType != NtfsAttributeType::AttributeEndOfRecord;
current = (NTFS_ATTRIBUTE*)((unsigned char*)current + current->Length))
{
func(current);
}
}
| 30.573529 | 142 | 0.746994 | ambray |
9b9527084fade5933b613150bacd7da8f99aed7b | 949 | hpp | C++ | include/actl/operation/scalar/comparison/less.hpp | AlCash07/ACTL | 15de4e2783d8e39dbd8e10cd635aaab328ca4f5b | [
"BSL-1.0"
] | 17 | 2018-08-22T06:48:20.000Z | 2022-02-22T21:20:09.000Z | include/actl/operation/scalar/comparison/less.hpp | AlCash07/ACTL | 15de4e2783d8e39dbd8e10cd635aaab328ca4f5b | [
"BSL-1.0"
] | null | null | null | include/actl/operation/scalar/comparison/less.hpp | AlCash07/ACTL | 15de4e2783d8e39dbd8e10cd635aaab328ca4f5b | [
"BSL-1.0"
] | null | null | null | // Copyright 2020 Oleksandr Bacherikov.
//
// Distributed under the Boost Software License, Version 1.0
// (see accompanying file LICENSE.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt).
#pragma once
#include <actl/operation/scalar/scalar_operation.hpp>
namespace ac {
namespace scalar {
struct less_f : scalar_operation<less_f, 2>
{
using category = ordering_operation_tag;
using argument_category = scalar_tag;
template <class T, class U>
static constexpr bool eval_scalar(T lhs, U rhs)
{
return lhs < rhs;
}
};
inline constexpr less_f less;
} // namespace scalar
struct less_f : operation<less_f>
{
using category = ordering_operation_tag;
static constexpr auto formula = scalar::less;
};
inline constexpr less_f less;
template <class T, class U, enable_operators<T, U> = 0>
constexpr auto operator<(T&& lhs, U&& rhs)
{
return less(pass<T>(lhs), pass<U>(rhs));
}
} // namespace ac
| 21.088889 | 60 | 0.702845 | AlCash07 |
9b9ad6d38e874528617dd5edf39aeb0e92fe366b | 4,443 | cxx | C++ | ITS/ITSbase/AliITSdigitSSD.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 52 | 2016-12-11T13:04:01.000Z | 2022-03-11T11:49:35.000Z | ITS/ITSbase/AliITSdigitSSD.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 1,388 | 2016-11-01T10:27:36.000Z | 2022-03-30T15:26:09.000Z | ITS/ITSbase/AliITSdigitSSD.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 275 | 2016-06-21T20:24:05.000Z | 2022-03-31T13:06:19.000Z | /**************************************************************************
* Copyright(c) 2004-2006, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
#include <AliITSdigitSSD.h>
#include <TArrayI.h>
#include <iostream>
///////////////////////////////////////////////////////////////////
// //
// Class defining the digit object
// for SSD
// Inherits from AliITSdigit
// //
///////////////////////////////////////////////////////////////////
ClassImp(AliITSdigitSSD)
//______________________________________________________________________
AliITSdigitSSD::AliITSdigitSSD():AliITSdigit(){
// default constructor
Int_t i;
for(i=0; i<fgkSize; i++) fTracks[i] = -3;
for(i=0; i<fgkSize; i++) fHits[i] = -1;
}
//__________________________________________________________________________
AliITSdigitSSD::AliITSdigitSSD(const Int_t *digits):AliITSdigit(digits){
// Creates a real SSD digit object
}
//_____________________________________________________________________________
AliITSdigitSSD::AliITSdigitSSD(const Int_t *digits,const Int_t *tracks,
const Int_t *hits):AliITSdigit(digits){
// Creates a simulated SSD digit object
for(Int_t i=0; i<fgkSize; i++) {
fTracks[i] = tracks[i];
fHits[i] = hits[i];
} // end for i
}
//______________________________________________________________________
Int_t AliITSdigitSSD::GetListOfTracks(TArrayI &t){
// Fills the TArrayI t with the tracks found in fTracks removing
// duplicated tracks, but otherwise in the same order. It will return
// the number of tracks and fill the remaining elements to the array
// t with -1.
// Inputs:
// TArrayI &t Reference to a TArrayI to contain the list of
// nonduplicated track numbers.
// Output:
// TArrayI &t The input array filled with the nonduplicated track
// numbers.
// Return:
// Int_t The number of none -1 entries in the TArrayI t.
Int_t nt = t.GetSize();
Int_t nth = this->GetNTracks();
Int_t n = 0,i,j;
Bool_t inlist = kFALSE;
t.Reset(-1); // -1 array.
for(i=0;i<nth;i++) {
if(this->GetTrack(i) == -1) continue;
inlist = kFALSE;
for(j=0;j<n;j++)if(this->GetTrack(i) == t.At(j)) inlist = kTRUE;
if(!inlist){ // add to end of list
t.AddAt(this->GetTrack(i),n);
if(n<nt) n++;
} // end if
} // end for i
return n;
}
//______________________________________________________________________
void AliITSdigitSSD::Print(ostream *os){
//Standard output format for this class
Int_t i;
AliITSdigit::Print(os);
for(i=0; i<fgkSize; i++) *os <<","<< fTracks[i];
for(i=0; i<fgkSize; i++) *os <<","<< fHits[i];
}
//______________________________________________________________________
void AliITSdigitSSD::Read(istream *os){
//Standard input for this class
Int_t i;
AliITSdigit::Read(os);
for(i=0; i<fgkSize; i++) *os >> fTracks[i];
for(i=0; i<fgkSize; i++) *os >> fHits[i];
}
//______________________________________________________________________
ostream &operator<<(ostream &os,AliITSdigitSSD &source){
// Standard output streaming function.
source.Print(&os);
return os;
}
//______________________________________________________________________
istream &operator>>(istream &os,AliITSdigitSSD &source){
// Standard output streaming function.
source.Read(&os);
return os;
}
| 38.634783 | 79 | 0.597569 | AllaMaevskaya |
9b9b04e6df390c202915d081bc3ff390efa01033 | 2,072 | cpp | C++ | MPAGSCipher/CaesarCipher.cpp | tomlatham/mpags-day-3-JamesDownsLab | 1bd5cddd53ec798440aec77978668f5056bd3d18 | [
"MIT"
] | null | null | null | MPAGSCipher/CaesarCipher.cpp | tomlatham/mpags-day-3-JamesDownsLab | 1bd5cddd53ec798440aec77978668f5056bd3d18 | [
"MIT"
] | 1 | 2019-11-06T14:17:01.000Z | 2019-11-06T14:17:01.000Z | MPAGSCipher/CaesarCipher.cpp | tomlatham/mpags-day-3-JamesDownsLab | 1bd5cddd53ec798440aec77978668f5056bd3d18 | [
"MIT"
] | 1 | 2019-11-06T11:39:22.000Z | 2019-11-06T11:39:22.000Z | //
// Created by james on 01/11/2019.
//
#include "CaesarCipher.hpp"
#include <iostream>
#include <string>
#include <vector>
CaesarCipher::CaesarCipher(const size_t key): key_{key} {}
CaesarCipher::CaesarCipher(const std::string& key): key_{0} {
// check to see whether string can be parsed as a number
bool stringIsNumber{true};
for (const auto& elem: key){
if (! std::isdigit(elem)){
stringIsNumber=false;
}
}
if (stringIsNumber) {
key_ = std::stoul(key);
}
else{
std::cerr << "[error] problem converting Caesar cipher key, string cannot be parsed as integer, key will default to " << key_ << std::endl;
}
}
std::string CaesarCipher::applyCipher(const std::string &inputText, const CipherMode cipherMode) const
{
// Create the output string
std::string outputText {};
// Make sure that the key is in the range 0 - 25
const size_t truncatedKey { key_ % alphabetSize_};
// Loop over the input text
char processedChar {'x'};
for ( const auto& origChar : inputText ) {
// For each character in the input text, find the corresponding position in
// the alphabet_ by using an indexed loop over the alphabet_ container
for ( size_t i{0}; i < alphabetSize_; ++i ) {
if (origChar == alphabet_[i] ) {
// Apply the appropriate shift (depending on whether we're encrypting
// or decrypting) and determine the new character
// Can then break out of the loop over the alphabet_
if ( cipherMode == CipherMode::Encrypt ) {
processedChar = alphabet_[(i + truncatedKey) % alphabetSize_ ];
} else {
processedChar = alphabet_[(i + alphabetSize_ - truncatedKey) % alphabetSize_ ];
}
break;
}
}
// Add the new character to the output text
outputText += processedChar;
}
return outputText;
}
| 31.393939 | 151 | 0.585907 | tomlatham |
9b9e9d3e6bc01f9e16184354f5272b9a263ae466 | 1,065 | hpp | C++ | src/JSON/JSONSerialiser.hpp | ilyaskurikhin/beesim | f30a8fad0d784074400e48055d69823717cae623 | [
"DOC"
] | null | null | null | src/JSON/JSONSerialiser.hpp | ilyaskurikhin/beesim | f30a8fad0d784074400e48055d69823717cae623 | [
"DOC"
] | null | null | null | src/JSON/JSONSerialiser.hpp | ilyaskurikhin/beesim | f30a8fad0d784074400e48055d69823717cae623 | [
"DOC"
] | null | null | null | /*
* prjsv 2015, 2016
* 2014, 2016
* Marco Antognini
*/
#ifndef INFOSV_JSONSERIALISER_HPP
#define INFOSV_JSONSERIALISER_HPP
#include <JSON/JSON.hpp>
#include <stdexcept>
#include <string>
namespace j
{
class BadPayload : public std::runtime_error
{
public:
BadPayload(std::string const& msg);
};
class NoSuchFile : public std::runtime_error
{
public:
NoSuchFile(std::string const& msg);
};
// Read a JSON value from a payload string
// Throw a BadPayload when the format is invalid
Value readFromString(std::string const& payload);
// Like `readFromString` but the payload is read from the given file
// Throw a BadPayload when the file's content has an invalid format
// Throw a NoSuchFile when the file doesn't exist
Value readFromFile(std::string const& filepath);
// Convert a JSON value to the corresponding payload string
std::string writeToString(Value const& value);
// Like `writeToString` but write it to the given file
void writeToFile(Value const& value, std::string const& fileapath);
} // j
#endif // INFOSV_JSONSERIALISER_HPP
| 22.1875 | 68 | 0.748357 | ilyaskurikhin |
9b9f91932f7933f31ad51495f9796c4c7e1a3c1a | 1,538 | cpp | C++ | src/sound/load_music.cpp | Damdoshi/LibLapin | 800e0f17ed8f3c47797c48feea4c280bb0e4bdc9 | [
"BSD-3-Clause"
] | 38 | 2016-07-30T09:35:19.000Z | 2022-03-04T10:13:48.000Z | src/sound/load_music.cpp | Elania-Marvers/LibLapin | 800e0f17ed8f3c47797c48feea4c280bb0e4bdc9 | [
"BSD-3-Clause"
] | 15 | 2017-02-12T19:20:52.000Z | 2021-06-09T09:30:52.000Z | src/sound/load_music.cpp | Elania-Marvers/LibLapin | 800e0f17ed8f3c47797c48feea4c280bb0e4bdc9 | [
"BSD-3-Clause"
] | 12 | 2016-10-06T09:06:59.000Z | 2022-03-04T10:14:00.000Z | // Jason Brillante "Damdoshi"
// Hanged Bunny Studio 2014-2018
//
// Bibliotheque Lapin
#include <string.h>
#include "lapin_private.h"
#define PATTERN "%s -> %p"
t_bunny_music *bunny_read_music(t_bunny_configuration *cnf)
{
t_bunny_sound *pc = NULL;
if (bunny_set_sound_attribute(NULL, &pc, &cnf, true) == false)
return (NULL);
return ((t_bunny_music*)pc);
}
t_bunny_music *bunny_load_music(const char *file)
{
struct bunny_music *mus;
if (bunny_which_format(file) != BC_CUSTOM)
{
t_bunny_configuration *cnf;
if ((cnf = bunny_open_configuration(file, NULL)) == NULL)
return (NULL);
mus = (struct bunny_music*)bunny_read_music(cnf);
bunny_delete_configuration(cnf);
return ((t_bunny_music*)mus);
}
if ((mus = new (std::nothrow) struct bunny_music) == NULL)
goto Fail;
if ((mus->music.openFromFile(file)) == false)
goto FailStruct;
mus->file = bunny_strdup(file);
mus->type = MUSIC;
mus->duration = mus->music.getDuration().asSeconds();
mus->volume = 50;
mus->pitch = 1;
mus->loop = true;
mus->position[0] = 0;
mus->position[1] = 0;
mus->position[2] = 0;
mus->attenuation = 5;
mus->playing = false;
mus->pause = false;
mus->sound_manager = NULL;
mus->sound_areas = NULL;
mus->trap = NULL;
scream_log_if(PATTERN, "ressource,sound", file, mus);
return ((t_bunny_music*)mus);
FailStruct:
delete mus;
Fail:
scream_error_if(return (NULL), bunny_errno, PATTERN, "ressource,sound", file, (void*)NULL);
return (NULL);
}
| 23.30303 | 93 | 0.659948 | Damdoshi |
9ba04a333b68ffc1f035a2a6455d3a1c9e7b685c | 1,500 | cpp | C++ | Source/PyramidMath/ExplorerMovementComponent.cpp | andriuchap/summer-ue4jam-2019 | 125a67cffe6b98d5d6a04b762a07e2c75256d86b | [
"Apache-2.0"
] | null | null | null | Source/PyramidMath/ExplorerMovementComponent.cpp | andriuchap/summer-ue4jam-2019 | 125a67cffe6b98d5d6a04b762a07e2c75256d86b | [
"Apache-2.0"
] | null | null | null | Source/PyramidMath/ExplorerMovementComponent.cpp | andriuchap/summer-ue4jam-2019 | 125a67cffe6b98d5d6a04b762a07e2c75256d86b | [
"Apache-2.0"
] | null | null | null | // Fill out your copyright notice in the Description page of Project Settings.
#include "ExplorerMovementComponent.h"
#include "GameFramework/PhysicsVolume.h"
UExplorerMovementComponent::UExplorerMovementComponent(const FObjectInitializer &ObjInitializer)
{
FallingGravityScale = 2.0F;
FallingThreshold = 100.0F;
}
void UExplorerMovementComponent::OnMovementModeChanged(EMovementMode PreviousMovementMode, uint8 PreviousCustomMode)
{
Super::OnMovementModeChanged(PreviousMovementMode, PreviousCustomMode);
}
FVector UExplorerMovementComponent::NewFallVelocity(const FVector& InitialVelocity, const FVector& Gravity, float DeltaTime) const
{
FVector Result = InitialVelocity;
if (DeltaTime > 0.f)
{
if (InitialVelocity.Z < FallingThreshold)
{
// Apply extra gravity when falling so the character doesn't feel as floaty.
float Multiplier = 1 - (FMath::Clamp(InitialVelocity.Z, 0.0F, FallingThreshold) / FallingThreshold);
Result += Gravity * DeltaTime * FallingGravityScale;
}
else
{
// Apply gravity.
Result += Gravity * DeltaTime;
}
// Don't exceed terminal velocity.
const float TerminalLimit = FMath::Abs(GetPhysicsVolume()->TerminalVelocity);
if (Result.SizeSquared() > FMath::Square(TerminalLimit))
{
const FVector GravityDir = Gravity.GetSafeNormal();
if ((Result | GravityDir) > TerminalLimit)
{
Result = FVector::PointPlaneProject(Result, FVector::ZeroVector, GravityDir) + GravityDir * TerminalLimit;
}
}
}
return Result;
} | 30.612245 | 130 | 0.76 | andriuchap |
9ba04e7228cd06789745eb3286b692d96b630416 | 281 | cpp | C++ | CSES-Problemset/sorting and searching/distinct_numbers.cpp | rranjan14/cp-solutions | 9614508efbed1e4ee8b970b5eed535d782a5783f | [
"MIT"
] | null | null | null | CSES-Problemset/sorting and searching/distinct_numbers.cpp | rranjan14/cp-solutions | 9614508efbed1e4ee8b970b5eed535d782a5783f | [
"MIT"
] | null | null | null | CSES-Problemset/sorting and searching/distinct_numbers.cpp | rranjan14/cp-solutions | 9614508efbed1e4ee8b970b5eed535d782a5783f | [
"MIT"
] | null | null | null | #include <iostream>
#include <set>
#define lli long long int
using namespace std;
int main()
{
lli n, x;
cin >> n;
set<int, greater<int>> s;
for (lli i = 0; i < n; i++)
{
cin >> x;
s.insert(x);
}
cout << s.size() << "\n";
return 0;
} | 16.529412 | 31 | 0.480427 | rranjan14 |
9ba227d5b892261ae49a495c23d4152e89d695a5 | 4,976 | hpp | C++ | core/boards/stm32l073xx/include/dma.hpp | azuwey/hexos | 746901a86d664c44c03cd46bb2370975f6a11542 | [
"MIT"
] | null | null | null | core/boards/stm32l073xx/include/dma.hpp | azuwey/hexos | 746901a86d664c44c03cd46bb2370975f6a11542 | [
"MIT"
] | null | null | null | core/boards/stm32l073xx/include/dma.hpp | azuwey/hexos | 746901a86d664c44c03cd46bb2370975f6a11542 | [
"MIT"
] | null | null | null | #ifndef __STM32L073XX_DMA
#define __STM32L073XX_DMA
#include "common_types.hpp"
namespace DMA {
namespace ADDRESSES {
const inline t_uint32 BASE_ADDRESS = ((t_uint32)0x40020000U);
} // namespace ADDRESSES
namespace TYPEDEFS {
typedef union {
struct __attribute__((packed)) {
__R t_uint32 GIF1 : 0x01U;
__R t_uint32 TCIF1 : 0x01U;
__R t_uint32 HTIF1 : 0x01U;
__R t_uint32 TEIF1 : 0x01U;
__R t_uint32 GIF2 : 0x01U;
__R t_uint32 TCIF2 : 0x01U;
__R t_uint32 HTIF2 : 0x01U;
__R t_uint32 TEIF2 : 0x01U;
__R t_uint32 GIF3 : 0x01U;
__R t_uint32 TCIF3 : 0x01U;
__R t_uint32 HTIF3 : 0x01U;
__R t_uint32 TEIF3 : 0x01U;
__R t_uint32 GIF4 : 0x01U;
__R t_uint32 TCIF4 : 0x01U;
__R t_uint32 HTIF4 : 0x01U;
__R t_uint32 TEIF4 : 0x01U;
__R t_uint32 GIF5 : 0x01U;
__R t_uint32 TCIF5 : 0x01U;
__R t_uint32 HTIF5 : 0x01U;
__R t_uint32 TEIF5 : 0x01U;
__R t_uint32 GIF6 : 0x01U;
__R t_uint32 TCIF6 : 0x01U;
__R t_uint32 HTIF6 : 0x01U;
__R t_uint32 TEIF6 : 0x01U;
__R t_uint32 GIF7 : 0x01U;
__R t_uint32 TCIF7 : 0x01U;
__R t_uint32 HTIF7 : 0x01U;
__R t_uint32 TEIF7 : 0x01U;
t_uint32 /* RESERVED */ : 0x04U;
} BIT;
__R t_uint32 WORD;
} t_ISR;
typedef union {
struct __attribute__((packed)) {
__W t_uint32 CGIF1 : 0x01U;
__W t_uint32 CTCIF1 : 0x01U;
__W t_uint32 CHTIF1 : 0x01U;
__W t_uint32 CTEIF1 : 0x01U;
__W t_uint32 CGIF2 : 0x01U;
__W t_uint32 CTCIF2 : 0x01U;
__W t_uint32 CHTIF2 : 0x01U;
__W t_uint32 CTEIF2 : 0x01U;
__W t_uint32 CGIF3 : 0x01U;
__W t_uint32 CTCIF3 : 0x01U;
__W t_uint32 CHTIF3 : 0x01U;
__W t_uint32 CTEIF3 : 0x01U;
__W t_uint32 CGIF4 : 0x01U;
__W t_uint32 CTCIF4 : 0x01U;
__W t_uint32 CHTIF4 : 0x01U;
__W t_uint32 CTEIF4 : 0x01U;
__W t_uint32 CGIF5 : 0x01U;
__W t_uint32 CTCIF5 : 0x01U;
__W t_uint32 CHTIF5 : 0x01U;
__W t_uint32 CTEIF5 : 0x01U;
__W t_uint32 CGIF6 : 0x01U;
__W t_uint32 CTCIF6 : 0x01U;
__W t_uint32 CHTIF6 : 0x01U;
__W t_uint32 CTEIF6 : 0x01U;
__W t_uint32 CGIF7 : 0x01U;
__W t_uint32 CTCIF7 : 0x01U;
__W t_uint32 CHTIF7 : 0x01U;
__W t_uint32 CTEIF7 : 0x01U;
t_uint32 /* RESERVED */ : 0x04U;
} BIT;
__W t_uint32 WORD;
} t_IFCR;
typedef union {
struct __attribute__((packed)) {
__RW t_uint32 EN : 0x01U;
__RW t_uint32 TCIE : 0x01U;
__RW t_uint32 HTIE : 0x01U;
__RW t_uint32 TEIE : 0x01U;
__RW t_uint32 DIR : 0x01U;
__RW t_uint32 CIRC : 0x01U;
__RW t_uint32 PINC : 0x01U;
__RW t_uint32 MINC : 0x01U;
__RW t_uint32 PSIZE : 0x02U;
__RW t_uint32 MSIZE : 0x02U;
__RW t_uint32 PL : 0x02U;
__RW t_uint32 MEM2MEM : 0x01U;
t_uint32 /* RESERVED */ : 0x11U;
} BIT;
__RW t_uint32 WORD;
} t_CCR;
typedef union {
struct __attribute__((packed)) {
__RW t_uint32 NDT : 0x10U;
t_uint32 /* RESERVED */ : 0x10U;
} BIT;
__RW t_uint32 WORD;
} t_CNDTR;
typedef union {
struct __attribute__((packed)) {
__RW t_uint32 PA : 0x20U;
} BIT;
__RW t_uint32 WORD;
} t_CPAR;
typedef union {
struct __attribute__((packed)) {
__RW t_uint32 MA : 0x20U;
} BIT;
__RW t_uint32 WORD;
} t_CMAR;
typedef union {
struct __attribute__((packed)) {
__RW t_uint32 C1S : 0x04U;
__RW t_uint32 C2S : 0x04U;
__RW t_uint32 C3S : 0x04U;
__RW t_uint32 C4S : 0x04U;
__RW t_uint32 C5S : 0x04U;
__RW t_uint32 C6S : 0x04U;
__RW t_uint32 C7S : 0x04U;
t_uint32 /* RESERVED */ : 0x04U;
} BIT;
__RW t_uint32 WORD;
} t_CSELR;
typedef struct __attribute__((packed)) {
t_ISR ISR;
t_IFCR IFCR;
t_CCR CCR1;
t_CNDTR CNDTR1;
t_CPAR CPAR1;
t_CMAR CMAR1;
t_uint32 RESERVED0[1];
t_CCR CCR2;
t_CNDTR CNDTR2;
t_CPAR CPAR2;
t_CMAR CMAR2;
t_uint32 RESERVED1[1];
t_CCR CCR3;
t_CNDTR CNDTR3;
t_CPAR CPAR3;
t_CMAR CMAR3;
t_uint32 RESERVED2[1];
t_CCR CCR4;
t_CNDTR CNDTR4;
t_CPAR CPAR4;
t_CMAR CMAR4;
t_uint32 RESERVED3[1];
t_CCR CCR5;
t_CNDTR CNDTR5;
t_CPAR CPAR5;
t_CMAR CMAR5;
t_uint32 RESERVED4[1];
t_CCR CCR6;
t_CNDTR CNDTR6;
t_CPAR CPAR6;
t_CMAR CMAR6;
t_uint32 RESERVED5[1];
t_CCR CCR7;
t_CNDTR CNDTR7;
t_CPAR CPAR7;
t_CMAR CMAR7;
t_uint32 RESERVED6[6];
t_CSELR CSELR;
} t_DMA;
} // namespace TYPEDEFS
namespace HAL {} // namespace HAL
} // namespace DMA
namespace REGISTERS {
inline DMA::TYPEDEFS::t_DMA &r_DMA = *((DMA::TYPEDEFS::t_DMA *)DMA::ADDRESSES::BASE_ADDRESS);
} // namespace REGISTERS
#endif // __STM32L073XX_DMA | 26.897297 | 93 | 0.610732 | azuwey |
9ba729f79b09d9da86be71e67339b928a0abb3c9 | 10,229 | cpp | C++ | cVRP/Individual.cpp | Frown00/evolutionary-algorithm | 1ae279d904910be70c473c0ec6a9b9dc1395190e | [
"MIT"
] | null | null | null | cVRP/Individual.cpp | Frown00/evolutionary-algorithm | 1ae279d904910be70c473c0ec6a9b9dc1395190e | [
"MIT"
] | null | null | null | cVRP/Individual.cpp | Frown00/evolutionary-algorithm | 1ae279d904910be70c473c0ec6a9b9dc1395190e | [
"MIT"
] | null | null | null | #include "Individual.h"
#include "utils.cpp"
Individual::Individual(int t_dimension) {
m_dimension = t_dimension;
m_fitness = -1;
}
Individual::Individual(Individual* other)
{
m_genotype = other->m_genotype;
m_fitness = other->m_fitness;
m_dimension = other->m_dimension;
m_genotype_text = other->m_genotype_text;
}
Individual::~Individual()
{
std::cout << "\nINDIVIDUAL DEST\n";
}
std::vector<int> Individual::getGenotype() {
return m_genotype;
}
std::string Individual::getTextGenotype()
{
//std::string genotype = "";
/*for(int i = 0; i < m_genotype.size(); i++) {
genotype += std::to_string(m_genotype[i]);
genotype += " ";
}*/
return m_genotype_text;
}
void Individual::setGenotype(std::vector<int> t_genotype) {
m_genotype_text = "";
for(int i = 0; i < t_genotype.size(); i++) {
m_genotype.push_back(t_genotype[i]);
m_genotype_text += std::to_string(t_genotype[i]);
}
}
std::vector<int> Individual::getIds(int t_dimension, int t_depot_id) {
std::vector<int> left_location_ids;
for(int i = 1; i <= t_dimension; i++) {
if(i != t_depot_id)
left_location_ids.push_back(i);
}
return left_location_ids;
}
void Individual::setRandomGenotype(Location* t_depot, std::vector<Location*> t_locations, int t_capacity) {
int depot_id = t_depot->getId();
std::vector<int> left_location_ids = getIds(m_dimension, depot_id);
m_genotype.push_back(t_depot->getId());
for(int i = 0; i < m_dimension - 1; i++) {
int idx = rand() % left_location_ids.size();
m_genotype.push_back(left_location_ids[idx]);
left_location_ids.erase(left_location_ids.begin() + idx);
}
m_genotype.push_back(t_depot->getId());
// fill with random returns to depot
for(int i = 0; i < m_dimension; i++) {
int idx = rand() % m_genotype.size();
m_genotype.insert(m_genotype.begin() + idx, t_depot->getId());
}
fixGenotype(t_depot, t_locations, t_capacity);
}
double Individual::countFitness(Location* t_depot, std::vector<Location*> t_locations) {
m_fitness = 0;
const int genotype_size = m_genotype.size();
Location* first = getLocationById(t_locations, m_genotype[0]);
int prev_last = genotype_size - 1;
Location* last = getLocationById(t_locations, m_genotype[prev_last]);
m_fitness += t_depot->countDistance(first->getCoords());
for(int i = 0; i < prev_last; i++) {
Location* start_route = getLocationById(t_locations, m_genotype[i]);
int next = i + 1;
Location* end_route = getLocationById(t_locations, m_genotype[next]);
m_fitness += start_route->countDistance(end_route->getCoords());
}
m_fitness += t_depot->countDistance(last->getCoords());
return m_fitness;
}
double Individual::getFitness() {
return m_fitness;
}
Location* Individual::getLocationById(std::vector<Location*> t_locations, int t_id) {
for(int i = 0; i < t_locations.size(); i++) {
if(t_locations[i]->getId() == t_id)
return t_locations[i];
}
}
void Individual::mutate(
MutationType t_type,
Location* t_depot,
std::vector<Location*> t_locations,
int t_capacity
) {
int gen1_pos = (rand() % (m_genotype.size() - 1)) + 1;
int gen2_pos = (rand() % (m_genotype.size() - 1)) + 1;
switch (t_type) {
case MutationType::SWAP: {
swapMutation(gen1_pos, gen2_pos);
break;
}
case MutationType::INVERSION: {
inversionMutation(gen1_pos, gen2_pos);
break;
}
default: throw "Wrong mutation type";
}
fixGenotype(t_depot, t_locations, t_capacity);
}
void Individual::fixGenotype(Location* t_depot, std::vector<Location*> t_locations, int t_capacity) {
int depot_id = t_depot->getId();
if(m_genotype[0] != depot_id)
m_genotype.insert(m_genotype.begin() + 0, depot_id);
if(m_genotype[m_genotype.size() - 1] != depot_id)
m_genotype.insert(m_genotype.begin() + m_genotype.size(), depot_id);
// clear depot after depot
for(int i = 0; i < m_genotype.size() - 1; i++) {
if(m_genotype[i] == m_genotype[i + 1]) {
m_genotype.erase(m_genotype.begin() + i);
i--;
}
}
int current_weight = 0;
for(int i = 0; i < m_genotype.size(); i++) {
if(m_genotype[i] == t_depot->getId()) {
current_weight = 0;
}
else {
Location* loc = getLocationById(t_locations, m_genotype[i]);
current_weight += loc->getDemands();
if(current_weight > t_capacity) {
m_genotype.insert(m_genotype.begin() + i, depot_id);
current_weight = 0;
}
}
}
m_genotype_text = "";
for(int i = 0; i < m_genotype.size(); i++) {
m_genotype_text += std::to_string(m_genotype[i]);
}
}
std::vector<int> Individual::getPlainGenotype(Location* t_depot) {
std::vector<int> plain_genotype;
for(int i = 0; i < m_genotype.size(); i++) {
if(m_genotype[i] != t_depot->getId()) {
plain_genotype.push_back(m_genotype[i]);
}
}
return plain_genotype;
}
void Individual::swapMutation(int t_gen1_pos, int t_gen2_pos) {
int temp = m_genotype[t_gen1_pos];
m_genotype[t_gen1_pos] = m_genotype[t_gen2_pos];
m_genotype[t_gen2_pos] = temp;
}
void Individual::inversionMutation(int t_gen1_pos, int t_gen2_pos) {
int swap_amount = (abs(t_gen1_pos - t_gen2_pos) + 1)/ 2;
int left = t_gen1_pos;
int right = t_gen2_pos;
if(t_gen1_pos > t_gen2_pos) {
left = t_gen2_pos;
right = t_gen1_pos;
}
for(int i = 0; i <= swap_amount; i++) {
swapMutation(left + i, right - i);
}
}
std::vector<std::vector<int>> Individual::cycleCrossover(Individual* t_other_individual, Location* t_depot) {
std::vector<int> cycle;
std::vector<int> parent1 = getPlainGenotype(t_depot);
std::vector<int> parent2 = t_other_individual->getPlainGenotype(t_depot);
std::vector<int> child1_genotype, child2_genotype;
int pos = 0;
int first_in_cycle = parent1[0];
cycle.push_back(first_in_cycle); // first is a depot (start point)
while(parent1.size() > pos) {
int index = utils::findIndex(parent2, cycle[pos]);
int gen = parent1[index];
if(gen == first_in_cycle) break;
cycle.push_back(gen);
pos++;
}
// crossover
for(int i = 0; i < parent1.size(); i++) {
if(utils::findIndex(cycle, parent1[i]) != -1) {
child1_genotype.push_back(parent2[i]);
child2_genotype.push_back(parent1[i]);
}
else {
child1_genotype.push_back(parent1[i]);
child2_genotype.push_back(parent2[i]);
}
}
// set returns to depot according to their parents
for(int i = 0; i < m_genotype.size(); i++) {
if(m_genotype[i] == t_depot->getId()) {
child1_genotype.insert(child1_genotype.begin() + i, m_genotype[i]);
}
}
std::vector<int> partner_genotype = t_other_individual->getGenotype();
for(int i = 0; i < partner_genotype.size(); i++) {
if(partner_genotype[i] == t_depot->getId()) {
child2_genotype.insert(child2_genotype.begin() + i, partner_genotype[i]);
}
}
return std::vector<std::vector<int>> { child1_genotype, child2_genotype };
}
std::vector<std::vector<int>> Individual::orderedCrossover(Individual* t_other_individual, Location* t_depot) {
std::vector<int> parent1 = getPlainGenotype(t_depot);
std::vector<int> parent2 = t_other_individual->getPlainGenotype(t_depot);
std::vector<int> child1_genotype, child2_genotype = std::vector<int>();
child1_genotype.resize(parent1.size());
child2_genotype.resize(parent2.size());
int cross_point1 = rand() % parent1.size();
int cross_point2 = rand() % parent1.size();
int min_constr = cross_point1;
int max_constr = cross_point2;
if(min_constr > max_constr) {
int temp = min_constr;
min_constr = max_constr;
max_constr = min_constr;
}
std::vector<int> values_in_section;
std::vector<int> values_out_section;
for(int i = 0; i < parent1.size(); i++) {
int gen = parent1[i];
if(i >= min_constr && i <= max_constr) {
values_in_section.push_back(gen);
}
else {
values_out_section.push_back(gen);
}
}
int offset = 0;
for(int i = 0; i < parent1.size(); i++) {
if(i >= min_constr && i <= max_constr) {
child1_genotype[i] = parent1[i];
}
else {
int local_offset = -1;
for(int j = 0; j < parent2.size(); j++) {
int found = utils::findIndex(values_in_section, parent2[j]);
if(found == -1) {
local_offset++;
}
if(offset == local_offset) {
child1_genotype[i] = parent2[j];
offset++;
break;
}
}
}
}
for (int i = 0; i < parent2.size(); i++) {
int gen = parent2[i];
int found = utils::findIndex(values_out_section, gen);
if(found != -1) {
child2_genotype[i] = values_out_section[0];
values_out_section.erase(values_out_section.begin());
}
else {
child2_genotype[i] = parent2[i];
}
}
return std::vector<std::vector<int>> { child1_genotype, child2_genotype };
}
std::vector<Individual*> Individual::crossover(
CrossoverType t_type,
Location* t_depot,
std::vector<Location*> t_locations,
int t_capacity,
Individual* t_other_individual
) {
std::vector<std::vector<int>> child_genotypes;
switch(t_type) {
case CrossoverType::ORDERED:
child_genotypes = orderedCrossover(t_other_individual, t_depot);
case CrossoverType::CYCLE:
child_genotypes = cycleCrossover(t_other_individual, t_depot);
break;
default:
// error in config
break;
}
Individual* child1 = new Individual(m_dimension);
Individual* child2 = new Individual(m_dimension);
child1->setGenotype(child_genotypes[0]);
child1->fixGenotype(t_depot, t_locations, t_capacity);
child2->setGenotype(child_genotypes[1]);
child2->fixGenotype(t_depot, t_locations, t_capacity);
return std::vector<Individual*> { child1, child2 };
}
void Individual::printRouting(Location* t_depot) {
int route = 1;
std::cout << "\nDEPOT ID: " << t_depot->getId();
for(int i = 0; i < m_genotype.size() - 1; i++) {
if(m_genotype[i] == t_depot->getId()) {
std::cout << "\nROUTE " + std::to_string(route) + ": ";
route++;
}
else {
std::cout << m_genotype[i];
int next = i + 1;
if(m_genotype[next] != t_depot->getId()) {
std::cout << " -> ";
}
}
}
std::cout << '\n' << "FITNESS: " << getFitness();
}
| 30.810241 | 111 | 0.655196 | Frown00 |
9ba7ebc605fc3a841bc949e22916bb82cca3a365 | 2,081 | cpp | C++ | tests/msg_feed_id/test.cpp | morgenm/PMC-Game | ae09b3df200bd1cf47bcf8888939112e5ac42d38 | [
"MIT"
] | null | null | null | tests/msg_feed_id/test.cpp | morgenm/PMC-Game | ae09b3df200bd1cf47bcf8888939112e5ac42d38 | [
"MIT"
] | null | null | null | tests/msg_feed_id/test.cpp | morgenm/PMC-Game | ae09b3df200bd1cf47bcf8888939112e5ac42d38 | [
"MIT"
] | null | null | null | #include "msg_sys/msg_feed_id.h"
#include <iostream>
void TryEquals() {
MessageFeedID lhs;
MessageFeedID rhs;
rhs.NewID();
if( lhs == rhs ) {
std::cout << "MessageFeedID TryEquals Bad Test: FAILED!\n";
}
else {
std::cout << "MessageFeedID TryEquals Bad Test: Passed.\n";
}
MessageFeedID newLHS;
MessageFeedID newRHS;
if( newLHS == newRHS ) {
std::cout << "MessageFeedID TryEquals Good Test: Passed.\n";
}
else {
std::cout << "MessageFeedID TryEquals Good Test: FAILED!\n";
}
}
void TryLessThan() {
MessageFeedID lhs;
MessageFeedID rhs;
if( lhs < rhs ) {
std::cout << "MessageFeedID TryLessThan Bad Test: FAILED!\n";
}
else {
std::cout << "MessageFeedID TryLessThan Bad Test: Passed.\n";
}
MessageFeedID newLHS;
MessageFeedID newRHS;
newRHS.NewID();
if( newLHS < newRHS ) {
std::cout << "MessageFeedID TryLessThan Good Test: Passed.\n";
}
else {
std::cout << "MessageFeedID TryLessThan Good Test: FAILED!\n";
}
}
void TryGreaterThan() {
MessageFeedID lhs;
MessageFeedID rhs;
if( lhs > rhs ) {
std::cout << "MessageFeedID TryGreaterThan Bad Test: FAILED!\n";
}
else {
std::cout << "MessageFeedID TryLessThan Bad Test: Passed.\n";
}
MessageFeedID newLHS;
MessageFeedID newRHS;
newRHS.NewID();
if( newRHS > newLHS ) {
std::cout << "MessageFeedID TryGreaterThan Good Test: Passed.\n";
}
else {
std::cout << "MessageFeedID TryGreaterThan Good Test: FAILED!\n";
}
}
void TryNewID() {
MessageFeedID oldID;
MessageFeedID newID;
newID.NewID();
oldID = newID;
for(int i=0; i<1000; i++) {
newID.NewID();
}
if( newID > oldID ) {
std::cout << "MessageFeedID TryNewID Many Test: Passed.\n";
}
else {
std::cout << "MessageFeedID TryNewID Many Test: FAILED!\n";
}
}
int main() {
TryEquals();
TryLessThan();
TryGreaterThan();
TryNewID();
return 0;
}
| 21.905263 | 73 | 0.583373 | morgenm |
9baa88af4a23983b1d79e18b1992c91ec4dc3c21 | 1,207 | hh | C++ | libs/core/include/singleton.hh | no111u3/laptop_control | 92f25ef61511dfacd5edeff3dedf06f31a347a9f | [
"Apache-2.0"
] | 1 | 2019-04-30T13:46:51.000Z | 2019-04-30T13:46:51.000Z | libs/core/include/singleton.hh | no111u3/laptop_control | 92f25ef61511dfacd5edeff3dedf06f31a347a9f | [
"Apache-2.0"
] | null | null | null | libs/core/include/singleton.hh | no111u3/laptop_control | 92f25ef61511dfacd5edeff3dedf06f31a347a9f | [
"Apache-2.0"
] | null | null | null | /**
Copyright 2019 Boris Vinogradov <[email protected]>
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.
*/
#pragma once
#include <memory>
#include <utility>
namespace core {
template <typename T>
class Singleton {
public:
static T & get() {
return *t_;
}
template <typename ...Args>
static void create(Args ...args) {
t_ = std::make_unique<T>(std::forward<Args>(args)...);
}
private:
Singleton() = default;
Singleton(const Singleton &) = default;
Singleton(Singleton &&) noexcept = default;
~Singleton() = default;
static inline std::unique_ptr<T> t_;
};
} // namespace core | 28.738095 | 75 | 0.651201 | no111u3 |
9bb32ea99deda845c13b99b27305e1a56d6f0444 | 1,196 | hxx | C++ | ImageSharpOpenJpegNative/src/openjpeg.mct.hxx | cinderblocks/ImageSharp.OpenJpeg | bf5c976a6dbfa0d2666be566c845a7410440cea2 | [
"Apache-2.0"
] | null | null | null | ImageSharpOpenJpegNative/src/openjpeg.mct.hxx | cinderblocks/ImageSharp.OpenJpeg | bf5c976a6dbfa0d2666be566c845a7410440cea2 | [
"Apache-2.0"
] | null | null | null | ImageSharpOpenJpegNative/src/openjpeg.mct.hxx | cinderblocks/ImageSharp.OpenJpeg | bf5c976a6dbfa0d2666be566c845a7410440cea2 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2022 Sjofn LLC. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef _ISOJ_OPENJPEG_OPENJP2_OPENJPEG_MCT_H_
#define _ISOJ_OPENJPEG_OPENJP2_OPENJPEG_MCT_H_
#include "ImageSharpOpenJpeg_Exports.hxx"
#include "shared.hxx"
IMAGESHARPOPENJPEG_EXPORT bool openjpeg_openjp2_opj_set_MCT(opj_cparameters_t* parameters,
float* pEncodingMatrix,
int32_t* p_dc_shift,
const uint32_t pNbComp)
{
return ::opj_set_MCT(parameters, pEncodingMatrix, p_dc_shift, pNbComp);
}
#endif // _CPP_OPENJPEG_OPENJP2_OPENJPEG_MCT_H_ | 38.580645 | 90 | 0.698997 | cinderblocks |
9bb6ef5eb90e150ed1c7d1a90646c8202a54213e | 14,412 | cpp | C++ | project/src/bytecode_vm/vm.cpp | Jeff-Mott-OR/cpplox | 6b2b771c50fd3d0121283d1f2e54860e1d263bca | [
"MIT"
] | 57 | 2018-04-18T11:06:31.000Z | 2022-01-26T22:15:01.000Z | project/src/bytecode_vm/vm.cpp | Jeff-Mott-OR/cpplox | 6b2b771c50fd3d0121283d1f2e54860e1d263bca | [
"MIT"
] | 24 | 2018-04-20T04:24:39.000Z | 2018-11-13T06:11:37.000Z | project/src/bytecode_vm/vm.cpp | Jeff-Mott-OR/cpplox | 6b2b771c50fd3d0121283d1f2e54860e1d263bca | [
"MIT"
] | 6 | 2018-04-19T03:25:35.000Z | 2020-02-20T03:22:52.000Z | #include "vm.hpp"
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <iostream>
#include <utility>
#include <gsl/gsl_util>
#include "compiler.hpp"
#include "debug.hpp"
using std::chrono::duration_cast;
using std::chrono::seconds;
using std::chrono::system_clock;
using std::cout;
using std::move;
using std::nullptr_t;
using std::string;
using std::to_string;
using std::uint8_t;
using std::uint16_t;
using std::vector;
using boost::apply_visitor;
using boost::bad_get;
using boost::get;
using boost::static_visitor;
using gsl::narrow;
using namespace motts::lox;
namespace {
// Only false and nil are falsey, everything else is truthy
struct Is_truthy_visitor : static_visitor<bool> {
auto operator()(bool value) const {
return value;
}
auto operator()(nullptr_t) const {
return false;
}
template<typename T>
auto operator()(const T&) const {
return true;
}
};
struct Is_equal_visitor : static_visitor<bool> {
// Different types automatically compare false
template<typename T, typename U>
auto operator()(const T&, const U&) const {
return false;
}
// Same types use normal equality test
template<typename T>
auto operator()(const T& lhs, const T& rhs) const {
return lhs == rhs;
}
};
struct Plus_visitor : static_visitor<Value> {
auto operator()(const string& lhs, const string& rhs) const {
return Value{lhs + rhs};
}
auto operator()(double lhs, double rhs) const {
return Value{lhs + rhs};
}
// All other type combinations can't be '+'-ed together
template<typename T, typename U>
Value operator()(const T&, const U&) const {
throw VM_error{"Operands must be two numbers or two strings."};
}
};
struct Call_visitor : static_visitor<void> {
// "Capture" variables, like a lamba but the long-winded way
uint8_t& arg_count;
vector<Call_frame>& frames_;
vector<Value>& stack_;
explicit Call_visitor(
uint8_t& arg_count_capture,
vector<Call_frame>& frames_capture,
vector<Value>& stack_capture
) :
arg_count {arg_count_capture},
frames_ {frames_capture},
stack_ {stack_capture}
{}
auto operator()(const Function* callee) const {
if (arg_count != callee->arity) {
throw VM_error{
"Expected " + to_string(callee->arity) +
" arguments but got " + to_string(arg_count) + ".",
frames_
};
}
frames_.push_back(Call_frame{
*callee,
callee->chunk.code.cbegin(),
stack_.end() - 1 - arg_count
});
}
auto operator()(const Native_fn* callee) const {
auto return_value = callee->fn(stack_.end() - arg_count, stack_.end());
stack_.erase(stack_.end() - 1 - arg_count, stack_.end());
stack_.push_back(return_value);
}
template<typename T>
void operator()(const T&) const {
throw VM_error{"Can only call functions and classes.", frames_};
}
};
auto clock_native(vector<Value>::iterator /*args_begin*/, vector<Value>::iterator /*args_end*/) {
return Value{narrow<double>(duration_cast<seconds>(system_clock::now().time_since_epoch()).count())};
}
string stack_trace(const vector<Call_frame>& frames) {
string trace;
for (auto frame_iter = frames.crbegin(); frame_iter != frames.crend(); ++frame_iter) {
const auto instruction_offset = frame_iter->ip - 1 - frame_iter->function.chunk.code.cbegin();
const auto line = frame_iter->function.chunk.lines.at(instruction_offset);
trace += "[Line " + to_string(line) + "] in " + (
frame_iter->function.name.empty() ?
"script" :
frame_iter->function.name + "()"
) + "\n";
}
return trace;
}
}
namespace motts { namespace lox {
void VM::interpret(const string& source) {
// TODO: Allow dynamically-sized stack but without invalidating iterators.
// Maybe deque? Or offsets instead of iterators? For now just pre-allocate.
stack_.reserve(256);
auto entry_point_function = compile(source);
stack_.push_back(Value{&entry_point_function});
frames_.push_back(Call_frame{
entry_point_function,
entry_point_function.chunk.code.cbegin(),
stack_.begin()
});
globals_["clock"] = Value{new Native_fn{clock_native}};
run();
}
void VM::run() {
for (;;) {
#ifndef NDEBUG
cout << " ";
for (const auto value : stack_) {
cout << "[ ";
print_value(value);
cout << " ]";
}
cout << "\n";
disassemble_instruction(frames_.back().function.chunk, frames_.back().ip - frames_.back().function.chunk.code.cbegin());
#endif
const auto instruction = static_cast<Op_code>(*frames_.back().ip++);
switch (instruction) {
case Op_code::constant: {
const auto constant_offset = *frames_.back().ip++;
const auto constant = frames_.back().function.chunk.constants.at(constant_offset);
stack_.push_back(constant);
break;
}
case Op_code::nil: {
stack_.push_back(Value{nullptr});
break;
}
case Op_code::true_: {
stack_.push_back(Value{true});
break;
}
case Op_code::false_: {
stack_.push_back(Value{false});
break;
}
case Op_code::pop: {
stack_.pop_back();
break;
}
case Op_code::get_local: {
const auto local_offset = *frames_.back().ip++;
stack_.push_back(*(frames_.back().stack_begin + local_offset));
break;
}
case Op_code::set_local: {
const auto local_offset = *frames_.back().ip++;
*(frames_.back().stack_begin + local_offset) = stack_.back();
break;
}
case Op_code::get_global: {
const auto name_offset = *frames_.back().ip++;
const auto name = get<string>(frames_.back().function.chunk.constants.at(name_offset).variant);
const auto found_value = globals_.find(name);
if (found_value == globals_.end()) {
throw VM_error{"Undefined variable '" + name + "'", frames_};
}
stack_.push_back(found_value->second);
break;
}
case Op_code::set_global: {
const auto name_offset = *frames_.back().ip++;
const auto name = get<string>(frames_.back().function.chunk.constants.at(name_offset).variant);
const auto found_value = globals_.find(name);
if (found_value == globals_.end()) {
throw VM_error{"Undefined variable '" + name + "'", frames_};
}
found_value->second = stack_.back();
break;
}
case Op_code::define_global: {
const auto name_offset = *frames_.back().ip++;
const auto name = get<string>(frames_.back().function.chunk.constants.at(name_offset).variant);
globals_[name] = stack_.back();
stack_.pop_back();
break;
}
case Op_code::equal: {
const auto right_value = move(stack_.back());
stack_.pop_back();
const auto left_value = move(stack_.back());
stack_.pop_back();
stack_.push_back(Value{
apply_visitor(Is_equal_visitor{}, left_value.variant, right_value.variant)
});
break;
}
case Op_code::greater: {
const auto right_value = get<double>(stack_.back().variant);
stack_.pop_back();
const auto left_value = get<double>(stack_.back().variant);
stack_.pop_back();
stack_.push_back(Value{left_value > right_value});
break;
}
case Op_code::less: {
const auto right_value = get<double>(stack_.back().variant);
stack_.pop_back();
const auto left_value = get<double>(stack_.back().variant);
stack_.pop_back();
stack_.push_back(Value{left_value < right_value});
break;
}
case Op_code::add: {
const auto right_value = move(stack_.back());
stack_.pop_back();
const auto left_value = move(stack_.back());
stack_.pop_back();
stack_.push_back(apply_visitor(Plus_visitor{}, left_value.variant, right_value.variant));
break;
}
case Op_code::subtract: {
const auto right_value = get<double>(stack_.back().variant);
stack_.pop_back();
const auto left_value = get<double>(stack_.back().variant);
stack_.pop_back();
stack_.push_back(Value{left_value - right_value});
break;
}
case Op_code::multiply: {
const auto right_value = get<double>(stack_.back().variant);
stack_.pop_back();
const auto left_value = get<double>(stack_.back().variant);
stack_.pop_back();
stack_.push_back(Value{left_value * right_value});
break;
}
case Op_code::divide: {
const auto right_value = get<double>(stack_.back().variant);
stack_.pop_back();
const auto left_value = get<double>(stack_.back().variant);
stack_.pop_back();
stack_.push_back(Value{left_value / right_value});
break;
}
case Op_code::not_: {
const auto value = apply_visitor(Is_truthy_visitor{}, stack_.back().variant);
stack_.pop_back();
stack_.push_back(Value{!value});
break;
}
case Op_code::negate: {
// TODO Convert error: "Operand must be a number."
const auto value = get<double>(stack_.back().variant);
stack_.pop_back();
stack_.push_back(Value{-value});
break;
}
case Op_code::print: {
print_value(stack_.back());
cout << "\n";
stack_.pop_back();
break;
}
case Op_code::jump: {
// DANGER! Reinterpret cast: The two bytes following a jump_if_false instruction
// are supposed to represent a single uint16 number
const auto jump_length = reinterpret_cast<const uint16_t&>(*(frames_.back().ip));
frames_.back().ip += 2;
frames_.back().ip += jump_length;
break;
}
case Op_code::jump_if_false: {
// DANGER! Reinterpret cast: The two bytes following a jump_if_false instruction
// are supposed to represent a single uint16 number
const auto jump_length = reinterpret_cast<const uint16_t&>(*(frames_.back().ip));
frames_.back().ip += 2;
if (!apply_visitor(Is_truthy_visitor{}, stack_.back().variant)) {
frames_.back().ip += jump_length;
}
break;
}
case Op_code::loop: {
// DANGER! Reinterpret cast: The two bytes following a loop instruction
// are supposed to represent a single uint16 number
const auto jump_length = reinterpret_cast<const uint16_t&>(*(frames_.back().ip));
frames_.back().ip -= 1;
frames_.back().ip -= jump_length;
break;
}
case Op_code::call: {
auto arg_count = *frames_.back().ip++;
Call_visitor call_visitor {arg_count, frames_, stack_};
apply_visitor(call_visitor, (stack_.end() - 1 - arg_count)->variant);
break;
}
case Op_code::return_: {
const auto return_value = stack_.back();
stack_.erase(frames_.back().stack_begin, stack_.end());
frames_.pop_back();
if (frames_.empty()) {
return;
}
stack_.push_back(return_value);
break;
}
}
}
}
VM_error::VM_error(const string& what, const vector<Call_frame>& frames) :
VM_error{what + "\n" + stack_trace(frames)}
{}
}}
| 33.594406 | 136 | 0.490425 | Jeff-Mott-OR |
9bb8bc9b7e857f3e82af6939d8ca22a11a54b4d9 | 2,147 | hpp | C++ | search.hpp | dasapon/cappuccino | e198a495d8061b01ab34eb202415db2b28bce619 | [
"MIT"
] | 2 | 2018-02-14T15:10:41.000Z | 2018-02-19T23:46:45.000Z | search.hpp | dasapon/cappuccino | e198a495d8061b01ab34eb202415db2b28bce619 | [
"MIT"
] | null | null | null | search.hpp | dasapon/cappuccino | e198a495d8061b01ab34eb202415db2b28bce619 | [
"MIT"
] | null | null | null | #pragma once
#include "position.hpp"
#include "state.hpp"
#include "hash_table.hpp"
#include "time.hpp"
constexpr int max_ply = 128;
using PV = sheena::Array<Move, max_ply>;
enum {
RPSDepth = 4 * depth_scale,
};
class KillerMove : public sheena::Array<Move, 2>{
public:
void update(Move m){
if((*this)[0] != m){
(*this)[1] = (*this)[0];
(*this)[0] = m;
}
}
void clear(){
(*this)[1] = (*this)[0] = NullMove;
}
};
class MoveOrdering{
enum Status{
Hash,
Important,
All,
};
Status status;
int n_moves;
int idx;
sheena::Array<Move, MaxLegalMove> moves;
sheena::Array<float, MaxLegalMove> scores;
const State& state;
Move hash_move;
KillerMove killer;
bool do_fp;
void insertion_sort(int start, int end);
public:
MoveOrdering(const State& state, Move hash_move, const KillerMove& killer, bool rps, bool do_fp);
MoveOrdering(const State& state, Move hash_move);
Move next(float* score);
};
class Searcher{
int search(State& state, int alpha, int beta, int depth, int ply);
int qsearch(State& state, int alpha, int beta, int depth, int ply);
int search_w(State& state, int alpha, int beta, int depth, int ply);
std::thread main_thread, timer_thread;
uint64_t nodes;
HashTable hash_table;
PV pv_table[max_ply];
KillerMove killer[max_ply + 2];
int think_with_timer(State& state, int max_depth, bool print);
int think(State& state, int max_depth, PV& pv, bool print, bool wait_timer_stopping);
public:
~Searcher(){
if(main_thread.joinable())main_thread.join();
}
Searcher(){}
void go(State& state, uint64_t time, uint64_t inc, bool ponder_or_infinite);
int think(State& state, int max_depth, PV& pv, bool print);
int think(State& state, int max_depth, bool print);
void hash_size(size_t mb){hash_table.set_size(mb);}
uint64_t node_searched()const{return nodes;}
//time control
private:
volatile bool abort;
volatile bool inf;
Timer search_start;
void timer_start(uint64_t, uint64_t, bool);
public:
void ponder_hit(){
inf = false;
}
void stop(){
inf = false;
abort = true;
if(main_thread.joinable())main_thread.join();
if(timer_thread.joinable())timer_thread.join();
}
};
| 23.855556 | 98 | 0.704704 | dasapon |
9bbc054ea09ab3a7ff30d0248cdf6e577f52a1f9 | 15,964 | hpp | C++ | examples/example_utils.hpp | ROCmMathLibrariesBot/hipCUB | 003a5b2b791dc01e88d0c0caaaf1de9ae53ad638 | [
"BSD-3-Clause"
] | 36 | 2019-05-14T09:27:57.000Z | 2022-03-03T09:19:11.000Z | examples/example_utils.hpp | ROCmMathLibrariesBot/hipCUB | 003a5b2b791dc01e88d0c0caaaf1de9ae53ad638 | [
"BSD-3-Clause"
] | 70 | 2019-05-06T23:07:53.000Z | 2022-03-17T08:24:22.000Z | examples/example_utils.hpp | ROCmMathLibrariesBot/hipCUB | 003a5b2b791dc01e88d0c0caaaf1de9ae53ad638 | [
"BSD-3-Clause"
] | 25 | 2019-05-03T19:45:13.000Z | 2022-03-31T08:14:38.000Z | #ifndef EXAMPLES_EXAMPLE_UTILS_HPP
#define EXAMPLES_EXAMPLE_UTILS_HPP
#include "mersenne.h"
#include <vector>
#include <sstream>
#include <iostream>
#include <hipcub/util_type.hpp>
#include <hipcub/util_allocator.hpp>
#include <hipcub/iterator/discard_output_iterator.hpp>
#define AssertEquals(a, b) if ((a) != (b)) { std::cerr << "\n(" << __FILE__ << ": " << __LINE__ << ")\n"; exit(1);}
template <typename T>
T CoutCast(T val) { return val; }
int CoutCast(char val) { return val; }
int CoutCast(unsigned char val) { return val; }
int CoutCast(signed char val) { return val; }
/******************************************************************************
* Command-line parsing functionality
******************************************************************************/
/**
* Utility for parsing command line arguments
*/
struct CommandLineArgs
{
std::vector<std::string> keys;
std::vector<std::string> values;
std::vector<std::string> args;
hipDeviceProp_t deviceProp;
float device_giga_bandwidth;
std::size_t device_free_physmem;
std::size_t device_total_physmem;
/**
* Constructor
*/
CommandLineArgs(int argc, char **argv) :
keys(10),
values(10)
{
using namespace std;
// Initialize mersenne generator
unsigned int mersenne_init[4]= {0x123, 0x234, 0x345, 0x456};
mersenne::init_by_array(mersenne_init, 4);
for (int i = 1; i < argc; i++)
{
string arg = argv[i];
if ((arg[0] != '-') || (arg[1] != '-'))
{
args.push_back(arg);
continue;
}
string::size_type pos;
string key, val;
if ((pos = arg.find('=')) == string::npos) {
key = string(arg, 2, arg.length() - 2);
val = "";
} else {
key = string(arg, 2, pos - 2);
val = string(arg, pos + 1, arg.length() - 1);
}
keys.push_back(key);
values.push_back(val);
}
}
/**
* Checks whether a flag "--<flag>" is present in the commandline
*/
bool CheckCmdLineFlag(const char* arg_name)
{
using namespace std;
for (std::size_t i = 0; i < keys.size(); ++i)
{
if (keys[i] == string(arg_name))
return true;
}
return false;
}
/**
* Returns number of naked (non-flag and non-key-value) commandline parameters
*/
template <typename T>
int NumNakedArgs()
{
return args.size();
}
/**
* Returns the commandline parameter for a given index (not including flags)
*/
template <typename T>
void GetCmdLineArgument(std::size_t index, T &val)
{
using namespace std;
if (index < args.size()) {
std::istringstream str_stream(args[index]);
str_stream >> val;
}
}
/**
* Returns the value specified for a given commandline parameter --<flag>=<value>
*/
template <typename T>
void GetCmdLineArgument(const char *arg_name, T &val)
{
using namespace std;
for (std::size_t i = 0; i < keys.size(); ++i)
{
if (keys[i] == string(arg_name))
{
std::istringstream str_stream(values[i]);
str_stream >> val;
}
}
}
/**
* Returns the values specified for a given commandline parameter --<flag>=<value>,<value>*
*/
template <typename T>
void GetCmdLineArguments(const char *arg_name, std::vector<T> &vals)
{
using namespace std;
if (CheckCmdLineFlag(arg_name))
{
// Clear any default values
vals.clear();
// Recover from multi-value string
for (std::size_t i = 0; i < keys.size(); ++i)
{
if (keys[i] == string(arg_name))
{
string val_string(values[i]);
std::istringstream str_stream(val_string);
string::size_type old_pos = 0;
string::size_type new_pos = 0;
// Iterate comma-separated values
T val;
while ((new_pos = val_string.find(',', old_pos)) != string::npos)
{
if (new_pos != old_pos)
{
str_stream.width(new_pos - old_pos);
str_stream >> val;
vals.push_back(val);
}
// skip over comma
str_stream.ignore(1);
old_pos = new_pos + 1;
}
// Read last value
str_stream >> val;
vals.push_back(val);
}
}
}
}
/**
* The number of pairs parsed
*/
int ParsedArgc()
{
return (int) keys.size();
}
/**
* Initialize device
*/
hipError_t DeviceInit(int dev = -1)
{
hipError_t error = hipSuccess;
do
{
int deviceCount;
error = hipGetDeviceCount(&deviceCount);
if (error) break;
if (deviceCount == 0) {
fprintf(stderr, "No devices supporting CUDA.\n");
exit(1);
}
if (dev < 0)
{
GetCmdLineArgument("device", dev);
}
if ((dev > deviceCount - 1) || (dev < 0))
{
dev = 0;
}
error = hipSetDevice(dev);
if (error) break;
hipMemGetInfo(&device_free_physmem, &device_total_physmem);
// int ptx_version = 0;
// error = hipcub::PtxVersion(ptx_version);
// if (error) break;
error = hipGetDeviceProperties(&deviceProp, dev);
if (error) break;
if (deviceProp.major < 1) {
fprintf(stderr, "Device does not support Hip.\n");
exit(1);
}
device_giga_bandwidth = float(deviceProp.memoryBusWidth) * deviceProp.memoryClockRate * 2 / 8 / 1000 / 1000;
if (!CheckCmdLineFlag("quiet"))
{
printf(
"Using device %d: %s ( SM%d, %d SMs, "
"%lld free / %lld total MB physmem, "
"%.3f GB/s @ %d kHz mem clock, ECC %s)\n",
dev,
deviceProp.name,
deviceProp.major * 100 + deviceProp.minor * 10,
deviceProp.multiProcessorCount,
(unsigned long long) device_free_physmem / 1024 / 1024,
(unsigned long long) device_total_physmem / 1024 / 1024,
device_giga_bandwidth,
deviceProp.memoryClockRate,
(deviceProp.ECCEnabled) ? "on" : "off");
fflush(stdout);
}
} while (0);
return error;
}
};
/******************************************************************************
* Helper routines for list comparison and display
******************************************************************************/
/**
* Compares the equivalence of two arrays
*/
template <typename S, typename T, typename OffsetT>
int CompareResults(T* computed, S* reference, OffsetT len, bool verbose = true)
{
for (OffsetT i = 0; i < len; i++)
{
if (computed[i] != reference[i])
{
if (verbose) std::cout << "INCORRECT: [" << i << "]: "
<< CoutCast(computed[i]) << " != "
<< CoutCast(reference[i]);
return 1;
}
}
return 0;
}
/**
* Compares the equivalence of two arrays
*/
template <typename OffsetT>
int CompareResults(float* computed, float* reference, OffsetT len, bool verbose = true)
{
for (OffsetT i = 0; i < len; i++)
{
if (computed[i] != reference[i])
{
float difference = std::abs(computed[i]-reference[i]);
float fraction = difference / std::abs(reference[i]);
if (fraction > 0.0001)
{
if (verbose) std::cout << "INCORRECT: [" << i << "]: "
<< "(computed) " << CoutCast(computed[i]) << " != "
<< CoutCast(reference[i]) << " (difference:" << difference << ", fraction: " << fraction << ")";
return 1;
}
}
}
return 0;
}
/**
* Compares the equivalence of two arrays
*/
// template <typename OffsetT>
// int CompareResults(hipcub::NullType* computed, hipcub::NullType* reference, OffsetT len, bool verbose = true)
// {
// return 0;
// }
/**
* Compares the equivalence of two arrays
*/
template <typename OffsetT>
int CompareResults(double* computed, double* reference, OffsetT len, bool verbose = true)
{
for (OffsetT i = 0; i < len; i++)
{
if (computed[i] != reference[i])
{
double difference = std::abs(computed[i]-reference[i]);
double fraction = difference / std::abs(reference[i]);
if (fraction > 0.0001)
{
if (verbose) std::cout << "INCORRECT: [" << i << "]: "
<< CoutCast(computed[i]) << " != "
<< CoutCast(reference[i]) << " (difference:" << difference << ", fraction: " << fraction << ")";
return 1;
}
}
}
return 0;
}
// /**
// * Verify the contents of a device array match those
// * of a host array
// */
// int CompareDeviceResults(
// hipcub::NullType */* h_reference */,
// hipcub::NullType */* d_data */,
// std::size_t /* num_items */,
// bool /* verbose */ = true,
// bool /* display_data */ = false)
// {
// return 0;
// }
/**
* Verify the contents of a device array match those
* of a host array
*/
// template <typename S, typename OffsetT>
// int CompareDeviceResults(
// S *h_reference,
// hipcub::DiscardOutputIterator<OffsetT> d_data,
// std::size_t num_items,
// bool verbose = true,
// bool display_data = false)
// {
// return 0;
// }
/**
* Verify the contents of a device array match those
* of a host array
*/
template <typename S, typename T>
int CompareDeviceResults(
S *h_reference,
T *d_data,
std::size_t num_items,
bool verbose = true,
bool display_data = false)
{
// Allocate array on host
T *h_data = (T*) malloc(num_items * sizeof(T));
// Copy data back
hipMemcpy(h_data, d_data, sizeof(T) * num_items, hipMemcpyDeviceToHost);
// Display data
if (display_data)
{
printf("Reference:\n");
for (std::size_t i = 0; i < num_items; i++)
{
std::cout << CoutCast(h_reference[i]) << ", ";
}
printf("\n\nComputed:\n");
for (std::size_t i = 0; i < num_items; i++)
{
std::cout << CoutCast(h_data[i]) << ", ";
}
printf("\n\n");
}
// Check
int retval = CompareResults(h_data, h_reference, num_items, verbose);
// Cleanup
if (h_data) free(h_data);
return retval;
}
/**
* Verify the contents of a device array match those
* of a device array
*/
template <typename T>
int CompareDeviceDeviceResults(
T *d_reference,
T *d_data,
std::size_t num_items,
bool verbose = true,
bool display_data = false)
{
// Allocate array on host
T *h_reference = (T*) malloc(num_items * sizeof(T));
T *h_data = (T*) malloc(num_items * sizeof(T));
// Copy data back
hipMemcpy(h_reference, d_reference, sizeof(T) * num_items, hipMemcpyDeviceToHost);
hipMemcpy(h_data, d_data, sizeof(T) * num_items, hipMemcpyDeviceToHost);
// Display data
if (display_data) {
printf("Reference:\n");
for (std::size_t i = 0; i < num_items; i++)
{
std::cout << CoutCast(h_reference[i]) << ", ";
}
printf("\n\nComputed:\n");
for (std::size_t i = 0; i < num_items; i++)
{
std::cout << CoutCast(h_data[i]) << ", ";
}
printf("\n\n");
}
// Check
int retval = CompareResults(h_data, h_reference, num_items, verbose);
// Cleanup
if (h_reference) free(h_reference);
if (h_data) free(h_data);
return retval;
}
/**
* Print the contents of a host array
*/
template <typename InputIteratorT>
void DisplayResults(
InputIteratorT h_data,
std::size_t num_items)
{
// Display data
for (std::size_t i = 0; i < num_items; i++)
{
std::cout << CoutCast(h_data[i]) << ", ";
}
printf("\n");
}
int g_num_rand_samples = 0;
/**
* Generates random keys.
*
* We always take the second-order byte from rand() because the higher-order
* bits returned by rand() are commonly considered more uniformly distributed
* than the lower-order bits.
*
* We can decrease the entropy level of keys by adopting the technique
* of Thearling and Smith in which keys are computed from the bitwise AND of
* multiple random samples:
*
* entropy_reduction | Effectively-unique bits per key
* -----------------------------------------------------
* -1 | 0
* 0 | 32
* 1 | 25.95 (81%)
* 2 | 17.41 (54%)
* 3 | 10.78 (34%)
* 4 | 6.42 (20%)
* ... | ...
*
*/
template <typename K>
void RandomBits(
K &key,
int entropy_reduction = 0,
int begin_bit = 0,
int end_bit = sizeof(K) * 8)
{
const int NUM_BYTES = sizeof(K);
const int WORD_BYTES = sizeof(unsigned int);
const int NUM_WORDS = (NUM_BYTES + WORD_BYTES - 1) / WORD_BYTES;
unsigned int word_buff[NUM_WORDS];
if (entropy_reduction == -1)
{
memset((void *) &key, 0, sizeof(key));
return;
}
if (end_bit < 0)
end_bit = sizeof(K) * 8;
while (true)
{
// Generate random word_buff
for (int j = 0; j < NUM_WORDS; j++)
{
int current_bit = j * WORD_BYTES * 8;
unsigned int word = 0xffffffff;
word &= 0xffffffff << std::max(0, begin_bit - current_bit);
word &= 0xffffffff >> std::max(0, (current_bit + (WORD_BYTES * 8)) - end_bit);
for (int i = 0; i <= entropy_reduction; i++)
{
// Grab some of the higher bits from rand (better entropy, supposedly)
word &= mersenne::genrand_int32();
g_num_rand_samples++;
}
word_buff[j] = word;
}
memcpy(&key, word_buff, sizeof(K));
K copy = key;
if (!std::isnan(copy))
break; // avoids NaNs when generating random floating point numbers
}
}
/// Randomly select number between [0:max)
template <typename T>
T RandomValue(T max)
{
unsigned int bits;
unsigned int max_int = (unsigned int) -1;
do {
RandomBits(bits);
} while (bits == max_int);
return (T) ((double(bits) / double(max_int)) * double(max));
}
struct GpuTimer
{
hipEvent_t start;
hipEvent_t stop;
GpuTimer()
{
hipEventCreate(&start);
hipEventCreate(&stop);
}
~GpuTimer()
{
hipEventDestroy(start);
hipEventDestroy(stop);
}
void Start()
{
hipEventRecord(start, 0);
}
void Stop()
{
hipEventRecord(stop, 0);
}
float ElapsedMillis()
{
float elapsed;
hipEventSynchronize(stop);
hipEventElapsedTime(&elapsed, start, stop);
return elapsed;
}
};
#endif
| 26.343234 | 120 | 0.502255 | ROCmMathLibrariesBot |
9bbf252752ae1ef4d98f83d5c6ede747e24e2b01 | 164 | cpp | C++ | code/random-stuff/dzien-probny/test.cpp | tonowak/acmlib | ec295b8c76c588914475ad42cff81a64a6f2ebd5 | [
"MIT"
] | 6 | 2019-06-25T14:07:08.000Z | 2022-01-04T12:28:55.000Z | code/random-stuff/dzien-probny/test.cpp | tonowak/acmlib | ec295b8c76c588914475ad42cff81a64a6f2ebd5 | [
"MIT"
] | null | null | null | code/random-stuff/dzien-probny/test.cpp | tonowak/acmlib | ec295b8c76c588914475ad42cff81a64a6f2ebd5 | [
"MIT"
] | 1 | 2021-11-12T01:40:38.000Z | 2021-11-12T01:40:38.000Z | #include "../../utils/testing/test-wrapper.cpp"
#include "main.cpp"
void test() {
test_int128();
//test_float128();
test_clock();
test_rd();
test_policy();
}
| 14.909091 | 47 | 0.652439 | tonowak |
9bc25f05c0413407d9bdc1438266b84d865d8b20 | 3,588 | cpp | C++ | tests/src/surface.cpp | viennagrid/viennagrid-dev | 6e47c8d098a0b691d6b9988f2444cd11d440f4c2 | [
"MIT"
] | 7 | 2015-09-13T03:50:58.000Z | 2019-06-27T14:24:49.000Z | tests/src/surface.cpp | viennagrid/viennagrid-dev | 6e47c8d098a0b691d6b9988f2444cd11d440f4c2 | [
"MIT"
] | null | null | null | tests/src/surface.cpp | viennagrid/viennagrid-dev | 6e47c8d098a0b691d6b9988f2444cd11d440f4c2 | [
"MIT"
] | 5 | 2015-07-03T07:14:15.000Z | 2021-05-20T00:51:58.000Z | /* =======================================================================
Copyright (c) 2011-2014, Institute for Microelectronics,
Institute for Analysis and Scientific Computing,
TU Wien.
-----------------
ViennaGrid - The Vienna Grid Library
-----------------
License: MIT (X11), see file LICENSE in the base directory
======================================================================= */
#ifdef _MSC_VER
#pragma warning( disable : 4503 ) //truncated name decoration
#endif
#include "viennagrid/algorithm/boundary.hpp"
#include "viennagrid/algorithm/centroid.hpp"
#include "viennagrid/config/default_configs.hpp"
#include "viennagrid/io/vtk_reader.hpp"
#include "viennagrid/io/vtk_writer.hpp"
#include "viennagrid/io/opendx_writer.hpp"
#include "viennagrid/io/netgen_reader.hpp"
#include "viennagrid/algorithm/volume.hpp"
#include "viennagrid/algorithm/surface.hpp"
template <typename MeshType, typename ReaderType>
void test(ReaderType & my_reader, std::string const & infile)
{
typedef typename viennagrid::result_of::segmentation<MeshType>::type SegmentationType;
typedef typename viennagrid::result_of::cell_range<MeshType>::type CellRange;
typedef typename viennagrid::result_of::iterator<CellRange>::type CellIterator;
MeshType mesh;
SegmentationType segmentation(mesh);
try
{
my_reader(mesh, segmentation, infile);
}
catch (std::exception const & ex)
{
std::cerr << ex.what() << std::endl;
std::cerr << "File-Reader failed. Aborting program..." << std::endl;
exit(EXIT_FAILURE);
}
std::cout << "Volume of mesh: " << viennagrid::volume(mesh) << std::endl;
std::cout << "Surface of mesh: " << viennagrid::surface(mesh) << std::endl;
CellRange cells(mesh);
for (CellIterator cit = cells.begin();
cit != cells.end();
++cit)
{
//std::cout << *cit << std::endl;
std::cout << "Surface: " << viennagrid::surface(*cit) << std::endl;
}
}
int main()
{
// typedef viennagrid::result_of::mesh<viennagrid::config::quadrilateral_2d>::type Mesh2d;
// typedef viennagrid::result_of::mesh<viennagrid::config::hexahedral_3d>::type Mesh3d;
std::cout << "*****************" << std::endl;
std::cout << "* Test started! *" << std::endl;
std::cout << "*****************" << std::endl;
std::string path = "../examples/data/";
viennagrid::io::netgen_reader my_netgen_reader;
std::cout << "*********** triangular, 2d ***********" << std::endl;
test<viennagrid::triangular_2d_mesh>(my_netgen_reader, path + "square32.mesh");
std::cout << "*********** tetrahedral, 3d ***********" << std::endl;
test<viennagrid::tetrahedral_3d_mesh>(my_netgen_reader, path + "cube48.mesh");
std::cout << "*********** quadrilateral, 2d ***********" << std::endl;
viennagrid::io::vtk_reader<viennagrid::quadrilateral_2d_mesh> vtk_reader_2d;
test<viennagrid::quadrilateral_2d_mesh>(vtk_reader_2d, path + "quadrilateral2.vtu");
std::cout << "*********** hexahedral, 3d ***********" << std::endl;
viennagrid::io::vtk_reader<viennagrid::hexahedral_3d_mesh> vtk_reader_3d;
test<viennagrid::hexahedral_3d_mesh
>(vtk_reader_3d, path + "hexahedron2.vtu");
std::cout << "*******************************" << std::endl;
std::cout << "* Test finished successfully! *" << std::endl;
std::cout << "*******************************" << std::endl;
return EXIT_SUCCESS;
}
| 35.88 | 99 | 0.582776 | viennagrid |
9be2a8fc174178052e2e78a680976dde0f7f33f4 | 2,556 | cpp | C++ | project2D/GameStateManager.cpp | PancakesMan/GameStateProject | 09a2587d96759768f04c521585b90bd961ef1758 | [
"MIT"
] | null | null | null | project2D/GameStateManager.cpp | PancakesMan/GameStateProject | 09a2587d96759768f04c521585b90bd961ef1758 | [
"MIT"
] | null | null | null | project2D/GameStateManager.cpp | PancakesMan/GameStateProject | 09a2587d96759768f04c521585b90bd961ef1758 | [
"MIT"
] | null | null | null | #pragma once
#include "GameStateManager.h"
#include "IGameState.h"
#include <assert.h>
GameStateManager::GameStateManager()
{
}
GameStateManager::~GameStateManager()
{
for (auto iter = m_registeredStates.begin(); iter != m_registeredStates.end(); iter++)
delete iter->value;
m_registeredStates.clear();
}
void GameStateManager::updateStates(float deltaTime)
{
processCommands();
(*m_activeStates.top()).update(deltaTime);
//for (auto iter = m_activeStates.begin(); iter != m_activeStates.end(); iter++)
//(*iter)->update(deltaTime);
}
void GameStateManager::renderStates(aie::Renderer2D * renderer)
{
//(*m_activeStates.rbegin())->render(renderer);
for (auto iter = m_activeStates.begin(); iter != m_activeStates.end(); iter++)
(*iter)->render(renderer);
}
void GameStateManager::setState(int id, IGameState * state)
{
Command command;
command.cmd = eCommand::SET;
command.id = id;
command.state = state;
m_commands.AddToEnd(command);
}
void GameStateManager::pushState(int id)
{
Command command;
command.cmd = eCommand::PUSH;
command.id = id;
command.state = nullptr;
m_commands.AddToEnd(command);
}
void GameStateManager::popState()
{
Command command;
command.cmd = eCommand::POP;
command.id = -1;
command.state = nullptr;
m_commands.AddToEnd(command);
}
IGameState* GameStateManager::getTopState()
{
if (m_activeStates.count() > 0)
return m_activeStates.top();
return nullptr;
}
void GameStateManager::processCommands()
{
for (auto iter = m_commands.begin(); iter != m_commands.end(); iter++)
{
Command &c = (*iter);
switch (c.cmd)
{
case eCommand::POP:
processPopState();
break;
case eCommand::PUSH:
processPushState(c.id);
break;
case eCommand::SET:
processSetState(c.id, c.state);
break;
default:
assert(false && "Command not found!");
break;
}
}
m_commands.Clear();
}
void GameStateManager::processSetState(int id, IGameState * state)
{
//auto iter = m_registeredStates.find(id);
if (m_registeredStates.find(id) != -1)
m_registeredStates.remove(id); // Delete the state if it already exists
// Replace it with the new state
m_registeredStates[id] = state;
}
void GameStateManager::processPushState(int id)
{
auto iter = m_registeredStates.find(id);
if (iter != -1)
m_activeStates.push(m_registeredStates[id]); // If the state exists, add it to the list of active states
else
assert((int)id && "State not found!"); // if not, crash
}
void GameStateManager::processPopState()
{
if (m_activeStates.count() > 0)
m_activeStates.pop();
}
| 21.478992 | 106 | 0.704617 | PancakesMan |
9bea79b4d6457b629dcc50a10d23dd97ac76bd3e | 5,418 | hh | C++ | include/threadmap.hh | GYJQTYL2/DoubleTake | cdcd0200bb364b5343beae72756420e6c3954a6f | [
"MIT"
] | 19 | 2015-09-17T18:10:14.000Z | 2021-08-16T11:26:33.000Z | include/threadmap.hh | GYJQTYL2/DoubleTake | cdcd0200bb364b5343beae72756420e6c3954a6f | [
"MIT"
] | 17 | 2015-04-27T14:33:42.000Z | 2016-05-23T20:15:48.000Z | include/threadmap.hh | plasma-umass/DoubleTake | cdcd0200bb364b5343beae72756420e6c3954a6f | [
"MIT"
] | 13 | 2015-07-29T15:15:00.000Z | 2021-01-15T04:53:21.000Z | #if !defined(DOUBLETAKE_THREADMAP_H)
#define DOUBLETAKE_THREADMAP_H
/*
* @file threadmap.h
* @brief Mapping between pthread_t and internal thread information.
* @author Tongping Liu <http://www.cs.umass.edu/~tonyliu>
*/
#include <assert.h>
#include <pthread.h>
#include <stdint.h>
#include <stdlib.h>
#include <new>
#include "hashfuncs.hh"
#include "hashmap.hh"
#include "internalheap.hh"
#include "list.hh"
#include "log.hh"
#include "mm.hh"
#include "recordentries.hh"
#include "semaphore.hh"
#include "spinlock.hh"
#include "threadstruct.hh"
#include "xdefines.hh"
class threadmap {
public:
threadmap() {}
static threadmap& getInstance() {
static char buf[sizeof(threadmap)];
static threadmap* theOneTrueObject = new (buf) threadmap();
return *theOneTrueObject;
}
void initialize() {
// PRINF("xmap initializeNNNNNNNNNNNNNN\n");
_xmap.initialize(HashFuncs::hashAddr, HashFuncs::compareAddr, xdefines::THREAD_MAP_SIZE);
listInit(&_alivethreads);
}
thread_t* getThreadInfo(pthread_t thread) {
thread_t* info = NULL;
_xmap.find((void*)thread, sizeof(void*), &info);
if(info == NULL) {
PRINF("Can't find thread_t for thread %lx. Exit now!!\n", thread);
abort();
}
return info;
}
void deleteThreadMap(pthread_t thread) { _xmap.erase((void*)thread, sizeof(void*)); }
void insertAliveThread(thread_t* thread, pthread_t tid) {
// Malloc
struct aliveThread* ath =
(struct aliveThread*)InternalHeap::getInstance().malloc(sizeof(struct aliveThread));
assert(ath != NULL);
listInit(&ath->list);
ath->thread = thread;
PRINF("Insert alive thread %p\n", (void *)thread);
listInsertTail(&ath->list, &_alivethreads);
_xmap.insert((void*)tid, sizeof(void*), thread);
}
void removeAliveThread(thread_t* thread) {
// First, remove thread from the threadmap.
deleteThreadMap(thread->self);
// Second, remove thread from the alive list.
struct aliveThread* ath;
// Now the _alivethreads list should not be empty.
assert(isListEmpty(&_alivethreads) != true);
// Search the whole list for given tid.
ath = (struct aliveThread*)nextEntry(&_alivethreads);
while(true) {
PRINF("Traverse thread %p\n", (void *)ath->thread);
// If we found the entry, remove this entry from the list.
if(ath->thread == thread) {
listRemoveNode(&ath->list);
break;
}
// It is impossible that we haven't find the node until the end of a list.
if(isListTail(&ath->list, &_alivethreads) == true) {
PRWRN("WRong, we can't find alive thread %p in the list.", (void *)thread);
abort();
}
ath = (struct aliveThread*)nextEntry(&ath->list);
}
InternalHeap::getInstance().free((void*)ath);
// Setting a thread structure to be "Free" status.
setFreeThread(thread);
}
// Set a threadInfo structure to be free.
void setFreeThread(thread_t* thread) { thread->available = true; }
// How to return a thread event from specified entry.
inline struct syncEvent* getThreadEvent(list_t* entry) {
// FIXME: if we changed the structure of syncEvent.
int threadEventOffset = sizeof(list_t);
return (struct syncEvent*)((intptr_t)entry - threadEventOffset);
}
public:
class aliveThreadIterator {
struct aliveThread* thread;
public:
aliveThreadIterator(struct aliveThread* ithread = NULL) { thread = ithread; }
~aliveThreadIterator() {}
aliveThreadIterator& operator++(int) // in postfix ++
{
if(!isListTail(&thread->list, &_alivethreads)) {
thread = (struct aliveThread*)nextEntry(&thread->list);
} else {
thread = NULL;
}
return *this;
}
// aliveThreadIterator& operator -- ();
// Iterpreted as a = b is treated as a.operator=(b)
aliveThreadIterator& operator=(const aliveThreadIterator& that) {
thread = that.thread;
return *this;
}
bool operator==(const aliveThreadIterator& that) const { return thread == that.thread; }
bool operator!=(const aliveThreadIterator& that) const { return thread != that.thread; }
thread_t* getThread() { return thread->thread; }
};
void traverseAllThreads() {
struct aliveThread* ath;
// Search the whole list for given tid.
ath = (struct aliveThread*)nextEntry(&_alivethreads);
while(true) {
thread_t* thread = ath->thread;
if(thread->status != E_THREAD_WAITFOR_REAPING) {
PRINF("thread %p self %p status %d\n", (void *)thread, (void*)thread->self, thread->status);
}
// Update to the next thread.
if(isListTail(&ath->list, &_alivethreads)) {
break;
} else {
ath = (struct aliveThread*)nextEntry(&ath->list);
}
}
}
// Acquire the first entry of the hash table
aliveThreadIterator begin() {
// Get the first non-null entry
if(isListEmpty(&_alivethreads) != true) {
return aliveThreadIterator((struct aliveThread*)nextEntry(&_alivethreads));
} else {
return end();
}
}
aliveThreadIterator end() { return aliveThreadIterator(NULL); }
private:
// We are maintainning a private hash map for each thread.
typedef HashMap<void*, thread_t*, spinlock, InternalHeapAllocator> threadHashMap;
// The variables map shared by all threads
threadHashMap _xmap;
static list_t _alivethreads;
};
#endif
| 27.226131 | 100 | 0.66076 | GYJQTYL2 |
9bf043771fc2395d6f34fef93afb03bac9e92ee6 | 193 | hpp | C++ | samples/chalet/app.hpp | YiJiangFengYun/vulkan-graphics-examples | e7b788b8f47dd238b08840c019940c7c52335a54 | [
"MIT"
] | 1 | 2018-03-01T01:05:25.000Z | 2018-03-01T01:05:25.000Z | samples/chalet/app.hpp | YiJiangFengYun/vulkan-graphics-examples | e7b788b8f47dd238b08840c019940c7c52335a54 | [
"MIT"
] | null | null | null | samples/chalet/app.hpp | YiJiangFengYun/vulkan-graphics-examples | e7b788b8f47dd238b08840c019940c7c52335a54 | [
"MIT"
] | null | null | null | #ifndef APP_H
#define APP_H
#include "sampleslib/app.hpp"
namespace chalet
{
class App : public sampleslib::App
{
public:
App();
private:
};
}
#endif // !APP_H
| 10.157895 | 38 | 0.585492 | YiJiangFengYun |
9bf410394e8999d85ded440780dd5e1122aa13e2 | 659 | cpp | C++ | laboratorios/lab_04/02_funcao_seno.cpp | sueyvid/Atividade_de_programacao_cpp | 691941fc94125eddd4e5466862d5a1fe04dfb520 | [
"MIT"
] | null | null | null | laboratorios/lab_04/02_funcao_seno.cpp | sueyvid/Atividade_de_programacao_cpp | 691941fc94125eddd4e5466862d5a1fe04dfb520 | [
"MIT"
] | null | null | null | laboratorios/lab_04/02_funcao_seno.cpp | sueyvid/Atividade_de_programacao_cpp | 691941fc94125eddd4e5466862d5a1fe04dfb520 | [
"MIT"
] | null | null | null | #include <iostream>
#include <cmath>
using namespace std;
float qual_seno_do_angulo(float x, int n);
int qual_o_fatorial(int y);
int main()
{
float alfa;
int num_termos;
cin >> alfa >> num_termos;
cout << qual_seno_do_angulo(alfa, num_termos);
return 0;
}
int qual_o_fatorial(int y){
int j, r = 0;
for(j = 1; j < y; j++){
r = j*(j+1);
}
return r;
}
float qual_seno_do_angulo(float x, int n){
int i, sen = 0, fat;
x *= M_PI/180;
for(i = 0; i < n; i++){
fat = (2*i+1);
sen += pow(-1, i)*pow(x, fat)/qual_o_fatorial(fat);
}
cout << sen << endl;
return sen;
} | 17.342105 | 59 | 0.54173 | sueyvid |
9bf61b1cc4954f6bf3f3beeb571039004faac9da | 19,537 | cpp | C++ | simMolView3D.cpp | neelsoumya/cycells | a3a6e632addf0a91c75c0a579ad0d41ad9d7a089 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null | simMolView3D.cpp | neelsoumya/cycells | a3a6e632addf0a91c75c0a579ad0d41ad9d7a089 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null | simMolView3D.cpp | neelsoumya/cycells | a3a6e632addf0a91c75c0a579ad0d41ad9d7a089 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 3 | 2018-06-20T21:55:11.000Z | 2020-10-21T19:04:54.000Z | /************************************************************************
* *
* Copyright (C) 2007 Christina Warrender and Drew Levin *
* *
* This file is part of QtCyCells. *
* *
* QtCyCells is free software; you can redistribute it and/or modify it *
* under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* QtCyCells is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with QtCyCells; if not, write to the Free Software Foundation, *
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *
* *
************************************************************************/
/************************************************************************
* File SimMolView3D.cc *
* render() routine for SimMolView3D *
* Allows 3D display of tissue model *
************************************************************************/
#include <GL/gl.h>
#include <GL/glut.h>
#include <math.h>
#include <iostream>
#include <sys/types.h>
#include <unistd.h>
#include "simMolView3D.h"
#include "tissue.h"
#include "cellType.h"
using namespace std;
#define MAX(x,y) ( x > y ? x : y )
#define MIN(x,y) ( x < y ? x : y )
#define TURN_SENSITIVITY 200.0
#define ZOOM_SENSITIVITY 2400.0
/************************************************************************
* SimMolView3D() *
* Constructor *
* *
* Parameters *
* QWidget *parent: Window containing this view *
* int x, y, w, h: Position (x,y) and size (w,h) of view *
* const Tissue *t; Pointer to model tissue *
* *
* Returns - nothing *
************************************************************************/
SimMolView3D::SimMolView3D(QWidget *parent, int x, int y, int w, int h,
const Tissue *t, int mol_id)
: SimView(parent, x, y, w, h),
m_tissuep(t), m_molId(mol_id), m_first(true), m_mousedown(false),
oldPos(0,0), m_anglex(0.0), m_angley(0.0), m_zoom(1.0), frame(0)
{
// Get tissue size info (do once at beginning rather than repeatedly)
m_xsize = m_tissuep->getXSize();
m_ysize = m_tissuep->getYSize();
m_zsize = m_tissuep->getZSize();
m_maxlength = MAX(MAX(m_xsize, m_ysize), m_zsize);
}
/************************************************************************
* render() *
* OpenGL code to draw current view of model *
* *
* Returns - nothing *
************************************************************************/
void SimMolView3D::render()
{
if (m_first)
{
// set up lighting
GLfloat light_position[] = { 1.0, 1.0, m_zsize*2, 0.0 };
GLfloat light_position2[] = { m_xsize, m_ysize, m_zsize*2, 0.0};
GLfloat white_light[] = { 1.0, 1.0, 1.0, 1.0 };
GLfloat lmodel_ambient[] = { 0.9, 0.9, 0.9, 0.9 };
glLightfv(GL_LIGHT0, GL_POSITION, light_position);
glLightfv(GL_LIGHT0, GL_DIFFUSE, white_light);
glLightfv(GL_LIGHT0, GL_SPECULAR, white_light);
glLightfv(GL_LIGHT1, GL_POSITION, light_position2);
glLightfv(GL_LIGHT1, GL_DIFFUSE, white_light);
glLightfv(GL_LIGHT1, GL_SPECULAR, white_light);
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, lmodel_ambient);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glEnable(GL_LIGHT1);
glClearColor(1.0, 1.0, 1.0, 0.0); // set white background; no blending
glShadeModel(GL_SMOOTH);
glEnable(GL_DEPTH_TEST);
glEnable(GL_BLEND);
// set size/projection - should be in resize routine?
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glFrustum(-m_xsize/2*m_zoom, m_xsize/2*m_zoom, -m_ysize/2*m_zoom, m_ysize/2*m_zoom, 9*m_maxlength, 11*m_maxlength);
m_first = false;
}
// clear; get ready to do model/view transformations
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
// Position and orient the camera
gluLookAt(10*m_maxlength*sin(m_anglex)*cos(m_angley)+m_xsize/2,
10*m_maxlength*sin(m_angley)+m_ysize/2,
-10*m_maxlength*cos(m_anglex)*cos(m_angley)+m_zsize/2,
m_xsize/2, m_ysize/2, m_zsize/2, 0.0, 1.0, 0.0);
renderMolecules();
drawBorder();
if (draw_time) drawTime();
glFlush();
if (save_image) saveImage();
swapBuffers();
frame++;
}
/************************************************************************
* renderMolecules() *
* *
* Parameters - none *
* *
* Returns - nothing *
************************************************************************/
void SimMolView3D::renderMolecules()
{
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
glEnable(GL_COLOR_MATERIAL);
int xnum = m_tissuep->getXSize()/m_tissuep->getGridSize();
int ynum = m_tissuep->getYSize()/m_tissuep->getGridSize();
int znum = m_tissuep->getZSize()/m_tissuep->getGridSize();
// get concentration data for this molecule type
const Array3D<Molecule::Conc>& conc = m_tissuep->getConc(m_molId);
Color color = Color(0,0,0,255);
double scale;
// loop through grid cells
for (int i=1; i<=xnum; i++)
for (int j=1; j<=ynum; j++)
for (int k=1; k<=znum; k++)
{
double c = conc.at(i, j, k);
// scale color according to concentration
if (c == 0) // nothing to draw
continue;
else if (c >= 1.66e-14) // White
glColor4fv(Color(255,255,255,255).getfv());
else if (c >= 1.66e-16) // Red -> White
{
scale = (log10(c)+15.78)/2;
scale = MIN(MAX(scale, 0), 1);
glColor4fv(blendColors(255,0,0,255,255,255,scale).getfv());
}
else if (c >= 1.66e-18) // Orange -> Red
{
scale = (log10(c)+17.78)/2;
scale = MIN(MAX(scale, 0), 1);
glColor4fv(blendColors(255,116,0,255,0,0,scale).getfv());
}
else if (c >= 1.66e-20) // Yellow -> Orange
{
scale = (log10(c)+19.78)/2;
scale = MIN(MAX(scale, 0), 1);
glColor4fv(blendColors(255,255,0,255,116,0,scale).getfv());
}
else if (c >= 1.66e-22) // Green -> Yellow
{
scale = (log10(c)+21.78)/2;
scale = MIN(MAX(scale, 0), 1);
glColor4fv(blendColors(0,255,0,255,255,0,scale).getfv());
}
else if (c >= 1.66e-24) // Blue -> Green
{
scale = (log10(c)+23.78)/2;
scale = MIN(MAX(scale, 0), 1);
glColor4fv(blendColors(0,0,255,0,255,0,scale).getfv());
}
else if (c >= 1.66e-26) // Purple -> Blue
{
scale = (log10(c)+25.78)/2;
scale = MIN(MAX(scale, 0), 1);
glColor4fv(blendColors(164,0,255,0,0,255,scale).getfv());
}
else if (c >= 1.66e-28) // Black -> Purple
{
scale = (log10(c)+27.78)/2;
scale = MIN(MAX(scale, 0), 1);
glColor4fv(blendColors(0,0,0,164,0,255,scale).getfv());
}
else
glColor4fv(Color(0,0,0,1.0).getfv());
// scale, translate by grid cell indices & draw
glPushMatrix();
glScalef(m_tissuep->getGridSize(), m_tissuep->getGridSize(), m_tissuep->getGridSize());
glTranslatef(i-1.0, j-1.0, k-1.0);
drawGrid();
glPopMatrix();
}
glDisable(GL_COLOR_MATERIAL);
}
/************************************************************************
* drawGrid() *
* OpenGL code to draw a grid cell; calling routine must handle *
* translation to appropriate location *
* *
* Parameters - none *
* *
* Returns - nothing *
************************************************************************/
void SimMolView3D::drawGrid()
{
// glPolygonMode(GL_FRONT);
glBegin(GL_QUADS);
// back
glVertex3f(0.0, 0.0, 0.0);
glVertex3f(1.0, 0.0, 0.0);
glVertex3f(1.0, 1.0, 0.0);
glVertex3f(0.0, 1.0, 0.0);
// top
glVertex3f(0.0, 1.0, 1.0);
glVertex3f(1.0, 1.0, 1.0);
glVertex3f(1.0, 1.0, 0.0);
glVertex3f(0.0, 1.0, 0.0);
// left
glVertex3f(0.0, 0.0, 0.0);
glVertex3f(0.0, 0.0, 1.0);
glVertex3f(0.0, 1.0, 1.0);
glVertex3f(0.0, 1.0, 0.0);
// right
glVertex3f(1.0, 0.0, 0.0);
glVertex3f(1.0, 0.0, 1.0);
glVertex3f(1.0, 1.0, 1.0);
glVertex3f(1.0, 1.0, 0.0);
// bottom
glVertex3f(0.0, 0.0, 0.0);
glVertex3f(0.0, 0.0, 1.0);
glVertex3f(1.0, 0.0, 1.0);
glVertex3f(1.0, 0.0, 0.0);
// front
glVertex3f(0.0, 0.0, 1.0);
glVertex3f(1.0, 0.0, 1.0);
glVertex3f(1.0, 1.0, 1.0);
glVertex3f(0.0, 1.0, 1.0);
glEnd();
// glDisable(GL_COLOR_MATERIAL);
}
/************************************************************************
* drawBorder() *
* OpenGL code to draw border box around the limits of the simulation *
* *
* Parameters - none *
* *
* Returns - nothing *
************************************************************************/
void SimMolView3D::drawBorder()
{
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
glEnable(GL_COLOR_MATERIAL);
glColor3f(0.4, 0.4, 0.4);
glBegin(GL_QUADS);
// back
glVertex3f(0.0, 0.0, 0.0);
glVertex3f(m_xsize, 0.0, 0.0);
glVertex3f(m_xsize, m_ysize, 0.0);
glVertex3f(0.0, m_ysize, 0.0);
// top
glVertex3f(0.0, m_ysize, m_zsize);
glVertex3f(m_xsize, m_ysize, m_zsize);
glVertex3f(m_xsize, m_ysize, 0.0);
glVertex3f(0.0, m_ysize, 0.0);
// left
glVertex3f(0.0, 0.0, 0.0);
glVertex3f(0.0, 0.0, m_zsize);
glVertex3f(0.0, m_ysize, m_zsize);
glVertex3f(0.0, m_ysize, 0.0);
// right
glVertex3f(m_xsize, 0.0, 0.0);
glVertex3f(m_xsize, 0.0, m_zsize);
glVertex3f(m_xsize, m_ysize, m_zsize);
glVertex3f(m_xsize, m_ysize, 0.0);
// bottom
glVertex3f(0.0, 0.0, 0.0);
glVertex3f(0.0, 0.0, m_zsize);
glVertex3f(m_xsize, 0.0, m_zsize);
glVertex3f(m_xsize, 0.0, 0.0);
// front
glVertex3f(0.0, 0.0, m_zsize);
glVertex3f(m_xsize, 0.0, m_zsize);
glVertex3f(m_xsize, m_ysize, m_zsize);
glVertex3f(0.0, m_ysize, m_zsize);
glEnd();
glDisable(GL_COLOR_MATERIAL);
}
/************************************************************************
* drawTime () *
* OpenGL code to draw the simulation time in the upper left corner. *
* *
* Parameters - none *
* *
* Returns - nothing *
************************************************************************/
void SimMolView3D::drawTime()
{
const char *c;
double time;
int days, hours, minutes, seconds;
char str_days[256];
time = m_tissuep->getTime();
days = (int)floor(time/86400);
time -= days*86400;
hours = (int)floor(time/3600);
time -= hours*3600;
minutes = (int)floor(time/60);
seconds = (int)time-(minutes*60);
if (days > 0) {
sprintf(str_days, "Day %d ", days);
} else {
sprintf(str_days, "");
}
sprintf(time_string, "%s %d:%02d:%02d", str_days, hours, minutes, seconds);
glEnable(GL_COLOR_MATERIAL);
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
gluOrtho2D(0, width, 0, height);
glScalef(1, -1, 1);
glTranslatef(0, -height, 0);
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
glColor3d(0.9, 0.9, 0.9);
glRasterPos2f(10, 28);
for (c=time_string; *c != '\0'; c++) {
glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, *c);
}
glColor3d(0.1, 0.1, 0.1);
glRasterPos2f(11, 29);
for (c=time_string; *c != '\0'; c++) {
glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, *c);
}
glPopMatrix();
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glMatrixMode(GL_MODELVIEW);
}
/************************************************************************
* mousePressEvent() *
* QT4 function to track mouse dragging. *
* *
* Parameters - event *
* *
* Returns - nothing *
************************************************************************/
void SimMolView3D::mousePressEvent(QMouseEvent *event)
{
oldPos = event->pos();
}
/************************************************************************
* mouseMoveEvent() *
* QT4 function to track mouse dragging. Only functions if the *
* mouse button is pressed. Reorients the OpenGL view. *
* *
* Parameters - event *
* *
* Returns - nothing *
************************************************************************/
void SimMolView3D::mouseMoveEvent(QMouseEvent *event)
{
// Only react to mouse dragging, not regular movement.
if ((event->buttons() & Qt::LeftButton))
{
QPoint dxy = event->pos() - oldPos;
oldPos = event->pos();
m_anglex += dxy.x() / TURN_SENSITIVITY;
m_angley += dxy.y() / TURN_SENSITIVITY;
render();
}
}
/************************************************************************
* wheelEvent() *
* QT4 function to track the mouse wheel. Zooms in and out by *
* narrowing or widening the view frustum. *
* *
* Parameters - event *
* *
* Returns - nothing *
************************************************************************/
void SimMolView3D::wheelEvent(QWheelEvent *event)
{
// Get mouse wheel rotation in 1/8 of a degree.
// Most mouse wheels click every 15 degrees, or 120 delta units.
double delta = (double)(event->delta());
if (delta > 0) // Zoom in
m_zoom *= 1 - (delta / ZOOM_SENSITIVITY);
else // Zoom Out
m_zoom /= 1 - (-delta / ZOOM_SENSITIVITY);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glFrustum(-m_xsize/2*m_zoom, m_xsize/2*m_zoom, -m_ysize/2*m_zoom, m_ysize/2*m_zoom, 9*m_maxlength, 11*m_maxlength);
render();
}
/************************************************************************
* saveImage() *
* private function to save current frame as an image file. *
* *
* Parameters - none *
* *
* Returns - nothing *
************************************************************************/
void SimMolView3D::saveImage()
{
makeCurrent();
int pid = (int)getpid();
printf("Frame: %5d\n", frame);
QImage *screen = new QImage(grabFrameBuffer());
screen->save(QString("/nfs/adaptive/drew/cycells2/cycells/frames/frame_%1_%2.png").arg(pid).arg(frame, 6, 10, QChar('0')), "PNG");
delete screen;
}
/************************************************************************
* blendColors() *
* Blends two RGB colors based on the scale factor *
* *
* Parameters - Color 1, Color2, scale factor *
* *
* Will return Color 1 with scale factor of 0 and Color 2 with scale *
* factor of 1 *
* *
* Returns - nothing *
************************************************************************/
Color SimMolView3D::blendColors(int r1, int g1, int b1, int r2, int g2, int b2, double scale)
{
float r, g, b;
r = ((double)r1 + (r2-r1)*scale)/255;
g = ((double)g1 + (g2-g1)*scale)/255;
b = ((double)b1 + (b2-b1)*scale)/255;
if (r > 1 || g > 1 || b > 1 || r < 0 || g < 0 || b < 0)
{
printf("\nColor1: (%d, %d, %d)\n", r1, g1, b1);
printf("Color2: (%d, %d, %d)\n", r2, g2, b2);
printf("Scale: %f\n", scale);
printf("Color: (%f, %f, %f)\n\n", r, g, b);
}
return Color(r, g, b, 1.0);
}
| 38.840954 | 131 | 0.417004 | neelsoumya |
5009bc05bc1e84f9f371cc010c7b05ea1e65b80e | 3,978 | cpp | C++ | src/Npfs/Resources/StdStringFile.cpp | joluxer/NpfsCpp | f19d422b9ab4fa67e35c1e0c29dfa2abc8b0d78f | [
"Zlib"
] | null | null | null | src/Npfs/Resources/StdStringFile.cpp | joluxer/NpfsCpp | f19d422b9ab4fa67e35c1e0c29dfa2abc8b0d78f | [
"Zlib"
] | null | null | null | src/Npfs/Resources/StdStringFile.cpp | joluxer/NpfsCpp | f19d422b9ab4fa67e35c1e0c29dfa2abc8b0d78f | [
"Zlib"
] | null | null | null | /*
* StdStringFile.cpp
*
*/
#include "StdStringFile.h"
#include <string.h>
#include <assert.h>
namespace Npfs
{
StdStringFile::StdStringFile(const char* filename, Npfs::Directory* parent, std::string& storage, uint16_t umask)
: Npfs::Resource(filename, parent), fileData(storage),
updateHandler(0), changeHandler(0), truncHandler(0), modifiedHandler(0)
{
// deny all accesses
stat.mode &= ~0777;
stat.mode |= 0666 & ~umask;
stat.setMode(stat.mode);
}
//StdStringFile::~StdStringFile()
//{
// // Auto-generated destructor stub
//}
void * StdStringFile::IoRefState::operator new(size_t size) throw()
{
return new unsigned char[size];
}
void StdStringFile::IoRefState::operator delete(void *mem) throw()
{
delete[] (unsigned char*)mem;
}
Npfs::Resource::ResultMessage StdStringFile::open(Npfs::OpenIoState& workRef, uint8_t mode, uint32_t& iounit)
{
ResultMessage result = 0;
setNewSize(fileData.length());
if (!updateHandler || updateHandler->execute(fileData, stat.length))
{
IoRefState* ioRef = new IoRefState;
if (!handleNoMemory(ioRef, result))
{
ioRef->isWritten = false;
workRef.ioState = ioRef;
result = OpSuccess;
}
else
{
result = NoMemory;
}
}
return result;
}
Npfs::Resource::ResultMessage StdStringFile::read(Npfs::OpenIoState& workRef, unsigned char* dataBuffer, uint32_t& count, uint64_t offset) // in count will be returned the actual read amount of data
{
ResultMessage result = OpSuccess;
setNewSize(fileData.length());
if (stat.length <= offset)
{
// nichts kann gelesen werden
count = 0;
}
// sonst ist die volle Menge lesbar
if (count)
count = fileData.copy((char*) dataBuffer, count, offset);
return result;
}
Npfs::Resource::ResultMessage StdStringFile::write(Npfs::OpenIoState& workRef, const unsigned char* dataBuffer, uint32_t& count, uint64_t offset)
{
ResultMessage result = OpSuccess;
IoRefState* ioRef = static_cast<IoRefState*>(workRef.ioState);
if (fileData.length() < (offset + count))
{
fileData.reserve(offset + count);
fileData.append((offset + count) - fileData.length(), 0);
ioRef->isWritten = true;
}
if (count)
{
fileData.replace(offset, count, (const char*) dataBuffer, count);
// Datei-Laenge bearbeiten
setNewSize(fileData.length());
stat.qid.version++;
ioRef->isWritten = true;
if (modifiedHandler)
{
uint32_t countCopy = count; // needed, as the handler is allowed to modify the value, but we want to ignore these changes.
uint64_t offsetCopy = offset; // needed, as the handler is allowed to modify the value, but we want to ignore these changes.
modifiedHandler->notify(fileData, countCopy, offsetCopy);
}
}
return result;
}
void StdStringFile::flush(Npfs::OpenIoState& workRef)
{
// intentionally left empty
}
Npfs::Resource::ResultMessage StdStringFile::close(Npfs::OpenIoState& workRef)
{
ResultMessage result = OpSuccess;
IoRefState* ioRef = static_cast<IoRefState*>(workRef.ioState);
setNewSize(fileData.length());
if (ioRef->isWritten)
{
if (!changeHandler || changeHandler->notify(fileData, stat.length))
{
delete ioRef;
workRef.ioState = ioRef = 0;
}
else
{
result = 0;
}
}
else
{
delete ioRef;
workRef.ioState = ioRef = 0;
}
return result;
}
Npfs::Resource::ResultMessage StdStringFile::trunc(Npfs::BlockingOpState* &workRef, uint64_t newLength)
{
ResultMessage result = 0;
if (truncHandler)
{
if (truncHandler->notify(fileData, newLength))
{
fileData.erase(newLength);
setNewSize(fileData.length());
result = OpSuccess;
}
}
else
{
fileData.erase(newLength);
setNewSize(fileData.length());
result = OpSuccess;
}
return result;
}
const NpStat& StdStringFile::getStat()
{
setNewSize(fileData.length());
return Resource::getStat();
}
}
| 21.857143 | 199 | 0.672448 | joluxer |
500b7fdd8572a9a1a4b1f2b78aba99ab17a8ab64 | 361 | cpp | C++ | util.cpp | fightling/decklink-debugger | 796be29a62a02593cf7b53e695b2f53f04a2fc75 | [
"MIT"
] | 18 | 2018-01-07T19:19:59.000Z | 2021-12-27T14:11:32.000Z | util.cpp | fightling/decklink-debugger | 796be29a62a02593cf7b53e695b2f53f04a2fc75 | [
"MIT"
] | 8 | 2018-01-10T23:28:11.000Z | 2021-07-15T22:12:50.000Z | util.cpp | fightling/decklink-debugger | 796be29a62a02593cf7b53e695b2f53f04a2fc75 | [
"MIT"
] | 10 | 2018-05-10T19:53:30.000Z | 2020-12-05T11:54:20.000Z | #include "util.h"
#include "log.h"
void throwIfNotOk(HRESULT result, const char* message)
{
if(result != S_OK) {
LOG(ERROR) << "result (=0x" << std::hex << result << ") != S_OK, " << message;
throw message;
}
}
void throwIfNull(void* ptr, const char* message)
{
if(ptr == nullptr) {
LOG(ERROR) << "ptr == nullptr, " << message;
throw message;
}
}
| 19 | 80 | 0.603878 | fightling |
50149195e681700189c64bb8a73d45c5fd83539a | 63,015 | cpp | C++ | Dodo-Engine/code/renderer/Renderer.cpp | TKscoot/Dodo-Engine | ba6c56a898d2e07e0fd7e89161cbdafd8bc02abd | [
"MIT"
] | null | null | null | Dodo-Engine/code/renderer/Renderer.cpp | TKscoot/Dodo-Engine | ba6c56a898d2e07e0fd7e89161cbdafd8bc02abd | [
"MIT"
] | null | null | null | Dodo-Engine/code/renderer/Renderer.cpp | TKscoot/Dodo-Engine | ba6c56a898d2e07e0fd7e89161cbdafd8bc02abd | [
"MIT"
] | null | null | null | #include "dodopch.h"
#include "Renderer.h"
using namespace Dodo::Environment;
bool Dodo::Rendering::CRenderer::m_bFramebufferResized = false;
DodoError Dodo::Rendering::CRenderer::Initialize(std::shared_ptr<VKIntegration> _integration, std::shared_ptr<CWindow> _window)
{
m_pIntegration = _integration;
m_pWindow = _window;
CreateSwapChain();
CreateImageViews();
CreateRenderPass();
CreateDescriptorSetLayout();
CreateGraphicsPipeline();
CreateCommandPool();
CreateDepthResources();
CreateFramebuffers();
CreateTextureImages();
CreateTextureImageViews();
CreateTextureSampler();
CreateVertexBuffers();
CreateIndexBuffers();
CreateUniformBuffers();
CreateDescriptorPool();
CreateDescriptorSets();
// GUI
m_pGui = std::make_shared<Rendering::GUI>(m_pIntegration, &m_pCamera->cameraPos, &m_pCamera->cameraFront, m_pCamera->camSpeed);
m_pGui->CreateRenderPass(m_vkSwapChainImageFormat, FindDepthFormat());
m_pGui->CreateFramebuffers(m_vkSwapChainImageViews, m_vkDepthImageView, m_vkSwapChainExtent);
m_pGui->Initialize(m_vkRenderPass, m_vkSwapChainExtent.width, m_vkSwapChainExtent.height);
// Skybox
m_pSkybox = std::make_shared<CSkybox>(m_pIntegration, m_vkRenderPass, m_vkCommandPool, m_vkSwapChainExtent);
m_pSkybox->Initialize();
// ShadowMap
m_pShadowMap = std::make_shared<CShadowMapping>(m_pIntegration, m_pCamera);
m_pShadowMap->Initialize();
CreateCommandBuffers();
CreateSyncObjects();
return DODO_OK;
}
DodoError Dodo::Rendering::CRenderer::DrawFrame(double deltaTime)
{
DodoError result = DODO_INITIALIZATION_FAILED;
VkResult vkResult = VK_ERROR_INITIALIZATION_FAILED;
uint32_t imageIndex = 0;
vkResult = vkWaitForFences(m_pIntegration->device(),
1,
&m_sSyncObjects.inFlightFences[m_iCurrentFrame],
VK_TRUE,
std::numeric_limits<uint64_t>::max());
CError::CheckError<VkResult>(vkResult);
vkResult = vkResetFences(m_pIntegration->device(), 1, &m_sSyncObjects.inFlightFences[m_iCurrentFrame]);
CError::CheckError<VkResult>(vkResult);
vkResult = vkAcquireNextImageKHR(m_pIntegration->device(),
m_vkSwapChain,
std::numeric_limits<uint64_t>::max(),
m_sSyncObjects.imageAvailableSemaphores[m_iCurrentFrame],
VK_NULL_HANDLE,
&imageIndex);
// check if swapchain needs to be recreated
if (vkResult == VK_ERROR_OUT_OF_DATE_KHR || vkResult == VK_SUBOPTIMAL_KHR || m_bFramebufferResized)
{
m_bFramebufferResized = false;
RecreateSwapChain();
}
else
{
CError::CheckError<VkResult>(vkResult);
}
// Update uniform buffers here!!
UpdateUniformBuffer();
m_pSkybox->UpdateUniformBuffer(m_pCamera);
m_pShadowMap->UpdateUniformBuffer();
VkSubmitInfo submitInfo = {};
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
std::vector<VkSemaphore> waitSemaphores = { m_sSyncObjects.imageAvailableSemaphores[m_iCurrentFrame] };
std::vector<VkPipelineStageFlags> waitStages = { VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT };
std::vector<VkCommandBuffer> commandBuffers;
if (m_bDrawGui)
{
commandBuffers = {
m_vkCommandBuffers.at(imageIndex),
m_pGui->m_vkCommandBuffers.at(imageIndex)
};
}
else
{
commandBuffers = { m_vkCommandBuffers.at(imageIndex)};
}
submitInfo.waitSemaphoreCount = 1;
submitInfo.pWaitSemaphores = waitSemaphores.data();
submitInfo.pWaitDstStageMask = waitStages.data();
submitInfo.commandBufferCount = commandBuffers.size();
submitInfo.pCommandBuffers = commandBuffers.data();
std::vector<VkSemaphore> signalSemaphores = { m_sSyncObjects.renderFinishedSemaphores[m_iCurrentFrame] };
submitInfo.signalSemaphoreCount = 1;
submitInfo.pSignalSemaphores = signalSemaphores.data();
vkResetFences(m_pIntegration->device(), 1, &m_sSyncObjects.inFlightFences[m_iCurrentFrame]);
vkResult = vkQueueSubmit(m_pIntegration->queues().graphicsQueue, 1, &submitInfo, m_sSyncObjects.inFlightFences[m_iCurrentFrame]);
CError::CheckError<VkResult>(vkResult);
VkPresentInfoKHR presentInfo = {};
presentInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
presentInfo.waitSemaphoreCount = 1;
presentInfo.pWaitSemaphores = signalSemaphores.data();
presentInfo.swapchainCount = 1;
presentInfo.pSwapchains = &m_vkSwapChain;
presentInfo.pImageIndices = &imageIndex;
presentInfo.pResults = nullptr;
vkResult = vkQueuePresentKHR(m_pIntegration->queues().presentQueue, &presentInfo);
CError::CheckError<VkResult>(vkResult);
m_fFrameTimeCounter += deltaTime;
if (m_bDrawGui)
{
if (vkWaitForFences(m_pIntegration->device(),
1,
&m_sSyncObjects.inFlightFences[m_iCurrentFrame],
VK_TRUE,
std::numeric_limits<uint64_t>::max()) == VK_SUCCESS)
{
//UpdateCommandBuffers();
if (m_fFrameTimeCounter >= 1.0f)
{
m_pGui->NewFrame(deltaTime, true);
m_fFrameTimeCounter = 0.0f;
}
else
{
m_pGui->NewFrame(deltaTime, false);
}
if (m_pGui->UpdateBuffers())
{
m_pGui->DrawFrame(m_vkSwapChainExtent, m_vkRenderPass, m_vkSwapChainFramebuffers, deltaTime);
}
}
}
m_iCurrentFrame = (m_iCurrentFrame + 1) % MAX_FRAMES_IN_FLIGHT;
result = DODO_OK;
return result;
}
DodoError Dodo::Rendering::CRenderer::Finalize()
{
CleanupSwapChain();
m_pGui->Finalize();
for (auto &mat : m_pMaterials)
{
mat->Finalize();
}
vkDestroyDescriptorSetLayout(m_pIntegration->device(), m_vkDescriptorSetLayout, nullptr);
for (auto &mesh : m_pMeshes)
{
vkDestroyBuffer(m_pIntegration->device(), mesh->m_dataBuffers.indexBuffer, nullptr);
vkFreeMemory(m_pIntegration->device(), mesh->m_dataBuffers.indexBufferMemory, nullptr);
vkDestroyBuffer(m_pIntegration->device(), mesh->m_dataBuffers.vertexBuffer, nullptr);
vkFreeMemory(m_pIntegration->device(), mesh->m_dataBuffers.vertexBufferMemory, nullptr);
}
for (size_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++)
{
vkDestroySemaphore(m_pIntegration->device(), m_sSyncObjects.renderFinishedSemaphores[i], nullptr);
vkDestroySemaphore(m_pIntegration->device(), m_sSyncObjects.imageAvailableSemaphores[i], nullptr);
vkDestroyFence(m_pIntegration->device(), m_sSyncObjects.inFlightFences[i], nullptr);
}
vkDestroyCommandPool(m_pIntegration->device(), m_vkCommandPool, nullptr);
m_pIntegration->Finalize();
return DODO_OK;
}
VkResult Dodo::Rendering::CRenderer::CreateSwapChain()
{
VkResult result = VK_ERROR_INITIALIZATION_FAILED;
SwapChainSupportDetails swapChainDetails = QuerySwapChainSupport();
VkSurfaceFormatKHR surfaceFormat = ChooseSwapSurfaceFormat(swapChainDetails.formats);
VkPresentModeKHR presentMode = ChooseSwapPresentMode(swapChainDetails.presentModes);
VkExtent2D extent = ChooseSwapExtent(swapChainDetails.capabilities);
// Number of images in the swap chain
uint32_t imageCount = swapChainDetails.capabilities.minImageCount + 1;
if (swapChainDetails.capabilities.maxImageCount > 0 && imageCount > swapChainDetails.capabilities.maxImageCount)
{
imageCount = swapChainDetails.capabilities.maxImageCount;
}
VkSwapchainCreateInfoKHR createInfo = {};
createInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
createInfo.surface = m_pIntegration->surface();
createInfo.minImageCount = imageCount;
createInfo.imageFormat = surfaceFormat.format;
createInfo.imageColorSpace = surfaceFormat.colorSpace;
createInfo.imageExtent = extent;
createInfo.imageArrayLayers = 1;
createInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
//uint32_t queueFamilyIndices[] = {
// (uint32_t)m_pIntegration->queueFamilies().graphicsQueueFamilyIndices,
// (uint32_t)m_pIntegration->queueFamilies().presentQueueFamilyIndices };
std::vector<uint32_t> queueFamilyIndices(2);
queueFamilyIndices = {
(uint32_t)m_pIntegration->queueFamilies().graphicsQueueFamilyIndices,
(uint32_t)m_pIntegration->queueFamilies().presentQueueFamilyIndices };
if (m_pIntegration->queueFamilies().graphicsQueueFamilyIndices != m_pIntegration->queueFamilies().presentQueueFamilyIndices)
{
createInfo.imageSharingMode = VK_SHARING_MODE_CONCURRENT;
createInfo.queueFamilyIndexCount = queueFamilyIndices.size();
createInfo.pQueueFamilyIndices = queueFamilyIndices.data();
}
else
{
createInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
}
createInfo.preTransform = swapChainDetails.capabilities.currentTransform;
createInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
createInfo.presentMode = presentMode;
createInfo.clipped = VK_TRUE;
result = vkCreateSwapchainKHR(m_pIntegration->device(), &createInfo, nullptr, &m_vkSwapChain);
CError::CheckError<VkResult>(result);
result = vkGetSwapchainImagesKHR(m_pIntegration->device(), m_vkSwapChain, &imageCount, nullptr);
m_vkSwapChainImages.resize(imageCount);
result = vkGetSwapchainImagesKHR(m_pIntegration->device(), m_vkSwapChain, &imageCount, m_vkSwapChainImages.data());
m_vkSwapChainImageFormat = surfaceFormat.format;
m_vkSwapChainExtent = extent;
return result;
}
VkImageView Dodo::Rendering::CRenderer::CreateImageView(VkImage image, VkFormat format, VkImageAspectFlags aspectFlags)
{
VkImageViewCreateInfo viewInfo = {};
viewInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
viewInfo.image = image;
viewInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
viewInfo.format = format;
viewInfo.subresourceRange.aspectMask = aspectFlags;
viewInfo.subresourceRange.baseMipLevel = 0;
viewInfo.subresourceRange.levelCount = 1;
viewInfo.subresourceRange.baseArrayLayer = 0;
viewInfo.subresourceRange.layerCount = 1;
VkImageView imageView;
if (vkCreateImageView(m_pIntegration->device(), &viewInfo, nullptr, &imageView) != VK_SUCCESS)
{
throw std::runtime_error("failed to create texture image view!");
}
return imageView;
}
VkResult Dodo::Rendering::CRenderer::CreateTextureImage(Components::CMaterial::Texture &_texture)
{
VkResult result = VK_ERROR_INITIALIZATION_FAILED;
VkBuffer stagingBuffer;
VkDeviceMemory stagingBufferMemory;
VkDeviceSize imageSize = _texture.texWidth * _texture.texHeight * 4;
result = CreateBuffer(imageSize,
VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
stagingBuffer, stagingBufferMemory);
void* data;
vkMapMemory(m_pIntegration->device(), stagingBufferMemory, 0, imageSize, 0, &data);
memcpy(data, _texture.pixels, static_cast<size_t>(imageSize));
vkUnmapMemory(m_pIntegration->device(), stagingBufferMemory);
stbi_image_free(_texture.pixels);
result = CreateImage(
_texture.texWidth,
_texture.texHeight,
VK_FORMAT_R8G8B8A8_UNORM,
VK_IMAGE_TILING_OPTIMAL,
VK_IMAGE_USAGE_TRANSFER_DST_BIT |
VK_IMAGE_USAGE_SAMPLED_BIT,
VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
_texture.textureData.textureImage,
_texture.textureData.textureImageMemory);
result = TransitionImageLayout(
_texture.textureData.textureImage,
VK_FORMAT_R8G8B8A8_UNORM,
VK_IMAGE_LAYOUT_UNDEFINED,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);
result = CopyBufferToImage(
stagingBuffer,
_texture.textureData.textureImage,
static_cast<uint32_t>(_texture.texWidth),
static_cast<uint32_t>(_texture.texHeight));
result = TransitionImageLayout(
_texture.textureData.textureImage,
VK_FORMAT_R8G8B8A8_UNORM,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
vkDestroyBuffer(m_pIntegration->device(), stagingBuffer, nullptr);
vkFreeMemory(m_pIntegration->device(), stagingBufferMemory, nullptr);
return result;
}
VkResult Dodo::Rendering::CRenderer::CreateImageViews()
{
VkResult result = VK_ERROR_INITIALIZATION_FAILED;
m_vkSwapChainImageViews.resize(m_vkSwapChainImages.size());
for (size_t i = 0; i < m_vkSwapChainImages.size(); i++)
{
m_vkSwapChainImageViews[i] = CreateImageView(
m_vkSwapChainImages[i],
m_vkSwapChainImageFormat,
VK_IMAGE_ASPECT_COLOR_BIT);
}
return result;
}
VkResult Dodo::Rendering::CRenderer::CreateRenderPass()
{
VkResult result = VK_ERROR_INITIALIZATION_FAILED;
VkAttachmentDescription colorAttachment = {};
colorAttachment.format = m_vkSwapChainImageFormat;
colorAttachment.samples = VK_SAMPLE_COUNT_1_BIT;
colorAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
colorAttachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
colorAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
colorAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
colorAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
colorAttachment.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
VkAttachmentDescription depthAttachment = {};
depthAttachment.format = FindDepthFormat();
depthAttachment.samples = VK_SAMPLE_COUNT_1_BIT;
depthAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
depthAttachment.storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
depthAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
depthAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
depthAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
depthAttachment.finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
VkAttachmentReference colorAttachmentRef = {};
colorAttachmentRef.attachment = 0;
colorAttachmentRef.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
VkAttachmentReference depthAttachmentRef = {};
depthAttachmentRef.attachment = 1;
depthAttachmentRef.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
VkSubpassDescription subpass = {};
subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
subpass.colorAttachmentCount = 1;
subpass.pColorAttachments = &colorAttachmentRef;
subpass.pDepthStencilAttachment = &depthAttachmentRef;
VkSubpassDependency dependency = {};
dependency.srcSubpass = VK_SUBPASS_EXTERNAL;
dependency.dstSubpass = 0;
dependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
dependency.srcAccessMask = 0;
dependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
std::array<VkAttachmentDescription, 2> attachments = { colorAttachment, depthAttachment };
VkRenderPassCreateInfo renderPassInfo = {};
renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
renderPassInfo.attachmentCount = static_cast<uint32_t>(attachments.size());
renderPassInfo.pAttachments = attachments.data();
renderPassInfo.subpassCount = 1;
renderPassInfo.pSubpasses = &subpass;
renderPassInfo.dependencyCount = 1;
renderPassInfo.pDependencies = &dependency;
result = vkCreateRenderPass(m_pIntegration->device(), &renderPassInfo, nullptr, &m_vkRenderPass);
CError::CheckError<VkResult>(result);
return result;
}
VkResult Dodo::Rendering::CRenderer::CreateDescriptorSetLayout()
{
VkResult result = VK_ERROR_INITIALIZATION_FAILED;
VkDescriptorSetLayoutBinding uboLayoutBinding = {};
uboLayoutBinding.binding = 0;
uboLayoutBinding.descriptorCount = 1;
uboLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
uboLayoutBinding.pImmutableSamplers = nullptr; // image sampling related
uboLayoutBinding.stageFlags = VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT;
//VkDescriptorSetLayoutCreateInfo layoutInfo = {};
//layoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
//layoutInfo.bindingCount = 1;
//layoutInfo.pBindings = &uboLayoutBinding;
VkDescriptorSetLayoutBinding albedoSamplerLayoutBinding = {};
albedoSamplerLayoutBinding.binding = 1;
albedoSamplerLayoutBinding.descriptorCount = 1;
albedoSamplerLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
albedoSamplerLayoutBinding.pImmutableSamplers = nullptr;
albedoSamplerLayoutBinding.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT;
VkDescriptorSetLayoutBinding normalSamplerLayoutBinding = {};
normalSamplerLayoutBinding.binding = 2;
normalSamplerLayoutBinding.descriptorCount = 1;
normalSamplerLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
normalSamplerLayoutBinding.pImmutableSamplers = nullptr;
normalSamplerLayoutBinding.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT;
VkDescriptorSetLayoutBinding metallicSamplerLayoutBinding = {};
metallicSamplerLayoutBinding.binding = 3;
metallicSamplerLayoutBinding.descriptorCount = 1;
metallicSamplerLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
metallicSamplerLayoutBinding.pImmutableSamplers = nullptr;
metallicSamplerLayoutBinding.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT;
VkDescriptorSetLayoutBinding roughnessSamplerLayoutBinding = {};
roughnessSamplerLayoutBinding.binding = 4;
roughnessSamplerLayoutBinding.descriptorCount = 1;
roughnessSamplerLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
roughnessSamplerLayoutBinding.pImmutableSamplers = nullptr;
roughnessSamplerLayoutBinding.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT;
VkDescriptorSetLayoutBinding lightUboLayoutBinding = {};
lightUboLayoutBinding.binding = 5;
lightUboLayoutBinding.descriptorCount = 1;
lightUboLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
lightUboLayoutBinding.pImmutableSamplers = nullptr; // image sampling related
lightUboLayoutBinding.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT;
std::array<VkDescriptorSetLayoutBinding, 6> bindings = {
uboLayoutBinding,
albedoSamplerLayoutBinding,
normalSamplerLayoutBinding,
metallicSamplerLayoutBinding,
roughnessSamplerLayoutBinding,
lightUboLayoutBinding
};
VkDescriptorSetLayoutCreateInfo layoutInfo = {};
layoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
layoutInfo.bindingCount = static_cast<uint32_t>(bindings.size());
layoutInfo.pBindings = bindings.data();
result = vkCreateDescriptorSetLayout(m_pIntegration->device(), &layoutInfo, nullptr, &m_vkDescriptorSetLayout);
CError::CheckError<VkResult>(result);
return result;
}
VkResult Dodo::Rendering::CRenderer::CreateGraphicsPipeline()
{
VkResult result = VK_ERROR_INITIALIZATION_FAILED;
std::vector<VkPipelineShaderStageCreateInfo> shaderStages;
//for (auto material : m_pMaterials)
//{
m_pMaterials[0]->CreateShaders();
VkPipelineShaderStageCreateInfo vertShaderStageInfo = {};
vertShaderStageInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
vertShaderStageInfo.stage = VK_SHADER_STAGE_VERTEX_BIT;
vertShaderStageInfo.module = m_pMaterials[0]->shaders().vertShaderStage.module;
vertShaderStageInfo.pName = "main";
shaderStages.push_back(vertShaderStageInfo);
VkPipelineShaderStageCreateInfo fragShaderStageInfo = {};
fragShaderStageInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
fragShaderStageInfo.stage = VK_SHADER_STAGE_FRAGMENT_BIT;
fragShaderStageInfo.module = m_pMaterials[0]->shaders().fragShaderStage.module;
fragShaderStageInfo.pName = "main";
shaderStages.push_back(fragShaderStageInfo);
//}
auto bindingDescriptions = CMaterial::GetBindingDescription();
auto attributeDescriptions = CMaterial::GetAttributeDescriptions();
VkPipelineVertexInputStateCreateInfo vertexInputInfo = {};
vertexInputInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
vertexInputInfo.vertexBindingDescriptionCount = 1;
vertexInputInfo.vertexAttributeDescriptionCount = static_cast<uint32_t>(attributeDescriptions.size());
vertexInputInfo.pVertexBindingDescriptions = &bindingDescriptions;
vertexInputInfo.pVertexAttributeDescriptions = attributeDescriptions.data();
VkPipelineInputAssemblyStateCreateInfo inputAssembly = {};
inputAssembly.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
inputAssembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
inputAssembly.primitiveRestartEnable = VK_FALSE;
VkViewport viewport = {};
viewport.x = 0.0f;
viewport.y = 0.0f;
viewport.width = (float)m_vkSwapChainExtent.width;
viewport.height = (float)m_vkSwapChainExtent.height;
viewport.minDepth = 0.0f;
viewport.maxDepth = 1.0f;
VkRect2D scissor = {};
scissor.offset = { 0, 0 };
scissor.extent = m_vkSwapChainExtent;
VkPipelineViewportStateCreateInfo viewportState = {};
viewportState.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
viewportState.viewportCount = 1;
viewportState.pViewports = &viewport;
viewportState.scissorCount = 1;
viewportState.pScissors = &scissor;
VkPipelineRasterizationStateCreateInfo rasterizer = {};
rasterizer.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
rasterizer.depthClampEnable = VK_FALSE;
rasterizer.rasterizerDiscardEnable = VK_FALSE;
rasterizer.polygonMode = VK_POLYGON_MODE_FILL;
rasterizer.lineWidth = 1.0f;
rasterizer.cullMode = VK_CULL_MODE_BACK_BIT;
rasterizer.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE;
rasterizer.depthBiasEnable = VK_FALSE;
rasterizer.depthBiasConstantFactor = 0.0f; // Optional
rasterizer.depthBiasClamp = 0.0f; // Optional
rasterizer.depthBiasSlopeFactor = 0.0f; // Optional
VkPipelineMultisampleStateCreateInfo multisampling = {};
multisampling.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
multisampling.sampleShadingEnable = VK_FALSE;
multisampling.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;
multisampling.minSampleShading = 1.0f; // Optional
multisampling.pSampleMask = nullptr; // Optional
multisampling.alphaToCoverageEnable = VK_FALSE; // Optional
multisampling.alphaToOneEnable = VK_FALSE; // Optional
VkPipelineDepthStencilStateCreateInfo depthStencil = {};
depthStencil.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO;
depthStencil.depthTestEnable = VK_TRUE;
depthStencil.depthWriteEnable = VK_TRUE;
depthStencil.depthCompareOp = VK_COMPARE_OP_LESS;
depthStencil.depthBoundsTestEnable = VK_FALSE;
depthStencil.stencilTestEnable = VK_FALSE;
depthStencil.minDepthBounds = 0.0f; // Optional
depthStencil.maxDepthBounds = 1.0f; // Optional
depthStencil.stencilTestEnable = VK_FALSE;
depthStencil.front = {}; // Optional
depthStencil.back = {}; // Optional
VkPipelineColorBlendAttachmentState colorBlendAttachment = {};
colorBlendAttachment.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT;
colorBlendAttachment.blendEnable = VK_FALSE;
colorBlendAttachment.srcColorBlendFactor = VK_BLEND_FACTOR_ONE; // Optional
colorBlendAttachment.dstColorBlendFactor = VK_BLEND_FACTOR_ZERO; // Optional
colorBlendAttachment.colorBlendOp = VK_BLEND_OP_ADD; // Optional
colorBlendAttachment.srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE; // Optional
colorBlendAttachment.dstAlphaBlendFactor = VK_BLEND_FACTOR_ZERO; // Optional
colorBlendAttachment.alphaBlendOp = VK_BLEND_OP_ADD; // Optional
VkPipelineColorBlendStateCreateInfo colorBlending = {};
colorBlending.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
colorBlending.logicOpEnable = VK_FALSE;
colorBlending.logicOp = VK_LOGIC_OP_COPY;
colorBlending.attachmentCount = 1;
colorBlending.pAttachments = &colorBlendAttachment;
colorBlending.blendConstants[0] = 0.0f;
colorBlending.blendConstants[1] = 0.0f;
colorBlending.blendConstants[2] = 0.0f;
colorBlending.blendConstants[3] = 0.0f;
std::vector<VkPushConstantRange> pushConstantRanges = {
vks::initializers::pushConstantRange(VK_SHADER_STAGE_VERTEX_BIT, sizeof(glm::vec3), 0),
vks::initializers::pushConstantRange(VK_SHADER_STAGE_FRAGMENT_BIT, sizeof(CMaterial::PushConsts), sizeof(Vector3f)),
};
VkPipelineLayoutCreateInfo pipelineLayoutInfo = {};
pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
pipelineLayoutInfo.setLayoutCount = 1; // Optional
pipelineLayoutInfo.pSetLayouts = &m_vkDescriptorSetLayout;
pipelineLayoutInfo.pushConstantRangeCount = 2;
pipelineLayoutInfo.pPushConstantRanges = pushConstantRanges.data();
result = vkCreatePipelineLayout(m_pIntegration->device(), &pipelineLayoutInfo, nullptr, &m_vkPipelineLayout);
CError::CheckError<VkResult>(result);
VkGraphicsPipelineCreateInfo pipelineInfo = {};
pipelineInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
pipelineInfo.stageCount = 2;
pipelineInfo.pStages = shaderStages.data();
pipelineInfo.pVertexInputState = &vertexInputInfo;
pipelineInfo.pInputAssemblyState = &inputAssembly;
pipelineInfo.pViewportState = &viewportState;
pipelineInfo.pRasterizationState = &rasterizer;
pipelineInfo.pMultisampleState = &multisampling;
pipelineInfo.pDepthStencilState = &depthStencil;
pipelineInfo.pColorBlendState = &colorBlending;
pipelineInfo.pDynamicState = nullptr;
pipelineInfo.layout = m_vkPipelineLayout;
pipelineInfo.renderPass = m_vkRenderPass;
pipelineInfo.subpass = 0;
pipelineInfo.basePipelineHandle = VK_NULL_HANDLE;
pipelineInfo.basePipelineIndex = -1;
pipelineInfo.flags = VK_DYNAMIC_STATE_SCISSOR | VK_DYNAMIC_STATE_VIEWPORT;
// on swap recreation shader modules problems
result = vkCreateGraphicsPipelines(m_pIntegration->device(), VK_NULL_HANDLE, 1, &pipelineInfo, nullptr, &m_vkGraphicsPipeline);
CError::CheckError<VkResult>(result);
for (auto &stage : shaderStages)
{
vkDestroyShaderModule(m_pIntegration->device(), stage.module, nullptr);
}
return result;
}
VkResult Dodo::Rendering::CRenderer::CreateFramebuffers()
{
VkResult result = VK_ERROR_INITIALIZATION_FAILED;
m_vkSwapChainFramebuffers.resize(m_vkSwapChainImageViews.size());
for (size_t i = 0; i < m_vkSwapChainImageViews.size(); i++)
{
std::array<VkImageView, 2> attachments = {
m_vkSwapChainImageViews[i],
m_vkDepthImageView
};
VkFramebufferCreateInfo framebufferInfo = {};
framebufferInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
framebufferInfo.renderPass = m_vkRenderPass;
framebufferInfo.attachmentCount = static_cast<uint32_t>(attachments.size());
framebufferInfo.pAttachments = attachments.data();
framebufferInfo.width = m_vkSwapChainExtent.width;
framebufferInfo.height = m_vkSwapChainExtent.height;
framebufferInfo.layers = 1;
result = vkCreateFramebuffer(m_pIntegration->device(), &framebufferInfo, nullptr, &m_vkSwapChainFramebuffers[i]);
CError::CheckError<VkResult>(result);
}
return result;
}
VkResult Dodo::Rendering::CRenderer::CreateCommandPool()
{
VkResult result = VK_ERROR_INITIALIZATION_FAILED;
VkCommandPoolCreateInfo poolInfo = {};
poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
poolInfo.queueFamilyIndex = m_pIntegration->queueFamilies().graphicsQueueFamilyIndices;
poolInfo.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
result = vkCreateCommandPool(m_pIntegration->device(), &poolInfo, nullptr, &m_vkCommandPool);
CError::CheckError<VkResult>(result);
return result;
}
VkResult Dodo::Rendering::CRenderer::CreateTextureImages()
{
VkResult result = VK_ERROR_INITIALIZATION_FAILED;
for (auto &mat : m_pMaterials)
{
CMaterial::Textures* textures = &mat->textures();
result = CreateTextureImage(textures->albedo );
CError::CheckError<VkResult>(result);
result = CreateTextureImage(textures->normal );
CError::CheckError<VkResult>(result);
result = CreateTextureImage(textures->metallic );
CError::CheckError<VkResult>(result);
result = CreateTextureImage(textures->roughness);
CError::CheckError<VkResult>(result);
}
return result;
}
VkResult Dodo::Rendering::CRenderer::CreateTextureImageViews()
{
VkResult result = VK_ERROR_INITIALIZATION_FAILED;
for (auto &mat : m_pMaterials)
{
CMaterial::Textures* textures = &mat->textures();
textures->albedo. textureData.textureImageView = CreateImageView(textures->albedo.textureData.textureImage, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_ASPECT_COLOR_BIT);
textures->normal. textureData.textureImageView = CreateImageView(textures->normal.textureData.textureImage, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_ASPECT_COLOR_BIT);
textures->metallic. textureData.textureImageView = CreateImageView(textures->metallic.textureData.textureImage, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_ASPECT_COLOR_BIT);
textures->roughness.textureData.textureImageView = CreateImageView(textures->roughness.textureData.textureImage, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_ASPECT_COLOR_BIT);
}
return result;
}
VkResult Dodo::Rendering::CRenderer::CreateTextureSampler()
{
VkResult result = VK_ERROR_INITIALIZATION_FAILED;
VkSamplerCreateInfo samplerInfo = {};
samplerInfo.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO;
samplerInfo.magFilter = VK_FILTER_LINEAR;
samplerInfo.minFilter = VK_FILTER_LINEAR;
samplerInfo.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT;
samplerInfo.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT;
samplerInfo.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT;
samplerInfo.anisotropyEnable = VK_TRUE;
samplerInfo.maxAnisotropy = 16;
samplerInfo.borderColor = VK_BORDER_COLOR_INT_OPAQUE_BLACK;
samplerInfo.unnormalizedCoordinates = VK_FALSE;
samplerInfo.compareEnable = VK_FALSE;
samplerInfo.compareOp = VK_COMPARE_OP_ALWAYS;
samplerInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR;
samplerInfo.mipLodBias = 0.0f;
samplerInfo.minLod = 0.0f;
samplerInfo.maxLod = 0.0f;
for (auto &mat : m_pMaterials)
{
CMaterial::Textures* texures = &mat->textures();
result = vkCreateSampler(m_pIntegration->device(), &samplerInfo, nullptr, &texures->albedo.textureData.textureSampler);
result = vkCreateSampler(m_pIntegration->device(), &samplerInfo, nullptr, &texures->normal.textureData.textureSampler);
result = vkCreateSampler(m_pIntegration->device(), &samplerInfo, nullptr, &texures->metallic.textureData.textureSampler);
result = vkCreateSampler(m_pIntegration->device(), &samplerInfo, nullptr, &texures->roughness.textureData.textureSampler);
CError::CheckError<VkResult>(result);
}
return result;
}
VkResult Dodo::Rendering::CRenderer::CreateDepthResources()
{
VkResult result = VK_ERROR_INITIALIZATION_FAILED;
VkFormat depthFormat = FindDepthFormat();
result = CreateImage(
m_vkSwapChainExtent.width,
m_vkSwapChainExtent.height,
depthFormat,
VK_IMAGE_TILING_OPTIMAL,
VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT,
VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
m_vkDepthImage,
m_vkDepthImageMemory);
m_vkDepthImageView = CreateImageView(m_vkDepthImage, depthFormat, VK_IMAGE_ASPECT_DEPTH_BIT);
TransitionImageLayout(m_vkDepthImage, depthFormat, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL);
return result;
}
VkResult Dodo::Rendering::CRenderer::CreateVertexBuffers()
{
VkResult result = VK_ERROR_INITIALIZATION_FAILED;
for (const std::shared_ptr<Components::CMesh> mesh : m_pMeshes)
{
const std::vector<Vertex> verts = mesh->vertices();
VkDeviceSize bufferSize = sizeof(verts[0]) * verts.size();
// creating staging buffer
VkBuffer stagingBuffer;
VkDeviceMemory stagingBufferMemory;
result = CreateBuffer(bufferSize,
VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
stagingBuffer, stagingBufferMemory);
// copying vert data to staging buffer
void* data;
vkMapMemory(m_pIntegration->device(), stagingBufferMemory, 0, bufferSize, 0, &data);
memcpy(data, verts.data(), (size_t)bufferSize);
vkUnmapMemory(m_pIntegration->device(), stagingBufferMemory);
// creating vertex Buffer
CreateBuffer(
bufferSize,
VK_BUFFER_USAGE_TRANSFER_DST_BIT |
VK_BUFFER_USAGE_VERTEX_BUFFER_BIT,
VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
mesh->m_dataBuffers.vertexBuffer, mesh->m_dataBuffers.vertexBufferMemory);
// copying staging buffer to vertex buffer
CopyBuffer(stagingBuffer, mesh->m_dataBuffers.vertexBuffer, bufferSize);
vkDestroyBuffer(m_pIntegration->device(), stagingBuffer, nullptr);
vkFreeMemory(m_pIntegration->device(), stagingBufferMemory, nullptr);
// push vertex buffer to array for further use (buffer binding, etc.)
//m_matDataBuffers.push_back(buffer);
}
return result;
}
VkResult Dodo::Rendering::CRenderer::CreateIndexBuffers()
{
VkResult result = VK_ERROR_INITIALIZATION_FAILED;
for (const std::shared_ptr<Components::CMesh> mesh : m_pMeshes)
{
VkDeviceSize bufferSize = sizeof(mesh->m_indices[0]) * mesh->m_indices.size();
VkBuffer stagingBuffer;
VkDeviceMemory stagingBufferMemory;
CreateBuffer(bufferSize, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, stagingBuffer, stagingBufferMemory);
void* data;
vkMapMemory(m_pIntegration->device(), stagingBufferMemory, 0, bufferSize, 0, &data);
memcpy(data, mesh->m_indices.data(), (size_t)bufferSize);
vkUnmapMemory(m_pIntegration->device(), stagingBufferMemory);
CreateBuffer(bufferSize,
VK_BUFFER_USAGE_TRANSFER_DST_BIT |
VK_BUFFER_USAGE_INDEX_BUFFER_BIT,
VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
mesh->m_dataBuffers.indexBuffer, mesh->m_dataBuffers.indexBufferMemory);
CopyBuffer(stagingBuffer, mesh->m_dataBuffers.indexBuffer, bufferSize);
vkDestroyBuffer(m_pIntegration->device(), stagingBuffer, nullptr);
vkFreeMemory(m_pIntegration->device(), stagingBufferMemory, nullptr);
m_matDataBuffers.push_back(mesh->m_dataBuffers);
}
return result;
}
VkResult Dodo::Rendering::CRenderer::CreateUniformBuffers()
{
VkResult result = VK_ERROR_INITIALIZATION_FAILED;
m_vkUniformBuffers.resize(m_pTransforms.size());
m_vkUniformBuffersMemory.resize(m_pTransforms.size());
for (size_t i = 0; i < m_pTransforms.size(); i++)
{
VkDeviceSize bufferSize = sizeof(CMaterial::UniformBufferObject);
result = CreateBuffer(
bufferSize,
VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
m_vkUniformBuffers[i],
m_vkUniformBuffersMemory[i]);
CError::CheckError<VkResult>(result);
}
VkDeviceSize lightBufferSize = sizeof(CLight::LightProperties) * m_pLights.size();
result = CreateBuffer(
lightBufferSize,
VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
m_vkLightUniformBuffer,
m_vkLightUniformBufferMemory);
CError::CheckError<VkResult>(result);
return result;
}
VkResult Dodo::Rendering::CRenderer::CreateCommandBuffers()
{
VkResult result = VK_ERROR_INITIALIZATION_FAILED;
m_vkCommandBuffers.resize(m_vkSwapChainFramebuffers.size());
VkCommandBufferAllocateInfo allocInfo = {};
allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
allocInfo.commandPool = m_vkCommandPool;
allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
allocInfo.commandBufferCount = (uint32_t)m_vkCommandBuffers.size();
result = vkAllocateCommandBuffers(m_pIntegration->device(), &allocInfo, m_vkCommandBuffers.data());
CError::CheckError<VkResult>(result);
//GUI
m_pGui->CreateCommandBuffer(&m_vkSwapChainFramebuffers, m_vkCommandPool);
m_pGui->NewFrame(deltaTime(), true);
m_pGui->UpdateBuffers();
m_pGui->DrawFrame(m_vkSwapChainExtent, m_vkRenderPass, m_vkSwapChainFramebuffers);
for (size_t i = 0; i < m_vkCommandBuffers.size(); i++)
{
VkCommandBufferBeginInfo beginInfo = {};
beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
beginInfo.flags = VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT;
beginInfo.pInheritanceInfo = nullptr;
result = vkBeginCommandBuffer(m_vkCommandBuffers[i], &beginInfo);
CError::CheckError<VkResult>(result);
VkRenderPassBeginInfo renderPassInfo = {};
renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
renderPassInfo.renderPass = m_vkRenderPass;
renderPassInfo.framebuffer = m_vkSwapChainFramebuffers[i];
renderPassInfo.renderArea.offset = { 0, 0 };
renderPassInfo.renderArea.extent = m_vkSwapChainExtent;
std::array<VkClearValue, 2> clearValues = {};
clearValues[0].color = { 0.2f, 0.2f, 0.2f, 1.0f };
clearValues[1].depthStencil = { 1.0f, 0 };
renderPassInfo.clearValueCount = clearValues.size();
renderPassInfo.pClearValues = clearValues.data();
vkCmdBeginRenderPass(m_vkCommandBuffers[i], &renderPassInfo, VK_SUBPASS_CONTENTS_INLINE);
// Skybox
m_pSkybox->BuildOnMainCmdBuf(m_vkCommandBuffers[i]);
vkCmdBindPipeline(m_vkCommandBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, m_vkGraphicsPipeline);
//std::vector<VkBuffer> vertexBuffers = {};
VkBuffer *vertexBuffers = new VkBuffer[m_matDataBuffers.size()];
VkDeviceSize offsets[1] = { 0 };
for (int j = 0; j < m_pMeshes.size(); j++)
{
vkCmdBindVertexBuffers(m_vkCommandBuffers[i], 0, 1, &m_pMeshes[j]->m_dataBuffers.vertexBuffer, offsets);
vkCmdBindIndexBuffer(m_vkCommandBuffers[i], m_pMeshes[j]->m_dataBuffers.indexBuffer, 0, VK_INDEX_TYPE_UINT32);
vkCmdBindDescriptorSets(m_vkCommandBuffers[i],
VK_PIPELINE_BIND_POINT_GRAPHICS,
m_vkPipelineLayout,
0,
1,
&m_vkDescriptorSets[j],
0,
nullptr);
Vector3f pos = m_pMeshes[j]->entity->GetComponent<Components::CTransform>()->getPosition();
vkCmdPushConstants(m_vkCommandBuffers[i], m_vkPipelineLayout, VK_SHADER_STAGE_VERTEX_BIT, 0, sizeof(Math::Vector3f), &pos);
CMaterial::PushConsts pushConsts = m_pMeshes[j]->entity->GetComponent<Components::CMaterial>()->pushConstants();
vkCmdPushConstants(m_vkCommandBuffers[i], m_vkPipelineLayout, VK_SHADER_STAGE_FRAGMENT_BIT, sizeof(Vector3f), sizeof(CMaterial::PushConsts), &pushConsts);
vkCmdDrawIndexed(m_vkCommandBuffers[i], m_pMeshes[j]->m_indices.size(), 1, 0, 0, 0);
}
vkCmdEndRenderPass(m_vkCommandBuffers[i]);
m_pShadowMap->RecordCommandBuffer(m_vkCommandBuffers[i]);
result = vkEndCommandBuffer(m_vkCommandBuffers[i]);
CError::CheckError<VkResult>(result);
}
return result;
}
VkResult Dodo::Rendering::CRenderer::CreateSyncObjects()
{
m_sSyncObjects.imageAvailableSemaphores.resize(MAX_FRAMES_IN_FLIGHT);
m_sSyncObjects.renderFinishedSemaphores.resize(MAX_FRAMES_IN_FLIGHT);
m_sSyncObjects.inFlightFences.resize(MAX_FRAMES_IN_FLIGHT);
VkResult result = VK_ERROR_INITIALIZATION_FAILED;
VkSemaphoreCreateInfo semaphoreInfo = {};
semaphoreInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
VkFenceCreateInfo fenceInfo = {};
fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
fenceInfo.flags = VK_FENCE_CREATE_SIGNALED_BIT;
for (size_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++)
{
result = vkCreateSemaphore(m_pIntegration->device(), &semaphoreInfo, nullptr, &m_sSyncObjects.imageAvailableSemaphores[i]);
CError::CheckError<VkResult>(result);
result = vkCreateSemaphore(m_pIntegration->device(), &semaphoreInfo, nullptr, &m_sSyncObjects.renderFinishedSemaphores[i]);
CError::CheckError<VkResult>(result);
result = vkCreateFence(m_pIntegration->device(), &fenceInfo, nullptr, &m_sSyncObjects.inFlightFences[i]);
CError::CheckError<VkResult>(result);
}
return result;
}
VkResult Dodo::Rendering::CRenderer::CreateDescriptorPool()
{
VkResult result = VK_ERROR_INITIALIZATION_FAILED;
std::array<VkDescriptorPoolSize, 6> poolSizes = {};
poolSizes[0].type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
poolSizes[0].descriptorCount = static_cast<uint32_t>(m_pMaterials.size());
poolSizes[1].type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
poolSizes[1].descriptorCount = static_cast<uint32_t>(m_pMaterials.size());
poolSizes[2].type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
poolSizes[2].descriptorCount = static_cast<uint32_t>(m_pMaterials.size());
poolSizes[3].type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
poolSizes[3].descriptorCount = static_cast<uint32_t>(m_pMaterials.size());
poolSizes[4].type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
poolSizes[4].descriptorCount = static_cast<uint32_t>(m_pMaterials.size());
poolSizes[5].type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
poolSizes[5].descriptorCount = static_cast<uint32_t>(m_pMaterials.size());
VkDescriptorPoolCreateInfo poolInfo = {};
poolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
poolInfo.poolSizeCount = static_cast<uint32_t>(poolSizes.size());
poolInfo.pPoolSizes = poolSizes.data();
poolInfo.maxSets = static_cast<uint32_t>(m_pMaterials.size());
result = vkCreateDescriptorPool(m_pIntegration->device(), &poolInfo, nullptr, &m_vkDescriptorPool);
CError::CheckError<VkResult>(result);
return result;
}
VkResult Dodo::Rendering::CRenderer::CreateDescriptorSets()
{
VkResult result = VK_ERROR_INITIALIZATION_FAILED;
std::vector<VkDescriptorSetLayout> layouts(m_pMaterials.size(), m_vkDescriptorSetLayout);
VkDescriptorSetAllocateInfo allocInfo = {};
allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
allocInfo.descriptorPool = m_vkDescriptorPool;
allocInfo.descriptorSetCount = m_pMaterials.size();
allocInfo.pSetLayouts = layouts.data();
m_vkDescriptorSets.resize(m_pMaterials.size());
result = vkAllocateDescriptorSets(m_pIntegration->device(), &allocInfo, m_vkDescriptorSets.data());
CError::CheckError<VkResult>(result);
for (size_t i = 0; i < m_pMaterials.size(); i++)
{
VkDescriptorBufferInfo bufferInfo = {};
bufferInfo.buffer = m_vkUniformBuffers[i];
bufferInfo.offset = 0;
bufferInfo.range = sizeof(CMaterial::UniformBufferObject);
VkDescriptorImageInfo imageInfo = {};
imageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
m_pMaterials[i]->textures().albedo.textureData.imageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
m_pMaterials[i]->textures().normal.textureData.imageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
m_pMaterials[i]->textures().metallic.textureData.imageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
m_pMaterials[i]->textures().roughness.textureData.imageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
m_pMaterials[i]->textures().albedo.textureData.imageInfo.imageView = m_pMaterials[i]->textures().albedo.textureData.textureImageView;
m_pMaterials[i]->textures().normal.textureData.imageInfo.imageView = m_pMaterials[i]->textures().normal.textureData.textureImageView;
m_pMaterials[i]->textures().metallic.textureData.imageInfo.imageView = m_pMaterials[i]->textures().metallic.textureData.textureImageView;
m_pMaterials[i]->textures().roughness.textureData.imageInfo.imageView = m_pMaterials[i]->textures().roughness.textureData.textureImageView;
m_pMaterials[i]->textures().albedo.textureData.imageInfo.sampler = m_pMaterials[i]->textures().albedo.textureData.textureSampler;
m_pMaterials[i]->textures().normal.textureData.imageInfo.sampler = m_pMaterials[i]->textures().normal.textureData.textureSampler;
m_pMaterials[i]->textures().metallic.textureData.imageInfo.sampler = m_pMaterials[i]->textures().metallic.textureData.textureSampler;
m_pMaterials[i]->textures().roughness.textureData.imageInfo.sampler = m_pMaterials[i]->textures().roughness.textureData.textureSampler;
VkDescriptorBufferInfo lightBufferInfo = {};
lightBufferInfo.buffer = m_vkLightUniformBuffer;
lightBufferInfo.offset = 0;
lightBufferInfo.range = sizeof(CLight::LightProperties) * m_pLights.size();
std::vector<VkWriteDescriptorSet> writeDescriptorSets = {
vks::initializers::writeDescriptorSet(m_vkDescriptorSets[i], VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, &bufferInfo),
vks::initializers::writeDescriptorSet(m_vkDescriptorSets[i], VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, &m_pMaterials[i]->textures().albedo.textureData.imageInfo),
vks::initializers::writeDescriptorSet(m_vkDescriptorSets[i], VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 2, &m_pMaterials[i]->textures().normal.textureData.imageInfo),
vks::initializers::writeDescriptorSet(m_vkDescriptorSets[i], VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 3, &m_pMaterials[i]->textures().metallic.textureData.imageInfo),
vks::initializers::writeDescriptorSet(m_vkDescriptorSets[i], VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 4, &m_pMaterials[i]->textures().roughness.textureData.imageInfo),
vks::initializers::writeDescriptorSet(m_vkDescriptorSets[i], VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 5, &lightBufferInfo)
};
vkUpdateDescriptorSets(
m_pIntegration->device(),
static_cast<uint32_t>(writeDescriptorSets.size()),
writeDescriptorSets.data(), 0,
nullptr);
}
return result;
}
VkResult Dodo::Rendering::CRenderer::UpdateCommandBuffers()
{
VkResult result = VK_ERROR_INITIALIZATION_FAILED;
for (size_t i = 0; i < m_vkCommandBuffers.size(); i++)
{
VkCommandBufferBeginInfo beginInfo = {};
beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
beginInfo.flags = VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT;
beginInfo.pInheritanceInfo = nullptr;
result = vkBeginCommandBuffer(m_vkCommandBuffers[i], &beginInfo);
CError::CheckError<VkResult>(result);
VkRenderPassBeginInfo renderPassInfo = {};
renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
renderPassInfo.renderPass = m_vkRenderPass;
renderPassInfo.framebuffer = m_vkSwapChainFramebuffers[i];
renderPassInfo.renderArea.offset = { 0, 0 };
renderPassInfo.renderArea.extent = m_vkSwapChainExtent;
std::array<VkClearValue, 2> clearValues = {};
clearValues[0].color = { 0.2f, 0.2f, 0.2f, 1.0f };
clearValues[1].depthStencil = { 1.0f, 0 };
renderPassInfo.clearValueCount = clearValues.size();
renderPassInfo.pClearValues = clearValues.data();
vkCmdBeginRenderPass(m_vkCommandBuffers[i], &renderPassInfo, VK_SUBPASS_CONTENTS_INLINE);
vkCmdBindPipeline(m_vkCommandBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, m_vkGraphicsPipeline);
if (m_pGui->uiSettings.displayModels)
{
VkBuffer *vertexBuffers = new VkBuffer[m_matDataBuffers.size()];
VkDeviceSize offsets[1] = { 0 };
for (int j = 0; j < m_pMeshes.size(); j++)
{
vertexBuffers[j] = m_matDataBuffers[j].vertexBuffer;
vkCmdBindVertexBuffers(m_vkCommandBuffers[i], 0, 1, &m_matDataBuffers[j].vertexBuffer, offsets); // evtl buggy bei mehreren vertex buffern
vkCmdBindIndexBuffer(m_vkCommandBuffers[i], m_pMeshes[j]->m_dataBuffers.indexBuffer, 0, VK_INDEX_TYPE_UINT32);
vkCmdBindDescriptorSets(m_vkCommandBuffers[i],
VK_PIPELINE_BIND_POINT_GRAPHICS,
m_vkPipelineLayout,
0,
1,
&m_vkDescriptorSets[j],
0,
nullptr);
Vector3f pos = m_pMeshes[j]->entity->GetComponent<Components::CTransform>()->getPosition();
vkCmdPushConstants(m_vkCommandBuffers[i], m_vkPipelineLayout, VK_SHADER_STAGE_VERTEX_BIT, 0, sizeof(Math::Vector3f), &pos);
float f = 0.5f;
//m_pMeshes[0]->entity->GetComponent<Components::CMaterial>()->setPushConstants(1.0f, 0.0f, 1.0f, 1.0f, 1.0f);
//m_pMeshes[1]->entity->GetComponent<Components::CMaterial>()->setPushConstants(0.0f, 0.8f, 1.0f, 1.0f, 1.0f);
CMaterial::PushConsts pushConsts = m_pMaterials[j]->entity->GetComponent<Components::CMaterial>()->pushConstants();
pushConsts.roughness = m_pGui->uiSettings.roughness;
pushConsts.metallic = m_pGui->uiSettings.metallic;
vkCmdPushConstants(m_vkCommandBuffers[i], m_vkPipelineLayout, VK_SHADER_STAGE_FRAGMENT_BIT, sizeof(Vector3f), sizeof(CMaterial::PushConsts), &pushConsts);
vkCmdDrawIndexed(m_vkCommandBuffers[i], m_pMeshes[j]->m_indices.size(), 1, 0, 0, 0);
}
}
vkCmdEndRenderPass(m_vkCommandBuffers[i]);
result = vkEndCommandBuffer(m_vkCommandBuffers[i]);
CError::CheckError<VkResult>(result);
}
return result;
}
VkResult Dodo::Rendering::CRenderer::CreateBuffer(VkDeviceSize _size, VkBufferUsageFlags _usage, VkMemoryPropertyFlags _properties, VkBuffer &_buffer, VkDeviceMemory &_bufferMemory)
{
VkResult result = VK_ERROR_INITIALIZATION_FAILED;
VkBufferCreateInfo bufferInfo = {};
bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
bufferInfo.size = _size;
bufferInfo.usage = _usage;
bufferInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
result = vkCreateBuffer(m_pIntegration->device(), &bufferInfo, nullptr, &_buffer);
CError::CheckError<VkResult>(result);
VkMemoryRequirements memRequirements;
vkGetBufferMemoryRequirements(m_pIntegration->device(), _buffer, &memRequirements);
VkMemoryAllocateInfo allocInfo = {};
allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
allocInfo.allocationSize = memRequirements.size;
allocInfo.memoryTypeIndex = m_pIntegration->FindMemoryType(
memRequirements.memoryTypeBits, _properties);
result = vkAllocateMemory(m_pIntegration->device(), &allocInfo, nullptr, &_bufferMemory);
CError::CheckError<VkResult>(result);
vkBindBufferMemory(m_pIntegration->device(), _buffer, _bufferMemory, 0);
return result;
}
VkResult Dodo::Rendering::CRenderer::CreateImage(uint32_t width, uint32_t height, VkFormat format, VkImageTiling tiling, VkImageUsageFlags usage, VkMemoryPropertyFlags properties, VkImage & image, VkDeviceMemory & imageMemory)
{
VkResult result = VK_ERROR_INITIALIZATION_FAILED;
VkImageCreateInfo imageInfo = {};
imageInfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
imageInfo.imageType = VK_IMAGE_TYPE_2D;
imageInfo.extent.width = width;
imageInfo.extent.height = height;
imageInfo.extent.depth = 1;
imageInfo.mipLevels = 1;
imageInfo.arrayLayers = 1;
imageInfo.format = format;
imageInfo.tiling = tiling;
imageInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
imageInfo.usage = usage;
imageInfo.samples = VK_SAMPLE_COUNT_1_BIT;
imageInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
imageInfo.flags = 0; // Optional
result = vkCreateImage(m_pIntegration->device(), &imageInfo, nullptr, &image);
CError::CheckError<VkResult>(result);
VkMemoryRequirements memRequirements;
vkGetImageMemoryRequirements(m_pIntegration->device(), image, &memRequirements);
VkMemoryAllocateInfo allocInfo = {};
allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
allocInfo.allocationSize = memRequirements.size;
allocInfo.memoryTypeIndex = m_pIntegration->FindMemoryType(memRequirements.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
result = vkAllocateMemory(m_pIntegration->device(), &allocInfo, nullptr, &imageMemory);
CError::CheckError<VkResult>(result);
vkBindImageMemory(
m_pIntegration->device(),
image,
imageMemory,
0);
return result;
}
VkResult Dodo::Rendering::CRenderer::TransitionImageLayout(VkImage image, VkFormat format, VkImageLayout oldLayout, VkImageLayout newLayout)
{
VkResult result = VK_SUCCESS;
VkCommandBuffer commandBuffer = BeginSingleTimeCommands();
VkImageMemoryBarrier barrier = {};
barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
barrier.oldLayout = oldLayout;
barrier.newLayout = newLayout;
barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.image = image;
if (newLayout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL)
{
barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
if (HasStencilComponent(format))
{
barrier.subresourceRange.aspectMask |= VK_IMAGE_ASPECT_STENCIL_BIT;
}
}
else
{
barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
}
barrier.subresourceRange.baseMipLevel = 0;
barrier.subresourceRange.levelCount = 1;
barrier.subresourceRange.baseArrayLayer = 0;
barrier.subresourceRange.layerCount = 1;
VkPipelineStageFlags sourceStage;
VkPipelineStageFlags destinationStage;
if (oldLayout == VK_IMAGE_LAYOUT_UNDEFINED && newLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL)
{
barrier.srcAccessMask = 0;
barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
sourceStage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
destinationStage = VK_PIPELINE_STAGE_TRANSFER_BIT;
}
else if (oldLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL && newLayout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL)
{
barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
sourceStage = VK_PIPELINE_STAGE_TRANSFER_BIT;
destinationStage = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
}
else if (oldLayout == VK_IMAGE_LAYOUT_UNDEFINED && newLayout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL)
{
barrier.srcAccessMask = 0;
barrier.dstAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
sourceStage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
destinationStage = VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT;
}
else
{
throw std::invalid_argument("unsupported layout transition!");
}
vkCmdPipelineBarrier(
commandBuffer,
sourceStage, destinationStage,
0,
0, nullptr,
0, nullptr,
1, &barrier
);
EndSingleTimeCommands(commandBuffer);
return result;
}
VkResult Dodo::Rendering::CRenderer::CopyBufferToImage(VkBuffer _buffer, VkImage _image, uint32_t _width, uint32_t _height)
{
VkResult result = VK_SUCCESS;
VkCommandBuffer commandBuffer = BeginSingleTimeCommands();
VkBufferImageCopy region = {};
region.bufferOffset = 0;
region.bufferRowLength = 0;
region.bufferImageHeight = 0;
region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
region.imageSubresource.mipLevel = 0;
region.imageSubresource.baseArrayLayer = 0;
region.imageSubresource.layerCount = 1;
region.imageOffset = { 0, 0, 0 };
region.imageExtent = {
_width,
_height,
1
};
vkCmdCopyBufferToImage(
commandBuffer,
_buffer,
_image,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
1,
®ion);
EndSingleTimeCommands(commandBuffer);
return result;
}
VkResult Dodo::Rendering::CRenderer::CopyBuffer(VkBuffer _srcBuffer, VkBuffer _dstBuffer, VkDeviceSize _size)
{
VkResult result = VK_ERROR_INITIALIZATION_FAILED;
VkCommandBuffer commandBuffer = BeginSingleTimeCommands();
VkBufferCopy copyRegion = {};
copyRegion.srcOffset = 0;
copyRegion.dstOffset = 0;
copyRegion.size = _size;
vkCmdCopyBuffer(commandBuffer, _srcBuffer, _dstBuffer, 1, ©Region);
EndSingleTimeCommands(commandBuffer);
return result;
}
VkCommandBuffer Dodo::Rendering::CRenderer::BeginSingleTimeCommands()
{
VkCommandBufferAllocateInfo allocInfo = {};
allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
allocInfo.commandPool = m_vkCommandPool;
allocInfo.commandBufferCount = 1;
VkCommandBuffer commandBuffer;
vkAllocateCommandBuffers(m_pIntegration->device(), &allocInfo, &commandBuffer);
VkCommandBufferBeginInfo beginInfo = {};
beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
vkBeginCommandBuffer(commandBuffer, &beginInfo);
return commandBuffer;
}
void Dodo::Rendering::CRenderer::EndSingleTimeCommands(VkCommandBuffer _buf)
{
vkEndCommandBuffer(_buf);
VkSubmitInfo submitInfo = {};
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &_buf;
vkQueueSubmit(m_pIntegration->queues().graphicsQueue, 1, &submitInfo, VK_NULL_HANDLE);
vkQueueWaitIdle(m_pIntegration->queues().graphicsQueue);
vkFreeCommandBuffers(m_pIntegration->device(), m_vkCommandPool, 1, &_buf);
}
VkResult Dodo::Rendering::CRenderer::UpdateUniformBuffer()
{
VkResult result = VK_ERROR_INITIALIZATION_FAILED;
static auto startTime = std::chrono::high_resolution_clock::now();
auto currentTime = std::chrono::high_resolution_clock::now();
float time = std::chrono::duration<float, std::chrono::seconds::period>(currentTime - startTime).count();
m_dDeltaTime = time;
for (int i = 0; i < m_pTransforms.size(); i++)
{
CMaterial::UniformBufferObject ubo = {};
if (m_pTransforms[i] != nullptr)
{
ubo.model = m_pTransforms[i]->getComposed();
}
else
{
ubo.model = glm::rotate(glm::mat4(1.0f), time * glm::radians(90.0f), glm::vec3(0.0f, 0.0f, 1.0f));
}
ubo.camPos = m_pCamera->cameraPos;
ubo.View = m_pCamera->getViewMatrix();
ubo.projection = m_pCamera->getProjectionMatrix();
ubo.projection[1][1] *= -1;
void* data;
vkMapMemory(m_pIntegration->device(), m_vkUniformBuffersMemory[i], 0, sizeof(ubo), 0, &data);
memcpy(data, &ubo, sizeof(ubo));
vkUnmapMemory(m_pIntegration->device(), m_vkUniformBuffersMemory[i]);
}
std::vector<Components::CLight::LightProperties> props = {};
for (auto& l : m_pLights)
{
props.push_back(l->GetProperties());
}
props[0].position = Vector4f(0.0f, 0.0f, time, 1.0f);
void* data;
result = vkMapMemory(m_pIntegration->device(), m_vkLightUniformBufferMemory, 0, sizeof(Components::CLight::LightProperties) * props.size(), 0, &data);
memcpy(data, props.data(), sizeof(Components::CLight::LightProperties) * props.size());
vkUnmapMemory(m_pIntegration->device(), m_vkLightUniformBufferMemory);
return VK_SUCCESS;
}
VkResult Dodo::Rendering::CRenderer::CleanupSwapChain()
{
VkResult result = VK_ERROR_INITIALIZATION_FAILED;
vkDestroyImageView(m_pIntegration->device(), m_vkDepthImageView, nullptr);
vkDestroyImage(m_pIntegration->device(), m_vkDepthImage, nullptr);
vkFreeMemory(m_pIntegration->device(), m_vkDepthImageMemory, nullptr);
for (size_t i = 0; i < m_vkSwapChainFramebuffers.size(); i++)
{
vkDestroyFramebuffer(m_pIntegration->device(), m_vkSwapChainFramebuffers[i], nullptr);
}
vkFreeCommandBuffers(m_pIntegration->device(), m_vkCommandPool, m_vkCommandBuffers.size(), m_vkCommandBuffers.data());
vkDestroyPipeline(m_pIntegration->device(), m_vkGraphicsPipeline, nullptr);
vkDestroyPipelineLayout(m_pIntegration->device(), m_vkPipelineLayout, nullptr);
vkDestroyRenderPass(m_pIntegration->device(), m_vkRenderPass, nullptr);
for (size_t i = 0; i < m_vkSwapChainImageViews.size(); i++)
{
vkDestroyImageView(m_pIntegration->device(), m_vkSwapChainImageViews[i], nullptr);
}
vkDestroySwapchainKHR(m_pIntegration->device(), m_vkSwapChain, nullptr);
for (size_t i = 0; i < m_pTransforms.size(); i++)
{
vkDestroyBuffer(m_pIntegration->device(), m_vkUniformBuffers[i], nullptr);
vkFreeMemory(m_pIntegration->device(), m_vkUniformBuffersMemory[i], nullptr);
}
vkDestroyDescriptorPool(m_pIntegration->device(), m_vkDescriptorPool, nullptr);
return result;
}
VkResult Dodo::Rendering::CRenderer::RecreateSwapChain()
{
VkResult result = VK_ERROR_INITIALIZATION_FAILED;
int width = 0, height = 0;
while (width == 0 || height == 0)
{
glfwGetFramebufferSize(m_pWindow->GetWindow(), &width, &height);
glfwWaitEvents();
}
result = vkDeviceWaitIdle(m_pIntegration->device());
CError::CheckError<VkResult>(result);
CleanupSwapChain();
CreateSwapChain();
CreateImageViews();
CreateRenderPass();
CreateGraphicsPipeline();
CreateDepthResources();
CreateFramebuffers();
m_pGui->CreateFramebuffers(m_vkSwapChainImageViews, m_vkDepthImageView, m_vkSwapChainExtent);
m_pSkybox->SetRenderPass(m_vkRenderPass);
m_pSkybox->SetExtent(m_vkSwapChainExtent);
m_pSkybox->CreatePipeline();
CreateUniformBuffers();
CreateDescriptorPool();
CreateDescriptorSets();
CreateCommandBuffers();
return result;
}
Dodo::Rendering::CRenderer::SwapChainSupportDetails Dodo::Rendering::CRenderer::QuerySwapChainSupport()
{
SwapChainSupportDetails details = {};
// Get capabilities
VkResult result = vkGetPhysicalDeviceSurfaceCapabilitiesKHR(m_pIntegration->physicalDevice(),
m_pIntegration->surface(),
&details.capabilities);
CError::CheckError<VkResult>(result);
// Get formats
uint32_t formatCount = 0;
result = vkGetPhysicalDeviceSurfaceFormatsKHR(m_pIntegration->physicalDevice(),
m_pIntegration->surface(),
&formatCount,
nullptr);
if (formatCount != 0)
{
details.formats.resize(formatCount);
result = vkGetPhysicalDeviceSurfaceFormatsKHR(m_pIntegration->physicalDevice(),
m_pIntegration->surface(),
&formatCount,
details.formats.data());
}
CError::CheckError<VkResult>(result);
// Get present modes
uint32_t presentModeCount = 0;
result = vkGetPhysicalDeviceSurfacePresentModesKHR(m_pIntegration->physicalDevice(),
m_pIntegration->surface(),
&presentModeCount,
nullptr);
if (presentModeCount != 0)
{
details.presentModes.resize(presentModeCount);
result = vkGetPhysicalDeviceSurfacePresentModesKHR(m_pIntegration->physicalDevice(),
m_pIntegration->surface(),
&presentModeCount,
details.presentModes.data());
}
CError::CheckError<VkResult>(result);
return details;
}
VkSurfaceFormatKHR Dodo::Rendering::CRenderer::ChooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& _availableFormats)
{
if (_availableFormats.size() == 1 && _availableFormats[0].format == VK_FORMAT_UNDEFINED)
{
return{ VK_FORMAT_B8G8R8A8_UNORM, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR };
}
for (const auto& availableFormat : _availableFormats)
{
if (availableFormat.format == VK_FORMAT_B8G8R8A8_UNORM && availableFormat.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR)
{
return availableFormat;
}
}
return _availableFormats[0];
}
VkPresentModeKHR Dodo::Rendering::CRenderer::ChooseSwapPresentMode(const std::vector<VkPresentModeKHR> _availablePresentModes)
{
VkPresentModeKHR bestMode = VK_PRESENT_MODE_FIFO_KHR;
for (const auto& availablePresentMode : _availablePresentModes)
{
if (availablePresentMode == VK_PRESENT_MODE_MAILBOX_KHR)
{
return availablePresentMode;
}
else if (availablePresentMode == VK_PRESENT_MODE_IMMEDIATE_KHR)
{
bestMode = availablePresentMode;
}
}
return bestMode;
}
VkExtent2D Dodo::Rendering::CRenderer::ChooseSwapExtent(const VkSurfaceCapabilitiesKHR & _capabilities)
{
if (_capabilities.currentExtent.width != std::numeric_limits<uint32_t>::max() /*UINT32_MAX*/)
{
return _capabilities.currentExtent;
}
else
{
int width, height;
glfwGetFramebufferSize(m_pWindow->GetWindow(), &width, &height);
VkExtent2D actualExtent = { static_cast<uint32_t>(width), static_cast<uint32_t>(height) };
actualExtent.width = glm::max(_capabilities.minImageExtent.width, glm::min(_capabilities.maxImageExtent.width, actualExtent.width));
actualExtent.height = glm::max(_capabilities.minImageExtent.height, glm::min(_capabilities.maxImageExtent.height, actualExtent.height));
return actualExtent;
}
}
VkFormat Dodo::Rendering::CRenderer::FindSupportedFormat(const std::vector<VkFormat>& _candidates, VkImageTiling _tiling, VkFormatFeatureFlags _features)
{
for (VkFormat format : _candidates)
{
VkFormatProperties props;
vkGetPhysicalDeviceFormatProperties(m_pIntegration->physicalDevice(), format, &props);
if (_tiling == VK_IMAGE_TILING_LINEAR && (props.linearTilingFeatures & _features) == _features)
{
return format;
}
else if (_tiling == VK_IMAGE_TILING_OPTIMAL && (props.optimalTilingFeatures & _features) == _features)
{
return format;
}
}
CLog::Error("Couldnt find supported format");
return VK_FORMAT_END_RANGE;
}
| 36.87244 | 226 | 0.786162 | TKscoot |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.