hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13 values | lang stringclasses 1 value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 109 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 48.5k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
c0ee1c369e61032ba700744bab4cf75213db36d0 | 9,752 | cpp | C++ | sourceCode/dotNet4.6/vb/language/vbhosted/vbhosted/vbhostedcompiler.cpp | csoap/csoap.github.io | 2a8db44eb63425deff147652b65c5912f065334e | [
"Apache-2.0"
] | 5 | 2017-03-03T02:13:16.000Z | 2021-08-18T09:59:56.000Z | sourceCode/dotNet4.6/vb/language/vbhosted/vbhosted/vbhostedcompiler.cpp | 295007712/295007712.github.io | 25241dbf774427545c3ece6534be6667848a6faf | [
"Apache-2.0"
] | null | null | null | sourceCode/dotNet4.6/vb/language/vbhosted/vbhosted/vbhostedcompiler.cpp | 295007712/295007712.github.io | 25241dbf774427545c3ece6534be6667848a6faf | [
"Apache-2.0"
] | 4 | 2016-11-15T05:20:12.000Z | 2021-11-13T16:32:11.000Z | #include "stdafx.h"
VbHostedCompiler::VbHostedCompiler(gcroot<System::Collections::Generic::IList<System::Reflection::Assembly ^>^> referenceAssemblies)
:
m_fInit(false),
m_referenceAssemblies(gcnew System::Collections::Generic::List<System::Reflection::Assembly ^>(referenceAssemblies)),
m_ErrorTable()
{
}
VbHostedCompiler::~VbHostedCompiler()
{
if(m_spVbCompilerProject)
{
m_spVbCompilerProject->Disconnect();
}
if (m_spVbExternalCompilerProject)
{
m_spVbExternalCompilerProject->Disconnect();
}
}
STDMETHODIMP VbHostedCompiler::InitCompiler()
{
HRESULT hr = S_OK;
if (!m_fInit)
{
ASSERT(!m_spVbCompiler, "[VbHostedCompiler::InitCompiler] 'm_spVbCompiler' member is not NULL");
ASSERT(!m_spVbCompilerHost, "[VbHostedCompiler::InitCompiler] 'm_spVbCompilerHost' member is not NULL");
ASSERT(!m_spVbCompilerProject, "[VbHostedCompiler::InitCompiler] 'm_spVbCompilerProject' member is not NULL");
ASSERT(!m_pCompilerProject, "[VbHostedCompiler::InitCompiler] 'm_pCompilerProject' member is not NULL");
IfFailGo(VbCompilerHost::Create(&m_spVbCompilerHost));
IfFailGo(GetCompiler());
IfFailGo(SetupCompilerProject(&m_ErrorTable));
IfFailGo(CreateExternalCompilerProject());
m_fInit = true;
}
Error:
if (FAILED(hr))
{
m_spVbCompilerHost = NULL;
m_spVbCompiler = NULL;
}
return hr;
}
STDMETHODIMP VbHostedCompiler::CompileExpression
(
BSTR Expression,
VbContext* pContext,
gcroot<System::Type ^> TargetType,
VbParsed *pParsed
)
{
// Asserts are NOT necessary since the Verify* macros all invoke VSFAIL which is a VSASSERT wrapper.
VerifyInPtr(Expression, "[VbHostedCompiler::CompileExpression] 'Expression' parameter is null");
VerifyParamCond(SysStringLen(Expression) > 0, E_INVALIDARG, "[VbHostedCompiler::CompileExpression] 'Expression' parameter is zero length string");
VerifyInPtr(pContext, "[VbHostedCompiler::CompileExpression] 'pContext' parameter is null");
VerifyInPtr(pParsed, "[VbHostedCompiler::CompileExpression] 'pParsed' parameter is null");
VB_ENTRY();
IfFailGo(InitCompiler());
pParsed->SetSharedErrorTable(&m_ErrorTable);
if (!m_ErrorTable.HasErrors())
{
VBHostedSession session(Expression, m_spVbCompiler, m_spVbCompilerHost, m_spVbCompilerProject, m_pExternalCompilerProject, pContext, TargetType);
pParsed->GetErrorTable()->Init(m_pCompiler, m_pCompilerProject, NULL);
IfFailGo(session.CompileExpression(pParsed));
}
g_pvbNorlsManager->GetPageHeap().ShrinkUnusedResources();
VB_EXIT_LABEL();
}
STDMETHODIMP VbHostedCompiler::CompileStatements
(
BSTR Statements,
VbContext* pContext,
VbParsed *pParsed
)
{
// Asserts are NOT necessary since the Verify* macros all invoke VSFAIL which is a VSASSERT wrapper.
VerifyInPtr(Statements, "[VbHostedCompiler::CompileStatements] 'Statements' parameter is null");
VerifyParamCond(SysStringLen(Statements) > 0, E_INVALIDARG, "[VbHostedCompiler::CompileStatements] 'Statements' parameter is zero length string");
VerifyInPtr(pContext, "[VbHostedCompiler::CompileStatements] 'pContext' parameter is null");
VerifyInPtr(pParsed, "[VbHostedCompiler::CompileStatements] 'pParsed' parameter is null");
VB_ENTRY();
IfFailGo(InitCompiler());
pParsed->SetSharedErrorTable(&m_ErrorTable);
if (!m_ErrorTable.HasErrors())
{
VBHostedSession session(Statements, m_spVbCompiler, m_spVbCompilerHost, m_spVbCompilerProject, m_pExternalCompilerProject, pContext, nullptr);
pParsed->GetErrorTable()->Init(m_pCompiler, m_pCompilerProject, NULL);
IfFailGo(session.CompileStatements(pParsed));
}
VB_EXIT_LABEL();
}
STDMETHODIMP VbHostedCompiler::GetCompiler()
{
HRESULT hr = S_OK;
CompilerHost *pCompilerHost = NULL; // Don't need to manage lifetime of pCompilerHost as it is controlled by pCompiler.
// Create the compiler, this will have references to the default libraries
IfFailGo(VBCreateBasicCompiler(false, DelayLoadUICallback, m_spVbCompilerHost, &m_spVbCompiler));
m_pCompiler = (Compiler *)((IVbCompiler*)m_spVbCompiler);
//"Compile" the mscorlib project
if(m_pCompiler->FindCompilerHost(m_spVbCompilerHost, &pCompilerHost) && pCompilerHost && pCompilerHost->GetComPlusProject())
{
IfTrueGo(pCompilerHost->GetComPlusProject()->Compile(), E_FAIL);
}
else
{
ASSERT(pCompilerHost, "Could not get Compiler Host");
ASSERT(!pCompilerHost, "Could not get mscorlib's project");
IfFailGo(E_FAIL);
}
Error:
return hr;
}
STDMETHODIMP VbHostedCompiler::SetupCompilerProject(ErrorTable *pErrorTable)
{
// Asserts are NOT necessary since the Verify* macros all invoke VSFAIL which is a VSASSERT wrapper.
VerifyInPtr(pErrorTable, "[VBHostedSession::SetupCompilerProject] 'pErrorTable' parameter is null");
ASSERT(m_spVbCompilerHost, "[VBHostedSession::SetupCompilerProject] 'm_spVbCompilerHost' is null");
ASSERT(m_spVbCompiler, "[VBHostedSession::SetupCompilerProject] 'm_spVbCompiler' is null");
HRESULT hr = S_OK;
IfFailGo(CreateCompilerProject());
IfFailGo(InitializeCompilerProject(pErrorTable));
// Ensure that all the projects (in particular mscorlib and the VB runtime
// have been compiled at least to CS_Bound).
//
IfFailGo(m_pCompiler->CompileToBound(
m_pCompilerProject->GetCompilerHost(),
NULL, // ULONG *pcWarnings
NULL, // ULONG *pcErrors,
NULL // VbError **ppErrors
));
Error:
return hr;
}
STDMETHODIMP VbHostedCompiler::CreateCompilerProject()
{
ASSERT(m_spVbCompilerHost, "[VBHostedSession::CreateCompilerProject] 'm_spVbCompilerHost' is null");
ASSERT(m_spVbCompiler, "[VBHostedSession::CreateCompilerProject] 'm_spVbCompiler' is null");
ASSERT(!m_spVbCompilerProject, "[VBHostedSession::CreateCompilerProject] 'm_spVbCompilerProject' is not null");
ASSERT(!m_pCompilerProject, "[VBHostedSession::CreateCompilerProject] 'm_pCompilerProject' is not null");
HRESULT hr = S_OK;
// Add System.Core.dll as it is required for DLR tree conversion
//
{
// Register the compiler host to get access to the underlying "CompierHost"
// object before the project is created so that System.Core can also be
// added to the list of standard libraries and thus found using the
// FX search paths and added as a reference to the project when it
// is created.
//
IfFailGo(m_pCompiler->RegisterVbCompilerHost(m_spVbCompilerHost));
CompilerHost *CompilerHost = NULL;
IfFalseGo(m_pCompiler->FindCompilerHost(m_spVbCompilerHost, &CompilerHost), E_UNEXPECTED);
ThrowIfNull(CompilerHost);
DynamicArray<STRING *> *StdLibs = CompilerHost->GetStandardLibraries();
ThrowIfNull(StdLibs);
STRING **StdLibsArray = StdLibs->Array();
// Add to the list only if not already present.
STRING *SystemCoreDLL = m_pCompiler->AddString(L"System.Core.dll");
for(unsigned i = 0; i < StdLibs->Count(); i++)
{
if (StringPool::IsEqual(StdLibsArray[i] , SystemCoreDLL)) break;
}
if (i == StdLibs->Count())
{
StdLibs->AddElement(SystemCoreDLL);
}
}
// Create our default project.
IfFailGo(m_spVbCompiler->CreateProject
(
L"vbhost",
m_spVbCompiler,
NULL,
m_spVbCompilerHost,
&m_spVbCompilerProject
));
m_pCompilerProject = (CompilerProject*)m_spVbCompilerProject.p;
Error:
return hr;
}
STDMETHODIMP VbHostedCompiler::InitializeCompilerProject(ErrorTable *pErrorTable)
{
// Asserts are NOT necessary since the Verify* macros all invoke VSFAIL which is a VSASSERT wrapper.
VerifyInPtr(pErrorTable, "[VBHostedSession::InitializeCompilerProject] 'pErrorTable' parameter is null");
ASSERT(m_pCompiler, "[VBHostedSession::InitializeCompilerProject] 'm_pCompiler' is null");
ASSERT(m_spVbCompilerProject, "[VBHostedSession::InitializeCompilerProject] 'm_spVbCompilerProject' is null");
HRESULT hr = S_OK;
// Must initialize errortable before calling SetAssemblyRefs so that failures encountered when processing
// the assembly references are captured correctly.
pErrorTable->Init(m_pCompiler, m_pCompilerProject, NULL);
m_pCompilerProject->AddStandardLibraries();
IfFailGo(VbContext::SetAssemblyRefs(m_referenceAssemblies, m_pCompiler, m_spVbCompilerProject, pErrorTable));
//Need to set the options to something so that the project will be compiled to bound.
IfFailGo(VbContext::SetDefaultOptions(m_spVbCompilerProject));
Error:
return hr;
}
STDMETHODIMP VbHostedCompiler::CreateExternalCompilerProject()
{
ASSERT(m_spVbCompilerHost, "[VBHostedSession::CreateExternalCompilerProject] 'm_spVbCompilerHost' is null");
ASSERT(m_spVbCompiler, "[VBHostedSession::CreateExternalCompilerProject] 'm_spVbCompiler' is null");
ASSERT(!m_spVbExternalCompilerProject, "[VBHostedSession::CreateExternalCompilerProject] 'm_spVbExternalCompilerProject' is not null");
ASSERT(!m_pExternalCompilerProject, "[VBHostedSession::CreateExternalCompilerProject] 'm_pExternalCompilerProject' is not null");
HRESULT hr = S_OK;
//Create the Type Scope Project
IfFailGo(m_pCompilerProject->AddTypeScopeReference(&m_pExternalCompilerProject));
m_spVbExternalCompilerProject = m_pExternalCompilerProject;
Error:
return hr;
}
| 35.591241 | 153 | 0.717904 | csoap |
c0ef5d287b39ace47f4b993c1bf516a59d9491e7 | 1,072 | cpp | C++ | test/test_large_messages.cpp | bripage/ygm | 6ef1a47b90474947ee751afe3a60eabfb20d4c0c | [
"MIT-0",
"MIT"
] | 10 | 2020-03-06T17:56:42.000Z | 2022-01-10T01:24:07.000Z | test/test_large_messages.cpp | bripage/ygm | 6ef1a47b90474947ee751afe3a60eabfb20d4c0c | [
"MIT-0",
"MIT"
] | 31 | 2021-04-13T23:08:13.000Z | 2022-03-29T21:40:21.000Z | test/test_large_messages.cpp | bripage/ygm | 6ef1a47b90474947ee751afe3a60eabfb20d4c0c | [
"MIT-0",
"MIT"
] | 10 | 2021-02-02T23:15:11.000Z | 2021-11-10T17:43:47.000Z | // Copyright 2019-2021 Lawrence Livermore National Security, LLC and other YGM
// Project Developers. See the top-level COPYRIGHT file for details.
//
// SPDX-License-Identifier: MIT
#undef NDEBUG
#include <ygm/comm.hpp>
#include <ygm/detail/ygm_ptr.hpp>
int main(int argc, char** argv) {
// Create comm for very small messages
ygm::comm world(&argc, &argv, 8);
// Test Rank 0 large message to all ranks
{
size_t large_msg_size = 1024;
size_t counter{};
ygm::ygm_ptr<size_t> pcounter(&counter);
if (world.rank() == 0) {
std::vector<size_t> large_msg(large_msg_size);
for (int dest = 0; dest < world.size(); ++dest) {
// Count elements in large message's vector
world.async(
dest,
[](auto pcomm, int from, auto pcounter,
const std::vector<size_t>& vec) {
for (size_t i = 0; i < vec.size(); ++i) { (*pcounter)++; }
},
pcounter, large_msg);
}
}
world.barrier();
ASSERT_RELEASE(counter == large_msg_size);
}
return 0;
}
| 27.487179 | 78 | 0.600746 | bripage |
c0f144f7483c32df2ae92bd5d203fc3d3e4185ad | 1,218 | cpp | C++ | signal-slot-benchmarks/benchmark/cpp/benchmark_nod.cpp | qubka/signals | 6bd39c662ab2b1e0caafc5a4c4510a74fb9f9e1c | [
"MIT"
] | 181 | 2020-01-17T13:49:59.000Z | 2022-03-17T03:23:12.000Z | signal-slot-benchmarks/benchmark/cpp/benchmark_nod.cpp | qubka/signals | 6bd39c662ab2b1e0caafc5a4c4510a74fb9f9e1c | [
"MIT"
] | 22 | 2020-01-16T23:37:02.000Z | 2021-09-08T23:51:12.000Z | signal-slot-benchmarks/benchmark/cpp/benchmark_nod.cpp | qubka/signals | 6bd39c662ab2b1e0caafc5a4c4510a74fb9f9e1c | [
"MIT"
] | 16 | 2020-01-28T15:40:18.000Z | 2022-02-25T08:32:15.000Z | #include "../hpp/benchmark_nod.hpp"
NOINLINE(void Nod::initialize())
{
// NOOP
}
NOINLINE(void Nod::validate_assert(std::size_t N))
{
return Benchmark<Signal, Nod>::validation_assert(N);
}
NOINLINE(double Nod::construction(std::size_t N, std::size_t limit))
{
return Benchmark<Signal, Nod>::construction(N, limit);
}
NOINLINE(double Nod::destruction(std::size_t N, std::size_t limit))
{
return Benchmark<Signal, Nod>::destruction(N, limit);
}
NOINLINE(double Nod::connection(std::size_t N, std::size_t limit))
{
return Benchmark<Signal, Nod>::connection(N, limit);
}
NOINLINE(double Nod::disconnect(std::size_t N, std::size_t limit))
{
return Benchmark<Signal, Nod>::disconnect(N, limit);
}
NOINLINE(double Nod::reconnect(std::size_t N, std::size_t limit))
{
return Benchmark<Signal, Nod>::reconnect(N, limit);
}
NOINLINE(double Nod::emission(std::size_t N, std::size_t limit))
{
return Benchmark<Signal, Nod>::emission(N, limit);
}
NOINLINE(double Nod::combined(std::size_t N, std::size_t limit))
{
return Benchmark<Signal, Nod>::combined(N, limit);
}
NOINLINE(double Nod::threaded(std::size_t N, std::size_t limit))
{
return Benchmark<Signal, Nod>::threaded(N, limit);
}
| 28.325581 | 68 | 0.703612 | qubka |
c0f25d2231d5e519dc15331a1450316114c94a6b | 277 | hpp | C++ | app/raytracing/ScreenRayTracer.hpp | Yousazoe/Solar | 349c75f7a61b1727aa0c6d581cf75124b2502a57 | [
"Apache-2.0"
] | 1 | 2021-08-07T13:02:01.000Z | 2021-08-07T13:02:01.000Z | app/raytracing/ScreenRayTracer.hpp | Yousazoe/Solar | 349c75f7a61b1727aa0c6d581cf75124b2502a57 | [
"Apache-2.0"
] | null | null | null | app/raytracing/ScreenRayTracer.hpp | Yousazoe/Solar | 349c75f7a61b1727aa0c6d581cf75124b2502a57 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include<math/Math3d.hpp>
#include<render/Filter.hpp>
#include<render/Viewport.hpp>
namespace tutorial::graphics
{
class ScreenRayTracer
{
private:
ScreenRayTracer() = delete;
public:
static void draw(Viewport& viewport, ShaderVersion shader);
};
}
| 14.578947 | 61 | 0.736462 | Yousazoe |
c0f68569b69b34722569b76c4d3691968324900c | 392 | cpp | C++ | Chapter08/Exercise58/Exercise58.cpp | Archiit19/The-Cpp-Workshop | ae2f8d0c375d6bcdd7fa5ab9e34370ce83d1f501 | [
"MIT"
] | 4 | 2019-08-12T08:59:46.000Z | 2022-03-08T07:49:29.000Z | Chapter08/Exercise58/Exercise58.cpp | Archiit19/The-Cpp-Workshop | ae2f8d0c375d6bcdd7fa5ab9e34370ce83d1f501 | [
"MIT"
] | null | null | null | Chapter08/Exercise58/Exercise58.cpp | Archiit19/The-Cpp-Workshop | ae2f8d0c375d6bcdd7fa5ab9e34370ce83d1f501 | [
"MIT"
] | 5 | 2019-10-09T17:00:56.000Z | 2022-03-08T07:49:41.000Z | #include <iostream>
#include <string>
using namespace std;
class Track
{
public:
float lengthInSeconds;
string trackName;
Track ()
{
lengthInSeconds = 0.0f;
trackName = "not set";
}
};
int main()
{
Track track;
cout << "Track Name = " << track.trackName << endl;
cout << "Track Length = " << track.lengthInSeconds << endl;
return 0;
}
| 15.076923 | 62 | 0.581633 | Archiit19 |
c0ffe7630a0e5ac395c0e996175645ec04ba8423 | 459 | cpp | C++ | 2021/day22/main.cpp | alexandru-andronache/adventofcode | ee41d82bae8b705818fda5bd43e9962bb0686fec | [
"Apache-2.0"
] | 3 | 2021-07-01T14:31:06.000Z | 2022-03-29T20:41:21.000Z | 2021/day22/main.cpp | alexandru-andronache/adventofcode | ee41d82bae8b705818fda5bd43e9962bb0686fec | [
"Apache-2.0"
] | null | null | null | 2021/day22/main.cpp | alexandru-andronache/adventofcode | ee41d82bae8b705818fda5bd43e9962bb0686fec | [
"Apache-2.0"
] | null | null | null | #include "file.h"
#include "utilities.h"
#include <iostream>
namespace aoc2021_day22 {
int part_1(std::string_view path) {
return 0;
}
int part_2(std::string_view path) {
return 0;
}
}
#ifndef TESTING
int main() {
std::cout << "Part 1: " << aoc2021_day22::part_1("../2021/day22/input.in") << std::endl;
std::cout << "Part 2: " << aoc2021_day22::part_2("../2021/day22/input.in") << std::endl;
return 0;
}
#endif
| 19.956522 | 92 | 0.59695 | alexandru-andronache |
8d06325146b5e2db60d6dbf217774fd60b04e894 | 1,070 | cpp | C++ | code_practice/10/1018_class/3_shared_ptr8.cpp | armkernel/armkernel.github.io | f74b8ddfc8a69dec8b5eeccb4d92c62dcc6c321a | [
"MIT"
] | 2 | 2019-08-06T13:45:02.000Z | 2019-11-06T01:15:30.000Z | code_practice/10/1018_class/3_shared_ptr8.cpp | armkernel/armkernel.github.io | f74b8ddfc8a69dec8b5eeccb4d92c62dcc6c321a | [
"MIT"
] | null | null | null | code_practice/10/1018_class/3_shared_ptr8.cpp | armkernel/armkernel.github.io | f74b8ddfc8a69dec8b5eeccb4d92c62dcc6c321a | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
#include <memory>
using namespace std;
struct People
{
string name;
People(string n) : name(n) {}
~People() { cout << name << " 파괴" << endl; }
//shared_ptr<People> bestFriend; // 참조 계수 증가한다.
// People* bestFriend; // 참조계수가 증가하지 않는다.
weak_ptr<People> bestFriend; // 참조 계수가 증가하지 않는
// 스마트 포인터.
// 장점: 객체 파괴 여부 조사가능
};
int main()
{
shared_ptr<People> sp1 = make_shared<People>("kim");
{
shared_ptr<People> sp2 = make_shared<People>("lee");
sp1->bestFriend = sp2;
sp2->bestFriend = sp1; // weak는 shared랑 호환된다.
}
if (sp1->bestFriend.expired())
{
cout << "객체 파괴됨" << endl; // ??
}
else
{
// 살아 있는 경우..
// cout << sp1->bestFriend->name << endl;
// 접근이 안돼.. => compile error
// shared_ptr 만들어야해
shared_ptr<People> sp = sp1->bestFriend.lock();
if(sp)
{
cout << sp -> name << endl;
}
// weak 는 소유권이 없어
// 안전한 객체 접근을 하기 위해서는 shared_ptr로 변경해야해
// 안전함을 위해서 이렇게 설계
}
}
| 19.454545 | 56 | 0.536449 | armkernel |
8d0b8688a77ee3880255a9027c53e6c69e5e2619 | 9,815 | cpp | C++ | qmovstack.cpp | deepakm/deepquor | 6e7746ad7e9b359ed5b0567c580a97684a76ad12 | [
"BSD-3-Clause"
] | null | null | null | qmovstack.cpp | deepakm/deepquor | 6e7746ad7e9b359ed5b0567c580a97684a76ad12 | [
"BSD-3-Clause"
] | null | null | null | qmovstack.cpp | deepakm/deepquor | 6e7746ad7e9b359ed5b0567c580a97684a76ad12 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2005-2006
* Brent Miller and Charles Morrey. All rights reserved.
*
* See the COPYRIGHT_NOTICE file for terms.
*/
#include "qmovstack.h"
IDSTR("$Id: qmovstack.cpp,v 1.11 2006/07/31 06:25:50 bmiller Exp $");
/****/
/***********************
* class qWallMoveList *
***********************/
qMoveStack::qMoveStack
(const qPosition *pos, qPlayer player2move)
:sp(0)
{
moveStack[sp].resultingPos = *pos;
// moveStack[sp].move = qMove(); Unnecessary
moveStack[sp].wallMovesBlockedByMove.clearList();
moveStack[sp].playerMoved = qPlayer(player2move.getOtherPlayerId());
moveStack[sp].posInfo = NULL;
initWallMoveTable();
}
qMoveStack::~qMoveStack() {
return;
};
/* Good optimizations:
* !!! Prune "dead space" from the list of possible wall moves (well,
* everything after the first "dead" move).
* !!! Keep separate lists for white and black???
*/
void qMoveStack::initWallMoveTable()
{
qPosition pos = moveStack[0].resultingPos;
int rowColNo, posNo;
int rowOrCol;
qMove mv;
qWallMoveInfo *thisMove;
// Can't revise the wallMoveTable with a bunch of state in the stack
if (sp != 0) {
g_assert(sp==0);
return;
}
// 1st pass: construct list of all possible wall moves.
for (rowOrCol=1; rowOrCol >= 0; rowOrCol--)
for (rowColNo=7; rowColNo >= 0; rowColNo--)
for (posNo=7; posNo >= 0; posNo--)
{
mv = qMove(rowOrCol, rowColNo, posNo); // how about mv.qMove(...)???
thisMove = &allWallMoveArry[mv.getEncoding()];
thisMove->move = mv;
thisMove->possible = pos.canPutWall(rowOrCol, rowColNo, posNo);
thisMove->eliminates.clear();
if (thisMove->possible)
possibleWallMoves.push(thisMove);
else
thisMove->next = thisMove->prev = NULL;
}
// 2nd pass: for each possible move, note which future wall moves it blocks
#define MAYBE_ELIMINATE(m) if((m)->possible){thisMove->eliminates.push_back(m);}
for (thisMove=possibleWallMoves.getHead();
thisMove;
thisMove = thisMove->next)
{
mv = thisMove->move;
g_assert(mv.isWallMove());
if (mv.wallPosition()>0)
MAYBE_ELIMINATE(&allWallMoveArry[qMove(mv.wallMoveIsRow(),
mv.wallRowOrColNo(),
mv.wallPosition()-1).getEncoding()]);
if (mv.wallPosition()<7)
MAYBE_ELIMINATE(&allWallMoveArry[qMove(mv.wallMoveIsRow(),
mv.wallRowOrColNo(),
mv.wallPosition()+1).getEncoding()]);
MAYBE_ELIMINATE(&allWallMoveArry[qMove(!mv.wallMoveIsRow(),
mv.wallPosition(),
mv.wallRowOrColNo()).getEncoding()]);
}
}
void qMoveStack::pushMove
(qPlayer playerMoving,
qMove mv,
qPosition *endPos)
{
#define ARRAYSIZE(ARR) (sizeof(ARR)/sizeof((ARR)[0]))
g_assert(sp < ARRAYSIZE(moveStack));
qMoveStackFrame *frame = &moveStack[++sp];
// Record the move
frame->move = mv;
frame->playerMoved = playerMoving;
frame->posInfo = NULL;
// Record the new position
if (endPos)
frame->resultingPos = *endPos;
else
(frame->resultingPos = moveStack[sp-1].resultingPos).applyMove(playerMoving, mv);
if (mv.isPawnMove())
frame->wallMovesBlockedByMove.clearList();
else {
qWallMoveInfo *thisMove, *next;
list<qWallMoveInfo*>::iterator blockedMove;
thisMove = &allWallMoveArry[mv.getEncoding()];
g_assert(thisMove->possible == TRUE);
frame->wallMovesBlockedByMove.clearList();
// Of course, remove the wall placement from possible moves
thisMove->possible = FALSE;
possibleWallMoves.pop(thisMove);
frame->wallMovesBlockedByMove.push(thisMove);
// Remove any other wall move options that are now blocked
for (blockedMove=thisMove->eliminates.begin();
blockedMove != thisMove->eliminates.end();
++blockedMove)
{
if ((*blockedMove)->possible) {
(*blockedMove)->possible = FALSE;
possibleWallMoves.pop(*blockedMove);
frame->wallMovesBlockedByMove.push(*blockedMove);
}
}
}
return;
}
void qMoveStack::popMove
(void)
{
qWallMoveInfo *blockedMove, *next;
qMoveStackFrame *frame = &moveStack[sp--];
// Replace any wall moves that had been blocked by the popped move
while (blockedMove = frame->wallMovesBlockedByMove.pop())
{
blockedMove->possible = TRUE;
// !!! Optimization: we could insert the entire wallMovesBlockedByMove
// list into possibleWallMoves in one segment.
possibleWallMoves.push(blockedMove);
}
return;
}
/***************************
* class qWallMoveInfoList *
***************************/
qWallMoveInfoList::qWallMoveInfoList
(void):
head(NULL), tail(NULL)
{
DEBUG_CODE(numElts = 0;)
return;
}
#ifdef DEBUG
void qWallMoveInfoList::verifyEltCount()
{ // Make sure this mv isn't already in the info list (which will corrupt us)
qWallMoveInfo *tmp = head;
int countedElts = 0;
while (tmp) {
tmp = tmp->next;
countedElts++;
}
g_assert(countedElts == numElts);
}
#endif
void qWallMoveInfoList::push
(qWallMoveInfo *mv)
{
#ifdef DEBUG
{ // Make sure this mv isn't already in the info list (which will corrupt us)
qWallMoveInfo *tmp = head;
while (tmp) {
g_assert(tmp!=mv);
tmp = tmp->next;
}
}
#endif
DEBUG_CODE(verifyEltCount();)
mv->prev = NULL;
mv->next = head;
if (head) {
head->prev = mv;
} else {
tail = mv;
}
head = mv;
DEBUG_CODE(++numElts;)
DEBUG_CODE(verifyEltCount();) //Make sure we didn't break anything
}
void qWallMoveInfoList::pop
(qWallMoveInfo *mv)
{
#ifdef DEBUG
{ // Make sure the mv is actually in the list
qWallMoveInfo *tmp = head;
while (tmp) {
if (tmp==mv)
break;
tmp = tmp->next;
}
g_assert(tmp);
}
#endif
DEBUG_CODE(verifyEltCount();)
if (mv->next) {
mv->next->prev = mv->prev;
} else {
tail = mv->prev;
}
if (mv->prev) {
mv->prev->next = mv->next;
} else {
head = mv->next;
}
DEBUG_CODE(--numElts;)
DEBUG_CODE(verifyEltCount();) //Make sure we didn't break anything
}
qWallMoveInfo *qWallMoveInfoList::pop
(void)
{
DEBUG_CODE(verifyEltCount();)
qWallMoveInfo *rval=head;
if (head) {
head = head->next;
if (head)
head->prev = NULL;
else
tail = NULL;
}
DEBUG_CODE(if (rval) --numElts;)
DEBUG_CODE(verifyEltCount();) //Make sure we didn't break anything
return rval;
};
bool qMoveStack::getPossibleWallMoves(qMoveList *moveList) const
{
if (!moveList)
return FALSE;
qWallMoveInfo *c = possibleWallMoves.getHead();
while (c) {
g_assert(c->possible == TRUE);
moveList->push_back(c->move);
c = c->next;
}
return TRUE;
}
// Funcs that flag positions in the thought sequence (i.e. for evaluating
// moves temporarily rather than actually making them.
// These funcs use the positionHash to flag which moves are under evaluation
//
inline static void setMoveInEval
(qPositionInfo *posInfo, qPlayer playerToMove)
{
if (playerToMove.isWhite())
posInfo->setPositionFlagBits(qPositionInfo::flag_WhiteToMove);
else
posInfo->setPositionFlagBits(qPositionInfo::flag_BlackToMove);
}
inline static void clearMoveInEval
(qPositionInfo *posInfo, qPlayer playerToMove)
{
if (playerToMove.isWhite())
posInfo->clearPositionFlagBits(qPositionInfo::flag_WhiteToMove);
else
posInfo->clearPositionFlagBits(qPositionInfo::flag_BlackToMove);
}
qPositionInfo *qMoveStack::pushEval
(qPositionInfo *startPosInfo, // optimizer
qPositionInfo *endPosInfo, // optimizer
qPositionInfoHash *posHash, // reqd if endPosInfo==NULL or startPosInfo==NULL
qPlayer whoMoved, // From here down same
qMove move, // as pushMove()
qPosition *endPos)
{
g_assert(endPosInfo || posHash);
if (!endPosInfo && !posHash)
return NULL;
g_assert(whoMoved.getPlayerId() == this->getPlayer2Move().getPlayerId());
// 1. Mark position as under evaluation in posInfo w/setMoveInEval()
if (!this->moveStack[sp].posInfo) {
if (startPosInfo)
this->moveStack[sp].posInfo = startPosInfo;
else
this->moveStack[sp].posInfo = posHash->getOrAddElt(this->getPos());
}
g_assert(this->moveStack[sp].posInfo);
setMoveInEval(this->moveStack[sp].posInfo, whoMoved);
// 2. Push move onto stack with posInfo
if (!endPosInfo) {
if (!endPos) {
g_assert(this->getPos());
qPosition myPos = *this->getPos();
myPos.applyMove(whoMoved, move);
endPosInfo = posHash->getOrAddElt(&myPos);
this->pushMove(whoMoved, move, &myPos);
return endPosInfo;
}
endPosInfo = posHash->getOrAddElt(endPos);
}
this->pushMove(whoMoved, move, endPos);
return endPosInfo;
}
void qMoveStack::popEval(void)
{
// 1. Pop off to previous moveStack frame
this->popMove();
// Can't pop a move that's not in eval
g_assert(this->getPosInfo());
// 2. Mark the position we were examining as no longer under evaluation
clearMoveInEval(this->getPosInfo(), this->getPlayer2Move());
}
// This is a fast check--since revisiting positions is rare, it should
// be used before checking for which playerToMove is in the stack
inline static bool private_isInEvalStack
(qPositionInfo *posInfo)
{
return (posInfo->isPosExceptional() && (posInfo->getPositionFlag() > 0));
}
bool qMoveStack::isInEvalStack
(qPositionInfo *posInfo, qPlayer p) const
{
return (p.isWhite() ?
isWhiteMoveInEvalStack(posInfo) : isBlackMoveInEvalStack(posInfo));
}
bool qMoveStack::isWhiteMoveInEvalStack
(qPositionInfo *posInfo) const
{
return (private_isInEvalStack(posInfo) &&
(posInfo->getPositionFlag() & qPositionInfo::flag_WhiteToMove));
}
bool qMoveStack::isBlackMoveInEvalStack
(qPositionInfo *posInfo) const
{
return (private_isInEvalStack(posInfo) &&
(posInfo->getPositionFlag() & qPositionInfo::flag_BlackToMove));
}
| 25.038265 | 85 | 0.668263 | deepakm |
8d0e01232aa2658c99492909bfab42023691b260 | 4,777 | hpp | C++ | include/realm/core/system.hpp | pyrbin/realm.hpp | e34b18ce1f5c39b080a9e70f675adf740490ff83 | [
"MIT"
] | 2 | 2020-03-01T18:15:27.000Z | 2020-03-25T10:21:59.000Z | include/realm/core/system.hpp | pyrbin/realm.hpp | e34b18ce1f5c39b080a9e70f675adf740490ff83 | [
"MIT"
] | null | null | null | include/realm/core/system.hpp | pyrbin/realm.hpp | e34b18ce1f5c39b080a9e70f675adf740490ff83 | [
"MIT"
] | 1 | 2020-03-25T10:22:00.000Z | 2020-03-25T10:22:00.000Z | #pragma once
#include <cstddef>
#include <memory>
#include <stdexcept>
#include <string>
#include <utility>
#include <realm/core/archetype.hpp>
#include <realm/util/tuple_util.hpp>
namespace realm {
/**
* Forward declarations
*/
struct world;
template<typename... Ts>
struct view;
template<typename F>
constexpr internal::enable_if_query_fn<F, void> query(world* world, F&& f);
template<typename F>
constexpr internal::enable_if_query_fn<F, void> query_seq(world* world, F&& f);
/**
* @brief System meta
* Contains meta information about a system.
* Eg. which components it mutates/reads, mask etc.
*/
struct system_meta
{
const size_t mask{ 0 };
const size_t mut_mask{ 0 };
const size_t read_mask{ 0 };
template<typename... Args>
static constexpr system_meta from_pack()
{
using components = internal::component_tuple<Args...>;
size_t read{ 0 };
size_t mut{ 0 };
(from_pack_helper<Args>(read, mut), ...);
return { archetype::mask_from_tuple<components>(), mut, read };
}
template<typename F, typename... Args>
static constexpr system_meta of(void (F::*f)(Args...) const)
{
return from_pack<Args...>();
}
template<typename F, typename... Args>
static constexpr system_meta of(void (F::*f)(view<Args...>) const)
{
return from_pack<Args...>();
}
private:
template<typename T>
static constexpr void from_pack_helper(size_t& read, size_t& mut)
{
if constexpr (!internal::is_entity<T> && std::is_const_v<std::remove_reference_t<T>>) {
read |= component_meta::of<internal::pure_t<T>>().mask;
} else if constexpr (!internal::is_entity<T>) {
mut |= component_meta::of<internal::pure_t<T>>().mask;
}
}
};
/**
* @brief System reference
* Base system reference holder
*/
struct system_ref
{
const u64 id{ 0 };
const system_meta meta{ 0, 0 };
const std::string name{ "" };
system_ref() = default;
;
virtual ~system_ref() = default;
virtual bool compare(size_t hash) const = 0;
virtual bool mutates(size_t hash) const = 0;
virtual bool reads(size_t hash) const = 0;
virtual void invoke(world*) const = 0;
virtual void invoke_seq(world*) const = 0;
protected:
system_ref(const u64 id, system_meta meta, std::string name)
: id{ id }
, meta{ meta }
, name{ std::move(name) } {};
};
/**
* @brief System proxy
* A proxy class used to communicate with a defined system.
* Used to invoke the update function and uses query_helper functions to
* execute the query logic.
* @tparam T Underlying system class
*/
template<typename T>
struct system_proxy final : public system_ref
{
private:
/*! @brief Underlying system pointer */
const std::unique_ptr<T> instance_;
/*! @brief Creates a lamdba object to system update function */
template<typename R = void, typename... Args>
static constexpr auto update_lambda(const system_proxy<T>* proxy, void (T::*f)(Args...) const)
{
return [proxy, f](Args... args) -> void {
(proxy->instance_.get()->*f)(std::forward<Args>(args)...);
};
}
public:
/**
* Construct a system proxy from an object
* @param t Underlying system to make a proxy to
*/
explicit system_proxy(T& t)
: system_ref{ internal::identifier_hash_v<T>, system_meta::of(&T::update),
typeid(T).name() }
, instance_{ std::unique_ptr<T>(std::move(t)) }
{}
/**
* Construct a system proxy with arguments for the underlying system.
* @tparam Args Argument types
* @param args Arguments for underlying system
*/
template<typename... Args>
explicit system_proxy(Args&&... args)
: system_ref{ internal::identifier_hash_v<T>, system_meta::of(&T::update),
typeid(T).name() }
, instance_{ std::make_unique<T>(std::forward<Args>(args)...) }
{}
bool compare(const size_t other) const override { return archetype::subset(other, meta.mask); }
bool mutates(const size_t other) const override
{
return archetype::subset(meta.mut_mask, other);
}
bool reads(const size_t other) const override
{
return archetype::subset(meta.read_mask, other);
}
/**
* Call the system query on a world in parallel
* @param world
*/
[[nodiscard]] void invoke(world* world) const override
{
query(world, update_lambda(this, &T::update));
}
/**
* Call the system query on a world sequentially
* @param world
*/
[[nodiscard]] void invoke_seq(world* world) const override
{
query_seq(world, update_lambda(this, &T::update));
}
};
} // namespace realm | 27.297143 | 99 | 0.630731 | pyrbin |
8d114342a7fa4f43cd2dcf2a26c1fc14ad8d9c88 | 844 | cpp | C++ | libmetartc5/src/yangutil/buffer/YangAudioBuffer.cpp | metartc/metaRTC | 7b3125c9244632c82c55aacd628e6f0d7b151488 | [
"MIT"
] | 136 | 2021-12-17T09:17:44.000Z | 2022-03-28T09:51:51.000Z | libmetartc5/src/yangutil/buffer/YangAudioBuffer.cpp | metartc/metaRTC | 7b3125c9244632c82c55aacd628e6f0d7b151488 | [
"MIT"
] | 2 | 2021-12-24T02:00:53.000Z | 2022-03-28T02:40:12.000Z | libmetartc5/src/yangutil/buffer/YangAudioBuffer.cpp | metartc/metaRTC | 7b3125c9244632c82c55aacd628e6f0d7b151488 | [
"MIT"
] | 40 | 2021-12-17T09:17:48.000Z | 2022-03-27T14:40:25.000Z | //
// Copyright (c) 2019-2022 yanggaofeng
//
#include "yangutil/buffer/YangAudioBuffer.h"
#include <stdlib.h>
#include "stdio.h"
YangAudioBuffer::YangAudioBuffer(int32_t pcacheNum)
{
resetIndex();
m_cache_num=pcacheNum;
m_bufLen=0;
}
void YangAudioBuffer::reset(){
resetIndex();
}
YangAudioBuffer::~YangAudioBuffer(void)
{
}
void YangAudioBuffer::putAudio(YangFrame* pframe)
{
if(m_bufLen==0){
m_bufLen=pframe->nb;
initFrames(m_cache_num,pframe->nb);
}
putFrame(pframe);
}
int32_t YangAudioBuffer::getAudio(YangFrame* pframe)
{
if(size()>0){
getFrame(pframe);
return 0;
}else
return 1;
}
uint8_t *YangAudioBuffer::getAudioRef(YangFrame* pframe)
{
if(size()>0){
return getFrameRef(pframe);
}else{
return NULL;
}
}
| 15.071429 | 57 | 0.632701 | metartc |
8d1258dc0ff0b4a25312f6a3661cefc9e7e25368 | 11,376 | cpp | C++ | yoshicar_base_controller/src/MotorStateMachine.cpp | Badenhoop/yoshicar | c542e75dccf73b006a6483ced357168c15d893fe | [
"MIT"
] | null | null | null | yoshicar_base_controller/src/MotorStateMachine.cpp | Badenhoop/yoshicar | c542e75dccf73b006a6483ced357168c15d893fe | [
"MIT"
] | null | null | null | yoshicar_base_controller/src/MotorStateMachine.cpp | Badenhoop/yoshicar | c542e75dccf73b006a6483ced357168c15d893fe | [
"MIT"
] | 1 | 2020-09-11T17:54:54.000Z | 2020-09-11T17:54:54.000Z | #include "yoshicar_base_controller/MotorStateMachine.h"
namespace yoshicar
{
double varianceDecay(double t, double vStart, double vEnd, double duration)
{
double vDelta = vStart - vEnd;
return vStart - (vDelta / (1 + std::exp(-(12. / duration * t - 6.))));
}
MotorStateMachine::MotorStateMachine()
{
ros::NodeHandle nh;
ros::NodeHandle nhPriv;
targetVelocitySubscriber =
nh.subscribe<std_msgs::Float64>("target_velocity", 1, &MotorStateMachine::targetVelocityCallback, this);
isDrivingSubscriber = nh.subscribe<std_msgs::Bool>("is_driving", 1, &MotorStateMachine::isDrivingCallback, this);
motorCommandPublisher = nh.advertise<std_msgs::Float64>("motor", 1);
estimatedVelocityPublisher = nh.advertise<yoshicar_msgs::VelocityEstimate>("msm_velocity_estimate", 1);
auto updatePeriod = nhPriv.param<double>("msm_update_period", 0.01);
stateUpdateTimer = nh.createTimer(
ros::Duration(updatePeriod), [this] { updateCallback(); }, false);
state = std::make_unique<StoppedMotorState>();
}
void MotorStateMachine::targetVelocityCallback(const std_msgs::Float64ConstPtr& msg)
{
performEvent([&] { return state->targetVelocityEvent(msg->data); });
}
void MotorStateMachine::isDrivingCallback(const std_msgs::BoolConstPtr& msg)
{
performEvent([&] { return state->isDrivingEvent(msg->data); });
}
void MotorStateMachine::updateCallback()
{
performEvent([&] { return state->updateEvent(); });
std_msgs::Float64 motorCommand;
motorCommand.data = state->getMotorCommand();
motorCommandPublisher.publish(motorCommand);
estimatedVelocityPublisher.publish(state->getVelocityEstimate());
}
void MotorStateMachine::performEvent(const std::function<MotorStatePtr()>& event)
{
auto newState = event();
if (newState == nullptr)
return;
state = std::move(newState);
}
StoppedMotorState::StoppedMotorState() : MotorState()
{
ros::NodeHandle nhPriv{ "~" };
brakeReleaseDuration = nhPriv.param<double>("brake_release_duration", 0.2);
}
MotorStatePtr StoppedMotorState::targetVelocityEvent(double targetVelocity)
{
return nullptr;
}
MotorStatePtr StoppedMotorState::isDrivingEvent(bool isDriving)
{
return nullptr;
}
MotorStatePtr StoppedMotorState::updateEvent()
{
if (ros::Time::now() - startTime > ros::Duration{ brakeReleaseDuration })
return std::make_unique<ReleasedBrakeMotorState>();
return nullptr;
}
double StoppedMotorState::getMotorCommand() const
{
return 0.;
}
yoshicar_msgs::VelocityEstimate StoppedMotorState::getVelocityEstimate() const
{
yoshicar_msgs::VelocityEstimate estimate;
estimate.velocity = 0.;
estimate.variance = 0.01;
return estimate;
}
MotorStatePtr ReleasedBrakeMotorState::targetVelocityEvent(double targetVelocity)
{
if (targetVelocity > 0.)
return std::make_unique<ForwardCommandMotorState>(targetVelocity);
if (targetVelocity < 0.)
return std::make_unique<ReverseCommandMotorState>(targetVelocity);
return nullptr;
}
MotorStatePtr ReleasedBrakeMotorState::isDrivingEvent(bool isDriving)
{
return nullptr;
}
MotorStatePtr ReleasedBrakeMotorState::updateEvent()
{
return nullptr;
}
double ReleasedBrakeMotorState::getMotorCommand() const
{
return 0.;
}
yoshicar_msgs::VelocityEstimate ReleasedBrakeMotorState::getVelocityEstimate() const
{
yoshicar_msgs::VelocityEstimate estimate;
estimate.velocity = 0.;
estimate.variance = 0.01;
return estimate;
}
ForwardDrivingMotorState::ForwardDrivingMotorState(double currTargetVelocity)
: MotorState(), currTargetVelocity(currTargetVelocity)
{
}
MotorStatePtr ForwardDrivingMotorState::targetVelocityEvent(double targetVelocity)
{
if (targetVelocity <= 0.)
return std::make_unique<ForwardBrakingMotorState>(currTargetVelocity);
double currMotorCommand = config.velocityToMotorCommand(currTargetVelocity);
double nextMotorCommand = config.velocityToMotorCommand(targetVelocity);
if (currMotorCommand == nextMotorCommand)
return nullptr;
// If the new target velocity results in a new motor command, we perform
// a self transition with the new target velocity
return std::make_unique<ForwardDrivingMotorState>(targetVelocity);
}
MotorStatePtr ForwardDrivingMotorState::isDrivingEvent(bool isDriving)
{
if (isDriving)
return nullptr;
// This may only happen if the motor fails for some reason
return std::make_unique<StoppedMotorState>();
}
MotorStatePtr ForwardDrivingMotorState::updateEvent()
{
return nullptr;
}
double ForwardDrivingMotorState::getMotorCommand() const
{
return config.velocityToMotorCommand(currTargetVelocity);
}
yoshicar_msgs::VelocityEstimate ForwardDrivingMotorState::getVelocityEstimate() const
{
yoshicar_msgs::VelocityEstimate estimate;
if (currTargetVelocity < config.getMinForwardVelocity())
{
estimate.velocity = 0.;
estimate.variance = 0.01;
return estimate;
}
estimate.velocity = currTargetVelocity;
double t = (ros::Time::now() - startTime).toSec();
estimate.variance = varianceDecay(t, currTargetVelocity, currTargetVelocity * 0.1, 1.);
return estimate;
}
ForwardBrakingMotorState::ForwardBrakingMotorState(double prevTargetVelocity)
: MotorState(), prevTargetVelocity(prevTargetVelocity)
{
ros::NodeHandle nhPriv;
brakeMotorCommand = nhPriv.param<double>("forward_brake_motor_command", -1.);
}
MotorStatePtr ForwardBrakingMotorState::targetVelocityEvent(double targetVelocity)
{
if (targetVelocity <= 0.)
return nullptr;
return std::make_unique<ForwardDrivingMotorState>(targetVelocity);
}
MotorStatePtr ForwardBrakingMotorState::isDrivingEvent(bool isDriving)
{
if (isDriving)
return nullptr;
return std::make_unique<StoppedMotorState>();
}
MotorStatePtr ForwardBrakingMotorState::updateEvent()
{
if (ros::Time::now() - startTime > ros::Duration{ 5. })
return std::make_unique<StoppedMotorState>();
return nullptr;
}
double ForwardBrakingMotorState::getMotorCommand() const
{
return brakeMotorCommand;
}
yoshicar_msgs::VelocityEstimate ForwardBrakingMotorState::getVelocityEstimate() const
{
yoshicar_msgs::VelocityEstimate estimate;
estimate.velocity = 0.;
double t = (ros::Time::now() - startTime).toSec();
estimate.variance = varianceDecay(t, prevTargetVelocity * prevTargetVelocity, 0.01, 1.);
return estimate;
}
ForwardCommandMotorState::ForwardCommandMotorState(double currTargetVelocity) : currTargetVelocity(currTargetVelocity)
{
}
MotorStatePtr ForwardCommandMotorState::targetVelocityEvent(double targetVelocity)
{
currTargetVelocity = targetVelocity;
return nullptr;
}
MotorStatePtr ForwardCommandMotorState::isDrivingEvent(bool isDriving)
{
if (!isDriving)
return nullptr;
return std::make_unique<ForwardDrivingMotorState>(currTargetVelocity);
}
MotorStatePtr ForwardCommandMotorState::updateEvent()
{
// In case the ESC is still in the weird state of not having
// recognized that we released the brakes we go back to the stop state
if (ros::Time::now() - startTime > ros::Duration{ 1. })
return std::make_unique<StoppedMotorState>();
return nullptr;
}
double ForwardCommandMotorState::getMotorCommand() const
{
return config.velocityToMotorCommand(currTargetVelocity);
}
yoshicar_msgs::VelocityEstimate ForwardCommandMotorState::getVelocityEstimate() const
{
yoshicar_msgs::VelocityEstimate estimate;
estimate.velocity = 0.;
estimate.variance = 0.01;
return estimate;
}
ReverseDrivingMotorState::ReverseDrivingMotorState(double currTargetVelocity)
: MotorState(), currTargetVelocity(currTargetVelocity)
{
}
MotorStatePtr ReverseDrivingMotorState::targetVelocityEvent(double targetVelocity)
{
if (targetVelocity >= 0.)
return std::make_unique<ReverseBrakingMotorState>(currTargetVelocity);
double currMotorCommand = config.velocityToMotorCommand(currTargetVelocity);
double nextMotorCommand = config.velocityToMotorCommand(targetVelocity);
if (currMotorCommand == nextMotorCommand)
return nullptr;
// If the new target velocity results in a new motor command, we perform
// a self transition with the new target velocity
return std::make_unique<ReverseDrivingMotorState>(targetVelocity);
}
MotorStatePtr ReverseDrivingMotorState::isDrivingEvent(bool isDriving)
{
if (isDriving)
return nullptr;
// This may only happen if the motor fails for some reason
return std::make_unique<StoppedMotorState>();
}
MotorStatePtr ReverseDrivingMotorState::updateEvent()
{
return nullptr;
}
double ReverseDrivingMotorState::getMotorCommand() const
{
return config.velocityToMotorCommand(currTargetVelocity);
}
yoshicar_msgs::VelocityEstimate ReverseDrivingMotorState::getVelocityEstimate() const
{
yoshicar_msgs::VelocityEstimate estimate;
if (currTargetVelocity < config.getMinReverseVelocity())
{
estimate.velocity = 0.;
estimate.variance = 0.01;
return estimate;
}
estimate.velocity = currTargetVelocity;
double t = (ros::Time::now() - startTime).toSec();
estimate.variance = varianceDecay(t, currTargetVelocity, currTargetVelocity * 0.1, 1.);
return estimate;
}
ReverseBrakingMotorState::ReverseBrakingMotorState(double prevTargetVelocity)
: MotorState(), prevTargetVelocity(prevTargetVelocity)
{
ros::NodeHandle nhPriv;
brakeMotorCommand = nhPriv.param<double>("reverse_brake_motor_command", 0.);
}
MotorStatePtr ReverseBrakingMotorState::targetVelocityEvent(double targetVelocity)
{
if (targetVelocity >= 0.)
return nullptr;
return std::make_unique<ForwardDrivingMotorState>(targetVelocity);
}
MotorStatePtr ReverseBrakingMotorState::isDrivingEvent(bool isDriving)
{
if (isDriving)
return nullptr;
return std::make_unique<StoppedMotorState>();
}
MotorStatePtr ReverseBrakingMotorState::updateEvent()
{
if (ros::Time::now() - startTime > ros::Duration{ 5. })
return std::make_unique<StoppedMotorState>();
return nullptr;
}
double ReverseBrakingMotorState::getMotorCommand() const
{
return brakeMotorCommand;
}
yoshicar_msgs::VelocityEstimate ReverseBrakingMotorState::getVelocityEstimate() const
{
yoshicar_msgs::VelocityEstimate estimate;
estimate.velocity = 0.;
double t = (ros::Time::now() - startTime).toSec();
estimate.variance = varianceDecay(t, prevTargetVelocity * prevTargetVelocity, 0.01, 1.);
return estimate;
}
ReverseCommandMotorState::ReverseCommandMotorState(double currTargetVelocity) : currTargetVelocity(currTargetVelocity)
{
}
MotorStatePtr ReverseCommandMotorState::targetVelocityEvent(double targetVelocity)
{
currTargetVelocity = targetVelocity;
return nullptr;
}
MotorStatePtr ReverseCommandMotorState::isDrivingEvent(bool isDriving)
{
if (!isDriving)
return nullptr;
return std::make_unique<ForwardDrivingMotorState>(currTargetVelocity);
}
MotorStatePtr ReverseCommandMotorState::updateEvent()
{
// In case the ESC is still in the weird state of not having
// recognized that we released the brakes we go back to the stop state
if (ros::Time::now() - startTime > ros::Duration{ 1. })
return std::make_unique<StoppedMotorState>();
return nullptr;
}
double ReverseCommandMotorState::getMotorCommand() const
{
return config.velocityToMotorCommand(currTargetVelocity);
}
yoshicar_msgs::VelocityEstimate ReverseCommandMotorState::getVelocityEstimate() const
{
yoshicar_msgs::VelocityEstimate estimate;
estimate.velocity = 0.;
estimate.variance = 0.01;
return estimate;
}
} // namespace yoshicar | 27.61165 | 118 | 0.774701 | Badenhoop |
8d12ccf482d8cb7b41e22716dbce49e1f2cff68b | 3,381 | cc | C++ | src/scsi2sd-util6/libzipper-1.0.4/Compressor.cc | fhgwright/SCSI2SD-V6 | 29555b30d3f96257ac12a546e75891490603aee8 | [
"BSD-3-Clause"
] | 2 | 2020-11-29T01:28:03.000Z | 2021-11-07T18:23:11.000Z | src/scsi2sd-util6/libzipper-1.0.4/Compressor.cc | tweakoz/SCSI2SD-V6 | 77db5f86712213e25c9b12fa5c9fa9c54b80cb80 | [
"BSD-3-Clause"
] | null | null | null | src/scsi2sd-util6/libzipper-1.0.4/Compressor.cc | tweakoz/SCSI2SD-V6 | 77db5f86712213e25c9b12fa5c9fa9c54b80cb80 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (C) 2011 Michael McMaster <[email protected]>
//
// This file is part of libzipper.
//
// libzipper 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.
//
// libzipper 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 libzipper. If not, see <http://www.gnu.org/licenses/>.
#include "zipper.hh"
#include "gzip.hh"
#include "zip.hh"
#include "util.hh"
#include <algorithm>
using namespace zipper;
class Compressor::CompressorImpl
{
public:
virtual ~CompressorImpl() {}
virtual void
addFile(const std::string& filename, const Reader& reader) = 0;
};
namespace
{
class PlainCompressor : public Compressor::CompressorImpl
{
public:
PlainCompressor(const WriterPtr& writer) : m_writer(writer) {}
virtual void
addFile(const std::string&, const Reader& reader)
{
enum Constants
{
ChunkSize = 64*1024
};
uint8_t buffer[ChunkSize];
zsize_t offset(0);
while (offset < reader.getSize())
{
zsize_t bytes(
std::min(zsize_t(ChunkSize), reader.getSize() - offset));
reader.readData(offset, bytes, &buffer[0]);
m_writer->writeData(offset, bytes, &buffer[0]);
offset += bytes;
}
}
private:
WriterPtr m_writer;
};
class ZipCompressor : public Compressor::CompressorImpl
{
public:
ZipCompressor(const WriterPtr& writer) : m_writer(writer) {}
virtual ~ZipCompressor()
{
zipFinalise(m_records, m_writer);
}
virtual void
addFile(const std::string& filename, const Reader& reader)
{
ZipFileRecord record;
zip(filename, reader, m_writer, record);
m_records.push_back(record);
}
private:
WriterPtr m_writer;
std::vector<ZipFileRecord> m_records;
};
class GzipCompressor : public Compressor::CompressorImpl
{
public:
GzipCompressor(const WriterPtr& writer) : m_writer(writer) {}
virtual void
addFile(const std::string& filename, const Reader& reader)
{
gzip(filename, reader, m_writer);
}
private:
WriterPtr m_writer;
};
}
Compressor::Compressor(ContainerFormat format, const WriterPtr& writer)
{
switch (format)
{
case Container_none:
m_compressor = new PlainCompressor(writer); break;
case Container_zip:
m_compressor = new ZipCompressor(writer); break;
case Container_gzip:
m_compressor = new GzipCompressor(writer); break;
default:
throw UnsupportedException("Unknown format");
}
}
Compressor::Compressor(ContainerFormat format, Writer& writer) :
m_compressor(NULL)
{
WriterPtr ptr(&writer, dummy_delete<Writer>());
switch (format)
{
case Container_none:
m_compressor = new PlainCompressor(ptr); break;
case Container_zip:
m_compressor = new ZipCompressor(ptr); break;
case Container_gzip:
m_compressor = new GzipCompressor(ptr); break;
default:
throw UnsupportedException("Unknown format");
}
}
Compressor::~Compressor()
{
delete m_compressor;
}
void
Compressor::addFile(const Reader& reader)
{
m_compressor->addFile(reader.getSourceName(), reader);
}
| 22.098039 | 71 | 0.722272 | fhgwright |
8d1899c71f93415feb9a58504bd0fe6f2a068d19 | 985 | hpp | C++ | include/commata/buffer_size.hpp | furfurylic/commata | 6afbc218d262d8363e8436fd943b1e13444d9f83 | [
"Unlicense"
] | null | null | null | include/commata/buffer_size.hpp | furfurylic/commata | 6afbc218d262d8363e8436fd943b1e13444d9f83 | [
"Unlicense"
] | null | null | null | include/commata/buffer_size.hpp | furfurylic/commata | 6afbc218d262d8363e8436fd943b1e13444d9f83 | [
"Unlicense"
] | null | null | null | /**
* These codes are licensed under the Unlicense.
* http://unlicense.org
*/
#ifndef COMMATA_GUARD_4E257056_FA43_4ED4_BF21_5638E8C46B14
#define COMMATA_GUARD_4E257056_FA43_4ED4_BF21_5638E8C46B14
#include <algorithm>
#include <cstddef>
#include <memory>
#include <limits>
namespace commata { namespace detail {
template <class Allocator>
std::size_t sanitize_buffer_size(
std::size_t buffer_size, Allocator alloc) noexcept
{
constexpr std::size_t buffer_size_max =
std::numeric_limits<std::size_t>::max();
constexpr std::size_t default_buffer_size =
std::min(buffer_size_max, static_cast<std::size_t>(8192U));
if (buffer_size == 0U) {
buffer_size = default_buffer_size;
}
const auto max_alloc0 = std::allocator_traits<Allocator>::max_size(alloc);
const auto max_alloc = (max_alloc0 > buffer_size_max) ?
static_cast<std::size_t>(buffer_size_max) : max_alloc0;
return std::min(buffer_size, max_alloc);
}
}}
#endif
| 27.361111 | 78 | 0.73198 | furfurylic |
8d1907f99094d3d56c755e085ed46f84e01ba9bc | 1,130 | hh | C++ | src/circuit/pws_circuit.hh | hyraxZK/libpws | cc1b7dfdafb3d01b025cdb72ed83379d205a0147 | [
"Apache-2.0"
] | null | null | null | src/circuit/pws_circuit.hh | hyraxZK/libpws | cc1b7dfdafb3d01b025cdb72ed83379d205a0147 | [
"Apache-2.0"
] | null | null | null | src/circuit/pws_circuit.hh | hyraxZK/libpws | cc1b7dfdafb3d01b025cdb72ed83379d205a0147 | [
"Apache-2.0"
] | 1 | 2020-01-16T07:49:03.000Z | 2020-01-16T07:49:03.000Z | #pragma once
#include <vector>
#include <map>
#include "pws_circuit_parser.hh"
#include "cmt_circuit.hh"
#include "cmt_circuit_builder.hh"
class PWSCircuit : public CMTCircuit
{
private:
PWSCircuitParser& parser;
public:
PWSCircuit(PWSCircuitParser& pp);
Gate getGate(const GatePosition& pos);
CircuitLayer& getGatePosLayer(int gatePosLayer);
void evalGates(const std::vector<int>& start);
void evalGates(const std::vector<int>& start, const std::vector<int>& end);
virtual void evaluate();
virtual void initializeInputs(const MPQVector& inputs, const MPQVector& magic = MPQVector(0));
virtual void initializeOutputs(const MPQVector& outputs);
protected:
virtual void constructCircuit();
private:
void makeGateMapping(std::vector<Gate*>& gates, CircuitLayer& layer, const std::vector<int>& mapping);
void makeGateMapping(std::vector<Gate*>& gates, CircuitLayer& layer, const std::map<int, int>& mapping, int offset);
};
class PWSCircuitBuilder : public CMTCircuitBuilder
{
PWSCircuitParser& parser;
public:
PWSCircuitBuilder(PWSCircuitParser& pp);
PWSCircuit* buildCircuit();
};
| 25.681818 | 118 | 0.749558 | hyraxZK |
8d1b7b5c7e67cb8d38f63cbe0f613a59b08398cb | 1,786 | hpp | C++ | gk++/include/gk/gk++.hpp | rpav/GameKernel | 1f3eb863b58243f5f14aa76283b60a259d881522 | [
"MIT"
] | 11 | 2016-04-28T15:09:19.000Z | 2019-07-15T15:58:59.000Z | gk++/include/gk/gk++.hpp | rpav/GameKernel | 1f3eb863b58243f5f14aa76283b60a259d881522 | [
"MIT"
] | null | null | null | gk++/include/gk/gk++.hpp | rpav/GameKernel | 1f3eb863b58243f5f14aa76283b60a259d881522 | [
"MIT"
] | null | null | null | #pragma once
/*
This uses a slight bit of STL. You can probably replace this with
a slimmer implementation without issues.
This also abuses templates and virtuals a bit to keep code concise.
*/
#include <stdexcept>
#include <vector>
#include <rpav/ptr.hpp>
#include "gk/gk++cmd.hpp"
#include "gk/gk++list.hpp"
#include "gk/gk++util.hpp"
#include "gk/gk.h"
namespace gk {
class Error : public std::runtime_error {
public:
gk_error_code code{};
Error(gk_error_code code, const char* msg) : runtime_error{msg}, code{code} {}
};
class Bundle {
ListVector lists;
public:
Bundle(unsigned int start = 0, gk_pass_sorting sort = GK_PASS_SORT_NONE);
~Bundle() {}
void handleError();
gk_bundle bundle;
template<typename... Rest>
inline void add(ListBase& list, Rest&... args)
{
lists.push_back(list.listPtr());
add(args...);
}
inline void add()
{
bundle.nlists = lists.size();
bundle.lists = lists.data();
}
inline void clear()
{
lists.clear();
bundle.nlists = 0;
bundle.lists = nullptr;
}
};
struct Context {
rpav::ptr<gk_context> ctx;
Context(gk_impl impl) { ctx = gk_create(impl); }
~Context() { gk_destroy(ctx); }
operator gk_context*() { return ctx; }
operator const gk_context*() const { return ctx; }
inline void process(Bundle& bundle)
{
gk_process(ctx, &bundle.bundle);
if(bundle.bundle.error.code) bundle.handleError();
}
template<typename L, typename...Ts>
inline void process(Ts&...vs) {
gk::Bundle b;
L list;
b.add(list);
list.add(vs...);
process(b);
}
};
} // namespace gk
#define BEGIN_NS_GK namespace gk {
#define END_NS_GK }
| 20.067416 | 82 | 0.613102 | rpav |
8d203b2bb42da1d3c8d32247b41c2f65a1c6d5f5 | 2,361 | cpp | C++ | src/byte_array.cpp | rnascunha/my_async | 5fbe3a46e87a2d74fc07d16252a3b3cf488b4684 | [
"MIT"
] | null | null | null | src/byte_array.cpp | rnascunha/my_async | 5fbe3a46e87a2d74fc07d16252a3b3cf488b4684 | [
"MIT"
] | null | null | null | src/byte_array.cpp | rnascunha/my_async | 5fbe3a46e87a2d74fc07d16252a3b3cf488b4684 | [
"MIT"
] | null | null | null | #include "my_async/util/byte_array.h"
#include <ostream>
#include <iomanip>
#include <sstream>
std::string Byte_Array::to_hex(bool up_case /* = true */, const char* separator /* = "" */,
unsigned int byte_space /* = 1 */) const
{
std::ostringstream ret;
for (std::string::size_type i = 0; i < size(); ++i){
ret << byte_to_hex(this->at(i), up_case);
if((i + 1) != size() && ((i+1) % byte_space) == 0){
ret << separator;
}
}
return std::move(ret.str());
}
std::string Byte_Array::to_string() const
{
std::string s(reinterpret_cast<char const*>(data()), size());
return s;
}
std::string Byte_Array::to_scape_string(Byte_Array::Escape_Format format /* = PRINTF */,
const char* enclose_begin /* = "\\" */, const char* enclose_end /* = "" */)
{
std::string str;
for(unsigned int i = 0; i < size(); i++){
if(isprint((int)at(i)) && (int)at(i) != '\\'){
str.push_back(at(i));
continue;
}
str += enclose_begin;
if(format == PRINTF){
switch(at(i)){
case 0x5C:
str.push_back('\\');
break;
case 0xA:
str.push_back('n');
break;
case 0xD:
str.push_back('n');
break;
case 0x9:
str.push_back('t');
break;
case 0xB:
str.push_back('v');
break;
default:
str.push_back('x');
str += byte_to_hex((int)at(i));
break;
}
} else if(format == HEX){
str.push_back('x');
str += byte_to_hex((int)at(i));
} else {
str += byte_to_octo((int)at(i));
}
str += enclose_end;
}
return str;
}
std::string Byte_Array::byte_to_hex(uint8_t byte, bool up_case /* = true */)
{
std::ostringstream ret;
ret << std::hex
<< std::setfill('0')
<< std::setw(2)
<< (up_case ? std::uppercase : std::nouppercase)
<< (int)byte;
return std::move(ret.str());
}
std::string Byte_Array::byte_to_octo(uint8_t byte)
{
std::ostringstream ret;
ret << std::oct
<< std::setfill('0')
<< std::setw(3)
<< (int)byte;
return std::move(ret.str());
}
void Byte_Array::copy(const std::string& str){
clear();
for(unsigned int i = 0; i < str.size(); i++)
push_back(str[i]);
}
void Byte_Array::copy(const std::stringstream& ss)
{
copy(ss.str());
}
Byte_Array& Byte_Array::operator=(const std::string& a)
{
this->copy(a);
return *this;
}
Byte_Array& Byte_Array::operator=(const std::stringstream& a)
{
this->copy(a);
return *this;
}
| 19.195122 | 91 | 0.591275 | rnascunha |
8d25b14e89d354f8ff34834e576c4b5b9d01da5f | 568 | cpp | C++ | Olympiad Programs/M3/M3 Madrese/Afther M2 Results/Day 1/M3s/22/Day 2/1.cpp | mirtaba/ACMICPC-INOI_Archive | ea06e4e40e984f0807410e4f9b5f7042580da2e3 | [
"MIT"
] | 1 | 2020-12-08T11:21:34.000Z | 2020-12-08T11:21:34.000Z | Olympiad Programs/M3/M3 Madrese/Afther M2 Results/Day 1/M3s/22/Day 2/1.cpp | mirtaba/ACMICPC-INOI_Archive | ea06e4e40e984f0807410e4f9b5f7042580da2e3 | [
"MIT"
] | null | null | null | Olympiad Programs/M3/M3 Madrese/Afther M2 Results/Day 1/M3s/22/Day 2/1.cpp | mirtaba/ACMICPC-INOI_Archive | ea06e4e40e984f0807410e4f9b5f7042580da2e3 | [
"MIT"
] | null | null | null | #include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <vector>
using namespace std;
#define pb push_back
#define mp make_pair
#define pf push_front
#define FOR(i,s,f) for (int i=s;i<f;i++)
typedef long long LL ;
typedef pair <int ,int > PII;
typedef pair <LL , LL > PLL;
const int Maxn = 1000 +25;
const int Mod = 1000*1000*1000 +9;
const int Del = 11117;
int main()
{
ios::sync_with_stdio(0);
cout << (1<<26) << endl;
int M=(1<<26);
M%=Del;
M*=M;
M%=Del;
M*=3;
M%=Del;
cout << M << endl;
}
| 16.228571 | 40 | 0.603873 | mirtaba |
8d2ae03d437b155e5145b3755f7746e440dfe36e | 41,376 | cpp | C++ | src/wl_state.cpp | TobiasKarnat/Wolf4GW | a49ead44cb4a6476255e355c4c5e3e48bb7f1d55 | [
"Unlicense"
] | 8 | 2015-06-28T09:38:45.000Z | 2021-10-02T16:33:47.000Z | src/wl_state.cpp | TobiasKarnat/Wolf4GW | a49ead44cb4a6476255e355c4c5e3e48bb7f1d55 | [
"Unlicense"
] | null | null | null | src/wl_state.cpp | TobiasKarnat/Wolf4GW | a49ead44cb4a6476255e355c4c5e3e48bb7f1d55 | [
"Unlicense"
] | 2 | 2018-09-08T08:30:38.000Z | 2019-03-24T18:10:52.000Z | // WL_STATE.C
/*
=============================================================================
LOCAL CONSTANTS
=============================================================================
*/
/*
=============================================================================
GLOBAL VARIABLES
=============================================================================
*/
dirtype opposite[9] =
{west,southwest,south,southeast,east,northeast,north,northwest,nodir};
dirtype diagonal[9][9] =
{
/* east */ {nodir,nodir,northeast,nodir,nodir,nodir,southeast,nodir,nodir},
{nodir,nodir,nodir,nodir,nodir,nodir,nodir,nodir,nodir},
/* north */ {northeast,nodir,nodir,nodir,northwest,nodir,nodir,nodir,nodir},
{nodir,nodir,nodir,nodir,nodir,nodir,nodir,nodir,nodir},
/* west */ {nodir,nodir,northwest,nodir,nodir,nodir,southwest,nodir,nodir},
{nodir,nodir,nodir,nodir,nodir,nodir,nodir,nodir,nodir},
/* south */ {southeast,nodir,nodir,nodir,southwest,nodir,nodir,nodir,nodir},
{nodir,nodir,nodir,nodir,nodir,nodir,nodir,nodir,nodir},
{nodir,nodir,nodir,nodir,nodir,nodir,nodir,nodir,nodir}
};
void SpawnNewObj (unsigned tilex, unsigned tiley, statetype *state);
void NewState (objtype *ob, statetype *state);
boolean TryWalk (objtype *ob);
void MoveObj (objtype *ob, long move);
void KillActor (objtype *ob);
void DamageActor (objtype *ob, unsigned damage);
boolean CheckLine (objtype *ob);
void FirstSighting (objtype *ob);
boolean CheckSight (objtype *ob);
/*
=============================================================================
LOCAL VARIABLES
=============================================================================
*/
//===========================================================================
/*
===================
=
= SpawnNewObj
=
= Spaws a new actor at the given TILE coordinates, with the given state, and
= the given size in GLOBAL units.
=
= new = a pointer to an initialized new actor
=
===================
*/
void SpawnNewObj (unsigned tilex, unsigned tiley, statetype *state)
{
GetNewActor ();
newobj->state = state;
if (state->tictime)
newobj->ticcount = US_RndT () % state->tictime + 1; // Chris' moonwalk bugfix ;D
else
newobj->ticcount = 0;
newobj->tilex = (short) tilex;
newobj->tiley = (short) tiley;
newobj->x = ((long)tilex<<TILESHIFT)+TILEGLOBAL/2;
newobj->y = ((long)tiley<<TILESHIFT)+TILEGLOBAL/2;
newobj->dir = nodir;
actorat[tilex][tiley] = newobj;
newobj->areanumber =
*(mapsegs[0] + (newobj->tiley<<mapshift)+newobj->tilex) - AREATILE;
}
/*
===================
=
= NewState
=
= Changes ob to a new state, setting ticcount to the max for that state
=
===================
*/
void NewState (objtype *ob, statetype *state)
{
ob->state = state;
ob->ticcount = state->tictime;
}
/*
=============================================================================
ENEMY TILE WORLD MOVEMENT CODE
=============================================================================
*/
/*
==================================
=
= TryWalk
=
= Attempts to move ob in its current (ob->dir) direction.
=
= If blocked by either a wall or an actor returns FALSE
=
= If move is either clear or blocked only by a door, returns TRUE and sets
=
= ob->tilex = new destination
= ob->tiley
= ob->areanumber = the floor tile number (0-(NUMAREAS-1)) of destination
= ob->distance = TILEGLOBAl, or -doornumber if a door is blocking the way
=
= If a door is in the way, an OpenDoor call is made to start it opening.
= The actor code should wait until
= doorobjlist[-ob->distance].action = dr_open, meaning the door has been
= fully opened
=
==================================
*/
#define CHECKDIAG(x,y) \
{ \
temp=(unsigned)actorat[x][y]; \
if (temp) \
{ \
if (temp<256) \
return false; \
if (((objtype *)temp)->flags&FL_SHOOTABLE) \
return false; \
} \
}
#define CHECKSIDE(x,y) \
{ \
temp=(unsigned)actorat[x][y]; \
if (temp) \
{ \
if (temp<128) \
return false; \
if (temp<256) \
{ \
doornum = temp&127; \
OpenDoor (doornum); \
ob->distance = -doornum-1; \
return true; \
} \
else if (((objtype *)temp)->flags&FL_SHOOTABLE)\
return false; \
} \
}
boolean TryWalk (objtype *ob)
{
int doornum;
unsigned temp;
if (ob->obclass == inertobj)
{
switch (ob->dir)
{
case north:
ob->tiley--;
break;
case northeast:
ob->tilex++;
ob->tiley--;
break;
case east:
ob->tilex++;
break;
case southeast:
ob->tilex++;
ob->tiley++;
break;
case south:
ob->tiley++;
break;
case southwest:
ob->tilex--;
ob->tiley++;
break;
case west:
ob->tilex--;
break;
case northwest:
ob->tilex--;
ob->tiley--;
break;
}
}
else
switch (ob->dir)
{
case north:
if (ob->obclass == dogobj || ob->obclass == fakeobj)
{
CHECKDIAG(ob->tilex,ob->tiley-1);
}
else
{
CHECKSIDE(ob->tilex,ob->tiley-1);
}
ob->tiley--;
break;
case northeast:
CHECKDIAG(ob->tilex+1,ob->tiley-1);
CHECKDIAG(ob->tilex+1,ob->tiley);
CHECKDIAG(ob->tilex,ob->tiley-1);
ob->tilex++;
ob->tiley--;
break;
case east:
if (ob->obclass == dogobj || ob->obclass == fakeobj)
{
CHECKDIAG(ob->tilex+1,ob->tiley);
}
else
{
CHECKSIDE(ob->tilex+1,ob->tiley);
}
ob->tilex++;
break;
case southeast:
CHECKDIAG(ob->tilex+1,ob->tiley+1);
CHECKDIAG(ob->tilex+1,ob->tiley);
CHECKDIAG(ob->tilex,ob->tiley+1);
ob->tilex++;
ob->tiley++;
break;
case south:
if (ob->obclass == dogobj || ob->obclass == fakeobj)
{
CHECKDIAG(ob->tilex,ob->tiley+1);
}
else
{
CHECKSIDE(ob->tilex,ob->tiley+1);
}
ob->tiley++;
break;
case southwest:
CHECKDIAG(ob->tilex-1,ob->tiley+1);
CHECKDIAG(ob->tilex-1,ob->tiley);
CHECKDIAG(ob->tilex,ob->tiley+1);
ob->tilex--;
ob->tiley++;
break;
case west:
if (ob->obclass == dogobj || ob->obclass == fakeobj)
{
CHECKDIAG(ob->tilex-1,ob->tiley);
}
else
{
CHECKSIDE(ob->tilex-1,ob->tiley);
}
ob->tilex--;
break;
case northwest:
CHECKDIAG(ob->tilex-1,ob->tiley-1);
CHECKDIAG(ob->tilex-1,ob->tiley);
CHECKDIAG(ob->tilex,ob->tiley-1);
ob->tilex--;
ob->tiley--;
break;
case nodir:
return false;
default:
Quit ("Walk: Bad dir");
}
ob->areanumber =
*(mapsegs[0] + (ob->tiley<<mapshift)+ob->tilex) - AREATILE;
ob->distance = TILEGLOBAL;
return true;
}
/*
==================================
=
= SelectDodgeDir
=
= Attempts to choose and initiate a movement for ob that sends it towards
= the player while dodging
=
= If there is no possible move (ob is totally surrounded)
=
= ob->dir = nodir
=
= Otherwise
=
= ob->dir = new direction to follow
= ob->distance = TILEGLOBAL or -doornumber
= ob->tilex = new destination
= ob->tiley
= ob->areanumber = the floor tile number (0-(NUMAREAS-1)) of destination
=
==================================
*/
void SelectDodgeDir (objtype *ob)
{
int deltax,deltay,i;
unsigned absdx,absdy;
dirtype dirtry[5];
dirtype turnaround,tdir;
if (ob->flags & FL_FIRSTATTACK)
{
//
// turning around is only ok the very first time after noticing the
// player
//
turnaround = nodir;
ob->flags &= ~FL_FIRSTATTACK;
}
else
turnaround=opposite[ob->dir];
deltax = player->tilex - ob->tilex;
deltay = player->tiley - ob->tiley;
//
// arange 5 direction choices in order of preference
// the four cardinal directions plus the diagonal straight towards
// the player
//
if (deltax>0)
{
dirtry[1]= east;
dirtry[3]= west;
}
else
{
dirtry[1]= west;
dirtry[3]= east;
}
if (deltay>0)
{
dirtry[2]= south;
dirtry[4]= north;
}
else
{
dirtry[2]= north;
dirtry[4]= south;
}
//
// randomize a bit for dodging
//
absdx = abs(deltax);
absdy = abs(deltay);
if (absdx > absdy)
{
tdir = dirtry[1];
dirtry[1] = dirtry[2];
dirtry[2] = tdir;
tdir = dirtry[3];
dirtry[3] = dirtry[4];
dirtry[4] = tdir;
}
if (US_RndT() < 128)
{
tdir = dirtry[1];
dirtry[1] = dirtry[2];
dirtry[2] = tdir;
tdir = dirtry[3];
dirtry[3] = dirtry[4];
dirtry[4] = tdir;
}
dirtry[0] = diagonal [ dirtry[1] ] [ dirtry[2] ];
//
// try the directions util one works
//
for (i=0;i<5;i++)
{
if ( dirtry[i] == nodir || dirtry[i] == turnaround)
continue;
ob->dir = dirtry[i];
if (TryWalk(ob))
return;
}
//
// turn around only as a last resort
//
if (turnaround != nodir)
{
ob->dir = turnaround;
if (TryWalk(ob))
return;
}
ob->dir = nodir;
}
/*
============================
=
= SelectChaseDir
=
= As SelectDodgeDir, but doesn't try to dodge
=
============================
*/
void SelectChaseDir (objtype *ob)
{
int deltax,deltay;
dirtype d[3];
dirtype tdir, olddir, turnaround;
olddir=ob->dir;
turnaround=opposite[olddir];
deltax=player->tilex - ob->tilex;
deltay=player->tiley - ob->tiley;
d[1]=nodir;
d[2]=nodir;
if (deltax>0)
d[1]= east;
else if (deltax<0)
d[1]= west;
if (deltay>0)
d[2]=south;
else if (deltay<0)
d[2]=north;
if (abs(deltay)>abs(deltax))
{
tdir=d[1];
d[1]=d[2];
d[2]=tdir;
}
if (d[1]==turnaround)
d[1]=nodir;
if (d[2]==turnaround)
d[2]=nodir;
if (d[1]!=nodir)
{
ob->dir=d[1];
if (TryWalk(ob))
return; /*either moved forward or attacked*/
}
if (d[2]!=nodir)
{
ob->dir=d[2];
if (TryWalk(ob))
return;
}
/* there is no direct path to the player, so pick another direction */
if (olddir!=nodir)
{
ob->dir=olddir;
if (TryWalk(ob))
return;
}
if (US_RndT()>128) /*randomly determine direction of search*/
{
for (tdir=north;tdir<=west;tdir=(dirtype)(tdir+1))
{
if (tdir!=turnaround)
{
ob->dir=tdir;
if ( TryWalk(ob) )
return;
}
}
}
else
{
for (tdir=west;tdir>=north;tdir=(dirtype)(tdir-1))
{
if (tdir!=turnaround)
{
ob->dir=tdir;
if ( TryWalk(ob) )
return;
}
}
}
if (turnaround != nodir)
{
ob->dir=turnaround;
if (ob->dir != nodir)
{
if ( TryWalk(ob) )
return;
}
}
ob->dir = nodir; // can't move
}
/*
============================
=
= SelectRunDir
=
= Run Away from player
=
============================
*/
void SelectRunDir (objtype *ob)
{
int deltax,deltay;
dirtype d[3];
dirtype tdir;
deltax=player->tilex - ob->tilex;
deltay=player->tiley - ob->tiley;
if (deltax<0)
d[1]= east;
else
d[1]= west;
if (deltay<0)
d[2]=south;
else
d[2]=north;
if (abs(deltay)>abs(deltax))
{
tdir=d[1];
d[1]=d[2];
d[2]=tdir;
}
ob->dir=d[1];
if (TryWalk(ob))
return; /*either moved forward or attacked*/
ob->dir=d[2];
if (TryWalk(ob))
return;
/* there is no direct path to the player, so pick another direction */
if (US_RndT()>128) /*randomly determine direction of search*/
{
for (tdir=north;tdir<=west;tdir=(dirtype)(tdir+1))
{
ob->dir=tdir;
if ( TryWalk(ob) )
return;
}
}
else
{
for (tdir=west;tdir>=north;tdir=(dirtype)(tdir-1))
{
ob->dir=tdir;
if ( TryWalk(ob) )
return;
}
}
ob->dir = nodir; // can't move
}
/*
=================
=
= MoveObj
=
= Moves ob be move global units in ob->dir direction
= Actors are not allowed to move inside the player
= Does NOT check to see if the move is tile map valid
=
= ob->x = adjusted for new position
= ob->y
=
=================
*/
void MoveObj (objtype *ob, long move)
{
long deltax,deltay;
switch (ob->dir)
{
case north:
ob->y -= move;
break;
case northeast:
ob->x += move;
ob->y -= move;
break;
case east:
ob->x += move;
break;
case southeast:
ob->x += move;
ob->y += move;
break;
case south:
ob->y += move;
break;
case southwest:
ob->x -= move;
ob->y += move;
break;
case west:
ob->x -= move;
break;
case northwest:
ob->x -= move;
ob->y -= move;
break;
case nodir:
return;
default:
Quit ("MoveObj: bad dir!");
}
//
// check to make sure it's not on top of player
//
if (areabyplayer[ob->areanumber])
{
deltax = ob->x - player->x;
if (deltax < -MINACTORDIST || deltax > MINACTORDIST)
goto moveok;
deltay = ob->y - player->y;
if (deltay < -MINACTORDIST || deltay > MINACTORDIST)
goto moveok;
if (ob->hidden) // move closer until he meets CheckLine
goto moveok;
if (ob->obclass == ghostobj || ob->obclass == spectreobj)
TakeDamage (tics*2,ob);
//
// back up
//
switch (ob->dir)
{
case north:
ob->y += move;
break;
case northeast:
ob->x -= move;
ob->y += move;
break;
case east:
ob->x -= move;
break;
case southeast:
ob->x -= move;
ob->y -= move;
break;
case south:
ob->y -= move;
break;
case southwest:
ob->x += move;
ob->y -= move;
break;
case west:
ob->x += move;
break;
case northwest:
ob->x += move;
ob->y += move;
break;
case nodir:
return;
}
return;
}
moveok:
ob->distance -=move;
}
/*
=============================================================================
STUFF
=============================================================================
*/
/*
===============
=
= KillActor
=
===============
*/
void KillActor (objtype *ob)
{
int tilex,tiley;
tilex = ob->tilex = (word)(ob->x >> TILESHIFT); // drop item on center
tiley = ob->tiley = (word)(ob->y >> TILESHIFT);
switch (ob->obclass)
{
case guardobj:
GivePoints (100);
NewState (ob,&s_grddie1);
PlaceItemType (bo_clip2,tilex,tiley);
break;
case officerobj:
GivePoints (400);
NewState (ob,&s_ofcdie1);
PlaceItemType (bo_clip2,tilex,tiley);
break;
case mutantobj:
GivePoints (700);
NewState (ob,&s_mutdie1);
PlaceItemType (bo_clip2,tilex,tiley);
break;
case ssobj:
GivePoints (500);
NewState (ob,&s_ssdie1);
if (gamestate.bestweapon < wp_machinegun)
PlaceItemType (bo_machinegun,tilex,tiley);
else
PlaceItemType (bo_clip2,tilex,tiley);
break;
case dogobj:
GivePoints (200);
NewState (ob,&s_dogdie1);
break;
#ifndef SPEAR
case bossobj:
GivePoints (5000);
NewState (ob,&s_bossdie1);
PlaceItemType (bo_key1,tilex,tiley);
break;
case gretelobj:
GivePoints (5000);
NewState (ob,&s_greteldie1);
PlaceItemType (bo_key1,tilex,tiley);
break;
case giftobj:
GivePoints (5000);
gamestate.killx = player->x;
gamestate.killy = player->y;
NewState (ob,&s_giftdie1);
break;
case fatobj:
GivePoints (5000);
gamestate.killx = player->x;
gamestate.killy = player->y;
NewState (ob,&s_fatdie1);
break;
case schabbobj:
GivePoints (5000);
gamestate.killx = player->x;
gamestate.killy = player->y;
NewState (ob,&s_schabbdie1);
A_DeathScream(ob);
break;
case fakeobj:
GivePoints (2000);
NewState (ob,&s_fakedie1);
break;
case mechahitlerobj:
GivePoints (5000);
NewState (ob,&s_mechadie1);
break;
case realhitlerobj:
GivePoints (5000);
gamestate.killx = player->x;
gamestate.killy = player->y;
NewState (ob,&s_hitlerdie1);
A_DeathScream(ob);
break;
#else
case spectreobj:
if (ob->flags&FL_BONUS)
{
GivePoints (200); // Get points once for each
ob->flags &= ~FL_BONUS;
}
NewState (ob,&s_spectredie1);
break;
case angelobj:
GivePoints (5000);
NewState (ob,&s_angeldie1);
break;
case transobj:
GivePoints (5000);
NewState (ob,&s_transdie0);
PlaceItemType (bo_key1,tilex,tiley);
break;
case uberobj:
GivePoints (5000);
NewState (ob,&s_uberdie0);
PlaceItemType (bo_key1,tilex,tiley);
break;
case willobj:
GivePoints (5000);
NewState (ob,&s_willdie1);
PlaceItemType (bo_key1,tilex,tiley);
break;
case deathobj:
GivePoints (5000);
NewState (ob,&s_deathdie1);
PlaceItemType (bo_key1,tilex,tiley);
break;
#endif
}
gamestate.killcount++;
ob->flags &= ~FL_SHOOTABLE;
actorat[ob->tilex][ob->tiley] = NULL;
ob->flags |= FL_NONMARK;
}
/*
===================
=
= DamageActor
=
= Called when the player succesfully hits an enemy.
=
= Does damage points to enemy ob, either putting it into a stun frame or
= killing it.
=
===================
*/
void DamageActor (objtype *ob, unsigned damage)
{
madenoise = true;
//
// do double damage if shooting a non attack mode actor
//
if ( !(ob->flags & FL_ATTACKMODE) )
damage <<= 1;
ob->hitpoints -= (short)damage;
if (ob->hitpoints<=0)
KillActor (ob);
else
{
if (! (ob->flags & FL_ATTACKMODE) )
FirstSighting (ob); // put into combat mode
switch (ob->obclass) // dogs only have one hit point
{
case guardobj:
if (ob->hitpoints&1)
NewState (ob,&s_grdpain);
else
NewState (ob,&s_grdpain1);
break;
case officerobj:
if (ob->hitpoints&1)
NewState (ob,&s_ofcpain);
else
NewState (ob,&s_ofcpain1);
break;
case mutantobj:
if (ob->hitpoints&1)
NewState (ob,&s_mutpain);
else
NewState (ob,&s_mutpain1);
break;
case ssobj:
if (ob->hitpoints&1)
NewState (ob,&s_sspain);
else
NewState (ob,&s_sspain1);
break;
}
}
}
/*
=============================================================================
CHECKSIGHT
=============================================================================
*/
/*
=====================
=
= CheckLine
=
= Returns true if a straight line between the player and ob is unobstructed
=
=====================
*/
boolean CheckLine (objtype *ob)
{
int x1,y1,xt1,yt1,x2,y2,xt2,yt2;
int x,y;
int xdist,ydist,xstep,ystep;
int partial,delta;
long ltemp;
int xfrac,yfrac,deltafrac;
unsigned value,intercept;
x1 = ob->x >> UNSIGNEDSHIFT; // 1/256 tile precision
y1 = ob->y >> UNSIGNEDSHIFT;
xt1 = x1 >> 8;
yt1 = y1 >> 8;
x2 = plux;
y2 = pluy;
xt2 = player->tilex;
yt2 = player->tiley;
xdist = abs(xt2-xt1);
if (xdist > 0)
{
if (xt2 > xt1)
{
partial = 256-(x1&0xff);
xstep = 1;
}
else
{
partial = x1&0xff;
xstep = -1;
}
deltafrac = abs(x2-x1);
delta = y2-y1;
ltemp = ((long)delta<<8)/deltafrac;
if (ltemp > 0x7fffl)
ystep = 0x7fff;
else if (ltemp < -0x7fffl)
ystep = -0x7fff;
else
ystep = ltemp;
yfrac = y1 + (((long)ystep*partial) >>8);
x = xt1+xstep;
xt2 += xstep;
do
{
y = yfrac>>8;
yfrac += ystep;
value = (unsigned)tilemap[x][y];
x += xstep;
if (!value)
continue;
if (value<128 || value>256)
return false;
//
// see if the door is open enough
//
value &= ~0x80;
intercept = yfrac-ystep/2;
if (intercept>doorposition[value])
return false;
} while (x != xt2);
}
ydist = abs(yt2-yt1);
if (ydist > 0)
{
if (yt2 > yt1)
{
partial = 256-(y1&0xff);
ystep = 1;
}
else
{
partial = y1&0xff;
ystep = -1;
}
deltafrac = abs(y2-y1);
delta = x2-x1;
ltemp = ((long)delta<<8)/deltafrac;
if (ltemp > 0x7fffl)
xstep = 0x7fff;
else if (ltemp < -0x7fffl)
xstep = -0x7fff;
else
xstep = ltemp;
xfrac = x1 + (((long)xstep*partial) >>8);
y = yt1 + ystep;
yt2 += ystep;
do
{
x = xfrac>>8;
xfrac += xstep;
value = (unsigned)tilemap[x][y];
y += ystep;
if (!value)
continue;
if (value<128 || value>256)
return false;
//
// see if the door is open enough
//
value &= ~0x80;
intercept = xfrac-xstep/2;
if (intercept>doorposition[value])
return false;
} while (y != yt2);
}
return true;
}
/*
================
=
= CheckSight
=
= Checks a straight line between player and current object
=
= If the sight is ok, check alertness and angle to see if they notice
=
= returns true if the player has been spoted
=
================
*/
#define MINSIGHT 0x18000l
boolean CheckSight (objtype *ob)
{
long deltax,deltay;
//
// don't bother tracing a line if the area isn't connected to the player's
//
if (!areabyplayer[ob->areanumber])
return false;
//
// if the player is real close, sight is automatic
//
deltax = player->x - ob->x;
deltay = player->y - ob->y;
if (deltax > -MINSIGHT && deltax < MINSIGHT
&& deltay > -MINSIGHT && deltay < MINSIGHT)
return true;
//
// see if they are looking in the right direction
//
switch (ob->dir)
{
case north:
if (deltay > 0)
return false;
break;
case east:
if (deltax < 0)
return false;
break;
case south:
if (deltay < 0)
return false;
break;
case west:
if (deltax > 0)
return false;
break;
// check diagonal moving guards fix
case northwest:
if (deltay > -deltax)
return false;
break;
case northeast:
if (deltay > deltax)
return false;
break;
case southwest:
if (deltax > deltay)
return false;
break;
case southeast:
if (-deltax > deltay)
return false;
break;
}
//
// trace a line to check for blocking tiles (corners)
//
return CheckLine (ob);
}
/*
===============
=
= FirstSighting
=
= Puts an actor into attack mode and possibly reverses the direction
= if the player is behind it
=
===============
*/
void FirstSighting (objtype *ob)
{
//
// react to the player
//
switch (ob->obclass)
{
case guardobj:
PlaySoundLocActor(HALTSND,ob);
NewState (ob,&s_grdchase1);
ob->speed *= 3; // go faster when chasing player
break;
case officerobj:
PlaySoundLocActor(SPIONSND,ob);
NewState (ob,&s_ofcchase1);
ob->speed *= 5; // go faster when chasing player
break;
case mutantobj:
NewState (ob,&s_mutchase1);
ob->speed *= 3; // go faster when chasing player
break;
case ssobj:
PlaySoundLocActor(SCHUTZADSND,ob);
NewState (ob,&s_sschase1);
ob->speed *= 4; // go faster when chasing player
break;
case dogobj:
PlaySoundLocActor(DOGBARKSND,ob);
NewState (ob,&s_dogchase1);
ob->speed *= 2; // go faster when chasing player
break;
#ifndef SPEAR
case bossobj:
SD_PlaySound(GUTENTAGSND);
NewState (ob,&s_bosschase1);
ob->speed = SPDPATROL*3; // go faster when chasing player
break;
case gretelobj:
SD_PlaySound(KEINSND);
NewState (ob,&s_gretelchase1);
ob->speed *= 3; // go faster when chasing player
break;
case giftobj:
SD_PlaySound(EINESND);
NewState (ob,&s_giftchase1);
ob->speed *= 3; // go faster when chasing player
break;
case fatobj:
SD_PlaySound(ERLAUBENSND);
NewState (ob,&s_fatchase1);
ob->speed *= 3; // go faster when chasing player
break;
case schabbobj:
SD_PlaySound(SCHABBSHASND);
NewState (ob,&s_schabbchase1);
ob->speed *= 3; // go faster when chasing player
break;
case fakeobj:
SD_PlaySound(TOT_HUNDSND);
NewState (ob,&s_fakechase1);
ob->speed *= 3; // go faster when chasing player
break;
case mechahitlerobj:
SD_PlaySound(DIESND);
NewState (ob,&s_mechachase1);
ob->speed *= 3; // go faster when chasing player
break;
case realhitlerobj:
SD_PlaySound(DIESND);
NewState (ob,&s_hitlerchase1);
ob->speed *= 5; // go faster when chasing player
break;
case ghostobj:
NewState (ob,&s_blinkychase1);
ob->speed *= 2; // go faster when chasing player
break;
#else
case spectreobj:
SD_PlaySound(GHOSTSIGHTSND);
NewState (ob,&s_spectrechase1);
ob->speed = 800; // go faster when chasing player
break;
case angelobj:
SD_PlaySound(ANGELSIGHTSND);
NewState (ob,&s_angelchase1);
ob->speed = 1536; // go faster when chasing player
break;
case transobj:
SD_PlaySound(TRANSSIGHTSND);
NewState (ob,&s_transchase1);
ob->speed = 1536; // go faster when chasing player
break;
case uberobj:
NewState (ob,&s_uberchase1);
ob->speed = 3000; // go faster when chasing player
break;
case willobj:
SD_PlaySound(WILHELMSIGHTSND);
NewState (ob,&s_willchase1);
ob->speed = 2048; // go faster when chasing player
break;
case deathobj:
SD_PlaySound(KNIGHTSIGHTSND);
NewState (ob,&s_deathchase1);
ob->speed = 2048; // go faster when chasing player
break;
#endif
}
if (ob->distance < 0)
ob->distance = 0; // ignore the door opening command
ob->flags |= FL_ATTACKMODE|FL_FIRSTATTACK;
}
/*
===============
=
= SightPlayer
=
= Called by actors that ARE NOT chasing the player. If the player
= is detected (by sight, noise, or proximity), the actor is put into
= it's combat frame and true is returned.
=
= Incorporates a random reaction delay
=
===============
*/
boolean SightPlayer (objtype *ob)
{
if (ob->flags & FL_ATTACKMODE)
Quit ("An actor in ATTACKMODE called SightPlayer!");
if (ob->temp2)
{
//
// count down reaction time
//
ob->temp2 -= (short) tics;
if (ob->temp2 > 0)
return false;
ob->temp2 = 0; // time to react
}
else
{
if (!areabyplayer[ob->areanumber])
return false;
if (ob->flags & FL_AMBUSH)
{
if (!CheckSight (ob))
return false;
ob->flags &= ~FL_AMBUSH;
}
else
{
if (!madenoise && !CheckSight (ob))
return false;
}
switch (ob->obclass)
{
case guardobj:
ob->temp2 = 1+US_RndT()/4;
break;
case officerobj:
ob->temp2 = 2;
break;
case mutantobj:
ob->temp2 = 1+US_RndT()/6;
break;
case ssobj:
ob->temp2 = 1+US_RndT()/6;
break;
case dogobj:
ob->temp2 = 1+US_RndT()/8;
break;
case bossobj:
case schabbobj:
case fakeobj:
case mechahitlerobj:
case realhitlerobj:
case gretelobj:
case giftobj:
case fatobj:
case spectreobj:
case angelobj:
case transobj:
case uberobj:
case willobj:
case deathobj:
ob->temp2 = 1;
break;
}
return false;
}
FirstSighting (ob);
return true;
}
| 28.339726 | 101 | 0.357284 | TobiasKarnat |
8d2bd7d6a9dfa98cf123dc64d71bb01ca37b79d1 | 26,078 | cpp | C++ | editor/gui/src/renderersettingsdialog.cpp | lizardkinger/blacksun | 0119948726d2a057c13d208044c7664a8348a1ea | [
"Linux-OpenIB"
] | null | null | null | editor/gui/src/renderersettingsdialog.cpp | lizardkinger/blacksun | 0119948726d2a057c13d208044c7664a8348a1ea | [
"Linux-OpenIB"
] | null | null | null | editor/gui/src/renderersettingsdialog.cpp | lizardkinger/blacksun | 0119948726d2a057c13d208044c7664a8348a1ea | [
"Linux-OpenIB"
] | null | null | null | /***************************************************************************
* Copyright (C) 2006 by The Hunter *
* hunter@localhost *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#include "./../include/renderersettingsdialog.h"
namespace BSGui
{
RendererSettingsDialog::RendererSettingsDialog()
{
ui.setupUi(this);
renderer = BSRenderer::Renderer::getInstance();
rendererSettings = renderer->getSettings();
setColors();
setNumbers();
setCheckboxses();
connect(ui.saveColorButton, SIGNAL(clicked()), this, SLOT(saveColorButtonClicked()));
connect(ui.loadColorButton, SIGNAL(clicked()), this, SLOT(loadColorButtonClicked()));
connect(ui.resetColorsButton, SIGNAL(clicked()), this, SLOT(resetColorsButtonClicked()));
connect(ui.lineColorLabel, SIGNAL(colorChanged(QColor)), this, SLOT(optionsChanged()));
connect(ui.lineSelectedColorLabel, SIGNAL(colorChanged(QColor)), this, SLOT(optionsChanged()));
connect(ui.pointColorLabel, SIGNAL(colorChanged(QColor)), this, SLOT(optionsChanged()));
connect(ui.pointSelectedColorLabel, SIGNAL(colorChanged(QColor)), this, SLOT(optionsChanged()));
connect(ui.freezeColorLabel, SIGNAL(colorChanged(QColor)), this, SLOT(optionsChanged()));
connect(ui.normalColorLabel, SIGNAL(colorChanged(QColor)), this, SLOT(optionsChanged()));
connect(ui.selectionAABBColorLabel, SIGNAL(colorChanged(QColor)), this, SLOT(optionsChanged()));
connect(ui.orthogonalViewColorLabel, SIGNAL(colorChanged(QColor)), this, SLOT(optionsChanged()));
connect(ui.perspectiveViewColorLabel, SIGNAL(colorChanged(QColor)), this, SLOT(optionsChanged()));
connect(ui.majorGridLineColorLabel, SIGNAL(colorChanged(QColor)), this, SLOT(optionsChanged()));
connect(ui.minorGridLineColorLabel, SIGNAL(colorChanged(QColor)), this, SLOT(optionsChanged()));
connect(ui.rubberBandColorLabel, SIGNAL(colorChanged(QColor)), this, SLOT(optionsChanged()));
connect(ui.overpaintingColorLabel, SIGNAL(colorChanged(QColor)), this, SLOT(optionsChanged()));
connect(ui.gridSize, SIGNAL(valueChanged(int)), this, SLOT(optionsChanged()));
connect(ui.lineWidth, SIGNAL(valueChanged(double)), this, SLOT(optionsChanged()));
connect(ui.pointSize, SIGNAL(valueChanged(double)), this, SLOT(optionsChanged()));
connect(ui.normalScaling, SIGNAL(valueChanged(double)), this, SLOT(optionsChanged()));
connect(ui.selectionAABBScaling, SIGNAL(valueChanged(double)), this, SLOT(optionsChanged()));
connect(ui.wireframeOverlayScaling, SIGNAL(valueChanged(double)), this, SLOT(optionsChanged()));
connect(ui.cameraFOV, SIGNAL(valueChanged(double)), this, SLOT(optionsChanged()));
connect(ui.nearPlane, SIGNAL(valueChanged(double)), this, SLOT(optionsChanged()));
connect(ui.farPlane, SIGNAL(valueChanged(double)), this, SLOT(optionsChanged()));
connect(ui.mouseWheelSpeed, SIGNAL(valueChanged(double)), this, SLOT(optionsChanged()));
connect(ui.cullingCheckBox, SIGNAL(stateChanged(int)), this, SLOT(optionsChanged()));
connect(ui.lineSmoothingCheckBox, SIGNAL(stateChanged(int)), this, SLOT(optionsChanged()));
connect(ui.pointSmoothingCheckBox, SIGNAL(stateChanged(int)), this, SLOT(optionsChanged()));
connect(ui.polygonSmoothingCheckBox, SIGNAL(stateChanged(int)), this, SLOT(optionsChanged()));
}
void RendererSettingsDialog::optionsChanged()
{
emit statusChanged(checkOptionsChanged());
}
void RendererSettingsDialog::dialogAccept()
{
writeColors();
writeNumbers();
writeCheckboxses();
emit statusChanged(false);
}
void RendererSettingsDialog::reset()
{
setColors();
setNumbers();
setCheckboxses();
}
void RendererSettingsDialog::setColors()
{
Color wireframeColor = rendererSettings->getWireframeColor();
ui.lineColorLabel->setColor(ColorToQColor(wireframeColor));
Color wireframeSelectionColor = rendererSettings->getWireframeSelectionColor();
ui.lineSelectedColorLabel->setColor(ColorToQColor(wireframeSelectionColor));
Color pointColor = rendererSettings->getPointColor();
ui.pointColorLabel->setColor(ColorToQColor(pointColor));
Color selectedPointsColor = rendererSettings->getPointSelectionColor();
ui.pointSelectedColorLabel->setColor(ColorToQColor(selectedPointsColor));
Color freezedColor = rendererSettings->getFreezeColor();
ui.freezeColorLabel->setColor(ColorToQColor(freezedColor));
Color normalColor = rendererSettings->getNormalColor();
ui.normalColorLabel->setColor(ColorToQColor(normalColor));
Color selectionAABBColor = rendererSettings->getSelectionAABBColor();
ui.selectionAABBColorLabel->setColor(ColorToQColor(selectionAABBColor));
Color colorOrtho = rendererSettings->getClearColorOrtho();
ui.orthogonalViewColorLabel->setColor(ColorToQColor(colorOrtho));
Color colorPerspective = rendererSettings->getClearColorPerspective();
ui.perspectiveViewColorLabel->setColor(ColorToQColor(colorPerspective));
Color majorLineColor = rendererSettings->getGridMajorLineColor();
ui.majorGridLineColorLabel->setColor(ColorToQColor(majorLineColor));
Color minorLineColor = rendererSettings->getGridMinorLineColor();
ui.minorGridLineColorLabel->setColor(ColorToQColor(minorLineColor));
ui.rubberBandColorLabel->setColor(MainWindow::getInstance()->getContainer()->getSelectionBoxColor());
ui.overpaintingColorLabel->setColor(MainWindow::getInstance()->getContainer()->getOverpaintingColor());
}
void RendererSettingsDialog::writeColors()
{
QColor wireframeColor = ui.lineColorLabel->getColor();
rendererSettings->setWireframeColor(QColorToColor(wireframeColor));
QColor wireframeSelectionColor = ui.lineSelectedColorLabel->getColor();
rendererSettings->setWireframeSelectionColor(QColorToColor(wireframeSelectionColor));
QColor pointColor = ui.pointColorLabel->getColor();
rendererSettings->setPointColor(QColorToColor(pointColor));
QColor selectedPointsColor = ui.pointSelectedColorLabel->getColor();
rendererSettings->setPointSelectionColor(QColorToColor(selectedPointsColor));
QColor freezedColor = ui.freezeColorLabel->getColor();
rendererSettings->setFreezeColor(QColorToColor(freezedColor));
QColor normalColor = ui.normalColorLabel->getColor();
rendererSettings->setNormalColor(QColorToColor(normalColor));
QColor selectionAABBColor = ui.selectionAABBColorLabel->getColor();
rendererSettings->setSelectionAABBColor(QColorToColor(selectionAABBColor));
QColor colorOrtho = ui.orthogonalViewColorLabel->getColor();
rendererSettings->setClearColorOrtho(QColorToColor(colorOrtho));
QColor colorPerspective = ui.perspectiveViewColorLabel->getColor();
rendererSettings->setClearColorPerspective(QColorToColor(colorPerspective));
QColor majorLineColor = ui.majorGridLineColorLabel->getColor();
rendererSettings->setGridMajorLineColor(QColorToColor(majorLineColor));
QColor minorLineColor = ui.minorGridLineColorLabel->getColor();
rendererSettings->setGridMinorLineColor(QColorToColor(minorLineColor));
MainWindow::getInstance()->getContainer()->setSelectionBoxColor(ui.rubberBandColorLabel->getColor());
MainWindow::getInstance()->getContainer()->setOverpaintingColor(ui.overpaintingColorLabel->getColor());
}
void RendererSettingsDialog::setNumbers()
{
int gridSize = rendererSettings->getGridSize();
ui.gridSize->setValue(gridSize);
double lineWidth = rendererSettings->getLineWidth();
ui.lineWidth->setValue(lineWidth);
double pointSize = rendererSettings->getPointSize();
ui.pointSize->setValue(pointSize);
double normalScaling = rendererSettings->getNormalScaling();
ui.normalScaling->setValue(normalScaling);
double selectionAABBScaling = rendererSettings->getSelectionAABBScaling();
ui.selectionAABBScaling->setValue(selectionAABBScaling);
double wireframeOverlayScaling = rendererSettings->getWireframeOverlayScaling();
ui.wireframeOverlayScaling->setValue(wireframeOverlayScaling);
double FOV = rendererSettings->getFOV();
ui.cameraFOV->setValue(FOV);
double nearPlane = rendererSettings->getNearPlane();
ui.nearPlane->setValue(nearPlane);
double farPlane = rendererSettings->getFarPlane();
ui.farPlane->setValue(farPlane);
double mouseWheelSpeed = rendererSettings->getMouseWheelSpeed();
ui.mouseWheelSpeed->setValue(mouseWheelSpeed);
}
void RendererSettingsDialog::writeNumbers()
{
int gridSize = ui.gridSize->value();
rendererSettings->setGridSize(gridSize);
double lineWidth = ui.lineWidth->value();
rendererSettings->setLineWidth(lineWidth);
double pointSize = ui.pointSize->value();
rendererSettings->setPointSize(pointSize);
double normalScaling = ui.normalScaling->value();
rendererSettings->setNormalScaling(normalScaling);
double selectionAABBScaling = ui.selectionAABBScaling->value();
rendererSettings->setSelectionAABBScaling(selectionAABBScaling);
double wireframeOverlayScaling = ui.wireframeOverlayScaling->value();
rendererSettings->setWireframeOverlayScaling(wireframeOverlayScaling);
double FOV = ui.cameraFOV->value();
rendererSettings->setFOV(FOV);
double nearPlane = ui.nearPlane->value();
rendererSettings->setNearPlane(nearPlane);
double farPlane = ui.farPlane->value();
rendererSettings->setFarPlane(farPlane);
double mouseWheelSpeed = ui.mouseWheelSpeed->value();
rendererSettings->setMouseWheelSpeed(mouseWheelSpeed);
}
void RendererSettingsDialog::saveColorButtonClicked()
{
QFileDialog* fileDialog = new QFileDialog(this, "Please select the destination", QDir::currentPath(), "Blacksun Color Schemes (*.bsscheme)");
fileDialog->setDefaultSuffix("bsscheme");
fileDialog->setFileMode(QFileDialog::AnyFile);
fileDialog->setAcceptMode(QFileDialog::AcceptSave);
QString pathToFile = "";
if (fileDialog->exec())
{
QStringList pathToFiles;
pathToFiles = fileDialog->selectedFiles();
if (!pathToFiles.isEmpty())
{
pathToFile = pathToFiles.at(0);
}
}
if (pathToFile == "")
{
return;
}
QFile file(pathToFile);
if(!file.open(QIODevice::WriteOnly | QIODevice::Text))
{
QMessageBox::critical(this, "Error", "Unable to open file");
return;
}
QTextStream outputStream(&file);
outputStream << getColorScheme();
}
void RendererSettingsDialog::loadColorButtonClicked()
{
QString pathToFile = QFileDialog::getOpenFileName(this, "Please select the Scheme File", QDir::currentPath(), "Blacksun Color Schemes (*.bsscheme)");
if (pathToFile == "")
{
return;
}
QFile file(pathToFile);
if(!file.open(QIODevice::ReadOnly | QIODevice::Text))
{
QMessageBox::critical(this, "Error", "Unable to open file");
return;
}
QString colorScheme;
while (!file.atEnd())
{
colorScheme.append(file.readLine());
}
if(!setColorScheme(colorScheme))
{
QMessageBox::critical(this, "Error", "File is not a valid Blacksun Scheme file");
}
}
void RendererSettingsDialog::setCheckboxses()
{
ui.cullingCheckBox->setChecked(rendererSettings->getEnableFrustumCulling());
ui.lineSmoothingCheckBox->setChecked(rendererSettings->getLineSmoothing());
ui.pointSmoothingCheckBox->setChecked(rendererSettings->getPointSmoothing());
ui.polygonSmoothingCheckBox->setChecked(rendererSettings->getPolygonSmoothing());
}
void RendererSettingsDialog::writeCheckboxses()
{
rendererSettings->enableFrustumCulling(ui.cullingCheckBox->isChecked());
rendererSettings->setLineSmoothing(ui.lineSmoothingCheckBox->isChecked());
rendererSettings->setPointSmoothing(ui.pointSmoothingCheckBox->isChecked());
rendererSettings->setPolygonSmoothing(ui.polygonSmoothingCheckBox->isChecked());
}
QString RendererSettingsDialog::getColorScheme()
{
QDomDocument scheme("BSColorScheme");
QDomElement root = scheme.createElement("ColorScheme");
scheme.appendChild(root);
QDomElement wireframeColor = scheme.createElement("wireframeColor");
wireframeColor.setAttribute("Red", ui.lineColorLabel->getColor().redF());
wireframeColor.setAttribute("Green", ui.lineColorLabel->getColor().greenF());
wireframeColor.setAttribute("Blue", ui.lineColorLabel->getColor().blueF());
root.appendChild(wireframeColor);
QDomElement wireframeSelectionColor = scheme.createElement("wireframeSelectionColor");
wireframeSelectionColor.setAttribute("Red", ui.lineSelectedColorLabel->getColor().redF());
wireframeSelectionColor.setAttribute("Green", ui.lineSelectedColorLabel->getColor().greenF());
wireframeSelectionColor.setAttribute("Blue", ui.lineSelectedColorLabel->getColor().blueF());
root.appendChild(wireframeSelectionColor);
QDomElement pointColor = scheme.createElement("pointColor");
pointColor.setAttribute("Red", ui.pointColorLabel->getColor().redF());
pointColor.setAttribute("Green", ui.pointColorLabel->getColor().greenF());
pointColor.setAttribute("Blue", ui.pointColorLabel->getColor().blueF());
root.appendChild(pointColor);
QDomElement selectedPointsColor = scheme.createElement("selectedPointsColor");
selectedPointsColor.setAttribute("Red", ui.pointSelectedColorLabel->getColor().redF());
selectedPointsColor.setAttribute("Green", ui.pointSelectedColorLabel->getColor().greenF());
selectedPointsColor.setAttribute("Blue", ui.pointSelectedColorLabel->getColor().blueF());
root.appendChild(selectedPointsColor);
QDomElement freezedColor = scheme.createElement("freezedColor");
freezedColor.setAttribute("Red", ui.freezeColorLabel->getColor().redF());
freezedColor.setAttribute("Green", ui.freezeColorLabel->getColor().greenF());
freezedColor.setAttribute("Blue", ui.freezeColorLabel->getColor().blueF());
root.appendChild(freezedColor);
QDomElement normalColor = scheme.createElement("normalColor");
normalColor.setAttribute("Red", ui.normalColorLabel->getColor().redF());
normalColor.setAttribute("Green", ui.normalColorLabel->getColor().greenF());
normalColor.setAttribute("Blue", ui.normalColorLabel->getColor().blueF());
root.appendChild(normalColor);
QDomElement selectionAABBColor = scheme.createElement("selectionAABBColor");
selectionAABBColor.setAttribute("Red", ui.selectionAABBColorLabel->getColor().redF());
selectionAABBColor.setAttribute("Green", ui.selectionAABBColorLabel->getColor().greenF());
selectionAABBColor.setAttribute("Blue", ui.selectionAABBColorLabel->getColor().blueF());
root.appendChild(selectionAABBColor);
QDomElement colorOrtho = scheme.createElement("colorOrtho");
colorOrtho.setAttribute("Red", ui.orthogonalViewColorLabel->getColor().redF());
colorOrtho.setAttribute("Green", ui.orthogonalViewColorLabel->getColor().greenF());
colorOrtho.setAttribute("Blue", ui.orthogonalViewColorLabel->getColor().blueF());
root.appendChild(colorOrtho);
QDomElement colorPerspective = scheme.createElement("colorPerspective");
colorPerspective.setAttribute("Red", ui.perspectiveViewColorLabel->getColor().redF());
colorPerspective.setAttribute("Green", ui.perspectiveViewColorLabel->getColor().greenF());
colorPerspective.setAttribute("Blue", ui.perspectiveViewColorLabel->getColor().blueF());
root.appendChild(colorPerspective);
QDomElement majorLineColor = scheme.createElement("majorLineColor");
majorLineColor.setAttribute("Red", ui.majorGridLineColorLabel->getColor().redF());
majorLineColor.setAttribute("Green", ui.majorGridLineColorLabel->getColor().greenF());
majorLineColor.setAttribute("Blue", ui.majorGridLineColorLabel->getColor().blueF());
root.appendChild(majorLineColor);
QDomElement minorLineColor = scheme.createElement("minorLineColor");
minorLineColor.setAttribute("Red", ui.minorGridLineColorLabel->getColor().redF());
minorLineColor.setAttribute("Green", ui.minorGridLineColorLabel->getColor().greenF());
minorLineColor.setAttribute("Blue", ui.minorGridLineColorLabel->getColor().blueF());
root.appendChild(minorLineColor);
QDomElement rubberBandColor = scheme.createElement("rubberBandColor");
rubberBandColor.setAttribute("Red", ui.rubberBandColorLabel->getColor().redF());
rubberBandColor.setAttribute("Green", ui.rubberBandColorLabel->getColor().greenF());
rubberBandColor.setAttribute("Blue", ui.rubberBandColorLabel->getColor().blueF());
root.appendChild(rubberBandColor);
QDomElement overpaintingColor = scheme.createElement("overpaintingColor");
overpaintingColor.setAttribute("Red", ui.overpaintingColorLabel->getColor().redF());
overpaintingColor.setAttribute("Green", ui.overpaintingColorLabel->getColor().greenF());
overpaintingColor.setAttribute("Blue", ui.overpaintingColorLabel->getColor().blueF());
root.appendChild(overpaintingColor);
return scheme.toString();
}
bool RendererSettingsDialog::setColorScheme(const QString& colorScheme)
{
QDomDocument scheme("BSColorScheme");
scheme.setContent(colorScheme);
QDomElement root = scheme.documentElement();
if ( root.tagName() != "ColorScheme")
{
return false;
}
QDomNode currentNode = root.firstChild();
while(!currentNode.isNull())
{
QDomElement currentElement = currentNode.toElement();
{
if(!currentElement.isNull())
{
QString currentTagName = currentElement.tagName();
if(currentTagName == "wireframeColor")
{
ui.lineColorLabel->setColor(colorFromElement(currentElement));
}
else if(currentTagName == "wireframeSelectionColor")
{
ui.lineSelectedColorLabel->setColor(colorFromElement(currentElement));
}
else if(currentTagName == "pointColor")
{
ui.pointColorLabel->setColor(colorFromElement(currentElement));
}
else if(currentTagName == "selectedPointsColor")
{
ui.pointSelectedColorLabel->setColor(colorFromElement(currentElement));
}
else if(currentTagName == "freezedColor")
{
ui.freezeColorLabel->setColor(colorFromElement(currentElement));
}
else if(currentTagName == "normalColor")
{
ui.normalColorLabel->setColor(colorFromElement(currentElement));
}
else if(currentTagName == "selectionAABBColor")
{
ui.selectionAABBColorLabel->setColor(colorFromElement(currentElement));
}
else if(currentTagName == "colorOrtho")
{
ui.orthogonalViewColorLabel->setColor(colorFromElement(currentElement));
}
else if(currentTagName == "colorPerspective")
{
ui.perspectiveViewColorLabel->setColor(colorFromElement(currentElement));
}
else if(currentTagName == "majorLineColor")
{
ui.majorGridLineColorLabel->setColor(colorFromElement(currentElement));
}
else if(currentTagName == "minorLineColor")
{
ui.minorGridLineColorLabel->setColor(colorFromElement(currentElement));
}
else if(currentTagName == "rubberBandColor")
{
ui.rubberBandColorLabel->setColor(colorFromElement(currentElement));
}
else if(currentTagName == "overpaintingColor")
{
ui.overpaintingColorLabel->setColor(colorFromElement(currentElement));
}
}
}
currentNode = currentNode.nextSibling();
}
return true;
}
bool RendererSettingsDialog::checkOptionsChanged()
{
if(
ui.lineColorLabel->getColor() == ColorToQColor(rendererSettings->getWireframeColor())
&&
ui.lineSelectedColorLabel->getColor() == ColorToQColor(rendererSettings->getWireframeSelectionColor())
&&
ui.pointColorLabel->getColor() == ColorToQColor(rendererSettings->getPointColor())
&&
ui.pointSelectedColorLabel->getColor() == ColorToQColor(rendererSettings->getPointSelectionColor())
&&
ui.freezeColorLabel->getColor() == ColorToQColor(rendererSettings->getFreezeColor())
&&
ui.normalColorLabel->getColor() == ColorToQColor(rendererSettings->getNormalColor())
&&
ui.selectionAABBColorLabel->getColor() == ColorToQColor(rendererSettings->getSelectionAABBColor())
&&
ui.orthogonalViewColorLabel->getColor() == ColorToQColor(rendererSettings->getClearColorOrtho())
&&
ui.perspectiveViewColorLabel->getColor() == ColorToQColor(rendererSettings->getClearColorPerspective())
&&
ui.majorGridLineColorLabel->getColor() == ColorToQColor(rendererSettings->getGridMajorLineColor())
&&
ui.minorGridLineColorLabel->getColor() == ColorToQColor(rendererSettings->getGridMinorLineColor())
&&
ui.rubberBandColorLabel->getColor() == MainWindow::getInstance()->getContainer()->getSelectionBoxColor()
&&
ui.overpaintingColorLabel->getColor() == MainWindow::getInstance()->getContainer()->getOverpaintingColor()
&&
ui.gridSize->value() == rendererSettings->getGridSize()
&&
ui.lineWidth->value() == rendererSettings->getLineWidth()
&&
ui.pointSize->value() == rendererSettings->getPointSize()
&&
ui.normalScaling->value() == rendererSettings->getNormalScaling()
&&
ui.selectionAABBScaling->value() == rendererSettings->getSelectionAABBScaling()
&&
ui.wireframeOverlayScaling->value() == rendererSettings->getWireframeOverlayScaling()
&&
ui.cameraFOV->value() == rendererSettings->getFOV()
&&
ui.nearPlane->value() == rendererSettings->getNearPlane()
&&
ui.farPlane->value() == rendererSettings->getFarPlane()
&&
ui.mouseWheelSpeed->value() == rendererSettings->getMouseWheelSpeed()
&&
ui.cullingCheckBox->isChecked() == rendererSettings->getEnableFrustumCulling()
&&
ui.lineSmoothingCheckBox->isChecked() == rendererSettings->getLineSmoothing()
&&
ui.pointSmoothingCheckBox->isChecked() == rendererSettings->getPointSmoothing()
&&
ui.polygonSmoothingCheckBox->isChecked() == rendererSettings->getPolygonSmoothing()
)
{
return false;
}
else
{
return true;
}
}
void RendererSettingsDialog::resetColorsButtonClicked()
{
QString stdColor = "";
stdColor.append("<!DOCTYPE BSColorScheme>");
stdColor.append("<ColorScheme>");
stdColor.append("<wireframeColor Blue=\"1\" Red=\"1\" Green=\"1\" />");
stdColor.append("<wireframeSelectionColor Blue=\"0\" Red=\"1\" Green=\"0\" />");
stdColor.append("<pointColor Blue=\"0\" Red=\"1\" Green=\"1\" />");
stdColor.append("<selectedPointsColor Blue=\"0\" Red=\"1\" Green=\"0.5000076295109483\" />");
stdColor.append("<freezedColor Blue=\"1\" Red=\"0.5499961852445259\" Green=\"0.6\" />");
stdColor.append("<normalColor Blue=\"1\" Red=\"1\" Green=\"0\" />");
stdColor.append("<selectionAABBColor Blue=\"0\" Red=\"0\" Green=\"1\" />");
stdColor.append("<colorOrtho Blue=\"0.8\" Red=\"0.8\" Green=\"0.8\" />");
stdColor.append("<colorPerspective Blue=\"0.6999923704890516\" Red=\"0.2\" Green=\"0.5000076295109483\" />");
stdColor.append("<majorLineColor Blue=\"0\" Red=\"0.5000076295109483\" Green=\"0.5000076295109483\" />");
stdColor.append("<minorLineColor Blue=\"0.6999923704890516\" Red=\"0.6999923704890516\" Green=\"0.6999923704890516\" />");
stdColor.append("<rubberBandColor Blue=\"1.0\" Red=\"0\" Green=\"0\" />");
stdColor.append("<overpaintingColor Blue=\"0\" Red=\"0\" Green=\"0\" />");
stdColor.append("</ColorScheme>");
setColorScheme(stdColor);
}
QColor RendererSettingsDialog::colorFromElement(QDomElement e)
{
qreal red = e.attribute("Red").toDouble();
qreal green = e.attribute("Green").toDouble();
qreal blue = e.attribute("Blue").toDouble();
return QColor::fromRgbF(red, green, blue);
}
}
| 44.884682 | 153 | 0.685904 | lizardkinger |
8d2d7a1a6f9488a109c822e7b22271da217db9a9 | 1,621 | cc | C++ | src/exceptions.cc | websms-com/websmscom-cpp | a9214bd7dcc02c0e058a345e353d7417597f77c9 | [
"MIT"
] | null | null | null | src/exceptions.cc | websms-com/websmscom-cpp | a9214bd7dcc02c0e058a345e353d7417597f77c9 | [
"MIT"
] | null | null | null | src/exceptions.cc | websms-com/websmscom-cpp | a9214bd7dcc02c0e058a345e353d7417597f77c9 | [
"MIT"
] | null | null | null | /**
* Copyright (C) 2012, sms.at mobile internet services gmbh
*
* @author Markus Opitz
*/
#include <websms/exceptions.h>
#include <websms/misc.h>
namespace websms {
Exception::Exception(const char* message)
: message_(Strdup(message)),
error_code_(0) {
}
Exception::Exception(const char* message, int error_code)
: message_(Strdup(message)),
error_code_(error_code) {
}
Exception::Exception(const Exception& source)
: message_(Strdup(source.message_)),
error_code_(source.error_code_) {
}
Exception::~Exception() {
Strdel(message_);
}
Exception& Exception::operator=(const Exception& source) {
Strdel(message_);
message_ = Strdup(source.message_);
error_code_ = source.error_code_;
return *this;
}
const char* Exception::What() const {
return message_;
}
int Exception::error_code() const {
return error_code_;
}
const char* Exception::message() const {
return message_;
}
ApiException::ApiException(const char* status_message, int status_code)
: Exception(status_message, status_code) {
}
int ApiException::status_code() const {
return error_code();
}
const char* ApiException::status_message() const {
return message();
}
AuthorizationFailedException::AuthorizationFailedException(const char* message)
: Exception(message) {
}
HttpConnectionException::HttpConnectionException(const char* message,
int error_code)
: Exception(message, error_code) {
}
ParameterValidationException::ParameterValidationException(const char* message)
: Exception(message) {
}
} /* namespace websms */
| 21.051948 | 79 | 0.70512 | websms-com |
8d2f0cb539e2222afc2dc16dd34a35133ded3e76 | 787 | cpp | C++ | Core/Driver/vf_drv_clr/vf_task_clr.cpp | sartrey/vapula | 557dff9cf526eee6fe5b787f25c80a972c1451de | [
"Apache-2.0"
] | 1 | 2019-04-17T14:45:49.000Z | 2019-04-17T14:45:49.000Z | Core/Driver/vf_drv_clr/vf_task_clr.cpp | sartrey/vapula | 557dff9cf526eee6fe5b787f25c80a972c1451de | [
"Apache-2.0"
] | null | null | null | Core/Driver/vf_drv_clr/vf_task_clr.cpp | sartrey/vapula | 557dff9cf526eee6fe5b787f25c80a972c1451de | [
"Apache-2.0"
] | null | null | null | #include "vf_driver_clr.h"
#include "vf_task_clr.h"
#include "vf_library_clr.h"
#include "vf_stack.h"
TaskCLR::TaskCLR()
{
_Method = null;
}
TaskCLR::~TaskCLR()
{
}
pcstr TaskCLR::GetHandle()
{
LibraryCLR* library = (LibraryCLR*)_Method->GetLibrary();
return library->GetHandle();
}
bool TaskCLR::Bind(Method* method)
{
Task::Bind(method);
_Method = method;
return true;
}
void TaskCLR::OnProcess()
{
string args = GetHandle();
args += "|";
args += _Method->GetProcessSym();
DriverCLR* driver = DriverCLR::Instance();
driver->CallBridge("OnProcess", args.c_str());
}
void TaskCLR::OnRollback()
{
string args = GetHandle();
args += "|";
args += _Method->GetRollbackSym();
DriverCLR* driver = DriverCLR::Instance();
driver->CallBridge("OnRollback", args.c_str());
} | 17.108696 | 58 | 0.682338 | sartrey |
8d311bb4e267e2cbd7a1ea5b1468dbe911461477 | 769 | hpp | C++ | src/strings.hpp | Schumbi/flaschengeist | ffed5c2a858d77dd2216d2a124c2a0c5a089a924 | [
"MIT"
] | null | null | null | src/strings.hpp | Schumbi/flaschengeist | ffed5c2a858d77dd2216d2a124c2a0c5a089a924 | [
"MIT"
] | null | null | null | src/strings.hpp | Schumbi/flaschengeist | ffed5c2a858d77dd2216d2a124c2a0c5a089a924 | [
"MIT"
] | null | null | null | #ifndef MAKELIGHT_STRINGS_H
#define MAKELIGHT_STRINGS_H
#include <Arduino.h>
// ab in PROGMEM damit Todo
String Response = "";
String html_anfang = "<!DOCTYPE html>\r\n<html>\r\n\
<head>\r\n<meta content=\"text/html; charset=ISO-8859-1\" http-equiv=\"content-type\">\r\n\
<title>WebSchalter</title>\r\n<body><p>";
String html_ende = "</p></body>\r\n</html>";
String redirect = "<!DOCTYPE html>\r\n<html>\r\n\
<head>\r\n\
<meta content=\"text/html; charset=ISO-8859-1\" \
<meta http-equiv=\"refresh\" content=\"0; URL='./'\" /> \
</head><body/></html>";
String form = "<form action='led'><input type='radio' name='state' value='1' checked>On<input type='radio' name='state' value='0'>Off<input type='submit' value='Submit'></form>";
#endif // MAKELIGHT_STRINGS_H
| 32.041667 | 178 | 0.668401 | Schumbi |
8d3708e500f2bf0f134fd1b9dac83abf5b42093e | 1,831 | hpp | C++ | jobin/worker.hpp | Marcos30004347/jobin | 40eec7bf9579002426320253eae6eaaea6b50d10 | [
"Apache-2.0"
] | 2 | 2020-09-30T05:12:09.000Z | 2020-10-12T23:40:32.000Z | jobin/worker.hpp | Marcos30004347/Jobin | 40eec7bf9579002426320253eae6eaaea6b50d10 | [
"Apache-2.0"
] | null | null | null | jobin/worker.hpp | Marcos30004347/Jobin | 40eec7bf9579002426320253eae6eaaea6b50d10 | [
"Apache-2.0"
] | null | null | null | #ifndef JOBIN_WORKER_H
#define JOBIN_WORKER_H
#include "job.hpp"
#include "thread.hpp"
class worker;
thread_local static worker* current_worker = nullptr;
class worker {
friend void return_to_worker();
private:
/**
* handler of the worker.
*/
void(*handler)(void*);
/**
* voidless pointer to pass as argument to handler.
*/
void* arg = nullptr;
/**
* _thread of execution of this worker.
*/
thread* _thread = nullptr;
/**
* flag that signal if workers can stop pooling jobs.
*/
static bool should_pool;
/**
* number of currently running workers.
*/
static atomic<unsigned int> running_workers;
/**
* worker id.
*/
unsigned int id = 0;
/**
* Main routine of the worker, this function is responsable for
* pooling and executing jobs.
*/
static void do_work(void *data);
/**
* Routine responsable for setting up a worker for
* the do_work method.
*/
static void init_worker(void *data);
public:
/**
* worker contructor.
* @param handler: worker initial job;
* @param arg: initial argument.
*/
worker(void(*handler)(void*), void* arg);
/**
* worker contructor.
* @note: this contrutor dont dispatch any initial job.
*/
worker();
/**
* wait for current worker to return.
*/
void wait();
/**
* worker destructor.
*/
~worker();
/**
* Convert current thread to a worker.
*/
static void convert_thread_to_worker(void(*handler)(void*), void* arg);
class all_workers {
public:
/**
* Let all workers end current executing jobs and exit
*/
static void done();
static void begin();
};
};
#endif
| 17.776699 | 75 | 0.572911 | Marcos30004347 |
8d39d3a50cf21b640e310dc9cfb7d49ead41b4d4 | 38,613 | cpp | C++ | src/math_implementation_1.cpp | tmilev/calculator | e39280f23975241985393651fe7a52db5c7fd1d5 | [
"Apache-2.0"
] | 7 | 2017-07-12T11:15:54.000Z | 2021-10-29T18:33:33.000Z | src/math_implementation_1.cpp | tmilev/calculator | e39280f23975241985393651fe7a52db5c7fd1d5 | [
"Apache-2.0"
] | 18 | 2017-05-16T03:48:45.000Z | 2022-03-16T19:51:26.000Z | src/math_implementation_1.cpp | tmilev/calculator | e39280f23975241985393651fe7a52db5c7fd1d5 | [
"Apache-2.0"
] | 1 | 2018-08-02T09:05:08.000Z | 2018-08-02T09:05:08.000Z | // The current file is licensed under the license terms found in the main header file "calculator.h".
// For additional information refer to the file "calculator.h".
#include "math_extra_finite_groups_implementation.h"
#include "general_lists.h"
#include "math_general.h"
#include "math_extra_universal_enveloping.h"
#include "math_rational_function_implementation.h"
void SemisimpleLieAlgebra::getChevalleyGeneratorAsLieBracketsSimpleGenerators(
int generatorIndex,
List<int>& outputIndicesFormatAd0Ad1Ad2etc,
Rational& outputMultiplyLieBracketsToGetGenerator
) {
MacroRegisterFunctionWithName("SemisimpleLieAlgebra::getChevalleyGeneratorAsLieBracketsSimpleGenerators");
outputIndicesFormatAd0Ad1Ad2etc.size = 0;
if (this->isGeneratorFromCartan(generatorIndex)) {
int simpleIndex = generatorIndex - this->getNumberOfPositiveRoots();
outputIndicesFormatAd0Ad1Ad2etc.addOnTop(generatorIndex + this->getRank());
outputIndicesFormatAd0Ad1Ad2etc.addOnTop(2 * this->getNumberOfPositiveRoots() - 1 - generatorIndex);
outputMultiplyLieBracketsToGetGenerator = this->weylGroup.cartanSymmetric.elements[simpleIndex][simpleIndex] / 2;
return;
}
Vector<Rational> weight = this->getWeightOfGenerator(generatorIndex);
outputMultiplyLieBracketsToGetGenerator = 1;
Vector<Rational> genWeight, newWeight;
while (!weight.isEqualToZero()) {
for (int i = 0; i < this->getRank(); i ++) {
genWeight.makeEi(this->getRank(), i);
if (weight.isPositive()) {
genWeight.negate();
}
newWeight = weight + genWeight;
if (newWeight.isEqualToZero() || this->weylGroup.isARoot(newWeight)) {
weight = newWeight;
int index = this->getGeneratorIndexFromRoot(- genWeight);
outputIndicesFormatAd0Ad1Ad2etc.addOnTop(index);
if (!weight.isEqualToZero()) {
int currentIndex = this->weylGroup.rootSystem.getIndex(weight);
index = this->getRootIndexFromGenerator(index);
if (!this->computedChevalleyConstants.elements[index][currentIndex]) {
global.fatal
<< "For some reason I am not computed. Here is me: " << this->toString() << global.fatal;
}
outputMultiplyLieBracketsToGetGenerator /= this->chevalleyConstants.elements[index][currentIndex];
}
break;
}
}
}
}
bool PartialFractions::argumentsAllowed(
Vectors<Rational>& arguments, std::string& outputWhatWentWrong
) {
if (arguments.size < 1) {
return false;
}
Cone tempCone;
bool result = tempCone.createFromVertices(arguments);
if (tempCone.isEntireSpace()) {
outputWhatWentWrong = "Error: the vectors you gave as input span the entire space.";
return false;
}
for (int i = 0; i < tempCone.vertices.size; i ++) {
if (tempCone.isInCone(tempCone.vertices[i]) && tempCone.isInCone(- tempCone.vertices[i])) {
std::stringstream out;
out << "Error: the Q_{>0} span of vectors you gave as input contains zero (as it contains the vector "
<< tempCone.vertices[i].toString() << " as well as its opposite vector "
<< (- tempCone.vertices[i]).toString()
<< "), hence the vector partition function is " << "can only take values infinity or zero. ";
outputWhatWentWrong = out.str();
return false;
}
}
return result;
}
void Lattice::intersectWithLineGivenBy(Vector<Rational>& inputLine, Vector<Rational>& outputGenerator) {
Vectors<Rational> roots;
roots.addOnTop(inputLine);
this->intersectWithLinearSubspaceSpannedBy(roots);
if (this->basisRationalForm.numberOfRows > 1) {
global.fatal << "This should not be possible. " << global.fatal;
}
if (this->basisRationalForm.numberOfRows == 0) {
outputGenerator.makeZero(inputLine.size);
} else {
this->basisRationalForm.getVectorFromRow(0, outputGenerator);
}
}
void LittelmannPath::actByEFDisplayIndex(int displayIndex) {
if (this->owner == nullptr) {
global.fatal << "LS path without initialized owner is begin acted upon. " << global.fatal;
}
if (displayIndex > 0) {
this->actByEAlpha(displayIndex - 1);
} else {
this->actByFAlpha(- displayIndex - 1);
}
}
void LittelmannPath::actByEAlpha(int indexAlpha) {
if (this->owner == nullptr) {
global.fatal << "LS path without initialized owner is begin acted upon. " << global.fatal;
}
if (indexAlpha < 0 || indexAlpha >= this->owner->getDimension()) {
global.fatal << "Index of Littelmann root operator out of range. " << global.fatal;
}
if (this->waypoints.size == 0) {
return;
}
Rational minimalScalarProduct = 0;
int indexMinimalScalarProduct = - 1;
if (this->owner == nullptr) {
global.fatal << "zero owner not allowed here. " << global.fatal;
}
WeylGroupData& weylGroup = *this->owner;
weylGroup.computeRho(true);
Vector<Rational>& alpha = weylGroup.rootsOfBorel[indexAlpha];
Rational lengthAlpha = weylGroup.rootScalarCartanRoot(alpha, alpha);
Vector<Rational> alphaScaled = alpha * 2 / lengthAlpha;
for (int i = 0; i < this->waypoints.size; i ++) {
Rational scalarProduct = this->owner->rootScalarCartanRoot(this->waypoints[i], alphaScaled);
if (scalarProduct <= minimalScalarProduct) {
minimalScalarProduct = scalarProduct;
indexMinimalScalarProduct = i;
}
}
if (indexMinimalScalarProduct <= 0 || minimalScalarProduct > - 1) {
this->waypoints.size = 0;
return;
}
int precedingIndex = 0;
for (int i = 0; i <= indexMinimalScalarProduct; i ++) {
Rational tempScalar = weylGroup.rootScalarCartanRoot(this->waypoints[i], alphaScaled);
if (tempScalar >= minimalScalarProduct + 1) {
precedingIndex = i;
}
if (tempScalar < minimalScalarProduct + 1) {
break;
}
}
Rational s2 = this->owner->rootScalarCartanRoot(this->waypoints[precedingIndex], alphaScaled);
if (!this->minimaAreIntegral()) {
global.comments << "<br>Something is wrong: starting path is BAD!";
}
if (s2 > minimalScalarProduct + 1) {
this->waypoints.setSize(this->waypoints.size + 1);
for (int i = this->waypoints.size - 1; i >= precedingIndex + 2; i --) {
this->waypoints[i] = this->waypoints[i - 1];
}
precedingIndex ++;
indexMinimalScalarProduct ++;
Vector<Rational>& r1 = this->waypoints[precedingIndex];
Vector<Rational>& r2 = this->waypoints[precedingIndex - 1];
Rational s1 = weylGroup.rootScalarCartanRoot(r1, alphaScaled);
Rational x = (minimalScalarProduct + 1 - s2) / (s1 - s2);
this->waypoints[precedingIndex] = (r1 - r2) * x + r2;
}
Vectors<Rational> differences;
differences.setSize(indexMinimalScalarProduct-precedingIndex);
Rational currentDist = 0;
Rational minDist = 0;
for (int i = 0; i < differences.size; i ++) {
differences[i] = this->waypoints[i + precedingIndex + 1] - this->waypoints[i + precedingIndex];
currentDist += weylGroup.rootScalarCartanRoot(differences[i], alphaScaled);
if (currentDist < minDist) {
weylGroup.reflectSimple(indexAlpha, differences[i]);
minDist = currentDist;
}
}
for (int i = 0; i < differences.size; i ++) {
this->waypoints[i + precedingIndex + 1] = this->waypoints[i + precedingIndex] + differences[i];
}
for (int i = indexMinimalScalarProduct + 1; i < this->waypoints.size; i ++) {
this->waypoints[i] += alpha;
}
this->simplify();
}
void LittelmannPath::actByFAlpha(int indexAlpha) {
if (this->waypoints.size == 0) {
return;
}
if (this->owner == nullptr) {
global.fatal << "LS path without initialized owner is begin acted upon. " << global.fatal;
}
if (indexAlpha < 0 || indexAlpha >= this->owner->getDimension()) {
global.fatal << "Index of Littelmann root operator out of range. " << global.fatal;
}
Rational minimalScalarProduct = 0;
int indexMinimalScalarProduct = - 1;
WeylGroupData& weylGroup = *this->owner;
Vector<Rational>& alpha = weylGroup.rootsOfBorel[indexAlpha];
Rational LengthAlpha = this->owner->rootScalarCartanRoot(alpha, alpha);
Vector<Rational> alphaScaled = alpha * 2 / LengthAlpha;
for (int i = 0; i < this->waypoints.size; i ++) {
Rational scalarProduct = this->owner->rootScalarCartanRoot(this->waypoints[i], alphaScaled);
if (scalarProduct <= minimalScalarProduct) {
minimalScalarProduct = scalarProduct;
indexMinimalScalarProduct = i;
}
}
Rational lastScalar = this->owner->rootScalarCartanRoot(*this->waypoints.lastObject(), alphaScaled);
if (indexMinimalScalarProduct < 0 || lastScalar - minimalScalarProduct < 1) {
this->waypoints.size = 0;
return;
}
int succeedingIndex = 0;
for (int i = this->waypoints.size - 1; i >= indexMinimalScalarProduct; i --) {
Rational tempScalar = weylGroup.rootScalarCartanRoot(alphaScaled, this->waypoints[i]);
if (tempScalar >= minimalScalarProduct + 1) {
succeedingIndex = i;
}
if (tempScalar < minimalScalarProduct + 1) {
break;
}
}
Rational s1 = this->owner->rootScalarCartanRoot(this->waypoints[succeedingIndex], alphaScaled);
if (s1 > minimalScalarProduct + 1) {
this->waypoints.setSize(this->waypoints.size + 1);
for (int i = this->waypoints.size - 1; i >= succeedingIndex + 1; i --) {
this->waypoints[i] = this->waypoints[i - 1];
}
//Rational scalarNext = weylGroup.rootScalarCartanRoot(this->waypoints[succeedingIndex], alphaScaled);
Vector<Rational>& r1 = this->waypoints[succeedingIndex];
Vector<Rational>& r2 = this->waypoints[succeedingIndex - 1];
Rational s2 = weylGroup.rootScalarCartanRoot(r2, alphaScaled);
Rational x = (minimalScalarProduct + 1 - s2) / (s1 - s2);
this->waypoints[succeedingIndex] = (r1 - r2) * x + r2;
}
Vector<Rational> diff, oldWayPoint;
oldWayPoint = this->waypoints[indexMinimalScalarProduct];
Rational currentDist = 0;
for (int i = 0; i < succeedingIndex - indexMinimalScalarProduct; i ++) {
diff = this->waypoints[i + indexMinimalScalarProduct + 1] - oldWayPoint;
currentDist += weylGroup.rootScalarCartanRoot(diff, alphaScaled);
if (currentDist > 0) {
weylGroup.reflectSimple(indexAlpha, diff);
currentDist = 0;
}
oldWayPoint = this->waypoints[i + indexMinimalScalarProduct + 1];
this->waypoints[i + indexMinimalScalarProduct + 1] = this->waypoints[i + indexMinimalScalarProduct] + diff;
}
for (int i = succeedingIndex + 1; i < this->waypoints.size; i ++) {
this->waypoints[i] -= alpha;
}
this->simplify();
}
void LittelmannPath::simplify() {
if (this->waypoints.size == 0) {
return;
}
Vector<Rational> d1, d2;
Rational d11, d12, d22;
int leftIndex = 0;
int rightIndex = 2;
while (rightIndex < this->waypoints.size) {
Vector<Rational>& left = this->waypoints[leftIndex];
Vector<Rational>& middle = this->waypoints[rightIndex - 1];
Vector<Rational>& right = this->waypoints[rightIndex];
d1 = left - middle;
d2 = right - middle;
d11 = d1.scalarEuclidean(d1);
d12 = d1.scalarEuclidean(d2);
d22 = d2.scalarEuclidean(d2);
bool isBad = ((d11 * d22 - d12 * d12).isEqualToZero() && (d12 <= 0));
if (!isBad) {
leftIndex ++;
this->waypoints[leftIndex] = middle;
}
rightIndex ++;
}
leftIndex ++;
this->waypoints[leftIndex] = *this->waypoints.lastObject();
this->waypoints.setSize(leftIndex + 1);
}
bool LittelmannPath::minimaAreIntegral() {
if (this->waypoints.size == 0) {
return true;
}
List<Rational> minima;
WeylGroupData& weyl = *this->owner;
int dimension = weyl.getDimension();
minima.setSize(dimension);
for (int i = 0; i < dimension; i ++) {
minima[i] = weyl.getScalarProductSimpleRoot(this->waypoints[0], i) * 2 / weyl.cartanSymmetric.elements[i][i];
}
for (int i = 1; i < this->waypoints.size; i ++) {
for (int j = 0; j < dimension; j ++) {
minima[j] = MathRoutines::minimum(weyl.getScalarProductSimpleRoot(
this->waypoints[i], j) * 2 / weyl.cartanSymmetric.elements[j][j], minima[j]
);
}
}
for (int i = 0; i < dimension; i ++) {
if (!minima[i].isSmallInteger()) {
return false;
}
}
return true;
}
void LittelmannPath::makeFromWeightInSimpleCoords(
const Vector<Rational>& weightInSimpleCoords, WeylGroupData& inputOwner
) {
this->owner = &inputOwner;
this->waypoints.setSize(2);
this->waypoints[0].makeZero(inputOwner.getDimension());
this->waypoints[1] = weightInSimpleCoords;
this->simplify();
}
std::string LittelmannPath::toStringIndicesToCalculatorOutput(LittelmannPath& inputStartingPath, List<int>& input) {
std::stringstream out;
for (int i = input.size - 1; i >= 0; i --) {
int displayIndex = input[i];
if (displayIndex >= 0) {
displayIndex ++;
}
out << "eAlpha(" << displayIndex << ", ";
}
out << "littelmann"
<< inputStartingPath.owner->getFundamentalCoordinatesFromSimple(*inputStartingPath.waypoints.lastObject()).toString();
for (int i = 0; i < input.size; i ++) {
out << " ) ";
}
return out.str();
}
bool LittelmannPath::generateOrbit(
List<LittelmannPath>& output,
List<List<int> >& outputOperators,
int UpperBoundNumElts,
Selection* parabolicNonSelectedAreInLeviPart
) {
HashedList<LittelmannPath> hashedOutput;
hashedOutput.addOnTop(*this);
int dimension = this->owner->getDimension();
outputOperators.setSize(1);
outputOperators[0].setSize(0);
List<int> currentSequence;
if (UpperBoundNumElts > 0) {
currentSequence.reserve(UpperBoundNumElts);
}
LittelmannPath currentPath;
bool result = true;
Selection parabolicSelectionSelectedAreInLeviPart;
parabolicSelectionSelectedAreInLeviPart.initialize(dimension);
if (parabolicNonSelectedAreInLeviPart != nullptr) {
parabolicSelectionSelectedAreInLeviPart = *parabolicNonSelectedAreInLeviPart;
parabolicSelectionSelectedAreInLeviPart.invertSelection();
} else {
parabolicSelectionSelectedAreInLeviPart.makeFullSelection();
}
for (int lowestNonExplored = 0; lowestNonExplored < hashedOutput.size; lowestNonExplored ++) {
if (UpperBoundNumElts > 0 && UpperBoundNumElts < hashedOutput.size) {
result = false;
break;
} else {
for (int j = 0; j < parabolicSelectionSelectedAreInLeviPart.cardinalitySelection; j ++) {
bool found = true;
currentPath = hashedOutput[lowestNonExplored];
currentSequence = outputOperators[lowestNonExplored];
int index = parabolicSelectionSelectedAreInLeviPart.elements[j];
while (found) {
found = false;
currentPath.actByEAlpha(index);
if (!currentPath.isEqualToZero()) {
if (hashedOutput.addOnTopNoRepetition(currentPath)) {
found = true;
currentSequence.addOnTop(index);
outputOperators.addOnTop(currentSequence);
if (!currentPath.minimaAreIntegral()) {
global.comments << "<hr>Found a bad path:<br> ";
global.comments << " = " << currentPath.toString();
}
}
}
}
found = true;
currentPath = hashedOutput[lowestNonExplored];
currentSequence = outputOperators[lowestNonExplored];
while (found) {
found = false;
currentPath.actByFAlpha(index);
if (!currentPath.isEqualToZero()) {
if (hashedOutput.addOnTopNoRepetition(currentPath)) {
found = true;
currentSequence.addOnTop(- index - 1);
outputOperators.addOnTop(currentSequence);
if (!currentPath.minimaAreIntegral()) {
global.comments << "<hr>Found a bad path:<br> ";
global.comments << " = " << currentPath.toString();
}
}
}
}
}
}
}
output = hashedOutput;
return result;
}
std::string LittelmannPath:: toStringOperatorSequenceStartingOnMe(List<int>& input) {
MonomialTensor<Rational> tempMon;
tempMon = input;
tempMon.generatorsIndices.reverseElements();
tempMon.powers.reverseElements();
return tempMon.toString();
}
template <class Coefficient>
bool MonomialUniversalEnvelopingOrdered<Coefficient>::modOutFDRelationsExperimental(
const Vector<Rational>& highestWeightSimpleCoordinates,
const Coefficient& ringUnit,
const Coefficient& ringZero
) {
WeylGroupData& weyl = this->owner->ownerSemisimpleLieAlgebra->weylGroup;
Vector<Rational> highestWeightSimpleCoordinatesTrue = highestWeightSimpleCoordinates;
weyl.raiseToDominantWeight(highestWeightSimpleCoordinatesTrue);
Vector<Rational> highestWeightDualCoordinates = weyl.getDualCoordinatesFromFundamental(
weyl.getFundamentalCoordinatesFromSimple(highestWeightSimpleCoordinatesTrue)
);
List<Coefficient> substitution;
substitution.setSize(highestWeightDualCoordinates.size);
for (int i = 0; i < highestWeightDualCoordinates.size; i ++) {
substitution[i] = highestWeightDualCoordinates[i];
}
this->modOutVermaRelations(&substitution, ringUnit, ringZero);
int numberOfPositiveRoots = this->owner->ownerSemisimpleLieAlgebra->getNumberOfPositiveRoots();
Vector<Rational> currentWeight = highestWeightSimpleCoordinatesTrue;
Vector<Rational> testWeight;
for (int k = this->generatorsIndices.size - 1; k >= 0; k --) {
int indexCurrentGenerator = this->generatorsIndices[k];
if (indexCurrentGenerator >= numberOfPositiveRoots) {
return false;
}
ElementSemisimpleLieAlgebra<Rational>& currentElt = this->owner->elementOrder[indexCurrentGenerator];
if (!currentElt.getCartanPart().isEqualToZero() || currentElt.size() > 1) {
return false;
}
int power = 0;
if (!this->powers[k].isSmallInteger(power)) {
return false;
}
int rootIndex = this->owner->ownerSemisimpleLieAlgebra->getRootIndexFromGenerator(currentElt[0].generatorIndex);
const Vector<Rational>& currentRoot = weyl.rootSystem[rootIndex];
for (int j = 0; j < power; j ++) {
currentWeight += currentRoot;
testWeight = currentWeight;
weyl.raiseToDominantWeight(testWeight);
if (!(highestWeightSimpleCoordinatesTrue - testWeight).isPositiveOrZero()) {
this->makeZero(ringZero, *this->owner);
return true;
}
}
}
return true;
}
template <class Coefficient>
bool ElementUniversalEnvelopingOrdered<Coefficient>::modOutFDRelationsExperimental(
const Vector<Rational>& highestWeightSimpleCoordinates,
const Coefficient& ringUnit,
const Coefficient& ringZero
) {
MonomialUniversalEnvelopingOrdered<Coefficient> tempMon;
ElementUniversalEnvelopingOrdered<Coefficient> output;
output.makeZero(*this->owner);
bool result = true;
for (int i = 0; i < this->size; i ++) {
tempMon = this->objects[i];
if (!tempMon.modOutFDRelationsExperimental(highestWeightSimpleCoordinates, ringUnit, ringZero)) {
result = false;
}
output.addMonomial(tempMon);
}
this->operator=(output);
return result;
}
template <class Coefficient>
bool ElementUniversalEnveloping<Coefficient>::getCoordinatesInBasis(
List<ElementUniversalEnveloping<Coefficient> >& basis,
Vector<Coefficient>& output,
const Coefficient& ringUnit,
const Coefficient& ringZero
) const {
List<ElementUniversalEnveloping<Coefficient> > tempBasis, elements;
tempBasis = basis;
tempBasis.addOnTop(*this);
Vectors<Coefficient> tempCoords;
if (!this->getBasisFromSpanOfElements(tempBasis, tempCoords, elements, ringUnit, ringZero)) {
return false;
}
Vector<Coefficient> root;
root = *tempCoords.lastObject();
tempCoords.setSize(basis.size);
return root.getCoordinatesInBasis(tempCoords, output);
}
template<class Coefficient>
template<class CoefficientTypeQuotientField>
bool ElementUniversalEnveloping<Coefficient>::getBasisFromSpanOfElements(
List<ElementUniversalEnveloping<Coefficient> >& elements,
Vectors<CoefficientTypeQuotientField>& outputCoords,
List<ElementUniversalEnveloping<Coefficient> >& outputBasis,
const CoefficientTypeQuotientField& fieldUnit,
const CoefficientTypeQuotientField& fieldZero
) {
if (elements.size == 0) {
return false;
}
ElementUniversalEnveloping<Coefficient> outputCorrespondingMonomials;
outputCorrespondingMonomials.makeZero(*elements[0].owner);
Vectors<CoefficientTypeQuotientField> outputCoordsBeforeReduction;
for (int i = 0; i < elements.size; i ++) {
for (int j = 0; j < elements[i].size; j ++) {
outputCorrespondingMonomials.addOnTopNoRepetition(elements[i][j]);
}
}
outputCoordsBeforeReduction.setSize(elements.size);
for (int i = 0; i < elements.size; i ++) {
Vector<CoefficientTypeQuotientField>& currentList = outputCoordsBeforeReduction[i];
currentList.makeZero(outputCorrespondingMonomials.size);
ElementUniversalEnveloping<Coefficient>& currentElt = elements[i];
for (int j = 0; j < currentElt.size; j ++) {
MonomialUniversalEnveloping<Coefficient>& currentMon = currentElt[j];
currentList[outputCorrespondingMonomials.getIndex(currentMon)] = currentMon.coefficient;
}
}
outputBasis.size = 0;
outputBasis.reserve(elements.size);
Vectors<CoefficientTypeQuotientField> basisCoordForm;
basisCoordForm.reserve(elements.size);
Selection selectedBasis;
outputCoordsBeforeReduction.SelectABasis(basisCoordForm, fieldZero, selectedBasis);
for (int i = 0; i < selectedBasis.cardinalitySelection; i ++) {
outputBasis.addOnTop(elements.objects[selectedBasis.elements[i]]);
}
Matrix<Coefficient> bufferMat;
Vectors<Coefficient> bufferVectors;
outputCoordsBeforeReduction.getCoordinatesInBasis(
basisCoordForm, outputCoords, bufferVectors, bufferMat, fieldUnit, fieldZero
);
return true;
}
template<class Coefficient>
void ElementUniversalEnveloping<Coefficient>::modToMinDegreeFormFDRels(
const Vector<Rational>& highestWeightInSimpleCoordinates,
const Coefficient& ringUnit,
const Coefficient& ringZero
) {
ElementUniversalEnveloping<Coefficient> result;
result.makeZero(*this->owner);
bool Found = true;
int numPosRoots = this->owner->getNumberOfPositiveRoots();
while (Found) {
Found = false;
for (int j = numPosRoots - 1; j >= 0; j --) {
this->owner->universalEnvelopingGeneratorOrder.swapTwoIndices(j, numPosRoots - 1);
this->simplify(ringUnit);
this->owner->universalEnvelopingGeneratorOrder.swapTwoIndices(j, numPosRoots - 1);
if (this->modOutFDRelationsExperimental(highestWeightInSimpleCoordinates, ringUnit, ringZero)) {
Found = true;
}
}
}
this->simplify(ringUnit);
}
template<class Coefficient>
bool ElementUniversalEnveloping<Coefficient>::applyMinusTransposeAutoOnMe() {
MonomialUniversalEnveloping<Coefficient> tempMon;
ElementUniversalEnveloping<Coefficient> result;
result.makeZero(*this->owner);
int numPosRoots = this->getOwner().getNumberOfPositiveRoots();
int rank = this->getOwner().getRank();
Coefficient coefficient;
for (int i = 0; i < this->size; i ++) {
MonomialUniversalEnveloping<Coefficient>& currentMon = this->objects[i];
coefficient = this->coefficients[i];
tempMon.owner = currentMon.owner;
tempMon.powers.size = 0;
tempMon.generatorsIndices.size = 0;
for (int j = 0; j < currentMon.powers.size; j ++) {
int power;
if (!currentMon.powers[j].isSmallInteger(&power)) {
return false;
}
int generator = currentMon.generatorsIndices[j];
if (generator < numPosRoots) {
generator = 2 * numPosRoots + rank - 1 - generator;
} else if (generator >= numPosRoots + rank) {
generator = - generator + 2 * numPosRoots + rank - 1;
}
tempMon.multiplyByGeneratorPowerOnTheRight(generator, currentMon.powers[j]);
if (power % 2 == 1) {
coefficient *= - 1;
}
}
result.addMonomial(tempMon, coefficient);
}
*this = result;
return true;
}
template <class Coefficient>
bool ElementUniversalEnveloping<Coefficient>::highestWeightMTAbilinearForm(
const ElementUniversalEnveloping<Coefficient>& right,
Coefficient& output,
const Vector<Coefficient>* substitutionHiGoesToIthElement,
const Coefficient& ringUnit,
const Coefficient& ringZero,
std::stringstream* logStream
) {
output = ringZero;
ElementUniversalEnveloping<Coefficient> MTright;
MTright = right;
if (!MTright.applyMinusTransposeAutoOnMe()) {
return false;
}
ElementUniversalEnveloping<Coefficient> Accum, intermediateAccum, element;
Accum.makeZero(*this->owners, this->indexInOwners);
MonomialUniversalEnveloping<Coefficient> constMon;
constMon.makeConstant();
if (logStream != nullptr) {
*logStream << "backtraced elt: " << MTright.toString(&global.defaultFormat.getElement()) << "<br>";
*logStream << "this element: " << this->toString(&global.defaultFormat.getElement()) << "<br>";
}
for (int j = 0; j < right.size; j ++) {
intermediateAccum = *this;
intermediateAccum.simplify(global, ringUnit, ringZero);
if (logStream != nullptr) {
*logStream << "intermediate after simplification: "
<< intermediateAccum.toString(&global.defaultFormat.getElement()) << "<br>";
}
intermediateAccum.modOutVermaRelations(&global, substitutionHiGoesToIthElement, ringUnit, ringZero);
MonomialUniversalEnveloping<Coefficient>& rightMon = MTright[j];
Coefficient& rightMonCoeff = MTright.coefficients[j];
int power;
for (int i = rightMon.powers.size - 1; i >= 0; i --) {
if (rightMon.powers[i].isSmallInteger(&power)) {
for (int k = 0; k < power; k ++) {
element.makeOneGenerator(rightMon.generatorsIndices[i], *this->owners, this->indexInOwners, ringUnit);
MathRoutines::swap(element, intermediateAccum);
if (logStream != nullptr) {
*logStream << "element before mult: " << element.toString(&global.defaultFormat) << "<br>";
*logStream << "intermediate before mult: "
<< intermediateAccum.toString(&global.defaultFormat.getElement()) << "<br>";
}
intermediateAccum *= (element);
if (logStream != nullptr) {
*logStream << "intermediate before simplification: "
<< intermediateAccum.toString(&global.defaultFormat.getElement()) << "<br>";
}
intermediateAccum.simplify(ringUnit);
if (logStream != nullptr) {
*logStream << "intermediate after simplification: "
<< intermediateAccum.toString(&global.defaultFormat.getElement()) << "<br>";
}
intermediateAccum.modOutVermaRelations(substitutionHiGoesToIthElement, ringUnit, ringZero);
if (logStream != nullptr) {
*logStream << "intermediate after Verma rels: "
<< intermediateAccum.toString(&global.defaultFormat.getElement()) << "<br>";
}
}
} else {
return false;
}
}
intermediateAccum *= rightMonCoeff;
Accum += intermediateAccum;
int index = intermediateAccum.getIndex(constMon);
if (index != - 1) {
output += intermediateAccum.coefficients[index];
}
}
if (logStream != nullptr) {
*logStream << "final UE element: " << Accum.toString(&global.defaultFormat.getElement());
}
return true;
}
template <class Coefficient>
std::string ElementUniversalEnveloping<Coefficient>::isInProperSubmodule(
const Vector<Coefficient>* substitutionHiGoesToIthElement, const Coefficient& ringUnit, const Coefficient& ringZero
) {
std::stringstream out;
List<ElementUniversalEnveloping<Coefficient> > orbit;
orbit.reserve(1000);
ElementUniversalEnveloping<Coefficient> element;
int dimension = this->getOwner().getRank();
int numPosRoots = this->getOwner().getNumberOfPositiveRoots();
orbit.addOnTop(*this);
for (int i = 0; i < orbit.size; i ++) {
for (int j = 0; j < dimension; j ++) {
element.makeOneGenerator(j + numPosRoots + dimension, *this->owner, ringUnit);
element *= orbit[i];
element.simplify(ringUnit);
element.modOutVermaRelations(substitutionHiGoesToIthElement, ringUnit, ringZero);
if (!element.isEqualToZero()) {
orbit.addOnTop(element);
}
}
}
for (int i = 0; i < orbit.size; i ++) {
ElementUniversalEnveloping<Coefficient>& current = orbit[i];
out << "<br>" << current.toString(&global.defaultFormat.getElement());
}
return out.str();
}
template <class Coefficient>
bool ElementUniversalEnveloping<Coefficient>::convertToRationalCoefficient(ElementUniversalEnveloping<Rational>& output) {
output.makeZero(*this->owner);
MonomialUniversalEnveloping<Rational> tempMon;
Rational coefficient;
for (int i = 0; i < this->size; i ++) {
MonomialUniversalEnveloping<Coefficient>& currentMon = this->objects[i];
tempMon.makeOne(*this->owner);
if (!this->coefficients[i].isConstant(coefficient)) {
return false;
}
for (int j = 0; j < currentMon.powers.size; j ++) {
Rational constantPower;
if (!currentMon.powers[j].isConstant(constantPower)) {
return false;
}
tempMon.multiplyByGeneratorPowerOnTheRight(currentMon.generatorsIndices[j], constantPower);
}
output.addMonomial(tempMon, Coefficient(1));
}
return true;
}
void BranchingData::initializePart1NoSubgroups() {
MacroRegisterFunctionWithName("BranchingData::initAssumingParSelAndHmmInittedPart1NoSubgroups");
this->weylGroupFiniteDimensionalSmallAsSubgroupInLarge.ambientWeyl = &this->homomorphism.coDomainAlgebra().weylGroup;
this->weylGroupFiniteDimensionalSmall.ambientWeyl = &this->homomorphism.domainAlgebra().weylGroup;
this->weylGroupFiniteDimensional.ambientWeyl = &this->homomorphism.coDomainAlgebra().weylGroup;
this->smallParabolicSelection.initialize(weylGroupFiniteDimensionalSmall.ambientWeyl->getDimension());
for (int i = 0; i < this->homomorphism.imagesCartanDomain.size; i ++) {
Vector<Rational>& currentV = this->homomorphism.imagesCartanDomain[i];
this->generatorsSmallSub.addOnTop(currentV);
for (int j = 0; j < currentV.size; j ++) {
if (!currentV[j].isEqualToZero() && this->inducing.selected[j]) {
this->generatorsSmallSub.removeLastObject();
this->smallParabolicSelection.addSelectionAppendNewIndex(i);
break;
}
}
}
this->nilradicalModuloPreimageNilradical.setSize(0);
this->nilradicalSmall.setSize(0);
this->nilradicalLarge.setSize(0);
this->weightsNilradicalLarge.setSize(0);
this->weightsNilradicalSmall.setSize(0);
this->weightsNilModPreNil.setSize(0);
this->indicesNilradicalLarge.setSize(0);
this->indicesNilradicalSmall.setSize(0);
ElementSemisimpleLieAlgebra<Rational> element;
WeylGroupData& largeWeylGroup = this->homomorphism.coDomainAlgebra().weylGroup;
WeylGroupData& smallWeylGroup = this->homomorphism.domainAlgebra().weylGroup;
int numB3NegGenerators = this->homomorphism.coDomainAlgebra().getNumberOfPositiveRoots();
int numG2NegGenerators = this->homomorphism.domainAlgebra().getNumberOfPositiveRoots();
for (int i = 0; i < numB3NegGenerators; i ++) {
const Vector<Rational>& currentWeight = largeWeylGroup.rootSystem[i];
bool isInNilradical = false;
for (int k = 0; k < this->inducing.cardinalitySelection; k ++) {
if (!currentWeight[this->inducing.elements[k]].isEqualToZero()) {
isInNilradical = true;
break;
}
}
if (isInNilradical) {
this->weightsNilradicalLarge.addOnTop(currentWeight);
element.makeGenerator(i, this->homomorphism.coDomainAlgebra());
this->nilradicalLarge.addOnTop(element);
this->indicesNilradicalLarge.addOnTop(i);
}
}
for (int i = 0; i < numG2NegGenerators; i ++) {
const Vector<Rational>& currentWeight = smallWeylGroup.rootSystem[i];
bool isInNilradical = false;
for (int k = 0; k < this->smallParabolicSelection.cardinalitySelection; k ++) {
if (!currentWeight[this->smallParabolicSelection.elements[k]].isEqualToZero()) {
isInNilradical = true;
break;
}
}
if (isInNilradical) {
this->weightsNilradicalSmall.addOnTop(currentWeight);
element.makeGenerator(i, this->homomorphism.domainAlgebra());
this->nilradicalSmall.addOnTop(element);
this->indicesNilradicalSmall.addOnTop(i);
}
}
this->nilradicalModuloPreimageNilradical = this->nilradicalLarge;
this->weightsNilModPreNil = this->weightsNilradicalLarge;
Vector<Rational> proj;
for (int i = 0; i < this->nilradicalSmall.size; i ++) {
ElementSemisimpleLieAlgebra<Rational>& eltImage =
this->homomorphism.imagesAllChevalleyGenerators[this->indicesNilradicalSmall[i]];
int index = this->nilradicalModuloPreimageNilradical.getIndex(eltImage);
if (index != - 1) {
this->nilradicalModuloPreimageNilradical.removeIndexSwapWithLast(index);
this->weightsNilModPreNil.removeIndexSwapWithLast(index);
continue;
}
bool isGood = false;
for (int j = 0; j < this->weightsNilModPreNil.size; j ++) {
proj = this->projectWeight(this->weightsNilModPreNil[j]);
if (proj == this->weightsNilradicalSmall[i]) {
isGood = true;
this->nilradicalModuloPreimageNilradical.removeIndexSwapWithLast(j);
this->weightsNilModPreNil.removeIndexSwapWithLast(j);
break;
}
}
if (!isGood) {
global.fatal << "This is either a programming error, or Lemma 3.3, T. Milev, P. Somberg, \"On branching...\""
<< " is wrong. The question is, which is the more desirable case... The bad apple is element "
<< this->nilradicalSmall[i].toString() << " of weight "
<< this->weightsNilradicalSmall[i].toString() << ". " << global.fatal;
}
}
}
BranchingData::BranchingData() {
this->flagUseNilWeightGeneratorOrder = false;
this->flagAscendingGeneratorOrder = false;
}
void BranchingData::initializePart2NoSubgroups() {
List<Vectors<Rational> > emptyList;
this->weylGroupFiniteDimensionalSmallAsSubgroupInLarge.computeSubGroupFromGeneratingReflections(&this->generatorsSmallSub, &emptyList, 1000, true);
this->weylGroupFiniteDimensionalSmall.makeParabolicFromSelectionSimpleRoots(
*this->weylGroupFiniteDimensionalSmall.ambientWeyl, this->smallParabolicSelection, 1000
);
this->weylGroupFiniteDimensional.makeParabolicFromSelectionSimpleRoots(this->homomorphism.coDomainAlgebra().weylGroup, this->inducing, 1000);
this->weylGroupFiniteDimensional.computeRootSubsystem();
this->weylGroupFiniteDimensionalSmallAsSubgroupInLarge.computeRootSubsystem();
this->weylGroupFiniteDimensionalSmall.computeRootSubsystem();
}
std::string BranchingData::getStringCasimirProjector(int index, const Rational& additionalMultiple) {
Vector<RationalFraction<Rational> > weightDifference;
std::stringstream formulaStream1;
HashedList<Vector<RationalFraction<Rational> > > accountedDiffs;
accountedDiffs.setExpectedSize(this->g2Weights.size);
bool found = false;
for (int i = 0; i < this->g2Weights.size; i ++) {
weightDifference = this->g2Weights[i] - this->g2Weights[index];
if (weightDifference.isPositive() && !accountedDiffs.contains(weightDifference)) {
accountedDiffs.addOnTop(weightDifference);
if (additionalMultiple != 1) {
formulaStream1 << additionalMultiple.toString(&this->format);
}
formulaStream1 << "(i(\\bar c) - (" << this->allCharacters[i].toString(&this->format) << "))";
found = true;
}
}
if (!found) {
formulaStream1 << "id";
}
return formulaStream1.str();
}
LittelmannPath::LittelmannPath() {
this->owner = nullptr;
}
LittelmannPath::LittelmannPath(const LittelmannPath& other) {
*this = other;
}
bool LittelmannPath::isAdaptedString(MonomialTensor<int, HashFunctions::hashFunction>& inputString) {
LittelmannPath tempPath = *this;
LittelmannPath tempPath2;
for (int i = 0; i < inputString.generatorsIndices.size; i ++) {
for (int k = 0; k < inputString.powers[i]; k ++) {
tempPath.actByEAlpha(- inputString.generatorsIndices[i] - 1);
}
if (tempPath.isEqualToZero()) {
return false;
}
tempPath2 = tempPath;
tempPath2.actByEAlpha(- inputString.generatorsIndices[i] - 1);
if (!tempPath2.isEqualToZero()) {
return false;
}
}
return true;
}
void SubgroupWeylGroupAutomorphismsGeneratedByRootReflectionsAndAutomorphisms::getGroupElementsIndexedAsAmbientGroup(
List<ElementWeylGroup>& output
) {
MacroRegisterFunctionWithName("SubgroupWeylGroupAutomorphismsGeneratedByRootReflectionsAndAutomorphisms::getGroupElementsIndexedAsAmbientGroup");
if (this->externalAutomorphisms.size > 0) {
global.fatal << "This is a programming error: a function meant for subgroups that are "
<< "Weyl groups of Levi parts of parabolics "
<< "is called on a subgroup that is not of that type. "
<< global.fatal;
}
output.reserve(this->allElements.size);
output.setSize(0);
ElementWeylGroup currentOutput;
currentOutput.owner = this->ambientWeyl;
Vector<int> indexShifts;
indexShifts.setSize(this->simpleRootsInner.size);
for (int i = 0; i < this->simpleRootsInner.size; i ++) {
indexShifts[i] = this->simpleRootsInner[i].getIndexFirstNonZeroCoordinate();
}
for (int i = 0; i < this->allElements.size; i ++) {
const ElementSubgroupWeylGroupAutomorphismsGeneratedByRootReflectionsAndAutomorphisms& other = this->allElements[i];
currentOutput.generatorsLastAppliedFirst.setSize(other.generatorsLastAppliedFirst.size);
for (int j = 0; j < currentOutput.generatorsLastAppliedFirst.size; j ++) {
currentOutput.generatorsLastAppliedFirst[j].index = indexShifts[other.generatorsLastAppliedFirst[j].index];
}
output.addOnTop(currentOutput);
}
}
std::string LittelmannPath::toString(bool useSimpleCoords, bool useArrows, bool includeDominance) const {
if (this->waypoints.size == 0) {
return "0";
}
std::stringstream out;
for (int i = 0; i < this->waypoints.size; i ++) {
if (useSimpleCoords) {
out << this->waypoints[i].toString();
} else {
out << this->owner->getFundamentalCoordinatesFromSimple(this->waypoints[i]).toString();
}
if (i != this->waypoints.size - 1) {
if (useArrows) {
out << "->";
} else {
out << ",";
}
}
}
if (includeDominance) {
out << " ";
for (int i = 0; i < this->owner->getDimension(); i ++) {
LittelmannPath tempP = *this;
tempP.actByEFDisplayIndex(i + 1);
if (!tempP.isEqualToZero()) {
out << "e_{" << i + 1 << "}";
}
tempP = *this;
tempP.actByEFDisplayIndex(- i - 1);
if (!tempP.isEqualToZero()) {
out << "e_{" << - i - 1 << "},";
}
}
}
return out.str();
}
| 39.889463 | 149 | 0.696553 | tmilev |
8d3a264b07bc6b94d19707d71b211d5012035dac | 307 | cpp | C++ | tuan_5/main.cpp | thuanpham2311/thuc-hanh-nhap-mon-cau-truc-du-lieu | 04f73c98895e88b1c36b6cfc48da49cb7cec8cf4 | [
"Unlicense"
] | null | null | null | tuan_5/main.cpp | thuanpham2311/thuc-hanh-nhap-mon-cau-truc-du-lieu | 04f73c98895e88b1c36b6cfc48da49cb7cec8cf4 | [
"Unlicense"
] | 1 | 2021-11-29T04:37:17.000Z | 2021-11-29T04:37:17.000Z | tuan_5/main.cpp | thuanpham2311/thuc-hanh-nhap-mon-cau-truc-du-lieu | 04f73c98895e88b1c36b6cfc48da49cb7cec8cf4 | [
"Unlicense"
] | null | null | null | #include "header.h"
int main() {
Nodeptr danhSachSinhVien;
nhapDanhSachSinhVien(danhSachSinhVien);
xuatDanhSachSinhVien(danhSachSinhVien);
// xoaDau(danhSachSinhVien);
xoaCuoi(danhSachSinhVien);
xuatDanhSachSinhVien(danhSachSinhVien);
timSinhVienBangMa(danhSachSinhVien, s);
return 0;
}
| 19.1875 | 41 | 0.775244 | thuanpham2311 |
8d3fc7d747c76a2e2388db764fc4bbdf8f8dcc7c | 62,446 | cpp | C++ | src/skel/glfw/glfw.cpp | gameblabla/reeee3 | 1b6d0f742b1b6fb681756de702ed618e90361139 | [
"Unlicense"
] | 2 | 2021-03-24T22:11:27.000Z | 2021-05-07T06:51:04.000Z | src/skel/glfw/glfw.cpp | gameblabla/reeee3 | 1b6d0f742b1b6fb681756de702ed618e90361139 | [
"Unlicense"
] | null | null | null | src/skel/glfw/glfw.cpp | gameblabla/reeee3 | 1b6d0f742b1b6fb681756de702ed618e90361139 | [
"Unlicense"
] | null | null | null | #if defined RW_GL3 && !defined LIBRW_SDL2
#ifdef _WIN32
#include <shlobj.h>
#include <basetsd.h>
#include <mmsystem.h>
#include <regstr.h>
#include <shellapi.h>
#include <windowsx.h>
DWORD _dwOperatingSystemVersion;
#include "resource.h"
#else
long _dwOperatingSystemVersion;
#ifndef __APPLE__
#include <sys/sysinfo.h>
#else
#include <mach/mach_host.h>
#include <sys/sysctl.h>
#endif
#include <errno.h>
#include <locale.h>
#include <signal.h>
#include <stddef.h>
#endif
#include "common.h"
#if (defined(_MSC_VER))
#include <tchar.h>
#endif /* (defined(_MSC_VER)) */
#include <stdio.h>
#include "rwcore.h"
#include "skeleton.h"
#include "platform.h"
#include "crossplatform.h"
#include "main.h"
#include "FileMgr.h"
#include "Text.h"
#include "Pad.h"
#include "Timer.h"
#include "DMAudio.h"
#include "ControllerConfig.h"
#include "Frontend.h"
#include "Game.h"
#include "PCSave.h"
#include "MemoryCard.h"
#include "Sprite2d.h"
#include "AnimViewer.h"
#include "Font.h"
#include "MemoryMgr.h"
// We found out that GLFW's keyboard input handling is still pretty delayed/not stable, so now we fetch input from X11 directly on Linux.
#if !defined _WIN32 && !defined __APPLE__ && !defined __SWITCH__ // && !defined WAYLAND
#define GET_KEYBOARD_INPUT_FROM_X11
#endif
#ifdef GET_KEYBOARD_INPUT_FROM_X11
#include <X11/Xlib.h>
#include <X11/XKBlib.h>
#define GLFW_EXPOSE_NATIVE_X11
#include <GLFW/glfw3native.h>
#endif
#ifdef _WIN32
#define GLFW_EXPOSE_NATIVE_WIN32
#include <GLFW/glfw3native.h>
#endif
#define MAX_SUBSYSTEMS (16)
rw::EngineOpenParams openParams;
static RwBool ForegroundApp = TRUE;
static RwBool WindowIconified = FALSE;
static RwBool WindowFocused = TRUE;
static RwBool RwInitialised = FALSE;
static RwSubSystemInfo GsubSysInfo[MAX_SUBSYSTEMS];
static RwInt32 GnumSubSystems = 0;
static RwInt32 GcurSel = 0, GcurSelVM = 0;
static RwBool useDefault;
// What is that for anyway?
#ifndef IMPROVED_VIDEOMODE
static RwBool defaultFullscreenRes = TRUE;
#else
static RwBool defaultFullscreenRes = FALSE;
static RwInt32 bestWndMode = -1;
#endif
static psGlobalType PsGlobal;
#define PSGLOBAL(var) (((psGlobalType *)(RsGlobal.ps))->var)
size_t _dwMemAvailPhys;
RwUInt32 gGameState;
#ifdef DETECT_JOYSTICK_MENU
char gSelectedJoystickName[128] = "";
#endif
/*
*****************************************************************************
*/
void _psCreateFolder(const char *path)
{
#ifdef _WIN32
HANDLE hfle = CreateFile(path, GENERIC_READ,
FILE_SHARE_READ,
nil,
OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS | FILE_ATTRIBUTE_NORMAL,
nil);
if ( hfle == INVALID_HANDLE_VALUE )
CreateDirectory(path, nil);
else
CloseHandle(hfle);
#else
struct stat info;
char fullpath[PATH_MAX];
realpath(path, fullpath);
if (lstat(fullpath, &info) != 0) {
if (errno == ENOENT || (errno != EACCES && !S_ISDIR(info.st_mode))) {
mkdir(fullpath, 0755);
}
}
#endif
}
/*
*****************************************************************************
*/
const char *_psGetUserFilesFolder()
{
#if defined USE_MY_DOCUMENTS && defined _WIN32
HKEY hKey = NULL;
static CHAR szUserFiles[256];
if ( RegOpenKeyEx(HKEY_CURRENT_USER,
REGSTR_PATH_SPECIAL_FOLDERS,
REG_OPTION_RESERVED,
KEY_READ,
&hKey) == ERROR_SUCCESS )
{
DWORD KeyType;
DWORD KeycbData = sizeof(szUserFiles);
if ( RegQueryValueEx(hKey,
"Personal",
NULL,
&KeyType,
(LPBYTE)szUserFiles,
&KeycbData) == ERROR_SUCCESS )
{
RegCloseKey(hKey);
strcat(szUserFiles, "\\GTA3 User Files");
_psCreateFolder(szUserFiles);
return szUserFiles;
}
RegCloseKey(hKey);
}
strcpy(szUserFiles, "data");
return szUserFiles;
#else
static char szUserFiles[256];
strcpy(szUserFiles, "userfiles");
_psCreateFolder(szUserFiles);
return szUserFiles;
#endif
}
/*
*****************************************************************************
*/
RwBool
psCameraBeginUpdate(RwCamera *camera)
{
if ( !RwCameraBeginUpdate(Scene.camera) )
{
ForegroundApp = FALSE;
RsEventHandler(rsACTIVATE, (void *)FALSE);
return FALSE;
}
return TRUE;
}
/*
*****************************************************************************
*/
void
psCameraShowRaster(RwCamera *camera)
{
if (CMenuManager::m_PrefsVsync)
RwCameraShowRaster(camera, PSGLOBAL(window), rwRASTERFLIPWAITVSYNC);
else
RwCameraShowRaster(camera, PSGLOBAL(window), rwRASTERFLIPDONTWAIT);
return;
}
/*
*****************************************************************************
*/
RwImage *
psGrabScreen(RwCamera *pCamera)
{
#ifndef LIBRW
RwRaster *pRaster = RwCameraGetRaster(pCamera);
if (RwImage *pImage = RwImageCreate(pRaster->width, pRaster->height, 32)) {
RwImageAllocatePixels(pImage);
RwImageSetFromRaster(pImage, pRaster);
return pImage;
}
#else
rw::Image *image = RwCameraGetRaster(pCamera)->toImage();
image->removeMask();
if(image)
return image;
#endif
return nil;
}
/*
*****************************************************************************
*/
#ifdef _WIN32
#pragma comment( lib, "Winmm.lib" ) // Needed for time
RwUInt32
psTimer(void)
{
RwUInt32 time;
TIMECAPS TimeCaps;
timeGetDevCaps(&TimeCaps, sizeof(TIMECAPS));
timeBeginPeriod(TimeCaps.wPeriodMin);
time = (RwUInt32) timeGetTime();
timeEndPeriod(TimeCaps.wPeriodMin);
return time;
}
#else
double
psTimer(void)
{
struct timespec start;
#if defined(CLOCK_MONOTONIC_RAW)
clock_gettime(CLOCK_MONOTONIC_RAW, &start);
#elif defined(CLOCK_MONOTONIC_FAST)
clock_gettime(CLOCK_MONOTONIC_FAST, &start);
#else
clock_gettime(CLOCK_MONOTONIC, &start);
#endif
return start.tv_sec * 1000.0 + start.tv_nsec/1000000.0;
}
#endif
/*
*****************************************************************************
*/
void
psMouseSetPos(RwV2d *pos)
{
glfwSetCursorPos(PSGLOBAL(window), pos->x, pos->y);
PSGLOBAL(lastMousePos.x) = (RwInt32)pos->x;
PSGLOBAL(lastMousePos.y) = (RwInt32)pos->y;
return;
}
/*
*****************************************************************************
*/
RwMemoryFunctions*
psGetMemoryFunctions(void)
{
#ifdef USE_CUSTOM_ALLOCATOR
return &memFuncs;
#else
return nil;
#endif
}
/*
*****************************************************************************
*/
RwBool
psInstallFileSystem(void)
{
return (TRUE);
}
/*
*****************************************************************************
*/
RwBool
psNativeTextureSupport(void)
{
return true;
}
/*
*****************************************************************************
*/
#ifdef UNDER_CE
#define CMDSTR LPWSTR
#else
#define CMDSTR LPSTR
#endif
/*
*****************************************************************************
*/
RwBool
psInitialize(void)
{
PsGlobal.lastMousePos.x = PsGlobal.lastMousePos.y = 0.0f;
RsGlobal.ps = &PsGlobal;
PsGlobal.fullScreen = FALSE;
PsGlobal.cursorIsInWindow = FALSE;
WindowFocused = TRUE;
WindowIconified = FALSE;
PsGlobal.joy1id = -1;
PsGlobal.joy2id = -1;
CFileMgr::Initialise();
#ifdef PS2_MENU
CPad::Initialise();
CPad::GetPad(0)->Mode = 0;
CGame::frenchGame = false;
CGame::germanGame = false;
CGame::nastyGame = true;
CMenuManager::m_PrefsAllowNastyGame = true;
#ifndef _WIN32
// Mandatory for Linux(Unix? Posix?) to set lang. to environment lang.
setlocale(LC_ALL, "");
char *systemLang, *keyboardLang;
systemLang = setlocale (LC_ALL, NULL);
keyboardLang = setlocale (LC_CTYPE, NULL);
short lang;
lang = !strncmp(systemLang, "fr_",3) ? LANG_FRENCH :
!strncmp(systemLang, "de_",3) ? LANG_GERMAN :
!strncmp(systemLang, "en_",3) ? LANG_ENGLISH :
!strncmp(systemLang, "it_",3) ? LANG_ITALIAN :
!strncmp(systemLang, "es_",3) ? LANG_SPANISH :
LANG_OTHER;
#else
WORD lang = PRIMARYLANGID(GetSystemDefaultLCID());
#endif
if ( lang == LANG_ITALIAN )
CMenuManager::m_PrefsLanguage = CMenuManager::LANGUAGE_ITALIAN;
else if ( lang == LANG_SPANISH )
CMenuManager::m_PrefsLanguage = CMenuManager::LANGUAGE_SPANISH;
else if ( lang == LANG_GERMAN )
{
CGame::germanGame = true;
CGame::nastyGame = false;
CMenuManager::m_PrefsAllowNastyGame = false;
CMenuManager::m_PrefsLanguage = CMenuManager::LANGUAGE_GERMAN;
}
else if ( lang == LANG_FRENCH )
{
CGame::frenchGame = true;
CGame::nastyGame = false;
CMenuManager::m_PrefsAllowNastyGame = false;
CMenuManager::m_PrefsLanguage = CMenuManager::LANGUAGE_FRENCH;
}
else
CMenuManager::m_PrefsLanguage = CMenuManager::LANGUAGE_AMERICAN;
FrontEndMenuManager.InitialiseMenuContentsAfterLoadingGame();
TheMemoryCard.Init();
#else
C_PcSave::SetSaveDirectory(_psGetUserFilesFolder());
InitialiseLanguage();
#if GTA_VERSION < GTA3_PC_11
FrontEndMenuManager.LoadSettings();
#endif
#endif
gGameState = GS_START_UP;
TRACE("gGameState = GS_START_UP");
#ifdef _WIN32
OSVERSIONINFO verInfo;
verInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
GetVersionEx(&verInfo);
_dwOperatingSystemVersion = OS_WIN95;
if ( verInfo.dwPlatformId == VER_PLATFORM_WIN32_NT )
{
if ( verInfo.dwMajorVersion == 4 )
{
debug("Operating System is WinNT\n");
_dwOperatingSystemVersion = OS_WINNT;
}
else if ( verInfo.dwMajorVersion == 5 )
{
debug("Operating System is Win2000\n");
_dwOperatingSystemVersion = OS_WIN2000;
}
else if ( verInfo.dwMajorVersion > 5 )
{
debug("Operating System is WinXP or greater\n");
_dwOperatingSystemVersion = OS_WINXP;
}
}
else if ( verInfo.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS )
{
if ( verInfo.dwMajorVersion > 4 || verInfo.dwMajorVersion == 4 && verInfo.dwMinorVersion != 0 )
{
debug("Operating System is Win98\n");
_dwOperatingSystemVersion = OS_WIN98;
}
else
{
debug("Operating System is Win95\n");
_dwOperatingSystemVersion = OS_WIN95;
}
}
#else
_dwOperatingSystemVersion = OS_WINXP; // To fool other classes
#endif
#ifndef PS2_MENU
#if GTA_VERSION >= GTA3_PC_11
FrontEndMenuManager.LoadSettings();
#endif
#endif
#ifdef _WIN32
MEMORYSTATUS memstats;
GlobalMemoryStatus(&memstats);
_dwMemAvailPhys = memstats.dwAvailPhys;
debug("Physical memory size %u\n", memstats.dwTotalPhys);
debug("Available physical memory %u\n", memstats.dwAvailPhys);
#elif defined (__APPLE__)
uint64_t size = 0;
uint64_t page_size = 0;
size_t uint64_len = sizeof(uint64_t);
size_t ull_len = sizeof(unsigned long long);
sysctl((int[]){CTL_HW, HW_PAGESIZE}, 2, &page_size, &ull_len, NULL, 0);
sysctl((int[]){CTL_HW, HW_MEMSIZE}, 2, &size, &uint64_len, NULL, 0);
vm_statistics_data_t vm_stat;
mach_msg_type_number_t count = HOST_VM_INFO_COUNT;
host_statistics(mach_host_self(), HOST_VM_INFO, (host_info_t)&vm_stat, &count);
_dwMemAvailPhys = (uint64_t)(vm_stat.free_count * page_size);
debug("Physical memory size %llu\n", _dwMemAvailPhys);
debug("Available physical memory %llu\n", size);
#else
struct sysinfo systemInfo;
sysinfo(&systemInfo);
_dwMemAvailPhys = systemInfo.freeram;
debug("Physical memory size %u\n", systemInfo.totalram);
debug("Available physical memory %u\n", systemInfo.freeram);
#endif
TheText.Unload();
return TRUE;
}
/*
*****************************************************************************
*/
void
psTerminate(void)
{
return;
}
/*
*****************************************************************************
*/
static RwChar **_VMList;
RwInt32 _psGetNumVideModes()
{
return RwEngineGetNumVideoModes();
}
/*
*****************************************************************************
*/
RwBool _psFreeVideoModeList()
{
RwInt32 numModes;
RwInt32 i;
numModes = _psGetNumVideModes();
if ( _VMList == nil )
return TRUE;
for ( i = 0; i < numModes; i++ )
{
RwFree(_VMList[i]);
}
RwFree(_VMList);
_VMList = nil;
return TRUE;
}
/*
*****************************************************************************
*/
RwChar **_psGetVideoModeList()
{
RwInt32 numModes;
RwInt32 i;
if ( _VMList != nil )
{
return _VMList;
}
numModes = RwEngineGetNumVideoModes();
_VMList = (RwChar **)RwCalloc(numModes, sizeof(RwChar*));
for ( i = 0; i < numModes; i++ )
{
RwVideoMode vm;
RwEngineGetVideoModeInfo(&vm, i);
if ( vm.flags & rwVIDEOMODEEXCLUSIVE )
{
_VMList[i] = (RwChar*)RwCalloc(100, sizeof(RwChar));
rwsprintf(_VMList[i],"%d X %d X %d", vm.width, vm.height, vm.depth);
}
else
_VMList[i] = nil;
}
return _VMList;
}
/*
*****************************************************************************
*/
void _psSelectScreenVM(RwInt32 videoMode)
{
RwTexDictionarySetCurrent( nil );
FrontEndMenuManager.UnloadTextures();
if (!_psSetVideoMode(RwEngineGetCurrentSubSystem(), videoMode))
{
RsGlobal.quit = TRUE;
printf("ERROR: Failed to select new screen resolution\n");
}
else
FrontEndMenuManager.LoadAllTextures();
}
/*
*****************************************************************************
*/
RwBool IsForegroundApp()
{
return !!ForegroundApp;
}
/*
UINT GetBestRefreshRate(UINT width, UINT height, UINT depth)
{
LPDIRECT3D8 d3d = Direct3DCreate8(D3D_SDK_VERSION);
ASSERT(d3d != nil);
UINT refreshRate = INT_MAX;
D3DFORMAT format;
if ( depth == 32 )
format = D3DFMT_X8R8G8B8;
else if ( depth == 24 )
format = D3DFMT_R8G8B8;
else
format = D3DFMT_R5G6B5;
UINT modeCount = d3d->GetAdapterModeCount(GcurSel);
for ( UINT i = 0; i < modeCount; i++ )
{
D3DDISPLAYMODE mode;
d3d->EnumAdapterModes(GcurSel, i, &mode);
if ( mode.Width == width && mode.Height == height && mode.Format == format )
{
if ( mode.RefreshRate == 0 )
return 0;
if ( mode.RefreshRate < refreshRate && mode.RefreshRate >= 60 )
refreshRate = mode.RefreshRate;
}
}
#ifdef FIX_BUGS
d3d->Release();
#endif
if ( refreshRate == -1 )
return -1;
return refreshRate;
}
*/
/*
*****************************************************************************
*/
RwBool
psSelectDevice()
{
RwVideoMode vm;
RwInt32 subSysNum;
RwInt32 AutoRenderer = 0;
RwBool modeFound = FALSE;
if ( !useDefault )
{
GnumSubSystems = RwEngineGetNumSubSystems();
if ( !GnumSubSystems )
{
return FALSE;
}
/* Just to be sure ... */
GnumSubSystems = (GnumSubSystems > MAX_SUBSYSTEMS) ? MAX_SUBSYSTEMS : GnumSubSystems;
/* Get the names of all the sub systems */
for (subSysNum = 0; subSysNum < GnumSubSystems; subSysNum++)
{
RwEngineGetSubSystemInfo(&GsubSysInfo[subSysNum], subSysNum);
}
/* Get the default selection */
GcurSel = RwEngineGetCurrentSubSystem();
#ifdef IMPROVED_VIDEOMODE
if(FrontEndMenuManager.m_nPrefsSubsystem < GnumSubSystems)
GcurSel = FrontEndMenuManager.m_nPrefsSubsystem;
#endif
}
/* Set the driver to use the correct sub system */
if (!RwEngineSetSubSystem(GcurSel))
{
return FALSE;
}
#ifdef IMPROVED_VIDEOMODE
FrontEndMenuManager.m_nPrefsSubsystem = GcurSel;
#endif
#ifndef IMPROVED_VIDEOMODE
if ( !useDefault )
{
if ( _psGetVideoModeList()[FrontEndMenuManager.m_nDisplayVideoMode] && FrontEndMenuManager.m_nDisplayVideoMode )
{
FrontEndMenuManager.m_nPrefsVideoMode = FrontEndMenuManager.m_nDisplayVideoMode;
GcurSelVM = FrontEndMenuManager.m_nDisplayVideoMode;
}
else
{
#ifdef DEFAULT_NATIVE_RESOLUTION
// get the native video mode
HDC hDevice = GetDC(NULL);
int w = GetDeviceCaps(hDevice, HORZRES);
int h = GetDeviceCaps(hDevice, VERTRES);
int d = GetDeviceCaps(hDevice, BITSPIXEL);
#else
const int w = 640;
const int h = 480;
const int d = 16;
#endif
while ( !modeFound && GcurSelVM < RwEngineGetNumVideoModes() )
{
RwEngineGetVideoModeInfo(&vm, GcurSelVM);
if ( defaultFullscreenRes && vm.width != w
|| vm.height != h
|| vm.depth != d
|| !(vm.flags & rwVIDEOMODEEXCLUSIVE) )
++GcurSelVM;
else
modeFound = TRUE;
}
if ( !modeFound )
{
#ifdef DEFAULT_NATIVE_RESOLUTION
GcurSelVM = 1;
#else
printf("WARNING: Cannot find 640x480 video mode, selecting device cancelled\n");
return FALSE;
#endif
}
}
}
#else
if ( !useDefault )
{
if(FrontEndMenuManager.m_nPrefsWidth == 0 ||
FrontEndMenuManager.m_nPrefsHeight == 0 ||
FrontEndMenuManager.m_nPrefsDepth == 0){
// Defaults if nothing specified
const GLFWvidmode *mode = glfwGetVideoMode(glfwGetPrimaryMonitor());
FrontEndMenuManager.m_nPrefsWidth = mode->width;
FrontEndMenuManager.m_nPrefsHeight = mode->height;
FrontEndMenuManager.m_nPrefsDepth = 32;
FrontEndMenuManager.m_nPrefsWindowed = 0;
}
// Find the videomode that best fits what we got from the settings file
RwInt32 bestFsMode = -1;
RwInt32 bestWidth = -1;
RwInt32 bestHeight = -1;
RwInt32 bestDepth = -1;
for(GcurSelVM = 0; GcurSelVM < RwEngineGetNumVideoModes(); GcurSelVM++){
RwEngineGetVideoModeInfo(&vm, GcurSelVM);
if (!(vm.flags & rwVIDEOMODEEXCLUSIVE)){
bestWndMode = GcurSelVM;
} else {
// try the largest one that isn't larger than what we wanted
if(vm.width >= bestWidth && vm.width <= FrontEndMenuManager.m_nPrefsWidth &&
vm.height >= bestHeight && vm.height <= FrontEndMenuManager.m_nPrefsHeight &&
vm.depth >= bestDepth && vm.depth <= FrontEndMenuManager.m_nPrefsDepth){
bestWidth = vm.width;
bestHeight = vm.height;
bestDepth = vm.depth;
bestFsMode = GcurSelVM;
}
}
}
if(bestFsMode < 0){
printf("WARNING: Cannot find desired video mode, selecting device cancelled\n");
return FALSE;
}
GcurSelVM = bestFsMode;
FrontEndMenuManager.m_nDisplayVideoMode = GcurSelVM;
FrontEndMenuManager.m_nPrefsVideoMode = FrontEndMenuManager.m_nDisplayVideoMode;
FrontEndMenuManager.m_nSelectedScreenMode = FrontEndMenuManager.m_nPrefsWindowed;
}
#endif
RwEngineGetVideoModeInfo(&vm, GcurSelVM);
#ifdef IMPROVED_VIDEOMODE
if (FrontEndMenuManager.m_nPrefsWindowed)
GcurSelVM = bestWndMode;
// Now GcurSelVM is 0 but vm has sizes(and fullscreen flag) of the video mode we want, that's why we changed the rwVIDEOMODEEXCLUSIVE conditions below
FrontEndMenuManager.m_nPrefsWidth = vm.width;
FrontEndMenuManager.m_nPrefsHeight = vm.height;
FrontEndMenuManager.m_nPrefsDepth = vm.depth;
#endif
#ifndef PS2_MENU
FrontEndMenuManager.m_nCurrOption = 0;
#endif
/* Set up the video mode and set the apps window
* dimensions to match */
if (!RwEngineSetVideoMode(GcurSelVM))
{
return FALSE;
}
/*
TODO
if (vm.flags & rwVIDEOMODEEXCLUSIVE)
{
debug("%dx%dx%d", vm.width, vm.height, vm.depth);
UINT refresh = GetBestRefreshRate(vm.width, vm.height, vm.depth);
if ( refresh != (UINT)-1 )
{
debug("refresh %d", refresh);
RwD3D8EngineSetRefreshRate((RwUInt32)refresh);
}
}
*/
#ifndef IMPROVED_VIDEOMODE
if (vm.flags & rwVIDEOMODEEXCLUSIVE)
{
RsGlobal.maximumWidth = vm.width;
RsGlobal.maximumHeight = vm.height;
RsGlobal.width = vm.width;
RsGlobal.height = vm.height;
PSGLOBAL(fullScreen) = TRUE;
}
#else
RsGlobal.maximumWidth = FrontEndMenuManager.m_nPrefsWidth;
RsGlobal.maximumHeight = FrontEndMenuManager.m_nPrefsHeight;
RsGlobal.width = FrontEndMenuManager.m_nPrefsWidth;
RsGlobal.height = FrontEndMenuManager.m_nPrefsHeight;
PSGLOBAL(fullScreen) = !FrontEndMenuManager.m_nPrefsWindowed;
#endif
#ifdef MULTISAMPLING
RwD3D8EngineSetMultiSamplingLevels(1 << FrontEndMenuManager.m_nPrefsMSAALevel);
#endif
return TRUE;
}
#ifndef GET_KEYBOARD_INPUT_FROM_X11
void keypressCB(GLFWwindow* window, int key, int scancode, int action, int mods);
#endif
void resizeCB(GLFWwindow* window, int width, int height);
void scrollCB(GLFWwindow* window, double xoffset, double yoffset);
void cursorCB(GLFWwindow* window, double xpos, double ypos);
void cursorEnterCB(GLFWwindow* window, int entered);
void windowFocusCB(GLFWwindow* window, int focused);
void windowIconifyCB(GLFWwindow* window, int iconified);
void joysChangeCB(int jid, int event);
bool IsThisJoystickBlacklisted(int i)
{
#ifndef DETECT_JOYSTICK_MENU
return false;
#else
if (glfwJoystickIsGamepad(i))
return false;
const char* joyname = glfwGetJoystickName(i);
if (gSelectedJoystickName[0] != '\0' &&
strncmp(joyname, gSelectedJoystickName, strlen(gSelectedJoystickName)) == 0)
return false;
return true;
#endif
}
void _InputInitialiseJoys()
{
PSGLOBAL(joy1id) = -1;
PSGLOBAL(joy2id) = -1;
// Load our gamepad mappings.
#define SDL_GAMEPAD_DB_PATH "gamecontrollerdb.txt"
FILE *f = fopen(SDL_GAMEPAD_DB_PATH, "rb");
if (f) {
fseek(f, 0, SEEK_END);
size_t fsize = ftell(f);
fseek(f, 0, SEEK_SET);
char *db = (char*)malloc(fsize + 1);
if (fread(db, 1, fsize, f) == fsize) {
db[fsize] = '\0';
if (glfwUpdateGamepadMappings(db) == GLFW_FALSE)
Error("glfwUpdateGamepadMappings didn't succeed, check " SDL_GAMEPAD_DB_PATH ".\n");
} else
Error("fread on " SDL_GAMEPAD_DB_PATH " wasn't successful.\n");
free(db);
fclose(f);
} else
printf("You don't seem to have copied " SDL_GAMEPAD_DB_PATH " file from re3/gamefiles to GTA3 directory. Some gamepads may not be recognized.\n");
#undef SDL_GAMEPAD_DB_PATH
// But always overwrite it with the one in SDL_GAMECONTROLLERCONFIG.
char const* EnvControlConfig = getenv("SDL_GAMECONTROLLERCONFIG");
if (EnvControlConfig != nil) {
glfwUpdateGamepadMappings(EnvControlConfig);
}
for (int i = 0; i <= GLFW_JOYSTICK_LAST; i++) {
if (glfwJoystickPresent(i) && !IsThisJoystickBlacklisted(i)) {
if (PSGLOBAL(joy1id) == -1)
PSGLOBAL(joy1id) = i;
else if (PSGLOBAL(joy2id) == -1)
PSGLOBAL(joy2id) = i;
else
break;
}
}
if (PSGLOBAL(joy1id) != -1) {
int count;
glfwGetJoystickButtons(PSGLOBAL(joy1id), &count);
#ifdef DETECT_JOYSTICK_MENU
strcpy(gSelectedJoystickName, glfwGetJoystickName(PSGLOBAL(joy1id)));
#endif
ControlsManager.InitDefaultControlConfigJoyPad(count);
}
}
long _InputInitialiseMouse()
{
glfwSetInputMode(PSGLOBAL(window), GLFW_CURSOR, GLFW_CURSOR_HIDDEN);
return 0;
}
void psPostRWinit(void)
{
RwVideoMode vm;
RwEngineGetVideoModeInfo(&vm, GcurSelVM);
#ifndef GET_KEYBOARD_INPUT_FROM_X11
glfwSetKeyCallback(PSGLOBAL(window), keypressCB);
#endif
glfwSetFramebufferSizeCallback(PSGLOBAL(window), resizeCB);
glfwSetScrollCallback(PSGLOBAL(window), scrollCB);
glfwSetCursorPosCallback(PSGLOBAL(window), cursorCB);
glfwSetCursorEnterCallback(PSGLOBAL(window), cursorEnterCB);
glfwSetWindowIconifyCallback(PSGLOBAL(window), windowIconifyCB);
glfwSetWindowFocusCallback(PSGLOBAL(window), windowFocusCB);
glfwSetJoystickCallback(joysChangeCB);
_InputInitialiseJoys();
_InputInitialiseMouse();
if(!(vm.flags & rwVIDEOMODEEXCLUSIVE))
glfwSetWindowSize(PSGLOBAL(window), RsGlobal.maximumWidth, RsGlobal.maximumHeight);
// Make sure all keys are released
CPad::GetPad(0)->Clear(true);
CPad::GetPad(1)->Clear(true);
}
/*
*****************************************************************************
*/
RwBool _psSetVideoMode(RwInt32 subSystem, RwInt32 videoMode)
{
RwInitialised = FALSE;
RsEventHandler(rsRWTERMINATE, nil);
GcurSel = subSystem;
GcurSelVM = videoMode;
useDefault = TRUE;
if ( RsEventHandler(rsRWINITIALIZE, &openParams) == rsEVENTERROR )
return FALSE;
RwInitialised = TRUE;
useDefault = FALSE;
RwRect r;
r.x = 0;
r.y = 0;
r.w = RsGlobal.maximumWidth;
r.h = RsGlobal.maximumHeight;
RsEventHandler(rsCAMERASIZE, &r);
psPostRWinit();
return TRUE;
}
/*
*****************************************************************************
*/
static RwChar **
CommandLineToArgv(RwChar *cmdLine, RwInt32 *argCount)
{
RwInt32 numArgs = 0;
RwBool inArg, inString;
RwInt32 i, len;
RwChar *res, *str, **aptr;
len = strlen(cmdLine);
/*
* Count the number of arguments...
*/
inString = FALSE;
inArg = FALSE;
for(i=0; i<=len; i++)
{
if( cmdLine[i] == '"' )
{
inString = !inString;
}
if( (cmdLine[i] <= ' ' && !inString) || i == len )
{
if( inArg )
{
inArg = FALSE;
numArgs++;
}
}
else if( !inArg )
{
inArg = TRUE;
}
}
/*
* Allocate memory for result...
*/
res = (RwChar *)malloc(sizeof(RwChar *) * numArgs + len + 1);
str = res + sizeof(RwChar *) * numArgs;
aptr = (RwChar **)res;
strcpy(str, cmdLine);
/*
* Walk through cmdLine again this time setting pointer to each arg...
*/
inArg = FALSE;
inString = FALSE;
for(i=0; i<=len; i++)
{
if( cmdLine[i] == '"' )
{
inString = !inString;
}
if( (cmdLine[i] <= ' ' && !inString) || i == len )
{
if( inArg )
{
if( str[i-1] == '"' )
{
str[i-1] = '\0';
}
else
{
str[i] = '\0';
}
inArg = FALSE;
}
}
else if( !inArg && cmdLine[i] != '"' )
{
inArg = TRUE;
*aptr++ = &str[i];
}
}
*argCount = numArgs;
return (RwChar **)res;
}
/*
*****************************************************************************
*/
void InitialiseLanguage()
{
#ifndef _WIN32
// Mandatory for Linux(Unix? Posix?) to set lang. to environment lang.
setlocale(LC_ALL, "");
char *systemLang, *keyboardLang;
systemLang = setlocale (LC_ALL, NULL);
keyboardLang = setlocale (LC_CTYPE, NULL);
short primUserLCID, primSystemLCID;
primUserLCID = primSystemLCID = !strncmp(systemLang, "fr_",3) ? LANG_FRENCH :
!strncmp(systemLang, "de_",3) ? LANG_GERMAN :
!strncmp(systemLang, "en_",3) ? LANG_ENGLISH :
!strncmp(systemLang, "it_",3) ? LANG_ITALIAN :
!strncmp(systemLang, "es_",3) ? LANG_SPANISH :
LANG_OTHER;
short primLayout = !strncmp(keyboardLang, "fr_",3) ? LANG_FRENCH : (!strncmp(keyboardLang, "de_",3) ? LANG_GERMAN : LANG_ENGLISH);
short subUserLCID, subSystemLCID;
subUserLCID = subSystemLCID = !strncmp(systemLang, "en_AU",5) ? SUBLANG_ENGLISH_AUS : SUBLANG_OTHER;
short subLayout = !strncmp(keyboardLang, "en_AU",5) ? SUBLANG_ENGLISH_AUS : SUBLANG_OTHER;
#else
WORD primUserLCID = PRIMARYLANGID(GetSystemDefaultLCID());
WORD primSystemLCID = PRIMARYLANGID(GetUserDefaultLCID());
WORD primLayout = PRIMARYLANGID((DWORD)GetKeyboardLayout(0));
WORD subUserLCID = SUBLANGID(GetSystemDefaultLCID());
WORD subSystemLCID = SUBLANGID(GetUserDefaultLCID());
WORD subLayout = SUBLANGID((DWORD)GetKeyboardLayout(0));
#endif
if ( primUserLCID == LANG_GERMAN
|| primSystemLCID == LANG_GERMAN
|| primLayout == LANG_GERMAN )
{
CGame::nastyGame = false;
CMenuManager::m_PrefsAllowNastyGame = false;
CGame::germanGame = true;
}
if ( primUserLCID == LANG_FRENCH
|| primSystemLCID == LANG_FRENCH
|| primLayout == LANG_FRENCH )
{
CGame::nastyGame = false;
CMenuManager::m_PrefsAllowNastyGame = false;
CGame::frenchGame = true;
}
if ( subUserLCID == SUBLANG_ENGLISH_AUS
|| subSystemLCID == SUBLANG_ENGLISH_AUS
|| subLayout == SUBLANG_ENGLISH_AUS )
CGame::noProstitutes = true;
#ifdef NASTY_GAME
CGame::nastyGame = true;
CMenuManager::m_PrefsAllowNastyGame = true;
CGame::noProstitutes = false;
#endif
int32 lang;
switch ( primSystemLCID )
{
case LANG_GERMAN:
{
lang = LANG_GERMAN;
break;
}
case LANG_FRENCH:
{
lang = LANG_FRENCH;
break;
}
case LANG_SPANISH:
{
lang = LANG_SPANISH;
break;
}
case LANG_ITALIAN:
{
lang = LANG_ITALIAN;
break;
}
default:
{
lang = ( subSystemLCID == SUBLANG_ENGLISH_AUS ) ? -99 : LANG_ENGLISH;
break;
}
}
CMenuManager::OS_Language = primUserLCID;
switch ( lang )
{
case LANG_GERMAN:
{
CMenuManager::m_PrefsLanguage = CMenuManager::LANGUAGE_GERMAN;
break;
}
case LANG_SPANISH:
{
CMenuManager::m_PrefsLanguage = CMenuManager::LANGUAGE_SPANISH;
break;
}
case LANG_FRENCH:
{
CMenuManager::m_PrefsLanguage = CMenuManager::LANGUAGE_FRENCH;
break;
}
case LANG_ITALIAN:
{
CMenuManager::m_PrefsLanguage = CMenuManager::LANGUAGE_ITALIAN;
break;
}
default:
{
CMenuManager::m_PrefsLanguage = CMenuManager::LANGUAGE_AMERICAN;
break;
}
}
#ifndef _WIN32
// TODO this is needed for strcasecmp to work correctly across all languages, but can these cause other problems??
setlocale(LC_CTYPE, "C");
setlocale(LC_COLLATE, "C");
setlocale(LC_NUMERIC, "C");
#endif
TheText.Unload();
TheText.Load();
}
/*
*****************************************************************************
*/
void HandleExit()
{
#ifdef _WIN32
MSG message;
while ( PeekMessage(&message, nil, 0U, 0U, PM_REMOVE|PM_NOYIELD) )
{
if( message.message == WM_QUIT )
{
RsGlobal.quit = TRUE;
}
else
{
TranslateMessage(&message);
DispatchMessage(&message);
}
}
#else
// We now handle terminate message always, why handle on some cases?
return;
#endif
}
#ifndef _WIN32
void terminateHandler(int sig, siginfo_t *info, void *ucontext) {
RsGlobal.quit = TRUE;
}
#ifdef FLUSHABLE_STREAMING
void dummyHandler(int sig){
// Don't kill the app pls
}
#endif
#endif
void resizeCB(GLFWwindow* window, int width, int height) {
/*
* Handle event to ensure window contents are displayed during re-size
* as this can be disabled by the user, then if there is not enough
* memory things don't work.
*/
/* redraw window */
if (RwInitialised && gGameState == GS_PLAYING_GAME)
{
RsEventHandler(rsIDLE, (void *)TRUE);
}
if (RwInitialised && height > 0 && width > 0) {
RwRect r;
// TODO fix artifacts of resizing with mouse
RsGlobal.maximumHeight = height;
RsGlobal.maximumWidth = width;
r.x = 0;
r.y = 0;
r.w = width;
r.h = height;
RsEventHandler(rsCAMERASIZE, &r);
}
// glfwSetWindowPos(window, 0, 0);
}
void scrollCB(GLFWwindow* window, double xoffset, double yoffset) {
PSGLOBAL(mouseWheel) = yoffset;
}
bool lshiftStatus = false;
bool rshiftStatus = false;
#ifndef GET_KEYBOARD_INPUT_FROM_X11
int keymap[GLFW_KEY_LAST + 1];
static void
initkeymap(void)
{
int i;
for (i = 0; i < GLFW_KEY_LAST + 1; i++)
keymap[i] = rsNULL;
keymap[GLFW_KEY_SPACE] = ' ';
keymap[GLFW_KEY_APOSTROPHE] = '\'';
keymap[GLFW_KEY_COMMA] = ',';
keymap[GLFW_KEY_MINUS] = '-';
keymap[GLFW_KEY_PERIOD] = '.';
keymap[GLFW_KEY_SLASH] = '/';
keymap[GLFW_KEY_0] = '0';
keymap[GLFW_KEY_1] = '1';
keymap[GLFW_KEY_2] = '2';
keymap[GLFW_KEY_3] = '3';
keymap[GLFW_KEY_4] = '4';
keymap[GLFW_KEY_5] = '5';
keymap[GLFW_KEY_6] = '6';
keymap[GLFW_KEY_7] = '7';
keymap[GLFW_KEY_8] = '8';
keymap[GLFW_KEY_9] = '9';
keymap[GLFW_KEY_SEMICOLON] = ';';
keymap[GLFW_KEY_EQUAL] = '=';
keymap[GLFW_KEY_A] = 'A';
keymap[GLFW_KEY_B] = 'B';
keymap[GLFW_KEY_C] = 'C';
keymap[GLFW_KEY_D] = 'D';
keymap[GLFW_KEY_E] = 'E';
keymap[GLFW_KEY_F] = 'F';
keymap[GLFW_KEY_G] = 'G';
keymap[GLFW_KEY_H] = 'H';
keymap[GLFW_KEY_I] = 'I';
keymap[GLFW_KEY_J] = 'J';
keymap[GLFW_KEY_K] = 'K';
keymap[GLFW_KEY_L] = 'L';
keymap[GLFW_KEY_M] = 'M';
keymap[GLFW_KEY_N] = 'N';
keymap[GLFW_KEY_O] = 'O';
keymap[GLFW_KEY_P] = 'P';
keymap[GLFW_KEY_Q] = 'Q';
keymap[GLFW_KEY_R] = 'R';
keymap[GLFW_KEY_S] = 'S';
keymap[GLFW_KEY_T] = 'T';
keymap[GLFW_KEY_U] = 'U';
keymap[GLFW_KEY_V] = 'V';
keymap[GLFW_KEY_W] = 'W';
keymap[GLFW_KEY_X] = 'X';
keymap[GLFW_KEY_Y] = 'Y';
keymap[GLFW_KEY_Z] = 'Z';
keymap[GLFW_KEY_LEFT_BRACKET] = '[';
keymap[GLFW_KEY_BACKSLASH] = '\\';
keymap[GLFW_KEY_RIGHT_BRACKET] = ']';
keymap[GLFW_KEY_GRAVE_ACCENT] = '`';
keymap[GLFW_KEY_ESCAPE] = rsESC;
keymap[GLFW_KEY_ENTER] = rsENTER;
keymap[GLFW_KEY_TAB] = rsTAB;
keymap[GLFW_KEY_BACKSPACE] = rsBACKSP;
keymap[GLFW_KEY_INSERT] = rsINS;
keymap[GLFW_KEY_DELETE] = rsDEL;
keymap[GLFW_KEY_RIGHT] = rsRIGHT;
keymap[GLFW_KEY_LEFT] = rsLEFT;
keymap[GLFW_KEY_DOWN] = rsDOWN;
keymap[GLFW_KEY_UP] = rsUP;
keymap[GLFW_KEY_PAGE_UP] = rsPGUP;
keymap[GLFW_KEY_PAGE_DOWN] = rsPGDN;
keymap[GLFW_KEY_HOME] = rsHOME;
keymap[GLFW_KEY_END] = rsEND;
keymap[GLFW_KEY_CAPS_LOCK] = rsCAPSLK;
keymap[GLFW_KEY_SCROLL_LOCK] = rsSCROLL;
keymap[GLFW_KEY_NUM_LOCK] = rsNUMLOCK;
keymap[GLFW_KEY_PRINT_SCREEN] = rsNULL;
keymap[GLFW_KEY_PAUSE] = rsPAUSE;
keymap[GLFW_KEY_F1] = rsF1;
keymap[GLFW_KEY_F2] = rsF2;
keymap[GLFW_KEY_F3] = rsF3;
keymap[GLFW_KEY_F4] = rsF4;
keymap[GLFW_KEY_F5] = rsF5;
keymap[GLFW_KEY_F6] = rsF6;
keymap[GLFW_KEY_F7] = rsF7;
keymap[GLFW_KEY_F8] = rsF8;
keymap[GLFW_KEY_F9] = rsF9;
keymap[GLFW_KEY_F10] = rsF10;
keymap[GLFW_KEY_F11] = rsF11;
keymap[GLFW_KEY_F12] = rsF12;
keymap[GLFW_KEY_F13] = rsNULL;
keymap[GLFW_KEY_F14] = rsNULL;
keymap[GLFW_KEY_F15] = rsNULL;
keymap[GLFW_KEY_F16] = rsNULL;
keymap[GLFW_KEY_F17] = rsNULL;
keymap[GLFW_KEY_F18] = rsNULL;
keymap[GLFW_KEY_F19] = rsNULL;
keymap[GLFW_KEY_F20] = rsNULL;
keymap[GLFW_KEY_F21] = rsNULL;
keymap[GLFW_KEY_F22] = rsNULL;
keymap[GLFW_KEY_F23] = rsNULL;
keymap[GLFW_KEY_F24] = rsNULL;
keymap[GLFW_KEY_F25] = rsNULL;
keymap[GLFW_KEY_KP_0] = rsPADINS;
keymap[GLFW_KEY_KP_1] = rsPADEND;
keymap[GLFW_KEY_KP_2] = rsPADDOWN;
keymap[GLFW_KEY_KP_3] = rsPADPGDN;
keymap[GLFW_KEY_KP_4] = rsPADLEFT;
keymap[GLFW_KEY_KP_5] = rsPAD5;
keymap[GLFW_KEY_KP_6] = rsPADRIGHT;
keymap[GLFW_KEY_KP_7] = rsPADHOME;
keymap[GLFW_KEY_KP_8] = rsPADUP;
keymap[GLFW_KEY_KP_9] = rsPADPGUP;
keymap[GLFW_KEY_KP_DECIMAL] = rsPADDEL;
keymap[GLFW_KEY_KP_DIVIDE] = rsDIVIDE;
keymap[GLFW_KEY_KP_MULTIPLY] = rsTIMES;
keymap[GLFW_KEY_KP_SUBTRACT] = rsMINUS;
keymap[GLFW_KEY_KP_ADD] = rsPLUS;
keymap[GLFW_KEY_KP_ENTER] = rsPADENTER;
keymap[GLFW_KEY_KP_EQUAL] = rsNULL;
keymap[GLFW_KEY_LEFT_SHIFT] = rsLSHIFT;
keymap[GLFW_KEY_LEFT_CONTROL] = rsLCTRL;
keymap[GLFW_KEY_LEFT_ALT] = rsLALT;
keymap[GLFW_KEY_LEFT_SUPER] = rsLWIN;
keymap[GLFW_KEY_RIGHT_SHIFT] = rsRSHIFT;
keymap[GLFW_KEY_RIGHT_CONTROL] = rsRCTRL;
keymap[GLFW_KEY_RIGHT_ALT] = rsRALT;
keymap[GLFW_KEY_RIGHT_SUPER] = rsRWIN;
keymap[GLFW_KEY_MENU] = rsNULL;
}
void
keypressCB(GLFWwindow* window, int key, int scancode, int action, int mods)
{
if (key >= 0 && key <= GLFW_KEY_LAST && action != GLFW_REPEAT) {
RsKeyCodes ks = (RsKeyCodes)keymap[key];
if (key == GLFW_KEY_LEFT_SHIFT)
lshiftStatus = action != GLFW_RELEASE;
if (key == GLFW_KEY_RIGHT_SHIFT)
rshiftStatus = action != GLFW_RELEASE;
if (action == GLFW_RELEASE) RsKeyboardEventHandler(rsKEYUP, &ks);
else if (action == GLFW_PRESS) RsKeyboardEventHandler(rsKEYDOWN, &ks);
}
}
#else
uint32 keymap[512]; // 256 ascii + 256 KeySyms between 0xff00 - 0xffff
bool keyStates[512];
uint32 keyCodeToKeymapIndex[256]; // cache for physical keys
#define KEY_MAP_OFFSET (0xff00 - 256)
static void
initkeymap(void)
{
Display *display = glfwGetX11Display();
int i;
for (i = 0; i < ARRAY_SIZE(keymap); i++)
keymap[i] = rsNULL;
// You can add new ASCII mappings to here freely (but beware that if right hand side of assignment isn't supported on CFont, it'll be blank/won't work on binding screen)
// Right hand side of assigments should always be uppercase counterpart of character
keymap[XK_space] = ' ';
keymap[XK_apostrophe] = '\'';
keymap[XK_ampersand] = '&';
keymap[XK_percent] = '%';
keymap[XK_dollar] = '$';
keymap[XK_comma] = ',';
keymap[XK_minus] = '-';
keymap[XK_period] = '.';
keymap[XK_slash] = '/';
keymap[XK_question] = '?';
keymap[XK_exclam] = '!';
keymap[XK_quotedbl] = '"';
keymap[XK_colon] = ':';
keymap[XK_semicolon] = ';';
keymap[XK_equal] = '=';
keymap[XK_bracketleft] = '[';
keymap[XK_backslash] = '\\';
keymap[XK_bracketright] = ']';
keymap[XK_grave] = '`';
keymap[XK_0] = '0';
keymap[XK_1] = '1';
keymap[XK_2] = '2';
keymap[XK_3] = '3';
keymap[XK_4] = '4';
keymap[XK_5] = '5';
keymap[XK_6] = '6';
keymap[XK_7] = '7';
keymap[XK_8] = '8';
keymap[XK_9] = '9';
keymap[XK_a] = 'A';
keymap[XK_b] = 'B';
keymap[XK_c] = 'C';
keymap[XK_d] = 'D';
keymap[XK_e] = 'E';
keymap[XK_f] = 'F';
keymap[XK_g] = 'G';
keymap[XK_h] = 'H';
keymap[XK_i] = 'I';
keymap[XK_I] = 'I'; // Turkish I problem
keymap[XK_j] = 'J';
keymap[XK_k] = 'K';
keymap[XK_l] = 'L';
keymap[XK_m] = 'M';
keymap[XK_n] = 'N';
keymap[XK_o] = 'O';
keymap[XK_p] = 'P';
keymap[XK_q] = 'Q';
keymap[XK_r] = 'R';
keymap[XK_s] = 'S';
keymap[XK_t] = 'T';
keymap[XK_u] = 'U';
keymap[XK_v] = 'V';
keymap[XK_w] = 'W';
keymap[XK_x] = 'X';
keymap[XK_y] = 'Y';
keymap[XK_z] = 'Z';
// Some of regional but ASCII characters that GTA supports
keymap[XK_agrave] = 0x00c0;
keymap[XK_aacute] = 0x00c1;
keymap[XK_acircumflex] = 0x00c2;
keymap[XK_adiaeresis] = 0x00c4;
keymap[XK_ae] = 0x00c6;
keymap[XK_egrave] = 0x00c8;
keymap[XK_eacute] = 0x00c9;
keymap[XK_ecircumflex] = 0x00ca;
keymap[XK_ediaeresis] = 0x00cb;
keymap[XK_igrave] = 0x00cc;
keymap[XK_iacute] = 0x00cd;
keymap[XK_icircumflex] = 0x00ce;
keymap[XK_idiaeresis] = 0x00cf;
keymap[XK_ccedilla] = 0x00c7;
keymap[XK_odiaeresis] = 0x00d6;
keymap[XK_udiaeresis] = 0x00dc;
// These are 0xff00 - 0xffff range of KeySym's, and subtracting KEY_MAP_OFFSET is needed
keymap[XK_Escape - KEY_MAP_OFFSET] = rsESC;
keymap[XK_Return - KEY_MAP_OFFSET] = rsENTER;
keymap[XK_Tab - KEY_MAP_OFFSET] = rsTAB;
keymap[XK_BackSpace - KEY_MAP_OFFSET] = rsBACKSP;
keymap[XK_Insert - KEY_MAP_OFFSET] = rsINS;
keymap[XK_Delete - KEY_MAP_OFFSET] = rsDEL;
keymap[XK_Right - KEY_MAP_OFFSET] = rsRIGHT;
keymap[XK_Left - KEY_MAP_OFFSET] = rsLEFT;
keymap[XK_Down - KEY_MAP_OFFSET] = rsDOWN;
keymap[XK_Up - KEY_MAP_OFFSET] = rsUP;
keymap[XK_Page_Up - KEY_MAP_OFFSET] = rsPGUP;
keymap[XK_Page_Down - KEY_MAP_OFFSET] = rsPGDN;
keymap[XK_Home - KEY_MAP_OFFSET] = rsHOME;
keymap[XK_End - KEY_MAP_OFFSET] = rsEND;
keymap[XK_Caps_Lock - KEY_MAP_OFFSET] = rsCAPSLK;
keymap[XK_Scroll_Lock - KEY_MAP_OFFSET] = rsSCROLL;
keymap[XK_Num_Lock - KEY_MAP_OFFSET] = rsNUMLOCK;
keymap[XK_Pause - KEY_MAP_OFFSET] = rsPAUSE;
keymap[XK_F1 - KEY_MAP_OFFSET] = rsF1;
keymap[XK_F2 - KEY_MAP_OFFSET] = rsF2;
keymap[XK_F3 - KEY_MAP_OFFSET] = rsF3;
keymap[XK_F4 - KEY_MAP_OFFSET] = rsF4;
keymap[XK_F5 - KEY_MAP_OFFSET] = rsF5;
keymap[XK_F6 - KEY_MAP_OFFSET] = rsF6;
keymap[XK_F7 - KEY_MAP_OFFSET] = rsF7;
keymap[XK_F8 - KEY_MAP_OFFSET] = rsF8;
keymap[XK_F9 - KEY_MAP_OFFSET] = rsF9;
keymap[XK_F10 - KEY_MAP_OFFSET] = rsF10;
keymap[XK_F11 - KEY_MAP_OFFSET] = rsF11;
keymap[XK_F12 - KEY_MAP_OFFSET] = rsF12;
keymap[XK_F13 - KEY_MAP_OFFSET] = rsNULL;
keymap[XK_F14 - KEY_MAP_OFFSET] = rsNULL;
keymap[XK_F15 - KEY_MAP_OFFSET] = rsNULL;
keymap[XK_F16 - KEY_MAP_OFFSET] = rsNULL;
keymap[XK_F17 - KEY_MAP_OFFSET] = rsNULL;
keymap[XK_F18 - KEY_MAP_OFFSET] = rsNULL;
keymap[XK_F19 - KEY_MAP_OFFSET] = rsNULL;
keymap[XK_F20 - KEY_MAP_OFFSET] = rsNULL;
keymap[XK_F21 - KEY_MAP_OFFSET] = rsNULL;
keymap[XK_F22 - KEY_MAP_OFFSET] = rsNULL;
keymap[XK_F23 - KEY_MAP_OFFSET] = rsNULL;
keymap[XK_F24 - KEY_MAP_OFFSET] = rsNULL;
keymap[XK_F25 - KEY_MAP_OFFSET] = rsNULL;
keymap[XK_KP_0 - KEY_MAP_OFFSET] = rsPADINS;
keymap[XK_KP_1 - KEY_MAP_OFFSET] = rsPADEND;
keymap[XK_KP_2 - KEY_MAP_OFFSET] = rsPADDOWN;
keymap[XK_KP_3 - KEY_MAP_OFFSET] = rsPADPGDN;
keymap[XK_KP_4 - KEY_MAP_OFFSET] = rsPADLEFT;
keymap[XK_KP_5 - KEY_MAP_OFFSET] = rsPAD5;
keymap[XK_KP_6 - KEY_MAP_OFFSET] = rsPADRIGHT;
keymap[XK_KP_7 - KEY_MAP_OFFSET] = rsPADHOME;
keymap[XK_KP_8 - KEY_MAP_OFFSET] = rsPADUP;
keymap[XK_KP_9 - KEY_MAP_OFFSET] = rsPADPGUP;
keymap[XK_KP_Insert - KEY_MAP_OFFSET] = rsPADINS;
keymap[XK_KP_End - KEY_MAP_OFFSET] = rsPADEND;
keymap[XK_KP_Down - KEY_MAP_OFFSET] = rsPADDOWN;
keymap[XK_KP_Page_Down - KEY_MAP_OFFSET] = rsPADPGDN;
keymap[XK_KP_Left - KEY_MAP_OFFSET] = rsPADLEFT;
keymap[XK_KP_Begin - KEY_MAP_OFFSET] = rsPAD5;
keymap[XK_KP_Right - KEY_MAP_OFFSET] = rsPADRIGHT;
keymap[XK_KP_Home - KEY_MAP_OFFSET] = rsPADHOME;
keymap[XK_KP_Up - KEY_MAP_OFFSET] = rsPADUP;
keymap[XK_KP_Page_Up - KEY_MAP_OFFSET] = rsPADPGUP;
keymap[XK_KP_Decimal - KEY_MAP_OFFSET] = rsPADDEL;
keymap[XK_KP_Divide - KEY_MAP_OFFSET] = rsDIVIDE;
keymap[XK_KP_Multiply - KEY_MAP_OFFSET] = rsTIMES;
keymap[XK_KP_Subtract - KEY_MAP_OFFSET] = rsMINUS;
keymap[XK_KP_Add - KEY_MAP_OFFSET] = rsPLUS;
keymap[XK_KP_Enter - KEY_MAP_OFFSET] = rsPADENTER;
keymap[XK_KP_Equal - KEY_MAP_OFFSET] = rsNULL;
keymap[XK_Shift_L - KEY_MAP_OFFSET] = rsLSHIFT;
keymap[XK_Control_L - KEY_MAP_OFFSET] = rsLCTRL;
keymap[XK_Alt_L - KEY_MAP_OFFSET] = rsLALT;
keymap[XK_Super_L - KEY_MAP_OFFSET] = rsLWIN;
keymap[XK_Shift_R - KEY_MAP_OFFSET] = rsRSHIFT;
keymap[XK_Control_R - KEY_MAP_OFFSET] = rsRCTRL;
keymap[XK_Alt_R - KEY_MAP_OFFSET] = rsRALT;
keymap[XK_Super_R - KEY_MAP_OFFSET] = rsRWIN;
keymap[XK_Menu - KEY_MAP_OFFSET] = rsNULL;
// Cache the key codes' key symbol equivelants, otherwise we will have to do it on each frame
// KeyCode is always in [0,255], and represents a physical key
int min_keycode, max_keycode, keysyms_per_keycode;
KeySym *keymap, *origkeymap;
char *keyboardLang = setlocale (LC_CTYPE, NULL);
setlocale(LC_CTYPE, "");
XDisplayKeycodes(display, &min_keycode, &max_keycode);
origkeymap = XGetKeyboardMapping(display, min_keycode, (max_keycode - min_keycode + 1), &keysyms_per_keycode);
keymap = origkeymap;
for (int i = min_keycode; i <= max_keycode; i++) {
int j, lastKeysym;
lastKeysym = keysyms_per_keycode - 1;
while ((lastKeysym >= 0) && (keymap[lastKeysym] == NoSymbol))
lastKeysym--;
for (j = 0; j <= lastKeysym; j++) {
KeySym ks = keymap[j];
if (ks == NoSymbol)
continue;
if (ks < 256) {
keyCodeToKeymapIndex[i] = ks;
break;
} else if (ks >= 0xff00 && ks < 0xffff) {
keyCodeToKeymapIndex[i] = ks - KEY_MAP_OFFSET;
break;
}
}
keymap += keysyms_per_keycode;
}
XFree(origkeymap);
setlocale(LC_CTYPE, keyboardLang);
}
#undef KEY_MAP_OFFSET
void checkKeyPresses()
{
Display *display = glfwGetX11Display();
char keys[32];
XQueryKeymap(display, keys);
for (int i = 0; i < sizeof(keys); i++) {
for (int j = 0; j < 8; j++) {
KeyCode keycode = 8 * i + j;
uint32 keymapIndex = keyCodeToKeymapIndex[keycode];
if (keymapIndex != 0) {
int rsCode = keymap[keymapIndex];
if (rsCode == rsNULL)
continue;
bool pressed = WindowFocused && !!(keys[i] & (1 << j));
// idk why R* does that
if (rsCode == rsLSHIFT)
lshiftStatus = pressed;
else if (rsCode == rsRSHIFT)
rshiftStatus = pressed;
if (keyStates[keymapIndex] != pressed) {
if (pressed) {
RsKeyboardEventHandler(rsKEYDOWN, &rsCode);
} else {
RsKeyboardEventHandler(rsKEYUP, &rsCode);
}
}
keyStates[keymapIndex] = pressed;
}
}
}
}
#endif
// R* calls that in ControllerConfig, idk why
void
_InputTranslateShiftKeyUpDown(RsKeyCodes *rs) {
RsKeyboardEventHandler(lshiftStatus ? rsKEYDOWN : rsKEYUP, &(*rs = rsLSHIFT));
RsKeyboardEventHandler(rshiftStatus ? rsKEYDOWN : rsKEYUP, &(*rs = rsRSHIFT));
}
// TODO this only works in frontend(and luckily only frontend use this). Fun fact: if I get pos manually in game, glfw reports that it's > 32000
void
cursorCB(GLFWwindow* window, double xpos, double ypos) {
if (!FrontEndMenuManager.m_bMenuActive)
return;
int winw, winh;
glfwGetWindowSize(PSGLOBAL(window), &winw, &winh);
FrontEndMenuManager.m_nMouseTempPosX = xpos * (RsGlobal.maximumWidth / winw);
FrontEndMenuManager.m_nMouseTempPosY = ypos * (RsGlobal.maximumHeight / winh);
}
void
cursorEnterCB(GLFWwindow* window, int entered) {
PSGLOBAL(cursorIsInWindow) = !!entered;
}
void
windowFocusCB(GLFWwindow* window, int focused) {
WindowFocused = !!focused;
}
void
windowIconifyCB(GLFWwindow* window, int iconified) {
WindowIconified = !!iconified;
}
/*
*****************************************************************************
*/
#ifdef _WIN32
int PASCAL
WinMain(HINSTANCE instance,
HINSTANCE prevInstance __RWUNUSED__,
CMDSTR cmdLine,
int cmdShow)
{
RwInt32 argc;
RwChar** argv;
SystemParametersInfo(SPI_SETFOREGROUNDLOCKTIMEOUT, 0, nil, SPIF_SENDCHANGE);
#ifndef MASTER
if (strstr(cmdLine, "-console"))
{
AllocConsole();
freopen("CONIN$", "r", stdin);
freopen("CONOUT$", "w", stdout);
freopen("CONOUT$", "w", stderr);
}
#endif
#else
int
main(int argc, char *argv[])
{
#endif
RwV2d pos;
RwInt32 i;
#ifdef USE_CUSTOM_ALLOCATOR
InitMemoryMgr();
#endif
#ifndef _WIN32
struct sigaction act;
act.sa_sigaction = terminateHandler;
act.sa_flags = SA_SIGINFO;
sigaction(SIGTERM, &act, NULL);
#ifdef FLUSHABLE_STREAMING
struct sigaction sa;
sigemptyset(&sa.sa_mask);
sa.sa_handler = dummyHandler;
sa.sa_flags = 0;
sigaction(SIGUSR1, &sa, NULL);
#endif
#endif
/*
* Initialize the platform independent data.
* This will in turn initialize the platform specific data...
*/
if( RsEventHandler(rsINITIALIZE, nil) == rsEVENTERROR )
{
return FALSE;
}
#ifdef _WIN32
/*
* Get proper command line params, cmdLine passed to us does not
* work properly under all circumstances...
*/
cmdLine = GetCommandLine();
/*
* Parse command line into standard (argv, argc) parameters...
*/
argv = CommandLineToArgv(cmdLine, &argc);
/*
* Parse command line parameters (except program name) one at
* a time BEFORE RenderWare initialization...
*/
#endif
for(i=1; i<argc; i++)
{
RsEventHandler(rsPREINITCOMMANDLINE, argv[i]);
}
/*
* Parameters to be used in RwEngineOpen / rsRWINITIALISE event
*/
openParams.width = RsGlobal.maximumWidth;
openParams.height = RsGlobal.maximumHeight;
openParams.windowtitle = RsGlobal.appName;
openParams.window = &PSGLOBAL(window);
ControlsManager.MakeControllerActionsBlank();
ControlsManager.InitDefaultControlConfiguration();
/*
* Initialize the 3D (RenderWare) components of the app...
*/
if( rsEVENTERROR == RsEventHandler(rsRWINITIALIZE, &openParams) )
{
RsEventHandler(rsTERMINATE, nil);
return 0;
}
#ifdef _WIN32
HWND wnd = glfwGetWin32Window(PSGLOBAL(window));
HICON icon = LoadIcon(instance, MAKEINTRESOURCE(IDI_MAIN_ICON));
SendMessage(wnd, WM_SETICON, ICON_BIG, (LPARAM)icon);
SendMessage(wnd, WM_SETICON, ICON_SMALL, (LPARAM)icon);
#endif
psPostRWinit();
ControlsManager.InitDefaultControlConfigMouse(MousePointerStateHelper.GetMouseSetUp());
// glfwSetWindowPos(PSGLOBAL(window), 0, 0);
/*
* Parse command line parameters (except program name) one at
* a time AFTER RenderWare initialization...
*/
for(i=1; i<argc; i++)
{
RsEventHandler(rsCOMMANDLINE, argv[i]);
}
/*
* Force a camera resize event...
*/
{
RwRect r;
r.x = 0;
r.y = 0;
r.w = RsGlobal.maximumWidth;
r.h = RsGlobal.maximumHeight;
RsEventHandler(rsCAMERASIZE, &r);
}
#ifdef _WIN32
SystemParametersInfo(SPI_SETPOWEROFFACTIVE, FALSE, nil, SPIF_SENDCHANGE);
SystemParametersInfo(SPI_SETLOWPOWERACTIVE, FALSE, nil, SPIF_SENDCHANGE);
STICKYKEYS SavedStickyKeys;
SavedStickyKeys.cbSize = sizeof(STICKYKEYS);
SystemParametersInfo(SPI_GETSTICKYKEYS, sizeof(STICKYKEYS), &SavedStickyKeys, SPIF_SENDCHANGE);
STICKYKEYS NewStickyKeys;
NewStickyKeys.cbSize = sizeof(STICKYKEYS);
NewStickyKeys.dwFlags = SKF_TWOKEYSOFF;
SystemParametersInfo(SPI_SETSTICKYKEYS, sizeof(STICKYKEYS), &NewStickyKeys, SPIF_SENDCHANGE);
#endif
{
CFileMgr::SetDirMyDocuments();
#ifdef LOAD_INI_SETTINGS
// At this point InitDefaultControlConfigJoyPad must have set all bindings to default and ms_padButtonsInited to number of detected buttons.
// We will load stored bindings below, but let's cache ms_padButtonsInited before LoadINIControllerSettings and LoadSettings clears it,
// so we can add new joy bindings **on top of** stored bindings.
int connectedPadButtons = ControlsManager.ms_padButtonsInited;
#endif
int32 gta3set = CFileMgr::OpenFile("gta3.set", "r");
if ( gta3set )
{
ControlsManager.LoadSettings(gta3set);
CFileMgr::CloseFile(gta3set);
}
CFileMgr::SetDir("");
#ifdef LOAD_INI_SETTINGS
LoadINIControllerSettings();
if (connectedPadButtons != 0) {
ControlsManager.InitDefaultControlConfigJoyPad(connectedPadButtons);
SaveINIControllerSettings();
}
#endif
}
#ifdef _WIN32
SetErrorMode(SEM_FAILCRITICALERRORS);
#endif
#ifdef PS2_MENU
int32 r = TheMemoryCard.CheckCardStateAtGameStartUp(CARD_ONE);
if ( r == CMemoryCard::ERR_DIRNOENTRY || r == CMemoryCard::ERR_NOFORMAT
&& r != CMemoryCard::ERR_OPENNOENTRY && r != CMemoryCard::ERR_NONE )
{
LoadingScreen(nil, nil, "loadsc0");
TheText.Unload();
TheText.Load();
CFont::Initialise();
FrontEndMenuManager.DrawMemoryCardStartUpMenus();
}
#endif
initkeymap();
while ( TRUE )
{
RwInitialised = TRUE;
/*
* Set the initial mouse position...
*/
pos.x = RsGlobal.maximumWidth * 0.5f;
pos.y = RsGlobal.maximumHeight * 0.5f;
RsMouseSetPos(&pos);
/*
* Enter the message processing loop...
*/
#ifndef MASTER
if (gbModelViewer) {
// This is TheModelViewer in LCS, but not compiled on III Mobile.
LoadingScreen("Loading the ModelViewer", NULL, GetRandomSplashScreen());
CAnimViewer::Initialise();
CTimer::Update();
#ifndef PS2_MENU
FrontEndMenuManager.m_bGameNotLoaded = false;
#endif
}
#endif
#ifdef PS2_MENU
if (TheMemoryCard.m_bWantToLoad)
LoadSplash(GetLevelSplashScreen(CGame::currLevel));
TheMemoryCard.m_bWantToLoad = false;
CTimer::Update();
while( !RsGlobal.quit && !(FrontEndMenuManager.m_bWantToRestart || TheMemoryCard.b_FoundRecentSavedGameWantToLoad) && !glfwWindowShouldClose(PSGLOBAL(window)) )
#else
while( !RsGlobal.quit && !FrontEndMenuManager.m_bWantToRestart && !glfwWindowShouldClose(PSGLOBAL(window)))
#endif
{
glfwPollEvents();
#ifdef GET_KEYBOARD_INPUT_FROM_X11
checkKeyPresses();
#endif
#ifndef MASTER
if (gbModelViewer) {
// This is TheModelViewerCore in LCS, but TheModelViewer on other state-machine III-VCs.
TheModelViewer();
} else
#endif
if ( ForegroundApp )
{
switch ( gGameState )
{
case GS_START_UP:
{
#ifdef NO_MOVIES
gGameState = GS_INIT_ONCE;
#else
gGameState = GS_INIT_LOGO_MPEG;
#endif
TRACE("gGameState = GS_INIT_ONCE");
break;
}
case GS_INIT_LOGO_MPEG:
{
//if (!startupDeactivate)
// PlayMovieInWindow(cmdShow, "movies\\Logo.mpg");
gGameState = GS_LOGO_MPEG;
TRACE("gGameState = GS_LOGO_MPEG;");
break;
}
case GS_LOGO_MPEG:
{
// CPad::UpdatePads();
// if (startupDeactivate || ControlsManager.GetJoyButtonJustDown() != 0)
++gGameState;
// else if (CPad::GetPad(0)->GetLeftMouseJustDown())
// ++gGameState;
// else if (CPad::GetPad(0)->GetEnterJustDown())
// ++gGameState;
// else if (CPad::GetPad(0)->GetCharJustDown(' '))
// ++gGameState;
// else if (CPad::GetPad(0)->GetAltJustDown())
// ++gGameState;
// else if (CPad::GetPad(0)->GetTabJustDown())
// ++gGameState;
break;
}
case GS_INIT_INTRO_MPEG:
{
//#ifndef NO_MOVIES
// CloseClip();
// CoUninitialize();
//#endif
//
// if (CMenuManager::OS_Language == LANG_FRENCH || CMenuManager::OS_Language == LANG_GERMAN)
// PlayMovieInWindow(cmdShow, "movies\\GTAtitlesGER.mpg");
// else
// PlayMovieInWindow(cmdShow, "movies\\GTAtitles.mpg");
gGameState = GS_INTRO_MPEG;
TRACE("gGameState = GS_INTRO_MPEG;");
break;
}
case GS_INTRO_MPEG:
{
// CPad::UpdatePads();
//
// if (startupDeactivate || ControlsManager.GetJoyButtonJustDown() != 0)
++gGameState;
// else if (CPad::GetPad(0)->GetLeftMouseJustDown())
// ++gGameState;
// else if (CPad::GetPad(0)->GetEnterJustDown())
// ++gGameState;
// else if (CPad::GetPad(0)->GetCharJustDown(' '))
// ++gGameState;
// else if (CPad::GetPad(0)->GetAltJustDown())
// ++gGameState;
// else if (CPad::GetPad(0)->GetTabJustDown())
// ++gGameState;
break;
}
case GS_INIT_ONCE:
{
//CoUninitialize();
#ifdef PS2_MENU
extern char version_name[64];
if ( CGame::frenchGame || CGame::germanGame )
LoadingScreen(NULL, version_name, "loadsc24");
else
LoadingScreen(NULL, version_name, "loadsc0");
printf("Into TheGame!!!\n");
#else
LoadingScreen(nil, nil, "loadsc0");
#endif
if ( !CGame::InitialiseOnceAfterRW() )
RsGlobal.quit = TRUE;
#ifdef PS2_MENU
gGameState = GS_INIT_PLAYING_GAME;
#else
gGameState = GS_INIT_FRONTEND;
TRACE("gGameState = GS_INIT_FRONTEND;");
#endif
break;
}
#ifndef PS2_MENU
case GS_INIT_FRONTEND:
{
LoadingScreen(nil, nil, "loadsc0");
FrontEndMenuManager.m_bGameNotLoaded = true;
CMenuManager::m_bStartUpFrontEndRequested = true;
if ( defaultFullscreenRes )
{
defaultFullscreenRes = FALSE;
FrontEndMenuManager.m_nPrefsVideoMode = GcurSelVM;
FrontEndMenuManager.m_nDisplayVideoMode = GcurSelVM;
}
gGameState = GS_FRONTEND;
TRACE("gGameState = GS_FRONTEND;");
break;
}
case GS_FRONTEND:
{
if(!WindowIconified)
RsEventHandler(rsFRONTENDIDLE, nil);
#ifdef PS2_MENU
if ( !FrontEndMenuManager.m_bMenuActive || TheMemoryCard.m_bWantToLoad )
#else
if ( !FrontEndMenuManager.m_bMenuActive || FrontEndMenuManager.m_bWantToLoad )
#endif
{
gGameState = GS_INIT_PLAYING_GAME;
TRACE("gGameState = GS_INIT_PLAYING_GAME;");
}
#ifdef PS2_MENU
if (TheMemoryCard.m_bWantToLoad )
#else
if ( FrontEndMenuManager.m_bWantToLoad )
#endif
{
InitialiseGame();
FrontEndMenuManager.m_bGameNotLoaded = false;
gGameState = GS_PLAYING_GAME;
TRACE("gGameState = GS_PLAYING_GAME;");
}
break;
}
#endif
case GS_INIT_PLAYING_GAME:
{
#ifdef PS2_MENU
CGame::Initialise("DATA\\GTA3.DAT");
//LoadingScreen("Starting Game", NULL, GetRandomSplashScreen());
if ( TheMemoryCard.CheckCardInserted(CARD_ONE) == CMemoryCard::NO_ERR_SUCCESS
&& TheMemoryCard.ChangeDirectory(CARD_ONE, TheMemoryCard.Cards[CARD_ONE].dir)
&& TheMemoryCard.FindMostRecentFileName(CARD_ONE, TheMemoryCard.MostRecentFile) == true
&& TheMemoryCard.CheckDataNotCorrupt(TheMemoryCard.MostRecentFile))
{
strcpy(TheMemoryCard.LoadFileName, TheMemoryCard.MostRecentFile);
TheMemoryCard.b_FoundRecentSavedGameWantToLoad = true;
if (CMenuManager::m_PrefsLanguage != TheMemoryCard.GetLanguageToLoad())
{
CMenuManager::m_PrefsLanguage = TheMemoryCard.GetLanguageToLoad();
TheText.Unload();
TheText.Load();
}
CGame::currLevel = (eLevelName)TheMemoryCard.GetLevelToLoad();
}
#else
InitialiseGame();
FrontEndMenuManager.m_bGameNotLoaded = false;
#endif
gGameState = GS_PLAYING_GAME;
TRACE("gGameState = GS_PLAYING_GAME;");
break;
}
case GS_PLAYING_GAME:
{
float ms = (float)CTimer::GetCurrentTimeInCycles() / (float)CTimer::GetCyclesPerMillisecond();
if ( RwInitialised )
{
if (!CMenuManager::m_PrefsFrameLimiter || (1000.0f / (float)RsGlobal.maxFPS) < ms)
RsEventHandler(rsIDLE, (void *)TRUE);
}
break;
}
}
}
else
{
if ( RwCameraBeginUpdate(Scene.camera) )
{
RwCameraEndUpdate(Scene.camera);
ForegroundApp = TRUE;
RsEventHandler(rsACTIVATE, (void *)TRUE);
}
}
}
/*
* About to shut down - block resize events again...
*/
RwInitialised = FALSE;
FrontEndMenuManager.UnloadTextures();
#ifdef PS2_MENU
if ( !(FrontEndMenuManager.m_bWantToRestart || TheMemoryCard.b_FoundRecentSavedGameWantToLoad))
break;
#else
if ( !FrontEndMenuManager.m_bWantToRestart )
break;
#endif
CPad::ResetCheats();
CPad::StopPadsShaking();
DMAudio.ChangeMusicMode(MUSICMODE_DISABLE);
#ifdef PS2_MENU
CGame::ShutDownForRestart();
#endif
CTimer::Stop();
#ifdef PS2_MENU
if (FrontEndMenuManager.m_bWantToRestart || TheMemoryCard.b_FoundRecentSavedGameWantToLoad)
{
if (TheMemoryCard.b_FoundRecentSavedGameWantToLoad)
{
FrontEndMenuManager.m_bWantToRestart = true;
TheMemoryCard.m_bWantToLoad = true;
}
CGame::InitialiseWhenRestarting();
DMAudio.ChangeMusicMode(MUSICMODE_GAME);
FrontEndMenuManager.m_bWantToRestart = false;
continue;
}
CGame::ShutDown();
CTimer::Stop();
break;
#else
if ( FrontEndMenuManager.m_bWantToLoad )
{
CGame::ShutDownForRestart();
CGame::InitialiseWhenRestarting();
DMAudio.ChangeMusicMode(MUSICMODE_GAME);
LoadSplash(GetLevelSplashScreen(CGame::currLevel));
FrontEndMenuManager.m_bWantToLoad = false;
}
else
{
#ifndef MASTER
if ( gbModelViewer )
CAnimViewer::Shutdown();
else
#endif
if ( gGameState == GS_PLAYING_GAME )
CGame::ShutDown();
CTimer::Stop();
if ( FrontEndMenuManager.m_bFirstTime == true )
{
gGameState = GS_INIT_FRONTEND;
TRACE("gGameState = GS_INIT_FRONTEND;");
}
else
{
gGameState = GS_INIT_PLAYING_GAME;
TRACE("gGameState = GS_INIT_PLAYING_GAME;");
}
}
FrontEndMenuManager.m_bFirstTime = false;
FrontEndMenuManager.m_bWantToRestart = false;
#endif
}
#ifndef MASTER
if ( gbModelViewer )
CAnimViewer::Shutdown();
else
#endif
if ( gGameState == GS_PLAYING_GAME )
CGame::ShutDown();
DMAudio.Terminate();
_psFreeVideoModeList();
/*
* Tidy up the 3D (RenderWare) components of the application...
*/
RsEventHandler(rsRWTERMINATE, nil);
/*
* Free the platform dependent data...
*/
RsEventHandler(rsTERMINATE, nil);
#ifdef _WIN32
/*
* Free the argv strings...
*/
free(argv);
SystemParametersInfo(SPI_SETSTICKYKEYS, sizeof(STICKYKEYS), &SavedStickyKeys, SPIF_SENDCHANGE);
SystemParametersInfo(SPI_SETPOWEROFFACTIVE, TRUE, nil, SPIF_SENDCHANGE);
SystemParametersInfo(SPI_SETLOWPOWERACTIVE, TRUE, nil, SPIF_SENDCHANGE);
SetErrorMode(0);
#endif
return 0;
}
/*
*****************************************************************************
*/
RwV2d leftStickPos;
RwV2d rightStickPos;
void CapturePad(RwInt32 padID)
{
int8 glfwPad = -1;
if( padID == 0 )
glfwPad = PSGLOBAL(joy1id);
else if( padID == 1)
glfwPad = PSGLOBAL(joy2id);
else
assert("invalid padID");
if ( glfwPad == -1 )
return;
int numButtons, numAxes;
const uint8 *buttons = glfwGetJoystickButtons(glfwPad, &numButtons);
const float *axes = glfwGetJoystickAxes(glfwPad, &numAxes);
GLFWgamepadstate gamepadState;
if (ControlsManager.m_bFirstCapture == false) {
memcpy(&ControlsManager.m_OldState, &ControlsManager.m_NewState, sizeof(ControlsManager.m_NewState));
} else {
// In case connected gamepad doesn't have L-R trigger axes.
ControlsManager.m_NewState.mappedButtons[15] = ControlsManager.m_NewState.mappedButtons[16] = 0;
}
ControlsManager.m_NewState.buttons = (uint8*)buttons;
ControlsManager.m_NewState.numButtons = numButtons;
ControlsManager.m_NewState.id = glfwPad;
ControlsManager.m_NewState.isGamepad = glfwGetGamepadState(glfwPad, &gamepadState);
if (ControlsManager.m_NewState.isGamepad) {
memcpy(&ControlsManager.m_NewState.mappedButtons, gamepadState.buttons, sizeof(gamepadState.buttons));
float lt = gamepadState.axes[GLFW_GAMEPAD_AXIS_LEFT_TRIGGER], rt = gamepadState.axes[GLFW_GAMEPAD_AXIS_RIGHT_TRIGGER];
// glfw returns 0.0 for non-existent axises(which is bullocks) so we treat it as deadzone, and keep value of previous frame.
// otherwise if this axis is present, -1 = released, 1 = pressed
if (lt != 0.0f)
ControlsManager.m_NewState.mappedButtons[15] = lt > -0.8f;
if (rt != 0.0f)
ControlsManager.m_NewState.mappedButtons[16] = rt > -0.8f;
}
// TODO? L2-R2 axes(not buttons-that's fine) on joysticks that don't have SDL gamepad mapping AREN'T handled, and I think it's impossible to do without mapping.
if (ControlsManager.m_bFirstCapture == true) {
memcpy(&ControlsManager.m_OldState, &ControlsManager.m_NewState, sizeof(ControlsManager.m_NewState));
ControlsManager.m_bFirstCapture = false;
}
RsPadButtonStatus bs;
bs.padID = padID;
RsPadEventHandler(rsPADBUTTONUP, (void *)&bs);
// Gamepad axes are guaranteed to return 0.0f if that particular gamepad doesn't have that axis.
// And that's really good for sticks, because gamepads return 0.0 for them when sticks are in released state.
if ( glfwPad != -1 ) {
leftStickPos.x = ControlsManager.m_NewState.isGamepad ? gamepadState.axes[GLFW_GAMEPAD_AXIS_LEFT_X] : numAxes >= 1 ? axes[0] : 0.0f;
leftStickPos.y = ControlsManager.m_NewState.isGamepad ? gamepadState.axes[GLFW_GAMEPAD_AXIS_LEFT_Y] : numAxes >= 2 ? axes[1] : 0.0f;
rightStickPos.x = ControlsManager.m_NewState.isGamepad ? gamepadState.axes[GLFW_GAMEPAD_AXIS_RIGHT_X] : numAxes >= 3 ? axes[2] : 0.0f;
rightStickPos.y = ControlsManager.m_NewState.isGamepad ? gamepadState.axes[GLFW_GAMEPAD_AXIS_RIGHT_Y] : numAxes >= 4 ? axes[3] : 0.0f;
}
{
if (CPad::m_bMapPadOneToPadTwo)
bs.padID = 1;
RsPadEventHandler(rsPADBUTTONUP, (void *)&bs);
RsPadEventHandler(rsPADBUTTONDOWN, (void *)&bs);
}
{
if (CPad::m_bMapPadOneToPadTwo)
bs.padID = 1;
CPad *pad = CPad::GetPad(bs.padID);
if ( Abs(leftStickPos.x) > 0.3f )
pad->PCTempJoyState.LeftStickX = (int32)(leftStickPos.x * 128.0f);
if ( Abs(leftStickPos.y) > 0.3f )
pad->PCTempJoyState.LeftStickY = (int32)(leftStickPos.y * 128.0f);
if ( Abs(rightStickPos.x) > 0.3f )
pad->PCTempJoyState.RightStickX = (int32)(rightStickPos.x * 128.0f);
if ( Abs(rightStickPos.y) > 0.3f )
pad->PCTempJoyState.RightStickY = (int32)(rightStickPos.y * 128.0f);
}
return;
}
void joysChangeCB(int jid, int event)
{
if (event == GLFW_CONNECTED && !IsThisJoystickBlacklisted(jid)) {
if (PSGLOBAL(joy1id) == -1) {
PSGLOBAL(joy1id) = jid;
#ifdef DETECT_JOYSTICK_MENU
strcpy(gSelectedJoystickName, glfwGetJoystickName(jid));
#endif
// This is behind LOAD_INI_SETTINGS, because otherwise the Init call below will destroy/overwrite your bindings.
#ifdef LOAD_INI_SETTINGS
int count;
glfwGetJoystickButtons(PSGLOBAL(joy1id), &count);
ControlsManager.InitDefaultControlConfigJoyPad(count);
#endif
} else if (PSGLOBAL(joy2id) == -1)
PSGLOBAL(joy2id) = jid;
} else if (event == GLFW_DISCONNECTED) {
if (PSGLOBAL(joy1id) == jid) {
PSGLOBAL(joy1id) = -1;
} else if (PSGLOBAL(joy2id) == jid)
PSGLOBAL(joy2id) = -1;
}
}
#if (defined(_MSC_VER))
int strcasecmp(const char* str1, const char* str2)
{
return _strcmpi(str1, str2);
}
#endif
#endif
| 25.058587 | 170 | 0.677081 | gameblabla |
1d2ad9a8b2c8b8d69a051d12971d181f678bf912 | 16,284 | cc | C++ | src/4txn/txn_local.cc | cflaviu/upscaledb | 2d9aec05fd5c32e12115eed37695c828faac5472 | [
"Apache-2.0"
] | 350 | 2015-11-05T00:49:19.000Z | 2022-03-23T16:27:36.000Z | src/4txn/txn_local.cc | veloman-yunkan/upscaledb | 80d01b843719d5ca4c6fdfcf474fa0d66cf877e6 | [
"Apache-2.0"
] | 71 | 2015-11-05T19:26:57.000Z | 2021-08-20T14:52:21.000Z | src/4txn/txn_local.cc | veloman-yunkan/upscaledb | 80d01b843719d5ca4c6fdfcf474fa0d66cf877e6 | [
"Apache-2.0"
] | 55 | 2015-11-04T15:09:16.000Z | 2021-12-23T20:45:24.000Z | /*
* Copyright (C) 2005-2017 Christoph Rupp ([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.
*
* See the file COPYING for License information.
*/
#include "0root/root.h"
// Always verify that a file of level N does not include headers > N!
#include "3btree/btree_index.h"
#include "3journal/journal.h"
#include "4db/db_local.h"
#include "4txn/txn_local.h"
#include "4txn/txn_factory.h"
#include "4txn/txn_cursor.h"
#include "4env/env_local.h"
#include "4cursor/cursor_local.h"
#include "4context/context.h"
#ifndef UPS_ROOT_H
# error "root.h was not included"
#endif
namespace upscaledb {
// stuff for rb.h
#ifndef __ssize_t_defined
typedef signed ssize_t;
#endif
#ifndef __cplusplus
typedef int bool;
#define true 1
#define false (!true)
#endif // __cpluscplus
static int
compare(void *vlhs, void *vrhs)
{
TxnNode *lhs = (TxnNode *)vlhs;
TxnNode *rhs = (TxnNode *)vrhs;
LocalDb *db = lhs->db;
if (unlikely(lhs == rhs))
return 0;
ups_key_t *lhskey = lhs->key();
ups_key_t *rhskey = rhs->key();
assert(lhskey && rhskey);
return db->btree_index->compare_keys(lhskey, rhskey);
}
rb_proto(static, rbt_, TxnIndex, TxnNode)
rb_gen(static, rbt_, TxnIndex, TxnNode, node, compare)
static inline int
count_flushable_transactions(LocalTxnManager *tm)
{
int to_flush = 0;
LocalTxn *oldest = (LocalTxn *)tm->oldest_txn();
for (; oldest; oldest = (LocalTxn *)oldest->next()) {
// a transaction can be flushed if it's committed or aborted, and if there
// are no cursors coupled to it
if (oldest->is_committed() || oldest->is_aborted()) {
for (TxnOperation *op = oldest->oldest_op;
op != 0; op = op->next_in_txn)
if (unlikely(op->cursor_list != 0))
return to_flush;
to_flush++;
}
else
return to_flush;
}
return to_flush;
}
static inline void
flush_committed_txns_impl(LocalTxnManager *tm, Context *context)
{
LocalTxn *oldest;
uint64_t highest_lsn = 0;
assert(context->changeset.is_empty());
// always get the oldest transaction; if it was committed: flush
// it; if it was aborted: discard it; otherwise return
while ((oldest = (LocalTxn *)tm->oldest_txn())) {
if (oldest->is_committed()) {
uint64_t lsn = tm->flush_txn_to_changeset(context, (LocalTxn *)oldest);
if (lsn > highest_lsn)
highest_lsn = lsn;
}
else if (oldest->is_aborted()) {
; // nop
}
else
break;
// now remove the txn from the linked list
tm->remove_txn_from_head(oldest);
// and release the memory
delete oldest;
}
// now flush the changeset and write the modified pages to disk
if (highest_lsn && tm->lenv()->journal.get())
context->changeset.flush(tm->lenv()->lsn_manager.next());
else
context->changeset.clear();
assert(context->changeset.is_empty());
}
void
TxnOperation::initialize(LocalTxn *txn_, TxnNode *node_,
uint32_t flags_, uint32_t original_flags_, uint64_t lsn_,
ups_key_t *key_, ups_record_t *record_)
{
::memset(this, 0, sizeof(*this));
txn = txn_;
node = node_;
lsn = lsn_;
flags = flags_;
original_flags = original_flags_;
// copy the key data
if (key_) {
key = *key_;
if (likely(key.size)) {
key.data = &_data[0];
::memcpy(key.data, key_->data, key.size);
}
}
// copy the record data
if (record_) {
record = *record_;
if (likely(record.size)) {
record.data = &_data[key_ ? key.size : 0];
::memcpy(record.data, record_->data, record.size);
}
}
}
void
TxnOperation::destroy()
{
bool delete_node = false;
if (node->newest_op == this)
node->newest_op = previous_in_node;
// remove this op from the node
if (node->oldest_op == this) {
// if the node is empty: remove the node from the tree
// TODO should this be done in here??
if (next_in_node == 0) {
node->db->txn_index->remove(node);
delete_node = true;
}
node->oldest_op = next_in_node;
}
// remove this operation from the two linked lists
if (next_in_node)
next_in_node->previous_in_node = previous_in_node;
if (previous_in_node)
previous_in_node->next_in_node = next_in_node;
if (next_in_txn)
next_in_txn->previous_in_txn = previous_in_txn;
if (previous_in_txn)
previous_in_txn->next_in_txn = next_in_txn;
if (delete_node)
delete node;
Memory::release(this);
}
TxnNode *
TxnNode::next_sibling()
{
return rbt_next(db->txn_index.get(), this);
}
TxnNode *
TxnNode::previous_sibling()
{
return rbt_prev(db->txn_index.get(), this);
}
TxnNode::TxnNode(LocalDb *db_, ups_key_t *key)
: db(db_), oldest_op(0), newest_op(0), _key(key)
{
}
TxnOperation *
TxnNode::append(LocalTxn *txn, uint32_t orig_flags, uint32_t flags,
uint64_t lsn, ups_key_t *key, ups_record_t *record)
{
TxnOperation *op = TxnFactory::create_operation(txn, this, flags,
orig_flags, lsn, key, record);
// store it in the chronological list which is managed by the node
if (!newest_op) {
assert(oldest_op == 0);
newest_op = op;
oldest_op = op;
}
else {
TxnOperation *newest = newest_op;
newest->next_in_node = op;
op->previous_in_node = newest;
newest_op = op;
}
// store it in the chronological list which is managed by the transaction
if (!txn->newest_op) {
assert(txn->oldest_op == 0);
txn->newest_op = op;
txn->oldest_op = op;
}
else {
TxnOperation *newest = txn->newest_op;
newest->next_in_txn = op;
op->previous_in_txn = newest;
txn->newest_op = op;
}
// now that an operation is attached make sure that the node no
// longer uses the temporary key pointer
_key = 0;
return op;
}
TxnNode *
TxnIndex::store(ups_key_t *key, bool *node_created)
{
*node_created = false;
TxnNode *node = get(key, 0);
if (!node) {
node = new TxnNode(db, key);
*node_created = true;
rbt_insert(this, node);
}
return node;
}
void
TxnIndex::remove(TxnNode *node)
{
rbt_remove(this, node);
}
static inline void
flush_transaction_to_journal(LocalTxn *txn)
{
LocalEnv *lenv = (LocalEnv *)txn->env;
Journal *journal = lenv->journal.get();
if (unlikely(journal == 0))
return;
if (NOTSET(txn->flags, UPS_TXN_TEMPORARY))
journal->append_txn_begin(txn, txn->name.empty() ? 0 : txn->name.c_str(),
txn->lsn);
for (TxnOperation *op = txn->oldest_op;
op != 0;
op = op->next_in_txn) {
if (ISSET(op->flags, TxnOperation::kErase)) {
journal->append_erase(op->node->db, txn,
op->node->key(), op->referenced_duplicate,
op->original_flags, op->lsn);
continue;
}
if (ISSET(op->flags, TxnOperation::kInsert)) {
journal->append_insert(op->node->db, txn,
op->node->key(), &op->record,
op->original_flags, op->lsn);
continue;
}
if (ISSET(op->flags, TxnOperation::kInsertOverwrite)) {
journal->append_insert(op->node->db, txn,
op->node->key(), &op->record,
op->original_flags | UPS_OVERWRITE, op->lsn);
continue;
}
if (ISSET(op->flags, TxnOperation::kInsertDuplicate)) {
journal->append_insert(op->node->db, txn,
op->node->key(), &op->record,
op->original_flags | UPS_DUPLICATE, op->lsn);
continue;
}
assert(!"shouldn't be here");
}
if (NOTSET(txn->flags, UPS_TXN_TEMPORARY))
journal->append_txn_commit(txn, lenv->lsn_manager.next());
}
LocalTxn::LocalTxn(LocalEnv *env, const char *name, uint32_t flags)
: Txn(env, name, flags), log_descriptor(0), oldest_op(0), newest_op(0)
{
LocalTxnManager *ltm = (LocalTxnManager *)env->txn_manager.get();
id = ltm->incremented_txn_id();
lsn = env->lsn_manager.next();
}
LocalTxn::~LocalTxn()
{
free_operations();
}
void
LocalTxn::commit()
{
// are cursors attached to this txn? if yes, fail
if (unlikely(refcounter > 0)) {
ups_trace(("Txn cannot be committed till all attached Cursors are closed"));
throw Exception(UPS_CURSOR_STILL_OPEN);
}
// this transaction is now committed!
flags |= kStateCommitted;
}
void
LocalTxn::abort()
{
// are cursors attached to this txn? if yes, fail
if (unlikely(refcounter > 0)) {
ups_trace(("Txn cannot be aborted till all attached Cursors are closed"));
throw Exception(UPS_CURSOR_STILL_OPEN);
}
// this transaction is now aborted!
flags |= kStateAborted;
// immediately release memory of the cached operations
free_operations();
}
void
LocalTxn::free_operations()
{
TxnOperation *n, *op = oldest_op;
while (op) {
n = op->next_in_txn;
TxnFactory::destroy_operation(op);
op = n;
}
oldest_op = 0;
newest_op = 0;
}
TxnIndex::TxnIndex(LocalDb *db)
: db(db)
{
rbt_new(this);
}
TxnIndex::~TxnIndex()
{
TxnNode *node;
while ((node = rbt_last(this))) {
remove(node);
delete node;
}
// re-initialize the tree
rbt_new(this);
}
TxnNode *
TxnIndex::get(ups_key_t *key, uint32_t flags)
{
TxnNode *node = 0;
int match = 0;
// create a temporary node that we can search for
TxnNode tmp(db, key);
// search if node already exists - if yes, return it
if (ISSET(flags, UPS_FIND_GEQ_MATCH)) {
node = rbt_nsearch(this, &tmp);
if (node)
match = compare(&tmp, node);
}
else if (ISSET(flags, UPS_FIND_LEQ_MATCH)) {
node = rbt_psearch(this, &tmp);
if (node)
match = compare(&tmp, node);
}
else if (ISSET(flags, UPS_FIND_GT_MATCH)) {
node = rbt_search(this, &tmp);
if (node)
node = node->next_sibling();
else
node = rbt_nsearch(this, &tmp);
match = 1;
}
else if (ISSET(flags, UPS_FIND_LT_MATCH)) {
node = rbt_search(this, &tmp);
if (node)
node = node->previous_sibling();
else
node = rbt_psearch(this, &tmp);
match = -1;
}
else
return rbt_search(this, &tmp);
// Nothing found?
if (!node)
return 0;
// approx. matching: set the key flag
if (match < 0)
ups_key_set_intflags(key, (ups_key_get_intflags(key)
& ~BtreeKey::kApproximate) | BtreeKey::kLower);
else if (match > 0)
ups_key_set_intflags(key, (ups_key_get_intflags(key)
& ~BtreeKey::kApproximate) | BtreeKey::kGreater);
return node;
}
TxnNode *
TxnIndex::first()
{
return rbt_first(this);
}
TxnNode *
TxnIndex::last()
{
return rbt_last(this);
}
void
TxnIndex::enumerate(Context *context, TxnIndex::Visitor *visitor)
{
TxnNode *node = rbt_first(this);
while (node) {
visitor->visit(context, node);
node = rbt_next(this, node);
}
}
struct KeyCounter : TxnIndex::Visitor {
KeyCounter(LocalDb *_db, LocalTxn *_txn, bool _distinct)
: counter(0), distinct(_distinct), txn(_txn), db(_db) {
}
void visit(Context *context, TxnNode *node) {
BtreeIndex *be = db->btree_index.get();
//
// look at each tree_node and walk through each operation
// in reverse chronological order (from newest to oldest):
// - is this op part of an aborted txn? then skip it
// - is this op part of a committed txn? then include it
// - is this op part of an txn which is still active? then include it
// - if a committed txn has erased the item then there's no need
// to continue checking older, committed txns of the same key
//
// !!
// if keys are overwritten or a duplicate key is inserted, then
// we have to consolidate the btree keys with the txn-tree keys.
//
for (TxnOperation *op = node->newest_op;
op != 0;
op = op->previous_in_node) {
LocalTxn *optxn = op->txn;
if (optxn->is_aborted())
continue;
if (optxn->is_committed() || txn == optxn) {
if (ISSET(op->flags, TxnOperation::kIsFlushed))
continue;
// if key was erased then it doesn't exist
if (ISSET(op->flags, TxnOperation::kErase)) {
counter--;
return;
}
if (ISSET(op->flags, TxnOperation::kInsert)) {
counter++;
return;
}
// key exists - include it
if (ISSET(op->flags, TxnOperation::kInsert)
|| (ISSET(op->flags, TxnOperation::kInsertOverwrite))) {
// check if the key already exists in the btree - if yes,
// we do not count it (it will be counted later)
if (UPS_KEY_NOT_FOUND
== be->find(context, 0, node->key(), 0, 0, 0, 0))
counter++;
return;
}
if (ISSET(op->flags, TxnOperation::kInsertDuplicate)) {
// check if btree has other duplicates
if (0 == be->find(context, 0, node->key(), 0, 0, 0, 0)) {
// yes, there's another one
if (distinct)
return;
counter++;
}
else {
// check if other key is in this node
counter++;
if (distinct)
return;
}
continue;
}
if (NOTSET(op->flags, TxnOperation::kNop)) {
assert(!"shouldn't be here");
return;
}
}
// txn is still active - ignore it
}
}
int64_t counter;
bool distinct;
LocalTxn *txn;
LocalDb *db;
};
uint64_t
TxnIndex::count(Context *context, LocalTxn *txn, bool distinct)
{
KeyCounter k(db, txn, distinct);
enumerate(context, &k);
return k.counter;
}
void
LocalTxnManager::begin(Txn *txn)
{
append_txn_at_tail(txn);
}
ups_status_t
LocalTxnManager::commit(Txn *htxn)
{
LocalTxn *txn = dynamic_cast<LocalTxn *>(htxn);
Context context(lenv(), txn, 0);
try {
txn->commit();
// if this transaction can NOT be flushed immediately then write its
// operations to the journal; otherwise skip this step
flush_transaction_to_journal(txn);
// flush committed transactions
if (likely(NOTSET(lenv()->flags(), UPS_DONT_FLUSH_TRANSACTIONS))) {
if (unlikely(ISSET(lenv()->flags(), UPS_FLUSH_TRANSACTIONS_IMMEDIATELY)
|| count_flushable_transactions(this)
>= Globals::ms_flush_threshold)) {
flush_committed_txns_impl(this, &context);
return 0;
}
}
}
catch (Exception &ex) {
return ex.code;
}
return 0;
}
ups_status_t
LocalTxnManager::abort(Txn *htxn)
{
LocalTxn *txn = dynamic_cast<LocalTxn *>(htxn);
Context context(lenv(), txn, 0);
try {
txn->abort();
// flush committed transactions
if (likely(NOTSET(lenv()->flags(), UPS_DONT_FLUSH_TRANSACTIONS))) {
if (unlikely(ISSET(lenv()->flags(), UPS_FLUSH_TRANSACTIONS_IMMEDIATELY)
|| count_flushable_transactions(this)
>= Globals::ms_flush_threshold)) {
flush_committed_txns_impl(this, &context);
return 0;
}
}
}
catch (Exception &ex) {
return ex.code;
}
return 0;
}
void
LocalTxnManager::flush_committed_txns(Context *context /* = 0 */)
{
if (!context) {
Context new_context(lenv(), 0, 0);
flush_committed_txns_impl(this, &new_context);
}
else
flush_committed_txns_impl(this, context);
}
uint64_t
LocalTxnManager::flush_txn_to_changeset(Context *context, LocalTxn *txn)
{
uint64_t highest_lsn = 0;
for (TxnOperation *op = txn->oldest_op;
op != 0;
op = op->next_in_txn) {
TxnNode *node = op->node;
// perform the actual operation in the btree
if (NOTSET(op->flags, TxnOperation::kIsFlushed))
node->db->flush_txn_operation(context, txn, op);
assert(op->lsn > highest_lsn);
highest_lsn = op->lsn;
}
return highest_lsn;
}
} // namespace upscaledb
| 24.635401 | 80 | 0.626873 | cflaviu |
1d2d72f6e0343e754981f03119ee091631eba3cd | 269 | cpp | C++ | shared/scene.cpp | industry-advance/nin10kit | dbf81c62c0fa2f544cfd22b1f7d008a885c2b589 | [
"Apache-2.0"
] | 45 | 2015-03-26T17:14:55.000Z | 2022-03-29T20:27:32.000Z | shared/scene.cpp | industry-advance/nin10kit | dbf81c62c0fa2f544cfd22b1f7d008a885c2b589 | [
"Apache-2.0"
] | 35 | 2015-01-06T16:16:37.000Z | 2021-06-19T05:03:13.000Z | shared/scene.cpp | industry-advance/nin10kit | dbf81c62c0fa2f544cfd22b1f7d008a885c2b589 | [
"Apache-2.0"
] | 5 | 2017-03-26T04:48:02.000Z | 2020-07-10T22:55:49.000Z | #include "scene.hpp"
void Scene::WriteData(std::ostream& file) const
{
for (const auto& image : images)
image->WriteData(file);
}
void Scene::WriteExport(std::ostream& file) const
{
for (const auto& image : images)
image->WriteExport(file);
}
| 19.214286 | 49 | 0.650558 | industry-advance |
1d2f0fce6e5ff379b5038ce73c4eb0149c51bfb7 | 6,601 | cpp | C++ | tests/main.cpp | lukka/yagbe | 8f66d55f455e8a13db84cd521eabb498a1165f44 | [
"MIT"
] | 1 | 2018-06-10T14:45:53.000Z | 2018-06-10T14:45:53.000Z | tests/main.cpp | Kaosumaru/yagbe | 13a2dea9dd50ae4b548bec3704fdc88c2a48d956 | [
"MIT"
] | 1 | 2020-02-16T02:50:36.000Z | 2020-02-24T20:50:38.000Z | tests/main.cpp | lukka/yagbe | 8f66d55f455e8a13db84cd521eabb498a1165f44 | [
"MIT"
] | 1 | 2020-02-16T00:36:38.000Z | 2020-02-16T00:36:38.000Z | #include <iostream>
#include <stdexcept>
#include "vm/context.hpp"
#include "vm/instructions.hpp"
#include "vm/instructions_map.hpp"
#ifndef _MSC_VER
#define lest_FEATURE_COLOURISE 1
#endif
#include "lest.hpp"
using namespace std;
using namespace yagbe;
using namespace yagbe::instructions;
using namespace yagbe::instructions::automap;
bool test_opus5()
{
std::string path = YAGBE_ROMS;
path += "../test_roms/opus5.gb";
context c;
if (!c.load_rom(path))
return false;
int steps = 100;
for (int i = 0; i < steps; i++)
{
c.cpu_step();
//endian...
if (c.registers.pc == 0x017E)
break;
}
if (c.registers.pc != 0x017E)
return false;
bool s = true;
auto m = [&](uint16_t a) { return c.memory.raw_at(a); };
s &= m(0xFFFF) == 0x01;
s &= m(0xFF41) == 0x00;
s &= m(0xFF40) == 0x00;
s &= m(0xFF43) == 0x10;
s &= m(0xC1C9) == 0x10; s &= m(0xE1C9) == 0x10; //shadow RAM
s &= m(0xC1CC) == 0x10; s &= m(0xE1CC) == 0x10;
s &= m(0xFF42) == 0x08;
s &= m(0xC1CB) == 0x08; s &= m(0xE1CB) == 0x08;
s &= m(0xC1CD) == 0x08; s &= m(0xE1CD) == 0x08;
s &= m(0xC1C8) == 0x00; s &= m(0xE1C8) == 0x00;
s &= m(0xC1CA) == 0x00; s &= m(0xE1CA) == 0x00;
s &= m(0xC0A0) == 0x00; s &= m(0xE0A0) == 0x00;
//endian...
s &= c.registers.bc == 0x4000;
return true;
}
const lest::test specification[] =
{
CASE("01-special-5")
{
context ctx;
ctx.registers.bc = 0x1200;
do
{
PUSH<BC>::execute(ctx); static_assert(&(instruction<0xC5>::execute) == &(PUSH<BC>::execute), "Wrong mapping");
POP<AF>::execute(ctx); static_assert(&(instruction<0xF1>::execute) == &(POP<AF>::execute), "Wrong mapping");
PUSH<AF>::execute(ctx); static_assert(&(instruction<0xF5>::execute) == &(PUSH<AF>::execute), "Wrong mapping");
POP<DE>::execute(ctx); static_assert(&(instruction<0xD1>::execute) == &(POP<DE>::execute), "Wrong mapping");
LD<A, C>::execute(ctx); static_assert(&(instruction<0x79>::execute) == &(LD<A, C>::execute), "Wrong mapping");
ctx.registers.a &= 0xF0;
CP<E>::execute(ctx); static_assert(&(instruction<0xBB>::execute) == &(CP<E>::execute), "Wrong mapping");
bool condition = (bool)ctx.flags.z == true;
EXPECT(condition);
INC<B>::execute(ctx);
INC<C>::execute(ctx);
} while (!ctx.flags.z);
},
CASE("ROM")
{
context ctx;
ctx.memory.raw_at(0) = 1;
ctx.memory.at(0) = 2;
EXPECT(ctx.memory.at(0) == 1);
},
CASE("SHADOW RAM")
{
context ctx;
for (uint16_t i = 0xC000; i <= 0xDFFF; i++)
ctx.memory.at(i) = i % 256;
for (uint16_t i = 0xE000; i <= 0xFDFF; i++)
EXPECT(ctx.memory.read_at(i) == ctx.memory.read_at(i - 0x2000));
},
CASE("OPUS5")
{
EXPECT(test_opus5());
},
CASE("INC")
{
context ctx;
{
ctx.registers.b = 1;
ctx.registers.c = 2;
using inc_bc = INC<BC>;
inc_bc::execute(ctx);
EXPECT(ctx.registers.b == 1);
EXPECT(ctx.registers.c == 3);
}
},
CASE("LD")
{
context ctx;
//LD B,A
{
ctx.registers.a = 1;
ctx.registers.b = 2;
using ld_b_a = LD<B, A>;
ld_b_a::execute(ctx);
EXPECT(ctx.registers.b == 1);
EXPECT(ctx.registers.b == ctx.registers.a);
EXPECT(ld_b_a::size() == 1);
EXPECT(ld_b_a::cycles() == 4);
}
//LD B,(HL)
{
using ld_b_hl = LD<B, HL_pointer>;
EXPECT(ld_b_hl::cycles() == 8);
}
//LD BC,d16
{
using ld_bc_d16 = LD<BC, d16>;
ctx.registers.pc = 0;
ctx.memory.raw_at(0) = 6;
ctx.memory.raw_at(1) = 0;
ld_bc_d16::execute(ctx);
EXPECT(ctx.registers.bc == 6);
EXPECT(ld_bc_d16::cycles() == 12);
}
//LD (HLI)/(HLD),A
{
using ld_hli_a = LD<HLI, A>;
using ld_hld_a = LD<HLD, A>;
ctx.memory.raw_at(0xC000) = 6;
ctx.memory.raw_at(0xC001) = 6;
ctx.registers.a = 5;
ctx.registers.hl = 0xC000;
ld_hli_a::execute(ctx);
EXPECT(ctx.registers.hl == 0xC001);
EXPECT(ctx.memory.at(0xC000) == 5);
EXPECT(ctx.memory.at(0xE000) == 5); //shadow
ctx.registers.a = 1;
ld_hld_a::execute(ctx);
EXPECT(ctx.registers.hl == 0xC000);
EXPECT(ctx.memory.at(0xC001) == 1);
EXPECT(ctx.memory.at(0xE001) == 1); //shadow
EXPECT(ld_hli_a::cycles() == 8);
EXPECT(ld_hld_a::cycles() == 8);
}
//LD<HL, SP_p_r8> //TODO seems like this sets h & c - good test case
},
CASE("JP")
{
context ctx;
//JP d16
{
using jp_d16 = JP<condition::_, d16>;
ctx.registers.pc = 0;
ctx.memory.raw_at(0) = 6;
ctx.memory.raw_at(1) = 0;
auto cycles = jp_d16::execute(ctx);
EXPECT(ctx.registers.pc == 6);
EXPECT(cycles == 16);
}
//JP (HL)
{
using jp_HL = JP<condition::_, HL>;
ctx.registers.pc = 0;
ctx.registers.hl = 6;
auto cycles = jp_HL::execute(ctx);
EXPECT(ctx.registers.pc == 6);
EXPECT(cycles == 4);
}
//JP NC,d16
{
using JP_NC_HL = instructions::JP<condition::NC, d16>;
{
ctx.registers.pc = 0;
ctx.memory.raw_at(0) = 6;
ctx.memory.raw_at(1) = 0;
ctx.flags.c = 1;
auto cycles = JP_NC_HL::execute(ctx);
EXPECT(ctx.registers.pc == 2);
EXPECT(cycles == 12);
}
{
ctx.registers.pc = 0;
ctx.memory.raw_at(0) = 6;
ctx.memory.raw_at(1) = 0;
ctx.flags.c = 0;
auto cycles = JP_NC_HL::execute(ctx);
EXPECT(ctx.registers.pc == 6);
EXPECT(cycles == 16);
}
}
//JP NZ,d16
{
using JP_NZ_HL = instructions::JP<condition::NZ, d16>;
{
ctx.registers.pc = 0;
ctx.memory.raw_at(0) = 6;
ctx.memory.raw_at(1) = 0;
ctx.flags.z = 1;
auto cycles = JP_NZ_HL::execute(ctx);
EXPECT(ctx.registers.pc == 2);
EXPECT(cycles == 12);
}
{
ctx.registers.pc = 0;
ctx.memory.raw_at(0) = 6;
ctx.memory.raw_at(1) = 0;
ctx.flags.z = 0;
auto cycles = JP_NZ_HL::execute(ctx);
EXPECT(ctx.registers.pc == 6);
EXPECT(cycles == 16);
}
}
},
CASE("JR")
{
context ctx;
//JR r8
{
using JR_D8 = JR<condition::_, r8>;
ctx.registers.pc = 0;
ctx.memory.raw_at(0) = 6;
auto cycles = JR_D8::execute(ctx);
EXPECT(ctx.registers.pc == 7);
EXPECT(cycles == 12);
}
//JR NC,r8
{
using JR_NC_D8 = instructions::JR<condition::NC, r8>;
{
ctx.registers.pc = 0;
ctx.memory.raw_at(0) = 6;
ctx.flags.c = 1;
auto cycles = JR_NC_D8::execute(ctx);
EXPECT(ctx.registers.pc == 1);
EXPECT(cycles == 8);
}
{
ctx.registers.pc = 0;
ctx.memory.raw_at(0) = 6;
ctx.flags.c = 0;
auto cycles = JR_NC_D8::execute(ctx);
EXPECT(ctx.registers.pc == 7);
EXPECT(cycles == 12);
}
}
}
};
int main (int argc, char * argv[])
{
return lest::run(specification, argc, argv);
}
| 18.542135 | 118 | 0.5787 | lukka |
1d33ff8649bbd88b5afe5b268068ceec416cece4 | 7,936 | cc | C++ | examples/external/OpenMesh/include/OpenMesh/Tools/Smoother/JacobiLaplaceSmootherT.cc | zhangxaochen/Opt | 7f1af802bfc84cc9ef1adb9facbe4957078f529a | [
"MIT"
] | 260 | 2017-03-02T19:57:51.000Z | 2022-01-21T03:52:03.000Z | examples/external/OpenMesh/include/OpenMesh/Tools/Smoother/JacobiLaplaceSmootherT.cc | zhangxaochen/Opt | 7f1af802bfc84cc9ef1adb9facbe4957078f529a | [
"MIT"
] | 102 | 2017-03-03T00:42:56.000Z | 2022-03-30T14:15:20.000Z | examples/external/OpenMesh/include/OpenMesh/Tools/Smoother/JacobiLaplaceSmootherT.cc | zhangxaochen/Opt | 7f1af802bfc84cc9ef1adb9facbe4957078f529a | [
"MIT"
] | 71 | 2017-03-02T20:22:33.000Z | 2022-01-02T03:49:04.000Z | /* ========================================================================= *
* *
* OpenMesh *
* Copyright (c) 2001-2015, RWTH-Aachen University *
* Department of Computer Graphics and Multimedia *
* All rights reserved. *
* www.openmesh.org *
* *
*---------------------------------------------------------------------------*
* This file is part of OpenMesh. *
*---------------------------------------------------------------------------*
* *
* Redistribution and use in source and binary forms, with or without *
* modification, are permitted provided that the following conditions *
* are met: *
* *
* 1. Redistributions of source code must retain the above copyright notice, *
* this list of conditions and the following disclaimer. *
* *
* 2. Redistributions in binary form must reproduce the above copyright *
* notice, this list of conditions and the following disclaimer in the *
* documentation and/or other materials provided with the distribution. *
* *
* 3. Neither the name of the copyright holder nor the names of its *
* contributors may be used to endorse or promote products derived from *
* this software without specific prior written permission. *
* *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS *
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED *
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A *
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER *
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, *
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, *
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR *
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF *
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING *
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS *
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *
* *
* ========================================================================= */
/*===========================================================================*\
* *
* $Revision$ *
* $Date$ *
* *
\*===========================================================================*/
/** \file JacobiLaplaceSmootherT.cc
*/
//=============================================================================
//
// CLASS JacobiLaplaceSmootherT - IMPLEMENTATION
//
//=============================================================================
#define OPENMESH_JACOBI_LAPLACE_SMOOTHERT_C
//== INCLUDES =================================================================
#include <OpenMesh/Tools/Smoother/JacobiLaplaceSmootherT.hh>
//== NAMESPACES ===============================================================
namespace OpenMesh {
namespace Smoother {
//== IMPLEMENTATION ==========================================================
template <class Mesh>
void
JacobiLaplaceSmootherT<Mesh>::
smooth(unsigned int _n)
{
if (Base::continuity() > Base::C0)
{
Base::mesh_.add_property(umbrellas_);
if (Base::continuity() > Base::C1)
Base::mesh_.add_property(squared_umbrellas_);
}
LaplaceSmootherT<Mesh>::smooth(_n);
if (Base::continuity() > Base::C0)
{
Base::mesh_.remove_property(umbrellas_);
if (Base::continuity() > Base::C1)
Base::mesh_.remove_property(squared_umbrellas_);
}
}
//-----------------------------------------------------------------------------
template <class Mesh>
void
JacobiLaplaceSmootherT<Mesh>::
compute_new_positions_C0()
{
typename Mesh::VertexIter v_it, v_end(Base::mesh_.vertices_end());
typename Mesh::ConstVertexOHalfedgeIter voh_it;
typename Mesh::Normal u, p, zero(0,0,0);
typename Mesh::Scalar w;
for (v_it=Base::mesh_.vertices_begin(); v_it!=v_end; ++v_it)
{
if (this->is_active(*v_it))
{
// compute umbrella
u = zero;
for (voh_it = Base::mesh_.cvoh_iter(*v_it); voh_it.is_valid(); ++voh_it) {
w = this->weight(Base::mesh_.edge_handle(*voh_it));
u += vector_cast<typename Mesh::Normal>(Base::mesh_.point(Base::mesh_.to_vertex_handle(*voh_it))) * w;
}
u *= this->weight(*v_it);
u -= vector_cast<typename Mesh::Normal>(Base::mesh_.point(*v_it));
// damping
u *= 0.5;
// store new position
p = vector_cast<typename Mesh::Normal>(Base::mesh_.point(*v_it));
p += u;
this->set_new_position(*v_it, p);
}
}
}
//-----------------------------------------------------------------------------
template <class Mesh>
void
JacobiLaplaceSmootherT<Mesh>::
compute_new_positions_C1()
{
typename Mesh::VertexIter v_it, v_end(Base::mesh_.vertices_end());
typename Mesh::ConstVertexOHalfedgeIter voh_it;
typename Mesh::Normal u, uu, p, zero(0,0,0);
typename Mesh::Scalar w, diag;
// 1st pass: compute umbrellas
for (v_it=Base::mesh_.vertices_begin(); v_it!=v_end; ++v_it)
{
u = zero;
for (voh_it = Base::mesh_.cvoh_iter(*v_it); voh_it.is_valid(); ++voh_it) {
w = this->weight(Base::mesh_.edge_handle(*voh_it));
u -= vector_cast<typename Mesh::Normal>(Base::mesh_.point(Base::mesh_.to_vertex_handle(*voh_it)))*w;
}
u *= this->weight(*v_it);
u += vector_cast<typename Mesh::Normal>(Base::mesh_.point(*v_it));
Base::mesh_.property(umbrellas_, *v_it) = u;
}
// 2nd pass: compute updates
for (v_it=Base::mesh_.vertices_begin(); v_it!=v_end; ++v_it)
{
if (this->is_active(*v_it))
{
uu = zero;
diag = 0.0;
for (voh_it = Base::mesh_.cvoh_iter(*v_it); voh_it.is_valid(); ++voh_it) {
w = this->weight(Base::mesh_.edge_handle(*voh_it));
uu -= Base::mesh_.property(umbrellas_, Base::mesh_.to_vertex_handle(*voh_it));
diag += (w * this->weight(Base::mesh_.to_vertex_handle(*voh_it)) + static_cast<typename Mesh::Scalar>(1.0) ) * w;
}
uu *= this->weight(*v_it);
diag *= this->weight(*v_it);
uu += Base::mesh_.property(umbrellas_, *v_it);
if (diag) uu *= static_cast<typename Mesh::Scalar>(1.0) / diag;
// damping
uu *= 0.25;
// store new position
p = vector_cast<typename Mesh::Normal>(Base::mesh_.point(*v_it));
p -= uu;
this->set_new_position(*v_it, p);
}
}
}
//=============================================================================
} // namespace Smoother
} // namespace OpenMesh
//=============================================================================
| 39.879397 | 121 | 0.455771 | zhangxaochen |
1d35be5672c49d86924c7d34911e267133d8ba20 | 1,327 | hpp | C++ | src/3rd party/boost/boost/preprocessor/facilities/is_empty_or_1.hpp | OLR-xray/OLR-3.0 | b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611 | [
"Apache-2.0"
] | 8 | 2016-01-25T20:18:51.000Z | 2019-03-06T07:00:04.000Z | src/3rd party/boost/boost/preprocessor/facilities/is_empty_or_1.hpp | OLR-xray/OLR-3.0 | b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611 | [
"Apache-2.0"
] | null | null | null | src/3rd party/boost/boost/preprocessor/facilities/is_empty_or_1.hpp | OLR-xray/OLR-3.0 | b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611 | [
"Apache-2.0"
] | 3 | 2016-02-14T01:20:43.000Z | 2021-02-03T11:19:11.000Z | # /* **************************************************************************
# * *
# * (C) Copyright Paul Mensonides 2003. Permission to copy, use, *
# * modify, sell, and distribute this software is granted provided *
# * this copyright notice appears in all copies. This software is *
# * provided "as is" without express or implied warranty, and with *
# * no claim at to its suitability for any purpose. *
# * *
# ************************************************************************** */
#
# /* See http://www.boost.org for most recent version. */
#
# ifndef BOOST_PREPROCESSOR_FACILITIES_IS_EMPTY_OR_1_HPP
# define BOOST_PREPROCESSOR_FACILITIES_IS_EMPTY_OR_1_HPP
#
# include <boost/preprocessor/control/iif.hpp>
# include <boost/preprocessor/facilities/empty.hpp>
# include <boost/preprocessor/facilities/is_1.hpp>
# include <boost/preprocessor/facilities/is_empty.hpp>
#
# /* BOOST_PP_IS_EMPTY_OR_1 */
#
# define BOOST_PP_IS_EMPTY_OR_1(x) \
BOOST_PP_IIF( \
BOOST_PP_IS_EMPTY(x BOOST_PP_EMPTY()), \
1 BOOST_PP_EMPTY, \
BOOST_PP_IS_1 \
)(x) \
/**/
#
# endif
| 41.46875 | 80 | 0.50942 | OLR-xray |
1d386eab0ba517deef2b5b0fc69d05e864e12f08 | 4,035 | cpp | C++ | src_ana/bdcs_effs.cpp | serjinio/thesis_ana | 633a61dee56cf2cf4dcb67997ac87338537fb578 | [
"MIT"
] | null | null | null | src_ana/bdcs_effs.cpp | serjinio/thesis_ana | 633a61dee56cf2cf4dcb67997ac87338537fb578 | [
"MIT"
] | null | null | null | src_ana/bdcs_effs.cpp | serjinio/thesis_ana | 633a61dee56cf2cf4dcb67997ac87338537fb578 | [
"MIT"
] | null | null | null |
#include <fstream>
#include "TROOT.h"
#include "cli.hpp"
#include "init_ds.hpp"
#include "consts.hpp"
#include "csalg.hpp"
#include "drawing.hpp"
#include "scattyield.hpp"
#include "treewalk.hpp"
#include "cuts_conf.hpp"
#include "rootscript.hpp"
static s13::misc::CliOptions cli_opts;
using ElaCuts = s13::ana::ElasticScatteringCuts;
using Evt = s13::ana::ScatteringEvent;
class BdcsEffsAlg : public s13::ana::SimpleTTreeAlgorithmBase {
public:
BdcsEffsAlg(const ElaCuts& cuts) :
logger_{"BdcsEffsAlg"}, cuts_{cuts} {
init();
}
virtual void process_event(Evt& evt) {
if (cuts_.IsSignalEvent(evt)) {
compute_bdcs_effs(evt);
}
}
virtual void finalize() {
double bdc1_eff = bdcs_eff_hits_[0] / (double)bdcs_ref_hits_[1] * 100;
double bdc2_eff = bdcs_eff_hits_[1] / (double)bdcs_ref_hits_[0] * 100;
logger_.info("Total number of events: %d", total_events_);
logger_.info("BDC1 in pos. cut hits: %d", bdcs_ref_hits_[0]);
logger_.info("BDC2 in pos. cut hits: %d", bdcs_ref_hits_[1]);
logger_.info("BDC2*BDC1 hits: %d", bdcs_eff_hits_[0]);
logger_.info("BDC1*BDC2 hits: %d", bdcs_eff_hits_[1]);
logger_.info("BDC1 efficiency: %.1f%%", bdc1_eff);
logger_.info("BDC2 efficiency: %.1f%%", bdc2_eff);
double bdc1_eff_to_sbt = sbt_bdc1_hits_ / (double)sbt_hits_ * 100;
logger_.info("\nBDC1 efficiency relative to SBT:");
logger_.info("\tSBT hits: %d", sbt_hits_);
logger_.info("\tSBT*BDC1 hits: %d", sbt_bdc1_hits_);
logger_.info("\tBDC1 efficiency: %.1f%%", bdc1_eff_to_sbt);
}
ElaCuts cuts() {
return cuts_;
}
private:
void init() {
// auto th1 = &s13::ana::make_th1;
bdcs_ref_hits_ = { { 0, 0 } };
bdcs_eff_hits_ = { { 0, 0 } };
}
bool is_bdc1_pos_cut(Evt& evt) {
double evt_r = std::sqrt(std::pow(evt.bdc1_xpos, 2) + std::pow(evt.bdc1_ypos, 2));
if (evt_r < 1) {
return true;
}
return false;
}
bool is_bdc2_pos_cut(Evt& evt) {
double evt_r = std::sqrt(std::pow(evt.bdc2_xpos, 2) + std::pow(evt.bdc2_ypos, 2));
if (evt_r < 1) {
return true;
}
return false;
}
bool is_bdc1_hit(Evt& evt) {
if (is_well_defined(evt.bdc1_xpos) && is_well_defined(evt.bdc1_ypos)) {
return true;
}
return false;
}
bool is_bdc2_hit(Evt& evt) {
if (is_well_defined(evt.bdc2_xpos) && is_well_defined(evt.bdc2_ypos)) {
return true;
}
return false;
}
bool is_sbt_hit(Evt& evt) {
return true;
}
void compute_bdcs_effs(Evt& evt) {
total_events_ += 1;
if (is_bdc1_pos_cut(evt)) {
++bdcs_ref_hits_[0];
if (is_bdc2_hit(evt)) {
++bdcs_eff_hits_[1];
}
}
if (is_bdc2_pos_cut(evt)) {
++bdcs_ref_hits_[1];
if (is_bdc1_hit(evt)) {
++bdcs_eff_hits_[0];
}
}
if (is_sbt_hit(evt)) {
++sbt_hits_;
if (is_bdc1_hit(evt)) {
++sbt_bdc1_hits_;
}
}
}
s13::misc::MessageLogger logger_;
ElaCuts cuts_;
int total_events_ = 0;
int sbt_hits_ = 0;
int sbt_bdc1_hits_ = 0;
std::array<int, 2> bdcs_ref_hits_;
std::array<int, 2> bdcs_eff_hits_;
};
void draw_bdcs_effs(s13::ana::RootScript& script, std::shared_ptr<BdcsEffsAlg> alg) {
script.NewPage(1).cd();
}
void bdcs_effs() {
auto cuts = s13::io::parse_cuts_config(std::fstream(cli_opts.cuts_config()));
auto alg =
s13::ana::walk_alg<BdcsEffsAlg>(cuts,
init_dataset_from_cli(cli_opts),
cli_opts.use_mt());
s13::ana::RootScript script("bdcs_effs");
gStyle->SetOptStat(1111111);
// gStyle->SetOptFit();
draw_bdcs_effs(script, alg);
}
int main(int argc, char** argv) {
s13::misc::MessageLogger log("main()");
gROOT->SetStyle("Modern");
TThread::Initialize();
cli_opts.require_cuts_conf_opt(true);
try {
cli_opts.parse_options(argc, argv);
} catch (std::exception& ex) {
log.error("Invalid argument provided: %s", ex.what());
return -1;
}
bdcs_effs();
}
| 23.596491 | 86 | 0.626022 | serjinio |
1d3d2b5203ebfcf3410a21301102296d397ec443 | 1,014 | hpp | C++ | include/kip/xml/qname.hpp | kei10in/kip | 23d83ffa4f40431ef8bd6983e928ae889bfc3872 | [
"MIT"
] | null | null | null | include/kip/xml/qname.hpp | kei10in/kip | 23d83ffa4f40431ef8bd6983e928ae889bfc3872 | [
"MIT"
] | null | null | null | include/kip/xml/qname.hpp | kei10in/kip | 23d83ffa4f40431ef8bd6983e928ae889bfc3872 | [
"MIT"
] | null | null | null | #ifndef KIP_XML_QNAME_HPP_
#define KIP_XML_QNAME_HPP_
#include <string>
#include "kip/hash-combine.hpp"
namespace kip {
namespace xml {
struct qname {
std::string name;
std::string url;
qname() {}
qname(std::string const& name, std::string const& url)
: name(name)
, url(url)
{}
bool empty() const {
return name.empty() && url.empty();
}
size_t hash() const {
size_t h = 0;
hash_combine(h, name);
hash_combine(h, url);
return h;
}
};
inline bool operator==(qname const& lhs, qname const& rhs) {
return lhs.name == rhs.name &&
lhs.url == rhs.url;
}
inline bool operator!=(qname const& lhs, qname const& rhs) {
return !(lhs == rhs);
}
} // namespace qname
} // namespace pst
namespace std {
template <>
struct hash<kip::xml::qname> {
using result_type = size_t;
using argument_type = kip::xml::qname;
size_t operator()(kip::xml::qname const& v) const {
return v.hash();
}
};
} // namespace std
#endif // KIP_XML_QNAME_HPP_
| 16.095238 | 60 | 0.627219 | kei10in |
1d3e23ead9343bebdf8cf053fe8fbe0baa32ce5b | 11,725 | cpp | C++ | samples/threat_level/src/PlayerWeaponsSystem.cpp | fallahn/crogine | f6cf3ade1f4e5de610d52e562bf43e852344bca0 | [
"FTL",
"Zlib"
] | 41 | 2017-08-29T12:14:36.000Z | 2022-02-04T23:49:48.000Z | samples/threat_level/src/PlayerWeaponsSystem.cpp | fallahn/crogine | f6cf3ade1f4e5de610d52e562bf43e852344bca0 | [
"FTL",
"Zlib"
] | 11 | 2017-09-02T15:32:45.000Z | 2021-12-27T13:34:56.000Z | samples/threat_level/src/PlayerWeaponsSystem.cpp | fallahn/crogine | f6cf3ade1f4e5de610d52e562bf43e852344bca0 | [
"FTL",
"Zlib"
] | 5 | 2020-01-25T17:51:45.000Z | 2022-03-01T05:20:30.000Z | /*-----------------------------------------------------------------------
Matt Marchant 2017
http://trederia.blogspot.com
crogine test application - Zlib license.
This software is provided 'as-is', without any express or
implied warranty.In no event will the authors be held
liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute
it freely, subject to the following restrictions :
1. The origin of this software must not be misrepresented;
you must not claim that you wrote the original software.
If you use this software in a product, an acknowledgment
in the product documentation would be appreciated but
is not required.
2. Altered source versions must be plainly marked as such,
and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any
source distribution.
-----------------------------------------------------------------------*/
#include "PlayerWeaponsSystem.hpp"
#include "ItemSystem.hpp"
#include "Messages.hpp"
#include "ResourceIDs.hpp"
#include "PhysicsObject.hpp"
#include <crogine/core/App.hpp>
#include <crogine/core/Clock.hpp>
#include <crogine/ecs/components/Transform.hpp>
#include <crogine/ecs/components/Sprite.hpp>
#include <crogine/ecs/Scene.hpp>
namespace
{
const float pulseMoveSpeed = 18.f;
constexpr float pulseFireRate = 0.2f;
constexpr float pulseDoubleFireRate = pulseFireRate / 2.f;
constexpr float pulseTripleFireRate = pulseFireRate / 3.f;
const float pulseOffset = 0.6f;
const float pulseDamageSingle = 5.f;
const float pulseDamageDouble = 2.5f;
const float pulseDamageTriple = 1.2f;
const float laserDamage = 0.4f;
const float buddyDamage = 5.f;
const float laserRate = 0.025f;
const float weaponDowngradeTime = 5.f;
const glm::vec3 idlePos(-100.f); //be careful with this. When setting inactive actors to the same postion they cause collisions off screen
}
PlayerWeaponSystem::PlayerWeaponSystem(cro::MessageBus& mb)
: cro::System (mb, typeid(PlayerWeaponSystem)),
m_systemActive (false),
m_allowFiring (false),
m_fireMode (FireMode::Single),
m_fireTime (pulseFireRate),
m_weaponDowngradeTime (0.f),
m_playerID (0),
m_aliveCount (0),
m_deadPulseCount (0),
m_deadLaserCount (0)
{
requireComponent<PlayerWeapon>();
requireComponent<cro::Transform>();
requireComponent<cro::PhysicsObject>();
}
//public
void PlayerWeaponSystem::process(float dt)
{
//DPRINT("Dead Pulse", std::to_string(m_deadPulseCount));
//DPRINT("Alive Pulse", std::to_string(m_aliveCount));
//DPRINT("Fire Time", std::to_string(m_fireTime));
//DPRINT("Laser cooldown", std::to_string(m_laserCooldownTime));
m_fireTime += dt;
auto spawnPulse = [&](glm::vec3 position, float damage)
{
m_deadPulseCount--;
m_aliveList[m_aliveCount] = m_deadPulses[m_deadPulseCount];
auto entity = getScene()->getEntity(m_aliveList[m_aliveCount]);
entity.getComponent<cro::Transform>().setPosition(position);
entity.getComponent<PlayerWeapon>().damage = damage;
m_aliveCount++;
auto* msg = postMessage<PlayerEvent>(MessageID::PlayerMessage);
msg->position = position;
msg->type = PlayerEvent::FiredLaser;
};
//if active spawn more pulses or activate laser
if (m_systemActive)
{
switch (m_fireMode)
{
default:
case FireMode::Single:
if (m_fireTime > pulseFireRate
&& m_deadPulseCount > 0)
{
spawnPulse(m_playerPosition, pulseDamageSingle);
m_fireTime = 0.f;
}
break;
case FireMode::Double:
if (m_fireTime > pulseDoubleFireRate
&& m_deadPulseCount > 0)
{
static std::int32_t side = 0;
glm::vec3 offset = glm::vec3(0.f);
offset.z = (side) ? -pulseOffset : pulseOffset;
offset = getScene()->getEntity(m_playerID).getComponent<cro::Transform>().getWorldTransform() * glm::vec4(offset, 1.f);
spawnPulse(offset, pulseDamageDouble);
side = (side + 1) % 2;
m_fireTime = 0.f;
}
break;
case FireMode::Triple:
if (m_fireTime > pulseTripleFireRate
&& m_deadPulseCount > 0)
{
static std::int32_t side = 0;
glm::vec3 offset = glm::vec3(0.f);
offset.z = -pulseOffset + (pulseOffset * side);
offset = getScene()->getEntity(m_playerID).getComponent<cro::Transform>().getWorldTransform() * glm::vec4(offset, 1.f);
spawnPulse(offset, pulseDamageTriple);
side = (side + 1) % 3;
m_fireTime = 0.f;
}
break;
case FireMode::Laser:
if (m_deadLaserCount > 0)
{
m_deadLaserCount--;
m_aliveList[m_aliveCount] = m_deadLasers[m_deadLaserCount];
auto laserEnt = getScene()->getEntity(m_aliveList[m_aliveCount]);
laserEnt.getComponent<cro::Transform>().setPosition(glm::vec3(0.f, -0.1f, 0.f));
laserEnt.getComponent<cro::Transform>().setScale(glm::vec3(1.f));
m_aliveCount++;
}
break;
}
}
//downgrade weapon over time
if (m_fireMode > FireMode::Single)
{
m_weaponDowngradeTime -= dt;
if (m_weaponDowngradeTime < 0)
{
m_weaponDowngradeTime = weaponDowngradeTime;
m_fireMode = static_cast<FireMode>(m_fireMode - 1);
}
auto* msg = postMessage<WeaponEvent>(MessageID::WeaponMessage);
msg->downgradeTime = weaponDowngradeTime - m_weaponDowngradeTime;
msg->fireMode = m_fireMode;
}
//update alive
for (auto i = 0u; i < m_aliveCount; ++i)
{
auto e = getScene()->getEntity(m_aliveList[i]);
auto& weaponData = e.getComponent<PlayerWeapon>();
if (weaponData.type == PlayerWeapon::Type::Pulse)
{
//update position
e.getComponent<cro::Transform>().move({ dt * pulseMoveSpeed, 0.f, 0.f });
//handle collision with NPCs or end of map
const auto& collision = e.getComponent<cro::PhysicsObject>();
auto count = collision.getCollisionCount();
//const auto& IDs = collision.getCollisionIDs();
for (auto j = 0u; j < count; ++j)
{
//other entities handle their own reaction - we just want to reset the pulse
e.getComponent<cro::Transform>().setPosition(idlePos);
//move to dead list
m_deadPulses[m_deadPulseCount] = m_aliveList[i];
m_deadPulseCount++;
//and remove from alive list
m_aliveCount--;
m_aliveList[i] = m_aliveList[m_aliveCount];
i--; //decrement so the newly inserted ID doesn't get skipped, and we can be sure we're still < m_aliveCount
count = 0; //only want to handle one collision at most, else we might kill this ent more than once
}
}
else //laser is firing
{
static float laserTime = 0.f;
laserTime += dt;
if (laserTime > laserRate)
{
//animates the laser beam
auto scale = e.getComponent<cro::Transform>().getScale();
scale.y = scale.y < 1 ? 1.3f : 0.25f;
e.getComponent<cro::Transform>().setScale(scale);
laserTime = 0.f;
}
if (m_fireMode != FireMode::Laser || !m_systemActive)
{
//remove from alive list
e.getComponent<cro::Transform>().setPosition(idlePos);
e.getComponent<cro::Transform>().setScale(glm::vec3(0.f));
//move to dead list
m_deadLasers[m_deadLaserCount] = m_aliveList[i];
m_deadLaserCount++;
//and remove from alive list
m_aliveCount--;
m_aliveList[i] = m_aliveList[m_aliveCount];
i--;
}
}
}
}
void PlayerWeaponSystem::handleMessage(const cro::Message& msg)
{
if (msg.id == MessageID::PlayerMessage)
{
const auto& data = msg.getData<PlayerEvent>();
switch (data.type)
{
case PlayerEvent::Died:
m_fireMode = FireMode::Single;
m_systemActive = false;
m_allowFiring = false;
{
auto* msg = postMessage<WeaponEvent>(MessageID::WeaponMessage);
msg->downgradeTime = 0.f;
msg->fireMode = m_fireMode;
}
break;
case PlayerEvent::Moved:
m_playerPosition = data.position;
m_playerID = data.entityID;
break;
case PlayerEvent::Spawned:
m_allowFiring = true;
LOG("Enabled weapon", cro::Logger::Type::Info);
break;
case PlayerEvent::WeaponStateChange:
m_systemActive = (data.weaponActivated && m_allowFiring);
if (!data.weaponActivated)
{
m_fireTime = pulseFireRate;
}
break;
case PlayerEvent::CollectedItem:
if (data.itemID == CollectableItem::WeaponUpgrade)
{
m_weaponDowngradeTime = weaponDowngradeTime;
//HAH wtf?
if (m_fireMode < FireMode::Laser)
{
m_fireMode = static_cast<FireMode>(m_fireMode + 1);
}
}
break;
default: break;
}
}
else if (msg.id == MessageID::BuddyMessage)
{
const auto& data = msg.getData<BuddyEvent>();
if (data.type == BuddyEvent::FiredWeapon)
{
if (m_deadPulseCount > 0)
{
m_deadPulseCount--;
m_aliveList[m_aliveCount] = m_deadPulses[m_deadPulseCount];
auto entity = getScene()->getEntity(m_aliveList[m_aliveCount]);
entity.getComponent<cro::Transform>().setPosition(data.position);
entity.getComponent<PlayerWeapon>().damage = buddyDamage;
m_aliveCount++;
}
}
}
else if (msg.id == MessageID::GameMessage)
{
const auto& data = msg.getData<GameEvent>();
if (data.type == GameEvent::RoundStart)
{
m_aliveCount = 0;
m_deadPulseCount = m_deadPulses.size();
m_deadLaserCount = m_deadLasers.size();
}
}
}
//private
void PlayerWeaponSystem::onEntityAdded(cro::Entity entity)
{
//add entity to dead list based on type
if (entity.getComponent<PlayerWeapon>().type == PlayerWeapon::Type::Pulse)
{
m_deadPulses.push_back(entity.getIndex());
m_deadPulseCount = m_deadPulses.size();
}
else
{
m_deadLasers.push_back(entity.getIndex());
m_deadLaserCount = m_deadLasers.size();
entity.getComponent<PlayerWeapon>().damage = laserDamage;
}
//pad alive list to correct size (we're assuming no entities are actually
//created or destroyed at runtime)
m_aliveList.push_back(-1);
}
| 34.689349 | 142 | 0.574584 | fallahn |
1d42f60b9415a3a67e89a862132cbebb7635c888 | 1,096 | cpp | C++ | Dia1/G-ClockSolitaire.cpp | pauolivares/ICPCCL2018 | 72708a14ff5c1911ab87f7b758f131603603c808 | [
"Apache-2.0"
] | null | null | null | Dia1/G-ClockSolitaire.cpp | pauolivares/ICPCCL2018 | 72708a14ff5c1911ab87f7b758f131603603c808 | [
"Apache-2.0"
] | null | null | null | Dia1/G-ClockSolitaire.cpp | pauolivares/ICPCCL2018 | 72708a14ff5c1911ab87f7b758f131603603c808 | [
"Apache-2.0"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
bool solve(vector<char> &cards,vector<int> &acum, int pos, int l){
if(l==52) return true;
if(acum[pos]==4) return false;
char carta = cards[4*pos + acum[pos]];
acum[pos]++;
if(carta>='2' && carta<='9'){
return solve(cards,acum,carta-'1',l+1);
}
if(carta=='J'){
return solve(cards,acum,0,l+1);
}
if(carta=='T'){
return solve(cards,acum,9,l+1);
}
if(carta=='A'){
return solve(cards,acum,10,l+1);
}
if(carta=='Q'){
return solve(cards,acum,11,l+1);
}
if(carta=='K'){
return solve(cards,acum,12,l+1);
}
}
int main(){
char c;
while(cin >> c){
if(c=='0') break;
vector<char> cards(52);
cards[0] = c;
for(int i=1;i<52;i++){
cin >> cards[i];
}
int resp = 0;
for(int i=0;i<52;i++){
vector<int> acum(13,0);
vector<char> aux(52);
int k=0;
for(int j=i;j<52;j++,k++){
aux[k]=cards[j];
}
for(int j=0;j<i;j++,k++){
aux[k]=cards[j];
}
if(solve(aux,acum,12,0))
resp++;
}
cout << resp << endl;
}
return 0;
}
| 18.896552 | 66 | 0.514599 | pauolivares |
1d446f6f4d917f5e087e01c85c22dbef65af8aaf | 699 | ipp | C++ | ThirdParty/oglplus-develop/implement/oglplus/link_error.ipp | vif/3D-STG | 721402e76a9b9b99b88ba3eb06beb6abb17a9254 | [
"MIT"
] | null | null | null | ThirdParty/oglplus-develop/implement/oglplus/link_error.ipp | vif/3D-STG | 721402e76a9b9b99b88ba3eb06beb6abb17a9254 | [
"MIT"
] | null | null | null | ThirdParty/oglplus-develop/implement/oglplus/link_error.ipp | vif/3D-STG | 721402e76a9b9b99b88ba3eb06beb6abb17a9254 | [
"MIT"
] | null | null | null | /**
* @file oglplus/link_error.ipp
* @brief Implementation of
*
* @author Matus Chochlik
*
* Copyright 2010-2013 Matus Chochlik. 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)
*/
namespace oglplus {
OGLPLUS_LIB_FUNC
LinkError::LinkError(const String& log, const ErrorInfo& info)
: ProgramBuildError(
"OpenGL shading language program link error",
log,
info
)
{ }
OGLPLUS_LIB_FUNC
ValidationError::ValidationError(const String& log, const ErrorInfo& info)
: ProgramBuildError(
"OpenGL shading language program validation error",
log,
info
)
{ }
} // namespace oglplus
| 20.558824 | 74 | 0.738197 | vif |
1d45394ec14a2e0211876d5487ec88b544a2cd36 | 1,705 | cxx | C++ | Modules/Logger/TestingLog/TestAlgorithm.cxx | Hurna/Hurna-Lib | 61c267fc6ccf617e92560a84800f6a719cc5c6c8 | [
"MIT"
] | 2 | 2019-03-29T21:23:02.000Z | 2019-04-02T19:13:32.000Z | Modules/Logger/TestingLog/TestAlgorithm.cxx | Hurna/Hurna-Lib | 61c267fc6ccf617e92560a84800f6a719cc5c6c8 | [
"MIT"
] | null | null | null | Modules/Logger/TestingLog/TestAlgorithm.cxx | Hurna/Hurna-Lib | 61c267fc6ccf617e92560a84800f6a719cc5c6c8 | [
"MIT"
] | null | null | null | /*===========================================================================================================
*
* HUL - Hurna Lib
*
* Copyright (c) Michael Jeulin-Lagarrigue
*
* Licensed under the MIT License, you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://github.com/Hurna/Hurna-Lib/blob/master/LICENSE
*
* 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.
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
*=========================================================================================================*/
#include <gtest/gtest.h>
#include <algorithm.hxx>
using namespace hul;
#ifndef DOXYGEN_SKIP
namespace {
class Algo_Quick
{
public:
static const std::string GetAuthor() { return "Michael Jeulin-L"; }
static const std::string GetDoc() { return "Documentation."; }
static const std::string GetModule() { return "Sort"; }
static const std::string GetName() { return "QuickSort"; }
static const std::string GetVersion() { return "1.0"; }
};
}
#endif /* DOXYGEN_SKIP */
// Test TestAlgo Construction
TEST(TestAlgo_Traits, build)
{
// @todo Passing arguement as: Algo_Quick::Build(std::cout, x1, x2...)
// { Algo_Traits<Algo_Quick>::Build() };
//Algo_Traits<Algo_Quick>::Build(std::cout, OpGetAll);
}
| 37.065217 | 109 | 0.615836 | Hurna |
1d492b9ab4cdad486d4dfc27fa0e9bcfc991a622 | 2,222 | hpp | C++ | src/dsp/BiquadFilter.hpp | flyingLowSounds/LRTRack | 20121c1232e29a26d527134de13a0a3d3d065f52 | [
"BSD-3-Clause"
] | null | null | null | src/dsp/BiquadFilter.hpp | flyingLowSounds/LRTRack | 20121c1232e29a26d527134de13a0a3d3d065f52 | [
"BSD-3-Clause"
] | null | null | null | src/dsp/BiquadFilter.hpp | flyingLowSounds/LRTRack | 20121c1232e29a26d527134de13a0a3d3d065f52 | [
"BSD-3-Clause"
] | null | null | null | /* *\
** __ ___ ______ **
** / / / _ \/_ __/ **
** / /__/ , _/ / / Lindenberg **
** /____/_/|_| /_/ Research Tec. **
** **
** **
** https://github.com/lindenbergresearch/LRTRack **
** [email protected] **
** **
** Sound Modules for VCV Rack **
** Copyright 2017/2018 by Patrick Lindenberg / LRT **
** **
** For Redistribution and use in source and binary forms, **
** with or without modification please see LICENSE. **
** **
\* */
#pragma once
#include "DSPEffect.hpp"
namespace lrt {
enum BiquadType {
LOWPASS = 0,
HIGHPASS,
BANDPASS,
NOTCH,
PEAK,
LOWSHELF,
HIGHSHELF
};
/**
* @brief Common Biquad filters
* based on: https://www.earlevel.com/main/2012/11/26/biquad-c-source-code/
*/
struct Biquad : DSPEffect {
public:
Biquad(BiquadType type, double Fc, double Q, double peakGainDB, float sr);
~Biquad();
void setType(BiquadType type);
void setQ(double Q);
void setFc(double Fc);
void setPeakGain(double peakGainDB);
void setBiquad(BiquadType type, double Fc, double Q, double peakGain);
void process() override;
void invalidate() override;
void init() override;
double in, out;
protected:
int type;
double a0, a1, a2, b1, b2;
double Fc, Q, peakGain;
double z1, z2;
};
inline void Biquad::process() {
out = in * a0 + z1;
z1 = in * a1 + z2 - b1 * out;
z2 = in * a2 - b2 * out;
}
}
| 30.027027 | 78 | 0.382988 | flyingLowSounds |
1d57552649962a2385765a987376e50840a60437 | 6,617 | cpp | C++ | src/Math/Vector4d.cpp | bodguy/CrossPlatform | c8fb740456f8c9b0e6af495958d6b5d6c2d7946f | [
"Apache-2.0"
] | 6 | 2018-07-20T00:59:54.000Z | 2021-08-21T15:55:48.000Z | src/Math/Vector4d.cpp | bodguy/CrossPlatform | c8fb740456f8c9b0e6af495958d6b5d6c2d7946f | [
"Apache-2.0"
] | 9 | 2018-07-17T15:03:22.000Z | 2019-10-05T01:02:31.000Z | src/Math/Vector4d.cpp | bodguy/CrossPlatform | c8fb740456f8c9b0e6af495958d6b5d6c2d7946f | [
"Apache-2.0"
] | 1 | 2019-10-27T01:54:38.000Z | 2019-10-27T01:54:38.000Z | // Copyright (C) 2017 by bodguy
// This code is licensed under Apache 2.0 license (see LICENSE.md for details)
#include "Vector4d.h"
#include <algorithm> // until c++11 for std::swap
#include <cmath>
#include <utility> // since c++11 for std::swap
#include "Math.h"
#include "Vector2d.h"
#include "Vector3d.h"
namespace Theodore {
Vector4d::Vector4d() : x(0.f), y(0.f), z(0.f), w(1.f) {}
Vector4d::Vector4d(float tx, float ty, float tz, float tw) : x(tx), y(ty), z(tz), w(tw) {}
Vector4d::Vector4d(const Vector2d& other) {
x = other.x;
y = other.y;
z = 0.0f;
w = 0.0f;
}
Vector4d::Vector4d(const Vector3d& other) {
x = other.x;
y = other.y;
z = other.z;
w = 0.0f;
}
Vector4d::Vector4d(const Vector2d& other, float tz, float tw) {
x = other.x;
y = other.y;
z = tz;
w = tw;
}
Vector4d::Vector4d(const Vector3d& other, float tw) {
x = other.x;
y = other.y;
z = other.z;
w = tw;
}
Vector4d::Vector4d(const Vector4d& other) {
x = other.x;
y = other.y;
z = other.z;
w = other.w;
}
Vector4d& Vector4d::operator=(Vector4d other) {
Swap(*this, other);
return *this;
}
float Vector4d::operator[](unsigned int i) const {
switch (i) {
case 0:
return x;
case 1:
return y;
case 2:
return z;
case 3:
return w;
default:
return x;
}
}
Vector4d Vector4d::operator+(const Vector4d& other) const {
// using op= (more effective c++ section 22)
return Vector4d(*this) += other;
}
Vector4d& Vector4d::operator+=(const Vector4d& other) {
x += other.x;
y += other.y;
z += other.z;
w += other.w;
return *this;
}
Vector4d Vector4d::operator-(const Vector4d& other) const {
// using op= (more effective c++ section 22)
return Vector4d(*this) -= other;
}
Vector4d& Vector4d::operator-=(const Vector4d& other) {
x -= other.x;
y -= other.y;
z -= other.z;
w -= other.w;
return *this;
}
Vector4d Vector4d::operator*(const Vector4d& other) const {
// using op= (more effective c++ section 22)
return Vector4d(*this) *= other;
}
Vector4d& Vector4d::operator*=(const Vector4d& other) {
x *= other.x;
y *= other.y;
z *= other.z;
w *= other.w;
return *this;
}
Vector4d Vector4d::operator/(const Vector4d& other) const {
// using op= (more effective c++ section 22)
return Vector4d(*this) /= other;
}
Vector4d& Vector4d::operator/=(const Vector4d& other) {
x /= other.x;
y /= other.y;
z /= other.z;
w /= other.w;
return *this;
}
float Vector4d::DotProduct(const Vector4d& a, const Vector4d& b) { return a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w; }
Vector4d Vector4d::operator+(const float scalar) const { return Vector4d(*this) += scalar; }
Vector4d& Vector4d::operator+=(const float scalar) {
x += scalar;
y += scalar;
z += scalar;
w += scalar;
return *this;
}
Vector4d Vector4d::operator-(const float scalar) const { return Vector4d(*this) -= scalar; }
Vector4d& Vector4d::operator-=(const float scalar) {
x -= scalar;
y -= scalar;
z -= scalar;
w -= scalar;
return *this;
}
Vector4d Vector4d::operator*(const float scalar) const { return Vector4d(*this) *= scalar; }
Vector4d& Vector4d::operator*=(const float scalar) {
x *= scalar;
y *= scalar;
z *= scalar;
w *= scalar;
return *this;
}
Vector4d Vector4d::operator/(const float scalar) const { return Vector4d(*this) /= scalar; }
Vector4d& Vector4d::operator/=(const float scalar) {
x /= scalar;
y /= scalar;
z /= scalar;
w /= scalar;
return *this;
}
bool Vector4d::operator<(const Vector4d& other) const { return x < other.x && y < other.y && z < other.z && w < other.w; }
bool Vector4d::operator>(const Vector4d& other) const { return x > other.x && y > other.y && z > other.z && w > other.w; }
bool Vector4d::operator<=(const Vector4d& other) const { return x <= other.x && y <= other.y && z <= other.z && w <= other.w; }
bool Vector4d::operator>=(const Vector4d& other) const { return x >= other.x && y >= other.y && z >= other.z && w >= other.w; }
bool Vector4d::operator==(const Vector4d& other) const { return (Math::IsEqual(x, other.x) && Math::IsEqual(y, other.y) && Math::IsEqual(z, other.z) && Math::IsEqual(w, other.w)); }
bool Vector4d::operator!=(const Vector4d& other) const { return !(*this == other); }
bool Vector4d::operator<(const float scalar) const { return x < scalar && y < scalar && z < scalar; }
bool Vector4d::operator>(const float scalar) const { return x > scalar && y > scalar && z > scalar; }
bool Vector4d::operator<=(const float scalar) const { return x <= scalar && y <= scalar && z <= scalar; }
bool Vector4d::operator>=(const float scalar) const { return x >= scalar && y >= scalar && z >= scalar; }
bool Vector4d::operator==(const float scalar) const {
// scalar only equal with vector components.
return (Math::IsEqual(x, scalar) && Math::IsEqual(y, scalar) && Math::IsEqual(z, scalar));
}
bool Vector4d::operator!=(const float scalar) const { return !(*this == scalar); }
Vector4d& Vector4d::Normalize() {
float len = std::sqrt(x * x + y * y + z * z + w * w);
if (Math::IsZero(len) || Math::IsEqual(len, 1.f)) return *this;
float inv = 1 / len;
x = x * inv;
y = y * inv;
z = z * inv;
return *this;
}
float Vector4d::Length() { return std::sqrt(x * x + y * y + z * z + w * w); }
Vector3d Vector4d::ToVector3d(const Vector4d& other) { return Vector3d(other.x, other.y, other.z); }
Vector4d Vector4d::Absolute(const Vector4d& other) { return Vector4d(std::fabsf(other.x), std::fabsf(other.y), std::fabsf(other.z), std::fabsf(other.w)); }
void Vector4d::Swap(Vector4d& first, Vector4d& second) {
using std::swap;
swap(first.x, second.x);
swap(first.y, second.y);
swap(first.z, second.z);
swap(first.w, second.w);
}
const Vector4d Vector4d::up = Vector4d(0.f, 1.f, 0.f, 1.f);
const Vector4d Vector4d::down = Vector4d(0.f, -1.f, 0.f, 1.f);
const Vector4d Vector4d::left = Vector4d(-1.f, 0.f, 0.f, 1.f);
const Vector4d Vector4d::right = Vector4d(1.f, 0.f, 0.f, 1.f);
const Vector4d Vector4d::forward = Vector4d(0.f, 0.f, -1.f, 1.f);
const Vector4d Vector4d::backward = Vector4d(0.f, 0.f, 1.f, 1.f);
const Vector4d Vector4d::one = Vector4d(1.f, 1.f, 1.f, 1.f);
const Vector4d Vector4d::zero = Vector4d(0.f, 0.f, 0.f, 0.f);
} // namespace Theodore
| 27.686192 | 183 | 0.598156 | bodguy |
1d58a0e2d444eca04f97fa660467b8921a3386aa | 13,606 | cpp | C++ | android-31/android/provider/DocumentsProvider.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 12 | 2020-03-26T02:38:56.000Z | 2022-03-14T08:17:26.000Z | android-31/android/provider/DocumentsProvider.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 1 | 2021-01-27T06:07:45.000Z | 2021-11-13T19:19:43.000Z | android-29/android/provider/DocumentsProvider.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 3 | 2021-02-02T12:34:55.000Z | 2022-03-08T07:45:57.000Z | #include "../../JArray.hpp"
#include "../content/ContentValues.hpp"
#include "../content/Context.hpp"
#include "../content/IntentSender.hpp"
#include "../content/pm/ProviderInfo.hpp"
#include "../content/res/AssetFileDescriptor.hpp"
#include "../graphics/Point.hpp"
#include "../net/Uri.hpp"
#include "../os/Bundle.hpp"
#include "../os/CancellationSignal.hpp"
#include "../os/ParcelFileDescriptor.hpp"
#include "./DocumentsContract_Path.hpp"
#include "../../JString.hpp"
#include "./DocumentsProvider.hpp"
namespace android::provider
{
// Fields
// QJniObject forward
DocumentsProvider::DocumentsProvider(QJniObject obj) : android::content::ContentProvider(obj) {}
// Constructors
DocumentsProvider::DocumentsProvider()
: android::content::ContentProvider(
"android.provider.DocumentsProvider",
"()V"
) {}
// Methods
void DocumentsProvider::attachInfo(android::content::Context arg0, android::content::pm::ProviderInfo arg1) const
{
callMethod<void>(
"attachInfo",
"(Landroid/content/Context;Landroid/content/pm/ProviderInfo;)V",
arg0.object(),
arg1.object()
);
}
android::os::Bundle DocumentsProvider::call(JString arg0, JString arg1, android::os::Bundle arg2) const
{
return callObjectMethod(
"call",
"(Ljava/lang/String;Ljava/lang/String;Landroid/os/Bundle;)Landroid/os/Bundle;",
arg0.object<jstring>(),
arg1.object<jstring>(),
arg2.object()
);
}
android::net::Uri DocumentsProvider::canonicalize(android::net::Uri arg0) const
{
return callObjectMethod(
"canonicalize",
"(Landroid/net/Uri;)Landroid/net/Uri;",
arg0.object()
);
}
JString DocumentsProvider::copyDocument(JString arg0, JString arg1) const
{
return callObjectMethod(
"copyDocument",
"(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;",
arg0.object<jstring>(),
arg1.object<jstring>()
);
}
JString DocumentsProvider::createDocument(JString arg0, JString arg1, JString arg2) const
{
return callObjectMethod(
"createDocument",
"(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;",
arg0.object<jstring>(),
arg1.object<jstring>(),
arg2.object<jstring>()
);
}
android::content::IntentSender DocumentsProvider::createWebLinkIntent(JString arg0, android::os::Bundle arg1) const
{
return callObjectMethod(
"createWebLinkIntent",
"(Ljava/lang/String;Landroid/os/Bundle;)Landroid/content/IntentSender;",
arg0.object<jstring>(),
arg1.object()
);
}
jint DocumentsProvider::delete_(android::net::Uri arg0, JString arg1, JArray arg2) const
{
return callMethod<jint>(
"delete",
"(Landroid/net/Uri;Ljava/lang/String;[Ljava/lang/String;)I",
arg0.object(),
arg1.object<jstring>(),
arg2.object<jarray>()
);
}
void DocumentsProvider::deleteDocument(JString arg0) const
{
callMethod<void>(
"deleteDocument",
"(Ljava/lang/String;)V",
arg0.object<jstring>()
);
}
void DocumentsProvider::ejectRoot(JString arg0) const
{
callMethod<void>(
"ejectRoot",
"(Ljava/lang/String;)V",
arg0.object<jstring>()
);
}
android::provider::DocumentsContract_Path DocumentsProvider::findDocumentPath(JString arg0, JString arg1) const
{
return callObjectMethod(
"findDocumentPath",
"(Ljava/lang/String;Ljava/lang/String;)Landroid/provider/DocumentsContract$Path;",
arg0.object<jstring>(),
arg1.object<jstring>()
);
}
android::os::Bundle DocumentsProvider::getDocumentMetadata(JString arg0) const
{
return callObjectMethod(
"getDocumentMetadata",
"(Ljava/lang/String;)Landroid/os/Bundle;",
arg0.object<jstring>()
);
}
JArray DocumentsProvider::getDocumentStreamTypes(JString arg0, JString arg1) const
{
return callObjectMethod(
"getDocumentStreamTypes",
"(Ljava/lang/String;Ljava/lang/String;)[Ljava/lang/String;",
arg0.object<jstring>(),
arg1.object<jstring>()
);
}
JString DocumentsProvider::getDocumentType(JString arg0) const
{
return callObjectMethod(
"getDocumentType",
"(Ljava/lang/String;)Ljava/lang/String;",
arg0.object<jstring>()
);
}
JArray DocumentsProvider::getStreamTypes(android::net::Uri arg0, JString arg1) const
{
return callObjectMethod(
"getStreamTypes",
"(Landroid/net/Uri;Ljava/lang/String;)[Ljava/lang/String;",
arg0.object(),
arg1.object<jstring>()
);
}
JString DocumentsProvider::getType(android::net::Uri arg0) const
{
return callObjectMethod(
"getType",
"(Landroid/net/Uri;)Ljava/lang/String;",
arg0.object()
);
}
android::net::Uri DocumentsProvider::insert(android::net::Uri arg0, android::content::ContentValues arg1) const
{
return callObjectMethod(
"insert",
"(Landroid/net/Uri;Landroid/content/ContentValues;)Landroid/net/Uri;",
arg0.object(),
arg1.object()
);
}
jboolean DocumentsProvider::isChildDocument(JString arg0, JString arg1) const
{
return callMethod<jboolean>(
"isChildDocument",
"(Ljava/lang/String;Ljava/lang/String;)Z",
arg0.object<jstring>(),
arg1.object<jstring>()
);
}
JString DocumentsProvider::moveDocument(JString arg0, JString arg1, JString arg2) const
{
return callObjectMethod(
"moveDocument",
"(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;",
arg0.object<jstring>(),
arg1.object<jstring>(),
arg2.object<jstring>()
);
}
android::content::res::AssetFileDescriptor DocumentsProvider::openAssetFile(android::net::Uri arg0, JString arg1) const
{
return callObjectMethod(
"openAssetFile",
"(Landroid/net/Uri;Ljava/lang/String;)Landroid/content/res/AssetFileDescriptor;",
arg0.object(),
arg1.object<jstring>()
);
}
android::content::res::AssetFileDescriptor DocumentsProvider::openAssetFile(android::net::Uri arg0, JString arg1, android::os::CancellationSignal arg2) const
{
return callObjectMethod(
"openAssetFile",
"(Landroid/net/Uri;Ljava/lang/String;Landroid/os/CancellationSignal;)Landroid/content/res/AssetFileDescriptor;",
arg0.object(),
arg1.object<jstring>(),
arg2.object()
);
}
android::os::ParcelFileDescriptor DocumentsProvider::openDocument(JString arg0, JString arg1, android::os::CancellationSignal arg2) const
{
return callObjectMethod(
"openDocument",
"(Ljava/lang/String;Ljava/lang/String;Landroid/os/CancellationSignal;)Landroid/os/ParcelFileDescriptor;",
arg0.object<jstring>(),
arg1.object<jstring>(),
arg2.object()
);
}
android::content::res::AssetFileDescriptor DocumentsProvider::openDocumentThumbnail(JString arg0, android::graphics::Point arg1, android::os::CancellationSignal arg2) const
{
return callObjectMethod(
"openDocumentThumbnail",
"(Ljava/lang/String;Landroid/graphics/Point;Landroid/os/CancellationSignal;)Landroid/content/res/AssetFileDescriptor;",
arg0.object<jstring>(),
arg1.object(),
arg2.object()
);
}
android::os::ParcelFileDescriptor DocumentsProvider::openFile(android::net::Uri arg0, JString arg1) const
{
return callObjectMethod(
"openFile",
"(Landroid/net/Uri;Ljava/lang/String;)Landroid/os/ParcelFileDescriptor;",
arg0.object(),
arg1.object<jstring>()
);
}
android::os::ParcelFileDescriptor DocumentsProvider::openFile(android::net::Uri arg0, JString arg1, android::os::CancellationSignal arg2) const
{
return callObjectMethod(
"openFile",
"(Landroid/net/Uri;Ljava/lang/String;Landroid/os/CancellationSignal;)Landroid/os/ParcelFileDescriptor;",
arg0.object(),
arg1.object<jstring>(),
arg2.object()
);
}
android::content::res::AssetFileDescriptor DocumentsProvider::openTypedAssetFile(android::net::Uri arg0, JString arg1, android::os::Bundle arg2) const
{
return callObjectMethod(
"openTypedAssetFile",
"(Landroid/net/Uri;Ljava/lang/String;Landroid/os/Bundle;)Landroid/content/res/AssetFileDescriptor;",
arg0.object(),
arg1.object<jstring>(),
arg2.object()
);
}
android::content::res::AssetFileDescriptor DocumentsProvider::openTypedAssetFile(android::net::Uri arg0, JString arg1, android::os::Bundle arg2, android::os::CancellationSignal arg3) const
{
return callObjectMethod(
"openTypedAssetFile",
"(Landroid/net/Uri;Ljava/lang/String;Landroid/os/Bundle;Landroid/os/CancellationSignal;)Landroid/content/res/AssetFileDescriptor;",
arg0.object(),
arg1.object<jstring>(),
arg2.object(),
arg3.object()
);
}
android::content::res::AssetFileDescriptor DocumentsProvider::openTypedDocument(JString arg0, JString arg1, android::os::Bundle arg2, android::os::CancellationSignal arg3) const
{
return callObjectMethod(
"openTypedDocument",
"(Ljava/lang/String;Ljava/lang/String;Landroid/os/Bundle;Landroid/os/CancellationSignal;)Landroid/content/res/AssetFileDescriptor;",
arg0.object<jstring>(),
arg1.object<jstring>(),
arg2.object(),
arg3.object()
);
}
JObject DocumentsProvider::query(android::net::Uri arg0, JArray arg1, android::os::Bundle arg2, android::os::CancellationSignal arg3) const
{
return callObjectMethod(
"query",
"(Landroid/net/Uri;[Ljava/lang/String;Landroid/os/Bundle;Landroid/os/CancellationSignal;)Landroid/database/Cursor;",
arg0.object(),
arg1.object<jarray>(),
arg2.object(),
arg3.object()
);
}
JObject DocumentsProvider::query(android::net::Uri arg0, JArray arg1, JString arg2, JArray arg3, JString arg4) const
{
return callObjectMethod(
"query",
"(Landroid/net/Uri;[Ljava/lang/String;Ljava/lang/String;[Ljava/lang/String;Ljava/lang/String;)Landroid/database/Cursor;",
arg0.object(),
arg1.object<jarray>(),
arg2.object<jstring>(),
arg3.object<jarray>(),
arg4.object<jstring>()
);
}
JObject DocumentsProvider::query(android::net::Uri arg0, JArray arg1, JString arg2, JArray arg3, JString arg4, android::os::CancellationSignal arg5) const
{
return callObjectMethod(
"query",
"(Landroid/net/Uri;[Ljava/lang/String;Ljava/lang/String;[Ljava/lang/String;Ljava/lang/String;Landroid/os/CancellationSignal;)Landroid/database/Cursor;",
arg0.object(),
arg1.object<jarray>(),
arg2.object<jstring>(),
arg3.object<jarray>(),
arg4.object<jstring>(),
arg5.object()
);
}
JObject DocumentsProvider::queryChildDocuments(JString arg0, JArray arg1, android::os::Bundle arg2) const
{
return callObjectMethod(
"queryChildDocuments",
"(Ljava/lang/String;[Ljava/lang/String;Landroid/os/Bundle;)Landroid/database/Cursor;",
arg0.object<jstring>(),
arg1.object<jarray>(),
arg2.object()
);
}
JObject DocumentsProvider::queryChildDocuments(JString arg0, JArray arg1, JString arg2) const
{
return callObjectMethod(
"queryChildDocuments",
"(Ljava/lang/String;[Ljava/lang/String;Ljava/lang/String;)Landroid/database/Cursor;",
arg0.object<jstring>(),
arg1.object<jarray>(),
arg2.object<jstring>()
);
}
JObject DocumentsProvider::queryDocument(JString arg0, JArray arg1) const
{
return callObjectMethod(
"queryDocument",
"(Ljava/lang/String;[Ljava/lang/String;)Landroid/database/Cursor;",
arg0.object<jstring>(),
arg1.object<jarray>()
);
}
JObject DocumentsProvider::queryRecentDocuments(JString arg0, JArray arg1) const
{
return callObjectMethod(
"queryRecentDocuments",
"(Ljava/lang/String;[Ljava/lang/String;)Landroid/database/Cursor;",
arg0.object<jstring>(),
arg1.object<jarray>()
);
}
JObject DocumentsProvider::queryRecentDocuments(JString arg0, JArray arg1, android::os::Bundle arg2, android::os::CancellationSignal arg3) const
{
return callObjectMethod(
"queryRecentDocuments",
"(Ljava/lang/String;[Ljava/lang/String;Landroid/os/Bundle;Landroid/os/CancellationSignal;)Landroid/database/Cursor;",
arg0.object<jstring>(),
arg1.object<jarray>(),
arg2.object(),
arg3.object()
);
}
JObject DocumentsProvider::queryRoots(JArray arg0) const
{
return callObjectMethod(
"queryRoots",
"([Ljava/lang/String;)Landroid/database/Cursor;",
arg0.object<jarray>()
);
}
JObject DocumentsProvider::querySearchDocuments(JString arg0, JArray arg1, android::os::Bundle arg2) const
{
return callObjectMethod(
"querySearchDocuments",
"(Ljava/lang/String;[Ljava/lang/String;Landroid/os/Bundle;)Landroid/database/Cursor;",
arg0.object<jstring>(),
arg1.object<jarray>(),
arg2.object()
);
}
JObject DocumentsProvider::querySearchDocuments(JString arg0, JString arg1, JArray arg2) const
{
return callObjectMethod(
"querySearchDocuments",
"(Ljava/lang/String;Ljava/lang/String;[Ljava/lang/String;)Landroid/database/Cursor;",
arg0.object<jstring>(),
arg1.object<jstring>(),
arg2.object<jarray>()
);
}
void DocumentsProvider::removeDocument(JString arg0, JString arg1) const
{
callMethod<void>(
"removeDocument",
"(Ljava/lang/String;Ljava/lang/String;)V",
arg0.object<jstring>(),
arg1.object<jstring>()
);
}
JString DocumentsProvider::renameDocument(JString arg0, JString arg1) const
{
return callObjectMethod(
"renameDocument",
"(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;",
arg0.object<jstring>(),
arg1.object<jstring>()
);
}
void DocumentsProvider::revokeDocumentPermission(JString arg0) const
{
callMethod<void>(
"revokeDocumentPermission",
"(Ljava/lang/String;)V",
arg0.object<jstring>()
);
}
jint DocumentsProvider::update(android::net::Uri arg0, android::content::ContentValues arg1, JString arg2, JArray arg3) const
{
return callMethod<jint>(
"update",
"(Landroid/net/Uri;Landroid/content/ContentValues;Ljava/lang/String;[Ljava/lang/String;)I",
arg0.object(),
arg1.object(),
arg2.object<jstring>(),
arg3.object<jarray>()
);
}
} // namespace android::provider
| 31.422633 | 189 | 0.721961 | YJBeetle |
1d5d9cede9f7f9bf6df2da82d35587b759010128 | 836 | cpp | C++ | Array/stock.cpp | RYzen-009/DSA | 0f7f9d2c7f7452667329f7a43b3eb4110d5c174c | [
"MIT"
] | null | null | null | Array/stock.cpp | RYzen-009/DSA | 0f7f9d2c7f7452667329f7a43b3eb4110d5c174c | [
"MIT"
] | null | null | null | Array/stock.cpp | RYzen-009/DSA | 0f7f9d2c7f7452667329f7a43b3eb4110d5c174c | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
//This is a O(N*N) Solution
int stock(int price[],int start , int end)
{
if(start >= end)
return 0;
int profit=0,curr_profit=0;
for(int i=start;i<=end;i++)
{
for(int j=i+1;j<=end;j++)
{
if(price[j]>price[i])
{
curr_profit = (price[j]-price[i]) + stock(price,start,i-1) + stock(price,j+1,end);
profit=max(profit,curr_profit);
}
}
}
return profit;
}
int max_profit( int arr[], int n )
{
int profit = 0;
for(int i=1;i<n;i++)
{
if(arr[i]>arr[i-1])
profit += arr[i]-arr[i-1];
}
return profit;
}
int main()
{
int n;
cin>>n;
int price[n];
for(int i=0;i<n;i++)
cin>>price[i];
cout<<max_profit(price,n);
// cout << stock(price, 0, n-1);
return 0;
} | 18.173913 | 92 | 0.511962 | RYzen-009 |
1d5e5894b13b332ef7c8190174dcd6ed61f24b5a | 8,694 | cpp | C++ | SimCenterUQInputSurrogate.cpp | bhajay/quoFEM | 23e57fd85d28468379906eed59aaa54b77604a0c | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | SimCenterUQInputSurrogate.cpp | bhajay/quoFEM | 23e57fd85d28468379906eed59aaa54b77604a0c | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | SimCenterUQInputSurrogate.cpp | bhajay/quoFEM | 23e57fd85d28468379906eed59aaa54b77604a0c | [
"BSD-2-Clause-FreeBSD"
] | null | null | null |
/* *****************************************************************************
Copyright (c) 2016-2017, The Regents of the University of California (Regents).
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
THE SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS
PROVIDED "AS IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT,
UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
*************************************************************************** */
#include "SimCenterUQInputSurrogate.h"
#include "SimCenterUQResultsSurrogate.h"
#include <RandomVariablesContainer.h>
#include <QPushButton>
#include <QScrollArea>
#include <QJsonArray>
#include <QJsonObject>
#include <QLabel>
#include <QLineEdit>
#include <QDebug>
#include <QFileDialog>
#include <QPushButton>
#include <sectiontitle.h>
#include <iostream>
#include <sstream>
#include <fstream>
#include <time.h>
#include <QStackedWidget>
#include <SurrogateDoEInputWidget.h>
#include <SurrogateNoDoEInputWidget.h>
#include <SurrogateMFInputWidget.h>
#include <InputWidgetFEM.h>
#include <InputWidgetParameters.h>
#include <InputWidgetEDP.h>
SimCenterUQInputSurrogate::SimCenterUQInputSurrogate(InputWidgetParameters *param,InputWidgetFEM *femwidget,InputWidgetEDP *edpwidget, QWidget *parent)
: UQ_Engine(parent),uqSpecific(0), theParameters(param), theEdpWidget(edpwidget), theFemWidget(femwidget)
{
layout = new QVBoxLayout();
mLayout = new QVBoxLayout();
//
// create layout for input selection box
//
QHBoxLayout *methodLayout1= new QHBoxLayout;
inpMethod = new QComboBox();
inpMethod->addItem(tr("Sampling and Simulation"));
inpMethod->addItem(tr("Import Data File"));
inpMethod->addItem(tr("Import Multi-fidelity Data File"));
inpMethod->setMaximumWidth(250);
inpMethod->setMinimumWidth(250);
methodLayout1->addWidget(new QLabel("Training Dataset"));
methodLayout1->addWidget(inpMethod,2);
methodLayout1->addStretch();
mLayout->addLayout(methodLayout1);
//
// input selection widgets
//
theStackedWidget = new QStackedWidget();
theDoE = new SurrogateDoEInputWidget();
theStackedWidget->addWidget(theDoE);
theData = new SurrogateNoDoEInputWidget(theParameters,theFemWidget,theEdpWidget);
theStackedWidget->addWidget(theData);
theMultiFidelity = new SurrogateMFInputWidget(theParameters,theFemWidget,theEdpWidget);
theStackedWidget->addWidget(theMultiFidelity);
theStackedWidget->setCurrentIndex(0);
theInpCurrentMethod = theDoE;
mLayout->addWidget(theStackedWidget);
//
//
//
layout->addLayout(mLayout);
this->setLayout(layout);
connect(inpMethod, SIGNAL(currentIndexChanged(QString)), this, SLOT(onIndexChanged(QString)));
}
void SimCenterUQInputSurrogate::onIndexChanged(const QString &text)
{
if (text=="Sampling and Simulation") {
theStackedWidget->setCurrentIndex(0);
theInpCurrentMethod = theDoE;
theFemWidget->setFEMforGP("GPmodel"); // reset FEM
}
else if (text=="Import Data File") {
delete theData;
theData = new SurrogateNoDoEInputWidget(theParameters,theFemWidget,theEdpWidget);
theStackedWidget->insertWidget(1,theData);
theStackedWidget->setCurrentIndex(1);
theInpCurrentMethod = theData;
}
else if (text=="Import Multi-fidelity Data File") {
delete theMultiFidelity;
theMultiFidelity = new SurrogateMFInputWidget(theParameters,theFemWidget,theEdpWidget);
theStackedWidget->insertWidget(2,theMultiFidelity);
theStackedWidget->setCurrentIndex(2);
theInpCurrentMethod = theMultiFidelity;
theFemWidget->setFEMforGP("GPdata");
}
//theParameters->setGPVarNamesAndValues(QStringList({}));// remove GP RVs
}
SimCenterUQInputSurrogate::~SimCenterUQInputSurrogate()
{
}
int
SimCenterUQInputSurrogate::getMaxNumParallelTasks(void){
return theInpCurrentMethod->getNumberTasks();
}
void SimCenterUQInputSurrogate::clear(void)
{
}
void SimCenterUQInputSurrogate::numModelsChanged(int numModels) {
emit onNumModelsChanged(numModels);
}
bool
SimCenterUQInputSurrogate::outputToJSON(QJsonObject &jsonObject)
{
bool result = true;
QJsonObject uq;
uq["method"]=inpMethod->currentText();
theInpCurrentMethod->outputToJSON(uq);
jsonObject["surrogateMethodInfo"]=uq;
return result;
}
bool
SimCenterUQInputSurrogate::inputFromJSON(QJsonObject &jsonObject)
{
bool result = false;
this->clear();
//
// get sampleingMethodData, if not present it's an error
//
if (jsonObject.contains("surrogateMethodInfo")) {
QJsonObject uq = jsonObject["surrogateMethodInfo"].toObject();
if (uq.contains("method")) {
QString method =uq["method"].toString();
int index = inpMethod->findText(method);
if (index == -1) {
return false;
}
inpMethod->setCurrentIndex(index);
result = theInpCurrentMethod->inputFromJSON(uq);
if (result == false)
return result;
}
}
return result;
}
bool
SimCenterUQInputSurrogate::outputAppDataToJSON(QJsonObject &jsonObject)
{
bool result = true;
jsonObject["Application"] = "SimCenterUQ-UQ";
QJsonObject uq;
uq["method"]=inpMethod->currentText();
theInpCurrentMethod->outputToJSON(uq);
jsonObject["ApplicationData"] = uq;
return result;
}
bool
SimCenterUQInputSurrogate::inputAppDataFromJSON(QJsonObject &jsonObject)
{
bool result = false;
this->clear();
//
// get sampleingMethodData, if not present it's an error
if (jsonObject.contains("ApplicationData")) {
QJsonObject uq = jsonObject["ApplicationData"].toObject();
if (uq.contains("method")) {
QString method = uq["method"].toString();
int index = inpMethod->findText(method);
if (index == -1) {
errorMessage(QString("ERROR: Unknown Method") + method);
return false;
}
inpMethod->setCurrentIndex(index);
return theInpCurrentMethod->inputFromJSON(uq);
}
} else {
errorMessage("ERROR: Surrogate Input Widget - no \"surrogateMethodData\" input");
return false;
}
return result;
}
int SimCenterUQInputSurrogate::processResults(QString &filenameResults, QString &filenameTab) {
return 0;
}
UQ_Results *
SimCenterUQInputSurrogate::getResults(void) {
qDebug() << "RETURNED SimCenterUQRESULTSSURROGATE";
return new SimCenterUQResultsSurrogate(theRandomVariables);
}
RandomVariablesContainer *
SimCenterUQInputSurrogate::getParameters(void) {
QString classType("Uncertain");
theRandomVariables = new RandomVariablesContainer(classType,tr("SimCenterUQ"));
return theRandomVariables;
}
QString
SimCenterUQInputSurrogate::getMethodName(void){
//if (inpMethod->currentIndex()==0){
// return QString("surrogateModel");
//} else if (inpMethod->currentIndex()==1){
// return QString("surrogateData");
//}
return QString("surrogate");
}
| 29.773973 | 151 | 0.714286 | bhajay |
1d612ac6828828b43ba4d4d62f797163f66801c6 | 20,916 | cpp | C++ | tools/indextool.cpp | Arnaud-de-Grandmaison-ARM/tarmac-trace-utilities | 5428f72485531be0c4482768b4923640e7ada397 | [
"Apache-2.0"
] | 1 | 2021-07-03T23:54:51.000Z | 2021-07-03T23:54:51.000Z | tools/indextool.cpp | Arnaud-de-Grandmaison-ARM/tarmac-trace-utilities | 5428f72485531be0c4482768b4923640e7ada397 | [
"Apache-2.0"
] | null | null | null | tools/indextool.cpp | Arnaud-de-Grandmaison-ARM/tarmac-trace-utilities | 5428f72485531be0c4482768b4923640e7ada397 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2016-2021 Arm Limited. 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.
*
* This file is part of Tarmac Trace Utilities
*/
#include "libtarmac/argparse.hh"
#include "libtarmac/index.hh"
#include "libtarmac/tarmacutil.hh"
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <climits>
#include <functional>
#include <iostream>
#include <stack>
#include <string>
#include <vector>
using std::cerr;
using std::cout;
using std::dec;
using std::endl;
using std::hex;
using std::min;
using std::showbase;
using std::stack;
using std::string;
using std::vector;
static bool omit_index_offsets;
static void dump_memory_at_line(const IndexNavigator &IN, unsigned trace_line,
const std::string &prefix);
template <typename Payload, typename Annotation> class TreeDumper {
struct StackEntry {
bool first_of_two;
bool right_child;
string prefix;
};
string prefix;
stack<StackEntry> stk;
virtual void dump_payload(const string &prefix, const Payload &) = 0;
virtual void dump_annotation(const string &prefix, const Payload &,
const Annotation &)
{
}
virtual void node_header(off_t offset)
{
cout << prefix << "Node";
if (!omit_index_offsets)
cout << prefix << " at file offset " << offset;
cout << ":" << endl;
}
void visit(const Payload &payload, off_t offset)
{
node_header(offset);
dump_payload(prefix + " ", payload);
}
void walk(const Payload &payload, const Annotation &annotation,
off_t leftoff, const Annotation *, off_t rightoff,
const Annotation *, off_t offset)
{
string firstlineprefix, finalprefix, node_type;
if (!stk.empty()) {
StackEntry &pop = stk.top();
prefix = pop.prefix;
if (pop.first_of_two) {
firstlineprefix = prefix + "├── ";
prefix += "│ ";
finalprefix = prefix;
} else {
firstlineprefix = prefix + "└── ";
finalprefix = prefix;
prefix += " ";
}
node_type =
pop.right_child ? "Right child node" : "Left child node";
stk.pop();
} else {
node_type = "Root node";
firstlineprefix = finalprefix = prefix;
}
cout << firstlineprefix << hex << node_type << " at file offset "
<< offset << ":" << endl;
if (rightoff) {
stk.push({false, true, prefix});
if (leftoff)
stk.push({true, false, prefix});
} else if (leftoff) {
stk.push({false, false, prefix});
}
if (rightoff || leftoff)
prefix += "│ ";
else
prefix += " ";
cout << prefix << "Child offsets = { ";
if (leftoff)
cout << leftoff;
else
cout << "null";
cout << ", ";
if (rightoff)
cout << rightoff;
else
cout << "null";
cout << " }" << endl << dec;
dump_payload(prefix, payload);
dump_annotation(prefix, payload, annotation);
if (!stk.empty()) {
// Leave a blank line before the next node, if we're expecting one.
size_t useful_prefix_len =
min((size_t)1, prefix.find_last_not_of(" ")) - 1;
cout << prefix.substr(0, useful_prefix_len - 1) << endl;
}
prefix = finalprefix;
}
protected:
const IndexNavigator &IN;
public:
class Visitor {
TreeDumper *parent;
public:
Visitor(TreeDumper *parent) : parent(parent) {}
void operator()(const Payload &payload, off_t offset)
{
parent->visit(payload, offset);
}
} visitor;
class Walker {
TreeDumper *parent;
public:
Walker(TreeDumper *parent) : parent(parent) {}
void operator()(const Payload &payload, const Annotation &annotation,
off_t lo, const Annotation *la, off_t ro,
const Annotation *ra, off_t offset)
{
parent->walk(payload, annotation, lo, la, ro, ra, offset);
}
} walker;
TreeDumper(const IndexNavigator &IN) : IN(IN), visitor(this), walker(this)
{
}
};
class SeqTreeDumper : public TreeDumper<SeqOrderPayload, SeqOrderAnnotation> {
using TreeDumper::TreeDumper;
virtual void dump_payload(const string &prefix,
const SeqOrderPayload &node) override
{
cout << prefix << "Line range: start " << node.trace_file_firstline
<< ", extent " << node.trace_file_lines << endl;
cout << prefix << "Byte range: start " << hex << node.trace_file_pos
<< ", extent " << node.trace_file_len << dec << endl;
cout << prefix << "Modification time: " << node.mod_time << endl;
cout << prefix << "PC: ";
if (node.pc == KNOWN_INVALID_PC)
cout << "invalid";
else
cout << hex << node.pc << dec;
cout << endl;
if (!omit_index_offsets) {
cout << prefix << "Root of memory tree: " << hex << node.memory_root
<< dec << endl;
}
cout << prefix << "Call depth: " << node.call_depth << endl;
if (dump_memory) {
dump_memory_at_line(IN, node.trace_file_firstline, prefix + " ");
}
}
virtual void dump_annotation(const string &prefix,
const SeqOrderPayload &node,
const SeqOrderAnnotation &annotation) override
{
auto *array = (const CallDepthArrayEntry *)IN.index.index_offset(
annotation.call_depth_array);
for (unsigned i = 0, e = annotation.call_depth_arraylen; i < e; i++) {
const CallDepthArrayEntry &ent = array[i];
cout << prefix << "LRT[" << i << "] = { ";
if (ent.call_depth == SENTINEL_DEPTH)
cout << "sentinel";
else
cout << "depth " << ent.call_depth;
cout << ", " << ent.cumulative_lines << " lines, "
<< ent.cumulative_insns << " insns, "
<< "left-crosslink " << ent.leftlink << ", "
<< "right-crosslink " << ent.rightlink << "}" << endl;
}
}
public:
bool dump_memory;
};
class MemTreeDumper : public TreeDumper<MemoryPayload, MemoryAnnotation> {
using TreeDumper::TreeDumper;
virtual void dump_payload(const string &prefix,
const MemoryPayload &node) override
{
cout << prefix << "Range: ";
// FIXME: to make diagnostic dumps less opaque, it would be
// nice here to translate reg addresses back into some
// meaningful identification involving a register number.
if (node.type == 'r')
cout << "register-space";
else
cout << "memory";
cout << " [" << hex << node.lo << "-" << node.hi << dec << "]" << endl;
cout << prefix << "Contents: ";
if (node.raw) {
cout << (node.hi + 1 - node.lo) << " bytes";
if (!omit_index_offsets)
cout << " at file offset " << hex << node.contents << dec;
} else {
cout << "memory subtree";
if (!omit_index_offsets)
cout << " with root pointer at " << hex << node.contents
<< ", actual root is "
<< IN.index.index_subtree_root(node.contents) << dec;
}
cout << endl;
cout << prefix << "Last modification: ";
if (node.trace_file_firstline == 0)
cout << "never";
else
cout << "line " << node.trace_file_firstline;
cout << endl;
}
virtual void dump_annotation(const string &prefix,
const MemoryPayload &node,
const MemoryAnnotation &annotation) override
{
cout << prefix << "Latest modification time in whole subtree: "
<< annotation.latest << endl;
}
};
class MemSubtreeDumper
: public TreeDumper<MemorySubPayload, EmptyAnnotation<MemorySubPayload>> {
using TreeDumper::TreeDumper;
virtual void dump_payload(const string &prefix,
const MemorySubPayload &node) override
{
// Here we _can't_ translate register-space addresses back
// into registers, even if we wanted to, because we haven't
// been told whether this subtree even refers to register or
// memory space.
cout << prefix << "Range: [" << hex << node.lo << "-" << node.hi << dec
<< "]" << endl;
cout << prefix << "Contents: " << (node.hi + 1 - node.lo) << " bytes";
if (!omit_index_offsets)
cout << " at file offset " << hex << node.contents << dec;
cout << endl;
}
};
class ByPCTreeDumper
: public TreeDumper<ByPCPayload, EmptyAnnotation<ByPCPayload>> {
using TreeDumper::TreeDumper;
virtual void dump_payload(const string &prefix,
const ByPCPayload &node) override
{
cout << prefix << "PC: " << hex << node.pc << dec << endl;
cout << prefix << "Line: " << node.trace_file_firstline << endl;
}
};
static const struct {
const char *pname;
RegPrefix prefix;
unsigned nregs;
} reg_families[] = {
#define WRITE_ENTRY(prefix, ignore1, ignore2, nregs) \
{#prefix, RegPrefix::prefix, nregs},
REGPREFIXLIST(WRITE_ENTRY, WRITE_ENTRY)
#undef WRITE_ENTRY
};
static void dump_registers(bool got_iflags, unsigned iflags)
{
for (const auto &fam : reg_families) {
for (unsigned i = 0; i < fam.nregs; i++) {
RegisterId r{fam.prefix, i};
cout << reg_name(r);
if (!got_iflags && reg_needs_iflags(r)) {
cout << " - dependent on iflags\n";
} else {
cout << " offset=" << hex << reg_offset(r, iflags)
<< " size=" << hex << reg_size(r) << "\n";
}
}
}
}
static unsigned long long parseint(const string &s)
{
try {
size_t pos;
unsigned long long toret = stoull(s, &pos, 0);
if (pos < s.size())
throw ArgparseError("'" + s + "': unable to parse numeric value");
return toret;
} catch (std::invalid_argument) {
throw ArgparseError("'" + s + "': unable to parse numeric value");
} catch (std::out_of_range) {
throw ArgparseError("'" + s + "': numeric value out of range");
}
}
static void hexdump(const void *vdata, size_t size, Addr startaddr,
const std::string &prefix)
{
const unsigned char *data = (const unsigned char *)vdata;
char linebuf[100], fmtbuf[32];
constexpr Addr linelen = 16, mask = ~(linelen - 1);
while (size > 0) {
Addr lineaddr = startaddr & mask;
size_t linesize = min(size, (size_t)(lineaddr + linelen - startaddr));
memset(linebuf, ' ', 83);
snprintf(fmtbuf, sizeof(fmtbuf), "%016llx",
(unsigned long long)lineaddr);
memcpy(linebuf, fmtbuf, 16);
size_t outlinelen = 16;
for (size_t i = 0; i < linesize; i++) {
size_t lineoff = i + (startaddr - lineaddr);
size_t hexoff = 16 + 1 + 3 * lineoff;
snprintf(fmtbuf, sizeof(fmtbuf), "%02x", (unsigned)data[i]);
memcpy(linebuf + hexoff, fmtbuf, 2);
size_t chroff = 16 + 1 + 3 * 16 + 1 + lineoff;
linebuf[chroff] =
(0x20 <= data[i] && data[i] < 0x7F ? data[i] : '.');
outlinelen = chroff + 1;
}
linebuf[outlinelen] = '\0';
cout << prefix << linebuf << endl;
startaddr += linesize;
size -= linesize;
}
}
static void regdump(const std::vector<unsigned char> &val,
const std::vector<unsigned char> &def)
{
for (size_t i = 0, e = min(val.size(), def.size()); i < e; i++) {
if (i)
cout << " ";
if (def[i]) {
char fmtbuf[3];
snprintf(fmtbuf, sizeof(fmtbuf), "%02x", (unsigned)val[i]);
cout << fmtbuf;
} else {
cout << "..";
}
}
}
static void dump_memory_at_line(const IndexNavigator &IN, unsigned trace_line,
const std::string &prefix)
{
SeqOrderPayload node;
if (!IN.node_at_line(trace_line, &node)) {
cerr << "Unable to find a node at line " << trace_line << "\n";
exit(1);
}
off_t memroot = node.memory_root;
unsigned iflags = IN.get_iflags(memroot);
const void *outdata;
Addr outaddr;
size_t outsize;
unsigned outline;
Addr readaddr = 0;
size_t readsize = 0;
while (IN.getmem_next(memroot, 'm', readaddr, readsize, &outdata, &outaddr,
&outsize, &outline)) {
cout << prefix << "Memory last modified at line " << outline << ":"
<< endl;
hexdump(outdata, outsize, outaddr, prefix);
readsize -= outaddr + outsize - readaddr;
readaddr = outaddr + outsize;
if (!readaddr)
break;
}
for (const auto ®fam : reg_families) {
for (unsigned i = 0; i < regfam.nregs; i++) {
RegisterId reg{regfam.prefix, i};
size_t size = reg_size(reg);
vector<unsigned char> val(size), def(size);
unsigned mod_line = IN.getmem(memroot, 'r', reg_offset(reg, iflags),
size, &val[0], &def[0]);
bool print = false;
for (auto c : def) {
if (c) {
print = true;
break;
}
}
if (print) {
cout << prefix << reg_name(reg) << ", last modified at line "
<< mod_line << ": ";
regdump(val, def);
cout << endl;
}
}
}
}
int main(int argc, char **argv)
{
enum class Mode {
None,
Header,
SeqVisit,
SeqVisitWithMem,
SeqWalk,
MemVisit,
MemWalk,
MemSubVisit,
MemSubWalk,
ByPCVisit,
ByPCWalk,
RegMap,
FullMemByLine,
} mode = Mode::None;
off_t root;
unsigned trace_line;
unsigned iflags = 0;
bool got_iflags = false;
Argparse ap("tarmac-indextool", argc, argv);
TarmacUtility tu(ap, false, false);
ap.optnoval({"--header"}, "dump file header",
[&]() { mode = Mode::Header; });
ap.optnoval({"--seq"}, "dump logical content of the sequential order tree",
[&]() { mode = Mode::SeqVisit; });
ap.optnoval({"--seq-with-mem"},
"dump logical content of the sequential "
"order tree, and memory contents at each node",
[&]() { mode = Mode::SeqVisitWithMem; });
ap.optnoval({"--seqtree"},
"dump physical structure of the sequential "
"order tree",
[&]() { mode = Mode::SeqWalk; });
ap.optval({"--mem"}, "OFFSET",
"dump logical content of memory tree with "
"root at OFFSET",
[&](const string &s) {
mode = Mode::MemVisit;
root = parseint(s);
});
ap.optval({"--memtree"}, "OFFSET",
"dump physical structure of a memory "
"tree with root at OFFSET",
[&](const string &s) {
mode = Mode::MemWalk;
root = parseint(s);
});
ap.optval({"--memsub"}, "OFFSET",
"dump logical content of a memory "
"subtree with root at OFFSET",
[&](const string &s) {
mode = Mode::MemSubVisit;
root = parseint(s);
});
ap.optval({"--memsubtree"}, "OFFSET",
"dump physical structure of a memory"
" subtree with root at OFFSET",
[&](const string &s) {
mode = Mode::MemSubWalk;
root = parseint(s);
});
ap.optnoval({"--bypc"}, "dump logical content of the by-PC tree",
[&]() { mode = Mode::ByPCVisit; });
ap.optnoval({"--bypctree"}, "dump physical structure of the by-PC tree",
[&]() { mode = Mode::ByPCWalk; });
ap.optnoval({"--regmap"}, "write a memory map of the register space",
[&]() { mode = Mode::RegMap; });
ap.optval({"--iflags"}, "FLAGS",
"(for --regmap) specify iflags context "
"to retrieve registers",
[&](const string &s) {
got_iflags = true;
iflags = parseint(s);
});
ap.optnoval({"--omit-index-offsets"},
"do not dump offsets in index file "
"(so that output is more stable when index format changes)",
[&]() { omit_index_offsets = true; });
ap.optval({"--full-mem-at-line"}, "OFFSET",
"dump full content of memory "
"tree corresponding to a particular line of the trace file",
[&](const string &s) {
mode = Mode::FullMemByLine;
trace_line = parseint(s);
});
ap.parse([&]() {
if (mode == Mode::None && !tu.only_index())
throw ArgparseError("expected an option describing a query");
if (mode != Mode::RegMap && tu.trace.tarmac_filename.empty())
throw ArgparseError("expected a trace file name");
});
cout << showbase; // ensure all hex values have a leading 0x
// Modes that don't need a trace file
switch (mode) {
case Mode::RegMap: {
dump_registers(got_iflags, iflags);
return 0;
}
default:
// Exit this switch and go on to load the trace file
break;
}
tu.setup();
const IndexNavigator IN(tu.trace);
switch (mode) {
case Mode::None:
case Mode::RegMap:
assert(false && "This should have been ruled out above");
case Mode::Header: {
cout << "Endianness: " << (IN.index.isBigEndian() ? "big" : "little")
<< endl;
cout << "Architecture: "
<< (IN.index.isAArch64() ? "AArch64" : "AArch32") << endl;
cout << "Root of sequential order tree: " << IN.index.seqroot << endl;
cout << "Root of by-PC tree: " << IN.index.bypcroot << endl;
cout << "Line number adjustment for file header: "
<< IN.index.lineno_offset << endl;
break;
}
case Mode::SeqVisit:
case Mode::SeqVisitWithMem: {
SeqTreeDumper d(IN);
d.dump_memory = (mode == Mode::SeqVisitWithMem);
IN.index.seqtree.visit(IN.index.seqroot, d.visitor);
break;
}
case Mode::SeqWalk: {
SeqTreeDumper d(IN);
IN.index.seqtree.walk(IN.index.seqroot, WalkOrder::Preorder, d.walker);
break;
}
case Mode::MemVisit: {
MemTreeDumper d(IN);
IN.index.memtree.visit(root, d.visitor);
break;
}
case Mode::MemWalk: {
MemTreeDumper d(IN);
IN.index.memtree.walk(root, WalkOrder::Preorder, d.walker);
break;
}
case Mode::MemSubVisit: {
MemSubtreeDumper d(IN);
IN.index.memsubtree.visit(root, d.visitor);
break;
}
case Mode::MemSubWalk: {
MemSubtreeDumper d(IN);
IN.index.memsubtree.walk(root, WalkOrder::Preorder, d.walker);
break;
}
case Mode::ByPCVisit: {
ByPCTreeDumper d(IN);
IN.index.bypctree.visit(IN.index.bypcroot, d.visitor);
break;
}
case Mode::ByPCWalk: {
ByPCTreeDumper d(IN);
IN.index.bypctree.walk(IN.index.bypcroot, WalkOrder::Preorder,
d.walker);
break;
}
case Mode::FullMemByLine: {
dump_memory_at_line(IN, trace_line, "");
break;
}
}
return 0;
}
| 32.129032 | 80 | 0.525961 | Arnaud-de-Grandmaison-ARM |
1d649dac6a42226fa94ae240b8186b2955d1311a | 313 | cpp | C++ | srcgen/readme_gen.t.cpp | oleg-rabaev/cppa2z | f6ca795f5817901b075bf5b7fb43bd0f5b85f702 | [
"BSL-1.0"
] | 62 | 2016-10-05T11:31:50.000Z | 2021-09-07T06:20:40.000Z | srcgen/readme_gen.t.cpp | oleg-rabaev/cppa2z | f6ca795f5817901b075bf5b7fb43bd0f5b85f702 | [
"BSL-1.0"
] | 29 | 2021-02-14T20:12:46.000Z | 2021-05-09T17:56:27.000Z | srcgen/readme_gen.t.cpp | oleg-rabaev/cppa2z | f6ca795f5817901b075bf5b7fb43bd0f5b85f702 | [
"BSL-1.0"
] | 1 | 2021-01-31T13:40:39.000Z | 2021-01-31T13:40:39.000Z | #include <catch.hpp>
#include <readme_gen.h>
#include <iostream>
#include <fstream>
using namespace std;
namespace srcgen {
TEST_CASE( "readme_gen.generate" ) {
ofstream fout("README.md");
auto& out = fout;
//auto& out = cout;
readme_gen gen(out);
gen.generate();
}
} // namespace srcgen
| 15.65 | 36 | 0.654952 | oleg-rabaev |
1d68103ce4511c1b958913c200f8ae26f60f6791 | 2,212 | cpp | C++ | raygame/Grain.cpp | DynashEtvala/SandGame | 16b286533c2f8f6a20ebead2475e2c70d7d7cd56 | [
"MIT"
] | null | null | null | raygame/Grain.cpp | DynashEtvala/SandGame | 16b286533c2f8f6a20ebead2475e2c70d7d7cd56 | [
"MIT"
] | null | null | null | raygame/Grain.cpp | DynashEtvala/SandGame | 16b286533c2f8f6a20ebead2475e2c70d7d7cd56 | [
"MIT"
] | null | null | null | #include "Grain.h"
#include "MatManager.h"
Grain::Grain(int X, int Y) : GMaterial(X, Y)
{
grain = true;
density = 9;
}
Grain::~Grain()
{}
void Grain::Update(GMaterial*** matList, int bottom, int side, MatManager& m)
{
if (CanUpdate())
{
if (posY == bottom - 1)
{
m.PrepChange(posX, posY, AIR);
}
else if ((matList[posY + 1][posX]->liquid ? matList[posY + 1][posX]->CanUpdate() : true) && matList[posY + 1][posX]->density < density)
{
m.PrepChange(posX, posY, matList[posY + 1][posX]->type);
updatedFrame = true;
m.PrepChange(posX, posY + 1, type);
}
else if ((matList[posY + 1][posX + 1]->density < density && matList[posY][posX + 1]->density < density) || (matList[posY + 1][posX - 1]->density < density && matList[posY][posX - 1]->density < density))
{
if (((matList[posY + 1][posX + 1]->liquid ? matList[posY + 1][posX + 1]->CanUpdate() : true) && matList[posY + 1][posX + 1]->density < density && matList[posY][posX + 1]->density < density) && ((matList[posY + 1][posX - 1]->liquid ? matList[posY + 1][posX - 1]->CanUpdate() : true) && matList[posY + 1][posX - 1]->density < density && matList[posY][posX - 1]->density < density))
{
if (GetRandomValue(0, 1))
{
m.PrepChange(posX, posY, matList[posY + 1][posX + 1]->type);
updatedFrame = true;
m.PrepChange(posX + 1, posY + 1, type);
}
else
{
m.PrepChange(posX, posY, matList[posY + 1][posX - 1]->type);
updatedFrame = true;
m.PrepChange(posX - 1, posY + 1, type);
}
}
else if ((matList[posY + 1][posX + 1]->liquid ? matList[posY + 1][posX + 1]->CanUpdate() : true) && matList[posY + 1][posX + 1]->density < density && matList[posY][posX + 1]->density < density)
{
m.PrepChange(posX, posY, matList[posY + 1][posX + 1]->type);
updatedFrame = true;
m.PrepChange(posX + 1, posY + 1, type);
}
else if ((matList[posY + 1][posX - 1]->liquid ? matList[posY + 1][posX - 1]->CanUpdate() : true) && matList[posY + 1][posX - 1]->density < density && matList[posY][posX - 1]->density < density)
{
m.PrepChange(posX, posY, matList[posY + 1][posX - 1]->type);
updatedFrame = true;
m.PrepChange(posX - 1, posY + 1, type);
}
}
}
} | 36.866667 | 382 | 0.588156 | DynashEtvala |
1d69613537efd25d9bc893cf161343529d7c5984 | 5,409 | cpp | C++ | test/entity_system/aggregation_test.cpp | sheiny/ophidian | 037ae44357e0093d60b379513615b467c1f841cf | [
"Apache-2.0"
] | 40 | 2016-04-22T14:42:42.000Z | 2021-05-25T23:14:23.000Z | test/entity_system/aggregation_test.cpp | sheiny/ophidian | 037ae44357e0093d60b379513615b467c1f841cf | [
"Apache-2.0"
] | 64 | 2016-04-28T21:10:47.000Z | 2017-11-07T11:33:17.000Z | test/entity_system/aggregation_test.cpp | eclufsc/openeda | 037ae44357e0093d60b379513615b467c1f841cf | [
"Apache-2.0"
] | 25 | 2016-04-18T19:31:48.000Z | 2021-05-05T15:50:41.000Z | #include <catch.hpp>
#include <ophidian/entity_system/Aggregation.h>
using namespace ophidian::entity_system;
class EntityA : public EntityBase
{
public:
using EntityBase::EntityBase;
};
class EntityB : public EntityBase
{
public:
using EntityBase::EntityBase;
};
TEST_CASE("Aggregation: no parts", "[entity_system][Property][Aggregation][EntitySystem]")
{
EntitySystem<EntityA> sys1;
EntitySystem<EntityB> sys2;
Aggregation<EntityA, EntityB> aggregation(sys1, sys2);
auto en1 = sys1.add();
auto parts = aggregation.parts(en1);
REQUIRE(parts.begin() == parts.end());
REQUIRE(parts.empty());
REQUIRE(parts.size() == 0);
REQUIRE(aggregation.firstPart(en1) == EntityB());
}
TEST_CASE("Aggregation: add part", "[entity_system][Property][Aggregation][EntitySystem]")
{
EntitySystem<EntityA> sys1;
EntitySystem<EntityB> sys2;
Aggregation<EntityA, EntityB> aggregation(sys1, sys2);
auto en1 = sys1.add();
auto en2 = sys2.add();
REQUIRE(aggregation.whole(en2) == EntityA());
aggregation.addAssociation(en1, en2);
REQUIRE(aggregation.whole(en2) == en1);
auto parts = aggregation.parts(en1);
REQUIRE(parts.begin() != parts.end());
REQUIRE(!parts.empty());
REQUIRE(parts.size() == 1);
REQUIRE(std::count(parts.begin(), parts.end(), en2) == 1);
}
TEST_CASE("Aggregation: erase part", "[entity_system][Property][Aggregation][EntitySystem]")
{
EntitySystem<EntityA> sys1;
EntitySystem<EntityB> sys2;
Aggregation<EntityA, EntityB> aggregation(sys1, sys2);
auto en1 = sys1.add();
auto en2 = sys2.add();
aggregation.addAssociation(en1, en2);
sys2.erase(en2);
auto parts = aggregation.parts(en1);
REQUIRE(std::count(parts.begin(), parts.end(), en2) == 0);
}
TEST_CASE("Aggregation: erase whole", "[entity_system][Property][Aggregation][EntitySystem]")
{
EntitySystem<EntityA> sys1;
EntitySystem<EntityB> sys2;
Aggregation<EntityA, EntityB> aggregation(sys1, sys2);
auto en1 = sys1.add();
auto en2 = sys2.add();
aggregation.addAssociation(en1, en2);
sys1.erase(en1);
REQUIRE(aggregation.whole(en2) == EntityA());
}
TEST_CASE("Aggregation: add parts, erase one, keep others", "[entity_system][Property][Aggregation][EntitySystem]")
{
EntitySystem<EntityA> sys1;
EntitySystem<EntityB> sys2;
Aggregation<EntityA, EntityB> aggregation(sys1, sys2);
auto en1 = sys1.add();
auto part1 = sys2.add();
auto part2 = sys2.add();
auto part3 = sys2.add();
auto part4 = sys2.add();
auto part5 = sys2.add();
aggregation.addAssociation(en1, part1);
aggregation.addAssociation(en1, part2);
aggregation.addAssociation(en1, part3);
aggregation.addAssociation(en1, part4);
aggregation.addAssociation(en1, part5);
sys2.erase(part4);
REQUIRE(aggregation.whole(part1) == en1);
REQUIRE(aggregation.whole(part2) == en1);
REQUIRE(aggregation.whole(part3) == en1);
REQUIRE(aggregation.whole(part5) == en1);
REQUIRE(aggregation.parts(en1).size() == 4);
}
TEST_CASE("Aggregation: clear()", "[entity_system][Property][Aggregation][EntitySystem]")
{
INFO("Given an aggregation with 5 wholes and some parts");
EntitySystem<EntityA> sys1;
EntitySystem<EntityB> sys2;
Aggregation<EntityA, EntityB> aggregation(sys1, sys2);
std::vector<EntityA> wholes{ sys1.add(), sys1.add(), sys1.add(), sys1.add(), sys1.add() };
aggregation.addAssociation(wholes[0], sys2.add());
aggregation.addAssociation(wholes[0], sys2.add());
aggregation.addAssociation(wholes[1], sys2.add());
aggregation.addAssociation(wholes[1], sys2.add());
aggregation.addAssociation(wholes[1], sys2.add());
aggregation.addAssociation(wholes[2], sys2.add());
aggregation.addAssociation(wholes[3], sys2.add());
aggregation.addAssociation(wholes[3], sys2.add());
aggregation.addAssociation(wholes[3], sys2.add());
aggregation.addAssociation(wholes[3], sys2.add());
aggregation.addAssociation(wholes[4], sys2.add());
aggregation.addAssociation(wholes[4], sys2.add());
INFO("When the wholes system is cleared");
sys1.clear();
INFO("Then parts must be kept valid")
REQUIRE(sys2.size() == 12);
INFO("Then all parts must have nextPart == NIL")
{
std::list<EntityB> partsWithNextPart;
std::copy_if(sys2.begin(), sys2.end(), std::back_inserter(partsWithNextPart), [&aggregation](const EntityB & en)->bool
{
return aggregation.nextPart(en) != EntityB();
});
REQUIRE(partsWithNextPart.empty());
}
INFO("Then all parts must have whole == NIL")
{
std::list<EntityB> partsWithWhole;
std::copy_if(sys2.begin(), sys2.end(), std::back_inserter(partsWithWhole), [&aggregation](const EntityB & en)->bool
{
return aggregation.whole(en) != EntityA();
});
REQUIRE(partsWithWhole.empty());
}
}
TEST_CASE("Aggregation: lifetime managment", "[entity_system][Property][Aggregation][EntitySystem]")
{
std::unique_ptr<Aggregation<EntityA, EntityB> > agg;
EntitySystem<EntityA> sys1;
EntitySystem<EntityB> sys2;
REQUIRE_NOTHROW(sys1.add());
agg = std::move(std::make_unique<Aggregation<EntityA, EntityB> >(sys1, sys2));
REQUIRE_NOTHROW(sys1.add());
agg.reset();
REQUIRE_NOTHROW(sys1.add());
}
| 30.908571 | 126 | 0.66944 | sheiny |
1d6d9c273d5f7d9846b20218c85c3fc9f4fc1cda | 116 | cc | C++ | code/cmake_gtest/hello_test.cc | iusyu/c_practic | 7428b8d37df09cb27bc9d66d1e34c81a973b6119 | [
"MIT"
] | null | null | null | code/cmake_gtest/hello_test.cc | iusyu/c_practic | 7428b8d37df09cb27bc9d66d1e34c81a973b6119 | [
"MIT"
] | null | null | null | code/cmake_gtest/hello_test.cc | iusyu/c_practic | 7428b8d37df09cb27bc9d66d1e34c81a973b6119 | [
"MIT"
] | null | null | null | #include<gtest/gtest.h>
TEST(HelloTest, BaseAssertions) {
EXPECT_STRNE("Hello", "World");
EXPECT_EQ(4*7, 28);
}
| 14.5 | 33 | 0.689655 | iusyu |
1d6f00d0db2a9d242e151aace57d04d195111936 | 855 | cxx | C++ | Plugins/Mipf_Plugin_ModelExporter/Mipf_Plugin_ModelExporterActivator.cxx | linson7017/MIPF | adf982ae5de69fca9d6599fbbbd4ca30f4ae9767 | [
"ECL-2.0",
"Apache-2.0"
] | 4 | 2017-04-13T06:01:49.000Z | 2019-12-04T07:23:53.000Z | Plugins/Mipf_Plugin_ModelExporter/Mipf_Plugin_ModelExporterActivator.cxx | linson7017/MIPF | adf982ae5de69fca9d6599fbbbd4ca30f4ae9767 | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2017-10-27T02:00:44.000Z | 2017-10-27T02:00:44.000Z | Plugins/Mipf_Plugin_ModelExporter/Mipf_Plugin_ModelExporterActivator.cxx | linson7017/MIPF | adf982ae5de69fca9d6599fbbbd4ca30f4ae9767 | [
"ECL-2.0",
"Apache-2.0"
] | 2 | 2017-09-06T01:59:07.000Z | 2019-12-04T07:23:54.000Z | #include "Mipf_Plugin_ModelExporterActivator.h"
#include "ModelExporterView.h"
#include "Utils/PluginFactory.h"
QF_API QF::IQF_Activator* QF::QF_CreatePluginActivator(QF::IQF_Main* pMain)
{
QF::IQF_Activator* pActivator = new Mipf_Plugin_ModelExporter_Activator(pMain);
//assert(pActivator);
return pActivator;
}
const char Mipf_Plugin_ModelExporter_Activator_ID[] = "Mipf_Plugin_ModelExporter_Activator_ID";
Mipf_Plugin_ModelExporter_Activator::Mipf_Plugin_ModelExporter_Activator(QF::IQF_Main* pMain):ActivatorBase(pMain)
{
}
bool Mipf_Plugin_ModelExporter_Activator::Init()
{
return true;
}
const char* Mipf_Plugin_ModelExporter_Activator::GetID()
{
return Mipf_Plugin_ModelExporter_Activator_ID;
}
void Mipf_Plugin_ModelExporter_Activator::Register()
{
REGISTER_PLUGIN("ModelExporterWidget", ModelExporterView);
} | 26.71875 | 114 | 0.803509 | linson7017 |
1d700e704746fe72855cd291bcb6c139df468253 | 15,418 | cpp | C++ | src/BossBallos.cpp | haya3218/cse2-tweaks | 48bccbd58240942ed5f5b288a90ef092820698c0 | [
"MIT"
] | null | null | null | src/BossBallos.cpp | haya3218/cse2-tweaks | 48bccbd58240942ed5f5b288a90ef092820698c0 | [
"MIT"
] | null | null | null | src/BossBallos.cpp | haya3218/cse2-tweaks | 48bccbd58240942ed5f5b288a90ef092820698c0 | [
"MIT"
] | null | null | null | // THIS IS DECOMPILED PROPRIETARY CODE - USE AT YOUR OWN RISK.
//
// The original code belongs to Daisuke "Pixel" Amaya.
//
// Modifications and custom code are under the MIT licence.
// See LICENCE.txt for details.
#include "BossBallos.h"
#include <stddef.h>
#include "WindowsWrapper.h"
#include "Boss.h"
#include "Flash.h"
#include "Frame.h"
#include "Game.h"
#include "MyChar.h"
#include "MycHit.h"
#include "MycParam.h"
#include "NpChar.h"
#include "Sound.h"
static void ActBossChar_Eye(NPCHAR *npc)
{
RECT rcLeft[5] = {
{272, 0, 296, 16},
{272, 16, 296, 32},
{272, 32, 296, 48},
{0, 0, 0, 0},
{240, 16, 264, 32},
};
RECT rcRight[5] = {
{296, 0, 320, 16},
{296, 16, 320, 32},
{296, 32, 320, 48},
{0, 0, 0, 0},
{240, 32, 264, 48},
};
switch (npc->act_no)
{
case 100:
npc->act_no = 101;
npc->ani_no = 0;
npc->ani_wait = 0;
// Fallthrough
case 101:
++npc->ani_wait;
if (npc->ani_wait > 2)
{
npc->ani_wait = 0;
++npc->ani_no;
}
if (npc->ani_no > 2)
npc->act_no = 102;
break;
case 102:
npc->ani_no = 3;
break;
case 200:
npc->act_no = 201;
npc->ani_no = 3;
npc->ani_wait = 0;
// Fallthrough
case 201:
++npc->ani_wait;
if (npc->ani_wait > 2)
{
npc->ani_wait = 0;
--npc->ani_no;
}
if (npc->ani_no <= 0)
npc->act_no = 202;
break;
case 300:
npc->act_no = 301;
npc->ani_no = 4;
if (npc->direct == 0)
SetDestroyNpChar(npc->x - (4 * 0x200), npc->y, 0x800, 10);
else
SetDestroyNpChar(npc->x + (4 * 0x200), npc->y, 0x800, 10);
break;
}
if (npc->direct == 0)
npc->x = gBoss[0].x - (24 * 0x200);
else
npc->x = gBoss[0].x + (24 * 0x200);
npc->y = gBoss[0].y - (36 * 0x200);
if (npc->act_no >= 0 && npc->act_no < 300)
{
if (npc->ani_no != 3)
npc->bits &= ~NPC_SHOOTABLE;
else
npc->bits |= NPC_SHOOTABLE;
}
if (npc->direct == 0)
npc->rect = rcLeft[npc->ani_no];
else
npc->rect = rcRight[npc->ani_no];
}
static void ActBossChar_Body(NPCHAR *npc)
{
RECT rc[4] = {
{0, 0, 120, 120},
{120, 0, 240, 120},
{0, 120, 120, 240},
{120, 120, 240, 240},
};
npc->x = gBoss[0].x;
npc->y = gBoss[0].y;
npc->rect = rc[npc->ani_no];
}
static void ActBossChar_HITAI(NPCHAR *npc) // "Hitai" = "forehead" or "brow" (according to Google Translate, anyway)
{
npc->x = gBoss[0].x;
npc->y = gBoss[0].y - (44 * 0x200);
}
static void ActBossChar_HARA(NPCHAR *npc) // "Hara" = "belly" or "stomach" (according to Google Translate, anyway)
{
npc->x = gBoss[0].x;
npc->y = gBoss[0].y;
}
void ActBossChar_Ballos(void)
{
NPCHAR *npc = gBoss;
static unsigned char flash;
int i;
int x, y;
switch (npc->act_no)
{
case 0:
// Initialize main boss
npc->act_no = 1;
npc->cond = 0x80;
npc->exp = 1;
npc->direct = gMirrorMode? 2:0;
npc->x = 320 * 0x200;
npc->y = -64 * 0x200;
npc->hit_voice = 54;
npc->hit.front = 32 * 0x200;
npc->hit.top = 48 * 0x200;
npc->hit.back = 32 * 0x200;
npc->hit.bottom = 48 * 0x200;
npc->bits = (NPC_IGNORE_SOLIDITY | NPC_SOLID_HARD | NPC_EVENT_WHEN_KILLED | NPC_SHOW_DAMAGE);
npc->size = 3;
npc->damage = 0;
npc->code_event = 1000;
npc->life = 800;
// Initialize eyes
gBoss[1].cond = 0x90;
gBoss[1].direct = 0;
gBoss[1].bits = NPC_IGNORE_SOLIDITY;
gBoss[1].life = 10000;
gBoss[1].view.front = 12 * 0x200;
gBoss[1].view.top = 0;
gBoss[1].view.back = 12 * 0x200;
gBoss[1].view.bottom = 16 * 0x200;
gBoss[1].hit.front = 12 * 0x200;
gBoss[1].hit.top = 0;
gBoss[1].hit.back = 12 * 0x200;
gBoss[1].hit.bottom = 16 * 0x200;
gBoss[2] = gBoss[1];
gBoss[2].direct = 2;
// Initialize the body
gBoss[3].cond = 0x90;
gBoss[3].bits = (NPC_SOLID_SOFT | NPC_INVULNERABLE | NPC_IGNORE_SOLIDITY);
gBoss[3].view.front = 60 * 0x200;
gBoss[3].view.top = 60 * 0x200;
gBoss[3].view.back = 60 * 0x200;
gBoss[3].view.bottom = 60 * 0x200;
gBoss[3].hit.front = 48 * 0x200;
gBoss[3].hit.top = 24 * 0x200;
gBoss[3].hit.back = 48 * 0x200;
gBoss[3].hit.bottom = 32 * 0x200;
gBoss[4].cond = 0x90;
gBoss[4].bits = (NPC_SOLID_SOFT | NPC_INVULNERABLE | NPC_IGNORE_SOLIDITY);
gBoss[4].hit.front = 32 * 0x200;
gBoss[4].hit.top = 8 * 0x200;
gBoss[4].hit.back = 32 * 0x200;
gBoss[4].hit.bottom = 8 * 0x200;
gBoss[5].cond = 0x90;
gBoss[5].bits = (NPC_INVULNERABLE | NPC_IGNORE_SOLIDITY | NPC_SOLID_HARD);
gBoss[5].hit.front = 32 * 0x200;
gBoss[5].hit.top = 0;
gBoss[5].hit.back = 32 * 0x200;
gBoss[5].hit.bottom = 48 * 0x200;
break;
case 100:
npc->act_no = 101;
npc->ani_no = 0;
npc->x = gMC.x;
SetNpChar(333, gMC.x, 304 * 0x200, 0, 0, 2, NULL, 0x100);
npc->act_wait = 0;
// Fallthrough
case 101:
++npc->act_wait;
if (npc->act_wait > 30)
npc->act_no = 102;
break;
case 102:
npc->ym += 0x40;
if (npc->ym > 0xC00)
npc->ym = 0xC00;
npc->y += npc->ym;
if (npc->y > (304 * 0x200) - npc->hit.bottom)
{
npc->y = (304 * 0x200) - npc->hit.bottom;
npc->ym = 0;
npc->act_no = 103;
npc->act_wait = 0;
SetQuake2(30);
PlaySoundObject(44, SOUND_MODE_PLAY);
if (gMC.y > npc->y + (48 * 0x200) && gMC.x < npc->x + (24 * 0x200) && gMC.x > npc->x - (24 * 0x200)){
int damage = 16;
if (damage == 1 && gbDamageModifier == 0.5){
damage = 1;
}
else if (gbDamageModifier == -1 ){
damage = 127;
}
else{
damage = damage * gbDamageModifier;
}
DamageMyChar(damage);
}
for (i = 0; i < 0x10; ++i)
{
x = npc->x + (Random(-40, 40) * 0x200);
SetNpChar(4, x, npc->y + (40 * 0x200), 0, 0, 0, NULL, 0x100);
}
if (gMC.flag & 8)
gMC.ym = -0x200;
}
break;
case 103:
++npc->act_wait;
if (npc->act_wait == 50)
{
npc->act_no = 104;
gBoss[1].act_no = 100;
gBoss[2].act_no = 100;
}
break;
case 200:
npc->act_no = 201;
npc->count1 = 0;
// Fallthrough
case 201:
npc->act_no = 203;
npc->xm = 0;
++npc->count1;
npc->hit.bottom = 48 * 0x200;
npc->damage = 0;
if (npc->count1 % 3 == 0)
npc->act_wait = 150;
else
npc->act_wait = 50;
// Fallthrough
case 203:
--npc->act_wait;
if (npc->act_wait <= 0)
{
npc->act_no = 204;
npc->ym = -0xC00;
if (npc->x < gMC.x)
npc->xm = 0x200;
else
npc->xm = -0x200;
}
break;
case 204:
if (npc->x < 80 * 0x200)
npc->xm = 0x200;
if (npc->x > 544 * 0x200)
npc->xm = -0x200;
npc->ym += 0x55;
if (npc->ym > 0xC00)
npc->ym = 0xC00;
npc->x += npc->xm;
npc->y += npc->ym;
if (npc->y > (304 * 0x200) - npc->hit.bottom)
{
npc->y = (304 * 0x200) - npc->hit.bottom;
npc->ym = 0;
npc->act_no = 201;
npc->act_wait = 0;
if (gMC.y > npc->y + (56 * 0x200)){
int damage = 16;
if (damage == 1 && gbDamageModifier == 0.5){
damage = 1;
}
else if (gbDamageModifier == -1 ){
damage = 127;
}
else{
damage = damage * gbDamageModifier;
}
DamageMyChar(damage);
}
if (gMC.flag & 8)
gMC.ym = -0x200;
SetQuake2(30);
PlaySoundObject(26, SOUND_MODE_PLAY);
SetNpChar(332, npc->x - (12 * 0x200), npc->y + (52 * 0x200), 0, 0, 0, NULL, 0x100);
SetNpChar(332, npc->x + (12 * 0x200), npc->y + (52 * 0x200), 0, 0, 2, NULL, 0x100);
PlaySoundObject(44, SOUND_MODE_PLAY);
for (i = 0; i < 0x10; ++i)
{
x = npc->x + (Random(-40, 40) * 0x200);
SetNpChar(4, x, npc->y + (40 * 0x200), 0, 0, 0, NULL, 0x100);
}
}
break;
case 220:
npc->act_no = 221;
npc->life = 1200;
gBoss[1].act_no = 200;
gBoss[2].act_no = 200;
npc->xm = 0;
npc->ani_no = 0;
npc->shock = 0;
flash = 0;
// Fallthrough
case 221:
npc->ym += 0x40;
if (npc->ym > 0xC00)
npc->ym = 0xC00;
npc->y += npc->ym;
if (npc->y > (304 * 0x200) - npc->hit.bottom)
{
npc->y = (304 * 0x200) - npc->hit.bottom;
npc->ym = 0;
npc->act_no = 222;
npc->act_wait = 0;
SetQuake2(30);
PlaySoundObject(26, SOUND_MODE_PLAY);
for (i = 0; i < 0x10; ++i)
{
x = npc->x + (Random(-40, 40) * 0x200);
SetNpChar(4, x, npc->y + (40 * 0x200), 0, 0, 0, NULL, 0x100);
}
if (gMC.flag & 8)
gMC.ym = -0x200;
}
break;
case 300:
npc->act_no = 301;
npc->act_wait = 0;
for (i = 0; i < 0x100; i += 0x40)
{
SetNpChar(342, npc->x, npc->y, 0, 0, i, npc, 90);
SetNpChar(342, npc->x, npc->y, 0, 0, i + 0x220, npc, 90);
}
SetNpChar(343, npc->x, npc->y, 0, 0, 0, npc, 0x18);
SetNpChar(344, npc->x - (24 * 0x200), npc->y - (36 * 0x200), 0, 0, 0, npc, 0x20);
SetNpChar(344, npc->x + (24 * 0x200), npc->y - (36 * 0x200), 0, 0, 2, npc, 0x20);
// Fallthrough
case 301:
npc->y += ((225 * 0x200) - npc->y) / 8;
++npc->act_wait;
if (npc->act_wait > 50)
{
npc->act_no = 310;
npc->act_wait = 0;
}
break;
case 311:
npc->direct = gMirrorMode? 2:0;
npc->xm = -0x3AA;
npc->ym = 0;
npc->x += npc->xm;
if (npc->x < 111 * 0x200)
{
npc->x = 111 * 0x200;
npc->act_no = 312;
}
break;
case 312:
npc->direct = 1;
npc->ym = -0x3AA;
npc->xm = 0;
npc->y += npc->ym;
if (npc->y < 111 * 0x200)
{
npc->y = 111 * 0x200;
npc->act_no = 313;
}
break;
case 313:
npc->direct = gMirrorMode? 0:2;
npc->xm = 0x3AA;
npc->ym = 0;
npc->x += npc->xm;
if (npc->x > 513 * 0x200)
{
npc->x = 513 * 0x200;
npc->act_no = 314;
}
if (npc->count1 != 0)
--npc->count1;
if (npc->count1 == 0 && npc->x > 304 * 0x200 && npc->x < 336 * 0x200)
npc->act_no = 400;
break;
case 314:
npc->direct = 3;
npc->ym = 0x3AA;
npc->xm = 0;
npc->y += npc->ym;
if (npc->y > 225 * 0x200)
{
npc->y = 225 * 0x200;
npc->act_no = 311;
}
break;
case 400:
npc->act_no = 401;
npc->act_wait = 0;
npc->xm = 0;
npc->ym = 0;
DeleteNpCharCode(339, FALSE);
// Fallthrough
case 401:
npc->y += ((159 * 0x200) - npc->y) / 8;
++npc->act_wait;
if (npc->act_wait > 50)
{
npc->act_wait = 0;
npc->act_no = 410;
for (i = 0; i < 0x100; i += 0x20)
SetNpChar(346, npc->x, npc->y, 0, 0, i, npc, 0x50);
SetNpChar(343, npc->x, npc->y, 0, 0, 0, npc, 0x18);
SetNpChar(344, npc->x - (24 * 0x200), npc->y - (36 * 0x200), 0, 0, 0, npc, 0x20);
SetNpChar(344, npc->x + (24 * 0x200), npc->y - (36 * 0x200), 0, 0, 2, npc, 0x20);
}
break;
case 410:
++npc->act_wait;
if (npc->act_wait > 50)
{
npc->act_wait = 0;
npc->act_no = 411;
}
break;
case 411:
++npc->act_wait;
if (npc->act_wait % 30 == 1)
{
x = (((npc->act_wait / 30) * 2) + 2) * 0x10 * 0x200;
SetNpChar(348, x, 336 * 0x200, 0, 0, 0, NULL, 0x180);
}
if (npc->act_wait / 3 % 2)
PlaySoundObject(26, SOUND_MODE_PLAY);
if (npc->act_wait > 540)
npc->act_no = 420;
break;
case 420:
npc->act_no = 421;
npc->act_wait = 0;
npc->ani_wait = 0;
SetQuake2(30);
PlaySoundObject(35, SOUND_MODE_PLAY);
gBoss[1].act_no = 102;
gBoss[2].act_no = 102;
for (i = 0; i < 0x100; ++i)
{
x = npc->x + (Random(-60, 60) * 0x200);
y = npc->y + (Random(-60, 60) * 0x200);
SetNpChar(4, x, y, 0, 0, 0, NULL, 0);
}
// Fallthrough
case 421:
++npc->ani_wait;
if (npc->ani_wait > 500)
{
npc->ani_wait = 0;
npc->act_no = 422;
}
break;
case 422:
++npc->ani_wait;
if (npc->ani_wait > 200)
{
npc->ani_wait = 0;
npc->act_no = 423;
}
break;
case 423:
++npc->ani_wait;
if (npc->ani_wait > 20)
{
npc->ani_wait = 0;
npc->act_no = 424;
}
break;
case 424:
++npc->ani_wait;
if (npc->ani_wait > 200)
{
npc->ani_wait = 0;
npc->act_no = 425;
}
break;
case 425:
++npc->ani_wait;
if (npc->ani_wait > 500)
{
npc->ani_wait = 0;
npc->act_no = 426;
}
break;
case 426:
++npc->ani_wait;
if (npc->ani_wait > 200)
{
npc->ani_wait = 0;
npc->act_no = 427;
}
break;
case 427:
++npc->ani_wait;
if (npc->ani_wait > 20)
{
npc->ani_wait = 0;
npc->act_no = 428;
}
break;
case 428:
++npc->ani_wait;
if (npc->ani_wait > 200)
{
npc->ani_wait = 0;
npc->act_no = 421;
}
break;
case 1000:
npc->act_no = 1001;
npc->act_wait = 0;
gBoss[1].act_no = 300;
gBoss[2].act_no = 300;
#ifndef FIX_BUGS
// This code makes absolutely no sense.
// Luckily, it doesn't cause any bugs.
gBoss[1].act_no &= ~(NPC_SOLID_SOFT | NPC_SOLID_HARD);
gBoss[2].act_no &= ~(NPC_SOLID_SOFT | NPC_SOLID_HARD);
#endif
gBoss[0].bits &= ~(NPC_SOLID_SOFT | NPC_SOLID_HARD);
gBoss[3].bits &= ~(NPC_SOLID_SOFT | NPC_SOLID_HARD);
gBoss[4].bits &= ~(NPC_SOLID_SOFT | NPC_SOLID_HARD);
gBoss[5].bits &= ~(NPC_SOLID_SOFT | NPC_SOLID_HARD);
// Fallthrough
case 1001:
++gBoss[0].act_wait;
if (gBoss[0].act_wait % 12 == 0)
PlaySoundObject(44, SOUND_MODE_PLAY);
SetDestroyNpChar(gBoss[0].x + (Random(-60, 60) * 0x200), gBoss[0].y + (Random(-60, 60) * 0x200), 1, 1);
if (gBoss[0].act_wait > 150)
{
gBoss[0].act_wait = 0;
gBoss[0].act_no = 1002;
SetFlash(gBoss[0].x, gBoss[0].y, FLASH_MODE_EXPLOSION);
PlaySoundObject(35, SOUND_MODE_PLAY);
}
break;
case 1002:
SetQuake2(40);
++gBoss[0].act_wait;
if (gBoss[0].act_wait == 50)
{
gBoss[0].cond = 0;
gBoss[1].cond = 0;
gBoss[2].cond = 0;
gBoss[3].cond = 0;
gBoss[4].cond = 0;
gBoss[5].cond = 0;
DeleteNpCharCode(350, TRUE);
DeleteNpCharCode(348, TRUE);
}
break;
}
if (npc->act_no > 420 && npc->act_no < 500)
{
gBoss[3].bits |= NPC_SHOOTABLE;
gBoss[4].bits |= NPC_SHOOTABLE;
gBoss[5].bits |= NPC_SHOOTABLE;
++npc->act_wait;
if (npc->act_wait > 300)
{
npc->act_wait = 0;
if (gMC.x > npc->x)
{
for (i = 0; i < 8; ++i)
{
x = ((156 + Random(-4, 4)) * 0x200 * 0x10) / 4;
y = (Random(8, 68) * 0x200 * 0x10) / 4;
SetNpChar(350, x, y, 0, 0, 0, NULL, 0x100);
}
}
else
{
for (i = 0; i < 8; ++i)
{
x = (Random(-4, 4) * 0x200 * 0x10) / 4;
y = (Random(8, 68) * 0x200 * 0x10) / 4;
SetNpChar(350, x, y, 0, 0, 2, NULL, 0x100);
}
}
}
if (npc->act_wait == 270 || npc->act_wait == 280 || npc->act_wait == 290)
{
SetNpChar(353, npc->x, npc->y - (52 * 0x200), 0, 0, 1, NULL, 0x100);
PlaySoundObject(39, SOUND_MODE_PLAY);
for (i = 0; i < 4; ++i)
SetNpChar(4, npc->x, npc->y - (52 * 0x200), 0, 0, 0, NULL, 0x100);
}
if (npc->life > 500)
{
if (Random(0, 10) == 2)
{
x = npc->x + (Random(-40, 40) * 0x200);
y = npc->y + (Random(0, 40) * 0x200);
SetNpChar(270, x, y, 0, 0, 3, NULL, 0);
}
}
else
{
if (Random(0, 4) == 2)
{
x = npc->x + (Random(-40, 40) * 0x200);
y = npc->y + (Random(0, 40) * 0x200);
SetNpChar(270, x, y, 0, 0, 3, NULL, 0);
}
}
}
if (npc->shock != 0)
{
if (++flash / 2 % 2)
gBoss[3].ani_no = 1;
else
gBoss[3].ani_no = 0;
}
else
{
gBoss[3].ani_no = 0;
}
if (npc->act_no > 420)
gBoss[3].ani_no += 2;
ActBossChar_Eye(&gBoss[1]);
ActBossChar_Eye(&gBoss[2]);
ActBossChar_Body(&gBoss[3]);
ActBossChar_HITAI(&gBoss[4]);
ActBossChar_HARA(&gBoss[5]);
}
| 19.248439 | 116 | 0.530354 | haya3218 |
1d75d52fa51962008828179d04899833ebe4f7d2 | 13,646 | cpp | C++ | nlsCppSdk/jni/jniSpeechRecognizer.cpp | kaimingguo/alibabacloud-nls-cpp-sdk | e624eefd2f87c56e4340c35a834ebd14b96bb19c | [
"Apache-2.0"
] | 26 | 2019-06-02T15:22:01.000Z | 2022-03-11T06:54:23.000Z | nlsCppSdk/jni/jniSpeechRecognizer.cpp | kaimingguo/alibabacloud-nls-cpp-sdk | e624eefd2f87c56e4340c35a834ebd14b96bb19c | [
"Apache-2.0"
] | 8 | 2019-06-02T15:47:11.000Z | 2022-01-19T06:51:55.000Z | nlsCppSdk/jni/jniSpeechRecognizer.cpp | kaimingguo/alibabacloud-nls-cpp-sdk | e624eefd2f87c56e4340c35a834ebd14b96bb19c | [
"Apache-2.0"
] | 18 | 2019-06-02T13:00:17.000Z | 2022-01-21T13:12:29.000Z | #include <jni.h>
#include <string>
#include <cstdlib>
#include <vector>
#include "nlsClient.h"
#include "nlsEvent.h"
#include "sr/speechRecognizerRequest.h"
#include "log.h"
#include "NlsRequestWarpper.h"
#include "native-lib.h"
using namespace AlibabaNls;
using namespace AlibabaNls::utility;
extern "C" {
JNIEXPORT jlong JNICALL
Java_com_alibaba_idst_util_SpeechRecognizer_createRecognizerCallback(JNIEnv *env, jobject instance, jobject _callback);
//JNIEXPORT jlong JNICALL
//Java_com_alibaba_idst_util_SpeechRecognizer_createRecognizerCallback(JNIEnv *env, jobject instance);
JNIEXPORT jlong JNICALL
Java_com_alibaba_idst_util_SpeechRecognizer_buildRecognizerRequest(JNIEnv *env, jobject instance, jlong wrapper);
//JNIEXPORT jlong JNICALL
//Java_com_alibaba_idst_util_SpeechRecognizer_buildRecognizerRequest(JNIEnv *env, jobject instance, jobject _callback);
JNIEXPORT jint JNICALL
Java_com_alibaba_idst_util_SpeechRecognizer_start__J(JNIEnv *env, jobject instance, jlong id);
JNIEXPORT jint JNICALL
Java_com_alibaba_idst_util_SpeechRecognizer_stop__J(JNIEnv *env, jobject instance, jlong id);
JNIEXPORT jint JNICALL
Java_com_alibaba_idst_util_SpeechRecognizer_cancel__J(JNIEnv *env, jobject instance, jlong id);
JNIEXPORT jint JNICALL
Java_com_alibaba_idst_util_SpeechRecognizer_setToken__JLjava_lang_String_2(JNIEnv *env, jobject instance, jlong id, jstring token_);
JNIEXPORT jint JNICALL
Java_com_alibaba_idst_util_SpeechRecognizer_setUrl__JLjava_lang_String_2(JNIEnv *env, jobject instance, jlong id, jstring value);
JNIEXPORT jint JNICALL
Java_com_alibaba_idst_util_SpeechRecognizer_setAppKey__JLjava_lang_String_2(JNIEnv *env, jobject instance, jlong id, jstring value);
JNIEXPORT jint JNICALL
Java_com_alibaba_idst_util_SpeechRecognizer_setFormat__JLjava_lang_String_2(JNIEnv *env, jobject instance, jlong id, jstring value);
JNIEXPORT jint JNICALL
Java_com_alibaba_idst_util_SpeechRecognizer_setIntermediateResult(JNIEnv *env, jobject instance, jlong id, jboolean value);
JNIEXPORT jint JNICALL
Java_com_alibaba_idst_util_SpeechRecognizer_setInverseTextNormalization(JNIEnv *env, jobject instance, jlong id, jboolean value);
JNIEXPORT jint JNICALL
Java_com_alibaba_idst_util_SpeechRecognizer_setPunctuationPrediction(JNIEnv *env, jobject instance, jlong id, jboolean value);
JNIEXPORT jint JNICALL
Java_com_alibaba_idst_util_SpeechRecognizer_enableVoiceDetection(JNIEnv *env, jobject instance, jlong id, jboolean value);
JNIEXPORT jint JNICALL
Java_com_alibaba_idst_util_SpeechRecognizer_setMaxStartSilence(JNIEnv *env, jobject instance, jlong id, jint _value);
JNIEXPORT jint JNICALL
Java_com_alibaba_idst_util_SpeechRecognizer_setMaxEndSilence(JNIEnv *env, jobject instance, jlong id, jint _value);
JNIEXPORT jint JNICALL
Java_com_alibaba_idst_util_SpeechRecognizer_setSampleRate__JI(JNIEnv *env, jobject instance, jlong id, jint _value);
JNIEXPORT jint JNICALL
Java_com_alibaba_idst_util_SpeechRecognizer_setParams__JLjava_lang_String_2(JNIEnv *env, jobject instance, jlong id, jstring value_);
JNIEXPORT jint JNICALL
Java_com_alibaba_idst_util_SpeechRecognizer_setContext__JLjava_lang_String_2(JNIEnv *env, jobject instance, jlong id, jstring value_);
JNIEXPORT jint JNICALL
Java_com_alibaba_idst_util_SpeechRecognizer_addHttpHeader(JNIEnv *env, jobject instance, jlong id, jstring key_, jstring value_);
JNIEXPORT jint JNICALL
Java_com_alibaba_idst_util_SpeechRecognizer_setCustomizationId__JLjava_lang_String_2(JNIEnv *env, jobject instance, jlong id, jstring customizationId_);
JNIEXPORT jint JNICALL
Java_com_alibaba_idst_util_SpeechRecognizer_setVocabularyId__JLjava_lang_String_2(JNIEnv *env, jobject instance, jlong id, jstring vocabularyId_);
JNIEXPORT jint JNICALL
Java_com_alibaba_idst_util_SpeechRecognizer_sendAudio(JNIEnv *env, jobject instance, jlong id, jbyteArray data_, jint num_byte);
JNIEXPORT void JNICALL
Java_com_alibaba_idst_util_SpeechRecognizer_releaseCallback(JNIEnv *env, jobject instance, jlong id);
}
JNIEXPORT jlong JNICALL
Java_com_alibaba_idst_util_SpeechRecognizer_createRecognizerCallback(JNIEnv *env, jobject instance, jobject _callback){
jobject callback = env->NewGlobalRef(_callback);
// NlsRequestWarpper* wrapper = new NlsRequestWarpper(callback, &NlsRequestWarpper::_global_mtx);
NlsRequestWarpper* wrapper = new NlsRequestWarpper(callback);
env->GetJavaVM(&wrapper->_jvm);
pthread_mutex_lock(&NlsRequestWarpper::_global_mtx);
NlsRequestWarpper::_requestMap.insert(std::make_pair(wrapper, true));
LOG_DEBUG("Set request: %p true, size: %d", wrapper, NlsRequestWarpper::_requestMap.size());
pthread_mutex_unlock(&NlsRequestWarpper::_global_mtx);
return (jlong) wrapper;
}
JNIEXPORT jlong JNICALL
Java_com_alibaba_idst_util_SpeechRecognizer_buildRecognizerRequest(JNIEnv *env, jobject instance, jlong wrapper) {
NlsRequestWarpper* pWrapper = (NlsRequestWarpper*)wrapper;
SpeechRecognizerRequest* request = gnlsClient->createRecognizerRequest();
request->setOnTaskFailed(OnTaskFailed, pWrapper);
request->setOnRecognitionStarted(OnRecognizerStarted, pWrapper);
request->setOnRecognitionCompleted(OnRecognizerCompleted, pWrapper);
request->setOnRecognitionResultChanged(OnRecognizedResultChanged, pWrapper);
request->setOnChannelClosed(OnChannelClosed, pWrapper);
return (jlong) request;
}
JNIEXPORT jint JNICALL
Java_com_alibaba_idst_util_SpeechRecognizer_start__J(JNIEnv *env, jobject instance, jlong id) {
SpeechRecognizerRequest* request = (SpeechRecognizerRequest*) id;
int ret = request->start();
return ret;
}
JNIEXPORT jint JNICALL
Java_com_alibaba_idst_util_SpeechRecognizer_stop__J(JNIEnv *env, jobject instance, jlong id) {
SpeechRecognizerRequest* request = (SpeechRecognizerRequest*) id;
if (request != NULL) {
int ret = request->stop();
gnlsClient->releaseRecognizerRequest(request);
return ret;
}
return 0;
}
JNIEXPORT jint JNICALL
Java_com_alibaba_idst_util_SpeechRecognizer_cancel__J(JNIEnv *env, jobject instance, jlong id) {
SpeechRecognizerRequest* request = (SpeechRecognizerRequest*) id;
if (request != NULL) {
int ret = request->cancel();
gnlsClient->releaseRecognizerRequest(request);
return ret;
}
return 0;
}
JNIEXPORT jint JNICALL
Java_com_alibaba_idst_util_SpeechRecognizer_setToken__JLjava_lang_String_2(JNIEnv *env, jobject instance, jlong id,
jstring token_) {
if (token_ == NULL) {
return -1;
}
const char *token = env->GetStringUTFChars(token_, 0);
SpeechRecognizerRequest* request = (SpeechRecognizerRequest*) id;
int ret = request->setToken(token);
env->ReleaseStringUTFChars(token_, token);
return ret;
}
JNIEXPORT jint JNICALL
Java_com_alibaba_idst_util_SpeechRecognizer_setCustomizationId__JLjava_lang_String_2(JNIEnv *env, jobject instance, jlong id, jstring customizationId_) {
if (customizationId_ == NULL) {
return -1;
}
const char *customizationId = env->GetStringUTFChars(customizationId_, 0);
SpeechRecognizerRequest* request = (SpeechRecognizerRequest*) id;
int ret = request->setCustomizationId(customizationId);
env->ReleaseStringUTFChars(customizationId_, customizationId);
return ret;
}
JNIEXPORT jint JNICALL
Java_com_alibaba_idst_util_SpeechRecognizer_setVocabularyId__JLjava_lang_String_2(JNIEnv *env, jobject instance, jlong id, jstring vocabularyId_) {
if (vocabularyId_ == NULL) {
return -1;
}
const char *vocabularyId = env->GetStringUTFChars(vocabularyId_, 0);
SpeechRecognizerRequest* request = (SpeechRecognizerRequest*) id;
int ret = request->setVocabularyId(vocabularyId);
env->ReleaseStringUTFChars(vocabularyId_, vocabularyId);
return ret;
}
JNIEXPORT jint JNICALL
Java_com_alibaba_idst_util_SpeechRecognizer_setUrl__JLjava_lang_String_2(JNIEnv *env, jobject instance, jlong id, jstring _value) {
if (_value == NULL) {
return -1;
}
const char *value = env->GetStringUTFChars(_value, 0);
SpeechRecognizerRequest* request = (SpeechRecognizerRequest*) id;
int ret = request->setUrl(value);
env->ReleaseStringUTFChars(_value, value);
return ret;
}
JNIEXPORT jint JNICALL
Java_com_alibaba_idst_util_SpeechRecognizer_setAppKey__JLjava_lang_String_2(JNIEnv *env, jobject instance, jlong id, jstring _value) {
if (_value == NULL) {
return -1;
}
const char *value = env->GetStringUTFChars(_value, 0);
SpeechRecognizerRequest* request = (SpeechRecognizerRequest*) id;
int ret = request->setAppKey(value);
env->ReleaseStringUTFChars(_value, value);
return ret;
}
JNIEXPORT jint JNICALL
Java_com_alibaba_idst_util_SpeechRecognizer_setFormat__JLjava_lang_String_2(JNIEnv *env, jobject instance, jlong id, jstring _value) {
if (_value == NULL) {
return -1;
}
const char *value = env->GetStringUTFChars(_value, 0);
SpeechRecognizerRequest* request = (SpeechRecognizerRequest*) id;
int ret = request->setFormat(value);
env->ReleaseStringUTFChars(_value, value);
return ret;
}
JNIEXPORT jint JNICALL
Java_com_alibaba_idst_util_SpeechRecognizer_setSampleRate__JI(JNIEnv *env, jobject instance, jlong id, jint _value) {
SpeechRecognizerRequest* request = (SpeechRecognizerRequest*) id;
return request->setSampleRate(_value);
}
JNIEXPORT jint JNICALL
Java_com_alibaba_idst_util_SpeechRecognizer_setIntermediateResult(JNIEnv *env, jobject instance, jlong id, jboolean _value) {
SpeechRecognizerRequest* request = (SpeechRecognizerRequest*) id;
return request->setIntermediateResult(_value);
}
JNIEXPORT jint JNICALL
Java_com_alibaba_idst_util_SpeechRecognizer_setPunctuationPrediction(JNIEnv *env, jobject instance, jlong id, jboolean _value) {
SpeechRecognizerRequest* request = (SpeechRecognizerRequest*) id;
return request->setPunctuationPrediction(_value);
}
JNIEXPORT jint JNICALL
Java_com_alibaba_idst_util_SpeechRecognizer_setInverseTextNormalization(JNIEnv *env, jobject instance, jlong id, jboolean _value) {
SpeechRecognizerRequest* request = (SpeechRecognizerRequest*) id;
return request->setInverseTextNormalization(_value);
}
JNIEXPORT jint JNICALL
Java_com_alibaba_idst_util_SpeechRecognizer_enableVoiceDetection(JNIEnv *env, jobject instance, jlong id, jboolean value) {
SpeechRecognizerRequest* request = (SpeechRecognizerRequest*) id;
return request->setEnableVoiceDetection(value);
}
JNIEXPORT jint JNICALL
Java_com_alibaba_idst_util_SpeechRecognizer_setMaxStartSilence(JNIEnv *env, jobject instance, jlong id, jint value) {
SpeechRecognizerRequest* request = (SpeechRecognizerRequest*) id;
return request->setMaxStartSilence(value);
}
JNIEXPORT jint JNICALL
Java_com_alibaba_idst_util_SpeechRecognizer_setMaxEndSilence(JNIEnv *env, jobject instance, jlong id, jint value) {
SpeechRecognizerRequest* request = (SpeechRecognizerRequest*) id;
return request->setMaxEndSilence(value);
}
JNIEXPORT jint JNICALL
Java_com_alibaba_idst_util_SpeechRecognizer_setParams__JLjava_lang_String_2(JNIEnv *env, jobject instance, jlong id, jstring value_) {
if (value_ == NULL) {
return -1;
}
const char *value = env->GetStringUTFChars(value_, 0);
SpeechRecognizerRequest* request = (SpeechRecognizerRequest*) id;
int ret = request->setPayloadParam(value);
env->ReleaseStringUTFChars(value_, value);
return ret;
}
JNIEXPORT jint JNICALL
Java_com_alibaba_idst_util_SpeechRecognizer_setContext__JLjava_lang_String_2(JNIEnv *env, jobject instance, jlong id, jstring value_) {
if (value_ == NULL) {
return -1;
}
const char *value = env->GetStringUTFChars(value_, 0);
SpeechRecognizerRequest* request = (SpeechRecognizerRequest*) id;
int ret = request->setContextParam(value);
env->ReleaseStringUTFChars(value_, value);
return ret;
}
JNIEXPORT jint JNICALL
Java_com_alibaba_idst_util_SpeechRecognizer_addHttpHeader(JNIEnv *env, jobject instance, jlong id, jstring key_, jstring value_) {
if (key_ == NULL || value_ == NULL) {
return -1;
}
const char *key = env->GetStringUTFChars(key_, 0);
const char *value = env->GetStringUTFChars(value_, 0);
SpeechRecognizerRequest* request = (SpeechRecognizerRequest*) id;
int ret = request->AppendHttpHeaderParam(key, value);
env->ReleaseStringUTFChars(value_, value);
env->ReleaseStringUTFChars(key_, key);
return ret;
}
JNIEXPORT jint JNICALL
Java_com_alibaba_idst_util_SpeechRecognizer_sendAudio(JNIEnv *env, jobject instance, jlong id, jbyteArray data_, jint num_byte) {
jbyte *data = env->GetByteArrayElements(data_, NULL);
SpeechRecognizerRequest* request = (SpeechRecognizerRequest*) id;
int ret = request->sendAudio((uint8_t*)data, num_byte);
env->ReleaseByteArrayElements(data_, data, 0);
return ret;
}
JNIEXPORT void JNICALL
Java_com_alibaba_idst_util_SpeechRecognizer_releaseCallback(JNIEnv *env, jobject instance, jlong id) {
NlsRequestWarpper* wrapper = (NlsRequestWarpper*) id;
pthread_mutex_lock(&NlsRequestWarpper::_global_mtx);
if (NlsRequestWarpper::_requestMap.find(wrapper) != NlsRequestWarpper::_requestMap.end()) {
NlsRequestWarpper::_requestMap.erase(wrapper);
LOG_DEBUG("Set request: %p false, size: %d", wrapper, NlsRequestWarpper::_requestMap.size());
}
if (wrapper != NULL) {
LOG_DEBUG("Notify release sr callback.");
delete wrapper;
wrapper = NULL;
}
pthread_mutex_unlock(&NlsRequestWarpper::_global_mtx);
}
| 40.135294 | 153 | 0.785798 | kaimingguo |
1d75f9f0228674e6a665780321daf37f8f4b8afd | 1,983 | cpp | C++ | reverse_pair_leetcode.cpp | shivamkrs89/Sorting_problems | 4451103f52545df752b567fcbb575eb7e29947a6 | [
"MIT"
] | 1 | 2021-05-27T14:56:48.000Z | 2021-05-27T14:56:48.000Z | reverse_pair_leetcode.cpp | shivamkrs89/Sorting_problems | 4451103f52545df752b567fcbb575eb7e29947a6 | [
"MIT"
] | null | null | null | reverse_pair_leetcode.cpp | shivamkrs89/Sorting_problems | 4451103f52545df752b567fcbb575eb7e29947a6 | [
"MIT"
] | null | null | null | Given an integer array nums, return the number of reverse pairs in the array.
A reverse pair is a pair (i, j) where 0 <= i < j < nums.length and nums[i] > 2 * nums[j].
Example 1:
Input: nums = [1,3,2,3,1]
Output: 2
Example 2:
Input: nums = [2,4,3,5,1]
Output: 3
Constraints:
1 <= nums.length <= 5 * 104
-231 <= nums[i] <= 231 - 1
//code starts
class Solution {
public:
void merge(vector<int> &arr,int l,int m, int r,int& count)
{
// Your code here
int sz1=m-l+1;
int sz2=r-m;
int larr[sz1];
int rarr[sz2];
int i,j,k;
for(i=0;i<sz1;i++)
larr[i]=arr[l+i];
for(j=0;j<sz2;j++)
rarr[j]=arr[l+sz1+j];
j=0;
while(j<sz2){//checking for both subarray for number of reverse pairs
long long int sm=rarr[j];
sm*=2;
if(larr[sz1-1]<sm){
j++;continue;
}
for(i=0;i<sz1;i++)
{
// cout<<sz1<<' '<<sz2<<' '<<sm/2<<' '<<larr[i]<<'\n';
if(larr[i]>sm)
{
count+=(sz1-i);
break;
}
}
j++;
}
i=0,j=0,k=l;
while(i<sz1 && j<sz2)
{
if(larr[i]<rarr[j])
{
arr[k]=larr[i];
i++;
}
else
{
arr[k]=rarr[j];
j++;
}
k++;
}
while(i<sz1)
{
arr[k]=larr[i];
i++;k++;
}
while(j<sz2)
{
arr[k]=rarr[j];
j++;k++;
}
}
void mergeSort(vector<int> &arr, int l,int r,int& count) {
if (l < r) {
long long int m = l+(r-l)/2;
mergeSort(arr, l, m,count);
mergeSort(arr, m+1, r,count);
merge(arr, l, m, r,count);
}
}
int reversePairs(vector<int>& nums) {
int count=0;
mergeSort(nums,0,nums.size()-1,count);
return count;
}
};
| 18.192661 | 89 | 0.413011 | shivamkrs89 |
1d76ce7ac832293400bad337f5761086931d2f35 | 736 | cpp | C++ | Recursion/ReverseAstackusingRecursion.cpp | saurav-prakash/CB_DS_ALGO | 3f3133b31dbbda7d5229cd6c72c378ed08e35e6f | [
"MIT"
] | null | null | null | Recursion/ReverseAstackusingRecursion.cpp | saurav-prakash/CB_DS_ALGO | 3f3133b31dbbda7d5229cd6c72c378ed08e35e6f | [
"MIT"
] | null | null | null | Recursion/ReverseAstackusingRecursion.cpp | saurav-prakash/CB_DS_ALGO | 3f3133b31dbbda7d5229cd6c72c378ed08e35e6f | [
"MIT"
] | 2 | 2018-10-28T13:31:41.000Z | 2018-10-31T02:37:42.000Z | https://www.quora.com/How-can-we-reverse-a-stack-by-using-only-push-and-pop-operations-without-using-any-secondary-DS
#include<iostream>
#include<stack>
using namespace std;
stack<int> s;
int BottomInsert(int x){
if(s.size()==0) s.push(x);
else{
int a = s.top();
s.pop();
BottomInsert(x);
s.push(a);
}
}
int reverse(){
if(s.size()>0){
int x = s.top();
s.pop();
reverse();
BottomInsert(x);
}
}
int main()
{
int n,a;
cin>>n;
for(int i=0;i<n;i++){
cin>>a;
s.push(a);
}
reverse();
while(!s.empty()){for(int i=0;i<n;i++){
cout << s.top() <<endl;
s.pop();}
return 0;}
}
| 18.4 | 117 | 0.480978 | saurav-prakash |
1d798bfcd952ec393825f1afa2423c455c5143bf | 5,533 | hh | C++ | dune/xt/grid/functors/interfaces.hh | dune-community/dune-xt | da921524c6fff8d60c715cb4849a0bdd5f020d2b | [
"BSD-2-Clause"
] | 2 | 2020-02-08T04:08:52.000Z | 2020-08-01T18:54:14.000Z | dune/xt/grid/functors/interfaces.hh | dune-community/dune-xt | da921524c6fff8d60c715cb4849a0bdd5f020d2b | [
"BSD-2-Clause"
] | 35 | 2019-08-19T12:06:35.000Z | 2020-03-27T08:20:39.000Z | dune/xt/grid/functors/interfaces.hh | dune-community/dune-xt | da921524c6fff8d60c715cb4849a0bdd5f020d2b | [
"BSD-2-Clause"
] | 1 | 2020-02-08T04:09:34.000Z | 2020-02-08T04:09:34.000Z | // This file is part of the dune-xt project:
// https://zivgitlab.uni-muenster.de/ag-ohlberger/dune-community/dune-xt
// Copyright 2009-2021 dune-xt developers and contributors. All rights reserved.
// License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
// or GPL-2.0+ (http://opensource.org/licenses/gpl-license)
// with "runtime exception" (http://www.dune-project.org/license.html)
// Authors:
// Felix Schindler (2014, 2016 - 2018, 2020)
// René Fritze (2014 - 2020)
// Tobias Leibner (2020)
#ifndef DUNE_XT_GRID_FUNCTORS_INTERFACES_HH
#define DUNE_XT_GRID_FUNCTORS_INTERFACES_HH
#include <dune/xt/common/timedlogging.hh>
#include <dune/xt/grid/boundaryinfo.hh>
#include <dune/xt/grid/entity.hh>
#include <dune/xt/grid/intersection.hh>
#include <dune/xt/grid/type_traits.hh>
namespace Dune::XT::Grid {
template <class GL>
class ElementFunctor;
/**
* \brief Interface for functors which are applied to elements (codim 0 entities) of a grid layer by the Walker.
*
* \sa Walker
* \sa IntersectionFunctor
* \sa ElementAndIntersectionFunctor
*/
template <class GL>
class ElementFunctor : public Common::WithLogger<ElementFunctor<GL>>
{
static_assert(is_layer<GL>::value);
protected:
//! force implementors to use copy() method
public:
using GridViewType = GL;
using ElementType = extract_entity_t<GridViewType>;
using GV = GridViewType;
using E = ElementType;
ElementFunctor(const std::string& log_prefix = "",
const std::array<bool, 3>& logging_state = Common::default_logger_state())
: Common::WithLogger<ElementFunctor<GL>>(log_prefix.empty() ? "ElementFunctor" : log_prefix, logging_state)
{}
ElementFunctor(const ElementFunctor<GL>&) = default;
virtual ~ElementFunctor() = default;
virtual ElementFunctor<GridViewType>* copy() = 0;
virtual void prepare() {}
virtual void apply_local(const ElementType& /*element*/) {}
virtual void finalize() {}
}; // class ElementFunctor
template <class GL>
class IntersectionFunctor;
/**
* \brief Interface for functors which are applied to intersections (codim 1 entities) of a grid layer by the Walker.
*
* \sa Walker
* \sa ElementFunctor
* \sa ElementAndIntersectionFunctor
*/
template <class GL>
class IntersectionFunctor : public Common::WithLogger<IntersectionFunctor<GL>>
{
static_assert(is_layer<GL>::value);
protected:
//! force implementors to use copy() method
IntersectionFunctor(const IntersectionFunctor<GL>&) = default;
public:
using GridViewType = GL;
using ElementType = extract_entity_t<GridViewType>;
using IntersectionType = extract_intersection_t<GridViewType>;
using GV = GridViewType;
using E = ElementType;
using I = IntersectionType;
IntersectionFunctor(const std::string& log_prefix = "",
const std::array<bool, 3>& logging_state = Common::default_logger_state())
: Common::WithLogger<IntersectionFunctor<GL>>(log_prefix.empty() ? "IntersectionFunctor" : log_prefix,
logging_state)
{}
virtual ~IntersectionFunctor() = default;
virtual IntersectionFunctor<GridViewType>* copy() = 0;
virtual void prepare() {}
/**
* \note The meaning of outside_element depends on the circumstances. If intersection.neighbor() is true, the result
* of intersection.outside() is given (the meaning of which is different on inner, periodic or process boundary
* intersections). If intersection.neighbor() is false, intersection.inside() is given.
*/
virtual void apply_local(const IntersectionType& /*intersection*/,
const ElementType& /*inside_element*/,
const ElementType& /*outside_element*/)
{}
virtual void finalize() {}
}; // class IntersectionFunctor
template <class GL>
class ElementAndIntersectionFunctor;
/**
* \brief Interface for functors which are applied to entities and intersections of a grid layer by the Walker.
*
* \sa Walker
* \sa ElementFunctor
* \sa IntersectionFunctor
*/
template <class GL>
class ElementAndIntersectionFunctor : public Common::WithLogger<ElementAndIntersectionFunctor<GL>>
{
static_assert(is_layer<GL>::value);
protected:
//! force implementors to use copy() method
ElementAndIntersectionFunctor(const ElementAndIntersectionFunctor<GL>&) = default;
public:
using GridViewType = GL;
using ElementType = extract_entity_t<GridViewType>;
using IntersectionType = extract_intersection_t<GridViewType>;
using GV = GridViewType;
using E = ElementType;
using I = IntersectionType;
ElementAndIntersectionFunctor(const std::string& log_prefix = "",
const std::array<bool, 3>& logging_state = Common::default_logger_state())
: Common::WithLogger<ElementAndIntersectionFunctor<GL>>(
log_prefix.empty() ? "ElementAndIntersectionFunctor" : log_prefix, logging_state)
{}
virtual ~ElementAndIntersectionFunctor() = default;
virtual ElementAndIntersectionFunctor<GL>* copy() = 0;
virtual void prepare() {}
virtual void apply_local(const ElementType& /*element*/) {}
virtual void apply_local(const IntersectionType& /*intersection*/,
const ElementType& /*inside_element*/,
const ElementType& /*outside_element*/)
{}
virtual void finalize() {}
}; // class ElementAndIntersectionFunctor
} // namespace Dune::XT::Grid
#endif // DUNE_XT_GRID_FUNCTORS_INTERFACES_HH
| 31.259887 | 119 | 0.711007 | dune-community |
1d7b92d30ae02e61f242523442784963f4e61ca4 | 2,999 | cpp | C++ | src/net/ip4/icmpv4.cpp | pidEins/IncludeOS | b92339164a2ba61f03ca9a940b1e9a0907c08bea | [
"Apache-2.0"
] | 2 | 2017-04-28T17:29:25.000Z | 2017-05-03T07:36:22.000Z | src/net/ip4/icmpv4.cpp | lefticus/IncludeOS | b92339164a2ba61f03ca9a940b1e9a0907c08bea | [
"Apache-2.0"
] | null | null | null | src/net/ip4/icmpv4.cpp | lefticus/IncludeOS | b92339164a2ba61f03ca9a940b1e9a0907c08bea | [
"Apache-2.0"
] | 2 | 2017-05-01T18:16:28.000Z | 2019-11-15T19:48:01.000Z | // This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// 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 "../../api/net/ip4/icmpv4.hpp"
#include <os>
#include <net/inet_common.hpp>
#include <net/ip4/packet_ip4.hpp>
#include <net/util.hpp>
namespace net {
ICMPv4::ICMPv4(Inet<LinkLayer,IP4>& inet) :
inet_{inet}
{}
void ICMPv4::bottom(Packet_ptr pckt) {
if (pckt->size() < sizeof(full_header)) // Drop if not a full header
return;
full_header* full_hdr = reinterpret_cast<full_header*>(pckt->buffer());
icmp_header* hdr = &full_hdr->icmp_hdr;
#ifdef DEBUG
auto ip_address = full_hdr->ip_hdr.saddr.str().c_str();
#endif
switch(hdr->type) {
case (ICMP_ECHO):
debug("<ICMP> PING from %s\n", ip_address);
ping_reply(full_hdr, pckt->size());
break;
case (ICMP_ECHO_REPLY):
debug("<ICMP> PING Reply from %s\n", ip_address);
break;
}
}
void ICMPv4::ping_reply(full_header* full_hdr, uint16_t size) {
auto packet_ptr = inet_.create_packet(size);
auto buf = packet_ptr->buffer();
icmp_header* hdr = &reinterpret_cast<full_header*>(buf)->icmp_hdr;
hdr->type = ICMP_ECHO_REPLY;
hdr->code = 0;
hdr->identifier = full_hdr->icmp_hdr.identifier;
hdr->sequence = full_hdr->icmp_hdr.sequence;
debug("<ICMP> Rest of header IN: 0x%lx OUT: 0x%lx\n",
full_hdr->icmp_hdr.rest, hdr->rest);
debug("<ICMP> Transmitting answer\n");
// Populate response IP header
auto ip4_pckt = std::static_pointer_cast<PacketIP4>(packet_ptr);
ip4_pckt->init();
ip4_pckt->set_src(full_hdr->ip_hdr.daddr);
ip4_pckt->set_dst(full_hdr->ip_hdr.saddr);
ip4_pckt->set_protocol(IP4::IP4_ICMP);
ip4_pckt->set_ip_data_length(size);
// Copy payload from old to new packet
uint8_t* payload = reinterpret_cast<uint8_t*>(hdr) + sizeof(icmp_header);
uint8_t* source = reinterpret_cast<uint8_t*>(&full_hdr->icmp_hdr) + sizeof(icmp_header);
memcpy(payload, source, size - sizeof(full_header));
hdr->checksum = 0;
hdr->checksum = net::checksum(reinterpret_cast<uint16_t*>(hdr),
size - sizeof(full_header) + sizeof(icmp_header));
network_layer_out_(packet_ptr);
}
void icmp_default_out(Packet_ptr UNUSED(pckt)) {
debug("<ICMP IGNORE> No handler. DROP!\n");
}
} //< namespace net
| 32.247312 | 93 | 0.683228 | pidEins |
1d7f74ad7e40faa7a119dd70081c07dfd0ec00d4 | 11,275 | cpp | C++ | contrib/groff/src/utils/addftinfo/guess.cpp | ivadasz/DragonFlyBSD | 460227f342554313be3c7728ff679dd4a556cce9 | [
"BSD-3-Clause"
] | 3 | 2017-03-06T14:12:57.000Z | 2019-11-23T09:35:10.000Z | contrib/groff/src/utils/addftinfo/guess.cpp | jorisgio/DragonFlyBSD | d37cc9027d161f3e36bf2667d32f41f87606b2ac | [
"BSD-3-Clause"
] | null | null | null | contrib/groff/src/utils/addftinfo/guess.cpp | jorisgio/DragonFlyBSD | d37cc9027d161f3e36bf2667d32f41f87606b2ac | [
"BSD-3-Clause"
] | null | null | null | // -*- C++ -*-
/* Copyright (C) 1989, 1990, 1991, 1992, 2009
Free Software Foundation, Inc.
Written by James Clark ([email protected])
This file is part of groff.
groff 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.
groff is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
#include "guess.h"
void guess(const char *s, const font_params ¶m, char_metric *metric)
{
int &height = metric->height;
int &depth = metric->depth;
metric->ic = 0;
metric->left_ic = 0;
metric->sk = 0;
height = 0;
depth = 0;
if (s[0] == '\0' || (s[1] != '\0' && s[2] != '\0'))
goto do_default;
#define HASH(c1, c2) (((unsigned char)(c1) << 8) | (unsigned char)(c2))
switch (HASH(s[0], s[1])) {
default:
do_default:
if (metric->type & 01)
depth = param.desc_depth;
if (metric->type & 02)
height = param.asc_height;
else
height = param.x_height;
break;
case HASH('\\', '|'):
case HASH('\\', '^'):
case HASH('\\', '&'):
// these have zero height and depth
break;
case HASH('f', 0):
height = param.asc_height;
if (param.italic)
depth = param.desc_depth;
break;
case HASH('a', 0):
case HASH('c', 0):
case HASH('e', 0):
case HASH('m', 0):
case HASH('n', 0):
case HASH('o', 0):
case HASH('r', 0):
case HASH('s', 0):
case HASH('u', 0):
case HASH('v', 0):
case HASH('w', 0):
case HASH('x', 0):
case HASH('z', 0):
height = param.x_height;
break;
case HASH('i', 0):
height = param.x_height;
break;
case HASH('b', 0):
case HASH('d', 0):
case HASH('h', 0):
case HASH('k', 0):
case HASH('l', 0):
case HASH('F', 'i'):
case HASH('F', 'l'):
case HASH('f', 'f'):
case HASH('f', 'i'):
case HASH('f', 'l'):
height = param.asc_height;
break;
case HASH('t', 0):
height = param.asc_height;
break;
case HASH('g', 0):
case HASH('p', 0):
case HASH('q', 0):
case HASH('y', 0):
height = param.x_height;
depth = param.desc_depth;
break;
case HASH('j', 0):
height = param.x_height;
depth = param.desc_depth;
break;
case HASH('A', 0):
case HASH('B', 0):
case HASH('C', 0):
case HASH('D', 0):
case HASH('E', 0):
case HASH('F', 0):
case HASH('G', 0):
case HASH('H', 0):
case HASH('I', 0):
case HASH('J', 0):
case HASH('K', 0):
case HASH('L', 0):
case HASH('M', 0):
case HASH('N', 0):
case HASH('O', 0):
case HASH('P', 0):
case HASH('Q', 0):
case HASH('R', 0):
case HASH('S', 0):
case HASH('T', 0):
case HASH('U', 0):
case HASH('V', 0):
case HASH('W', 0):
case HASH('X', 0):
case HASH('Y', 0):
case HASH('Z', 0):
height = param.cap_height;
break;
case HASH('*', 'A'):
case HASH('*', 'B'):
case HASH('*', 'C'):
case HASH('*', 'D'):
case HASH('*', 'E'):
case HASH('*', 'F'):
case HASH('*', 'G'):
case HASH('*', 'H'):
case HASH('*', 'I'):
case HASH('*', 'K'):
case HASH('*', 'L'):
case HASH('*', 'M'):
case HASH('*', 'N'):
case HASH('*', 'O'):
case HASH('*', 'P'):
case HASH('*', 'Q'):
case HASH('*', 'R'):
case HASH('*', 'S'):
case HASH('*', 'T'):
case HASH('*', 'U'):
case HASH('*', 'W'):
case HASH('*', 'X'):
case HASH('*', 'Y'):
case HASH('*', 'Z'):
height = param.cap_height;
break;
case HASH('0', 0):
case HASH('1', 0):
case HASH('2', 0):
case HASH('3', 0):
case HASH('4', 0):
case HASH('5', 0):
case HASH('6', 0):
case HASH('7', 0):
case HASH('8', 0):
case HASH('9', 0):
case HASH('1', '2'):
case HASH('1', '4'):
case HASH('3', '4'):
height = param.fig_height;
break;
case HASH('(', 0):
case HASH(')', 0):
case HASH('[', 0):
case HASH(']', 0):
case HASH('{', 0):
case HASH('}', 0):
height = param.body_height;
depth = param.body_depth;
break;
case HASH('i', 's'):
height = (param.em*3)/4;
depth = param.em/4;
break;
case HASH('*', 'a'):
case HASH('*', 'e'):
case HASH('*', 'i'):
case HASH('*', 'k'):
case HASH('*', 'n'):
case HASH('*', 'o'):
case HASH('*', 'p'):
case HASH('*', 's'):
case HASH('*', 't'):
case HASH('*', 'u'):
case HASH('*', 'w'):
height = param.x_height;
break;
case HASH('*', 'd'):
case HASH('*', 'l'):
height = param.asc_height;
break;
case HASH('*', 'g'):
case HASH('*', 'h'):
case HASH('*', 'm'):
case HASH('*', 'r'):
case HASH('*', 'x'):
case HASH('*', 'y'):
height = param.x_height;
depth = param.desc_depth;
break;
case HASH('*', 'b'):
case HASH('*', 'c'):
case HASH('*', 'f'):
case HASH('*', 'q'):
case HASH('*', 'z'):
height = param.asc_height;
depth = param.desc_depth;
break;
case HASH('t', 's'):
height = param.x_height;
depth = param.desc_depth;
break;
case HASH('!', 0):
case HASH('?', 0):
case HASH('"', 0):
case HASH('#', 0):
case HASH('$', 0):
case HASH('%', 0):
case HASH('&', 0):
case HASH('*', 0):
case HASH('+', 0):
height = param.asc_height;
break;
case HASH('`', 0):
case HASH('\'', 0):
height = param.asc_height;
break;
case HASH('~', 0):
case HASH('^', 0):
case HASH('a', 'a'):
case HASH('g', 'a'):
height = param.asc_height;
break;
case HASH('r', 'u'):
case HASH('.', 0):
break;
case HASH(',', 0):
depth = param.comma_depth;
break;
case HASH('m', 'i'):
case HASH('-', 0):
case HASH('h', 'y'):
case HASH('e', 'm'):
height = param.x_height;
break;
case HASH(':', 0):
height = param.x_height;
break;
case HASH(';', 0):
height = param.x_height;
depth = param.comma_depth;
break;
case HASH('=', 0):
case HASH('e', 'q'):
height = param.x_height;
break;
case HASH('<', 0):
case HASH('>', 0):
case HASH('>', '='):
case HASH('<', '='):
case HASH('@', 0):
case HASH('/', 0):
case HASH('|', 0):
case HASH('\\', 0):
height = param.asc_height;
break;
case HASH('_', 0):
case HASH('u', 'l'):
case HASH('\\', '_'):
depth = param.em/4;
break;
case HASH('r', 'n'):
height = (param.em*3)/4;
break;
case HASH('s', 'r'):
height = (param.em*3)/4;
depth = param.em/4;
break;
case HASH('b', 'u'):
case HASH('s', 'q'):
case HASH('d', 'e'):
case HASH('d', 'g'):
case HASH('f', 'm'):
case HASH('c', 't'):
case HASH('r', 'g'):
case HASH('c', 'o'):
case HASH('p', 'l'):
case HASH('*', '*'):
case HASH('s', 'c'):
case HASH('s', 'l'):
case HASH('=', '='):
case HASH('~', '='):
case HASH('a', 'p'):
case HASH('!', '='):
case HASH('-', '>'):
case HASH('<', '-'):
case HASH('u', 'a'):
case HASH('d', 'a'):
case HASH('m', 'u'):
case HASH('d', 'i'):
case HASH('+', '-'):
case HASH('c', 'u'):
case HASH('c', 'a'):
case HASH('s', 'b'):
case HASH('s', 'p'):
case HASH('i', 'b'):
case HASH('i', 'p'):
case HASH('i', 'f'):
case HASH('p', 'd'):
case HASH('g', 'r'):
case HASH('n', 'o'):
case HASH('p', 't'):
case HASH('e', 's'):
case HASH('m', 'o'):
case HASH('b', 'r'):
case HASH('d', 'd'):
case HASH('r', 'h'):
case HASH('l', 'h'):
case HASH('o', 'r'):
case HASH('c', 'i'):
height = param.asc_height;
break;
case HASH('l', 't'):
case HASH('l', 'b'):
case HASH('r', 't'):
case HASH('r', 'b'):
case HASH('l', 'k'):
case HASH('r', 'k'):
case HASH('b', 'v'):
case HASH('l', 'f'):
case HASH('r', 'f'):
case HASH('l', 'c'):
case HASH('r', 'c'):
height = (param.em*3)/4;
depth = param.em/4;
break;
#if 0
case HASH('%', '0'):
case HASH('-', '+'):
case HASH('-', 'D'):
case HASH('-', 'd'):
case HASH('-', 'd'):
case HASH('-', 'h'):
case HASH('.', 'i'):
case HASH('.', 'j'):
case HASH('/', 'L'):
case HASH('/', 'O'):
case HASH('/', 'l'):
case HASH('/', 'o'):
case HASH('=', '~'):
case HASH('A', 'E'):
case HASH('A', 'h'):
case HASH('A', 'N'):
case HASH('C', 's'):
case HASH('D', 'o'):
case HASH('F', 'c'):
case HASH('F', 'o'):
case HASH('I', 'J'):
case HASH('I', 'm'):
case HASH('O', 'E'):
case HASH('O', 'f'):
case HASH('O', 'K'):
case HASH('O', 'm'):
case HASH('O', 'R'):
case HASH('P', 'o'):
case HASH('R', 'e'):
case HASH('S', '1'):
case HASH('S', '2'):
case HASH('S', '3'):
case HASH('T', 'P'):
case HASH('T', 'p'):
case HASH('Y', 'e'):
case HASH('\\', '-'):
case HASH('a', '"'):
case HASH('a', '-'):
case HASH('a', '.'):
case HASH('a', '^'):
case HASH('a', 'b'):
case HASH('a', 'c'):
case HASH('a', 'd'):
case HASH('a', 'e'):
case HASH('a', 'h'):
case HASH('a', 'o'):
case HASH('a', 't'):
case HASH('a', '~'):
case HASH('b', 'a'):
case HASH('b', 'b'):
case HASH('b', 's'):
case HASH('c', '*'):
case HASH('c', '+'):
case HASH('f', '/'):
case HASH('f', 'a'):
case HASH('f', 'c'):
case HASH('f', 'o'):
case HASH('h', 'a'):
case HASH('h', 'o'):
case HASH('i', 'j'):
case HASH('l', 'A'):
case HASH('l', 'B'):
case HASH('l', 'C'):
case HASH('m', 'd'):
case HASH('n', 'c'):
case HASH('n', 'e'):
case HASH('n', 'm'):
case HASH('o', 'A'):
case HASH('o', 'a'):
case HASH('o', 'e'):
case HASH('o', 'q'):
case HASH('p', 'l'):
case HASH('p', 'p'):
case HASH('p', 's'):
case HASH('r', '!'):
case HASH('r', '?'):
case HASH('r', 'A'):
case HASH('r', 'B'):
case HASH('r', 'C'):
case HASH('r', 's'):
case HASH('s', 'h'):
case HASH('s', 's'):
case HASH('t', 'e'):
case HASH('t', 'f'):
case HASH('t', 'i'):
case HASH('t', 'm'):
case HASH('~', '~'):
case HASH('v', 'S'):
case HASH('v', 'Z'):
case HASH('v', 's'):
case HASH('v', 'z'):
case HASH('^', 'A'):
case HASH('^', 'E'):
case HASH('^', 'I'):
case HASH('^', 'O'):
case HASH('^', 'U'):
case HASH('^', 'a'):
case HASH('^', 'e'):
case HASH('^', 'i'):
case HASH('^', 'o'):
case HASH('^', 'u'):
case HASH('`', 'A'):
case HASH('`', 'E'):
case HASH('`', 'I'):
case HASH('`', 'O'):
case HASH('`', 'U'):
case HASH('`', 'a'):
case HASH('`', 'e'):
case HASH('`', 'i'):
case HASH('`', 'o'):
case HASH('`', 'u'):
case HASH('~', 'A'):
case HASH('~', 'N'):
case HASH('~', 'O'):
case HASH('~', 'a'):
case HASH('~', 'n'):
case HASH('~', 'o'):
case HASH('\'', 'A'):
case HASH('\'', 'C'):
case HASH('\'', 'E'):
case HASH('\'', 'I'):
case HASH('\'', 'O'):
case HASH('\'', 'U'):
case HASH('\'', 'a'):
case HASH('\'', 'c'):
case HASH('\'', 'e'):
case HASH('\'', 'i'):
case HASH('\'', 'o'):
case HASH('\'', 'u')
case HASH(':', 'A'):
case HASH(':', 'E'):
case HASH(':', 'I'):
case HASH(':', 'O'):
case HASH(':', 'U'):
case HASH(':', 'Y'):
case HASH(':', 'a'):
case HASH(':', 'e'):
case HASH(':', 'i'):
case HASH(':', 'o'):
case HASH(':', 'u'):
case HASH(':', 'y'):
case HASH(',', 'C'):
case HASH(',', 'c'):
#endif
}
}
| 22.96334 | 72 | 0.478847 | ivadasz |
1d7f7d015cd3ec939392650f78f504b0c234e3de | 9,302 | cpp | C++ | wxMsOptionsDialog/wxMsOptionsDialog.cpp | tester0077/wxMS | da7b8aaefa7107f51b7ecab05c07c109d09f933f | [
"Zlib",
"MIT"
] | null | null | null | wxMsOptionsDialog/wxMsOptionsDialog.cpp | tester0077/wxMS | da7b8aaefa7107f51b7ecab05c07c109d09f933f | [
"Zlib",
"MIT"
] | null | null | null | wxMsOptionsDialog/wxMsOptionsDialog.cpp | tester0077/wxMS | da7b8aaefa7107f51b7ecab05c07c109d09f933f | [
"Zlib",
"MIT"
] | null | null | null | /*-----------------------------------------------------------------
* Name: wxMsOptionsDialog.cpp
* Purpose:
* Author: A. Wiegert
*
* Copyright:
* Licence: wxWidgets license
*---------------------------------------------------------------- */
/*----------------------------------------------------------------
* Standard wxWidgets headers
*---------------------------------------------------------------- */
// Note __VISUALC__ is defined by wxWidgets, not by MSVC IDE
// and thus won't be defined until some wxWidgets headers are included
#if defined( _MSC_VER )
# if defined ( _DEBUG )
// this statement NEEDS to go BEFORE all headers
# define _CRTDBG_MAP_ALLOC
# endif
#endif
#include "wxMsPreProcDefsh.h" // needs to be first
// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
/* For all others, include the necessary headers
* (this file is usually all you need because it
* includes almost all "standard" wxWidgets headers) */
#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif
// -----------------------------------------------------------------
#include "wxMsh.h"
#include "wxMsOptionsDialogh.h"
#include "wxMsFilterDialogh.h"
// ------------------------------------------------------------------
// Note __VISUALC__ is defined by wxWidgets, not by MSVC IDE
// and thus won't be defined until some wxWidgets headers are included
#if defined( _MSC_VER )
// only good for MSVC
// this block needs to AFTER all headers
#include <stdlib.h>
#include <crtdbg.h>
#ifdef _DEBUG
#ifndef DBG_NEW
#define DBG_NEW new ( _NORMAL_BLOCK , __FILE__ , __LINE__ )
#define new DBG_NEW
#endif
#endif
#endif
// ------------------------------------------------------------------
// Note: Check box update code is in the file for each page
// Constructor
wxMsOptionsDialog::wxMsOptionsDialog( wxWindow* parent ) :
MyDialogOptionsBase( parent )
{
m_pParent = parent;
}
// ------------------------------------------------------------------
bool wxMsOptionsDialog::TransferDataToWindow()
{
wxString wsT;
bool b;
// 'General' tab
// launch mail client after processing mail
b = m_iniPrefs.data[IE_LAUNCH_MAIL_CLIENT].dataCurrent.bVal;
m_checkBoxOptLaunchMailClient->SetValue( b );
// e-mail client path
m_textCtrlEmailClient->AppendText(
m_iniPrefs.data[IE_MAIL_CLIENT_PATH].dataCurrent.wsVal );
// check for new mail at startup
b = m_iniPrefs.data[IE_CHECK_MAIL_STARTUP].dataCurrent.bVal;
m_checkBoxOptCheckMailAtStart->SetValue( b );
// play sound when new mail arrives
b = m_iniPrefs.data[IE_SOUND_4_NEW_MAIL].dataCurrent.bVal;
m_checkBoxOptPlaySound->SetValue( b );
// schedule mail check
b = m_iniPrefs.data[IE_SCHEDULE_MAIL_CHECK].dataCurrent.bVal;
m_checkBoxScheduleMailCheck->SetValue( b );
// schedule mail check interval - minutes
m_spinCtrlMailCheckInterval->SetValue(
m_iniPrefs.data[IE_MAIL_CHECK_INTERVAL].dataCurrent.lVal );
// schedule mail srerver connection check
b = m_iniPrefs.data[IE_SCHEDULE_SERVER_CHECK].dataCurrent.bVal;
m_checkBoxScheduleMailCheck->SetValue( b );
// schedule mail server connection check interval - minutes
m_spinCtrlMailServerConectCheckInterval->SetValue(
m_iniPrefs.data[IE_SERVER_CHECK_INTERVAL].dataCurrent.lVal );
// check for updates at startup
m_checkBoxAutoUpdateCheck->SetValue(
m_iniPrefs.data[IE_OPT_AUTO_UPDATE_CHECK].dataCurrent.bVal );
// number of message lines to get with TOP request
m_spinCtrlMaxTopLines->SetValue(
m_iniPrefs.data[IE_OPT_MAX_TOP_LINES].dataCurrent.lVal );
// ------------------------------------------------------------------
// same for the 'Log' tab
b = m_iniPrefs.data[IE_LOG_FILE_WANTED].dataCurrent.bVal;
m_cbOptLogToFile->SetValue( b );
if ( b )
{
b = m_iniPrefs.data[IE_USE_LOG_DEF_DIR].dataCurrent.bVal;
m_cbOptLogUseDefaultPath->SetValue( b );
if ( b )
{
m_btnOptLogSelLogFilesDir->Enable( false );
m_tcOptLogFilesDestDir->Disable();
}
else
{
m_btnOptLogSelLogFilesDir->Enable();
m_tcOptLogFilesDestDir->Enable();
}
}
else
{
m_cbOptLogUseDefaultPath->Disable();
m_btnOptLogSelLogFilesDir->Enable( false );
m_tcOptLogFilesDestDir->Disable();
}
// the status has been set, just show the values
b = m_cbOptLogUseDefaultPath->GetValue();
if( b )
{
m_tcOptLogFilesDestDir->SetValue( wxStandardPaths::Get().GetDataDir() );
}
else
{
m_tcOptLogFilesDestDir->SetValue(
m_iniPrefs.data[IE_LOG_DIR_PATH].dataCurrent.wsVal );
}
m_tcOptLogFilesDestDir->SetValue(
m_iniPrefs.data[IE_LOG_DIR_PATH].dataCurrent.wsVal );
m_sliderOptLogVerbosity->SetValue(
m_iniPrefs.data[IE_LOG_VERBOSITY].dataCurrent.lVal );
// ------------------------------------------------------------------
// and the Filter tab
// list all of the current filters in m_checkListBoxFilter
UpDateFilterList();
// set the default status color
m_colourPickerStatusDefColor->SetColour(
m_iniPrefs.data[IE_STATUS_DEFAULT_COLOR].dataCurrent.wsVal );
return true;
}
// ------------------------------------------------------------------
/**
* Break out this code so we can update the list after modifying the
* filter list because of either additions, deletion or name changes.
*/
void wxMsOptionsDialog::UpDateFilterList()
{
wxArrayString wasChoices;
for ( std::vector<MyFilterListEl>::iterator it = wxGetApp().m_FilterList.begin();
it != wxGetApp().m_FilterList.end(); ++it )
{
// need to add them to the front to keep them in
// the same sequence as they are in the list.
wasChoices.Add( it->m_wsName );
}
// insert the filter names
m_checkListBoxFilter->Clear();
if( wasChoices.GetCount() ) // any contents??
{
m_checkListBoxFilter->InsertItems( wasChoices, 0);
// set the checkboxes as needed
int i = 0;
for ( std::vector<MyFilterListEl>::iterator it = wxGetApp().m_FilterList.begin();
it != wxGetApp().m_FilterList.end(); ++it, i++ )
{
m_checkListBoxFilter->Check( i, it->m_bState );
}
// just in case the filter file was fiddled with
int iNFilters = std::min( (long)(wxGetApp().m_FilterList.size() - 1),
m_iniPrefs.data[IE_FILTER_LAST_SEL].dataCurrent.lVal );
m_checkListBoxFilter->SetSelection( iNFilters );
ExplainFilter( iNFilters );
}
}
// ------------------------------------------------------------------
bool wxMsOptionsDialog::TransferDataFromWindow()
{
// 'General' tab
// Launch mail client after processing mail
m_iniPrefs.data[IE_LAUNCH_MAIL_CLIENT].dataCurrent.bVal =
m_checkBoxOptLaunchMailClient->GetValue();
// e-mail client path
m_iniPrefs.data[IE_MAIL_CLIENT_PATH].dataCurrent.wsVal =
m_textCtrlEmailClient->GetValue();
// check for new mail at startup
m_iniPrefs.data[IE_CHECK_MAIL_STARTUP].dataCurrent.bVal
= m_checkBoxOptCheckMailAtStart->GetValue();
// play sound when new mail arrives
m_iniPrefs.data[IE_SOUND_4_NEW_MAIL].dataCurrent.bVal =
m_checkBoxOptPlaySound->GetValue();
// schedule mail check
m_iniPrefs.data[IE_SCHEDULE_MAIL_CHECK].dataCurrent.bVal =
m_checkBoxScheduleMailCheck->GetValue();
// schedule mail check interval - minutes
m_iniPrefs.data[IE_MAIL_CHECK_INTERVAL].dataCurrent.lVal =
m_spinCtrlMailCheckInterval->GetValue();
// schedule mail srerver connection check
m_iniPrefs.data[IE_SCHEDULE_SERVER_CHECK].dataCurrent.bVal =
m_checkBoxScheduleMailCheck->GetValue();
// schedule mail server connection check interval - minutes
m_iniPrefs.data[IE_SERVER_CHECK_INTERVAL].dataCurrent.lVal =
m_spinCtrlMailServerConectCheckInterval->GetValue();
// schedule mail server connection check interval - minutes
m_iniPrefs.data[IE_SERVER_CHECK_INTERVAL].dataCurrent.lVal =
m_checkBoxScheduleConnectCheck->GetValue();
// check for updates at startup
m_iniPrefs.data[IE_OPT_AUTO_UPDATE_CHECK].dataCurrent.bVal =
m_checkBoxAutoUpdateCheck->GetValue();
// number of message lines to get with TOP request
m_iniPrefs.data[IE_OPT_MAX_TOP_LINES].dataCurrent.lVal =
m_spinCtrlMaxTopLines->GetValue();
// -------------------------------------------------------
// 'Log' tab
m_iniPrefs.data[IE_LOG_FILE_WANTED].dataCurrent.bVal =
m_cbOptLogToFile->GetValue();
m_iniPrefs.data[IE_USE_LOG_DEF_DIR].dataCurrent.bVal =
m_cbOptLogUseDefaultPath->GetValue();
m_iniPrefs.data[IE_LOG_DIR_PATH].dataCurrent.wsVal
= m_tcOptLogFilesDestDir->GetValue();
m_iniPrefs.data[IE_LOG_VERBOSITY].dataCurrent.lVal =
m_sliderOptLogVerbosity->GetValue();
// update the filter enabled/disabled status
int i = 0;
for ( std::vector<MyFilterListEl>::iterator it = wxGetApp().m_FilterList.begin();
it != wxGetApp().m_FilterList.end(); ++it, i++ )
{
it->m_bState = m_checkListBoxFilter->IsChecked( i );
}
m_iniPrefs.data[IE_FILTER_LAST_SEL].dataCurrent.lVal =
m_checkListBoxFilter->GetSelection();
// save the default status color
m_iniPrefs.data[IE_STATUS_DEFAULT_COLOR].dataCurrent.wsVal =
m_colourPickerStatusDefColor->GetColour().GetAsString();
return true;
}
// ------------------------------- eof ------------------------------
| 34.579926 | 85 | 0.659966 | tester0077 |
1d83f15f2aa24f6eb63ee0484c3f2848236484a5 | 5,505 | cxx | C++ | 3rd/fltk/src/list_fonts.cxx | MarioHenze/cgv | bacb2d270b1eecbea1e933b8caad8d7e11d807c2 | [
"BSD-3-Clause"
] | 11 | 2017-09-30T12:21:55.000Z | 2021-04-29T21:31:57.000Z | 3rd/fltk/src/list_fonts.cxx | MarioHenze/cgv | bacb2d270b1eecbea1e933b8caad8d7e11d807c2 | [
"BSD-3-Clause"
] | 2 | 2017-07-11T11:20:08.000Z | 2018-03-27T12:09:02.000Z | 3rd/fltk/src/list_fonts.cxx | MarioHenze/cgv | bacb2d270b1eecbea1e933b8caad8d7e11d807c2 | [
"BSD-3-Clause"
] | 24 | 2018-03-27T11:46:16.000Z | 2021-05-01T20:28:34.000Z | //
// "$Id: list_fonts.cxx 5556 2006-12-13 00:55:45Z spitzak $"
//
// Copyright 1998-2006 by Bill Spitzak and others.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Library General Public License for more details.
//
// You should have received a copy of the GNU Library General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
// USA.
//
// Please report all bugs and problems to "[email protected]".
//
// This file is seperate from Font.cxx due the historical reasons in
// that on X11 significant code was saved by only using the fltk
// built-in fonts and not doing anything with named fonts. This
// is probably irrelevant now and they could be merged.
#include <config.h>
#include <fltk/Font.h>
#include <fltk/string.h>
#if USE_X11
# include "x11/list_fonts.cxx"
#elif defined(_WIN32)
# include "win32/list_fonts.cxx"
#elif USE_QUARTZ
# include "osx/list_fonts.cxx"
#endif
using namespace fltk;
/*! \fn int fltk::list_fonts(fltk::Font**& arrayp);
\relates fltk::Font
Generate an array containing every font on the server. \a arrayp
is set to a pointer to this array, and the length of the array is
the return value. Each entry is a "base" font, there may be bold,
italic, and bold+italic version of each font pointed to by bold() or
italic().
Subsequent calls will usually return the same array quickly, but if
a signal comes in indicating a change it will probably delete the
old array and return a new one.
*/
/*! \relates fltk::Font
Find a font with the given "nice" name. You can get bold and italic
by adding a space and "bold" or "italic" (or both) to the name, or
by passing them as the attributes. Case is ignored and fltk will
accept some variations in the font name.
The current implementation calls fltk::list_fonts() and then does a
binary search of the returned list. This can make the first call
pretty slow, especially on X. Directly calling the system has a
problem in that we want the same structure returned for any call
that names the same font. This is sufficiently painful that I have
not done this yet.
*/
fltk::Font* fltk::font(const char* name, int attributes /* = 0 */) {
if (!name || !*name) return 0;
// find out if the " bold" or " italic" are on the end:
int length = strlen(name);
// also accept "italics" because old Nuke saved scripts used that:
if (length > 8 && !strncasecmp(name+length-8, " italics", 8)) {
length -= 8; attributes |= ITALIC;
}
if (length > 7 && !strncasecmp(name+length-7, " italic", 7)) {
length -= 7; attributes |= ITALIC;
}
if (length > 5 && !strncasecmp(name+length-5, " bold", 5)) {
length -= 5; attributes |= BOLD;
}
Font* font = 0;
// always try the built-in fonts first, because list_fonts is *slow*...
int i; for (i = 0; i <= 12; i += 4) {
font = fltk::font(i);
const char* fontname = font->name();
if (!strncasecmp(name, fontname, length) && !fontname[length]) goto GOTIT;
}
// now try all the fonts on the server, using a binary search:
#if defined(WIN32) && !defined(__CYGWIN__)
// this function is in win32/list_fonts.cxx:
name = GetFontSubstitutes(name,length);
#endif
font = 0;
{Font** list; int b = list_fonts(list); int a = 0;
while (a < b) {
int c = (a+b)/2;
Font* testfont = list[c];
const char* fontname = testfont->name();
int d = strncasecmp(name, fontname, length);
if (!d) {
// If we match a prefix of the font return it unless a better match found
font = testfont;
if (!fontname[length]) goto GOTIT;
}
if (d > 0) a = c+1;
else b = c;
}}
if (!font) return 0;
GOTIT:
return font->plus(attributes);
}
/*! \fn fltk::Font* fltk::font(int i)
\relates fltk::Font
Turn an fltk1 integer font id into a font.
*/
/*! \fn int fltk::Font::sizes(int*& sizep);
Sets array to point at a list of sizes. The return value is the
length of this array. The sizes are sorted from smallest to largest
and indicate what sizes can be given to fltk::setfont() that will be
matched exactly (fltk::setfont() will pick the closest size for
other sizes). A zero in the first location of the array indicates a
scalable font, where any size works, although the array may still
list sizes that work "better" than others. The returned array points
at a static buffer that is overwritten each call, so you want to
copy it if you plan to keep it.
The return value is the length of the list. The argument \a arrayp
is set to point at the array, which is in static memory reused
each time this call is done.
*/
/*! \fn int fltk::Font::encodings(const char**& arrayp);
Return all the encodings for this font. These strings may be
sent to fltk::set_encoding() before using the font.
The return value is the length of the list. The argument \a arrayp
is set to point at the array, which is in static memory reused
each time this call is done.
*/
//
// End of "$Id: list_fonts.cxx 5556 2006-12-13 00:55:45Z spitzak $".
//
| 35.980392 | 79 | 0.695186 | MarioHenze |
1d8a781b17462e186cc72bd38c078f3fecca5161 | 2,085 | cpp | C++ | source/ashes/renderer/D3D11Renderer/Command/Commands/D3D11CopyImageCommand.cpp | DragonJoker/Ashes | a6ed950b3fd8fb9626c60b4291fbd52ea75ac66e | [
"MIT"
] | 227 | 2018-09-17T16:03:35.000Z | 2022-03-19T02:02:45.000Z | source/ashes/renderer/D3D11Renderer/Command/Commands/D3D11CopyImageCommand.cpp | DragonJoker/RendererLib | 0f8ad8edec1b0929ebd10247d3dd0a9ee8f8c91a | [
"MIT"
] | 39 | 2018-02-06T22:22:24.000Z | 2018-08-29T07:11:06.000Z | source/ashes/renderer/D3D11Renderer/Command/Commands/D3D11CopyImageCommand.cpp | DragonJoker/Ashes | a6ed950b3fd8fb9626c60b4291fbd52ea75ac66e | [
"MIT"
] | 8 | 2019-05-04T10:33:32.000Z | 2021-04-05T13:19:27.000Z | /*
This file belongs to Ashes.
See LICENSE file in root folder.
*/
#include "Command/Commands/D3D11CopyImageCommand.hpp"
#include "Image/D3D11Image.hpp"
#include "Image/D3D11ImageView.hpp"
#include "ashesd3d11_api.hpp"
namespace ashes::d3d11
{
namespace
{
D3D11_BOX doGetSrcBox( VkImageCopy const & copyInfo )
{
return
{
UINT( copyInfo.srcOffset.x ),
UINT( copyInfo.srcOffset.y ),
UINT( copyInfo.srcOffset.z ),
UINT( copyInfo.srcOffset.x ) + copyInfo.extent.width,
UINT( copyInfo.srcOffset.y ) + copyInfo.extent.height,
UINT( copyInfo.srcOffset.z ) + copyInfo.extent.depth,
};
}
}
CopyImageCommand::CopyImageCommand( VkDevice device
, VkImageCopy const & copyInfo
, VkImage src
, VkImage dst )
: CommandBase{ device }
, m_src{ src }
, m_dst{ dst }
, m_copyInfo{ copyInfo }
, m_srcBox{ doGetSrcBox( m_copyInfo ) }
, m_srcSubresource{ D3D11CalcSubresource( m_copyInfo.srcSubresource.mipLevel
, m_copyInfo.srcSubresource.baseArrayLayer
, get( m_src )->getMipmapLevels() ) }
, m_dstSubresource{ D3D11CalcSubresource( m_copyInfo.dstSubresource.mipLevel
, m_copyInfo.dstSubresource.baseArrayLayer
, get( m_dst )->getMipmapLevels() ) }
{
}
void CopyImageCommand::apply( Context const & context )const
{
if ( isDepthOrStencilFormat( get( m_src )->getFormat() ) )
{
context.context->CopySubresourceRegion( get( m_dst )->getResource()
, m_dstSubresource
, 0
, 0
, 0
, get( m_src )->getResource()
, m_srcSubresource
, nullptr );
}
else
{
context.context->CopySubresourceRegion( get( m_dst )->getResource()
, m_dstSubresource
, UINT( m_copyInfo.dstOffset.x )
, UINT( m_copyInfo.dstOffset.y )
, UINT( m_copyInfo.dstOffset.z )
, get( m_src )->getResource()
, m_srcSubresource
, &m_srcBox );
}
auto dstMemory = get( m_dst )->getMemory();
get( dstMemory )->updateDownload( 0u, get( m_dst )->getMemoryRequirements().size, 0u );
}
CommandPtr CopyImageCommand::clone()const
{
return std::make_unique< CopyImageCommand >( *this );
}
}
| 25.426829 | 89 | 0.686331 | DragonJoker |
1d91e4e76e434ac4473d937835788a3d1703d8f2 | 1,378 | cpp | C++ | 038.cpp | LeeYiyuan/projecteuler | 81a0b65f73b47fbb9bfe99cb5ff72da7e0ba0d74 | [
"MIT"
] | null | null | null | 038.cpp | LeeYiyuan/projecteuler | 81a0b65f73b47fbb9bfe99cb5ff72da7e0ba0d74 | [
"MIT"
] | null | null | null | 038.cpp | LeeYiyuan/projecteuler | 81a0b65f73b47fbb9bfe99cb5ff72da7e0ba0d74 | [
"MIT"
] | null | null | null | /*
We are considering the concatenated product of an integer a with (1, 2, ...,
n) with n > 1, i.e. n >= 2. If a >= 10000, then 2a >= 20000. As such, the
concatenated product will have at least 10 digits. By the pigeonhole
principle, one of the digit will occur at least twice, making it non
pandigital.
As such we only need consider a < 10000.
Also since all valid products are exactly 9 digits long, we can compare the
strings directly instead of having to convert them into a numerical.
*/
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
int main()
{
std::string max_product_string = "000000000";
std::vector<char> pandigital_digits = { '1', '2', '3', '4', '5', '6', '7', '8', '9' };
for (int a = 1; a < 10000; a++)
{
std::string product_string = "";
int n = 1;
while (product_string.length() < 8) // Extend to at least 9 digits long.
{
product_string += std::to_string(n * a);
n++;
}
if (product_string.length() != 9) // If not possible to produce exactly 9 digits.
continue;
if (std::is_permutation(product_string.begin(), product_string.end(), pandigital_digits.begin()))
max_product_string = std::max(max_product_string, product_string);
}
std::cout << max_product_string;
}
| 32.809524 | 105 | 0.618287 | LeeYiyuan |
1d95ef6eb38128f0002cf42c70e45e230ba12aab | 21,527 | cc | C++ | examples/uintTest/ffmpeg/ffmpeg_enc_mux_test.cc | rockchip-linux/rkmedia | 992663e9069e8426f5a71f4045666786b3bd4bcf | [
"BSD-3-Clause"
] | 23 | 2020-02-29T10:47:22.000Z | 2022-01-20T01:52:21.000Z | examples/uintTest/ffmpeg/ffmpeg_enc_mux_test.cc | rockchip-linux/rkmedia | 992663e9069e8426f5a71f4045666786b3bd4bcf | [
"BSD-3-Clause"
] | 13 | 2020-05-12T15:11:04.000Z | 2021-12-02T05:48:39.000Z | examples/uintTest/ffmpeg/ffmpeg_enc_mux_test.cc | rockchip-linux/rkmedia | 992663e9069e8426f5a71f4045666786b3bd4bcf | [
"BSD-3-Clause"
] | 19 | 2020-01-12T04:07:33.000Z | 2022-02-18T08:43:19.000Z | // Copyright 2019 Fuzhou Rockchip Electronics Co., Ltd. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifdef NDEBUG
#undef NDEBUG
#endif
#ifndef DEBUG
#define DEBUG
#endif
#include <assert.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <cmath>
#include <string>
#include <unordered_map>
extern "C" {
#define __STDC_CONSTANT_MACROS
#include <libavformat/avformat.h>
}
#include "buffer.h"
#include "encoder.h"
#include "key_string.h"
#include "muxer.h"
#include "media_type.h"
#ifndef M_PI
#define M_PI 3.14159265358979323846 /* pi */
#endif
static const int aac_sample_rates[] = {
96000, 88200, 64000, 48000, 44100, 32000,
24000, 22050, 16000, 12000, 11025, 8000, 0
};
static int free_memory(void *buffer) {
assert(buffer);
free(buffer);
return 0;
}
std::shared_ptr<easymedia::MediaBuffer> adts_get_extradata(SampleInfo sample_info) {
size_t dsi_size = 2;
char *ptr = (char*)malloc(dsi_size);
assert(ptr);
uint32_t sample_rate_idx = 0;
for (; aac_sample_rates[sample_rate_idx] != 0; sample_rate_idx++)
if (sample_info.sample_rate == aac_sample_rates[sample_rate_idx])
break;
uint32_t object_type = 2; // AAC LC by default
ptr[0] = (object_type << 3) | (sample_rate_idx >> 1);
ptr[1] = ((sample_rate_idx & 1) << 7) | (sample_info.channels << 3);
std::shared_ptr<easymedia::MediaBuffer> extra_data =
std::make_shared<easymedia::MediaBuffer>(ptr, dsi_size, -1, ptr, free_memory);
extra_data->SetValidSize(dsi_size);
return extra_data;
}
template <typename Encoder>
int encode(std::shared_ptr<easymedia::Muxer> mux,
std::shared_ptr<easymedia::Stream> file_write,
std::shared_ptr<Encoder> encoder,
std::shared_ptr<easymedia::MediaBuffer> src,
int stream_no) {
auto enc = encoder;
int ret = enc->SendInput(src);
if (ret < 0) {
fprintf(stderr, "[%d]: frame encode failed, ret=%d\n", stream_no, ret);
return -1;
}
while (ret >= 0) {
auto out = enc->FetchOutput();
if (!out) {
if (errno != EAGAIN) {
fprintf(stderr, "[%d]: frame fetch failed, ret=%d\n", stream_no, errno);
ret = errno;
}
break;
}
size_t out_len = out->GetValidSize();
if (out_len == 0)
break;
fprintf(stderr, "[%d]: frame encoded, out %zu bytes\n\n", stream_no,
out_len);
if (mux)
mux->Write(out, stream_no);
if (file_write)
file_write->Write(out->GetPtr(), 1, out_len);
}
return ret;
}
std::shared_ptr<easymedia::AudioEncoder>
initAudioEncoder(std::string EncoderName, std::string EncType, SampleInfo& sample) {
std::string param;
PARAM_STRING_APPEND(param, KEY_OUTPUTDATATYPE, EncType);
auto aud_enc = easymedia::REFLECTOR(Encoder)::Create<easymedia::AudioEncoder>(
EncoderName.c_str(), param.c_str());
if (!aud_enc) {
fprintf(stderr, "Create %s encoder failed\n", EncoderName.c_str());
exit(EXIT_FAILURE);
}
MediaConfig aud_enc_config;
auto &ac = aud_enc_config.aud_cfg;
ac.sample_info = sample;
ac.bit_rate = 64000; // 64kbps
ac.codec_type = StringToCodecType(EncType.c_str());
aud_enc_config.type = Type::Audio;
if (!aud_enc->InitConfig(aud_enc_config)) {
fprintf(stderr, "Init config of ffmpeg_aud encoder failed\n");
exit(EXIT_FAILURE);
}
return aud_enc;
}
std::shared_ptr<easymedia::VideoEncoder> initVideoEncoder(std::string EncoderName,
std::string SrcFormat,
std::string OutFormat,
int w, int h) {
std::string param;
PARAM_STRING_APPEND(param, KEY_OUTPUTDATATYPE, OutFormat);
// If not rkmpp, then it is ffmpeg
if (EncoderName == "ffmpeg_vid") {
if (OutFormat == "video:h264") {
PARAM_STRING_APPEND(param, KEY_NAME, "libx264");
} else if (OutFormat == "video:h265") {
PARAM_STRING_APPEND(param, KEY_NAME, "libx265");
} else {
exit(EXIT_FAILURE);
}
}
auto vid_enc = easymedia::REFLECTOR(Encoder)::Create<easymedia::VideoEncoder>(
EncoderName.c_str(), param.c_str());
if (!vid_enc) {
fprintf(stderr, "Create encoder %s failed\n", EncoderName.c_str());
exit(EXIT_FAILURE);
}
PixelFormat fmt = PIX_FMT_NONE;
if (SrcFormat == "nv12") {
fmt = PIX_FMT_NV12;
} else if (SrcFormat == "yuv420p") {
fmt = PIX_FMT_YUV420P;
} else {
fprintf(stderr, "TO BE TESTED <%s:%s,%d>\n", __FILE__, __FUNCTION__,
__LINE__);
exit(EXIT_FAILURE);
}
// TODO SrcFormat and OutFormat use the same variable
ImageInfo vid_info = {fmt, w, h, w, h};
if (EncoderName == "rkmpp") {
vid_info.vir_width = UPALIGNTO16(w);
vid_info.vir_height = UPALIGNTO16(h);
}
MediaConfig vid_enc_config;
if (OutFormat == VIDEO_H264 || OutFormat == VIDEO_H265) {
VideoConfig &vid_cfg = vid_enc_config.vid_cfg;
ImageConfig &img_cfg = vid_cfg.image_cfg;
img_cfg.image_info = vid_info;
vid_cfg.qp_init = 24;
vid_cfg.qp_step = 4;
vid_cfg.qp_min = 12;
vid_cfg.qp_max = 48;
vid_cfg.bit_rate = w * h * 7;
if (vid_cfg.bit_rate > 1000000) {
vid_cfg.bit_rate /= 1000000;
vid_cfg.bit_rate *= 1000000;
}
vid_cfg.frame_rate = 30;
vid_cfg.level = 52;
vid_cfg.gop_size = 10; // vid_cfg.frame_rate;
vid_cfg.profile = 100;
// vid_cfg.rc_quality = "aq_only"; vid_cfg.rc_mode = "vbr";
vid_cfg.rc_quality = KEY_HIGHEST;
vid_cfg.rc_mode = KEY_CBR;
vid_enc_config.type = Type::Video;
} else {
// TODO
assert(0);
}
if (!vid_enc->InitConfig(vid_enc_config)) {
fprintf(stderr, "Init config of encoder %s failed\n", EncoderName.c_str());
exit(EXIT_FAILURE);
}
return vid_enc;
}
std::shared_ptr<easymedia::SampleBuffer> initAudioBuffer(MediaConfig &cfg) {
auto &audio_info = cfg.aud_cfg.sample_info;
fprintf(stderr, "sample number=%d\n", audio_info.nb_samples);
int aud_size = GetSampleSize(audio_info) * audio_info.nb_samples;
auto aud_mb = easymedia::MediaBuffer::Alloc2(aud_size);
auto aud_buffer =
std::make_shared<easymedia::SampleBuffer>(aud_mb, audio_info);
aud_buffer->SetValidSize(aud_size);
assert(aud_buffer && (int)aud_buffer->GetSize() >= aud_size);
return aud_buffer;
}
std::shared_ptr<easymedia::MediaBuffer>
initVideoBuffer(std::string &EncoderName, ImageInfo &image_info) {
// The vir_width/vir_height have aligned when init video encoder
size_t len = CalPixFmtSize(image_info);
fprintf(stderr, "video buffer len %zu\n", len);
// Just treat all aligned memory to be hardware memory
// need to know rkmpp needs DRM managed memory,
// but ffmpeg software encoder doesn't need.
easymedia::MediaBuffer::MemType MemType =
EncoderName == "rkmpp"
? easymedia::MediaBuffer::MemType::MEM_HARD_WARE
: easymedia::MediaBuffer::MemType::MEM_COMMON;
auto &&src_mb = easymedia::MediaBuffer::Alloc2(
len, MemType);
assert(src_mb.GetSize() > 0);
auto src_buffer =
std::make_shared<easymedia::ImageBuffer>(src_mb, image_info);
assert(src_buffer && src_buffer->GetSize() >= len);
return src_buffer;
}
std::shared_ptr<easymedia::Muxer> initMuxer(std::string &output_path) {
easymedia::REFLECTOR(Muxer)::DumpFactories();
std::string param;
char* cut = strrchr((char*)output_path.c_str(), '.');
if (cut) {
std::string output_data_type = cut + 1;
if (output_data_type == "mp4") {
PARAM_STRING_APPEND(param, KEY_OUTPUTDATATYPE, "mp4");
} else if (output_data_type == "aac") {
PARAM_STRING_APPEND(param, KEY_OUTPUTDATATYPE, "adts");
}
}
PARAM_STRING_APPEND(param, KEY_PATH, output_path);
return easymedia::REFLECTOR(Muxer)::Create<easymedia::Muxer>(
"ffmpeg", param.c_str());
}
std::shared_ptr<easymedia::Stream> initFileWrite(std::string &output_path) {
std::string stream_name = "file_write_stream";
std::string params = "";
PARAM_STRING_APPEND(params, KEY_PATH, output_path.c_str());
PARAM_STRING_APPEND(params, KEY_OPEN_MODE, "we"); // write and close-on-exec
return easymedia::REFLECTOR(Stream)::
Create<easymedia::Stream>(stream_name.c_str(), params.c_str());
}
std::shared_ptr<easymedia::Stream>
initAudioCapture(std::string device, SampleInfo& sample_info) {
std::string stream_name = "alsa_capture_stream";
std::string params;
std::string fmt_str = SampleFmtToString(sample_info.fmt);
std::string rule = "output_data_type=" + fmt_str + "\n";
if (!easymedia::REFLECTOR(Stream)::IsMatch(stream_name.c_str(),
rule.c_str())) {
fprintf(stderr, "unsupport data type\n");
return nullptr;
}
PARAM_STRING_APPEND(params, KEY_DEVICE, device.c_str());
PARAM_STRING_APPEND(params, KEY_SAMPLE_FMT, fmt_str);
PARAM_STRING_APPEND_TO(params, KEY_CHANNELS, sample_info.channels);
PARAM_STRING_APPEND_TO(params, KEY_SAMPLE_RATE, sample_info.sample_rate);
printf("%s params:\n%s\n", stream_name.c_str(), params.c_str());
return easymedia::REFLECTOR(Stream)::Create<easymedia::Stream>(
stream_name.c_str(), params.c_str());
}
static char optstr[] = "?t:i:o:w:h:e:c:";
int main(int argc, char **argv) {
int c;
std::string input_path;
std::string output_path;
int w = 0, h = 0;
std::string vid_input_format;
std::string vid_enc_format;
std::string vid_enc_codec_name = "rkmpp"; // rkmpp, ffmpeg_vid
std::string aud_enc_format = AUDIO_AAC; // test mp2, aac
std::string aud_input_format = AUDIO_PCM_FLTP;
std::string aud_enc_codec_name = "ffmpeg_aud";
std::string stream_type;
std::string device_name = "default";
opterr = 1;
while ((c = getopt(argc, argv, optstr)) != -1) {
switch (c) {
case 't':
stream_type = optarg;
break;
case 'i': {
char *cut = strchr(optarg, ':');
if (cut) {
cut[0] = 0;
device_name = optarg;
if (device_name == "alsa")
device_name = cut + 1;
}
input_path = optarg;
} break;
case 'o':
output_path = optarg;
break;
case 'w':
w = atoi(optarg);
break;
case 'h':
h = atoi(optarg);
break;
case 'e': {
char *cut = strchr(optarg, ':');
if (cut) {
cut[0] = 0;
char *sub = optarg;
if (!strcmp(sub,"aud")) {
sub = cut + 1;
char *subsub = strchr(sub, '_');
if (subsub) {
subsub[0] = 0;
aud_input_format = sub;
aud_enc_format = subsub + 1;
}
break;
} else if (!strcmp(sub,"vid")) {
optarg = cut + 1;
} else {
exit(EXIT_FAILURE);
}
}
cut = strchr(optarg, '_');
if (!cut) {
fprintf(stderr, "input/output format must be cut by \'_\'\n");
exit(EXIT_FAILURE);
}
cut[0] = 0;
vid_input_format = optarg;
vid_enc_format = cut + 1;
if (vid_enc_format == "h264")
vid_enc_format = VIDEO_H264;
else if (vid_enc_format == "h265")
vid_enc_format = VIDEO_H265;
} break;
case 'c': {
char *cut = strchr(optarg, ':');
if (cut) {
cut[0] = 0;
char *sub = optarg;
if (!strcmp(sub, "aud")) {
aud_enc_codec_name = cut + 1;
break;
} else if (!strcmp(sub, "vid")) {
optarg = cut + 1;
} else {
exit(EXIT_FAILURE);
}
}
cut = strchr(optarg, ':');
if (cut) {
cut[0] = 0;
std::string ff = optarg;
if (ff == "ffmpeg")
vid_enc_codec_name = cut + 1;
} else {
vid_enc_codec_name = optarg;
}
} break;
case '?':
default:
printf("usage example: \n");
printf("ffmpeg_enc_mux_test -t video_audio -i input.yuv -o output.mp4 -w 320 -h 240 -e "
"nv12_h264 -c rkmpp\n");
printf("ffmpeg_enc_mux_test -t audio -i alsa:default -o output.aac -e aud:fltp_aac "
"-c aud:ffmpeg_aud\n");
printf("ffmpeg_enc_mux_test -t audio -i alsa:default -o output.mp2 -e aud:s16le_mp2 "
"-c aud:ffmpeg_aud\n");
exit(0);
}
}
if (aud_input_format == "u8") {
aud_input_format = AUDIO_PCM_U8;
} else if (aud_input_format == "s16le") {
aud_input_format = AUDIO_PCM_S16;
} else if (aud_input_format == "s32le") {
aud_input_format = AUDIO_PCM_S32;
} else if (aud_input_format == "fltp") {
aud_input_format = AUDIO_PCM_FLTP;
}
if (aud_enc_format == "aac") {
aud_enc_format = AUDIO_AAC;
} else if (aud_enc_format == "mp2") {
aud_enc_format = AUDIO_MP2;
}
printf("stream type: %s\n", stream_type.c_str());
printf("input file path: %s\n", input_path.c_str());
printf("output file path: %s\n", output_path.c_str());
if (!device_name.empty())
printf("device_name: %s\n", device_name.c_str());
if (stream_type.find("video") != stream_type.npos) {
printf("vid_input_format format: %s\n", vid_input_format.c_str());
printf("vid_enc_format format: %s\n", vid_enc_format.c_str());
}
if (stream_type.find("audio") != stream_type.npos) {
printf("aud_input_format: %s\n", aud_input_format.c_str());
printf("aud_enc_format: %s\n", aud_enc_format.c_str());
}
if (input_path.empty() || output_path.empty())
exit(EXIT_FAILURE);
if (stream_type.find("video") != stream_type.npos && (!w || !h))
exit(EXIT_FAILURE);
if (stream_type.find("video") != stream_type.npos &&
(vid_input_format.empty() || vid_enc_format.empty()))
exit(EXIT_FAILURE);
int vid_index = 0;
int aud_index = 0;
int64_t first_audio_time = 0;
int64_t first_video_time = 0;
int64_t vinterval_per_frame = 0;
int64_t ainterval_per_frame = 0;
size_t video_frame_len = 0;
std::shared_ptr<easymedia::VideoEncoder> vid_enc = nullptr;
std::shared_ptr<easymedia::MediaBuffer> src_buffer = nullptr;
std::shared_ptr<easymedia::MediaBuffer> dst_buffer = nullptr;
std::shared_ptr<easymedia::Stream> audio_capture = nullptr;
std::shared_ptr<easymedia::AudioEncoder> aud_enc = nullptr;
std::shared_ptr<easymedia::SampleBuffer> aud_buffer = nullptr;
std::shared_ptr<easymedia::Stream> file_write = nullptr;
// 0. muxer
int vid_stream_no = -1;
int aud_stream_no = -1;
auto mux = initMuxer(output_path);
if (!mux) {
fprintf(stderr,
"Init Muxer failed and then init file write stream."
"output_path = %s\n", output_path.c_str());
file_write = initFileWrite(output_path);
if (!file_write) {
fprintf(stderr, "Init file write stream failed.\n");
exit(EXIT_FAILURE);
}
}
easymedia::REFLECTOR(Encoder)::DumpFactories();
// 1.video stream
int input_file_fd = -1;
if (stream_type.find("video") != stream_type.npos) {
input_file_fd = open(input_path.c_str(), O_RDONLY | O_CLOEXEC);
assert(input_file_fd >= 0);
unlink(output_path.c_str());
vid_enc = initVideoEncoder(vid_enc_codec_name, vid_input_format, vid_enc_format, w, h);
src_buffer = initVideoBuffer(vid_enc_codec_name, vid_enc->GetConfig().img_cfg.image_info);
if (vid_enc_codec_name == "rkmpp") {
size_t dst_len = CalPixFmtSize(vid_enc->GetConfig().img_cfg.image_info);
dst_buffer = easymedia::MediaBuffer::Alloc(
dst_len, easymedia::MediaBuffer::MemType::MEM_HARD_WARE);
assert(dst_buffer && dst_buffer->GetSize() >= dst_len);
}
// TODO SrcFormat and OutFormat use the same variable
vid_enc->GetConfig().img_cfg.image_info.pix_fmt =
StringToPixFmt(vid_enc_format.c_str());
if (mux && !mux->NewMuxerStream(vid_enc->GetConfig(), vid_enc->GetExtraData(),
vid_stream_no)) {
fprintf(stderr, "NewMuxerStream failed for video\n");
exit(EXIT_FAILURE);
}
vinterval_per_frame =
1000000LL /* us */ / vid_enc->GetConfig().vid_cfg.frame_rate;
// TODO SrcFormat and OutFormat use the same variable
vid_enc->GetConfig().vid_cfg.image_cfg.image_info.pix_fmt =
StringToPixFmt(std::string("image:").append(vid_input_format).c_str());
// Since the input is packed yuv images, no padding buffer,
// we want to read actual pixel size
video_frame_len =
CalPixFmtSize(vid_enc->GetConfig().vid_cfg.image_cfg.image_info.pix_fmt, w, h);
}
// 2. audio stream.
SampleInfo sample_info = {SAMPLE_FMT_NONE, 2, 48000, 1024};
if (stream_type.find("audio") != stream_type.npos) {
sample_info.fmt = StringToSampleFmt(aud_input_format.c_str());
audio_capture = initAudioCapture(device_name, sample_info);
if (!audio_capture) {
fprintf(stderr, "initAudioCapture failed.\n");
exit(EXIT_FAILURE);
}
aud_enc = initAudioEncoder(aud_enc_codec_name, aud_enc_format, sample_info);
if (aud_enc_format == AUDIO_AAC) {
auto extra_data = adts_get_extradata(sample_info);
aud_enc->SetExtraData(extra_data);
}
aud_buffer = initAudioBuffer(aud_enc->GetConfig());
assert(aud_buffer && aud_buffer->GetValidSize() > 0);
auto &audio_info = aud_enc->GetConfig().aud_cfg.sample_info;
sample_info = audio_info;
if (mux && !mux->NewMuxerStream(aud_enc->GetConfig(), aud_enc->GetExtraData(),
aud_stream_no)) {
fprintf(stderr, "NewMuxerStream failed for audio\n");
exit(EXIT_FAILURE);
}
ainterval_per_frame =
1000000LL /* us */ * aud_enc->GetConfig().aud_cfg.sample_info.nb_samples /
aud_enc->GetConfig().aud_cfg.sample_info.sample_rate;
}
if (mux && !(mux->WriteHeader(aud_stream_no))) {
fprintf(stderr, "WriteHeader on stream index %d return nullptr\n",
aud_stream_no);
exit(EXIT_FAILURE);
}
// for ffmpeg, WriteHeader once, this call only dump info
//mux->WriteHeader(aud_stream_no);
int64_t audio_duration = 10 * 1000 * 1000;
while (true) {
if (stream_type.find("video") != stream_type.npos &&
vid_index * vinterval_per_frame < aud_index * ainterval_per_frame) {
// video
ssize_t read_len = read(input_file_fd, src_buffer->GetPtr(), video_frame_len);
if (read_len < 0) {
// if 0 Continue to drain all encoded buffer
fprintf(stderr, "%s read len %zu\n", vid_enc_codec_name.c_str(), read_len);
break;
} else if (read_len == 0 && vid_enc_codec_name == "rkmpp") {
// rkmpp process does not accept empty buffer
// it will treat the result of nullptr input as normal
// though it is ugly, but we cannot change it by now
fprintf(stderr, "%s read len 0\n", vid_enc_codec_name.c_str());
break;
}
if (first_video_time == 0) {
first_video_time = easymedia::gettimeofday();
}
// feed video buffer
src_buffer->SetValidSize(read_len); // important
src_buffer->SetUSTimeStamp(first_video_time +
vid_index * vinterval_per_frame); // important
vid_index++;
if (vid_enc_codec_name == "rkmpp") {
dst_buffer->SetValidSize(dst_buffer->GetSize());
if (0 != vid_enc->Process(src_buffer, dst_buffer, nullptr)) {
continue;
}
size_t out_len = dst_buffer->GetValidSize();
fprintf(stderr, "vframe %d encoded, type %s, out %zu bytes\n", vid_index,
dst_buffer->GetUserFlag() & easymedia::MediaBuffer::kIntra
? "I frame"
: "P frame",
out_len);
if (mux)
mux->Write(dst_buffer, vid_stream_no);
} else if (vid_enc_codec_name == "ffmpeg_vid") {
if (0 > encode<easymedia::VideoEncoder>(mux, file_write, vid_enc, src_buffer,
vid_stream_no)) {
fprintf(stderr, "Encode video frame %d failed\n", vid_index);
break;
}
}
} else {
// audio
if (first_audio_time == 0)
first_audio_time = easymedia::gettimeofday();
if (first_audio_time > 0 && easymedia::gettimeofday() - first_audio_time > audio_duration)
break;
size_t read_samples = audio_capture->Read(
aud_buffer->GetPtr(), aud_buffer->GetSampleSize(), sample_info.nb_samples);
if (!read_samples && errno != EAGAIN) {
exit(EXIT_FAILURE); // fatal error
}
aud_buffer->SetSamples(read_samples);
aud_buffer->SetUSTimeStamp(first_audio_time +
aud_index * ainterval_per_frame);
aud_index++;
if (0 > encode<easymedia::AudioEncoder>(mux, file_write, aud_enc, aud_buffer, aud_stream_no)) {
fprintf(stderr, "Encode audio frame %d failed\n", aud_index);
break;
}
}
}
if (stream_type.find("video") != stream_type.npos) {
src_buffer->SetValidSize(0);
if (0 > encode<easymedia::VideoEncoder>(mux, file_write, vid_enc, src_buffer, vid_stream_no)) {
fprintf(stderr, "Drain video frame %d failed\n", vid_index);
}
aud_buffer->SetSamples(0);
if (0 > encode<easymedia::AudioEncoder>(mux, file_write, aud_enc, aud_buffer, aud_stream_no)) {
fprintf(stderr, "Drain audio frame %d failed\n", aud_index);
}
}
if (mux) {
auto buffer = easymedia::MediaBuffer::Alloc(1);
buffer->SetEOF(true);
buffer->SetValidSize(0);
mux->Write(buffer, vid_stream_no);
}
close(input_file_fd);
mux = nullptr;
vid_enc = nullptr;
aud_enc = nullptr;
return 0;
}
| 32.966309 | 101 | 0.638036 | rockchip-linux |
1d9a980328700b6f6d3254e7cad32ca740d33f3c | 689 | hpp | C++ | gnet/include/net/connection.hpp | gapry/GNet | 4d63540e1f532fae1a44a97f9b2d74a6754f2513 | [
"MIT"
] | 1 | 2021-05-19T03:56:47.000Z | 2021-05-19T03:56:47.000Z | gnet/include/net/connection.hpp | gapry/GNet | 4d63540e1f532fae1a44a97f9b2d74a6754f2513 | [
"MIT"
] | null | null | null | gnet/include/net/connection.hpp | gapry/GNet | 4d63540e1f532fae1a44a97f9b2d74a6754f2513 | [
"MIT"
] | null | null | null | #pragma once
#include "net/packet.hpp"
#include "net/socket.hpp"
#include "noncopyable.hpp"
#include "platform/types.hpp"
namespace gnet {
class engine;
class connection : public noncopyable<connection> {
friend class engine;
public:
enum class status {
none,
listening,
connecting,
connected,
};
connection() = default;
~connection() = default;
auto set_user_data(void* const data) -> void;
auto get_user_data(void) -> void*;
auto close(void) -> void;
protected:
socket m_sock;
status m_status = status::none;
void* m_user_data = nullptr;
u64 m_totoal_send_bytes = 0;
u64 m_totoal_recv_bytes = 0;
};
} // namespace gnet
| 16.404762 | 51 | 0.67344 | gapry |
1d9d30a945339fabdd63cd82a686a8c6d5c8614d | 127 | hpp | C++ | src/main.hpp | Southclaws/pawn-bcrypt | c046c3dc5c65997ae92d0c83d87fd487b69eaf23 | [
"MIT"
] | 9 | 2019-01-02T21:13:26.000Z | 2022-01-15T09:43:11.000Z | src/main.hpp | Southclaws/pawn-bcrypt | c046c3dc5c65997ae92d0c83d87fd487b69eaf23 | [
"MIT"
] | null | null | null | src/main.hpp | Southclaws/pawn-bcrypt | c046c3dc5c65997ae92d0c83d87fd487b69eaf23 | [
"MIT"
] | null | null | null | #ifndef MAIN_H
#define MAIN_H
#include "SDK/amx/amx.h"
#include "SDK/plugincommon.h"
#define BCRYPT_VERSION "v2.2.3"
#endif
| 12.7 | 31 | 0.732283 | Southclaws |
1da1a863a316357d81a85c5e5da86b93ae9e3139 | 7,729 | cpp | C++ | IPhreeqcMMS/IPhreeqc/src/phreeqcpp/nvector.cpp | usgs-coupled/webmod | 66419e3714f20a357a7db0abd84246d61c002b88 | [
"DOC"
] | null | null | null | IPhreeqcMMS/IPhreeqc/src/phreeqcpp/nvector.cpp | usgs-coupled/webmod | 66419e3714f20a357a7db0abd84246d61c002b88 | [
"DOC"
] | null | null | null | IPhreeqcMMS/IPhreeqc/src/phreeqcpp/nvector.cpp | usgs-coupled/webmod | 66419e3714f20a357a7db0abd84246d61c002b88 | [
"DOC"
] | 1 | 2020-06-04T23:27:02.000Z | 2020-06-04T23:27:02.000Z | /**************************************************************************
* *
* File : nvector.c *
* Programmers : Radu Serban, LLNL *
* Version of : 26 June 2002 *
*------------------------------------------------------------------------*
* Copyright (c) 2002, The Regents of the University of California *
* Produced at the Lawrence Livermore National Laboratory *
* All rights reserved *
* For details, see LICENSE below *
*------------------------------------------------------------------------*
* This is the implementation file for a generic NVECTOR *
* package. It contains the implementation of the N_Vector *
* kernels listed in nvector.h. *
* *
*------------------------------------------------------------------------*
* LICENSE *
*------------------------------------------------------------------------*
* Copyright (c) 2002, The Regents of the University of California. *
* Produced at the Lawrence Livermore National Laboratory. *
* Written by S.D. Cohen, A.C. Hindmarsh, R. Serban, *
* D. Shumaker, and A.G. Taylor. *
* UCRL-CODE-155951 (CVODE) *
* UCRL-CODE-155950 (CVODES) *
* UCRL-CODE-155952 (IDA) *
* UCRL-CODE-237203 (IDAS) *
* UCRL-CODE-155953 (KINSOL) *
* All rights reserved. *
* *
* This file is part of SUNDIALS. *
* *
* Redistribution and use in source and binary forms, with or without *
* modification, are permitted provided that the following conditions *
* are met: *
* *
* 1. Redistributions of source code must retain the above copyright *
* notice, this list of conditions and the disclaimer below. *
* *
* 2. Redistributions in binary form must reproduce the above copyright *
* notice, this list of conditions and the disclaimer (as noted below) *
* in the documentation and/or other materials provided with the *
* distribution. *
* *
* 3. Neither the name of the UC/LLNL nor the names of its contributors *
* may be used to endorse or promote products derived from this software *
* without specific prior written permission. *
* *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS *
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT *
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS *
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE *
* REGENTS OF THE UNIVERSITY OF CALIFORNIA, THE U.S. DEPARTMENT OF ENERGY *
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, *
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT *
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, *
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY *
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT *
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE *
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *
**************************************************************************/
#include "nvector.h" /* generic M_Env and N_Vector */
#if defined(PHREEQCI_GUI)
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
#endif
N_Vector
N_VNew(integertype n, M_Env machEnv)
{
N_Vector v_new;
v_new = machEnv->ops->nvnew(n, machEnv);
return (v_new);
}
N_Vector_S
N_VNew_S(integertype ns, integertype n, M_Env machEnv)
{
N_Vector_S vs_new;
vs_new = machEnv->ops->nvnewS(ns, n, machEnv);
return (vs_new);
}
void
N_VFree(N_Vector v)
{
v->menv->ops->nvfree(v);
}
void
N_VFree_S(integertype ns, N_Vector_S vs)
{
(*vs)->menv->ops->nvfreeS(ns, vs);
}
N_Vector
N_VMake(integertype n, realtype * v_data, M_Env machEnv)
{
N_Vector v_new;
v_new = machEnv->ops->nvmake(n, v_data, machEnv);
return (v_new);
}
void
N_VDispose(N_Vector v)
{
v->menv->ops->nvdispose(v);
}
realtype *
N_VGetData(N_Vector v)
{
realtype *data;
data = v->menv->ops->nvgetdata(v);
return (data);
}
void
N_VSetData(realtype * v_data, N_Vector v)
{
v->menv->ops->nvsetdata(v_data, v);
}
void
N_VLinearSum(realtype a, N_Vector x, realtype b, N_Vector y, N_Vector z)
{
z->menv->ops->nvlinearsum(a, x, b, y, z);
}
void
N_VConst(realtype c, N_Vector z)
{
z->menv->ops->nvconst(c, z);
}
void
N_VProd(N_Vector x, N_Vector y, N_Vector z)
{
z->menv->ops->nvprod(x, y, z);
}
void
N_VDiv(N_Vector x, N_Vector y, N_Vector z)
{
z->menv->ops->nvdiv(x, y, z);
}
void
N_VScale(realtype c, N_Vector x, N_Vector z)
{
z->menv->ops->nvscale(c, x, z);
}
void
N_VAbs(N_Vector x, N_Vector z)
{
z->menv->ops->nvabs(x, z);
}
void
N_VInv(N_Vector x, N_Vector z)
{
z->menv->ops->nvinv(x, z);
}
void
N_VAddConst(N_Vector x, realtype b, N_Vector z)
{
z->menv->ops->nvaddconst(x, b, z);
}
realtype
N_VDotProd(N_Vector x, N_Vector y)
{
realtype prod;
prod = y->menv->ops->nvdotprod(x, y);
return (prod);
}
realtype
N_VMaxNorm(N_Vector x)
{
realtype norm;
norm = x->menv->ops->nvmaxnorm(x);
return (norm);
}
realtype
N_VWrmsNorm(N_Vector x, N_Vector w)
{
realtype norm;
norm = x->menv->ops->nvwrmsnorm(x, w);
return (norm);
}
realtype
N_VMin(N_Vector x)
{
realtype minval;
minval = x->menv->ops->nvmin(x);
return (minval);
}
realtype
N_VWL2Norm(N_Vector x, N_Vector w)
{
realtype norm;
norm = x->menv->ops->nvwl2norm(x, w);
return (norm);
}
realtype
N_VL1Norm(N_Vector x)
{
realtype norm;
norm = x->menv->ops->nvl1norm(x);
return (norm);
}
void
N_VOneMask(N_Vector x)
{
x->menv->ops->nvonemask(x);
}
void
N_VCompare(realtype c, N_Vector x, N_Vector z)
{
z->menv->ops->nvcompare(c, x, z);
}
booleantype
N_VInvTest(N_Vector x, N_Vector z)
{
booleantype flag;
flag = z->menv->ops->nvinvtest(x, z);
return (flag);
}
booleantype
N_VConstrProdPos(N_Vector c, N_Vector x)
{
booleantype flag;
flag = x->menv->ops->nvconstrprodpos(c, x);
return (flag);
}
booleantype
N_VConstrMask(N_Vector c, N_Vector x, N_Vector m)
{
booleantype flag;
flag = x->menv->ops->nvconstrmask(c, x, m);
return (flag);
}
realtype
N_VMinQuotient(N_Vector num, N_Vector denom)
{
realtype quotient;
quotient = num->menv->ops->nvminquotient(num, denom);
return (quotient);
}
void
N_VPrint(N_Vector x)
{
x->menv->ops->nvprint(x);
}
| 28.311355 | 76 | 0.514167 | usgs-coupled |
1daaeab8f7c7325dbb5d2011e0070c0dbbb5391a | 2,789 | cpp | C++ | distributions/univariate/continuous/InverseGaussianRand.cpp | aWeinzierl/RandLib | 7af0237d1902aadbf2451b7dfab02c52cf98ae87 | [
"MIT"
] | null | null | null | distributions/univariate/continuous/InverseGaussianRand.cpp | aWeinzierl/RandLib | 7af0237d1902aadbf2451b7dfab02c52cf98ae87 | [
"MIT"
] | null | null | null | distributions/univariate/continuous/InverseGaussianRand.cpp | aWeinzierl/RandLib | 7af0237d1902aadbf2451b7dfab02c52cf98ae87 | [
"MIT"
] | null | null | null | #include "InverseGaussianRand.h"
#include "NormalRand.h"
#include "UniformRand.h"
InverseGaussianRand::InverseGaussianRand(double mean, double shape)
{
SetParameters(mean, shape);
}
String InverseGaussianRand::Name() const
{
return "Inverse-Gaussian(" + toStringWithPrecision(GetMean()) + ", " + toStringWithPrecision(GetShape()) + ")";
}
void InverseGaussianRand::SetParameters(double mean, double shape)
{
if (mean <= 0.0)
throw std::invalid_argument("Inverse-Gaussian distribution: mean should be positive");
if (shape <= 0.0)
throw std::invalid_argument("Inverse-Gaussian distribution: shape should be positive");
mu = mean;
lambda = shape;
pdfCoef = 0.5 * std::log(0.5 * lambda * M_1_PI);
cdfCoef = std::exp(2 * lambda / mu);
}
double InverseGaussianRand::f(const double & x) const
{
return (x > 0.0) ? std::exp(logf(x)) : 0.0;
}
double InverseGaussianRand::logf(const double & x) const
{
if (x <= 0.0)
return -INFINITY;
double y = -1.5 * std::log(x);
double z = (x - mu);
z *= z;
z *= -0.5 * lambda / (x * mu * mu);
z += pdfCoef;
return y + z;
}
double InverseGaussianRand::F(const double & x) const
{
if (x <= 0.0)
return 0.0;
double b = std::sqrt(0.5 * lambda / x);
double a = b * x / mu;
double y = std::erfc(b - a);
y += cdfCoef * std::erfc(a + b);
return 0.5 * y;
}
double InverseGaussianRand::S(const double & x) const
{
if (x <= 0.0)
return 1.0;
double b = std::sqrt(0.5 * lambda / x);
double a = b * x / mu;
double y = std::erfc(a - b);
y -= cdfCoef * std::erfc(a + b);
return 0.5 * y;
}
double InverseGaussianRand::Variate() const
{
double X = NormalRand::StandardVariate(localRandGenerator);
double U = UniformRand::StandardVariate(localRandGenerator);
X *= X;
double mupX = mu * X;
double y = 4 * lambda + mupX;
y = std::sqrt(y * mupX);
y -= mupX;
y *= -0.5 / lambda;
++y;
if (U * (1 + y) > 1.0)
y = 1.0 / y;
return mu * y;
}
double InverseGaussianRand::Mean() const
{
return mu;
}
double InverseGaussianRand::Variance() const
{
return mu * mu * mu / lambda;
}
std::complex<double> InverseGaussianRand::CFImpl(double t) const
{
double im = mu * mu;
im *= t / lambda;
std::complex<double> y(1, -im - im);
y = 1.0 - std::sqrt(y);
y *= lambda / mu;
return std::exp(y);
}
double InverseGaussianRand::Mode() const
{
double aux = 1.5 * mu / lambda;
double mode = 1 + aux * aux;
mode = std::sqrt(mode);
mode -= aux;
return mu * mode;
}
double InverseGaussianRand::Skewness() const
{
return 3 * std::sqrt(mu / lambda);
}
double InverseGaussianRand::ExcessKurtosis() const
{
return 15 * mu / lambda;
}
| 23.049587 | 115 | 0.59663 | aWeinzierl |
1dade2debcc8231dc0676d580e1b76419631cd4f | 2,192 | cpp | C++ | Functions/FunctionAVX.cpp | alisa-vernigor/MathForTypingAnalysis | 28e72c8fbf116ddb379b1d823efbf3c5b99b3896 | [
"MIT"
] | null | null | null | Functions/FunctionAVX.cpp | alisa-vernigor/MathForTypingAnalysis | 28e72c8fbf116ddb379b1d823efbf3c5b99b3896 | [
"MIT"
] | null | null | null | Functions/FunctionAVX.cpp | alisa-vernigor/MathForTypingAnalysis | 28e72c8fbf116ddb379b1d823efbf3c5b99b3896 | [
"MIT"
] | null | null | null | #include "Function.h"
#include "vectorclass/vectorclass.h"
#include "vectorclass/vectormath_exp.h"
namespace NSMathModule {
namespace NSFunctions {
double CDensity0::compute0_AVX(const std::vector<double>& means, double arg) {
double tmp_result = 0;
size_t regular_part = means.size() & static_cast<size_t>(-4);
for (size_t index = 0; index < regular_part; index += 4) {
Vec4d means_block(means[index], means[index + 1], means[index + 2],
means[index + 3]);
tmp_result += find_derivative_0(means_block, arg);
}
for (size_t index = regular_part; index < means.size(); ++index) {
double mean = means[regular_part];
tmp_result += find_derivative_0(mean, arg);
}
return tmp_result / static_cast<double>(means.size());
}
double CDensity1::compute1_AVX(const std::vector<double>& means, double arg) {
double tmp_result = 0;
size_t regular_part = means.size() & static_cast<size_t>(-4);
for (size_t index = 0; index < regular_part; index += 4) {
Vec4d means_block(means[index], means[index + 1], means[index + 2],
means[index + 3]);
tmp_result += find_derivative_1(means_block, arg);
}
for (size_t index = regular_part; index < means.size(); ++index) {
double mean = means[regular_part];
tmp_result += find_derivative_1(mean, arg);
}
return tmp_result / static_cast<double>(means.size());
}
double CDensity2::compute2_AVX(const std::vector<double>& means, double arg) {
double tmp_result = 0;
size_t regular_part = means.size() & static_cast<size_t>(-4);
for (size_t index = 0; index < regular_part; index += 4) {
Vec4d means_block(means[index], means[index + 1], means[index + 2],
means[index + 3]);
tmp_result += find_derivative_2(means_block, arg);
}
for (size_t index = regular_part; index < means.size(); ++index) {
double mean = means[regular_part];
tmp_result += find_derivative_2(mean, arg);
}
return tmp_result / static_cast<double>(means.size());
}
}
}
| 35.934426 | 82 | 0.614507 | alisa-vernigor |
1db08e9350390ee0af6d3a24c1e181f70bfb3f20 | 12,144 | cpp | C++ | trunk/libs/platform/source/win32/core_app.cpp | ChuyX3/angsys | 89b2eaee866bcfd11e66efda49b38acc7468c780 | [
"Apache-2.0"
] | null | null | null | trunk/libs/platform/source/win32/core_app.cpp | ChuyX3/angsys | 89b2eaee866bcfd11e66efda49b38acc7468c780 | [
"Apache-2.0"
] | null | null | null | trunk/libs/platform/source/win32/core_app.cpp | ChuyX3/angsys | 89b2eaee866bcfd11e66efda49b38acc7468c780 | [
"Apache-2.0"
] | null | null | null | #include "pch.h"
#include <ang/platform/platform.h>
#include <ang/core/time.h>
#include "dispatcher.h"
#include "core_app.h"
#include <comdef.h>
#include <windowsx.h>
using namespace ang;
using namespace ang::platform;
using namespace ang::platform::events;
using namespace ang::platform::windows;
namespace ang::platform {
extern icore_app* s_current_app;
}
LRESULT STDCALL core_app::wndproc(HWND hwnd, UINT m, WPARAM wprm, LPARAM lprm)
{
message msg((core_msg)m, wprm, lprm);
core_app_t wnd = null;
if ((core_msg::created == (core_msg)m) && (lprm != 0))
{
LPCREATESTRUCT pcs = (LPCREATESTRUCT)lprm;
if (pcs->lpCreateParams)
{
wnd = (core_app*)pcs->lpCreateParams;
wnd->m_hwnd = hwnd;
SetWindowLongPtrW(hwnd, GWLP_USERDATA, (LONG_PTR)pcs->lpCreateParams);
}
}
else
{
wnd = reinterpret_cast<core_app*>(GetWindowLongPtrW(hwnd, GWLP_USERDATA));
}
if (!wnd.is_empty())
{
wnd->wndproc(msg);
return msg.result();
}
return DefWindowProcW(hwnd, m, wprm, lprm);
}
core_app::core_app()
: m_hint(null)
, m_hwnd(null)
{
s_current_app = this;
m_thread = core::async::thread::this_thread();
m_timer.reset();
m_controllers = new input::controller_manager();
}
core_app::~core_app()
{
m_controllers = null;
s_current_app = null;
}
pointer core_app::core_app_handle()const
{
return m_hint;
}
icore_view_t core_app::core_view()
{
return this;
}
input::ikeyboard_t core_app::keyboard()
{
return null;
}
ivar core_app::property(astring name)const
{
return null;
}
void core_app::property(astring name, ivar var)
{
}
pointer core_app::core_view_handle()const
{
return m_hwnd;
}
graphics::icore_context_t core_app::core_context()const
{
return new graphics::device_context(const_cast<core_app*>(this));
}
graphics::size<float> core_app::core_view_size()const
{
if (IsWindow(m_hwnd)) {
RECT rc;
GetClientRect(m_hwnd, &rc);
return { float(rc.right - rc.left), float(rc.bottom - rc.top) };
}
return{ 0,0 };
}
graphics::size<float> core_app::core_view_scale_factor()const
{
return{ 1.0f,1.0f };
}
imessage_listener_t core_app::dispatcher()const
{
return const_cast<core_app*>(this);
}
error core_app::run(function<error(icore_app_t)> setup, app_args_t& args)
{
//m_frm = frm;
m_thread = core::async::thread::this_thread();
error err = setup(this);
wstring name = args.name->cstr();
wstring title = args.title->cstr();
if (err.code() != error_code::success)
return err;
setup = null;//releasing scope
WNDCLASSEXW wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC | CS_SAVEBITS;
wcex.lpfnWndProc = &core_app::wndproc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = m_hint;
wcex.hIcon = NULL;
wcex.hCursor = LoadCursor(nullptr, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wcex.lpszMenuName = NULL;
wcex.lpszClassName = name.cstr();
wcex.hIconSm = NULL;
RegisterClassExW(&wcex);;
HWND hwnd = CreateWindowExW(0, name.cstr(), title.cstr(), WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, nullptr, nullptr, m_hint, this);
if (!hwnd)
{
_com_error err(GetLastError());
castr_t msg(err.ErrorMessage(), -1);
return error(err.Error(), msg, error_code::system_error);
}
ShowWindow(hwnd, SW_SHOW);
UpdateWindow(hwnd);
core::time::step_timer timer;
if (args.fps > 0)
{
timer.frames_per_second(args.fps);
timer.fixed_time_step(true);
}
// Main message loop:
MSG msg;
while (true)
{
core::async::async_action_status_t status = m_thread->status();
if (status & core::async::async_action_status::canceled)
PostQuitMessage(0);
if (PeekMessageW(&msg, NULL, 0, 0, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessageW(&msg);
/*if (msg.hwnd == NULL)
{
events::message m{ (events::core_msg)msg.message, msg.wParam, msg.lParam };
wndproc(m);
}*/
}
if (msg.message == WM_QUIT)
break;
else timer.tick([&]() {
m_controllers->update(timer.elapsed_time());
SendMessageW(m_hwnd, (UINT)core_msg::update, timer.elapsed_time(), timer.total_time());
});
}
return error_code::success;
}
void core_app::wndproc(events::message& msg)
{
switch (msg.msg())
{
case core_msg::created: {
//auto cs = LPCREATESTRUCT((LPARAM)msg.lparam());
on_created(msg);
}break;
case core_msg::destroyed: {
on_destroyed(msg);
} break;
case (core_msg)WM_ERASEBKGND:
case core_msg::draw: {
on_draw(msg);
} break;
case core_msg::update: {
on_update(msg);
} break;
case core_msg::display_change:
case core_msg::orientation:
case core_msg::size: {
on_display_event(msg);
} break;
case core_msg::system_reserved_event: {
on_task_command(msg);
}
case core_msg::got_focus:
case core_msg::lost_focus: {
on_activate(msg);
} break;
case core_msg::pointer_entered:
case core_msg::pointer_pressed:
case core_msg::pointer_moved:
case core_msg::pointer_released:
case core_msg::pointer_leaved: {
on_pointer_event(msg);
} break;
case core_msg::mouse_move:
case core_msg::lbutton_down:
case core_msg::rbutton_down:
case (core_msg)WM_XBUTTONDOWN:
case core_msg::lbutton_up:
case core_msg::rbutton_up:
case (core_msg)WM_XBUTTONUP: {
on_mouse_event(msg);
} break;
case core_msg::key_down:
case core_msg::put_char:
case core_msg::key_up: {
on_key_event(msg);
break;
}
default: {
def_wndproc(msg);
} break;
}
}
void core_app::def_wndproc(events::message& msg)
{
msg.result(DefWindowProcW(m_hwnd, (uint)(core_msg)msg.msg(), (WPARAM)msg.wparam(), (LPARAM)msg.lparam()));
}
dword core_app::on_created(events::message& m)
{
auto it = m_event_listeners.find(m.msg());
if (it.is_valid()) {
icreated_event_args_t args = new created_event_args(m, this, null);
try {
it->value->invoke(args.get());
}
catch (const exception & e) {
}
}
def_wndproc(m);
return m.result();
}
dword core_app::on_destroyed(events::message& m)
{
auto it = m_event_listeners.find(m.msg());
if (it.is_valid()) {
imsg_event_args_t args = new msg_event_args(m);
try {
it->value->invoke(args.get());
}
catch (const exception & e) {
}
}
m_event_listeners.clear();
def_wndproc(m);
PostQuitMessage(m.lparam());
return m.result();
}
dword core_app::on_draw(events::message& m)
{
auto it = m_event_listeners.find(m.msg());
if (it.is_valid()) {
graphics::device_context_t dc = new graphics::paint_dc(this);
if (dc->get_HDC() == null)
dc = new graphics::device_context(this);
idraw_event_args_t args = new draw_event_args(m, this, dc, core_view_size());
try {
it->value->invoke(args.get());
}
catch (const exception & e) {
}
}
m.result(0);
return m.result();
}
dword core_app::on_update(events::message& m)
{
auto it = m_event_listeners.find(m.msg());
if (it.is_valid()) {
imsg_event_args_t args = new msg_event_args(m);
try {
it->value->invoke(args.get());
}
catch (const exception & e) {
}
}
m.result(0);
return m.result();
}
dword core_app::on_activate(events::message& m)
{
int handled = 0;
auto it = m_event_listeners.find(m.msg());
if (it.is_valid()) {
activate_status_t status = m.msg() == core_msg::got_focus ? activate_status::activated : activate_status::deactivated;
iactivate_event_args_t args = new activate_event_args(m, status);
try {
handled = it->value->invoke(args.get());
}
catch (const exception & e) {
}
}
if (!handled) def_wndproc(m);
else m.result(0);
return m.result();
}
dword core_app::on_display_event(events::message& m)
{
auto it = m_event_listeners.find(m.msg());
if (it.is_valid()) {
dword value = (dword)m.lparam();
display_invalidate_reason_t reason
= m.msg() == core_msg::size ? display_invalidate_reason::size_changed
: m.msg() == core_msg::display_change ? display_invalidate_reason::display_invalidate
: m.msg() == core_msg::orientation ? display_invalidate_reason::orientation_changed
: display_invalidate_reason::none;
display::display_info info = {
system_info::current_screen_orientation(),
system_info::current_screen_orientation(),
graphics::size<float>((float)LOWORD(value), (float)HIWORD(value)),
core_view_scale_factor(),
96
};
m.result(-1);
idisplay_info_event_args_t args = new display_info_event_args(m, this, reason, info);
try {
it->value->invoke(args.get());
}
catch (const exception & e) {
}
}
def_wndproc(m);
return m.result();
}
dword core_app::on_pointer_event(events::message& m)
{
int handled = 0;
auto it = m_event_listeners.find(m.msg());
if (it.is_valid()) {
WPARAM wprm = (WPARAM)m.wparam();
LPARAM lprm = (LPARAM)m.lparam();
short id;
bool is_pa;
bool is_sa;
input::pointer_hardware_type_t type;
input::key_modifiers_t modifiers = input::key_modifiers::none;
POINTER_INFO pi;
id = (short)GET_POINTERID_WPARAM(wprm);
GetPointerInfo((uint)id, &pi);
type = (input::pointer_hardware_type)(pi.pointerType - 2);
is_pa = IS_POINTER_FIRSTBUTTON_WPARAM(wprm);
is_sa = IS_POINTER_SECONDBUTTON_WPARAM(wprm);
//POINTER_MOD_SHIFT
modifiers += ((POINTER_MOD_CTRL & pi.dwKeyStates) == POINTER_MOD_CTRL) ? input::key_modifiers::control : input::key_modifiers::none;
modifiers += ((POINTER_MOD_SHIFT & pi.dwKeyStates) == POINTER_MOD_SHIFT) ? input::key_modifiers::shift : input::key_modifiers::none;
ipointer_event_args_t args = new pointer_event_args(m, {
graphics::point<float>((float)GET_X_LPARAM(lprm), (float)GET_Y_LPARAM(lprm)),
id,
is_pa,
is_sa,
type,
modifiers,
});
int count = 0;
try {
handled = it->value->invoke(args.get());
}
catch (const exception & e) {
}
}
if (!handled) def_wndproc(m);
else m.result(0);
return m.result();
}
dword core_app::on_mouse_event(events::message& m)
{
int handled = 0;
auto it = m_event_listeners.find(m.msg());
if (it.is_valid()) {
WPARAM wprm = (WPARAM)m.wparam();
LPARAM lprm = m.lparam();
short id;
bool is_pa;
bool is_sa;
input::pointer_hardware_type_t type;
input::key_modifiers_t modifiers = input::key_modifiers::none;
id = 1U;
is_pa = (MK_LBUTTON & wprm) == MK_LBUTTON;
is_sa = (MK_RBUTTON & wprm) == MK_RBUTTON;
type = input::pointer_hardware_type::mouse;
modifiers += ((MK_CONTROL & wprm) == MK_CONTROL) ? input::key_modifiers::control : input::key_modifiers::none;
modifiers += ((MK_SHIFT & wprm) == MK_SHIFT) ? input::key_modifiers::shift : input::key_modifiers::none;
ipointer_event_args_t args = new pointer_event_args(m, {
graphics::point<float>((float)GET_X_LPARAM(lprm), (float)GET_Y_LPARAM(lprm)),
id,
is_pa,
is_sa,
type,
modifiers,
});
int count = 0;
try {
handled = it->value->invoke(args.get());
}
catch (const exception & e) {
}
}
if (!handled) def_wndproc(m);
else m.result(0);
return m.result();
}
dword core_app::on_key_event(events::message& m)
{
auto it = m_event_listeners.find(m.msg());
if (it.is_valid()) {
uint modifiers = 0;
if (GetKeyState(VK_CONTROL) && 0x8000)
modifiers |= (uint)input::key_modifiers::control;
if (GetKeyState(VK_SHIFT) && 0x8000)
modifiers |= (uint)input::key_modifiers::shift;
if (GetKeyState(VK_MENU) && 0x8000)
modifiers |= (uint)input::key_modifiers::alt;
if (GetKeyState(VK_CAPITAL) && 0x0001)
modifiers |= (uint)input::key_modifiers::caps_lock;
if (GetKeyState(VK_NUMLOCK) && 0x0001)
modifiers |= (uint)input::key_modifiers::num_lock;
ikey_event_args_t args = new key_event_args(m, {
(input::virtual_key)m.wparam(), //property<const virtual_key> key;
(char32_t)m.wparam(), //property<const virtual_key> key;
(word)(uint)m.lparam(), //property<const word> flags;
m.msg() == core_msg::key_down ? input::key_state::pressed
: m.msg() == core_msg::put_char ? input::key_state::pressed
: input::key_state::released,
(input::key_modifiers)modifiers //property<const key_modifiers> modifiers;
});
m.result(-1);
try {
it->value->invoke(args.get());
}
catch (const exception & e) {
}
}
def_wndproc(m);
return m.result();
}
dword core_app::on_task_command(events::message& m)
{
auto task = reinterpret_cast<async_task*>(m.lparam());
task->execute();
task->release();
m.result(0);
return 0;
}
| 23.353846 | 134 | 0.691041 | ChuyX3 |
1dbb1922e53cbb91c97d0eb823fb5d585d09ed3a | 876 | cpp | C++ | CodeFights/differentSubstrings.cpp | AREA44/competitive-programming | 00cede478685bf337193bce4804f13c4ff170903 | [
"MIT"
] | null | null | null | CodeFights/differentSubstrings.cpp | AREA44/competitive-programming | 00cede478685bf337193bce4804f13c4ff170903 | [
"MIT"
] | null | null | null | CodeFights/differentSubstrings.cpp | AREA44/competitive-programming | 00cede478685bf337193bce4804f13c4ff170903 | [
"MIT"
] | null | null | null | // Given a string, find the number of different non-empty substrings in it.
// Example
// For inputString = "abac", the output should be
// differentSubstrings(inputString) = 9.
string substring(std::string inputString, int start, int end){
std::string resultString;
for(int i=start;i<end;i++)
resultString+=inputString[i];
return resultString;
}
int differentSubstrings(std::string inputString) {
std::vector<std::string> substrings;
int result = 1;
for (int i = 0; i < inputString.size(); i++) {
for (int j = i + 1; j <= inputString.size(); j++) {
substrings.push_back(substring(inputString,i,j));
}
}
sort(substrings.begin(),substrings.end());
for (int i = 1; i < substrings.size(); i++) {
if (substrings[i] != substrings[i - 1]) {
result++;
}
}
return result;
}
| 30.206897 | 75 | 0.606164 | AREA44 |
1dbf91e581bdbaf7c3e59cdfeaf4f7d19790ba7e | 1,648 | hpp | C++ | lumino/Graphics/src/Animation/AnimationManager.hpp | lriki/Lumino | 1a80430f4a83dbdfbe965b3d5b16064991b3edb0 | [
"MIT"
] | 30 | 2016-01-24T05:35:45.000Z | 2020-03-03T09:54:27.000Z | lumino/Graphics/src/Animation/AnimationManager.hpp | lriki/Lumino | 1a80430f4a83dbdfbe965b3d5b16064991b3edb0 | [
"MIT"
] | 35 | 2016-04-18T06:14:08.000Z | 2020-02-09T15:51:58.000Z | lumino/Graphics/src/Animation/AnimationManager.hpp | lriki/Lumino | 1a80430f4a83dbdfbe965b3d5b16064991b3edb0 | [
"MIT"
] | 5 | 2016-04-03T02:52:05.000Z | 2018-01-02T16:53:06.000Z | #pragma once
#include <LuminoGraphics/Animation/Common.hpp>
#include <LuminoGraphics/Animation/AnimationClip.hpp>
#include <LuminoEngine/Base/detail/RefObjectCache.hpp>
namespace ln {
class AnimationClock;
namespace detail {
class AnimationManager : public RefObject {
public:
struct Settings {
AssetManager* assetManager = nullptr;
};
static AnimationManager* initialize(const Settings& settings);
static void terminate();
static inline AnimationManager* instance() { return s_instance; }
// void setSceneManager(SceneManager* sceneManager) { m_sceneManager = sceneManager; }
const Ref<AnimationClipImportSettings>& defaultAnimationClipImportSettings() const { return m_defaultAnimationClipImportSettings; }
void addClockToAffiliation(AnimationClock* clock, AnimationClockAffiliation affiliation);
Ref<GenericTask<Ref<AnimationClip>>> loadAnimationClip(const StringView& filePath);
// Ref<AnimationClipPromise> loadAnimationClipAsync(const StringView& filePath);
// Ref<AnimationClip> acquireAnimationClip(const AssetPath& assetPath);
// void loadAnimationClip(AnimationClip* clip, const AssetPath& assetPath);
void updateFrame(float elapsedSeconds);
private:
AnimationManager();
virtual ~AnimationManager();
Result init(const Settings& settings);
void dispose();
AssetManager* m_assetManager;
// SceneManager* m_sceneManager;
ObjectCache<String, AnimationClip> m_animationClipCache;
Ref<AnimationClipImportSettings> m_defaultAnimationClipImportSettings;
static Ref<AnimationManager> s_instance;
};
} // namespace detail
} // namespace ln
| 34.333333 | 135 | 0.771238 | lriki |
1dc0cf1354ab9c6c14c387bb3ada9152c85a255a | 3,536 | cpp | C++ | Source/Core/DX_12/DX_12Image.cpp | glowing-chemist/Bell | 0cf4d0ac925940869077779700c1d3bd45ff841f | [
"MIT"
] | 14 | 2020-02-12T19:13:46.000Z | 2022-03-05T02:26:06.000Z | Source/Core/DX_12/DX_12Image.cpp | glowing-chemist/Bell | 0cf4d0ac925940869077779700c1d3bd45ff841f | [
"MIT"
] | 5 | 2020-08-06T07:19:47.000Z | 2021-01-05T21:20:51.000Z | Source/Core/DX_12/DX_12Image.cpp | glowing-chemist/Bell | 0cf4d0ac925940869077779700c1d3bd45ff841f | [
"MIT"
] | 2 | 2021-09-18T13:36:47.000Z | 2021-12-04T15:08:53.000Z | #include "DX_12Image.hpp"
#include "DX_12RenderDevice.hpp"
#include "Core/ConversionUtils.hpp"
#include <algorithm>
DX_12Image::DX_12Image( RenderDevice* device,
const Format format,
const ImageUsage usage,
const uint32_t x,
const uint32_t y,
const uint32_t z,
const uint32_t mips,
const uint32_t levels,
const uint32_t samples,
const std::string& name) :
ImageBase(device, format, usage, x, y, z, mips, levels, samples, name),
mIsOwned(true)
{
D3D12_RESOURCE_DIMENSION type;
if (x != 0 && y == 0 && z == 0) type = D3D12_RESOURCE_DIMENSION::D3D12_RESOURCE_DIMENSION_TEXTURE1D;
if (x != 0 && y != 0 && z == 1) type = D3D12_RESOURCE_DIMENSION::D3D12_RESOURCE_DIMENSION_TEXTURE2D;
if (x != 0 && y != 0 && z > 1) type = D3D12_RESOURCE_DIMENSION::D3D12_RESOURCE_DIMENSION_TEXTURE3D;
D3D12_RESOURCE_DESC imageDesc{};
imageDesc.Width = x;
imageDesc.Height = y;
imageDesc.DepthOrArraySize = std::max(z, levels);
imageDesc.Dimension = type;
imageDesc.Layout = D3D12_TEXTURE_LAYOUT::D3D12_TEXTURE_LAYOUT_UNKNOWN;
imageDesc.Format = getDX12ImageFormat(format);
imageDesc.MipLevels = mips;
imageDesc.Alignment = D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT;
imageDesc.Flags = getDX12ImageUsage(usage);
DXGI_SAMPLE_DESC sampleDesc{};
sampleDesc.Count = samples;
sampleDesc.Quality = 0;
imageDesc.SampleDesc = sampleDesc;
DX_12RenderDevice* dev = static_cast<DX_12RenderDevice*>(getDevice());
const D3D12MA::ALLOCATION_DESC allocDesc = dev->getResourceAllocationDescription(usage);
dev->createResource(imageDesc, allocDesc, D3D12_RESOURCE_STATE_COMMON , &mImage, &mImageMemory);
}
DX_12Image::DX_12Image(RenderDevice* device,
ID3D12Resource* resource,
const Format format,
const ImageUsage usage,
const uint32_t x,
const uint32_t y,
const uint32_t z,
const uint32_t mips,
const uint32_t levels,
const uint32_t samples,
const std::string& name) :
ImageBase(device, format, usage, x, y, z, mips, levels, samples, name)
{
mImage = resource;
mImageMemory = nullptr;
mIsOwned = false;
}
DX_12Image::~DX_12Image()
{
if(mIsOwned)
getDevice()->destroyImage(*this);
}
void DX_12Image::swap(ImageBase& other)
{
ImageBase::swap(other);
DX_12Image& DXImage = static_cast<DX_12Image&>(other);
ID3D12Resource* tmpImage = mImage;
D3D12MA::Allocation* tmpMemory = DXImage.mImageMemory;
mImage = DXImage.mImage;
mImageMemory = DXImage.mImageMemory;
DXImage.mImage = tmpImage;
DXImage.mImageMemory = tmpMemory;
}
void DX_12Image::setContents( const void* data,
const uint32_t xsize,
const uint32_t ysize,
const uint32_t zsize,
const uint32_t level,
const uint32_t lod,
const int32_t offsetx,
const int32_t offsety,
const int32_t offsetz)
{
BELL_LOG("DX_12Image::SetContents not implemented")
}
void DX_12Image::clear(const float4&)
{
BELL_LOG("DX_12Image::clear not implemented")
}
void DX_12Image::generateMips()
{
BELL_LOG("DX_12Image::generateMips not implemented")
} | 31.017544 | 104 | 0.628394 | glowing-chemist |
1dc53e9641207626cc069fd7d6a480be67324a19 | 7,594 | cpp | C++ | GPTP/src/hooks/unit_morph_inject.cpp | idmontie/gptp | 14d68e5eac84c2f3085ac25a7fff31a07ea387f6 | [
"0BSD"
] | 8 | 2015-04-03T16:50:59.000Z | 2021-01-06T17:12:29.000Z | GPTP/src/hooks/unit_morph_inject.cpp | idmontie/gptp | 14d68e5eac84c2f3085ac25a7fff31a07ea387f6 | [
"0BSD"
] | 6 | 2015-04-03T18:10:56.000Z | 2016-02-18T05:04:21.000Z | GPTP/src/hooks/unit_morph_inject.cpp | idmontie/gptp | 14d68e5eac84c2f3085ac25a7fff31a07ea387f6 | [
"0BSD"
] | 6 | 2015-04-04T04:37:33.000Z | 2018-04-09T09:03:50.000Z | #include "unit_morph.h"
#include <hook_tools.h>
#include <SCBW/api.h>
#include <cassert>
namespace {
//-------- CMDRECV_UnitMorph --------//
const u32 Func_AddUnitToBuildQueue = 0x00467250;
bool addUnitToBuildQueue(const CUnit *unit, u16 unitId) {
static u32 result;
u32 unitId_ = unitId;
__asm {
PUSHAD
PUSH unitId_
MOV EDI, unit
CALL Func_AddUnitToBuildQueue
MOV result, EAX
POPAD
}
return result != 0;
}
void __stdcall unitMorphWrapper_CMDRECV_UnitMorph(u8 *commandData) {
const u16 morphUnitId = *((u16*)&commandData[1]);
*selectionIndexStart = 0;
while (CUnit *unit = getActivePlayerNextSelection()) {
if (hooks::unitCanMorphHook(unit, morphUnitId)
&& unit->mainOrderId != OrderId::Morph1
&& addUnitToBuildQueue(unit, morphUnitId))
{
unit->orderTo(OrderId::Morph1);
}
}
scbw::refreshConsole();
}
//-------- BTNSCOND_CanBuildUnit --------//
s32 __fastcall unitMorphWrapper_BTNSCOND_CanBuildUnit(u16 buildUnitId, s32 playerId, const CUnit *unit) {
if (*clientSelectionCount <= 1
|| hooks::getUnitMorphEggTypeHook(unit->id) != UnitId::None)
return unit->canMakeUnit(buildUnitId, playerId);
return 0;
}
//-------- Orders_Morph1 --------//
const u32 Hook_Orders_Morph1_Check_Success = 0x0045DFCA;
void __declspec(naked) unitMorphWrapper_Orders_Morph1_Check() {
static CUnit *unit;
__asm {
PUSHAD
MOV EBP, ESP
MOV unit, ESI
}
if (hooks::getUnitMorphEggTypeHook(unit->id) != UnitId::None) {
__asm {
POPAD
JMP Hook_Orders_Morph1_Check_Success
}
}
else {
__asm {
POPAD
POP EDI
POP ESI
MOV ESP, EBP
POP EBP
RETN
}
}
}
const u32 Hook_Orders_Morph1_EggType_Return = 0x0045E048;
void __declspec(naked) unitMorphWrapper_Orders_Morph1_EggType() {
static CUnit *unit;
static u32 morphEggType;
__asm {
PUSHAD
MOV EBP, ESP
MOV unit, ESI
}
unit->status &= ~(UnitStatus::Completed);
morphEggType = hooks::getUnitMorphEggTypeHook(unit->id);
assert(hooks::isEggUnitHook(morphEggType));
__asm {
POPAD
PUSH morphEggType
JMP Hook_Orders_Morph1_EggType_Return
}
}
//-------- hasSuppliesForUnit --------//
Bool32 __stdcall hasSuppliesForUnitWrapper(u8 playerId, u16 unitId, Bool32 canShowErrorMessage) {
if (hooks::hasSuppliesForUnitHook(playerId, unitId, canShowErrorMessage != 0))
return 1;
else
return 0;
}
//-------- cancelBuild --------//
typedef void(__stdcall *CancelZergBuildingFunc)(CUnit*);
CancelZergBuildingFunc cancelZergBuilding = (CancelZergBuildingFunc)0x0045DA40;
const u32 Func_ChangeUnitType = 0x0049FED0;
void changeUnitType(CUnit *unit, u16 newUnitId) {
u32 newUnitId_ = newUnitId;
__asm {
PUSHAD
PUSH newUnitId_
MOV EAX, unit
CALL Func_ChangeUnitType
POPAD
}
}
const u32 Func_ReplaceSpriteImages = 0x00499BB0;
void replaceSpriteImages(CSprite *sprite, u16 imageId, u8 imageDirection) {
u32 imageId_ = imageId, imageDirection_ = imageDirection;
__asm {
PUSHAD
PUSH imageDirection_
PUSH imageId_
MOV EAX, sprite
CALL Func_ReplaceSpriteImages
POPAD
}
}
//-------- cancelUnit --------//
void __fastcall cancelUnitWrapper(CUnit *unit) {
//Default StarCraft behavior
if (unit->isDead())
return;
if (unit->status & UnitStatus::Completed)
return;
if (unit->id == UnitId::nydus_canal && unit->building.nydusExit)
return;
//Don't bother if unit is not morphed yet
if (unit->id == UnitId::mutalisk || unit->id == UnitId::hydralisk)
return;
//Don't bother if unit has finished morphing
if (unit->id == UnitId::guardian
|| unit->id == UnitId::devourer
|| unit->id == UnitId::lurker)
return;
if (unit->status & UnitStatus::GroundedBuilding) {
if (unit->getRace() == RaceId::Zerg) {
cancelZergBuilding(unit);
return;
}
resources->minerals[unit->playerId] += units_dat::MineralCost[unit->id] * 3 / 4;
resources->gas[unit->playerId] += units_dat::GasCost[unit->id] * 3 / 4;
}
else {
u16 refundUnitId;
if (hooks::isEggUnitHook(unit->id))
refundUnitId = unit->buildQueue[unit->buildQueueSlot % 5];
else
refundUnitId = unit->id;
resources->minerals[unit->playerId] += units_dat::MineralCost[refundUnitId];
resources->gas[unit->playerId] += units_dat::GasCost[refundUnitId];
}
u16 cancelChangeUnitId = hooks::getCancelMorphRevertTypeHook(unit);
if (cancelChangeUnitId == UnitId::None) {
if (unit->id == UnitId::nuclear_missile) {
CUnit *silo = unit->connectedUnit;
if (silo) {
silo->building.silo.nuke = NULL;
silo->mainOrderState = 0;
}
scbw::refreshConsole();
}
unit->remove();
}
else {
changeUnitType(unit, cancelChangeUnitId);
unit->remainingBuildTime = 0;
unit->buildQueue[unit->buildQueueSlot] = UnitId::None;
replaceSpriteImages(unit->sprite,
sprites_dat::ImageId[flingy_dat::SpriteID[units_dat::Graphic[unit->displayedUnitId]]], 0);
unit->orderSignal &= ~0x4;
unit->playIscriptAnim(IscriptAnimation::SpecialState2);
unit->orderTo(OrderId::ZergBirth);
}
}
//-------- getRemainingBuildTimePct --------//
s32 getRemainingBuildTimePctHook(const CUnit *unit) {
u16 unitId = unit->id;
if (hooks::isEggUnitHook(unitId) || unit->isRemorphingBuilding())
unitId = unit->buildQueue[unit->buildQueueSlot];
return 100 * (units_dat::TimeCost[unitId] - unit->remainingBuildTime) / units_dat::TimeCost[unitId];
}
//Inject @ 0x004669E0
void __declspec(naked) getRemainingBuildTimePctWrapper() {
static CUnit *unit;
static s32 percentage;
__asm {
PUSHAD
MOV unit, ESI
MOV EBP, ESP
}
percentage = getRemainingBuildTimePctHook(unit);
__asm {
POPAD
MOV EAX, percentage
RETN
}
}
//-------- orders_zergBirth --------//
//Inject @ 0x0045DE00
const u32 Hook_GetUnitVerticalOffsetOnBirth_Return = 0x0045DE2C;
void __declspec(naked) getUnitVerticalOffsetOnBirthWrapper() {
static CUnit *unit;
static s16 yOffset;
__asm {
PUSHAD
MOV unit, EDI
}
yOffset = hooks::getUnitVerticalOffsetOnBirth(unit);
__asm {
POPAD
MOVSX EAX, yOffset
JMP Hook_GetUnitVerticalOffsetOnBirth_Return
}
}
//Inject @ 0x0045DE57
const u32 Hook_IsRallyableEggUnit_Yes = 0x0045DE6C;
const u32 Hook_IsRallyableEggUnit_No = 0x0045DE8B;
void __declspec(naked) isRallyableEggUnitWrapper() {
static CUnit *unit;
__asm {
POP ESI
POP EBX
PUSHAD
MOV unit, EDI
}
if (hooks::isRallyableEggUnitHook(unit->displayedUnitId)) {
__asm {
POPAD
JMP Hook_IsRallyableEggUnit_Yes
}
}
else {
__asm {
POPAD
JMP Hook_IsRallyableEggUnit_No
}
}
}
} //unnamed namespace
namespace hooks {
void injectUnitMorphHooks() {
callPatch(unitMorphWrapper_CMDRECV_UnitMorph, 0x00486B50);
jmpPatch(unitMorphWrapper_BTNSCOND_CanBuildUnit, 0x00428E60);
jmpPatch(unitMorphWrapper_Orders_Morph1_Check, 0x0045DFB0);
jmpPatch(unitMorphWrapper_Orders_Morph1_EggType, 0x0045E019);
jmpPatch(hasSuppliesForUnitWrapper, 0x0042CF70);
jmpPatch(cancelUnitWrapper, 0x00468280);
jmpPatch(getRemainingBuildTimePctWrapper, 0x004669E0);
jmpPatch(getUnitVerticalOffsetOnBirthWrapper, 0x0045DE00);
jmpPatch(isRallyableEggUnitWrapper, 0x0045DE57);
}
} //hooks
| 25.145695 | 107 | 0.667501 | idmontie |
1dc58721a7bf7de73e554838d8cf09c48780043b | 1,661 | hpp | C++ | include/codegen/include/System/Security/Cryptography/X509Certificates/X509Utils.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 1 | 2021-11-12T09:29:31.000Z | 2021-11-12T09:29:31.000Z | include/codegen/include/System/Security/Cryptography/X509Certificates/X509Utils.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | null | null | null | include/codegen/include/System/Security/Cryptography/X509Certificates/X509Utils.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 2 | 2021-10-03T02:14:20.000Z | 2021-11-12T09:29:36.000Z | // Autogenerated from CppHeaderCreator on 7/27/2020 3:10:18 PM
// Created by Sc2ad
// =========================================================================
#pragma once
#pragma pack(push, 8)
// Begin includes
#include "utils/typedefs.h"
// Including type: System.Object
#include "System/Object.hpp"
#include "utils/il2cpp-utils.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System::Security::Cryptography
namespace System::Security::Cryptography {
// Forward declaring type: OidGroup
struct OidGroup;
}
// Completed forward declares
// Type namespace: System.Security.Cryptography.X509Certificates
namespace System::Security::Cryptography::X509Certificates {
// Autogenerated type: System.Security.Cryptography.X509Certificates.X509Utils
class X509Utils : public ::Il2CppObject {
public:
// static System.String FindOidInfo(System.UInt32 keyType, System.String keyValue, System.Security.Cryptography.OidGroup oidGroup)
// Offset: 0x1206A30
static ::Il2CppString* FindOidInfo(uint keyType, ::Il2CppString* keyValue, System::Security::Cryptography::OidGroup oidGroup);
// static System.String FindOidInfoWithFallback(System.UInt32 key, System.String value, System.Security.Cryptography.OidGroup group)
// Offset: 0x12036A0
static ::Il2CppString* FindOidInfoWithFallback(uint key, ::Il2CppString* value, System::Security::Cryptography::OidGroup group);
}; // System.Security.Cryptography.X509Certificates.X509Utils
}
DEFINE_IL2CPP_ARG_TYPE(System::Security::Cryptography::X509Certificates::X509Utils*, "System.Security.Cryptography.X509Certificates", "X509Utils");
#pragma pack(pop)
| 48.852941 | 147 | 0.747742 | Futuremappermydud |
1dca671d290cc993c2c5635fd7c85612ac28634f | 1,943 | cpp | C++ | Src/EB/AMReX_EB_utils.cpp | khou2020/amrex | 2a75167fd3febd46e0090a89941e42793224ad15 | [
"BSD-3-Clause-LBNL"
] | null | null | null | Src/EB/AMReX_EB_utils.cpp | khou2020/amrex | 2a75167fd3febd46e0090a89941e42793224ad15 | [
"BSD-3-Clause-LBNL"
] | null | null | null | Src/EB/AMReX_EB_utils.cpp | khou2020/amrex | 2a75167fd3febd46e0090a89941e42793224ad15 | [
"BSD-3-Clause-LBNL"
] | 1 | 2020-01-17T05:00:26.000Z | 2020-01-17T05:00:26.000Z | #include <AMReX_EB_F.H>
#include <AMReX_MultiFab.H>
#include <AMReX_EB_utils.H>
#include <AMReX_Geometry.H>
#include <AMReX_MultiCutFab.H>
#include <AMReX_EBFabFactory.H>
namespace amrex {
void FillEBNormals(MultiFab & normals, const EBFArrayBoxFactory & eb_factory,
const Geometry & geom) {
BoxArray ba = normals.boxArray();
DistributionMapping dm = normals.DistributionMap();
int n_grow = normals.nGrow();
// Dummy array for MFIter
MultiFab dummy(ba, dm, 1, n_grow, MFInfo(), eb_factory);
// Area fraction data
std::array<const MultiCutFab*, AMREX_SPACEDIM> areafrac = eb_factory.getAreaFrac();
const auto & flags = eb_factory.getMultiEBCellFlagFab();
#ifdef _OPENMP
#pragma omp parallel
#endif
for(MFIter mfi(dummy, true); mfi.isValid(); ++mfi) {
Box tile_box = mfi.growntilebox();
const int * lo = tile_box.loVect();
const int * hi = tile_box.hiVect();
const auto & flag = flags[mfi];
if (flag.getType(tile_box) == FabType::singlevalued) {
// Target for compute_normals(...)
auto & norm_tile = normals[mfi];
// Area fractions in x, y, and z directions
const auto & af_x_tile = (* areafrac[0])[mfi];
const auto & af_y_tile = (* areafrac[1])[mfi];
const auto & af_z_tile = (* areafrac[2])[mfi];
amrex_eb_compute_normals(lo, hi,
BL_TO_FORTRAN_3D(flag),
BL_TO_FORTRAN_3D(norm_tile),
BL_TO_FORTRAN_3D(af_x_tile),
BL_TO_FORTRAN_3D(af_y_tile),
BL_TO_FORTRAN_3D(af_z_tile) );
}
}
normals.FillBoundary(geom.periodicity());
}
}
| 34.696429 | 91 | 0.545548 | khou2020 |
1dca85fc7bffe94417030860dbab852e517643dc | 14,326 | hpp | C++ | tm_kit/basic/CalculationsOnInit.hpp | cd606/tm_basic | ea2d13b561dd640161823a5e377f35fcb7fe5d48 | [
"Apache-2.0"
] | 1 | 2020-05-22T08:47:02.000Z | 2020-05-22T08:47:02.000Z | tm_kit/basic/CalculationsOnInit.hpp | cd606/tm_basic | ea2d13b561dd640161823a5e377f35fcb7fe5d48 | [
"Apache-2.0"
] | null | null | null | tm_kit/basic/CalculationsOnInit.hpp | cd606/tm_basic | ea2d13b561dd640161823a5e377f35fcb7fe5d48 | [
"Apache-2.0"
] | null | null | null | #ifndef TM_KIT_BASIC_CALCULATIONS_ON_INIT_HPP_
#define TM_KIT_BASIC_CALCULATIONS_ON_INIT_HPP_
#include <tm_kit/infra/RealTimeApp.hpp>
#include <tm_kit/infra/SinglePassIterationApp.hpp>
#include <tm_kit/infra/TopDownSinglePassIterationApp.hpp>
#include <tm_kit/infra/Environments.hpp>
#include <tm_kit/infra/TraceNodesComponent.hpp>
#include <type_traits>
namespace dev { namespace cd606 { namespace tm { namespace basic {
//Importers for calculating value on init
//Please notice that Func takes only one argument (the logger)
//This is deliberate choice. The reason is that if Func needs anything
//inside Env, it should be able to capture that by itself outside this
//logic. If we force Env to maintain something for use of Func, which is
//only executed at startup, there will be trickly resource-release timing
//questions, and by not doing that, we allow Func to manage resources by
//itself.
template <class App, class Func>
class ImporterOfValueCalculatedOnInit {};
template <class Env, class Func>
class ImporterOfValueCalculatedOnInit<infra::template RealTimeApp<Env>, Func>
: public infra::template RealTimeApp<Env>::template AbstractImporter<
decltype((* ((Func *) nullptr))(
std::function<void(infra::LogLevel, std::string const &)>()
))
>
{
private:
Func f_;
public:
using OutputT = decltype((* ((Func *) nullptr))(
std::function<void(infra::LogLevel, std::string const &)>()
));
ImporterOfValueCalculatedOnInit(Func &&f) : f_(std::move(f)) {}
virtual void start(Env *env) override final {
TM_INFRA_IMPORTER_TRACER(env);
this->publish(env, f_(
[env](infra::LogLevel level, std::string const &s) {
env->log(level, s);
}
));
}
};
template <class Env, class Func>
class ImporterOfValueCalculatedOnInit<infra::template SinglePassIterationApp<Env>, Func>
: public infra::template SinglePassIterationApp<Env>::template AbstractImporter<
decltype((* ((Func *) nullptr))(
std::function<void(infra::LogLevel, std::string const &)>()
))
>
{
public:
using OutputT = decltype((* ((Func *) nullptr))(
std::function<void(infra::LogLevel, std::string const &)>()
));
private:
Func f_;
typename infra::template SinglePassIterationApp<Env>::template Data<OutputT> data_;
public:
ImporterOfValueCalculatedOnInit(Func &&f) : f_(std::move(f)), data_(std::nullopt) {}
virtual void start(Env *env) override final {
TM_INFRA_IMPORTER_TRACER(env);
data_ = infra::template SinglePassIterationApp<Env>::template pureInnerData<OutputT>(
env
, f_(
[env](infra::LogLevel level, std::string const &s) {
env->log(level, s);
}
)
, true
);
}
virtual typename infra::template SinglePassIterationApp<Env>::template Data<OutputT> generate() override final {
return data_;
}
};
template <class Env, class Func>
class ImporterOfValueCalculatedOnInit<infra::template TopDownSinglePassIterationApp<Env>, Func>
: public infra::template TopDownSinglePassIterationApp<Env>::template AbstractImporter<
decltype((* ((Func *) nullptr))(
std::function<void(infra::LogLevel, std::string const &)>()
))
>
{
public:
using OutputT = decltype((* ((Func *) nullptr))(
std::function<void(infra::LogLevel, std::string const &)>()
));
private:
Func f_;
typename infra::template TopDownSinglePassIterationApp<Env>::template Data<OutputT> data_;
public:
ImporterOfValueCalculatedOnInit(Func &&f) : f_(std::move(f)), data_(std::nullopt) {}
virtual void start(Env *env) override final {
TM_INFRA_IMPORTER_TRACER(env);
data_ = infra::template TopDownSinglePassIterationApp<Env>::template pureInnerData<OutputT>(
env
, f_(
[env](infra::LogLevel level, std::string const &s) {
env->log(level, s);
}
)
, true
);
}
virtual std::tuple<bool, typename infra::template TopDownSinglePassIterationApp<Env>::template Data<OutputT>> generate() override final {
return {false, std::move(data_)};
}
};
template <class App, class Func>
auto importerOfValueCalculatedOnInit(Func &&f)
-> std::shared_ptr<typename App::template Importer<
typename ImporterOfValueCalculatedOnInit<App,Func>::OutputT
>>
{
return App::importer(
new ImporterOfValueCalculatedOnInit<App,Func>(std::move(f))
);
}
//on order facilities for holding pre-calculated value and returning it on query
template <class App, class Req, class PreCalculatedResult>
class LocalOnOrderFacilityReturningPreCalculatedValue :
public App::template AbstractIntegratedLocalOnOrderFacility<Req, PreCalculatedResult, PreCalculatedResult>
{
private:
std::conditional_t<App::PossiblyMultiThreaded, std::mutex, bool> mutex_;
PreCalculatedResult preCalculatedRes_;
public:
LocalOnOrderFacilityReturningPreCalculatedValue()
: mutex_(), preCalculatedRes_()
{}
virtual void start(typename App::EnvironmentType *) {}
virtual void handle(typename App::template InnerData<typename App::template Key<Req>> &&req) override final {
TM_INFRA_FACILITY_TRACER_WITH_SUFFIX(req.environment, ":handle");
std::conditional_t<App::PossiblyMultiThreaded, std::lock_guard<std::mutex>, bool> _(mutex_);
this->publish(
req.environment
, typename App::template Key<PreCalculatedResult> {
req.timedData.value.id(), preCalculatedRes_
}
, true
);
}
virtual void handle(typename App::template InnerData<PreCalculatedResult> &&data) override final {
TM_INFRA_FACILITY_TRACER_WITH_SUFFIX(data.environment, ":input");
std::conditional_t<App::PossiblyMultiThreaded, std::lock_guard<std::mutex>, bool> _(mutex_);
preCalculatedRes_ = std::move(data.timedData.value);
}
};
template <class App, class Req, class PreCalculatedResult>
auto localOnOrderFacilityReturningPreCalculatedValue()
-> std::shared_ptr<typename App::template LocalOnOrderFacility<Req, PreCalculatedResult, PreCalculatedResult>>
{
return App::localOnOrderFacility(new LocalOnOrderFacilityReturningPreCalculatedValue<App,Req,PreCalculatedResult>());
}
template <class App, class Req, class PreCalculatedResult, class Func>
class LocalOnOrderFacilityUsingPreCalculatedValue :
public App::template AbstractIntegratedLocalOnOrderFacility<
Req
, decltype(
(* ((Func *) nullptr))(
* ((PreCalculatedResult const *) nullptr)
, * ((Req const *) nullptr)
)
)
, PreCalculatedResult
>
{
private:
Func f_;
std::conditional_t<App::PossiblyMultiThreaded, std::mutex, bool> mutex_;
PreCalculatedResult preCalculatedRes_;
public:
using OutputT = decltype(
(* ((Func *) nullptr))(
* ((PreCalculatedResult const *) nullptr)
, * ((Req const *) nullptr)
)
);
LocalOnOrderFacilityUsingPreCalculatedValue(Func &&f) :
f_(std::move(f)), mutex_(), preCalculatedRes_()
{}
virtual void start(typename App::EnvironmentType *) override final {}
virtual void handle(typename App::template InnerData<typename App::template Key<Req>> &&req) override final {
TM_INFRA_FACILITY_TRACER_WITH_SUFFIX(req.environment, ":handle");
std::conditional_t<App::PossiblyMultiThreaded, std::lock_guard<std::mutex>, bool> _(mutex_);
this->publish(
req.environment
, typename App::template Key<OutputT> {
req.timedData.value.id(), f_(preCalculatedRes_, req.timedData.value.key())
}
, true
);
}
virtual void handle(typename App::template InnerData<PreCalculatedResult> &&data) override final {
TM_INFRA_FACILITY_TRACER_WITH_SUFFIX(data.environment, ":input");
std::conditional_t<App::PossiblyMultiThreaded, std::lock_guard<std::mutex>, bool> _(mutex_);
preCalculatedRes_ = std::move(data.timedData.value);
}
};
template <class App, class Req, class PreCalculatedResult, class Func>
auto localOnOrderFacilityUsingPreCalculatedValue(Func &&f)
-> std::shared_ptr<typename App::template LocalOnOrderFacility<Req, typename LocalOnOrderFacilityUsingPreCalculatedValue<App,Req,PreCalculatedResult,Func>::OutputT, PreCalculatedResult>>
{
return App::localOnOrderFacility(new LocalOnOrderFacilityUsingPreCalculatedValue<App,Req,PreCalculatedResult,Func>(std::move(f)));
}
//combination of the two above, on order facilities for
//holding pre-calculated value which is calculated internally
//at init, and returning it on query
template <class App, class Req, class CalcFunc>
class OnOrderFacilityReturningInternallyPreCalculatedValue :
public virtual App::IExternalComponent
, public App::template AbstractOnOrderFacility<
Req
, decltype((std::declval<CalcFunc>())(
std::function<void(infra::LogLevel, std::string const &)>()
))
>
{
public:
using PreCalculatedResult = decltype((std::declval<CalcFunc>())(
std::function<void(infra::LogLevel, std::string const &)>()
));
private:
CalcFunc f_;
PreCalculatedResult preCalculatedRes_;
public:
OnOrderFacilityReturningInternallyPreCalculatedValue(CalcFunc &&f)
: f_(f), preCalculatedRes_()
{}
virtual void start(typename App::EnvironmentType *env) override final {
preCalculatedRes_ = f_(
[env](infra::LogLevel level, std::string const &s) {
env->log(level, s);
}
);
}
virtual void handle(typename App::template InnerData<typename App::template Key<Req>> &&req) override final {
this->publish(
req.environment
, typename App::template Key<PreCalculatedResult> {
req.timedData.value.id(), preCalculatedRes_
}
, true
);
}
};
template <class App, class Req, class CalcFunc>
auto onOrderFacilityReturningInternallyPreCalculatedValue(CalcFunc &&f)
-> std::shared_ptr<typename App::template OnOrderFacility<Req, typename OnOrderFacilityReturningInternallyPreCalculatedValue<App,Req,CalcFunc>::PreCalculatedResult>>
{
return App::fromAbstractOnOrderFacility(new OnOrderFacilityReturningInternallyPreCalculatedValue<App,Req,CalcFunc>(std::move(f)));
}
template <class App, class Req, class CalcFunc, class FetchFunc>
class OnOrderFacilityUsingInternallyPreCalculatedValue :
public virtual App::IExternalComponent
, public App::template AbstractOnOrderFacility<
Req
, decltype(
(std::declval<FetchFunc>())(
* ((typename OnOrderFacilityReturningInternallyPreCalculatedValue<App,Req,CalcFunc>::PreCalculatedResult const *) nullptr)
, * ((Req const *) nullptr)
)
)
>
{
public:
using PreCalculatedResult = decltype((std::declval<CalcFunc>())(
std::function<void(infra::LogLevel, std::string const &)>()
));
using OutputT = decltype(
(std::declval<FetchFunc>())(
* ((PreCalculatedResult const *) nullptr)
, * ((Req const *) nullptr)
)
);
private:
CalcFunc calcFunc_;
FetchFunc fetchFunc_;
PreCalculatedResult preCalculatedRes_;
public:
OnOrderFacilityUsingInternallyPreCalculatedValue(CalcFunc &&calcFunc, FetchFunc &&fetchFunc) :
calcFunc_(std::move(calcFunc)), fetchFunc_(std::move(fetchFunc)), preCalculatedRes_()
{}
virtual void start(typename App::EnvironmentType *env) override final {
TM_INFRA_FACILITY_TRACER_WITH_SUFFIX(env, ":start");
preCalculatedRes_ = calcFunc_(
[env](infra::LogLevel level, std::string const &s) {
env->log(level, s);
}
);
}
virtual void handle(typename App::template InnerData<typename App::template Key<Req>> &&req) override final {
TM_INFRA_FACILITY_TRACER_WITH_SUFFIX(req.environment, ":handle");
this->publish(
req.environment
, typename App::template Key<OutputT> {
req.timedData.value.id(), fetchFunc_(preCalculatedRes_, req.timedData.value.key())
}
, true
);
}
};
template <class App, class Req, class CalcFunc, class FetchFunc>
auto onOrderFacilityUsingInternallyPreCalculatedValue(CalcFunc &&calcFunc, FetchFunc &&fetchFunc)
-> std::shared_ptr<typename App::template OnOrderFacility<Req, typename OnOrderFacilityUsingInternallyPreCalculatedValue<App,Req,CalcFunc,FetchFunc>::OutputT>>
{
return App::fromAbstractOnOrderFacility(new OnOrderFacilityUsingInternallyPreCalculatedValue<App,Req,CalcFunc,FetchFunc>(std::move(calcFunc), std::move(fetchFunc)));
}
} } } }
#endif | 43.150602 | 194 | 0.615594 | cd606 |
1dca89bec5153c7fe6683305110842690050fd61 | 1,608 | cpp | C++ | Sample/Sample_URLWriter/URLWriter.cpp | sherry0319/YTSvrLib | 5dda75aba927c4bf5c6a727592660bfc2619a063 | [
"MIT"
] | 61 | 2016-10-13T09:24:31.000Z | 2022-03-26T09:59:34.000Z | Sample/Sample_URLWriter/URLWriter.cpp | sherry0319/YTSvrLib | 5dda75aba927c4bf5c6a727592660bfc2619a063 | [
"MIT"
] | 3 | 2018-05-15T10:42:22.000Z | 2021-07-02T01:38:08.000Z | Sample/Sample_URLWriter/URLWriter.cpp | sherry0319/YTSvrLib | 5dda75aba927c4bf5c6a727592660bfc2619a063 | [
"MIT"
] | 36 | 2016-12-28T04:54:41.000Z | 2021-12-15T06:02:56.000Z | // URLWriter.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <cstdlib>
#include "URLWriter.h"
static struct
{
const char* url;
const char* post;
}g_data[] = {
{"http://v.juhe.cn/postcode/query?postcode=215001&key=%E7%94%B3%E8%AF%B7%E7%9A%84KEY",NULL},
{"http://v.juhe.cn/postcode/query","postcode=215001&key=%E7%94%B3%E8%AF%B7%E7%9A%84KEY"},
};
void OnURLRequestCallback(YTSvrLib::CURLRequest* pReq)
{
cout << "request index = " << pReq->m_ayParam[0] << endl;
cout << "request code = " << pReq->m_nReturnCode << endl;
cout << "return field = " << pReq->m_strReturn << endl;
}
void OnURLRequestSync()
{
std::string outdata;
int nResponseCode = YTSvrLib::CGlobalCURLRequest::GetInstance()->SendHTTPGETMessage(g_data[0].url, &outdata);
cout << "sync get request code = " << nResponseCode << endl;
cout << "sync get request return field = " << outdata << endl;
outdata.clear();
outdata.shrink_to_fit();
nResponseCode = YTSvrLib::CGlobalCURLRequest::GetInstance()->SendHTTPPOSTMessage(g_data[1].url, g_data[1].post, &outdata);
cout << "sync post request code = " << nResponseCode << endl;
cout << "sync post request return field = " << outdata << endl;
}
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
OnURLRequestSync();
CURLWriter::GetInstance()->StartURLWriter(5);
int index = 0;
while (true)
{
index++;
for (int i = 0; i < _countof(g_data);++i)
{
CURLWriter::GetInstance()->AddURLRequest(g_data[i].url, g_data[i].post, (YTSvrLib::URLPARAM)index, 0, 0, 0, OnURLRequestCallback);
}
CURLWriter::GetInstance()->WaitForAllRequestDone();
}
return 0;
} | 25.52381 | 133 | 0.675373 | sherry0319 |
1dcf151528f700d45c1e338fee82bb360d85b540 | 525 | cpp | C++ | solutions/986.interval-list-intersections.379341654.ac.cpp | satu0king/Leetcode-Solutions | 2edff60d76c2898d912197044f6284efeeb34119 | [
"MIT"
] | 78 | 2020-10-22T11:31:53.000Z | 2022-02-22T13:27:49.000Z | solutions/986.interval-list-intersections.379341654.ac.cpp | satu0king/Leetcode-Solutions | 2edff60d76c2898d912197044f6284efeeb34119 | [
"MIT"
] | null | null | null | solutions/986.interval-list-intersections.379341654.ac.cpp | satu0king/Leetcode-Solutions | 2edff60d76c2898d912197044f6284efeeb34119 | [
"MIT"
] | 26 | 2020-10-23T15:10:44.000Z | 2021-11-07T16:13:50.000Z | class Solution {
public:
vector<vector<int>> intervalIntersection(vector<vector<int>> &A,
vector<vector<int>> &B) {
int i = 0;
int j = 0;
int n1 = A.size();
int n2 = B.size();
vector<vector<int>> result;
while (i < n1 && j < n2) {
int r = min(A[i][1], B[j][1]);
int l = max(A[i][0], B[j][0]);
if (l <= r)
result.push_back({l, r});
if (A[i][1] < B[j][1])
i++;
else
j++;
}
return result;
}
};
| 21.875 | 68 | 0.420952 | satu0king |
1dd3f9694e9a14131f1c3a3fd946a6b960734c00 | 241 | cpp | C++ | cpp/examples/factorial.cpp | arturparkhisenko/til | 6fe7ddf2466d8090b9cf83fa5f7ae5fe5cacc19b | [
"MIT"
] | 5 | 2017-01-20T01:48:25.000Z | 2020-07-19T11:15:49.000Z | cpp/examples/factorial.cpp | arturparkhisenko/til | 6fe7ddf2466d8090b9cf83fa5f7ae5fe5cacc19b | [
"MIT"
] | null | null | null | cpp/examples/factorial.cpp | arturparkhisenko/til | 6fe7ddf2466d8090b9cf83fa5f7ae5fe5cacc19b | [
"MIT"
] | 1 | 2017-08-22T12:21:04.000Z | 2017-08-22T12:21:04.000Z | #include <iostream>
using namespace std;
int factorial(int n) {
if (n == 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}
int main(int argc, const char * argv[]) {
cout << factorial(5);
return 0;
}
// Outputs 120
| 14.176471 | 41 | 0.576763 | arturparkhisenko |
1dd5e29237ac4f550a143346a1d76ddb9383d3a3 | 1,332 | cpp | C++ | Master/XC-OS/BSP/BSP_Motor.cpp | robojkj/XC-OS | dbbd970d8ca6c7cdbd84cc1cf929d8c6ad13dec5 | [
"MIT"
] | 6 | 2020-11-21T03:03:07.000Z | 2022-03-30T00:00:05.000Z | Master/XC-OS/BSP/BSP_Motor.cpp | robojkj/XC-OS | dbbd970d8ca6c7cdbd84cc1cf929d8c6ad13dec5 | [
"MIT"
] | null | null | null | Master/XC-OS/BSP/BSP_Motor.cpp | robojkj/XC-OS | dbbd970d8ca6c7cdbd84cc1cf929d8c6ad13dec5 | [
"MIT"
] | 2 | 2021-02-08T05:57:19.000Z | 2021-07-24T21:10:49.000Z | #include "Basic/FileGroup.h"
#include "Basic/TasksManage.h"
#include "BSP.h"
static bool State_MotorVibrate = true;
static uint32_t MotorStop_TimePoint = 0;
static bool IsMotorRunning = false;
static uint8_t PWM_PIN;
static void Init_Motor()
{
uint8_t temp;
if(Motor_DIR)
{
PWM_PIN = Motor_IN1_Pin;
temp = Motor_IN2_Pin;
}else
{
PWM_PIN = Motor_IN2_Pin;
temp = Motor_IN1_Pin;
}
PWM_Init(PWM_PIN, 1000, 80);
pinMode(temp, OUTPUT);
pinMode(Motor_SLP_Pin, OUTPUT);
digitalWrite(temp, LOW);
digitalWrite(Motor_SLP_Pin, HIGH);
Motor_Vibrate(0.9f, 1000);
}
void Task_MotorRunning(TimerHandle_t xTimer)
{
__ExecuteOnce(Init_Motor());
if(IsMotorRunning && millis() >= MotorStop_TimePoint)
{
analogWrite(PWM_PIN, 0);
digitalWrite(Motor_SLP_Pin, LOW);
IsMotorRunning = false;
}
}
void Motor_SetEnable(bool en)
{
State_MotorVibrate = en;
}
void Motor_Vibrate(float strength, uint32_t time)
{
if(!State_MotorVibrate)
return;
__LimitValue(strength, 0.0f, 1.0f);
digitalWrite(Motor_SLP_Pin, HIGH);
analogWrite(PWM_PIN, strength * 1000);
IsMotorRunning = true;
MotorStop_TimePoint = millis() + time;
}
void Motor_SetState(bool state)
{
if(!State_MotorVibrate)
return;
analogWrite(PWM_PIN, state ? 1000 : 0);
}
| 18.5 | 57 | 0.690691 | robojkj |
1b8d63ace9bc75c1cfa2f5753b2e2b72ff29c59e | 9,574 | cpp | C++ | modules/imgui/imguimodule.cpp | tychonaut/OpenSpace | fa5bbc5a44b3c55474a6594d8be31ce8f25150c7 | [
"MIT"
] | null | null | null | modules/imgui/imguimodule.cpp | tychonaut/OpenSpace | fa5bbc5a44b3c55474a6594d8be31ce8f25150c7 | [
"MIT"
] | null | null | null | modules/imgui/imguimodule.cpp | tychonaut/OpenSpace | fa5bbc5a44b3c55474a6594d8be31ce8f25150c7 | [
"MIT"
] | null | null | null | /*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2020 *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this *
* software and associated documentation files (the "Software"), to deal in the Software *
* without restriction, including without limitation the rights to use, copy, modify, *
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to *
* permit persons to whom the Software is furnished to do so, subject to the following *
* conditions: *
* *
* The above copyright notice and this permission notice shall be included in all copies *
* or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
#include <modules/imgui/imguimodule.h>
#include <openspace/engine/globals.h>
#include <openspace/engine/globalscallbacks.h>
#include <openspace/engine/virtualpropertymanager.h>
#include <openspace/engine/windowdelegate.h>
#include <openspace/engine/moduleengine.h>
#include <openspace/interaction/navigationhandler.h>
#include <openspace/interaction/sessionrecording.h>
#include <openspace/network/parallelpeer.h>
#include <openspace/rendering/dashboard.h>
#include <openspace/rendering/luaconsole.h>
#include <openspace/rendering/renderengine.h>
#include <openspace/scene/scene.h>
#include <ghoul/logging/logmanager.h>
#include <ghoul/misc/profiling.h>
namespace openspace {
ImGUIModule::ImGUIModule() : OpenSpaceModule(Name) {
addPropertySubOwner(gui);
global::callback::initialize.emplace_back([&]() {
LDEBUGC("ImGUIModule", "Initializing GUI");
gui.initialize();
gui._globalProperty.setSource(
[]() {
std::vector<properties::PropertyOwner*> res = {
&global::navigationHandler,
&global::sessionRecording,
&global::timeManager,
&global::renderEngine,
&global::parallelPeer,
&global::luaConsole,
&global::dashboard
};
return res;
}
);
gui._screenSpaceProperty.setSource(
[]() {
return global::screenSpaceRootPropertyOwner.propertySubOwners();
}
);
gui._moduleProperty.setSource(
[]() {
std::vector<properties::PropertyOwner*> v;
v.push_back(&(global::moduleEngine));
return v;
}
);
gui._sceneProperty.setSource(
[]() {
const Scene* scene = global::renderEngine.scene();
const std::vector<SceneGraphNode*>& nodes = scene ?
scene->allSceneGraphNodes() :
std::vector<SceneGraphNode*>();
return std::vector<properties::PropertyOwner*>(
nodes.begin(),
nodes.end()
);
}
);
gui._virtualProperty.setSource(
[]() {
std::vector<properties::PropertyOwner*> res = {
&global::virtualPropertyManager
};
return res;
}
);
gui._featuredProperties.setSource(
[]() {
std::vector<SceneGraphNode*> nodes =
global::renderEngine.scene()->allSceneGraphNodes();
nodes.erase(
std::remove_if(
nodes.begin(),
nodes.end(),
[](SceneGraphNode* n) {
const std::vector<std::string>& tags = n->tags();
const auto it = std::find(
tags.begin(),
tags.end(),
"GUI.Interesting"
);
return it == tags.end();
}
),
nodes.end()
);
return std::vector<properties::PropertyOwner*>(
nodes.begin(),
nodes.end()
);
}
);
});
global::callback::deinitialize.emplace_back([&]() {
ZoneScopedN("ImGUI")
LDEBUGC("ImGui", "Deinitialize GUI");
gui.deinitialize();
});
global::callback::initializeGL.emplace_back([&]() {
ZoneScopedN("ImGUI")
LDEBUGC("ImGui", "Initializing GUI OpenGL");
gui.initializeGL();
});
global::callback::deinitializeGL.emplace_back([&]() {
ZoneScopedN("ImGUI")
LDEBUGC("ImGui", "Deinitialize GUI OpenGL");
gui.deinitializeGL();
});
global::callback::draw2D.emplace_back([&]() {
ZoneScopedN("ImGUI")
// TODO emiax: Make sure this is only called for one of the eyes, in the case
// of side-by-side / top-bottom stereo.
WindowDelegate& delegate = global::windowDelegate;
const bool showGui = delegate.hasGuiWindow() ? delegate.isGuiWindow() : true;
if (delegate.isMaster() && showGui) {
const glm::ivec2 windowSize = delegate.currentSubwindowSize();
const glm::ivec2 resolution = delegate.currentDrawBufferResolution();
if (windowSize.x <= 0 || windowSize.y <= 0) {
return;
}
glm::vec2 mousePosition = delegate.mousePosition();
uint32_t mouseButtons = delegate.mouseButtons(2);
const double dt = std::max(delegate.averageDeltaTime(), 0.0);
if (touchInput.active && mouseButtons == 0) {
mouseButtons = touchInput.action;
mousePosition = touchInput.pos;
}
// We don't do any collection of immediate mode user interface, so it
// is fine to open and close a frame immediately
gui.startFrame(
static_cast<float>(dt),
glm::vec2(windowSize),
resolution / windowSize,
mousePosition,
mouseButtons
);
gui.endFrame();
}
});
global::callback::keyboard.emplace_back(
[&](Key key, KeyModifier mod, KeyAction action) -> bool {
ZoneScopedN("ImGUI")
// A list of all the windows that can show up by themselves
if (gui.isEnabled() || gui._performance.isEnabled() ||
gui._sceneProperty.isEnabled())
{
return gui.keyCallback(key, mod, action);
}
else {
return false;
}
}
);
global::callback::character.emplace_back(
[&](unsigned int codepoint, KeyModifier modifier) -> bool {
ZoneScopedN("ImGUI")
// A list of all the windows that can show up by themselves
if (gui.isEnabled() || gui._performance.isEnabled() ||
gui._sceneProperty.isEnabled())
{
return gui.charCallback(codepoint, modifier);
}
else {
return false;
}
}
);
global::callback::mouseButton.emplace_back(
[&](MouseButton button, MouseAction action, KeyModifier) -> bool {
ZoneScopedN("ImGUI")
// A list of all the windows that can show up by themselves
if (gui.isEnabled() || gui._performance.isEnabled() ||
gui._sceneProperty.isEnabled())
{
return gui.mouseButtonCallback(button, action);
}
else {
return false;
}
}
);
global::callback::mouseScrollWheel.emplace_back(
[&](double, double posY) -> bool {
ZoneScopedN("ImGUI")
// A list of all the windows that can show up by themselves
if (gui.isEnabled() || gui._performance.isEnabled() ||
gui._sceneProperty.isEnabled())
{
return gui.mouseWheelCallback(posY);
}
else {
return false;
}
}
);
}
} // namespace openspace
| 37.108527 | 90 | 0.488719 | tychonaut |
1b994fde11422c094b973ea200686c8888419e8e | 6,747 | cc | C++ | third_party/blink/renderer/core/frame/v8_scanner/scanner-character-streams.cc | 1qaz2wsx7u8i9o0p/DOM-Tree-Type | 151e4c2c85bf93ba506277486d7989361d02b54c | [
"MIT"
] | null | null | null | third_party/blink/renderer/core/frame/v8_scanner/scanner-character-streams.cc | 1qaz2wsx7u8i9o0p/DOM-Tree-Type | 151e4c2c85bf93ba506277486d7989361d02b54c | [
"MIT"
] | null | null | null | third_party/blink/renderer/core/frame/v8_scanner/scanner-character-streams.cc | 1qaz2wsx7u8i9o0p/DOM-Tree-Type | 151e4c2c85bf93ba506277486d7989361d02b54c | [
"MIT"
] | null | null | null | // Copyright 2011 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/renderer/core/frame/v8_scanner/scanner-character-streams.h"
#include <memory>
#include <vector>
#include "third_party/blink/renderer/core/frame/v8_scanner/globals.h"
#include "third_party/blink/renderer/core/frame/v8_scanner/scanner.h"
#include "third_party/blink/renderer/core/frame/v8_scanner/unicode-inl.h"
namespace v8_scanner {
template <typename Char>
struct Range {
const Char* start;
const Char* end;
size_t length() { return static_cast<size_t>(end - start); }
bool unaligned_start() const {
return reinterpret_cast<intptr_t>(start) % sizeof(Char) == 1;
}
};
// A Char stream backed by a C array. Testing only.
template <typename Char>
class TestingStream {
public:
TestingStream(const Char* data, size_t length)
: data_(data), length_(length) {}
// The no_gc argument is only here because of the templated way this class
// is used along with other implementations that require V8 heap access.
Range<Char> GetDataAt(size_t pos) {
return {&data_[std::min(length_, pos)], &data_[length_]};
}
static const bool kCanBeCloned = true;
static const bool kCanAccessHeap = false;
private:
const Char* const data_;
const size_t length_;
};
// Provides a buffered utf-16 view on the bytes from the underlying ByteStream.
// Chars are buffered if either the underlying stream isn't utf-16 or the
// underlying utf-16 stream might move (is on-heap).
template <template <typename T> class ByteStream>
class BufferedCharacterStream : public Utf16CharacterStream {
public:
template <class... TArgs>
BufferedCharacterStream(size_t pos, TArgs... args) : byte_stream_(args...) {
buffer_pos_ = pos;
}
bool can_be_cloned() const final {
return ByteStream<uint16_t>::kCanBeCloned;
}
std::unique_ptr<Utf16CharacterStream> Clone() const override {
return std::unique_ptr<Utf16CharacterStream>(
new BufferedCharacterStream<ByteStream>(*this));
}
protected:
bool ReadBlock() final {
size_t position = pos();
buffer_pos_ = position;
buffer_start_ = &buffer_[0];
buffer_cursor_ = buffer_start_;
Range<uint8_t> range =
byte_stream_.GetDataAt(position);
if (range.length() == 0) {
buffer_end_ = buffer_start_;
return false;
}
size_t length = std::min({kBufferSize, range.length()});
for (unsigned int i = 0; i < length; ++i) {
buffer_[i] = *((uc16 *)(range.start) + i);
}
buffer_end_ = &buffer_[length];
return true;
}
bool can_access_heap() const final {
return ByteStream<uint8_t>::kCanAccessHeap;
}
private:
BufferedCharacterStream(const BufferedCharacterStream<ByteStream>& other)
: byte_stream_(other.byte_stream_) {}
static const size_t kBufferSize = 512;
uc16 buffer_[kBufferSize];
ByteStream<uint8_t> byte_stream_;
};
// Provides a unbuffered utf-16 view on the bytes from the underlying
// ByteStream.
template <template <typename T> class ByteStream>
class UnbufferedCharacterStream : public Utf16CharacterStream {
public:
template <class... TArgs>
UnbufferedCharacterStream(size_t pos, TArgs... args) : byte_stream_(args...) {
buffer_pos_ = pos;
}
bool can_access_heap() const final {
return ByteStream<uint16_t>::kCanAccessHeap;
}
bool can_be_cloned() const final {
return ByteStream<uint16_t>::kCanBeCloned;
}
std::unique_ptr<Utf16CharacterStream> Clone() const override {
return std::unique_ptr<Utf16CharacterStream>(
new UnbufferedCharacterStream<ByteStream>(*this));
}
protected:
bool ReadBlock() final {
size_t position = pos();
buffer_pos_ = position;
Range<uint16_t> range =
byte_stream_.GetDataAt(position);
buffer_start_ = range.start;
buffer_end_ = range.end;
buffer_cursor_ = buffer_start_;
if (range.length() == 0) return false;
return true;
}
UnbufferedCharacterStream(const UnbufferedCharacterStream<ByteStream>& other)
: byte_stream_(other.byte_stream_) {}
ByteStream<uint16_t> byte_stream_;
};
// ----------------------------------------------------------------------------
// BufferedUtf16CharacterStreams
//
// A buffered character stream based on a random access character
// source (ReadBlock can be called with pos() pointing to any position,
// even positions before the current).
//
// TODO(verwaest): Remove together with Utf8 external streaming streams.
class BufferedUtf16CharacterStream : public Utf16CharacterStream {
public:
BufferedUtf16CharacterStream();
protected:
static const size_t kBufferSize = 512;
bool ReadBlock() final;
// FillBuffer should read up to kBufferSize characters at position and store
// them into buffer_[0..]. It returns the number of characters stored.
virtual size_t FillBuffer(size_t position) = 0;
// Fixed sized buffer that this class reads from.
// The base class' buffer_start_ should always point to buffer_.
uc16 buffer_[kBufferSize];
};
BufferedUtf16CharacterStream::BufferedUtf16CharacterStream()
: Utf16CharacterStream(buffer_, buffer_, buffer_, 0) {}
bool BufferedUtf16CharacterStream::ReadBlock() {
size_t position = pos();
buffer_pos_ = position;
buffer_cursor_ = buffer_;
buffer_end_ = buffer_ + FillBuffer(position);
return buffer_cursor_ < buffer_end_;
}
std::unique_ptr<Utf16CharacterStream> ScannerStream::ForTesting(
const char* data) {
return ScannerStream::ForTesting(data, strlen(data));
}
std::unique_ptr<Utf16CharacterStream> ScannerStream::ForTesting(
const char* data, size_t length) {
if (data == nullptr) {
// We don't want to pass in a null pointer into the the character stream,
// because then the one-past-the-end pointer is undefined, so instead pass
// through this static array.
static const char non_null_empty_string[1] = {0};
data = non_null_empty_string;
}
return std::unique_ptr<Utf16CharacterStream>(
new BufferedCharacterStream<TestingStream>(
0, reinterpret_cast<const uint8_t*>(data), length));
}
std::unique_ptr<Utf16CharacterStream> ScannerStream::ForTesting(
const uint16_t* data, size_t length) {
if (data == nullptr) {
// We don't want to pass in a null pointer into the the character stream,
// because then the one-past-the-end pointer is undefined, so instead pass
// through this static array.
static const uint16_t non_null_empty_uint16_t_string[1] = {0};
data = non_null_empty_uint16_t_string;
}
return std::unique_ptr<Utf16CharacterStream>(
new UnbufferedCharacterStream<TestingStream>(0, data, length));
}
}
| 31.236111 | 87 | 0.716763 | 1qaz2wsx7u8i9o0p |
1ba21795be4e33ff522d8b9084a0393c0cf8a96c | 5,041 | hpp | C++ | cpp/subprojects/common/include/common/data/view_csr_binary.hpp | mrapp-ke/SyndromeLearner | ed18c282949bebbc8e1dd5d2ddfb0b224ee71293 | [
"MIT"
] | null | null | null | cpp/subprojects/common/include/common/data/view_csr_binary.hpp | mrapp-ke/SyndromeLearner | ed18c282949bebbc8e1dd5d2ddfb0b224ee71293 | [
"MIT"
] | null | null | null | cpp/subprojects/common/include/common/data/view_csr_binary.hpp | mrapp-ke/SyndromeLearner | ed18c282949bebbc8e1dd5d2ddfb0b224ee71293 | [
"MIT"
] | 1 | 2022-03-08T22:06:56.000Z | 2022-03-08T22:06:56.000Z | /*
* @author Michael Rapp ([email protected])
*/
#pragma once
#include "common/indices/index_forward_iterator.hpp"
/**
* Implements row-wise read-only access to binary values that are stored in a pre-allocated matrix in the compressed
* sparse row (CSR) format.
*/
class BinaryCsrConstView {
protected:
uint32 numRows_;
uint32 numCols_;
uint32* rowIndices_;
uint32* colIndices_;
public:
/**
* @param numRows The number of rows in the view
* @param numCols The number of columns in the view
* @param rowIndices A pointer to an array of type `uint32`, shape `(numRows + 1)`, that stores the indices
* of the first element in `colIndices` that corresponds to a certain row. The index at the
* last position is equal to `num_non_zero_values`
* @param colIndices A pointer to an array of type `uint32`, shape `(num_non_zero_values)`, that stores the
* column-indices, the non-zero elements correspond to
*/
BinaryCsrConstView(uint32 numRows, uint32 numCols, uint32* rowIndices, uint32* colIndices);
/**
* An iterator that provides read-only access to the indices in the view.
*/
typedef const uint32* index_const_iterator;
/**
* An iterator that provides read-only access to the values in the view.
*/
typedef IndexForwardIterator<index_const_iterator> value_const_iterator;
/**
* Returns an `index_const_iterator` to the beginning of the indices at a specific row.
*
* @param row The row
* @return An `index_const_iterator` to the beginning of the indices
*/
index_const_iterator row_indices_cbegin(uint32 row) const;
/**
* Returns an `index_const_iterator` to the end of the indices at a specific row.
*
* @param row The row
* @return An `index_const_iterator` to the end of the indices
*/
index_const_iterator row_indices_cend(uint32 row) const;
/**
* Returns a `value_const_iterator` to the beginning of the values at a specific row.
*
* @param row The row
* @return A `value_const_iterator` to the beginning of the values
*/
value_const_iterator row_values_cbegin(uint32 row) const;
/**
* Returns a `value_const_iterator` to the end of the values at a specific row.
*
* @param row The row
* @return A `value_const_iterator` to the end of the values
*/
value_const_iterator row_values_cend(uint32 row) const;
/**
* Returns the number of rows in the view.
*
* @return The number of rows
*/
uint32 getNumRows() const;
/**
* Returns the number of columns in the view.
*
* @return The number of columns
*/
uint32 getNumCols() const;
/**
* Returns the number of non-zero elements in the view.
*
* @return The number of non-zero elements
*/
uint32 getNumNonZeroElements() const;
};
/**
* Implements row-wise read and write access to binary values that are stored in a pre-allocated matrix in the
* compressed sparse row (CSR) format.
*/
class BinaryCsrView final : public BinaryCsrConstView {
public:
/**
* @param numRows The number of rows in the view
* @param numCols The number of columns in the view
* @param rowIndices A pointer to an array of type `uint32`, shape `(numRows + 1)`, that stores the indices
* of the first element in `colIndices` that corresponds to a certain row. The index at the
* last position is equal to `num_non_zero_values`
* @param colIndices A pointer to an array of type `uint32`, shape `(num_non_zero_values)`, that stores the
* column-indices, the non-zero elements correspond to
*/
BinaryCsrView(uint32 numRows, uint32 numCols, uint32* rowIndices, uint32* colIndices);
/**
* An iterator that provides access to the indices of the view and allows to modify them.
*/
typedef uint32* index_iterator;
/**
* Returns an `index_iterator` to the beginning of the indices at a specific row.
*
* @param row The row
* @return An `index_iterator` to the beginning of the indices
*/
index_iterator row_indices_begin(uint32 row);
/**
* Returns an `index_iterator` to the end of the indices at a specific row.
*
* @param row The row
* @return An `index_iterator` to the end of the indices
*/
index_iterator row_indices_end(uint32 row);
};
| 35.006944 | 120 | 0.594922 | mrapp-ke |
1ba25478ed9db1f61a3e9c49e3dd72b0103eea87 | 2,915 | cpp | C++ | Tutorials/AMR_Adv_C/Source/Adv_advance.cpp | Voskrese/BoxLib-old-msvc | da83349af10ef8f951b7a5b3182fc7cd710abeec | [
"BSD-3-Clause-LBNL"
] | null | null | null | Tutorials/AMR_Adv_C/Source/Adv_advance.cpp | Voskrese/BoxLib-old-msvc | da83349af10ef8f951b7a5b3182fc7cd710abeec | [
"BSD-3-Clause-LBNL"
] | null | null | null | Tutorials/AMR_Adv_C/Source/Adv_advance.cpp | Voskrese/BoxLib-old-msvc | da83349af10ef8f951b7a5b3182fc7cd710abeec | [
"BSD-3-Clause-LBNL"
] | 1 | 2019-08-06T13:09:09.000Z | 2019-08-06T13:09:09.000Z |
#include <Adv.H>
#include <Adv_F.H>
Real
Adv::advance (Real time,
Real dt,
int iteration,
int ncycle)
{
for (int k = 0; k < NUM_STATE_TYPE; k++) {
state[k].allocOldData();
state[k].swapTimeLevels(dt);
}
MultiFab& S_new = get_new_data(State_Type);
const Real prev_time = state[State_Type].prevTime();
const Real cur_time = state[State_Type].curTime();
const Real ctr_time = 0.5*(prev_time + cur_time);
const Real* dx = geom.CellSize();
const Real* prob_lo = geom.ProbLo();
//
// Get pointers to Flux registers, or set pointer to zero if not there.
//
FluxRegister *fine = 0;
FluxRegister *current = 0;
int finest_level = parent->finestLevel();
if (do_reflux && level < finest_level) {
fine = &getFluxReg(level+1);
fine->setVal(0.0);
}
if (do_reflux && level > 0) {
current = &getFluxReg(level);
}
MultiFab fluxes[BL_SPACEDIM];
if (do_reflux)
{
for (int j = 0; j < BL_SPACEDIM; j++)
{
BoxArray ba = S_new.boxArray();
ba.surroundingNodes(j);
fluxes[j].define(ba, NUM_STATE, 0, Fab_allocate);
}
}
// State with ghost cells
MultiFab Sborder(grids, NUM_STATE, NUM_GROW);
FillPatch(*this, Sborder, NUM_GROW, time, State_Type, 0, NUM_STATE);
#ifdef _OPENMP
#pragma omp parallel
#endif
{
FArrayBox flux[BL_SPACEDIM], uface[BL_SPACEDIM];
for (MFIter mfi(S_new, true); mfi.isValid(); ++mfi)
{
const Box& bx = mfi.tilebox();
const FArrayBox& statein = Sborder[mfi];
FArrayBox& stateout = S_new[mfi];
// Allocate fabs for fluxes and Godunov velocities.
for (int i = 0; i < BL_SPACEDIM ; i++) {
const Box& bxtmp = BoxLib::surroundingNodes(bx,i);
flux[i].resize(bxtmp,NUM_STATE);
uface[i].resize(BoxLib::grow(bxtmp,1),1);
}
BL_FORT_PROC_CALL(GET_FACE_VELOCITY,get_face_velocity)
(level, ctr_time,
D_DECL(BL_TO_FORTRAN(uface[0]),
BL_TO_FORTRAN(uface[1]),
BL_TO_FORTRAN(uface[2])),
dx, prob_lo);
BL_FORT_PROC_CALL(ADVECT,advect)
(time, bx.loVect(), bx.hiVect(),
BL_TO_FORTRAN_3D(statein),
BL_TO_FORTRAN_3D(stateout),
D_DECL(BL_TO_FORTRAN_3D(uface[0]),
BL_TO_FORTRAN_3D(uface[1]),
BL_TO_FORTRAN_3D(uface[2])),
D_DECL(BL_TO_FORTRAN_3D(flux[0]),
BL_TO_FORTRAN_3D(flux[1]),
BL_TO_FORTRAN_3D(flux[2])),
dx, dt);
if (do_reflux) {
for (int i = 0; i < BL_SPACEDIM ; i++)
fluxes[i][mfi].copy(flux[i],mfi.nodaltilebox(i));
}
}
}
if (do_reflux) {
if (current) {
for (int i = 0; i < BL_SPACEDIM ; i++)
current->FineAdd(fluxes[i],i,0,0,NUM_STATE,1.);
}
if (fine) {
for (int i = 0; i < BL_SPACEDIM ; i++)
fine->CrseInit(fluxes[i],i,0,0,NUM_STATE,-1.);
}
}
return dt;
}
| 24.91453 | 75 | 0.592453 | Voskrese |
1ba2a2866b3a3a4557bc420ed3df7293d4522457 | 2,128 | cc | C++ | arch/mx/decoder.cc | Gandalf-ND/fluxengine | 683bdcdf7f9147b43da90467e545fe0c78d6dcd1 | [
"MIT"
] | null | null | null | arch/mx/decoder.cc | Gandalf-ND/fluxengine | 683bdcdf7f9147b43da90467e545fe0c78d6dcd1 | [
"MIT"
] | null | null | null | arch/mx/decoder.cc | Gandalf-ND/fluxengine | 683bdcdf7f9147b43da90467e545fe0c78d6dcd1 | [
"MIT"
] | null | null | null | #include "globals.h"
#include "decoders/decoders.h"
#include "mx/mx.h"
#include "crc.h"
#include "fluxmap.h"
#include "decoders/fluxmapreader.h"
#include "sector.h"
#include "record.h"
#include "track.h"
#include <string.h>
const int SECTOR_SIZE = 256;
/*
* MX disks are a bunch of sectors glued together with no gaps or sync markers,
* following a single beginning-of-track synchronisation and identification
* sequence.
*/
/* FM beginning of track marker:
* 1010 1010 1010 1010 1111 1111 1010 1111
* a a a a f f a f
*/
const FluxPattern ID_PATTERN(32, 0xaaaaffaf);
void MxDecoder::beginTrack()
{
_currentSector = -1;
_clock = 0;
}
AbstractDecoder::RecordType MxDecoder::advanceToNextRecord()
{
if (_currentSector == -1)
{
/* First sector in the track: look for the sync marker. */
const FluxMatcher* matcher = nullptr;
_sector->clock = _clock = _fmr->seekToPattern(ID_PATTERN, matcher);
readRawBits(32); /* skip the ID mark */
_logicalTrack = decodeFmMfm(readRawBits(32)).reader().read_be16();
}
else if (_currentSector == 10)
{
/* That was the last sector on the disk. */
return UNKNOWN_RECORD;
}
else
{
/* Otherwise we assume the clock from the first sector is still valid.
* The decoder framwork will automatically stop when we hit the end of
* the track. */
_sector->clock = _clock;
}
_currentSector++;
return SECTOR_RECORD;
}
void MxDecoder::decodeSectorRecord()
{
auto bits = readRawBits((SECTOR_SIZE+2)*16);
auto bytes = decodeFmMfm(bits).slice(0, SECTOR_SIZE+2).swab();
uint16_t gotChecksum = 0;
ByteReader br(bytes);
for (int i=0; i<(SECTOR_SIZE/2); i++)
gotChecksum += br.read_le16();
uint16_t wantChecksum = br.read_le16();
_sector->logicalTrack = _logicalTrack;
_sector->logicalSide = _track->physicalSide;
_sector->logicalSector = _currentSector;
_sector->data = bytes.slice(0, SECTOR_SIZE);
_sector->status = (gotChecksum == wantChecksum) ? Sector::OK : Sector::BAD_CHECKSUM;
}
| 28 | 88 | 0.656955 | Gandalf-ND |
1ba9757b17aa5ed9852294b0a4d569ae7aaa3de2 | 5,074 | hpp | C++ | include/EntryPoint.hpp | NaioTechnologies/camCapture | 2af0ecbfe3b84fdeed8667ee73401cbfe22766cc | [
"MIT"
] | 1 | 2019-08-28T13:42:21.000Z | 2019-08-28T13:42:21.000Z | include/EntryPoint.hpp | NaioTechnologies/camCapture | 2af0ecbfe3b84fdeed8667ee73401cbfe22766cc | [
"MIT"
] | null | null | null | include/EntryPoint.hpp | NaioTechnologies/camCapture | 2af0ecbfe3b84fdeed8667ee73401cbfe22766cc | [
"MIT"
] | 1 | 2021-02-18T23:17:45.000Z | 2021-02-18T23:17:45.000Z | //==================================================================================================
//
// Copyright(c) 2013 - 2015 Naïo Technologies
//
// 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/>.
//
//==================================================================================================
#ifndef ENTRYPOINT_HPP
#define ENTRYPOINT_HPP
//==================================================================================================
// I N C L U D E F I L E S
#include "Core/COProcessUnit.hpp"
#include "Importer/IMImporter.hpp"
#include "IO/IOTiffWriter.hpp"
#include "HTCmdLineParser.h"
#include "HTLogger.h"
#include "HTSignalHandler.hpp"
#include "CLFileSystem.h"
#include "CLPrint.hpp"
//==================================================================================================
// F O R W A R D D E C L A R A T I O N S
//==================================================================================================
// C O N S T A N T S
//==================================================================================================
// C L A S S E S
class FileOutput
: public co::ProcessUnit
{
//--Methods-----------------------------------------------------------------------------------------
public:
FileOutput( const std::string& folderPath )
: folderPath_{ folderPath }
{ }
~FileOutput(){ }
virtual bool compute_result( co::ParamContext& context, const co::OutputResult& inResult ) final
{
const cm::BitmapPairEntry* bmEntry = dynamic_cast<cm::BitmapPairEntry*>(
&(*inResult.get_cached_entries().begin()->second) );
co::OutputResult result;
result.start_benchmark();
const cm::BitmapPairEntry::ID* id = dynamic_cast<cm::BitmapPairEntry::ID*>(
&(*inResult.get_cached_entries().begin()->first) );
std::string filepathL, filepathR;
bool generatedL = im::AsyncImporter::generate_filename( folderPath_, "",
id->get_index(),
id->get_timestamp(), "l",
"tif", filepathL );
bool generatedR = im::AsyncImporter::generate_filename( folderPath_, "",
id->get_index(),
id->get_timestamp(), "r",
"tif", filepathR );
if( generatedL && generatedR )
{
io::TiffWriter tiffWriterL{ filepathL };
tiffWriterL.write_to_file( bmEntry->bitmap_left(), id->get_index(),
id->get_timestamp(), 22.f );
io::TiffWriter tiffWriterR{ filepathR };
tiffWriterR.write_to_file( bmEntry->bitmap_right(), id->get_index(),
id->get_timestamp(), 22.f );
}
else
{
return false;
}
result.stop_benchmark();
//result.print_benchmark( "FileOuput:" );
for( auto& iter : get_output_list() )
{
if( iter )
{
if( !iter->compute_result( context, result ) )
{
return false;
}
}
}
return true;
}
virtual bool query_output_metrics( co::OutputMetrics& outputMetrics ) final
{
cl::ignore( outputMetrics );
return false;
}
virtual bool query_output_format( co::OutputFormat& outputFormat ) final
{
cl::ignore( outputFormat );
return false;
}
//--Data members------------------------------------------------------------------------------------
private:
const std::string folderPath_;
};
class EntryPoint
: private co::ProcessUnit
{
//--Methods-----------------------------------------------------------------------------------------
public:
EntryPoint();
~EntryPoint();
void set_signal();
bool is_signaled() const;
/// Outputs a header for the program on the standard output stream.
void print_header() const;
bool handle_parameters( const std::string& option, const std::string& type );
/// Main entry point of the application.
int32_t run( int32_t argc, const char** argv );
private:
virtual bool compute_result( co::ParamContext& context, const co::OutputResult& result ) final;
virtual bool query_output_metrics( co::OutputMetrics& om ) final;
virtual bool query_output_format( co::OutputFormat& of ) final;
//--Data members------------------------------------------------------------------------------------
private:
/// Command line parser, logger and debugger for the application
HTCmdLineParser parser_;
HTCmdLineParser::Visitor handler_;
ht::SignalHandler signalHandler_;
volatile bool signaled_;
};
//==================================================================================================
// I N L I N E F U N C T I O N S C O D E S E C T I O N
#endif // ENTRYPOINT_HPP
| 29.847059 | 100 | 0.539417 | NaioTechnologies |
1baacc10653cb8db8cbbb6feb1b11b4bb3beebfc | 1,357 | cpp | C++ | Source/DACore/DUtil.cpp | XDApp/DawnAppFramework | 8655de88200e847ce0e822899395247ade515bc6 | [
"MIT"
] | 1 | 2015-07-13T11:45:18.000Z | 2015-07-13T11:45:18.000Z | Source/DACore/DUtil.cpp | XDApp/DawnAppFramework | 8655de88200e847ce0e822899395247ade515bc6 | [
"MIT"
] | null | null | null | Source/DACore/DUtil.cpp | XDApp/DawnAppFramework | 8655de88200e847ce0e822899395247ade515bc6 | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include "DUtil.h"
std::wstring_convert<std::codecvt_utf16<wchar_t>> DUtil::converter;
DUtil::DUtil()
{
}
DUtil::~DUtil()
{
}
std::wstring DUtil::StringAtoW(const std::string &Origin)
{
return DUtil::converter.from_bytes(Origin);
}
std::string DUtil::StringWtoA(const std::wstring &Origin)
{
return DUtil::converter.to_bytes(Origin);
}
std::wstring DUtil::ANSIToUnicode(const std::string& str)
{
int len = 0;
len = str.length();
int unicodeLen = ::MultiByteToWideChar(CP_ACP,
0,
str.c_str(),
-1,
NULL,
0);
wchar_t * pUnicode;
pUnicode = new wchar_t[unicodeLen + 1];
memset(pUnicode, 0, (unicodeLen + 1)*sizeof(wchar_t));
::MultiByteToWideChar(CP_ACP,
0,
str.c_str(),
-1,
(LPWSTR)pUnicode,
unicodeLen);
std::wstring rt;
rt = (wchar_t*)pUnicode;
delete pUnicode;
return rt;
}
std::string DUtil::UnicodeToANSI(const std::wstring& str)
{
char* pElementText;
int iTextLen;
// wide char to multi char
iTextLen = WideCharToMultiByte(CP_ACP,
0,
str.c_str(),
-1,
NULL,
0,
NULL,
NULL);
pElementText = new char[iTextLen + 1];
memset((void*)pElementText, 0, sizeof(char) * (iTextLen + 1));
::WideCharToMultiByte(CP_ACP,
0,
str.c_str(),
-1,
pElementText,
iTextLen,
NULL,
NULL);
std::string strText;
strText = pElementText;
delete[] pElementText;
return strText;
} | 17.623377 | 67 | 0.676492 | XDApp |
1babcf3f19fc09aa66c30129945e65a4c3f29318 | 2,848 | hh | C++ | src/c++/include/main/GenomeMutatorOptions.hh | sequencing/EAGLE | 6da0438c1f7620ea74dec1f34baf20bb0b14b110 | [
"BSD-3-Clause"
] | 28 | 2015-05-22T16:03:29.000Z | 2022-01-15T12:12:46.000Z | src/c++/include/main/GenomeMutatorOptions.hh | sequencing/EAGLE | 6da0438c1f7620ea74dec1f34baf20bb0b14b110 | [
"BSD-3-Clause"
] | 15 | 2015-10-21T11:19:09.000Z | 2020-07-15T05:01:12.000Z | src/c++/include/main/GenomeMutatorOptions.hh | sequencing/EAGLE | 6da0438c1f7620ea74dec1f34baf20bb0b14b110 | [
"BSD-3-Clause"
] | 8 | 2017-01-21T00:31:17.000Z | 2018-08-12T13:28:57.000Z | /**
** Copyright (c) 2014 Illumina, Inc.
**
** This file is part of Illumina's Enhanced Artificial Genome Engine (EAGLE),
** covered by the "BSD 2-Clause License" (see accompanying LICENSE file)
**
** \description Command line options for 'variantModelling'
**
** \author Mauricio Varea
**/
#ifndef EAGLE_MAIN_GENOME_MUTATOR_OPTIONS_HH
#define EAGLE_MAIN_GENOME_MUTATOR_OPTIONS_HH
#include <string>
#include <map>
#include <boost/filesystem.hpp>
#include "common/Program.hh"
namespace eagle
{
namespace main
{
class GenomeMutatorOptions : public eagle::common::Options
{
public:
enum Modes
{
SAFE_MODE,
WHOLE_DIR
};
GenomeMutatorOptions();
std::map<std::string,unsigned int> exceptionPloidy() const;
private:
std::string usagePrefix() const {return std::string("Usage:\n")
+ std::string(" applyVariants [parameters] [options]");}
std::string usageSuffix() const {std::stringstream usage;
usage << "Examples:" << std::endl;
usage << " * Safe Mode" << std::endl;
usage << " applyVariants -v /path/to/VariantList.vcf \\" << std::endl;
usage << " -r /path/to/ReferenceDir/reference_1.fa \\" << std::endl;
usage << " -r /path/to/ReferenceDir/reference_2.fa \\" << std::endl;
usage << " ... etc ... \\" << std::endl;
usage << " [options]" << std::endl;
usage << " * Whole-dir Mode" << std::endl;
usage << " applyVariants -v /path/to/VariantList.vcf \\" << std::endl;
usage << " -R /path/to/ReferenceDir \\" << std::endl;
usage << " [options]" << std::endl;
return usage.str();}
void postProcess(boost::program_options::variables_map &vm);
public:
std::vector<boost::filesystem::path> referenceGenome;
boost::filesystem::path wholeGenome;
boost::filesystem::path sampleGenome;
std::vector<boost::filesystem::path> variantList;
boost::filesystem::path annotatedVariantList;
unsigned int organismPloidy;
std::vector<std::string> ploidyChromosome;
std::vector<unsigned int> ploidyLevel;
std::string prefixToAdd;
bool noTranslocationError;
bool onlyPrintOutputContigNames;
//bool withGenomeSize;
bool force;
Modes mode;
};
} // namespace main
} // namespace eagle
#endif // EAGLE_MAIN_GENOME_MUTATOR_OPTIONS_HH
| 37.473684 | 125 | 0.534059 | sequencing |
1bb4055254f0051d2870fbe910e9acb35bca88dc | 1,579 | cpp | C++ | Gep/Source/ps2/file.cpp | Sunlitspace542/SNESticle | 9590ebf3bf768424ebd6cb018f322e724a7aade3 | [
"MIT"
] | 318 | 2022-01-15T23:35:01.000Z | 2022-03-24T13:37:20.000Z | Gep/Source/ps2/file.cpp | Sunlitspace542/SNESticle | 9590ebf3bf768424ebd6cb018f322e724a7aade3 | [
"MIT"
] | 2 | 2022-01-25T23:58:23.000Z | 2022-01-30T21:59:09.000Z | Gep/Source/ps2/file.cpp | Sunlitspace542/SNESticle | 9590ebf3bf768424ebd6cb018f322e724a7aade3 | [
"MIT"
] | 46 | 2022-01-17T22:46:08.000Z | 2022-03-06T16:52:00.000Z |
//#include <sys/stat.h>
//#include <stdlib.h>
//#include <stdio.h>
#include <fileio.h>
#include "types.h"
#include "file.h"
Bool FileReadMem(Char *pFilePath, void *pMem, Uint32 nBytes)
{
#if 0
FILE *pFile;
pFile = fopen(pFilePath, "rb");
if (pFile)
{
Uint32 nReadBytes;
nReadBytes = fread(pMem, 1, nBytes, pFile);
fclose(pFile);
return (nBytes == nReadBytes);
}
return FALSE;
#else
int hFile;
unsigned int nReadBytes;
hFile = fioOpen(pFilePath, O_RDONLY);
if (hFile < 0)
{
return FALSE;
}
nReadBytes = fioRead(hFile, pMem, nBytes);
fioClose(hFile);
return (nReadBytes == nBytes);
#endif
}
Bool FileWriteMem(Char *pFilePath, void *pMem, Uint32 nBytes)
{
#if 0
FILE *pFile;
Uint32 nWriteBytes;
pFile = fopen(pFilePath, "wb");
if (pFile)
{
nWriteBytes = fwrite(pMem, 1, nBytes, pFile);
fclose(pFile);
return (nBytes == nWriteBytes);
}
return FALSE;
#else
int hFile;
unsigned int nWriteBytes;
hFile = fioOpen(pFilePath, O_CREAT | O_WRONLY);
if (hFile < 0)
{
return FALSE;
}
nWriteBytes = fioWrite(hFile, pMem, nBytes);
fioClose(hFile);
return (nWriteBytes == nBytes);
#endif
}
Bool FileExists(Char *pFilePath)
{
#if 0
FILE *pFile;
pFile = fopen(pFilePath, "rb");
if (pFile)
{
fclose(pFile);
return true;
}
else
{
return false;
}
#else
int hFile;
hFile = fioOpen(pFilePath, O_RDONLY);
if (hFile < 0)
{
return FALSE;
}
fioClose(hFile);
return TRUE;
#endif
}
| 15.182692 | 62 | 0.602913 | Sunlitspace542 |
1bb5f45c42ace30cd11f4ba10eff08925e217de5 | 5,137 | cpp | C++ | holdem/src/LYHoldemTrunk.cpp | caiqingfeng/libpoker | a2c60884fc5c8e31455fb39e432c49e0df55956b | [
"Apache-2.0"
] | 1 | 2021-04-20T06:22:30.000Z | 2021-04-20T06:22:30.000Z | holdem/src/LYHoldemTrunk.cpp | caiqingfeng/libpoker | a2c60884fc5c8e31455fb39e432c49e0df55956b | [
"Apache-2.0"
] | null | null | null | holdem/src/LYHoldemTrunk.cpp | caiqingfeng/libpoker | a2c60884fc5c8e31455fb39e432c49e0df55956b | [
"Apache-2.0"
] | 2 | 2020-10-29T08:21:22.000Z | 2020-12-02T06:40:18.000Z | /*
* LYHoldemTrunk.cpp
*
* Created on: 2013-7-5
* Author: caiqingfeng
*/
#include <cstdlib>
#include "LYHoldemTrunk.h"
#include "LYHoldemTable.h"
#include "LYHoldemGame.h"
//#include <boost/foreach.hpp>
//#include "common/src/my_log.h"
LYHoldemTrunk:: LYHoldemTrunk(const std::string &trunk_id, const std::string &trunk_name,
LYHoldemTable *tbl, unsigned int &ts, std::vector<LYSeatPtr> &all_seats,
const std::string &player, const std::string &pf) :
LYTrunk(trunk_id, trunk_name, (LYTable *)tbl, ts, all_seats, player, pf)
{
// TODO Auto-generated constructor stub
if (NULL == tbl->profileMgr) {
profile = NULL;
} else {
if ("" != pf) {
profile = (LYHoldemProfile *)tbl->profileMgr->getHoldemProfileById(pf).get();
}
}
}
LYHoldemTrunk::~LYHoldemTrunk() {
// TODO Auto-generated destructor stub
}
/*
* Game设计只处理当前的Action,可以保证Server和Client代码一致
*/
bool LYHoldemTrunk::playGame(LYHoldemAction &action)
{
// LY_LOG_DBG("enter LYHoldemTrunk::playGame");
if (currentGame == NULL) return false;
bool validAction = ((LYHoldemGame *)currentGame)->onAction(action);
if (!validAction) {
// LY_LOG_INF("invalid action");
return false;
}
return true;
}
void LYHoldemTrunk::createGame(const std::string &game_id, LYHoldemAlgorithmDelegate *had)
{
if (!this->ready2go()) {
// LY_LOG_DBG("not ready to go");
return;
}
this->resetAllSeatsForNewGame();
if (lastGame != NULL) {
delete lastGame;
lastGame = NULL;
}
lastGame = currentGame;
LYHoldemGame *last_game = (LYHoldemGame *)lastGame;
LYSeatPtr btnSeat;
LYSeatPtr sbSeat;
LYSeatPtr bbSeat;
if (lastGame != NULL) {
//brand new game
btnSeat = ((LYHoldemTable *)this->table)->fetchNextOccupiedSeat(last_game->btnSeatNo);
} else {
srand(time(NULL));
LYApplicant random_seat = (enum LYApplicant)(rand()%9+1);
btnSeat = ((LYHoldemTable *)this->table)->fetchNextOccupiedSeat(random_seat);
}
sbSeat = ((LYHoldemTable *)this->table)->fetchNextOccupiedSeat(btnSeat->seatNo);
bbSeat = ((LYHoldemTable *)this->table)->fetchNextOccupiedSeat(sbSeat->seatNo);
if (sbSeat->seatNo == btnSeat->seatNo || bbSeat->seatNo == btnSeat->seatNo) {
//20160413增加,只有2个人的时候,Btn小盲
sbSeat = btnSeat;
bbSeat = ((LYHoldemTable *)this->table)->fetchNextOccupiedSeat(btnSeat->seatNo);
}
currentGame = new LYHoldemGame(game_id, seats, this->getSmallBlindPrice(), this->getBigBlindPrice(),
btnSeat, sbSeat, bbSeat, (LYHoldemTable *)table, had);
}
unsigned int LYHoldemTrunk::getSmallBlindPrice()
{
//此处应该调用ProfileMgr的接口
if (NULL == profile) {
return 10;
}
return profile->get_small_blind();
}
unsigned int LYHoldemTrunk::getBigBlindPrice()
{
//此处应该调用ProfileMgr的接口
if (NULL == profile) {
return 25;
}
return profile->get_big_blind();
}
unsigned int LYHoldemTrunk::getCurrentMaxBuyin()
{
//此处应该调用ProfileMgr的接口
if (NULL == profile) {
return 0;
}
return profile->get_max_chips();
}
unsigned int LYHoldemTrunk::getCurrentMinBuyin()
{
//此处应该调用ProfileMgr的接口
if (NULL == profile) {
return 0;
}
return profile->get_min_chips();
}
bool LYHoldemTrunk::ready2go()
{
if (currentGame != NULL) {
enum LYGameRound round = ((LYHoldemGame *)currentGame)->getRound();
if (round != LYGameWaiting && round != LYGameClosed && round != LYGameInit) {
// LY_LOG_ERR("there is a game ongoing ... round=" << ((LYHoldemGame *)currentGame)->getRound());
return false;
}
}
unsigned int seated = 0;
std::vector<LYSeatPtr>::iterator it = seats.begin();
for (; it!=seats.end(); it++) {
LYSeatPtr st = *it;
if (st->status != LYSeatOpen && st->chipsAtHand > 0) {
seated++;
}
}
if (seated < 2) {
// LY_LOG_ERR("seated:" << seated << " must be greater than 2" );
return false;
}
return true;
}
bool LYHoldemTrunk::isGameOver()
{
if (currentGame == NULL || ((LYHoldemGame *)currentGame)->getRound() == LYGameClosed) {
return true;
}
return false;
}
void LYHoldemTrunk::resetAllSeatsForNewGame()
{
std::vector<LYSeatPtr>::iterator it = seats.begin();
for(; it != seats.end(); it++) {
LYSeatPtr st = *it;
LYHoldemSeat *holdemSeat = (LYHoldemSeat *)st.get();
holdemSeat->resetForNewGame();
}
}
void LYHoldemTrunk::activeProfile()
{
if ("" != profile_id && ((LYHoldemTable *)table)->profileMgr != NULL) {
profile = (LYHoldemProfile *)(((LYHoldemTable *)table)->profileMgr->getHoldemProfileById(profile_id).get());
}
}
/*
* 只是给客户端从空口中创建实例用,或者服务器侧从数据库中恢复实例
* 所有状态都在后续tableFromOta或者tableFromDb中设置
*/
void LYHoldemTrunk::createGameInstance(const std::string &game_id)
{
if (lastGame != NULL) {
delete lastGame;
lastGame = NULL;
}
lastGame = currentGame;
LYHoldemGame *last_game = (LYHoldemGame *)lastGame;
currentGame = new LYHoldemGame(game_id, seats,
(LYHoldemTable *)table);
}
/*
* 只是给客户端从空口中创建实例用,或者服务器侧从数据库中恢复实例
* 20160311
*/
void LYHoldemTrunk::createGameInstance(const std::string &game_id, std::vector < std::pair<std::string, std::string> >& kvps)
{
if (lastGame != NULL) {
delete lastGame;
lastGame = NULL;
}
lastGame = currentGame;
LYHoldemGame *last_game = (LYHoldemGame *)lastGame;
currentGame = new LYHoldemGame(game_id, seats,
(LYHoldemTable *)table, kvps);
} | 25.058537 | 125 | 0.696905 | caiqingfeng |
1bb8d67c0f9a83627c2c6eddd412be78c9295d64 | 5,467 | cpp | C++ | src/frameworks/av/media/libmedia/IMediaHTTPConnection.cpp | dAck2cC2/m3e | 475b89b59d5022a94e00b636438b25e27e4eaab2 | [
"Apache-2.0"
] | null | null | null | src/frameworks/av/media/libmedia/IMediaHTTPConnection.cpp | dAck2cC2/m3e | 475b89b59d5022a94e00b636438b25e27e4eaab2 | [
"Apache-2.0"
] | null | null | null | src/frameworks/av/media/libmedia/IMediaHTTPConnection.cpp | dAck2cC2/m3e | 475b89b59d5022a94e00b636438b25e27e4eaab2 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//#define LOG_NDEBUG 0
#define LOG_TAG "IMediaHTTPConnection"
#include <utils/Log.h>
#include <media/IMediaHTTPConnection.h>
#include <binder/IMemory.h>
#include <binder/Parcel.h>
#include <utils/String8.h>
#include <media/stagefright/foundation/ADebug.h>
#include <media/stagefright/MediaErrors.h>
namespace android {
enum {
CONNECT = IBinder::FIRST_CALL_TRANSACTION,
DISCONNECT,
READ_AT,
GET_SIZE,
GET_MIME_TYPE,
GET_URI
};
struct BpMediaHTTPConnection : public BpInterface<IMediaHTTPConnection> {
explicit BpMediaHTTPConnection(const sp<IBinder> &impl)
: BpInterface<IMediaHTTPConnection>(impl) {
}
virtual bool connect(
const char *uri, const KeyedVector<String8, String8> *headers) {
Parcel data, reply;
data.writeInterfaceToken(
IMediaHTTPConnection::getInterfaceDescriptor());
String16 tmp(uri);
data.writeString16(tmp);
tmp = String16("");
if (headers != NULL) {
for (size_t i = 0; i < headers->size(); ++i) {
String16 key(headers->keyAt(i).string());
String16 val(headers->valueAt(i).string());
tmp.append(key);
tmp.append(String16(": "));
tmp.append(val);
tmp.append(String16("\r\n"));
}
}
data.writeString16(tmp);
remote()->transact(CONNECT, data, &reply);
int32_t exceptionCode = reply.readExceptionCode();
if (exceptionCode) {
return false;
}
sp<IBinder> binder = reply.readStrongBinder();
mMemory = interface_cast<IMemory>(binder);
return mMemory != NULL;
}
virtual void disconnect() {
Parcel data, reply;
data.writeInterfaceToken(
IMediaHTTPConnection::getInterfaceDescriptor());
remote()->transact(DISCONNECT, data, &reply);
}
virtual ssize_t readAt(off64_t offset, void *buffer, size_t size) {
Parcel data, reply;
data.writeInterfaceToken(
IMediaHTTPConnection::getInterfaceDescriptor());
data.writeInt64(offset);
data.writeInt32(size);
status_t err = remote()->transact(READ_AT, data, &reply);
if (err != OK) {
ALOGE("remote readAt failed");
return UNKNOWN_ERROR;
}
int32_t exceptionCode = reply.readExceptionCode();
if (exceptionCode) {
return UNKNOWN_ERROR;
}
int32_t lenOrErrorCode = reply.readInt32();
// Negative values are error codes
if (lenOrErrorCode < 0) {
return lenOrErrorCode;
}
size_t len = lenOrErrorCode;
if (len > size) {
ALOGE("requested %zu, got %zu", size, len);
return ERROR_OUT_OF_RANGE;
}
if (len > mMemory->size()) {
ALOGE("got %zu, but memory has %zu", len, mMemory->size());
return ERROR_OUT_OF_RANGE;
}
if(buffer == NULL) {
ALOGE("readAt got a NULL buffer");
return UNKNOWN_ERROR;
}
if (mMemory->pointer() == NULL) {
ALOGE("readAt got a NULL mMemory->pointer()");
return UNKNOWN_ERROR;
}
memcpy(buffer, mMemory->pointer(), len);
return len;
}
virtual off64_t getSize() {
Parcel data, reply;
data.writeInterfaceToken(
IMediaHTTPConnection::getInterfaceDescriptor());
remote()->transact(GET_SIZE, data, &reply);
int32_t exceptionCode = reply.readExceptionCode();
if (exceptionCode) {
return UNKNOWN_ERROR;
}
return reply.readInt64();
}
virtual status_t getMIMEType(String8 *mimeType) {
*mimeType = String8("");
Parcel data, reply;
data.writeInterfaceToken(
IMediaHTTPConnection::getInterfaceDescriptor());
remote()->transact(GET_MIME_TYPE, data, &reply);
int32_t exceptionCode = reply.readExceptionCode();
if (exceptionCode) {
return UNKNOWN_ERROR;
}
*mimeType = String8(reply.readString16());
return OK;
}
virtual status_t getUri(String8 *uri) {
*uri = String8("");
Parcel data, reply;
data.writeInterfaceToken(
IMediaHTTPConnection::getInterfaceDescriptor());
remote()->transact(GET_URI, data, &reply);
int32_t exceptionCode = reply.readExceptionCode();
if (exceptionCode) {
return UNKNOWN_ERROR;
}
*uri = String8(reply.readString16());
return OK;
}
private:
sp<IMemory> mMemory;
};
IMPLEMENT_META_INTERFACE(
MediaHTTPConnection, "android.media.IMediaHTTPConnection");
} // namespace android
| 26.668293 | 76 | 0.600878 | dAck2cC2 |
1bb9a61043791730943e9a2018a2d27aec1a13d0 | 12,855 | cpp | C++ | MATLAB Files/StarshotACS1_ert_rtw/StarshotACS1.cpp | Natsoulas/ACS | aac4468e2bcd71eee61d89e9483a5dc9ef7302c1 | [
"MIT"
] | null | null | null | MATLAB Files/StarshotACS1_ert_rtw/StarshotACS1.cpp | Natsoulas/ACS | aac4468e2bcd71eee61d89e9483a5dc9ef7302c1 | [
"MIT"
] | null | null | null | MATLAB Files/StarshotACS1_ert_rtw/StarshotACS1.cpp | Natsoulas/ACS | aac4468e2bcd71eee61d89e9483a5dc9ef7302c1 | [
"MIT"
] | 1 | 2022-03-18T18:57:10.000Z | 2022-03-18T18:57:10.000Z | //
// Academic License - for use in teaching, academic research, and meeting
// course requirements at degree granting institutions only. Not for
// government, commercial, or other organizational use.
//
// File: StarshotACS1.cpp
//
// Code generated for Simulink model 'StarshotACS1'.
//
// Model version : 1.75
// Simulink Coder version : 8.12 (R2017a) 16-Feb-2017
// C/C++ source code generated on : Sun May 20 23:34:07 2018
//
// Target selection: ert.tlc
// Embedded hardware selection: ARM Compatible->ARM Cortex
// Code generation objectives:
// 1. Execution efficiency
// 2. RAM efficiency
// Validation result: Not run
//
#include "StarshotACS1.h"
// Model step function
void StarshotACS1ModelClass::step()
{
real_T rtb_Gain[3];
real_T rtb_TSamp[3];
real_T rtb_VectorConcatenate[9];
real_T rtb_Saturation3;
real_T rtb_TrigonometricFunction5;
real_T rtb_TSamp_o;
real_T rtb_Gain_0;
int32_T i;
real_T rtb_VectorConcatenate_0[9];
real_T rtb_Product1_f;
real_T rtb_Gain8_idx_1;
real_T rtb_Gain8_idx_2;
real_T rtb_Gain8_idx_0;
real_T rtb_Product1_i_idx_0;
real_T rtb_Product1_i_idx_1;
int32_T tmp;
// Outputs for Atomic SubSystem: '<Root>/StarshotACS'
// Gain: '<S2>/Kane damping' incorporates:
// DiscreteIntegrator: '<S2>/Discrete-Time Integrator'
// Gain: '<S2>/Gain 2'
rtb_Gain8_idx_0 = 0.41837 * -rtDW.DiscreteTimeIntegrator_DSTATE[0];
// Gain: '<S2>/Gain 2' incorporates:
// DiscreteIntegrator: '<S2>/Discrete-Time Integrator'
rtb_Product1_i_idx_0 = -rtDW.DiscreteTimeIntegrator_DSTATE[0];
// Gain: '<S2>/Kane damping' incorporates:
// DiscreteIntegrator: '<S2>/Discrete-Time Integrator'
// Gain: '<S2>/Gain 2'
rtb_Gain8_idx_1 = 0.41837 * -rtDW.DiscreteTimeIntegrator_DSTATE[1];
// Gain: '<S2>/Gain 2' incorporates:
// DiscreteIntegrator: '<S2>/Discrete-Time Integrator'
rtb_Product1_i_idx_1 = -rtDW.DiscreteTimeIntegrator_DSTATE[1];
rtb_Product1_f = -rtDW.DiscreteTimeIntegrator_DSTATE[2];
// Gain: '<S2>/Kane damping' incorporates:
// DiscreteIntegrator: '<S2>/Discrete-Time Integrator'
// Gain: '<S2>/Gain 2'
rtb_Gain8_idx_2 = 0.41837 * -rtDW.DiscreteTimeIntegrator_DSTATE[2];
// S-Function (sdsp2norm2): '<S2>/Normalization' incorporates:
// Inport: '<Root>/Bfield_body'
rtb_Saturation3 = 1.0 / (((rtU.Bfield_body[0] * rtU.Bfield_body[0] +
rtU.Bfield_body[1] * rtU.Bfield_body[1]) + rtU.Bfield_body[2] *
rtU.Bfield_body[2]) + 1.0E-10);
rtb_Gain[0] = rtU.Bfield_body[0] * rtb_Saturation3;
// SampleTimeMath: '<S5>/TSamp' incorporates:
// Inport: '<Root>/angularvelocity'
//
// About '<S5>/TSamp':
// y = u * K where K = 1 / ( w * Ts )
rtb_TSamp[0] = rtU.w[0] * 100.0;
// S-Function (sdsp2norm2): '<S2>/Normalization' incorporates:
// Inport: '<Root>/Bfield_body'
rtb_Gain[1] = rtU.Bfield_body[1] * rtb_Saturation3;
// SampleTimeMath: '<S5>/TSamp' incorporates:
// Inport: '<Root>/angularvelocity'
//
// About '<S5>/TSamp':
// y = u * K where K = 1 / ( w * Ts )
rtb_TSamp[1] = rtU.w[1] * 100.0;
// S-Function (sdsp2norm2): '<S2>/Normalization' incorporates:
// Inport: '<Root>/Bfield_body'
rtb_Gain[2] = rtU.Bfield_body[2] * rtb_Saturation3;
// SampleTimeMath: '<S5>/TSamp' incorporates:
// Inport: '<Root>/angularvelocity'
//
// About '<S5>/TSamp':
// y = u * K where K = 1 / ( w * Ts )
rtb_TSamp[2] = rtU.w[2] * 100.0;
// Product: '<S4>/Product2'
rtb_TrigonometricFunction5 = rtb_Gain[0];
// Product: '<S4>/Product4'
rtb_TSamp_o = rtb_Gain[1];
// Product: '<S4>/Product5'
rtb_Gain_0 = rtb_Gain[0];
// Gain: '<S2>/Gain' incorporates:
// Product: '<S4>/Product'
// Product: '<S4>/Product1'
// Product: '<S4>/Product2'
// Product: '<S4>/Product3'
// Sum: '<S4>/Sum'
// Sum: '<S4>/Sum1'
rtb_Gain[0] = (rtb_Gain8_idx_1 * rtb_Gain[2] - rtb_Gain8_idx_2 * rtb_Gain[1]) *
0.025063770565652812;
rtb_Gain[1] = (rtb_Gain8_idx_2 * rtb_TrigonometricFunction5 - rtb_Gain8_idx_0 *
rtb_Gain[2]) * 0.025063770565652812;
// SignalConversion: '<S6>/ConcatBufferAtVector ConcatenateIn1' incorporates:
// Constant: '<S6>/Constant3'
// Gain: '<S6>/Gain'
// Inport: '<Root>/angularvelocity'
rtb_VectorConcatenate[0] = 0.0;
rtb_VectorConcatenate[1] = rtU.w[2];
rtb_VectorConcatenate[2] = -rtU.w[1];
// SignalConversion: '<S6>/ConcatBufferAtVector ConcatenateIn2' incorporates:
// Constant: '<S6>/Constant3'
// Gain: '<S6>/Gain1'
// Inport: '<Root>/angularvelocity'
rtb_VectorConcatenate[3] = -rtU.w[2];
rtb_VectorConcatenate[4] = 0.0;
rtb_VectorConcatenate[5] = rtU.w[0];
// SignalConversion: '<S6>/ConcatBufferAtVector ConcatenateIn3' incorporates:
// Constant: '<S6>/Constant3'
// Gain: '<S6>/Gain2'
// Inport: '<Root>/angularvelocity'
rtb_VectorConcatenate[6] = rtU.w[1];
rtb_VectorConcatenate[7] = -rtU.w[0];
rtb_VectorConcatenate[8] = 0.0;
// Saturate: '<S2>/Saturation3'
rtb_Gain8_idx_2 = rtb_Gain[0];
// Saturate: '<S2>/Saturation4'
rtb_Saturation3 = rtb_Gain[1];
// Saturate: '<S2>/Saturation5' incorporates:
// Gain: '<S2>/Gain'
// Product: '<S4>/Product4'
// Product: '<S4>/Product5'
// Sum: '<S4>/Sum2'
rtb_Gain8_idx_0 = (rtb_Gain8_idx_0 * rtb_TSamp_o - rtb_Gain8_idx_1 *
rtb_Gain_0) * 0.025063770565652812;
// Sqrt: '<S8>/Sqrt4' incorporates:
// DotProduct: '<S8>/Dot Product6'
// Inport: '<Root>/Bfield_body'
rtb_Gain8_idx_1 = std::sqrt((rtU.Bfield_body[0] * rtU.Bfield_body[0] +
rtU.Bfield_body[1] * rtU.Bfield_body[1]) + rtU.Bfield_body[2] *
rtU.Bfield_body[2]);
// DotProduct: '<S9>/Dot Product6'
rtb_TSamp_o = 0.0;
for (i = 0; i < 3; i++) {
// Product: '<S3>/Product6' incorporates:
// Inport: '<Root>/Bfield_body'
// Product: '<S3>/Product4'
rtb_TrigonometricFunction5 = ((rtConstB.VectorConcatenate[i + 3] *
rtU.Bfield_body[1] + rtConstB.VectorConcatenate[i] * rtU.Bfield_body[0]) +
rtConstB.VectorConcatenate[i + 6] * rtU.Bfield_body[2]) / rtb_Gain8_idx_1;
// DotProduct: '<S9>/Dot Product6'
rtb_TSamp_o += rtb_TrigonometricFunction5 * rtb_TrigonometricFunction5;
// Product: '<S3>/Product6' incorporates:
// Inport: '<Root>/Bfield_body'
// Inport: '<Root>/angularvelocity'
// Product: '<S11>/Product3'
// Product: '<S3>/Product4'
rtb_Gain[i] = rtU.w[i] * rtU.Bfield_body[i];
}
// Sqrt: '<S9>/Sqrt4' incorporates:
// DotProduct: '<S9>/Dot Product6'
rtb_TrigonometricFunction5 = std::sqrt(rtb_TSamp_o);
// Trigonometry: '<S3>/Trigonometric Function5'
if (rtb_TrigonometricFunction5 > 1.0) {
rtb_TrigonometricFunction5 = 1.0;
} else {
if (rtb_TrigonometricFunction5 < -1.0) {
rtb_TrigonometricFunction5 = -1.0;
}
}
rtb_TrigonometricFunction5 = std::asin(rtb_TrigonometricFunction5);
// End of Trigonometry: '<S3>/Trigonometric Function5'
// SampleTimeMath: '<S7>/TSamp'
//
// About '<S7>/TSamp':
// y = u * K where K = 1 / ( w * Ts )
rtb_TSamp_o = rtb_TrigonometricFunction5 * 100.0;
// Switch: '<S12>/Switch1' incorporates:
// Constant: '<S12>/Constant10'
// Constant: '<S12>/Constant9'
// Inport: '<Root>/angularvelocity'
if (rtU.w[2] >= 0.0) {
i = 1;
} else {
i = -1;
}
// End of Switch: '<S12>/Switch1'
// Switch: '<S11>/Switch' incorporates:
// Constant: '<S11>/Constant3'
// Constant: '<S11>/Constant4'
// DotProduct: '<S13>/Dot Product6'
// DotProduct: '<S14>/Dot Product6'
// Inport: '<Root>/Bfield_body'
// Inport: '<Root>/angularvelocity'
// Product: '<S11>/Divide6'
// Sqrt: '<S13>/Sqrt4'
// Sqrt: '<S14>/Sqrt4'
// Sum: '<S11>/Add'
if (1.0 / std::sqrt((rtU.w[0] * rtU.w[0] + rtU.w[1] * rtU.w[1]) + rtU.w[2] *
rtU.w[2]) * ((rtb_Gain[0] + rtb_Gain[1]) + rtb_Gain[2]) /
std::sqrt((rtU.Bfield_body[0] * rtU.Bfield_body[0] + rtU.Bfield_body[1] *
rtU.Bfield_body[1]) + rtU.Bfield_body[2] * rtU.Bfield_body[2]) >
0.0) {
tmp = 1;
} else {
tmp = -1;
}
// End of Switch: '<S11>/Switch'
// Product: '<S3>/Product7' incorporates:
// Gain: '<S3>/Gain10'
// Gain: '<S3>/Gain11'
// Product: '<S3>/Product8'
// Sum: '<S3>/Sum7'
// Sum: '<S7>/Diff'
// UnitDelay: '<S7>/UD'
//
// Block description for '<S7>/Diff':
//
// Add in CPU
//
// Block description for '<S7>/UD':
//
// Store in Global RAM
rtb_Gain8_idx_1 = ((rtb_TSamp_o - rtDW.UD_DSTATE_k) * 7.5058075858287763E-5 +
2.0910503844363048E-6 * rtb_TrigonometricFunction5) *
(real_T)(i * tmp) / rtb_Gain8_idx_1;
// Sum: '<S2>/Sum10' incorporates:
// Constant: '<S2>/Identity matrix'
// Product: '<S2>/Product1'
for (i = 0; i < 3; i++) {
rtb_VectorConcatenate_0[3 * i] = rtb_VectorConcatenate[3 * i] +
rtConstP.Identitymatrix_Value[3 * i];
rtb_VectorConcatenate_0[1 + 3 * i] = rtb_VectorConcatenate[3 * i + 1] +
rtConstP.Identitymatrix_Value[3 * i + 1];
rtb_VectorConcatenate_0[2 + 3 * i] = rtb_VectorConcatenate[3 * i + 2] +
rtConstP.Identitymatrix_Value[3 * i + 2];
}
// End of Sum: '<S2>/Sum10'
for (i = 0; i < 3; i++) {
// Update for DiscreteIntegrator: '<S2>/Discrete-Time Integrator' incorporates:
// Gain: '<S2>/Gain 8'
// Gain: '<S2>/Gain 9'
// Gain: '<S2>/Id inverse'
// Product: '<S2>/Product1'
// Sum: '<S2>/Sum8'
// Sum: '<S5>/Diff'
// UnitDelay: '<S5>/UD'
//
// Block description for '<S5>/Diff':
//
// Add in CPU
//
// Block description for '<S5>/UD':
//
// Store in Global RAM
rtDW.DiscreteTimeIntegrator_DSTATE[i] += ((0.0 - (rtb_TSamp[i] -
rtDW.UD_DSTATE[i])) - ((121.13723637508934 * -rtb_Product1_i_idx_0 *
0.41837 * rtb_VectorConcatenate_0[i] + 121.13723637508934 *
-rtb_Product1_i_idx_1 * 0.41837 * rtb_VectorConcatenate_0[i + 3]) +
121.13723637508934 * -rtb_Product1_f * 0.41837 * rtb_VectorConcatenate_0[i
+ 6])) * 0.01;
// Update for UnitDelay: '<S5>/UD'
//
// Block description for '<S5>/UD':
//
// Store in Global RAM
rtDW.UD_DSTATE[i] = rtb_TSamp[i];
}
// Update for UnitDelay: '<S7>/UD'
//
// Block description for '<S7>/UD':
//
// Store in Global RAM
rtDW.UD_DSTATE_k = rtb_TSamp_o;
// Saturate: '<S2>/Saturation3'
if (rtb_Gain8_idx_2 > 0.00050127541131305623) {
// Outport: '<Root>/detumble'
rtY.detumble[0] = 0.00050127541131305623;
} else if (rtb_Gain8_idx_2 < -0.00050127541131305623) {
// Outport: '<Root>/detumble'
rtY.detumble[0] = -0.00050127541131305623;
} else {
// Outport: '<Root>/detumble'
rtY.detumble[0] = rtb_Gain8_idx_2;
}
// Saturate: '<S2>/Saturation4'
if (rtb_Saturation3 > 0.00050127541131305623) {
// Outport: '<Root>/detumble'
rtY.detumble[1] = 0.00050127541131305623;
} else if (rtb_Saturation3 < -0.00050127541131305623) {
// Outport: '<Root>/detumble'
rtY.detumble[1] = -0.00050127541131305623;
} else {
// Outport: '<Root>/detumble'
rtY.detumble[1] = rtb_Saturation3;
}
// Saturate: '<S2>/Saturation5'
if (rtb_Gain8_idx_0 > 0.00050127541131305623) {
// Outport: '<Root>/detumble'
rtY.detumble[2] = 0.00050127541131305623;
} else if (rtb_Gain8_idx_0 < -0.00050127541131305623) {
// Outport: '<Root>/detumble'
rtY.detumble[2] = -0.00050127541131305623;
} else {
// Outport: '<Root>/detumble'
rtY.detumble[2] = rtb_Gain8_idx_0;
}
// Outport: '<Root>/point' incorporates:
// Saturate: '<S3>/Saturation3'
// Saturate: '<S3>/Saturation4'
rtY.point[0] = 0.0;
rtY.point[1] = 0.0;
// Saturate: '<S3>/Saturation5' incorporates:
// Gain: '<S3>/Gain'
rtb_Gain8_idx_2 = 0.025063770565652812 * rtb_Gain8_idx_1;
if (rtb_Gain8_idx_2 > 0.00050127541131305623) {
// Outport: '<Root>/point'
rtY.point[2] = 0.00050127541131305623;
} else if (rtb_Gain8_idx_2 < -0.00050127541131305623) {
// Outport: '<Root>/point'
rtY.point[2] = -0.00050127541131305623;
} else {
// Outport: '<Root>/point'
rtY.point[2] = rtb_Gain8_idx_2;
}
// End of Saturate: '<S3>/Saturation5'
// End of Outputs for SubSystem: '<Root>/StarshotACS'
}
// Model initialize function
void StarshotACS1ModelClass::initialize()
{
// (no initialization code required)
}
// Constructor
StarshotACS1ModelClass::StarshotACS1ModelClass()
{
}
// Destructor
StarshotACS1ModelClass::~StarshotACS1ModelClass()
{
// Currently there is no destructor body generated.
}
// Real-Time Model get method
RT_MODEL * StarshotACS1ModelClass::getRTM()
{
return (&rtM);
}
//
// File trailer for generated code.
//
// [EOF]
//
| 29.349315 | 83 | 0.629094 | Natsoulas |
1bbdc79532f96536257f9f19ccabae3020b510d2 | 3,323 | cpp | C++ | src/renderer/rt/objects/extern.cpp | gartenriese2/monorenderer | 56c6754b2b765d5841fe73fb43ea49438f5dd96f | [
"MIT"
] | null | null | null | src/renderer/rt/objects/extern.cpp | gartenriese2/monorenderer | 56c6754b2b765d5841fe73fb43ea49438f5dd96f | [
"MIT"
] | null | null | null | src/renderer/rt/objects/extern.cpp | gartenriese2/monorenderer | 56c6754b2b765d5841fe73fb43ea49438f5dd96f | [
"MIT"
] | null | null | null | #include "extern.hpp"
#include <MonoEngine/core/log.hpp>
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wfloat-equal"
#pragma GCC diagnostic ignored "-Wconversion"
#include <assimp/Importer.hpp>
#include <assimp/scene.h>
#pragma GCC diagnostic pop
#include <assimp/postprocess.h>
#include <glm/glm.hpp>
namespace renderer {
namespace rt {
Extern::Extern(const std::string & path) {
Assimp::Importer importer;
const aiScene* scene = importer.ReadFile(path, aiProcess_Triangulate);
if (!scene) {
LOG(importer.GetErrorString());
} else {
LOG_ASSERT(scene->HasMeshes(), "imported scene has no meshes");
const auto * meshes = scene->mMeshes;
LOG("numMeshes:" + std::to_string(scene->mNumMeshes));
for (auto i {0u}; i < scene->mNumMeshes; ++i) {
LOG_ASSERT(meshes[i]->HasPositions() && meshes[i]->HasFaces(), "mesh does not have positions or faces");
const auto hasColors {meshes[i]->HasVertexColors(0)};
const auto * faces = meshes[i]->mFaces;
LOG("numFaces:" + std::to_string(meshes[i]->mNumFaces));
// for (auto j {0u}; j < meshes[i]->mNumFaces; ++j) {
for (auto j {0u}; j < 125000; ++j) {
LOG_ASSERT(faces[j].mNumIndices == 3, "face is not a triangle");
const auto aVec {meshes[i]->mVertices[faces[j].mIndices[0]]};
auto a {glm::vec3(aVec[0], aVec[1], aVec[2])};
const auto bVec {meshes[i]->mVertices[faces[j].mIndices[1]]};
auto b {glm::vec3(bVec[0], bVec[1], bVec[2])};
const auto cVec {meshes[i]->mVertices[faces[j].mIndices[2]]};
auto c {glm::vec3(cVec[0], cVec[1], cVec[2])};
// scaling
a *= 30.f;
b *= 30.f;
c *= 30.f;
// moving
a += glm::vec3(0.f, -6.5f, -7.f);
b += glm::vec3(0.f, -6.5f, -7.f);
c += glm::vec3(0.f, -6.5f, -7.f);
m_vertices.emplace_back(a.x);
m_vertices.emplace_back(a.y);
m_vertices.emplace_back(a.z);
m_vertices.emplace_back(0.f);
m_vertices.emplace_back(b.x);
m_vertices.emplace_back(b.y);
m_vertices.emplace_back(b.z);
m_vertices.emplace_back(0.f);
m_vertices.emplace_back(c.x);
m_vertices.emplace_back(c.y);
m_vertices.emplace_back(c.z);
m_vertices.emplace_back(0.f);
const auto n {glm::normalize(glm::cross(b - a, c - a))};
m_normals.emplace_back(n.x);
m_normals.emplace_back(n.y);
m_normals.emplace_back(n.z);
m_normals.emplace_back(0.f);
m_normals.emplace_back(n.x);
m_normals.emplace_back(n.y);
m_normals.emplace_back(n.z);
m_normals.emplace_back(0.f);
m_normals.emplace_back(n.x);
m_normals.emplace_back(n.y);
m_normals.emplace_back(n.z);
m_normals.emplace_back(0.f);
glm::vec4 col;
if (!hasColors) {
col = glm::vec4(1.f, 0.f, 0.f, 1.f); // default color
} else {
const auto color {meshes[i]->mColors[0][faces[j].mIndices[0]]};
col = glm::vec4(color.r, color.g, color.b, 1.f);
}
m_colors.emplace_back(col.r);
m_colors.emplace_back(col.g);
m_colors.emplace_back(col.b);
m_colors.emplace_back(col.a);
m_colors.emplace_back(col.r);
m_colors.emplace_back(col.g);
m_colors.emplace_back(col.b);
m_colors.emplace_back(col.a);
m_colors.emplace_back(col.r);
m_colors.emplace_back(col.g);
m_colors.emplace_back(col.b);
m_colors.emplace_back(col.a);
}
}
}
}
}
} // namespace renderer | 29.669643 | 107 | 0.647006 | gartenriese2 |
1bbf7ecaf3a304724db01622d481b4650767f2a3 | 646 | hpp | C++ | runtime/waitgroup.hpp | vron/compute | 25c57423a77171bdcf18e6ee17316cc295ea5469 | [
"Unlicense"
] | 6 | 2020-07-24T15:29:38.000Z | 2021-03-09T05:16:58.000Z | runtime/waitgroup.hpp | vron/compute | 25c57423a77171bdcf18e6ee17316cc295ea5469 | [
"Unlicense"
] | 1 | 2020-07-27T12:24:50.000Z | 2020-08-15T11:18:22.000Z | runtime/waitgroup.hpp | vron/compute | 25c57423a77171bdcf18e6ee17316cc295ea5469 | [
"Unlicense"
] | 1 | 2021-03-09T02:25:09.000Z | 2021-03-09T02:25:09.000Z | #pragma once
#include <condition_variable>
#include <mutex>
template <class T> class WaitGroup {
std::mutex m;
std::condition_variable cv;
T counter;
public:
WaitGroup() : counter(0) {};
~WaitGroup(){};
void add(T n) {
std::lock_guard<std::mutex> lk(m);
counter += n;
}
void done() {
bool notify = false;
{
std::lock_guard<std::mutex> lk(m);
counter -= 1;
assert(counter>=0);
if (counter == 0)
notify = true;
}
if (notify)
cv.notify_one();
}
void wait() {
std::unique_lock<std::mutex> lk(m);
cv.wait(lk, [this] { return this->counter <= 0; });
}
};
| 17.459459 | 55 | 0.557276 | vron |
1bc313d041ed043298578ce482c9df781a7a3c38 | 6,327 | cpp | C++ | src/cvar/cameraCalibration.cpp | vnm-interactive/Cinder-MarkerlessAR | 28db3199d92145cfb143c4cc457e2b8b013f5729 | [
"MIT"
] | null | null | null | src/cvar/cameraCalibration.cpp | vnm-interactive/Cinder-MarkerlessAR | 28db3199d92145cfb143c4cc457e2b8b013f5729 | [
"MIT"
] | null | null | null | src/cvar/cameraCalibration.cpp | vnm-interactive/Cinder-MarkerlessAR | 28db3199d92145cfb143c4cc457e2b8b013f5729 | [
"MIT"
] | null | null | null | /*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
//
// Copyright (C) 2012, Takuya MINAGAWA.
// Third party copyrights are property of their respective owners.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do
// so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//M*/
#include "cameraCalibration.h"
#include <stdio.h>
#include <iostream>
#include "opencv2/imgproc.hpp"
#include "opencv2/calib3d.hpp"
#include "opencv2/highgui.hpp"
#include "commonCvFunctions.h"
using namespace std;
using namespace cv;
using namespace cvar;
cameraCalibration::cameraCalibration(void)
{
max_img_num = 25;
pat_row = 7;
pat_col = 10;
chess_size = 23.0;
camera_matrix.create(3, 3, CV_32FC1);
distortion.create(1, 5, CV_32FC1);
}
cameraCalibration::~cameraCalibration(void)
{
}
void cameraCalibration::setMaxImageNum(int num)
{
max_img_num = num;
}
void cameraCalibration::setBoardColsAndRows(int r, int c)
{
pat_row = r;
pat_col = c;
}
void cameraCalibration::setChessSize(float size)
{
chess_size = size;
}
bool cameraCalibration::addCheckerImage(Mat& img)
{
if(checker_image_list.size() >= max_img_num)
return false;
else
checker_image_list.push_back(img);
return true;
}
void cameraCalibration::releaseCheckerImage()
{
checker_image_list.clear();
}
bool cameraCalibration::doCalibration()
{
int i, j, k;
bool found;
int image_num = checker_image_list.size();
// int pat_size = pat_row * pat_col;
// int all_points = image_num * pat_size;
if(image_num < 3){
cout << "please add checkker pattern image!" << endl;
return false;
}
// int *p_count = new int[image_num];
rotation.clear();
translation.clear();
cv::Size pattern_size(pat_col,pat_row);
// Point3f *objects = new Point3f[all_points];
// Point2f *corners = new Point2f[all_points];
Point3f obj;
vector<Point3f> objects;
vector<vector<Point3f>> object_points;
// 3D set of spatial coordinates
for (j = 0; j < pat_row; j++) {
for (k = 0; k < pat_col; k++) {
obj.x = j * chess_size;
obj.y = k * chess_size;
obj.z = 0.0;
objects.push_back(obj);
}
}
vector<Point2f> corners;
vector<vector<Point2f>> image_points;
int found_num = 0;
cvNamedWindow ("Calibration", CV_WINDOW_AUTOSIZE);
auto img_itr = checker_image_list.begin();
i = 0;
while (img_itr != checker_image_list.end()) {
// Corner detection of chess board (calibration pattern)
found = cv::findChessboardCorners(*img_itr, pattern_size, corners);
cout << i << "...";
if (found) {
cout << "ok" << endl;
found_num++;
}
else {
cout << "fail" << endl;
}
// Fixed a corner position in the sub-pixel accuracy, drawing
Mat src_gray(img_itr->size(), CV_8UC1, 1);
cvtColor(*img_itr, src_gray, CV_BGR2GRAY);
// cvCvtColor (src_img[i], src_gray, CV_BGR2GRAY);
cornerSubPix(src_gray, corners, cv::Size(3,3), cv::Size(-1,-1), TermCriteria(CV_TERMCRIT_ITER | CV_TERMCRIT_EPS, 20, 0.03));
// cvFindCornerSubPix (src_gray, &corners[i * PAT_SIZE], corner_count,
// cvSize (3, 3), cvSize (-1, -1), cvTermCriteria (CV_TERMCRIT_ITER | CV_TERMCRIT_EPS, 20, 0.03));
drawChessboardCorners(*img_itr, pattern_size, transPointVecToMat2D(corners), found);
// cvDrawChessboardCorners (src_img[i], pattern_size, &corners[i * PAT_SIZE], corner_count, found);
// p_count[i] = corner_count;
if(found){
image_points.push_back(corners);
object_points.push_back(objects);
}
corners.clear();
imshow("Calibration", *img_itr);
cvWaitKey (0);
i++;
img_itr++;
}
cvDestroyWindow ("Calibration");
if (found_num < 3){
return false;
}
// cvInitMatHeader (&image_points, ALL_POINTS, 1, CV_32FC2, corners);
// cvInitMatHeader (&point_counts, IMAGE_NUM, 1, CV_32SC1, p_count);
// Internal parameters, distortion factor, the estimation of the external parameters
// cvCalibrateCamera2 (&object_points, &image_points, &point_counts, cvSize (640, 480), intrinsic, distortion);
calibrateCamera(object_points, image_points, checker_image_list[0].size(), camera_matrix, distortion, rotation, translation);
/* CvMat sub_image_points, sub_object_points;
int base = 0;
cvGetRows (&image_points, &sub_image_points, base * PAT_SIZE, (base + 1) * PAT_SIZE);
cvGetRows (&object_points, &sub_object_points, base * PAT_SIZE, (base + 1) * PAT_SIZE);
cvFindExtrinsicCameraParams2 (&sub_object_points, &sub_image_points, intrinsic, distortion, rotation, translation);
// (7) Export to XML file
CvFileStorage *fs;
fs = cvOpenFileStorage ("camera.xml", 0, CV_STORAGE_WRITE);
cvWrite (fs, "intrinsic", intrinsic);
cvWrite (fs, "rotation", rotation);
cvWrite (fs, "translation", translation);
cvWrite (fs, "distortion", distortion);
cvReleaseFileStorage (&fs);
*/
return true;
}
void cameraCalibration::saveCameraMatrix(const string& filename)
{
FileStorage fs(filename, FileStorage::WRITE);
writeCameraMatrix(fs, "camera_matrix");
}
void cameraCalibration::writeCameraMatrix(FileStorage& cvfs, const string& name)
{
cvfs << name << camera_matrix;
} | 30.128571 | 132 | 0.706654 | vnm-interactive |
1bc55f8f655ef35887559e1a5d08e4b5cfbd86da | 3,838 | cpp | C++ | src/mapart/map_nbt.cpp | AgustinSRG/ImageToMapMC | fbff8017e87c30baaa0c9c2327bdd28846253646 | [
"MIT"
] | null | null | null | src/mapart/map_nbt.cpp | AgustinSRG/ImageToMapMC | fbff8017e87c30baaa0c9c2327bdd28846253646 | [
"MIT"
] | null | null | null | src/mapart/map_nbt.cpp | AgustinSRG/ImageToMapMC | fbff8017e87c30baaa0c9c2327bdd28846253646 | [
"MIT"
] | null | null | null | /*
* This file is part of ImageToMapMC project
*
* Copyright (c) 2021 Agustin San Roman
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "map_nbt.h"
#include <fstream>
#include <io/stream_reader.h>
#include <io/stream_writer.h>
#include <io/izlibstream.h>
#include <io/ozlibstream.h>
#include <nbt_tags.h>
using namespace std;
using namespace nbt;
using namespace colors;
using namespace mapart;
using namespace minecraft;
std::vector<map_color_t> mapart::readMapNBTFile(std::string fileName)
{
std::vector<map_color_t> result(MAP_WIDTH * MAP_HEIGHT);
std::ifstream file(fileName, std::ios::binary);
if (!file)
{
throw -1;
}
try
{
zlib::izlibstream igzs(file);
auto pair = nbt::io::read_compound(igzs);
nbt::tag_compound comp = *pair.second;
nbt::value *colorsArray = &comp.at(std::string("data")).at(std::string("colors"));
nbt::tag_byte_array colorsBytes = colorsArray->as<nbt::tag_byte_array>();
size_t map_size = MAP_WIDTH * MAP_HEIGHT;
for (size_t i = 0; i < map_size; i++)
{
result[i] = uint8_t(colorsBytes.at(i));
}
}
catch (...)
{
throw -2;
}
return result;
}
void mapart::writeMapNBTFile(std::string fileName, const std::vector<map_color_t> &mapColors, minecraft::McVersion version)
{
nbt::tag_compound root;
nbt::tag_compound data;
// Set meta data
data.insert("width", nbt::tag_int(MAP_WIDTH));
data.insert("height", nbt::tag_int(MAP_HEIGHT));
data.insert("dimension", nbt::tag_int(0));
data.insert("scale", nbt::tag_int(0));
data.insert("trackingPosition:", nbt::tag_int(0));
data.insert("unlimitedTracking", nbt::tag_int(0));
if (version >= McVersion::MC_1_14)
{
// If we can, prevent the map from being modified
data.insert("locked", nbt::tag_int(1));
}
// Set the center far away to prevent issues (20M)
data.insert("xCenter", nbt::tag_int(20000000));
data.insert("zCenter", nbt::tag_int(20000000));
// Set colors array
nbt::tag_byte_array byteArray;
size_t size = MAP_WIDTH * MAP_HEIGHT;
for (size_t i = 0; i < size; i++)
{
short val = mapColors[i];
int8_t ip = static_cast<int8_t>((val > 127) ? (val - 256) : val);
byteArray.push_back(ip);
}
data.insert("colors", byteArray.clone());
// Insert tags to root
root.insert("data", data.clone());
root.insert("DataVersion", minecraft::versionToDataVersion(version));
std::ofstream file(fileName, std::ios::binary);
if (!file)
{
throw -1;
}
try
{
zlib::ozlibstream ogzs(file, -1, true);
nbt::io::write_tag("", root, ogzs);
}
catch (...)
{
throw -2;
}
}
| 28.857143 | 123 | 0.656592 | AgustinSRG |
1bca8822cc7f4e1d41211158ff39b24eb841a77e | 10,247 | cpp | C++ | Src/Eni/UsbDevice/Stm/USBDDevice.cpp | vlad230596/Eni | 2bbd07b6e4e20b2c2a6ad6fdc9d948e6352eecb7 | [
"MIT"
] | null | null | null | Src/Eni/UsbDevice/Stm/USBDDevice.cpp | vlad230596/Eni | 2bbd07b6e4e20b2c2a6ad6fdc9d948e6352eecb7 | [
"MIT"
] | null | null | null | Src/Eni/UsbDevice/Stm/USBDDevice.cpp | vlad230596/Eni | 2bbd07b6e4e20b2c2a6ad6fdc9d948e6352eecb7 | [
"MIT"
] | null | null | null | #include "EniConfig.h"
#if defined(ENI_USB_DEVICE) && defined(ENI_STM)
#include "UsbDDevice.h"
#include "usbd_conf.h"
#include "Core/usbd_def.h"
#include "Core/usbd_ioreq.h"
#include "Core/usbd_ctlreq.h"
#include "Core/usbd_core.h"
#include ENI_HAL_INCLUDE_FILE
#include "USBTypes.h"
#include "UsbMicrosoftTypes.h"
#include <type_traits>
#include <new>
using namespace Eni;
extern "C" {
extern PCD_HandleTypeDef hpcd_USB_OTG_FS;
}
namespace Eni::USB {
__attribute__((used)) USBD_HandleTypeDef UsbDevice::hUsbDevice{};
__attribute__((used)) UsbDDeviceContext* _context = nullptr;
//For other-speed description
__ALIGN_BEGIN volatile USB::DeviceQualifierDescriptor USBD_NDC_DeviceQualifierDesc __ALIGN_END {
USB::UsbVersion(2),
USB::UsbClass::Device::UseInterfaceClass(),
64,
1,
0
};
#define USB_VENDOR_CODE_WINUSB 'P'
__ALIGN_BEGIN volatile USB::Microsoft::MicrosoftStringDescriptor NDC_StringDescriptor __ALIGN_END = {
(uint8_t)USB_VENDOR_CODE_WINUSB
};
extern volatile USB::DeviceQualifierDescriptor USBD_NDC_DeviceQualifierDesc;
extern volatile USB::Microsoft::MicrosoftStringDescriptor NDC_StringDescriptor;
__attribute__((used)) std::aligned_storage_t<USBD_MAX_STR_DESC_SIZ, 4> _descriptorsBuffer;
UsbDDeviceContext* UsbDevice::getContext(){
return _context;
}
void hang(){
while(true){
asm("nop");
}
}
__attribute__((used)) const USBD_DescriptorsTypeDef UsbDevice::_descriptorsTable = {
&UsbDevice::getDeviceDescriptor,
&UsbDevice::getLangidStrDescriptor,
&UsbDevice::getManufacturerStringDescriptor,
&UsbDevice::getProductStringDescriptor,
&UsbDevice::getSerialStringDescriptor,
&UsbDevice::getConfigStringDescriptor,
&UsbDevice::getInterfaceStringDescriptor
};
__attribute__((used)) const USBD_ClassTypeDef UsbDevice::_usbClassBinding = {
&UsbDevice::coreInit,
&UsbDevice::coreDeinit,
&UsbDevice::coreSetup,
0, //USBD_NDC_EP0_TxReady,
&UsbDevice::coreEp0RxReady,
&UsbDevice::coreDataIn,
&UsbDevice::coreDataOut,
&UsbDevice::coreSof,
&UsbDevice::coreIsoInIncomplete,
&UsbDevice::coreIsoOutIncomplete,
&UsbDevice::coreGetCfgDesc,
&UsbDevice::coreGetCfgDesc,
&UsbDevice::coreGetCfgDesc,
&UsbDevice::coreGetDeviceQualifierDesc,
&UsbDevice::coreGetUserStringDesc
};
uint8_t UsbDevice::coreInit(USBD_HandleTypeDef* pdev, uint8_t cfgidx){
//TODO: use configuration id
for(size_t i = 0; i < _context->getInterfaceCount(); ++i){
auto interface = _context->getInterface(i);
if(interface != nullptr){
if(!interface->init(pdev)){
return USBD_FAIL;
}
}
}
return USBD_OK;
}
uint8_t UsbDevice::coreDeinit(USBD_HandleTypeDef* pdev, uint8_t cfgidx){
//TODO: use configuration id
for(size_t i = 0; i < _context->getInterfaceCount(); ++i){
auto interface = _context->getInterface(i);
if(interface != nullptr){
if(!interface->deinit(pdev)){
//return USBD_FAIL;
}
}
}
return USBD_OK;
}
uint8_t UsbDevice::coreImplSetup(USBD_SetupReqTypedef request, void* data){
switch ( request.bmRequest & USB_REQ_RECIPIENT_MASK ){
case USB_REQ_RECIPIENT_INTERFACE:{
if(_context != nullptr){
auto* interface = _context->getInterface(request.wValue);
if(interface != nullptr){
hang();
/*if(interface->control(&hUsbDevice, request.bRequest, (uint8_t*)data, request.wLength)){
return USBD_OK;
}*/
}
}
break;
}
case USB_REQ_RECIPIENT_ENDPOINT:
hang();
/*if(_usb_device_context != nullptr){
if(request.bRequest == USB_REQ_CLEAR_FEATURE){ //reset pipe is called at host side
//do reset pipe
if(_clearFeatureCallback != nullptr){
_clearFeatureCallback(request.wIndex);
}
}
}*/
break;
case USB_REQ_RECIPIENT_DEVICE:
default:
break;
}
return USBD_OK;
}
uint8_t UsbDevice::coreSetup(USBD_HandleTypeDef* pdev, USBD_SetupReqTypedef *req){
hang();
/*if (req->wLength){
//Request with data stage{
if((req->bmRequest & USB_REQ_DATA_PHASE_MASK) == USB_REQ_DATA_PHASE_DEVICE_TO_HOST){
//device to host data stage => handler should send data
return coreImplSetup(*req, 0);
}else{ //host to device data stage! Can't execute now, read data first & execute later in Ep0Receive callback
last_request = *req;
USBD_CtlPrepareRx (pdev, (uint8_t*)&ep0Buffer[0], req->wLength);
}
} else {//No data stage => simple request => execute now
return coreImplSetup(*req, 0);
}*/
return USBD_OK;
}
uint8_t UsbDevice::coreEp0RxReady(USBD_HandleTypeDef* pdev){
hang();
//coreImplSetup(last_request, &ep0Buffer[0]); //data in stage complete => execute request
//last_request.bRequest = 0xff;
return USBD_OK;
}
UsbDInterface* UsbDevice::findInterfaceByEndpointAddress(uint8_t address){
if(_context == nullptr){
return nullptr;
}
auto if_cnt = _context->getInterfaceCount();
for(uint32_t i = 0; i < if_cnt; ++i){
auto interface = _context->getInterface(i);
if(interface != nullptr){
auto endpoint = interface->getEndpoint(address);
if(endpoint != nullptr){
return interface;
}
}
}
return nullptr;
}
uint8_t UsbDevice::coreDataIn(USBD_HandleTypeDef* pdev, uint8_t epnum){
auto interface = findInterfaceByEndpointAddress(USB::EndpointAddress::makeIn(epnum));//TODO: cleanup
if(interface != nullptr){
interface->txComplete(epnum | 0x80);
}
return USBD_OK;
}
uint8_t UsbDevice::coreDataOut(USBD_HandleTypeDef* pdev, uint8_t epnum){
uint32_t rxLen = USBD_LL_GetRxDataSize (pdev, epnum);
auto interface = findInterfaceByEndpointAddress(USB::EndpointAddress::makeOut(epnum));
if(interface != nullptr){
interface->rxComplete(rxLen, epnum);
}
return USBD_OK;
}
uint8_t UsbDevice::coreSof(USBD_HandleTypeDef* pdev){
hang();
return USBD_OK;
}
uint8_t UsbDevice::coreIsoInIncomplete(USBD_HandleTypeDef* pdev, uint8_t epnum){
hang();
return USBD_OK;
}
uint8_t UsbDevice::coreIsoOutIncomplete(USBD_HandleTypeDef* pdev, uint8_t epnum){
hang();
return USBD_OK;
}
uint8_t* UsbDevice::coreGetCfgDesc(uint16_t* length){
auto* mem = reinterpret_cast<uint8_t*>(&_descriptorsBuffer);
auto* buffer = mem;
USB::ConfigurationDescriptor* cd = new(buffer) USB::ConfigurationDescriptor();
cd->wTotalLength = 0;
cd->bNumInterfaces = (uint8_t)_context->getInterfaceCount();
cd->bConfigurationValue = 0x01;
cd->iConfiguration = USBD_IDX_CONFIG_STR;
cd->bmAttributes = USB::UsbAttributes().value;
cd->bMaxPower = 500;
buffer += sizeof(USB::ConfigurationDescriptor);
for(uint32_t i = 0; i < _context->getInterfaceCount(); ++i){
auto emptySize = (mem + sizeof(_descriptorsBuffer)) - buffer;
auto size = _context->getInterface(i)->getDescriptor(buffer, emptySize, i);
buffer += size;
cd->wTotalLength += size;
}
cd->wTotalLength += sizeof(USB::ConfigurationDescriptor);
*length = cd->wTotalLength;
return reinterpret_cast<uint8_t*>(&_descriptorsBuffer);
}
uint8_t* UsbDevice::getDeviceDescriptor(USBD_SpeedTypeDef speed, uint16_t* length){
auto mem = reinterpret_cast<uint8_t*>(&_descriptorsBuffer);
auto& desc = *new(mem) USB::DeviceDescriptor();
*length = sizeof(USB::DeviceDescriptor);
desc.bcdUSB = 0x0200;
desc.classDescription = USB::UsbClassDescriptor(0,0,0);
desc.bMaxPacketSize0 = 64;
desc.idVendor = _context->vid;
desc.idProduct = _context->pid;
desc.bcdDevice = USB::UsbVersion(2);
desc.iManufacturer = USBD_IDX_MFC_STR;
desc.iProduct = USBD_IDX_PRODUCT_STR;
desc.iSerialNumber = USBD_IDX_SERIAL_STR;
desc.bNumConfigurations = 1;
return reinterpret_cast<uint8_t*>(&desc);
}
struct USBDDummyClassData{
uint32_t reserved;
};
__attribute__((used)) static USBDDummyClassData _classData = {};
void UsbDevice::start(UsbDDeviceContext* context){
_context = context;
hUsbDevice.pClassData = &_classData; //Otherwise USBD_Reset handler would not disable interfaces ((
//hUsbDevice.pClassData = nullptr; //Init?
hUsbDevice.dev_speed = USBD_SPEED_FULL;
USBD_Init(&hUsbDevice, const_cast<USBD_DescriptorsTypeDef*>(&_descriptorsTable), 0);
USBD_RegisterClass(&hUsbDevice, const_cast<USBD_ClassTypeDef*>(&_usbClassBinding));
USBD_Start(&hUsbDevice);
}
uint8_t* UsbDevice::coreGetDeviceQualifierDesc (uint16_t *length){
*length = sizeof (USBD_NDC_DeviceQualifierDesc);
return (uint8_t*)&USBD_NDC_DeviceQualifierDesc;
}
uint8_t* UsbDevice::coreGetUserStringDesc(USBD_HandleTypeDef* pdev, uint8_t index, uint16_t* length){
*length = 0;
if ( 0xEE == index ){
*length = sizeof (NDC_StringDescriptor);
return (uint8_t*)&NDC_StringDescriptor;
}
return NULL;
}
uint8_t* UsbDevice::getLangidStrDescriptor(USBD_SpeedTypeDef speed, uint16_t* length){
auto mem = static_cast<void*>(&_descriptorsBuffer);
auto& desc = *new(mem) USB::LanguageIDStringDescriptor<1>();
*length = sizeof(USB::LanguageIDStringDescriptor<1>);
desc.languages[0] = USB::LanguageID::EnglishUnitedStates;
return reinterpret_cast<uint8_t*>(&desc);
}
uint8_t* UsbDevice::getManufacturerStringDescriptor(USBD_SpeedTypeDef speed, uint16_t* length){
return USB::MakeStringDescriptor(_context->manufacturerStringDescriptor, &_descriptorsBuffer, sizeof(_descriptorsBuffer), length);
}
uint8_t* UsbDevice::getProductStringDescriptor(USBD_SpeedTypeDef speed, uint16_t* length){
return USB::MakeStringDescriptor(_context->productStringDescriptor, &_descriptorsBuffer, sizeof(_descriptorsBuffer), length);
}
uint8_t* UsbDevice::getSerialStringDescriptor(USBD_SpeedTypeDef speed, uint16_t* length){
return USB::MakeStringDescriptor(_context->serialStringDescriptor, &_descriptorsBuffer, sizeof(_descriptorsBuffer), length);
}
uint8_t* UsbDevice::getConfigStringDescriptor(USBD_SpeedTypeDef speed, uint16_t* length){
return USB::MakeStringDescriptor(_context->configurationStringDescriptor, &_descriptorsBuffer, sizeof(_descriptorsBuffer), length);
}
uint8_t* UsbDevice::getInterfaceStringDescriptor(USBD_SpeedTypeDef speed, uint16_t* length){
return USB::MakeStringDescriptor(_context->interfaceStringDescriptor, &_descriptorsBuffer, sizeof(_descriptorsBuffer), length);
}
USBD_StatusTypeDef UsbDevice::interfaceRequest(USBD_HandleTypeDef* pdev, USBD_SetupReqTypedef* req){
uint8_t interface_id = (uint8_t)req->wValue; //TODO: bug! wIndex == interface id
auto interface = _context->getInterface(interface_id);
if(interface == nullptr){
return USBD_FAIL;
}
return interface->interfaceRequest(pdev, req);
}
}
#endif
| 29.110795 | 132 | 0.760027 | vlad230596 |
1bcd386bae008d200b1b68a5f70bff7ccfe2d92c | 706 | cpp | C++ | src/main.cpp | QQB17/simple_log | e800cce5bde4e04bc9d91d1180a6c28a1b658c69 | [
"MIT"
] | null | null | null | src/main.cpp | QQB17/simple_log | e800cce5bde4e04bc9d91d1180a6c28a1b658c69 | [
"MIT"
] | null | null | null | src/main.cpp | QQB17/simple_log | e800cce5bde4e04bc9d91d1180a6c28a1b658c69 | [
"MIT"
] | null | null | null | #include <iostream>
#include "logger.h"
int main()
{
// Simple log message
qlog::log("Hello world!");
// Select log_level
qlog::log(log_level::level::debug, "Debuging: ", "Selected log level");
// Debug log
qlog::debug("This is a debug message.");
// Info log
qlog::info("Information");
// Error log
qlog::error("Error");
// Crititcal log
qlog::critical("Critical operator: ", "1");
// Set log level to filter the output log
log_level::set_level(log_level::level::critical);
// Any information will not output if the the level is lower than setting level
qlog::info("This message unable to log.", "Log failed");
return 0;
} | 22.774194 | 83 | 0.621813 | QQB17 |
1bce55470ec93585ddba0657ed132f96c2a85aec | 1,627 | hpp | C++ | src/MarkerInterval.hpp | rlorigro/shasta | 06522d841362ee22265d006062759b0cbcf3a1ea | [
"BSD-3-Clause-Open-MPI"
] | 1 | 2019-02-11T02:46:16.000Z | 2019-02-11T02:46:16.000Z | src/MarkerInterval.hpp | rlorigro/shasta | 06522d841362ee22265d006062759b0cbcf3a1ea | [
"BSD-3-Clause-Open-MPI"
] | null | null | null | src/MarkerInterval.hpp | rlorigro/shasta | 06522d841362ee22265d006062759b0cbcf3a1ea | [
"BSD-3-Clause-Open-MPI"
] | 1 | 2019-08-14T22:56:29.000Z | 2019-08-14T22:56:29.000Z | #ifndef SHASTA_MARKER_INTERVAL_HPP
#define SHASTA_MARKER_INTERVAL_HPP
// Shasta.
#include "ReadId.hpp"
#include"tuple.hpp"
// Standard library.
#include "array.hpp"
namespace shasta {
class MarkerInterval;
class MarkerIntervalWithRepeatCounts;
}
// Class to describe the interval between
// two markers on an oriented read.
// The two markers are not necessarily consecutive.
// HOoever, the second marker has a higher ordinal
// than the first.
class shasta::MarkerInterval {
public:
OrientedReadId orientedReadId;
// The ordinals of the two markers.
array<uint32_t, 2> ordinals;
MarkerInterval() {}
MarkerInterval(
OrientedReadId orientedReadId,
uint32_t ordinal0,
uint32_t ordinal1) :
orientedReadId(orientedReadId)
{
ordinals[0] = ordinal0;
ordinals[1] = ordinal1;
}
bool operator==(const MarkerInterval& that) const
{
return
tie(orientedReadId, ordinals[0], ordinals[1])
==
tie(that.orientedReadId, that.ordinals[0], that.ordinals[1]);
}
bool operator<(const MarkerInterval& that) const
{
return
tie(orientedReadId, ordinals[0], ordinals[1])
<
tie(that.orientedReadId, that.ordinals[0], that.ordinals[1]);
}
};
class shasta::MarkerIntervalWithRepeatCounts :
public MarkerInterval {
public:
vector<uint8_t> repeatCounts;
// The constructor does not fill in the repeat counts.
MarkerIntervalWithRepeatCounts(const MarkerInterval& markerInterval) :
MarkerInterval(markerInterval){}
};
#endif
| 23.57971 | 74 | 0.672403 | rlorigro |
1bd6375b3f8a52ee376f3ed86437ace1b3a75d38 | 2,788 | cpp | C++ | solved-lightOj/1220.cpp | Maruf-Tuhin/Online_Judge | cf9b2a522e8b1a9623d3996a632caad7fd67f751 | [
"MIT"
] | 1 | 2019-03-31T05:47:30.000Z | 2019-03-31T05:47:30.000Z | solved-lightOj/1220.cpp | the-redback/competitive-programming | cf9b2a522e8b1a9623d3996a632caad7fd67f751 | [
"MIT"
] | null | null | null | solved-lightOj/1220.cpp | the-redback/competitive-programming | cf9b2a522e8b1a9623d3996a632caad7fd67f751 | [
"MIT"
] | null | null | null | /**
* @author : Maruf Tuhin
* @College : CUET CSE 11
* @Topcoder : the_redback
* @CodeForces : the_redback
* @UVA : the_redback
* @link : http://www.fb.com/maruf.2hin
*/
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long llu;
#define ft first
#define sd second
#define mp make_pair
#define pb(x) push_back(x)
#define all(x) x.begin(),x.end()
#define allr(x) x.rbegin(),x.rend()
#define mem(a,b) memset(a,b,sizeof(a))
#define repv(i,a) for(i=0;i<(ll)a.size();i++)
#define revv(i,a) for(i=(ll)a.size()-1;i>=0;i--)
#define rep(i,a,b) for(i=a;i<=b;i++)
#define rev(i,a,b) for(i=a;i>=b;i--)
#define sf(a) scanf("%lld",&a)
#define sf2(a,b) scanf("%lld %lld",&a,&b)
#define sf3(a,b,c) scanf("%lld %lld %lld",&a,&b,&c)
#define inf 1e9
#define eps 1e-9
#define mod 1000000007
#define NN 100010
#ifdef redback
#define bug printf("line=%d\n",__LINE__);
#define debug(args...) {cout<<":: "; dbg,args; cerr<<endl;}
struct debugger{template<typename T>debugger& operator ,(const T& v){cerr<<v<<" ";return *this;}}dbg;
#else
#define bug
#define debug(args...)
#endif //debugging macros
#define NN 70000
bool p[NN+7]; //Hashing
vector<ll>pr,facts; //storing prime
void sieve(ll n)
{
ll i,j,k,l;
p[1]=1;
pr.push_back(2);
for(i=4;i<=n;i+=2)
p[i]=1;
for(i=3;i<=n;i+=2)
{
if(p[i]==0)
{
pr.push_back(i);
for(j=i*i;j<=n;j+=2*i)
p[j]=1;
}
}
}
ll factor(ll n)
{
facts.clear();
ll count,k,i;
for(i=0;i<pr.size() && pr[i]*pr[i]<=n;i++)
{
k=pr[i];
count=0;
while(n%k==0)
{
n/=k;
count++;
}
facts.pb(count);
if(n==1)
break;
}
if(n>1)
facts.pb(1);
}
int main()
{
//ios_base::sync_with_stdio(0); cin.tie(0);
#ifdef redback
freopen("C:\\Users\\Maruf\\Desktop\\in.txt","r",stdin);
#endif
sieve(NN);
ll t=1,tc;
sf(tc);
ll l,m,n;
while(tc--) {
ll i,j,l;
sf(n);
ll minusFlag=0;
if(n<0)
{
n*=-1;
minusFlag=1;
}
factor(n);
ll ans=0;
for(i=1;i<34;i++)
{
ll flag=1;
for(j=0;j<facts.size();j++)
{
if(facts[j]%i!=0)
{
flag=0;
break;
}
}
if(minusFlag && i%2==0)
continue;
if(flag)
ans=max(ans,i);
}
printf("Case %lld: %lld\n",t++,ans);
}
return 0;
}
| 20.350365 | 102 | 0.455524 | Maruf-Tuhin |
1bd89cca521d094d1cd134dc7bfc1de501552147 | 948 | hpp | C++ | RubetekIOS-CPP.framework/Versions/A/Headers/libnet/dawn/string_method.hpp | yklishevich/RubetekIOS-CPP-releases | 7dfbbb45b8de7dbb6fa995ff5dcbca4ec06c2bdb | [
"MIT"
] | null | null | null | RubetekIOS-CPP.framework/Versions/A/Headers/libnet/dawn/string_method.hpp | yklishevich/RubetekIOS-CPP-releases | 7dfbbb45b8de7dbb6fa995ff5dcbca4ec06c2bdb | [
"MIT"
] | null | null | null | RubetekIOS-CPP.framework/Versions/A/Headers/libnet/dawn/string_method.hpp | yklishevich/RubetekIOS-CPP-releases | 7dfbbb45b8de7dbb6fa995ff5dcbca4ec06c2bdb | [
"MIT"
] | null | null | null | #pragma once
#include <string>
namespace dawn
{
inline void string_pop_front(std::string& s, size_t n)
{
s = s.substr(n);
}
inline bool string_pop_front_if_find(std::string& s, std::string const& w)
{
size_t const pos = s.find(w);
if (pos == std::string::npos) return false;
string_pop_front(s, pos + w.size());
return true;
}
inline bool string_pop_front_if_find_backward(std::string& s, std::string const& w)
{
size_t const pos = s.rfind(w);
if (pos == std::string::npos) return false;
string_pop_front(s, pos + w.size());
return true;
}
inline bool string_pop_front_equal(std::string& s, std::string const& w)
{
if (w.empty()) return true;
if (s.size() >= w.size() && s.compare(0, w.size() - 1, w))
{
s = s.substr(w.size());
return true;
}
return false;
}
}
| 25.621622 | 87 | 0.549578 | yklishevich |
1bdb8642d7c9b5cf912f7b4b68073aa0aa0c49e6 | 1,560 | cpp | C++ | homework/Pashchenko/01/hw02.cpp | nkotelevskii/msu_cpp_spring_2018 | b5d84447f9b8c7f3615b421c51cf4192f1b90342 | [
"MIT"
] | 12 | 2018-02-20T15:25:12.000Z | 2022-02-15T03:31:55.000Z | homework/Pashchenko/01/hw02.cpp | nkotelevskii/msu_cpp_spring_2018 | b5d84447f9b8c7f3615b421c51cf4192f1b90342 | [
"MIT"
] | 1 | 2018-02-26T12:40:47.000Z | 2018-02-26T12:40:47.000Z | homework/Pashchenko/01/hw02.cpp | nkotelevskii/msu_cpp_spring_2018 | b5d84447f9b8c7f3615b421c51cf4192f1b90342 | [
"MIT"
] | 33 | 2018-02-20T15:25:11.000Z | 2019-02-13T22:33:36.000Z | #include <iostream>
#include "numbers.dat"
void sieve(bool *primes, int len)
{
for(int i = 0; i < len; i++)
primes[i] = true;
primes[0] = primes[1] = false;
for (int i = 2; i < len; i++)
{
if (primes[i])
{
for (int j = 2 * i; j < len; j += i)
primes[j] = false;
}
}
}
int left(int edge)
{
int l = 0, r = Size, med;
while(r - l > 1)
{
med = (l + r) / 2;
if(Data[med] >= edge)
r = med;
else
l = med;
}
if(edge == Data[l])
return l;
if(edge == Data[r])
return r;
return -1;
}
int right(int edge)
{
int l = 0, r = Size, med;
while(r - l > 1)
{
med = (l + r) / 2;
if(Data[med] <= edge)
l = med;
else
r = med;
}
if(edge == Data[l])
return l;
if(edge == Data[r])
return r;
return -1;
}
int main(int argc, char *argv[])
{
if(!(argc & 1) || argc == 1)
return -1;
const int n = Data[Size - 1];
bool *primes = new bool[n];
sieve(primes, n);
int l, r, ld, rd;
for(int i = 1; i < argc; i += 2)
{
l = std::atoi(argv[i]);
r = std::atoi(argv[i + 1]);
ld = left(l);
rd = right(r);
if(ld == -1 || rd == -1)
continue;
int counter = 0;
for(int j = ld; j <= rd; ++j)
counter += primes[Data[j]];
std::cout << counter << std::endl;
}
delete [] primes;
return 0;
}
| 16.595745 | 48 | 0.398077 | nkotelevskii |
1bdc4885c28ba7c99411d2f285e03d1db51cce5f | 3,900 | cc | C++ | src/PhysListParticles.cc | hbidaman/detectorSimulations_v10 | 6ceae8e9561638d5a3c886571f60141abc09922c | [
"MIT"
] | 1 | 2020-06-26T15:29:46.000Z | 2020-06-26T15:29:46.000Z | src/PhysListParticles.cc | hbidaman/detectorSimulations_v10 | 6ceae8e9561638d5a3c886571f60141abc09922c | [
"MIT"
] | 1 | 2020-08-05T18:03:43.000Z | 2020-08-05T18:03:43.000Z | src/PhysListParticles.cc | hbidaman/detectorSimulations_v10 | 6ceae8e9561638d5a3c886571f60141abc09922c | [
"MIT"
] | 1 | 2020-06-08T14:21:23.000Z | 2020-06-08T14:21:23.000Z | //
// ********************************************************************
// * License and Disclaimer *
// * *
// * The Geant4 software is copyright of the Copyright Holders of *
// * the Geant4 Collaboration. It is provided under the terms and *
// * conditions of the Geant4 Software License, included in the file *
// * LICENSE and available at http://cern.ch/geant4/license . These *
// * include a list of copyright holders. *
// * *
// * Neither the authors of this software system, nor their employing *
// * institutes,nor the agencies providing financial support for this *
// * work make any representation or warranty, express or implied, *
// * regarding this software system or assume any liability for its *
// * use. Please see the license in the file LICENSE and URL above *
// * for the full disclaimer and the limitation of liability. *
// * *
// * This code implementation is the result of the scientific and *
// * technical work of the GEANT4 collaboration. *
// * By using, copying, modifying or distributing the software (or *
// * any work based on the software) you agree to acknowledge its *
// * use in resulting scientific publications, and indicate your *
// * acceptance of all terms of the Geant4 Software license. *
// ********************************************************************
//
// $Id: PhysListParticles.cc 68007 2013-03-13 11:28:03Z gcosmo $
//
/// \file radioactivedecay/rdecay02/src/PhysListParticles.cc
/// \brief Implementation of the PhysListParticles class
//
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
#include "PhysListParticles.hh"
// Bosons
#include "G4ChargedGeantino.hh"
#include "G4Geantino.hh"
#include "G4Gamma.hh"
#include "G4OpticalPhoton.hh"
// leptons
#include "G4MuonPlus.hh"
#include "G4MuonMinus.hh"
#include "G4NeutrinoMu.hh"
#include "G4AntiNeutrinoMu.hh"
#include "G4Electron.hh"
#include "G4Positron.hh"
#include "G4NeutrinoE.hh"
#include "G4AntiNeutrinoE.hh"
// Hadrons
#include "G4MesonConstructor.hh"
#include "G4BaryonConstructor.hh"
#include "G4IonConstructor.hh"
//ShortLived
#include "G4ShortLivedConstructor.hh"
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
PhysListParticles::PhysListParticles(const G4String& name)
: G4VPhysicsConstructor(name)
{}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
PhysListParticles::~PhysListParticles()
{}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
void PhysListParticles::ConstructParticle()
{
// pseudo-particles
G4Geantino::GeantinoDefinition();
G4ChargedGeantino::ChargedGeantinoDefinition();
// gamma
G4Gamma::GammaDefinition();
// optical photon
G4OpticalPhoton::OpticalPhotonDefinition();
// leptons
G4Electron::ElectronDefinition();
G4Positron::PositronDefinition();
G4MuonPlus::MuonPlusDefinition();
G4MuonMinus::MuonMinusDefinition();
G4NeutrinoE::NeutrinoEDefinition();
G4AntiNeutrinoE::AntiNeutrinoEDefinition();
G4NeutrinoMu::NeutrinoMuDefinition();
G4AntiNeutrinoMu::AntiNeutrinoMuDefinition();
// mesons
G4MesonConstructor mConstructor;
mConstructor.ConstructParticle();
// barions
G4BaryonConstructor bConstructor;
bConstructor.ConstructParticle();
// ions
G4IonConstructor iConstructor;
iConstructor.ConstructParticle();
// Construct resonaces and quarks
G4ShortLivedConstructor pShortLivedConstructor;
pShortLivedConstructor.ConstructParticle();
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
| 33.333333 | 80 | 0.642564 | hbidaman |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.