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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
6abf57c4cb44e56681b630fa98b483724f79f6b2 | 348 | hpp | C++ | inc/implementation/misc/Literals.hpp | LarsHagemann/OrbitEngine | 33e01efaac617c53a701f01729581932fc81e8bf | [
"MIT"
] | null | null | null | inc/implementation/misc/Literals.hpp | LarsHagemann/OrbitEngine | 33e01efaac617c53a701f01729581932fc81e8bf | [
"MIT"
] | 2 | 2022-01-18T21:31:01.000Z | 2022-01-20T21:02:09.000Z | inc/implementation/misc/Literals.hpp | LarsHagemann/OrbitEngine | 33e01efaac617c53a701f01729581932fc81e8bf | [
"MIT"
] | null | null | null | #pragma once
namespace orbit
{
static constexpr size_t operator ""_KiB(size_t in) { return in * 1024; }
static constexpr size_t operator ""_KB(size_t in) { return in * 1000; }
static constexpr size_t operator ""_MiB(size_t in) { return in * 1024 * 1024; }
static constexpr size_t operator ""_MB(size_t in) { return in * 1000 * 1000; }
} | 31.636364 | 80 | 0.695402 | LarsHagemann |
6ac00996bf3bb764d1ac6c8f1bcdad7ebf601c0a | 4,291 | cpp | C++ | Polyhedron/demo/Polyhedron/Plugins/Operations_on_polyhedra/Partition_graph_plugin.cpp | gaschler/cgal | d1fe2afa18da5524db6d4946f42ca4b8d00e0bda | [
"CC0-1.0"
] | 2 | 2020-12-10T00:33:11.000Z | 2020-12-10T00:33:20.000Z | Polyhedron/demo/Polyhedron/Plugins/Operations_on_polyhedra/Partition_graph_plugin.cpp | gaschler/cgal | d1fe2afa18da5524db6d4946f42ca4b8d00e0bda | [
"CC0-1.0"
] | null | null | null | Polyhedron/demo/Polyhedron/Plugins/Operations_on_polyhedra/Partition_graph_plugin.cpp | gaschler/cgal | d1fe2afa18da5524db6d4946f42ca4b8d00e0bda | [
"CC0-1.0"
] | 1 | 2022-03-05T04:18:59.000Z | 2022-03-05T04:18:59.000Z | #include <CGAL/Exact_predicates_inexact_constructions_kernel.h>
#include <CGAL/Three/Polyhedron_demo_plugin_helper.h>
#include "ui_PartitionDialog.h"
#include "Color_map.h"
#include "Scene_surface_mesh_item.h"
#include <CGAL/boost/graph/METIS/partition_graph.h>
#include <CGAL/boost/graph/METIS/partition_dual_graph.h>
#include <QString>
#include <QAction>
#include <QMenu>
#include <QMainWindow>
#include <QApplication>
#include <QElapsedTimer>
#include <QMessageBox>
typedef Scene_surface_mesh_item Scene_facegraph_item;
typedef Scene_facegraph_item::Face_graph FaceGraph;
class PartitionDialog :
public QDialog,
public Ui::PartitionDialog
{
Q_OBJECT
public:
PartitionDialog(QWidget* =0)
{
setupUi(this);
}
};
using namespace CGAL::Three;
class Partition_graph_plugin :
public QObject,
public Polyhedron_demo_plugin_helper
{
Q_OBJECT
Q_INTERFACES(CGAL::Three::Polyhedron_demo_plugin_interface)
Q_PLUGIN_METADATA(IID "com.geometryfactory.PolyhedronDemo.PluginInterface/1.0")
public:
QList<QAction*> actions() const {
return QList<QAction*>() << actionNodalPartition
<< actionDualPartition;;
}
bool applicable(QAction*) const {
return qobject_cast<Scene_facegraph_item*>(scene->item(scene->mainSelectionIndex()));
}
void init(QMainWindow* _mw, CGAL::Three::Scene_interface* scene_interface, Messages_interface*) {
mw = _mw;
this->scene = scene_interface;
actionNodalPartition = new QAction(
tr("Create a Nodal Graph Based Partition")
, mw);
if(actionNodalPartition) {
connect(actionNodalPartition, SIGNAL(triggered()),this, SLOT(create_nodal_partition()));
}
actionDualPartition = new QAction(
tr("Create a Dual Graph Based Partition")
, mw);
if(actionDualPartition) {
connect(actionDualPartition, SIGNAL(triggered()),this, SLOT(create_dual_partition()));
}
}
private:
QAction* actionNodalPartition;
QAction* actionDualPartition;
CGAL::Three::Scene_interface* scene;
enum PARTITION_TYPE{
NODAL=0,
DUAL};
void create_partition(PARTITION_TYPE type)
{
Scene_facegraph_item* item =
qobject_cast<Scene_facegraph_item*>(scene->item(scene->mainSelectionIndex()));
if(!item)
return;
if(!(CGAL::is_triangle_mesh(*item->face_graph())
&& is_valid(*item->face_graph())))
return;
PartitionDialog *dialog = new PartitionDialog();
//opens the dialog
if(!dialog->exec())
return;
int nparts = dialog->nparts_spinBox->value();
QApplication::setOverrideCursor(Qt::WaitCursor);
item->face_graph()->collect_garbage();
item->color_vector().clear();
if(!item->hasPatchIds()){
item->setItemIsMulticolor(true);
item->computeItemColorVectorAutomatically(true);
}
typedef boost::property_map<FaceGraph,CGAL::face_patch_id_t<int> >::type PatchIDMap;
FaceGraph* fg =item->face_graph();
boost::property_map<FaceGraph, boost::vertex_index_t>::type
vimap = get(boost::vertex_index, *fg);
PatchIDMap pidmap = get(CGAL::face_patch_id_t<int>(), *fg);
std::map<boost::graph_traits<FaceGraph>::vertex_descriptor,
int> vpm;
if(type == DUAL)
CGAL::METIS::partition_dual_graph(*fg,
nparts,
CGAL::parameters::vertex_partition_id_map(boost::make_assoc_property_map(vpm)).face_partition_id_map(pidmap).vertex_index_map(vimap)
);
else if(type == NODAL)
CGAL::METIS::partition_graph(*fg,
nparts,
CGAL::parameters::vertex_partition_id_map(boost::make_assoc_property_map(vpm)).face_partition_id_map(pidmap).vertex_index_map(vimap)
);
item->setProperty("NbPatchIds", nparts);
item->invalidateOpenGLBuffers();
QApplication::restoreOverrideCursor();
item->redraw();
}
public Q_SLOTS:
void create_nodal_partition()
{
create_partition(NODAL);
}
void create_dual_partition()
{
create_partition(DUAL);
}
}; // end class Polyhedron_demo_affine_transform_plugin
#include "Partition_graph_plugin.moc"
| 30.006993 | 172 | 0.674435 | gaschler |
6ac8a524062f1d3a40160c3f9ec76c7c4177219e | 110,090 | cpp | C++ | HTML_Lectures/Virtualization_Lecture/vbox/src/VBox/VMM/VMMR3/SELM.cpp | roughk/CSCI-49XX-OpenSource | 74268cbca8bcda3023b2350d046e2dca2853a3ef | [
"BSD-2-Clause",
"CC-BY-4.0"
] | null | null | null | HTML_Lectures/Virtualization_Lecture/vbox/src/VBox/VMM/VMMR3/SELM.cpp | roughk/CSCI-49XX-OpenSource | 74268cbca8bcda3023b2350d046e2dca2853a3ef | [
"BSD-2-Clause",
"CC-BY-4.0"
] | null | null | null | HTML_Lectures/Virtualization_Lecture/vbox/src/VBox/VMM/VMMR3/SELM.cpp | roughk/CSCI-49XX-OpenSource | 74268cbca8bcda3023b2350d046e2dca2853a3ef | [
"BSD-2-Clause",
"CC-BY-4.0"
] | null | null | null | /* $Id: SELM.cpp 73322 2018-07-23 14:04:59Z vboxsync $ */
/** @file
* SELM - The Selector Manager.
*/
/*
* Copyright (C) 2006-2017 Oracle Corporation
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* you can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) as published by the Free Software
* Foundation, in version 2 as it comes in the "COPYING" file of the
* VirtualBox OSE distribution. VirtualBox OSE is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
*/
/** @page pg_selm SELM - The Selector Manager
*
* SELM takes care of GDT, LDT and TSS shadowing in raw-mode, and the injection
* of a few hyper selector for the raw-mode context. In the hardware assisted
* virtualization mode its only task is to decode entries in the guest GDT or
* LDT once in a while.
*
* @see grp_selm
*
*
* @section seg_selm_shadowing Shadowing
*
* SELMR3UpdateFromCPUM() and SELMR3SyncTSS() does the bulk synchronization
* work. The three structures (GDT, LDT, TSS) are all shadowed wholesale atm.
* The idea is to do it in a more on-demand fashion when we get time. There
* also a whole bunch of issues with the current synchronization of all three
* tables, see notes and todos in the code.
*
* When the guest makes changes to the GDT we will try update the shadow copy
* without involving SELMR3UpdateFromCPUM(), see selmGCSyncGDTEntry().
*
* When the guest make LDT changes we'll trigger a full resync of the LDT
* (SELMR3UpdateFromCPUM()), which, needless to say, isn't optimal.
*
* The TSS shadowing is limited to the fields we need to care about, namely SS0
* and ESP0. The Patch Manager makes use of these. We monitor updates to the
* guest TSS and will try keep our SS0 and ESP0 copies up to date this way
* rather than go the SELMR3SyncTSS() route.
*
* When in raw-mode SELM also injects a few extra GDT selectors which are used
* by the raw-mode (hyper) context. These start their life at the high end of
* the table and will be relocated when the guest tries to make use of them...
* Well, that was that idea at least, only the code isn't quite there yet which
* is why we have trouble with guests which actually have a full sized GDT.
*
* So, the summary of the current GDT, LDT and TSS shadowing is that there is a
* lot of relatively simple and enjoyable work to be done, see @bugref{3267}.
*
*/
/*********************************************************************************************************************************
* Header Files *
*********************************************************************************************************************************/
#define LOG_GROUP LOG_GROUP_SELM
#include <VBox/vmm/selm.h>
#include <VBox/vmm/cpum.h>
#include <VBox/vmm/stam.h>
#include <VBox/vmm/em.h>
#include <VBox/vmm/hm.h>
#include <VBox/vmm/mm.h>
#include <VBox/vmm/ssm.h>
#include <VBox/vmm/pgm.h>
#include <VBox/vmm/trpm.h>
#include <VBox/vmm/dbgf.h>
#include "SELMInternal.h"
#include <VBox/vmm/vm.h>
#include <VBox/err.h>
#include <VBox/param.h>
#include <iprt/assert.h>
#include <VBox/log.h>
#include <iprt/asm.h>
#include <iprt/string.h>
#include <iprt/thread.h>
#include <iprt/string.h>
#include "SELMInline.h"
/** SELM saved state version. */
#define SELM_SAVED_STATE_VERSION 5
/*********************************************************************************************************************************
* Internal Functions *
*********************************************************************************************************************************/
static DECLCALLBACK(int) selmR3Save(PVM pVM, PSSMHANDLE pSSM);
static DECLCALLBACK(int) selmR3Load(PVM pVM, PSSMHANDLE pSSM, uint32_t uVersion, uint32_t uPass);
static DECLCALLBACK(int) selmR3LoadDone(PVM pVM, PSSMHANDLE pSSM);
static DECLCALLBACK(void) selmR3InfoGdt(PVM pVM, PCDBGFINFOHLP pHlp, const char *pszArgs);
static DECLCALLBACK(void) selmR3InfoGdtGuest(PVM pVM, PCDBGFINFOHLP pHlp, const char *pszArgs);
static DECLCALLBACK(void) selmR3InfoLdt(PVM pVM, PCDBGFINFOHLP pHlp, const char *pszArgs);
static DECLCALLBACK(void) selmR3InfoLdtGuest(PVM pVM, PCDBGFINFOHLP pHlp, const char *pszArgs);
//static DECLCALLBACK(void) selmR3InfoTss(PVM pVM, PCDBGFINFOHLP pHlp, const char *pszArgs);
//static DECLCALLBACK(void) selmR3InfoTssGuest(PVM pVM, PCDBGFINFOHLP pHlp, const char *pszArgs);
/*********************************************************************************************************************************
* Global Variables *
*********************************************************************************************************************************/
#if defined(VBOX_WITH_RAW_MODE) && defined(LOG_ENABLED)
/** Segment register names. */
static char const g_aszSRegNms[X86_SREG_COUNT][4] = { "ES", "CS", "SS", "DS", "FS", "GS" };
#endif
/**
* Initializes the SELM.
*
* @returns VBox status code.
* @param pVM The cross context VM structure.
*/
VMMR3DECL(int) SELMR3Init(PVM pVM)
{
int rc;
LogFlow(("SELMR3Init\n"));
/*
* Assert alignment and sizes.
* (The TSS block requires contiguous back.)
*/
AssertCompile(sizeof(pVM->selm.s) <= sizeof(pVM->selm.padding)); AssertRelease(sizeof(pVM->selm.s) <= sizeof(pVM->selm.padding));
AssertCompileMemberAlignment(VM, selm.s, 32); AssertRelease(!(RT_UOFFSETOF(VM, selm.s) & 31));
#if 0 /* doesn't work */
AssertCompile((RT_OFFSETOF(VM, selm.s.Tss) & PAGE_OFFSET_MASK) <= PAGE_SIZE - sizeof(pVM->selm.s.Tss));
AssertCompile((RT_OFFSETOF(VM, selm.s.TssTrap08) & PAGE_OFFSET_MASK) <= PAGE_SIZE - sizeof(pVM->selm.s.TssTrap08));
#endif
AssertRelease((RT_UOFFSETOF(VM, selm.s.Tss) & PAGE_OFFSET_MASK) <= PAGE_SIZE - sizeof(pVM->selm.s.Tss));
AssertRelease((RT_UOFFSETOF(VM, selm.s.TssTrap08) & PAGE_OFFSET_MASK) <= PAGE_SIZE - sizeof(pVM->selm.s.TssTrap08));
AssertRelease(sizeof(pVM->selm.s.Tss.IntRedirBitmap) == 0x20);
/*
* Init the structure.
*/
pVM->selm.s.offVM = RT_UOFFSETOF(VM, selm);
pVM->selm.s.aHyperSel[SELM_HYPER_SEL_CS] = (SELM_GDT_ELEMENTS - 0x1) << 3;
pVM->selm.s.aHyperSel[SELM_HYPER_SEL_DS] = (SELM_GDT_ELEMENTS - 0x2) << 3;
pVM->selm.s.aHyperSel[SELM_HYPER_SEL_CS64] = (SELM_GDT_ELEMENTS - 0x3) << 3;
pVM->selm.s.aHyperSel[SELM_HYPER_SEL_TSS] = (SELM_GDT_ELEMENTS - 0x4) << 3;
pVM->selm.s.aHyperSel[SELM_HYPER_SEL_TSS_TRAP08] = (SELM_GDT_ELEMENTS - 0x5) << 3;
if (VM_IS_RAW_MODE_ENABLED(pVM) || HMIsRawModeCtxNeeded(pVM))
{
/*
* Allocate GDT table.
*/
rc = MMR3HyperAllocOnceNoRel(pVM, sizeof(pVM->selm.s.paGdtR3[0]) * SELM_GDT_ELEMENTS,
PAGE_SIZE, MM_TAG_SELM, (void **)&pVM->selm.s.paGdtR3);
AssertRCReturn(rc, rc);
/*
* Allocate LDT area.
*/
rc = MMR3HyperAllocOnceNoRel(pVM, _64K + PAGE_SIZE, PAGE_SIZE, MM_TAG_SELM, &pVM->selm.s.pvLdtR3);
AssertRCReturn(rc, rc);
}
/*
* Init Guest's and Shadow GDT, LDT, TSS changes control variables.
*/
pVM->selm.s.cbEffGuestGdtLimit = 0;
pVM->selm.s.GuestGdtr.pGdt = RTRCPTR_MAX;
pVM->selm.s.GCPtrGuestLdt = RTRCPTR_MAX;
pVM->selm.s.GCPtrGuestTss = RTRCPTR_MAX;
pVM->selm.s.paGdtRC = NIL_RTRCPTR; /* Must be set in SELMR3Relocate because of monitoring. */
pVM->selm.s.pvLdtRC = RTRCPTR_MAX;
pVM->selm.s.pvMonShwTssRC = RTRCPTR_MAX;
pVM->selm.s.GCSelTss = RTSEL_MAX;
pVM->selm.s.fSyncTSSRing0Stack = false;
/* The I/O bitmap starts right after the virtual interrupt redirection
bitmap. Outside the TSS on purpose; the CPU will not check it for
I/O operations. */
pVM->selm.s.Tss.offIoBitmap = sizeof(VBOXTSS);
/* bit set to 1 means no redirection */
memset(pVM->selm.s.Tss.IntRedirBitmap, 0xff, sizeof(pVM->selm.s.Tss.IntRedirBitmap));
/*
* Register the virtual access handlers.
*/
pVM->selm.s.hShadowGdtWriteHandlerType = NIL_PGMVIRTHANDLERTYPE;
pVM->selm.s.hShadowLdtWriteHandlerType = NIL_PGMVIRTHANDLERTYPE;
pVM->selm.s.hShadowTssWriteHandlerType = NIL_PGMVIRTHANDLERTYPE;
pVM->selm.s.hGuestGdtWriteHandlerType = NIL_PGMVIRTHANDLERTYPE;
pVM->selm.s.hGuestLdtWriteHandlerType = NIL_PGMVIRTHANDLERTYPE;
pVM->selm.s.hGuestTssWriteHandlerType = NIL_PGMVIRTHANDLERTYPE;
#ifdef VBOX_WITH_RAW_MODE
if (VM_IS_RAW_MODE_ENABLED(pVM))
{
# ifdef SELM_TRACK_SHADOW_GDT_CHANGES
rc = PGMR3HandlerVirtualTypeRegister(pVM, PGMVIRTHANDLERKIND_HYPERVISOR, false /*fRelocUserRC*/,
NULL /*pfnInvalidateR3*/, NULL /*pfnHandlerR3*/,
NULL /*pszHandlerRC*/, "selmRCShadowGDTWritePfHandler",
"Shadow GDT write access handler", &pVM->selm.s.hShadowGdtWriteHandlerType);
AssertRCReturn(rc, rc);
# endif
# ifdef SELM_TRACK_SHADOW_TSS_CHANGES
rc = PGMR3HandlerVirtualTypeRegister(pVM, PGMVIRTHANDLERKIND_HYPERVISOR, false /*fRelocUserRC*/,
NULL /*pfnInvalidateR3*/, NULL /*pfnHandlerR3*/,
NULL /*pszHandlerRC*/, "selmRCShadowTSSWritePfHandler",
"Shadow TSS write access handler", &pVM->selm.s.hShadowTssWriteHandlerType);
AssertRCReturn(rc, rc);
# endif
# ifdef SELM_TRACK_SHADOW_LDT_CHANGES
rc = PGMR3HandlerVirtualTypeRegister(pVM, PGMVIRTHANDLERKIND_HYPERVISOR, false /*fRelocUserRC*/,
NULL /*pfnInvalidateR3*/, NULL /*pfnHandlerR3*/,
NULL /*pszHandlerRC*/, "selmRCShadowLDTWritePfHandler",
"Shadow LDT write access handler", &pVM->selm.s.hShadowLdtWriteHandlerType);
AssertRCReturn(rc, rc);
# endif
rc = PGMR3HandlerVirtualTypeRegister(pVM, PGMVIRTHANDLERKIND_WRITE, false /*fRelocUserRC*/,
NULL /*pfnInvalidateR3*/, selmGuestGDTWriteHandler,
"selmGuestGDTWriteHandler", "selmRCGuestGDTWritePfHandler",
"Guest GDT write access handler", &pVM->selm.s.hGuestGdtWriteHandlerType);
AssertRCReturn(rc, rc);
rc = PGMR3HandlerVirtualTypeRegister(pVM, PGMVIRTHANDLERKIND_WRITE, false /*fRelocUserRC*/,
NULL /*pfnInvalidateR3*/, selmGuestLDTWriteHandler,
"selmGuestLDTWriteHandler", "selmRCGuestLDTWritePfHandler",
"Guest LDT write access handler", &pVM->selm.s.hGuestLdtWriteHandlerType);
AssertRCReturn(rc, rc);
rc = PGMR3HandlerVirtualTypeRegister(pVM, PGMVIRTHANDLERKIND_WRITE, false /*fRelocUserRC*/,
NULL /*pfnInvalidateR3*/, selmGuestTSSWriteHandler,
"selmGuestTSSWriteHandler", "selmRCGuestTSSWritePfHandler",
"Guest TSS write access handler", &pVM->selm.s.hGuestTssWriteHandlerType);
AssertRCReturn(rc, rc);
}
#endif /* VBOX_WITH_RAW_MODE */
/*
* Register the saved state data unit.
*/
rc = SSMR3RegisterInternal(pVM, "selm", 1, SELM_SAVED_STATE_VERSION, sizeof(SELM),
NULL, NULL, NULL,
NULL, selmR3Save, NULL,
NULL, selmR3Load, selmR3LoadDone);
if (RT_FAILURE(rc))
return rc;
/*
* Statistics.
*/
if (VM_IS_RAW_MODE_ENABLED(pVM))
{
STAM_REG(pVM, &pVM->selm.s.StatRCWriteGuestGDTHandled, STAMTYPE_COUNTER, "/SELM/GC/Write/Guest/GDTInt", STAMUNIT_OCCURENCES, "The number of handled writes to the Guest GDT.");
STAM_REG(pVM, &pVM->selm.s.StatRCWriteGuestGDTUnhandled, STAMTYPE_COUNTER, "/SELM/GC/Write/Guest/GDTEmu", STAMUNIT_OCCURENCES, "The number of unhandled writes to the Guest GDT.");
STAM_REG(pVM, &pVM->selm.s.StatRCWriteGuestLDT, STAMTYPE_COUNTER, "/SELM/GC/Write/Guest/LDT", STAMUNIT_OCCURENCES, "The number of writes to the Guest LDT was detected.");
STAM_REG(pVM, &pVM->selm.s.StatRCWriteGuestTSSHandled, STAMTYPE_COUNTER, "/SELM/GC/Write/Guest/TSSInt", STAMUNIT_OCCURENCES, "The number of handled writes to the Guest TSS.");
STAM_REG(pVM, &pVM->selm.s.StatRCWriteGuestTSSRedir, STAMTYPE_COUNTER, "/SELM/GC/Write/Guest/TSSRedir",STAMUNIT_OCCURENCES, "The number of handled redir bitmap writes to the Guest TSS.");
STAM_REG(pVM, &pVM->selm.s.StatRCWriteGuestTSSHandledChanged,STAMTYPE_COUNTER, "/SELM/GC/Write/Guest/TSSIntChg", STAMUNIT_OCCURENCES, "The number of handled writes to the Guest TSS where the R0 stack changed.");
STAM_REG(pVM, &pVM->selm.s.StatRCWriteGuestTSSUnhandled, STAMTYPE_COUNTER, "/SELM/GC/Write/Guest/TSSEmu", STAMUNIT_OCCURENCES, "The number of unhandled writes to the Guest TSS.");
STAM_REG(pVM, &pVM->selm.s.StatTSSSync, STAMTYPE_PROFILE, "/PROF/SELM/TSSSync", STAMUNIT_TICKS_PER_CALL, "Profiling of the SELMR3SyncTSS() body.");
STAM_REG(pVM, &pVM->selm.s.StatUpdateFromCPUM, STAMTYPE_PROFILE, "/PROF/SELM/UpdateFromCPUM", STAMUNIT_TICKS_PER_CALL, "Profiling of the SELMR3UpdateFromCPUM() body.");
STAM_REL_REG(pVM, &pVM->selm.s.StatHyperSelsChanged, STAMTYPE_COUNTER, "/SELM/HyperSels/Changed", STAMUNIT_OCCURENCES, "The number of times we had to relocate our hypervisor selectors.");
STAM_REL_REG(pVM, &pVM->selm.s.StatScanForHyperSels, STAMTYPE_COUNTER, "/SELM/HyperSels/Scan", STAMUNIT_OCCURENCES, "The number of times we had find free hypervisor selectors.");
STAM_REL_REG(pVM, &pVM->selm.s.aStatDetectedStaleSReg[X86_SREG_ES], STAMTYPE_COUNTER, "/SELM/UpdateFromCPUM/DetectedStaleES", STAMUNIT_OCCURENCES, "Stale ES was detected in UpdateFromCPUM.");
STAM_REL_REG(pVM, &pVM->selm.s.aStatDetectedStaleSReg[X86_SREG_CS], STAMTYPE_COUNTER, "/SELM/UpdateFromCPUM/DetectedStaleCS", STAMUNIT_OCCURENCES, "Stale CS was detected in UpdateFromCPUM.");
STAM_REL_REG(pVM, &pVM->selm.s.aStatDetectedStaleSReg[X86_SREG_SS], STAMTYPE_COUNTER, "/SELM/UpdateFromCPUM/DetectedStaleSS", STAMUNIT_OCCURENCES, "Stale SS was detected in UpdateFromCPUM.");
STAM_REL_REG(pVM, &pVM->selm.s.aStatDetectedStaleSReg[X86_SREG_DS], STAMTYPE_COUNTER, "/SELM/UpdateFromCPUM/DetectedStaleDS", STAMUNIT_OCCURENCES, "Stale DS was detected in UpdateFromCPUM.");
STAM_REL_REG(pVM, &pVM->selm.s.aStatDetectedStaleSReg[X86_SREG_FS], STAMTYPE_COUNTER, "/SELM/UpdateFromCPUM/DetectedStaleFS", STAMUNIT_OCCURENCES, "Stale FS was detected in UpdateFromCPUM.");
STAM_REL_REG(pVM, &pVM->selm.s.aStatDetectedStaleSReg[X86_SREG_GS], STAMTYPE_COUNTER, "/SELM/UpdateFromCPUM/DetectedStaleGS", STAMUNIT_OCCURENCES, "Stale GS was detected in UpdateFromCPUM.");
STAM_REL_REG(pVM, &pVM->selm.s.aStatAlreadyStaleSReg[X86_SREG_ES], STAMTYPE_COUNTER, "/SELM/UpdateFromCPUM/AlreadyStaleES", STAMUNIT_OCCURENCES, "Already stale ES in UpdateFromCPUM.");
STAM_REL_REG(pVM, &pVM->selm.s.aStatAlreadyStaleSReg[X86_SREG_CS], STAMTYPE_COUNTER, "/SELM/UpdateFromCPUM/AlreadyStaleCS", STAMUNIT_OCCURENCES, "Already stale CS in UpdateFromCPUM.");
STAM_REL_REG(pVM, &pVM->selm.s.aStatAlreadyStaleSReg[X86_SREG_SS], STAMTYPE_COUNTER, "/SELM/UpdateFromCPUM/AlreadyStaleSS", STAMUNIT_OCCURENCES, "Already stale SS in UpdateFromCPUM.");
STAM_REL_REG(pVM, &pVM->selm.s.aStatAlreadyStaleSReg[X86_SREG_DS], STAMTYPE_COUNTER, "/SELM/UpdateFromCPUM/AlreadyStaleDS", STAMUNIT_OCCURENCES, "Already stale DS in UpdateFromCPUM.");
STAM_REL_REG(pVM, &pVM->selm.s.aStatAlreadyStaleSReg[X86_SREG_FS], STAMTYPE_COUNTER, "/SELM/UpdateFromCPUM/AlreadyStaleFS", STAMUNIT_OCCURENCES, "Already stale FS in UpdateFromCPUM.");
STAM_REL_REG(pVM, &pVM->selm.s.aStatAlreadyStaleSReg[X86_SREG_GS], STAMTYPE_COUNTER, "/SELM/UpdateFromCPUM/AlreadyStaleGS", STAMUNIT_OCCURENCES, "Already stale GS in UpdateFromCPUM.");
STAM_REL_REG(pVM, &pVM->selm.s.StatStaleToUnstaleSReg, STAMTYPE_COUNTER, "/SELM/UpdateFromCPUM/StaleToUnstale", STAMUNIT_OCCURENCES, "Transitions from stale to unstale UpdateFromCPUM.");
STAM_REG( pVM, &pVM->selm.s.aStatUpdatedSReg[X86_SREG_ES], STAMTYPE_COUNTER, "/SELM/UpdateFromCPUM/UpdatedES", STAMUNIT_OCCURENCES, "Updated hidden ES values in UpdateFromCPUM.");
STAM_REG( pVM, &pVM->selm.s.aStatUpdatedSReg[X86_SREG_CS], STAMTYPE_COUNTER, "/SELM/UpdateFromCPUM/UpdatedCS", STAMUNIT_OCCURENCES, "Updated hidden CS values in UpdateFromCPUM.");
STAM_REG( pVM, &pVM->selm.s.aStatUpdatedSReg[X86_SREG_SS], STAMTYPE_COUNTER, "/SELM/UpdateFromCPUM/UpdatedSS", STAMUNIT_OCCURENCES, "Updated hidden SS values in UpdateFromCPUM.");
STAM_REG( pVM, &pVM->selm.s.aStatUpdatedSReg[X86_SREG_DS], STAMTYPE_COUNTER, "/SELM/UpdateFromCPUM/UpdatedDS", STAMUNIT_OCCURENCES, "Updated hidden DS values in UpdateFromCPUM.");
STAM_REG( pVM, &pVM->selm.s.aStatUpdatedSReg[X86_SREG_FS], STAMTYPE_COUNTER, "/SELM/UpdateFromCPUM/UpdatedFS", STAMUNIT_OCCURENCES, "Updated hidden FS values in UpdateFromCPUM.");
STAM_REG( pVM, &pVM->selm.s.aStatUpdatedSReg[X86_SREG_GS], STAMTYPE_COUNTER, "/SELM/UpdateFromCPUM/UpdatedGS", STAMUNIT_OCCURENCES, "Updated hidden GS values in UpdateFromCPUM.");
}
STAM_REG( pVM, &pVM->selm.s.StatLoadHidSelGst, STAMTYPE_COUNTER, "/SELM/LoadHidSel/LoadedGuest", STAMUNIT_OCCURENCES, "SELMLoadHiddenSelectorReg: Loaded from guest tables.");
STAM_REG( pVM, &pVM->selm.s.StatLoadHidSelShw, STAMTYPE_COUNTER, "/SELM/LoadHidSel/LoadedShadow", STAMUNIT_OCCURENCES, "SELMLoadHiddenSelectorReg: Loaded from shadow tables.");
STAM_REL_REG(pVM, &pVM->selm.s.StatLoadHidSelReadErrors, STAMTYPE_COUNTER, "/SELM/LoadHidSel/GstReadErrors", STAMUNIT_OCCURENCES, "SELMLoadHiddenSelectorReg: Guest table read errors.");
STAM_REL_REG(pVM, &pVM->selm.s.StatLoadHidSelGstNoGood, STAMTYPE_COUNTER, "/SELM/LoadHidSel/NoGoodGuest", STAMUNIT_OCCURENCES, "SELMLoadHiddenSelectorReg: No good guest table entry.");
#ifdef VBOX_WITH_RAW_MODE
/*
* Default action when entering raw mode for the first time
*/
if (VM_IS_RAW_MODE_ENABLED(pVM))
{
PVMCPU pVCpu = &pVM->aCpus[0]; /* raw mode implies on VCPU */
VMCPU_FF_SET(pVCpu, VMCPU_FF_SELM_SYNC_TSS);
VMCPU_FF_SET(pVCpu, VMCPU_FF_SELM_SYNC_GDT);
VMCPU_FF_SET(pVCpu, VMCPU_FF_SELM_SYNC_LDT);
}
#endif
/*
* Register info handlers.
*/
if (VM_IS_RAW_MODE_ENABLED(pVM) || HMIsRawModeCtxNeeded(pVM))
{
DBGFR3InfoRegisterInternal(pVM, "gdt", "Displays the shadow GDT. No arguments.", &selmR3InfoGdt);
DBGFR3InfoRegisterInternal(pVM, "ldt", "Displays the shadow LDT. No arguments.", &selmR3InfoLdt);
//DBGFR3InfoRegisterInternal(pVM, "tss", "Displays the shadow TSS. No arguments.", &selmR3InfoTss);
}
DBGFR3InfoRegisterInternalEx(pVM, "gdtguest", "Displays the guest GDT. No arguments.", &selmR3InfoGdtGuest, DBGFINFO_FLAGS_RUN_ON_EMT);
DBGFR3InfoRegisterInternalEx(pVM, "ldtguest", "Displays the guest LDT. No arguments.", &selmR3InfoLdtGuest, DBGFINFO_FLAGS_RUN_ON_EMT);
//DBGFR3InfoRegisterInternal(pVM, "tssguest", "Displays the guest TSS. No arguments.", &selmR3InfoTssGuest, DBGFINFO_FLAGS_RUN_ON_EMT);
return rc;
}
/**
* Finalizes HMA page attributes.
*
* @returns VBox status code.
* @param pVM The cross context VM structure.
*/
VMMR3DECL(int) SELMR3InitFinalize(PVM pVM)
{
#ifdef VBOX_WITH_RAW_MODE
/** @cfgm{/DoubleFault,bool,false}
* Enables catching of double faults in the raw-mode context VMM code. This can
* be used when the triple faults or hangs occur and one suspect an unhandled
* double fault. This is not enabled by default because it means making the
* hyper selectors writeable for all supervisor code, including the guest's.
* The double fault is a task switch and thus requires write access to the GDT
* of the TSS (to set it busy), to the old TSS (to store state), and to the Trap
* 8 TSS for the back link.
*/
bool f;
# if defined(DEBUG_bird)
int rc = CFGMR3QueryBoolDef(CFGMR3GetRoot(pVM), "DoubleFault", &f, true);
# else
int rc = CFGMR3QueryBoolDef(CFGMR3GetRoot(pVM), "DoubleFault", &f, false);
# endif
AssertLogRelRCReturn(rc, rc);
if (f && (VM_IS_RAW_MODE_ENABLED(pVM) || HMIsRawModeCtxNeeded(pVM)))
{
PX86DESC paGdt = pVM->selm.s.paGdtR3;
rc = PGMMapSetPage(pVM, MMHyperR3ToRC(pVM, &paGdt[pVM->selm.s.aHyperSel[SELM_HYPER_SEL_TSS_TRAP08] >> 3]), sizeof(paGdt[0]),
X86_PTE_RW | X86_PTE_P | X86_PTE_A | X86_PTE_D);
AssertRC(rc);
rc = PGMMapSetPage(pVM, MMHyperR3ToRC(pVM, &paGdt[pVM->selm.s.aHyperSel[SELM_HYPER_SEL_TSS] >> 3]), sizeof(paGdt[0]),
X86_PTE_RW | X86_PTE_P | X86_PTE_A | X86_PTE_D);
AssertRC(rc);
rc = PGMMapSetPage(pVM, VM_RC_ADDR(pVM, &pVM->selm.s.aHyperSel[SELM_HYPER_SEL_TSS]), sizeof(pVM->selm.s.aHyperSel[SELM_HYPER_SEL_TSS]),
X86_PTE_RW | X86_PTE_P | X86_PTE_A | X86_PTE_D);
AssertRC(rc);
rc = PGMMapSetPage(pVM, VM_RC_ADDR(pVM, &pVM->selm.s.aHyperSel[SELM_HYPER_SEL_TSS_TRAP08]), sizeof(pVM->selm.s.aHyperSel[SELM_HYPER_SEL_TSS_TRAP08]),
X86_PTE_RW | X86_PTE_P | X86_PTE_A | X86_PTE_D);
AssertRC(rc);
}
#else /* !VBOX_WITH_RAW_MODE */
RT_NOREF(pVM);
#endif /* !VBOX_WITH_RAW_MODE */
return VINF_SUCCESS;
}
/**
* Setup the hypervisor GDT selectors in our shadow table
*
* @param pVM The cross context VM structure.
*/
static void selmR3SetupHyperGDTSelectors(PVM pVM)
{
PX86DESC paGdt = pVM->selm.s.paGdtR3;
/*
* Set up global code and data descriptors for use in the guest context.
* Both are wide open (base 0, limit 4GB)
*/
PX86DESC pDesc = &paGdt[pVM->selm.s.aHyperSel[SELM_HYPER_SEL_CS] >> 3];
pDesc->Gen.u16LimitLow = 0xffff;
pDesc->Gen.u4LimitHigh = 0xf;
pDesc->Gen.u16BaseLow = 0;
pDesc->Gen.u8BaseHigh1 = 0;
pDesc->Gen.u8BaseHigh2 = 0;
pDesc->Gen.u4Type = X86_SEL_TYPE_ER_ACC;
pDesc->Gen.u1DescType = 1; /* not system, but code/data */
pDesc->Gen.u2Dpl = 0; /* supervisor */
pDesc->Gen.u1Present = 1;
pDesc->Gen.u1Available = 0;
pDesc->Gen.u1Long = 0;
pDesc->Gen.u1DefBig = 1; /* def 32 bit */
pDesc->Gen.u1Granularity = 1; /* 4KB limit */
/* data */
pDesc = &paGdt[pVM->selm.s.aHyperSel[SELM_HYPER_SEL_DS] >> 3];
pDesc->Gen.u16LimitLow = 0xffff;
pDesc->Gen.u4LimitHigh = 0xf;
pDesc->Gen.u16BaseLow = 0;
pDesc->Gen.u8BaseHigh1 = 0;
pDesc->Gen.u8BaseHigh2 = 0;
pDesc->Gen.u4Type = X86_SEL_TYPE_RW_ACC;
pDesc->Gen.u1DescType = 1; /* not system, but code/data */
pDesc->Gen.u2Dpl = 0; /* supervisor */
pDesc->Gen.u1Present = 1;
pDesc->Gen.u1Available = 0;
pDesc->Gen.u1Long = 0;
pDesc->Gen.u1DefBig = 1; /* big */
pDesc->Gen.u1Granularity = 1; /* 4KB limit */
/* 64-bit mode code (& data?) */
pDesc = &paGdt[pVM->selm.s.aHyperSel[SELM_HYPER_SEL_CS64] >> 3];
pDesc->Gen.u16LimitLow = 0xffff;
pDesc->Gen.u4LimitHigh = 0xf;
pDesc->Gen.u16BaseLow = 0;
pDesc->Gen.u8BaseHigh1 = 0;
pDesc->Gen.u8BaseHigh2 = 0;
pDesc->Gen.u4Type = X86_SEL_TYPE_ER_ACC;
pDesc->Gen.u1DescType = 1; /* not system, but code/data */
pDesc->Gen.u2Dpl = 0; /* supervisor */
pDesc->Gen.u1Present = 1;
pDesc->Gen.u1Available = 0;
pDesc->Gen.u1Long = 1; /* The Long (L) attribute bit. */
pDesc->Gen.u1DefBig = 0; /* With L=1 this must be 0. */
pDesc->Gen.u1Granularity = 1; /* 4KB limit */
/*
* TSS descriptor
*/
pDesc = &paGdt[pVM->selm.s.aHyperSel[SELM_HYPER_SEL_TSS] >> 3];
RTRCPTR RCPtrTSS = VM_RC_ADDR(pVM, &pVM->selm.s.Tss);
pDesc->Gen.u16BaseLow = RT_LOWORD(RCPtrTSS);
pDesc->Gen.u8BaseHigh1 = RT_BYTE3(RCPtrTSS);
pDesc->Gen.u8BaseHigh2 = RT_BYTE4(RCPtrTSS);
pDesc->Gen.u16LimitLow = sizeof(VBOXTSS) - 1;
pDesc->Gen.u4LimitHigh = 0;
pDesc->Gen.u4Type = X86_SEL_TYPE_SYS_386_TSS_AVAIL;
pDesc->Gen.u1DescType = 0; /* system */
pDesc->Gen.u2Dpl = 0; /* supervisor */
pDesc->Gen.u1Present = 1;
pDesc->Gen.u1Available = 0;
pDesc->Gen.u1Long = 0;
pDesc->Gen.u1DefBig = 0;
pDesc->Gen.u1Granularity = 0; /* byte limit */
/*
* TSS descriptor for trap 08
*/
pDesc = &paGdt[pVM->selm.s.aHyperSel[SELM_HYPER_SEL_TSS_TRAP08] >> 3];
pDesc->Gen.u16LimitLow = sizeof(VBOXTSS) - 1;
pDesc->Gen.u4LimitHigh = 0;
RCPtrTSS = VM_RC_ADDR(pVM, &pVM->selm.s.TssTrap08);
pDesc->Gen.u16BaseLow = RT_LOWORD(RCPtrTSS);
pDesc->Gen.u8BaseHigh1 = RT_BYTE3(RCPtrTSS);
pDesc->Gen.u8BaseHigh2 = RT_BYTE4(RCPtrTSS);
pDesc->Gen.u4Type = X86_SEL_TYPE_SYS_386_TSS_AVAIL;
pDesc->Gen.u1DescType = 0; /* system */
pDesc->Gen.u2Dpl = 0; /* supervisor */
pDesc->Gen.u1Present = 1;
pDesc->Gen.u1Available = 0;
pDesc->Gen.u1Long = 0;
pDesc->Gen.u1DefBig = 0;
pDesc->Gen.u1Granularity = 0; /* byte limit */
}
/**
* Applies relocations to data and code managed by this
* component. This function will be called at init and
* whenever the VMM need to relocate it self inside the GC.
*
* @param pVM The cross context VM structure.
*/
VMMR3DECL(void) SELMR3Relocate(PVM pVM)
{
PX86DESC paGdt = pVM->selm.s.paGdtR3;
LogFlow(("SELMR3Relocate\n"));
if (VM_IS_RAW_MODE_ENABLED(pVM) || HMIsRawModeCtxNeeded(pVM))
{
for (VMCPUID i = 0; i < pVM->cCpus; i++)
{
PVMCPU pVCpu = &pVM->aCpus[i];
/*
* Update GDTR and selector.
*/
CPUMSetHyperGDTR(pVCpu, MMHyperR3ToRC(pVM, paGdt), SELM_GDT_ELEMENTS * sizeof(paGdt[0]) - 1);
/** @todo selector relocations should be a separate operation? */
CPUMSetHyperCS(pVCpu, pVM->selm.s.aHyperSel[SELM_HYPER_SEL_CS]);
CPUMSetHyperDS(pVCpu, pVM->selm.s.aHyperSel[SELM_HYPER_SEL_DS]);
CPUMSetHyperES(pVCpu, pVM->selm.s.aHyperSel[SELM_HYPER_SEL_DS]);
CPUMSetHyperSS(pVCpu, pVM->selm.s.aHyperSel[SELM_HYPER_SEL_DS]);
CPUMSetHyperTR(pVCpu, pVM->selm.s.aHyperSel[SELM_HYPER_SEL_TSS]);
}
selmR3SetupHyperGDTSelectors(pVM);
/** @todo SELM must be called when any of the CR3s changes during a cpu mode change. */
/** @todo PGM knows the proper CR3 values these days, not CPUM. */
/*
* Update the TSSes.
*/
/* Only applies to raw mode which supports only 1 VCPU */
PVMCPU pVCpu = &pVM->aCpus[0];
/* Current TSS */
pVM->selm.s.Tss.cr3 = PGMGetHyperCR3(pVCpu);
pVM->selm.s.Tss.ss0 = pVM->selm.s.aHyperSel[SELM_HYPER_SEL_DS];
pVM->selm.s.Tss.esp0 = VMMGetStackRC(pVCpu);
pVM->selm.s.Tss.cs = pVM->selm.s.aHyperSel[SELM_HYPER_SEL_CS];
pVM->selm.s.Tss.ds = pVM->selm.s.aHyperSel[SELM_HYPER_SEL_DS];
pVM->selm.s.Tss.es = pVM->selm.s.aHyperSel[SELM_HYPER_SEL_DS];
pVM->selm.s.Tss.offIoBitmap = sizeof(VBOXTSS);
/* trap 08 */
pVM->selm.s.TssTrap08.cr3 = PGMGetInterRCCR3(pVM, pVCpu); /* this should give use better survival chances. */
pVM->selm.s.TssTrap08.ss0 = pVM->selm.s.aHyperSel[SELM_HYPER_SEL_DS];
pVM->selm.s.TssTrap08.ss = pVM->selm.s.aHyperSel[SELM_HYPER_SEL_DS];
pVM->selm.s.TssTrap08.esp0 = VMMGetStackRC(pVCpu) - PAGE_SIZE / 2; /* upper half can be analysed this way. */
pVM->selm.s.TssTrap08.esp = pVM->selm.s.TssTrap08.esp0;
pVM->selm.s.TssTrap08.ebp = pVM->selm.s.TssTrap08.esp0;
pVM->selm.s.TssTrap08.cs = pVM->selm.s.aHyperSel[SELM_HYPER_SEL_CS];
pVM->selm.s.TssTrap08.ds = pVM->selm.s.aHyperSel[SELM_HYPER_SEL_DS];
pVM->selm.s.TssTrap08.es = pVM->selm.s.aHyperSel[SELM_HYPER_SEL_DS];
pVM->selm.s.TssTrap08.fs = 0;
pVM->selm.s.TssTrap08.gs = 0;
pVM->selm.s.TssTrap08.selLdt = 0;
pVM->selm.s.TssTrap08.eflags = 0x2; /* all cleared */
pVM->selm.s.TssTrap08.ecx = VM_RC_ADDR(pVM, &pVM->selm.s.Tss); /* setup ecx to normal Hypervisor TSS address. */
pVM->selm.s.TssTrap08.edi = pVM->selm.s.TssTrap08.ecx;
pVM->selm.s.TssTrap08.eax = pVM->selm.s.TssTrap08.ecx;
pVM->selm.s.TssTrap08.edx = VM_RC_ADDR(pVM, pVM); /* setup edx VM address. */
pVM->selm.s.TssTrap08.edi = pVM->selm.s.TssTrap08.edx;
pVM->selm.s.TssTrap08.ebx = pVM->selm.s.TssTrap08.edx;
pVM->selm.s.TssTrap08.offIoBitmap = sizeof(VBOXTSS);
/* TRPM will be updating the eip */
}
if (VM_IS_RAW_MODE_ENABLED(pVM))
{
/*
* Update shadow GDT/LDT/TSS write access handlers.
*/
PVMCPU pVCpu = VMMGetCpu(pVM); NOREF(pVCpu);
int rc; NOREF(rc);
#ifdef SELM_TRACK_SHADOW_GDT_CHANGES
if (pVM->selm.s.paGdtRC != NIL_RTRCPTR)
{
rc = PGMHandlerVirtualDeregister(pVM, pVCpu, pVM->selm.s.paGdtRC, true /*fHypervisor*/);
AssertRC(rc);
}
pVM->selm.s.paGdtRC = MMHyperR3ToRC(pVM, paGdt);
rc = PGMR3HandlerVirtualRegister(pVM, pVCpu, pVM->selm.s.hShadowGdtWriteHandlerType,
pVM->selm.s.paGdtRC,
pVM->selm.s.paGdtRC + SELM_GDT_ELEMENTS * sizeof(paGdt[0]) - 1,
NULL /*pvUserR3*/, NIL_RTR0PTR /*pvUserRC*/, NULL /*pszDesc*/);
AssertRC(rc);
#endif
#ifdef SELM_TRACK_SHADOW_TSS_CHANGES
if (pVM->selm.s.pvMonShwTssRC != RTRCPTR_MAX)
{
rc = PGMHandlerVirtualDeregister(pVM, pVCpu, pVM->selm.s.pvMonShwTssRC, true /*fHypervisor*/);
AssertRC(rc);
}
pVM->selm.s.pvMonShwTssRC = VM_RC_ADDR(pVM, &pVM->selm.s.Tss);
rc = PGMR3HandlerVirtualRegister(pVM, pVCpu, pVM->selm.s.hShadowTssWriteHandlerType,
pVM->selm.s.pvMonShwTssRC,
pVM->selm.s.pvMonShwTssRC + sizeof(pVM->selm.s.Tss) - 1,
NULL /*pvUserR3*/, NIL_RTR0PTR /*pvUserRC*/, NULL /*pszDesc*/);
AssertRC(rc);
#endif
/*
* Update the GC LDT region handler and address.
*/
#ifdef SELM_TRACK_SHADOW_LDT_CHANGES
if (pVM->selm.s.pvLdtRC != RTRCPTR_MAX)
{
rc = PGMHandlerVirtualDeregister(pVM, pVCpu, pVM->selm.s.pvLdtRC, true /*fHypervisor*/);
AssertRC(rc);
}
#endif
pVM->selm.s.pvLdtRC = MMHyperR3ToRC(pVM, pVM->selm.s.pvLdtR3);
#ifdef SELM_TRACK_SHADOW_LDT_CHANGES
rc = PGMR3HandlerVirtualRegister(pVM, pVCpu, pVM->selm.s.hShadowLdtWriteHandlerType,
pVM->selm.s.pvLdtRC,
pVM->selm.s.pvLdtRC + _64K + PAGE_SIZE - 1,
NULL /*pvUserR3*/, NIL_RTR0PTR /*pvUserRC*/, NULL /*pszDesc*/);
AssertRC(rc);
#endif
}
}
/**
* Terminates the SELM.
*
* Termination means cleaning up and freeing all resources,
* the VM it self is at this point powered off or suspended.
*
* @returns VBox status code.
* @param pVM The cross context VM structure.
*/
VMMR3DECL(int) SELMR3Term(PVM pVM)
{
NOREF(pVM);
return VINF_SUCCESS;
}
/**
* The VM is being reset.
*
* For the SELM component this means that any GDT/LDT/TSS monitors
* needs to be removed.
*
* @param pVM The cross context VM structure.
*/
VMMR3DECL(void) SELMR3Reset(PVM pVM)
{
LogFlow(("SELMR3Reset:\n"));
VM_ASSERT_EMT(pVM);
/*
* Uninstall guest GDT/LDT/TSS write access handlers.
*/
PVMCPU pVCpu = VMMGetCpu(pVM); NOREF(pVCpu);
if (pVM->selm.s.GuestGdtr.pGdt != RTRCPTR_MAX && pVM->selm.s.fGDTRangeRegistered)
{
#ifdef SELM_TRACK_GUEST_GDT_CHANGES
int rc = PGMHandlerVirtualDeregister(pVM, pVCpu, pVM->selm.s.GuestGdtr.pGdt, false /*fHypervisor*/);
AssertRC(rc);
#endif
pVM->selm.s.GuestGdtr.pGdt = RTRCPTR_MAX;
pVM->selm.s.GuestGdtr.cbGdt = 0;
}
pVM->selm.s.fGDTRangeRegistered = false;
if (pVM->selm.s.GCPtrGuestLdt != RTRCPTR_MAX)
{
#ifdef SELM_TRACK_GUEST_LDT_CHANGES
int rc = PGMHandlerVirtualDeregister(pVM, pVCpu, pVM->selm.s.GCPtrGuestLdt, false /*fHypervisor*/);
AssertRC(rc);
#endif
pVM->selm.s.GCPtrGuestLdt = RTRCPTR_MAX;
}
if (pVM->selm.s.GCPtrGuestTss != RTRCPTR_MAX)
{
#ifdef SELM_TRACK_GUEST_TSS_CHANGES
int rc = PGMHandlerVirtualDeregister(pVM, pVCpu, pVM->selm.s.GCPtrGuestTss, false /*fHypervisor*/);
AssertRC(rc);
#endif
pVM->selm.s.GCPtrGuestTss = RTRCPTR_MAX;
pVM->selm.s.GCSelTss = RTSEL_MAX;
}
/*
* Re-initialize other members.
*/
pVM->selm.s.cbLdtLimit = 0;
pVM->selm.s.offLdtHyper = 0;
pVM->selm.s.cbMonitoredGuestTss = 0;
pVM->selm.s.fSyncTSSRing0Stack = false;
#ifdef VBOX_WITH_RAW_MODE
if (VM_IS_RAW_MODE_ENABLED(pVM))
{
/*
* Default action when entering raw mode for the first time
*/
VMCPU_FF_SET(pVCpu, VMCPU_FF_SELM_SYNC_TSS);
VMCPU_FF_SET(pVCpu, VMCPU_FF_SELM_SYNC_GDT);
VMCPU_FF_SET(pVCpu, VMCPU_FF_SELM_SYNC_LDT);
}
#endif
}
/**
* Execute state save operation.
*
* @returns VBox status code.
* @param pVM The cross context VM structure.
* @param pSSM SSM operation handle.
*/
static DECLCALLBACK(int) selmR3Save(PVM pVM, PSSMHANDLE pSSM)
{
LogFlow(("selmR3Save:\n"));
/*
* Save the basic bits - fortunately all the other things can be resynced on load.
*/
PSELM pSelm = &pVM->selm.s;
SSMR3PutBool(pSSM, !VM_IS_RAW_MODE_ENABLED(pVM));
SSMR3PutBool(pSSM, pSelm->fSyncTSSRing0Stack);
SSMR3PutSel(pSSM, pSelm->aHyperSel[SELM_HYPER_SEL_CS]);
SSMR3PutSel(pSSM, pSelm->aHyperSel[SELM_HYPER_SEL_DS]);
SSMR3PutSel(pSSM, pSelm->aHyperSel[SELM_HYPER_SEL_CS64]);
SSMR3PutSel(pSSM, pSelm->aHyperSel[SELM_HYPER_SEL_CS64]); /* reserved for DS64. */
SSMR3PutSel(pSSM, pSelm->aHyperSel[SELM_HYPER_SEL_TSS]);
return SSMR3PutSel(pSSM, pSelm->aHyperSel[SELM_HYPER_SEL_TSS_TRAP08]);
}
/**
* Execute state load operation.
*
* @returns VBox status code.
* @param pVM The cross context VM structure.
* @param pSSM SSM operation handle.
* @param uVersion Data layout version.
* @param uPass The data pass.
*/
static DECLCALLBACK(int) selmR3Load(PVM pVM, PSSMHANDLE pSSM, uint32_t uVersion, uint32_t uPass)
{
LogFlow(("selmR3Load:\n"));
Assert(uPass == SSM_PASS_FINAL); NOREF(uPass);
/*
* Validate version.
*/
if (uVersion != SELM_SAVED_STATE_VERSION)
{
AssertMsgFailed(("selmR3Load: Invalid version uVersion=%d!\n", uVersion));
return VERR_SSM_UNSUPPORTED_DATA_UNIT_VERSION;
}
/*
* Do a reset.
*/
SELMR3Reset(pVM);
/* Get the monitoring flag. */
bool fIgnored;
SSMR3GetBool(pSSM, &fIgnored);
/* Get the TSS state flag. */
SSMR3GetBool(pSSM, &pVM->selm.s.fSyncTSSRing0Stack);
/*
* Get the selectors.
*/
RTSEL SelCS;
SSMR3GetSel(pSSM, &SelCS);
RTSEL SelDS;
SSMR3GetSel(pSSM, &SelDS);
RTSEL SelCS64;
SSMR3GetSel(pSSM, &SelCS64);
RTSEL SelDS64;
SSMR3GetSel(pSSM, &SelDS64);
RTSEL SelTSS;
SSMR3GetSel(pSSM, &SelTSS);
RTSEL SelTSSTrap08;
SSMR3GetSel(pSSM, &SelTSSTrap08);
/* Copy the selectors; they will be checked during relocation. */
PSELM pSelm = &pVM->selm.s;
pSelm->aHyperSel[SELM_HYPER_SEL_CS] = SelCS;
pSelm->aHyperSel[SELM_HYPER_SEL_DS] = SelDS;
pSelm->aHyperSel[SELM_HYPER_SEL_CS64] = SelCS64;
pSelm->aHyperSel[SELM_HYPER_SEL_TSS] = SelTSS;
pSelm->aHyperSel[SELM_HYPER_SEL_TSS_TRAP08] = SelTSSTrap08;
return VINF_SUCCESS;
}
/**
* Sync the GDT, LDT and TSS after loading the state.
*
* Just to play save, we set the FFs to force syncing before
* executing GC code.
*
* @returns VBox status code.
* @param pVM The cross context VM structure.
* @param pSSM SSM operation handle.
*/
static DECLCALLBACK(int) selmR3LoadDone(PVM pVM, PSSMHANDLE pSSM)
{
#ifdef VBOX_WITH_RAW_MODE
if (VM_IS_RAW_MODE_ENABLED(pVM))
{
PVMCPU pVCpu = VMMGetCpu(pVM);
LogFlow(("selmR3LoadDone:\n"));
/*
* Don't do anything if it's a load failure.
*/
int rc = SSMR3HandleGetStatus(pSSM);
if (RT_FAILURE(rc))
return VINF_SUCCESS;
/*
* Do the syncing if we're in protected mode and using raw-mode.
*/
if (PGMGetGuestMode(pVCpu) != PGMMODE_REAL)
{
VMCPU_FF_SET(pVCpu, VMCPU_FF_SELM_SYNC_GDT);
VMCPU_FF_SET(pVCpu, VMCPU_FF_SELM_SYNC_LDT);
VMCPU_FF_SET(pVCpu, VMCPU_FF_SELM_SYNC_TSS);
SELMR3UpdateFromCPUM(pVM, pVCpu);
}
/*
* Flag everything for resync on next raw mode entry.
*/
VMCPU_FF_SET(pVCpu, VMCPU_FF_SELM_SYNC_GDT);
VMCPU_FF_SET(pVCpu, VMCPU_FF_SELM_SYNC_LDT);
VMCPU_FF_SET(pVCpu, VMCPU_FF_SELM_SYNC_TSS);
}
#else /* !VBOX_WITH_RAW_MODE */
RT_NOREF(pVM, pSSM);
#endif /* !VBOX_WITH_RAW_MODE */
return VINF_SUCCESS;
}
#ifdef VBOX_WITH_RAW_MODE
/**
* Updates (syncs) the shadow GDT.
*
* @returns VBox status code.
* @param pVM The cross context VM structure.
* @param pVCpu The cross context virtual CPU structure of the calling EMT.
*/
static int selmR3UpdateShadowGdt(PVM pVM, PVMCPU pVCpu)
{
LogFlow(("selmR3UpdateShadowGdt\n"));
Assert(VM_IS_RAW_MODE_ENABLED(pVM));
/*
* Always assume the best...
*/
VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_SELM_SYNC_GDT);
/* If the GDT was changed, then make sure the LDT is checked too */
/** @todo only do this if the actual ldtr selector was changed; this is a bit excessive */
VMCPU_FF_SET(pVCpu, VMCPU_FF_SELM_SYNC_LDT);
/* Same goes for the TSS selector */
VMCPU_FF_SET(pVCpu, VMCPU_FF_SELM_SYNC_TSS);
/*
* Get the GDTR and check if there is anything to do (there usually is).
*/
VBOXGDTR GDTR;
CPUMGetGuestGDTR(pVCpu, &GDTR);
if (GDTR.cbGdt < sizeof(X86DESC))
{
Log(("No GDT entries...\n"));
return VINF_SUCCESS;
}
/*
* Read the Guest GDT.
* ASSUMES that the entire GDT is in memory.
*/
RTUINT cbEffLimit = GDTR.cbGdt;
PX86DESC pGDTE = &pVM->selm.s.paGdtR3[1];
int rc = PGMPhysSimpleReadGCPtr(pVCpu, pGDTE, GDTR.pGdt + sizeof(X86DESC), cbEffLimit + 1 - sizeof(X86DESC));
if (RT_FAILURE(rc))
{
/*
* Read it page by page.
*
* Keep track of the last valid page and delay memsets and
* adjust cbEffLimit to reflect the effective size. The latter
* is something we do in the belief that the guest will probably
* never actually commit the last page, thus allowing us to keep
* our selectors in the high end of the GDT.
*/
RTUINT cbLeft = cbEffLimit + 1 - sizeof(X86DESC);
RTGCPTR GCPtrSrc = (RTGCPTR)GDTR.pGdt + sizeof(X86DESC);
uint8_t *pu8Dst = (uint8_t *)&pVM->selm.s.paGdtR3[1];
uint8_t *pu8DstInvalid = pu8Dst;
while (cbLeft)
{
RTUINT cb = PAGE_SIZE - (GCPtrSrc & PAGE_OFFSET_MASK);
cb = RT_MIN(cb, cbLeft);
rc = PGMPhysSimpleReadGCPtr(pVCpu, pu8Dst, GCPtrSrc, cb);
if (RT_SUCCESS(rc))
{
if (pu8DstInvalid != pu8Dst)
RT_BZERO(pu8DstInvalid, pu8Dst - pu8DstInvalid);
GCPtrSrc += cb;
pu8Dst += cb;
pu8DstInvalid = pu8Dst;
}
else if ( rc == VERR_PAGE_NOT_PRESENT
|| rc == VERR_PAGE_TABLE_NOT_PRESENT)
{
GCPtrSrc += cb;
pu8Dst += cb;
}
else
{
AssertLogRelMsgFailed(("Couldn't read GDT at %016RX64, rc=%Rrc!\n", GDTR.pGdt, rc));
return VERR_SELM_GDT_READ_ERROR;
}
cbLeft -= cb;
}
/* any invalid pages at the end? */
if (pu8DstInvalid != pu8Dst)
{
cbEffLimit = pu8DstInvalid - (uint8_t *)pVM->selm.s.paGdtR3 - 1;
/* If any GDTEs was invalidated, zero them. */
if (cbEffLimit < pVM->selm.s.cbEffGuestGdtLimit)
RT_BZERO(pu8DstInvalid + cbEffLimit + 1, pVM->selm.s.cbEffGuestGdtLimit - cbEffLimit);
}
/* keep track of the effective limit. */
if (cbEffLimit != pVM->selm.s.cbEffGuestGdtLimit)
{
Log(("SELMR3UpdateFromCPUM: cbEffGuestGdtLimit=%#x -> %#x (actual %#x)\n",
pVM->selm.s.cbEffGuestGdtLimit, cbEffLimit, GDTR.cbGdt));
pVM->selm.s.cbEffGuestGdtLimit = cbEffLimit;
}
}
/*
* Check if the Guest GDT intrudes on our GDT entries.
*/
/** @todo we should try to minimize relocations by making sure our current selectors can be reused. */
RTSEL aHyperSel[SELM_HYPER_SEL_MAX];
if (cbEffLimit >= SELM_HYPER_DEFAULT_BASE)
{
PX86DESC pGDTEStart = pVM->selm.s.paGdtR3;
PX86DESC pGDTECur = (PX86DESC)((char *)pGDTEStart + GDTR.cbGdt + 1 - sizeof(X86DESC));
int iGDT = 0;
Log(("Internal SELM GDT conflict: use non-present entries\n"));
STAM_REL_COUNTER_INC(&pVM->selm.s.StatScanForHyperSels);
while ((uintptr_t)pGDTECur > (uintptr_t)pGDTEStart)
{
/* We can reuse non-present entries */
if (!pGDTECur->Gen.u1Present)
{
aHyperSel[iGDT] = ((uintptr_t)pGDTECur - (uintptr_t)pVM->selm.s.paGdtR3) / sizeof(X86DESC);
aHyperSel[iGDT] = aHyperSel[iGDT] << X86_SEL_SHIFT;
Log(("SELM: Found unused GDT %04X\n", aHyperSel[iGDT]));
iGDT++;
if (iGDT >= SELM_HYPER_SEL_MAX)
break;
}
pGDTECur--;
}
if (iGDT != SELM_HYPER_SEL_MAX)
{
AssertLogRelMsgFailed(("Internal SELM GDT conflict.\n"));
return VERR_SELM_GDT_TOO_FULL;
}
}
else
{
aHyperSel[SELM_HYPER_SEL_CS] = SELM_HYPER_DEFAULT_SEL_CS;
aHyperSel[SELM_HYPER_SEL_DS] = SELM_HYPER_DEFAULT_SEL_DS;
aHyperSel[SELM_HYPER_SEL_CS64] = SELM_HYPER_DEFAULT_SEL_CS64;
aHyperSel[SELM_HYPER_SEL_TSS] = SELM_HYPER_DEFAULT_SEL_TSS;
aHyperSel[SELM_HYPER_SEL_TSS_TRAP08] = SELM_HYPER_DEFAULT_SEL_TSS_TRAP08;
}
# ifdef VBOX_WITH_SAFE_STR
/* Use the guest's TR selector to plug the str virtualization hole. */
if (CPUMGetGuestTR(pVCpu, NULL) != 0)
{
Log(("SELM: Use guest TSS selector %x\n", CPUMGetGuestTR(pVCpu, NULL)));
aHyperSel[SELM_HYPER_SEL_TSS] = CPUMGetGuestTR(pVCpu, NULL);
}
# endif
/*
* Work thru the copied GDT entries adjusting them for correct virtualization.
*/
PX86DESC pGDTEEnd = (PX86DESC)((char *)pGDTE + cbEffLimit + 1 - sizeof(X86DESC));
while (pGDTE < pGDTEEnd)
{
if (pGDTE->Gen.u1Present)
selmGuestToShadowDesc(pVM, pGDTE);
/* Next GDT entry. */
pGDTE++;
}
/*
* Check if our hypervisor selectors were changed.
*/
if ( aHyperSel[SELM_HYPER_SEL_CS] != pVM->selm.s.aHyperSel[SELM_HYPER_SEL_CS]
|| aHyperSel[SELM_HYPER_SEL_DS] != pVM->selm.s.aHyperSel[SELM_HYPER_SEL_DS]
|| aHyperSel[SELM_HYPER_SEL_CS64] != pVM->selm.s.aHyperSel[SELM_HYPER_SEL_CS64]
|| aHyperSel[SELM_HYPER_SEL_TSS] != pVM->selm.s.aHyperSel[SELM_HYPER_SEL_TSS]
|| aHyperSel[SELM_HYPER_SEL_TSS_TRAP08] != pVM->selm.s.aHyperSel[SELM_HYPER_SEL_TSS_TRAP08])
{
/* Reinitialize our hypervisor GDTs */
pVM->selm.s.aHyperSel[SELM_HYPER_SEL_CS] = aHyperSel[SELM_HYPER_SEL_CS];
pVM->selm.s.aHyperSel[SELM_HYPER_SEL_DS] = aHyperSel[SELM_HYPER_SEL_DS];
pVM->selm.s.aHyperSel[SELM_HYPER_SEL_CS64] = aHyperSel[SELM_HYPER_SEL_CS64];
pVM->selm.s.aHyperSel[SELM_HYPER_SEL_TSS] = aHyperSel[SELM_HYPER_SEL_TSS];
pVM->selm.s.aHyperSel[SELM_HYPER_SEL_TSS_TRAP08] = aHyperSel[SELM_HYPER_SEL_TSS_TRAP08];
STAM_REL_COUNTER_INC(&pVM->selm.s.StatHyperSelsChanged);
/*
* Do the relocation callbacks to let everyone update their hyper selector dependencies.
* (SELMR3Relocate will call selmR3SetupHyperGDTSelectors() for us.)
*/
VMR3Relocate(pVM, 0);
}
# ifdef VBOX_WITH_SAFE_STR
else if ( cbEffLimit >= SELM_HYPER_DEFAULT_BASE
|| CPUMGetGuestTR(pVCpu, NULL) != 0) /* Our shadow TR entry was overwritten when we synced the guest's GDT. */
# else
else if (cbEffLimit >= SELM_HYPER_DEFAULT_BASE)
# endif
/* We overwrote all entries above, so we have to save them again. */
selmR3SetupHyperGDTSelectors(pVM);
/*
* Adjust the cached GDT limit.
* Any GDT entries which have been removed must be cleared.
*/
if (pVM->selm.s.GuestGdtr.cbGdt != GDTR.cbGdt)
{
if (pVM->selm.s.GuestGdtr.cbGdt > GDTR.cbGdt)
RT_BZERO(pGDTE, pVM->selm.s.GuestGdtr.cbGdt - GDTR.cbGdt);
}
/*
* Check if Guest's GDTR is changed.
*/
if ( GDTR.pGdt != pVM->selm.s.GuestGdtr.pGdt
|| GDTR.cbGdt != pVM->selm.s.GuestGdtr.cbGdt)
{
Log(("SELMR3UpdateFromCPUM: Guest's GDT is changed to pGdt=%016RX64 cbGdt=%08X\n", GDTR.pGdt, GDTR.cbGdt));
# ifdef SELM_TRACK_GUEST_GDT_CHANGES
/*
* [Re]Register write virtual handler for guest's GDT.
*/
if (pVM->selm.s.GuestGdtr.pGdt != RTRCPTR_MAX && pVM->selm.s.fGDTRangeRegistered)
{
rc = PGMHandlerVirtualDeregister(pVM, pVCpu, pVM->selm.s.GuestGdtr.pGdt, false /*fHypervisor*/);
AssertRC(rc);
}
rc = PGMR3HandlerVirtualRegister(pVM, pVCpu, pVM->selm.s.hGuestGdtWriteHandlerType,
GDTR.pGdt, GDTR.pGdt + GDTR.cbGdt /* already inclusive */,
NULL /*pvUserR3*/, NIL_RTR0PTR /*pvUserRC*/, NULL /*pszDesc*/);
# ifdef VBOX_WITH_RAW_RING1
/** @todo !HACK ALERT!
* Some guest OSes (QNX) share code and the GDT on the same page;
* PGMR3HandlerVirtualRegister doesn't support more than one handler,
* so we kick out the PATM handler as this one is more important. Fix this
* properly in PGMR3HandlerVirtualRegister?
*/
if (rc == VERR_PGM_HANDLER_VIRTUAL_CONFLICT)
{
LogRel(("selmR3UpdateShadowGdt: Virtual handler conflict %RGv -> kick out PATM handler for the higher priority GDT page monitor\n", GDTR.pGdt));
rc = PGMHandlerVirtualDeregister(pVM, pVCpu, GDTR.pGdt & PAGE_BASE_GC_MASK, false /*fHypervisor*/);
AssertRC(rc);
rc = PGMR3HandlerVirtualRegister(pVM, pVCpu, pVM->selm.s.hGuestGdtWriteHandlerType,
GDTR.pGdt, GDTR.pGdt + GDTR.cbGdt /* already inclusive */,
NULL /*pvUserR3*/, NIL_RTR0PTR /*pvUserRC*/, NULL /*pszDesc*/);
}
# endif
if (RT_FAILURE(rc))
return rc;
# endif /* SELM_TRACK_GUEST_GDT_CHANGES */
/* Update saved Guest GDTR. */
pVM->selm.s.GuestGdtr = GDTR;
pVM->selm.s.fGDTRangeRegistered = true;
}
return VINF_SUCCESS;
}
/**
* Updates (syncs) the shadow LDT.
*
* @returns VBox status code.
* @param pVM The cross context VM structure.
* @param pVCpu The cross context virtual CPU structure of the calling EMT.
*/
static int selmR3UpdateShadowLdt(PVM pVM, PVMCPU pVCpu)
{
LogFlow(("selmR3UpdateShadowLdt\n"));
int rc = VINF_SUCCESS;
Assert(VM_IS_RAW_MODE_ENABLED(pVM));
/*
* Always assume the best...
*/
VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_SELM_SYNC_LDT);
/*
* LDT handling is done similarly to the GDT handling with a shadow
* array. However, since the LDT is expected to be swappable (at least
* some ancient OSes makes it swappable) it must be floating and
* synced on a per-page basis.
*
* Eventually we will change this to be fully on demand. Meaning that
* we will only sync pages containing LDT selectors actually used and
* let the #PF handler lazily sync pages as they are used.
* (This applies to GDT too, when we start making OS/2 fast.)
*/
/*
* First, determine the current LDT selector.
*/
RTSEL SelLdt = CPUMGetGuestLDTR(pVCpu);
if (!(SelLdt & X86_SEL_MASK_OFF_RPL))
{
/* ldtr = 0 - update hyper LDTR and deregister any active handler. */
CPUMSetHyperLDTR(pVCpu, 0);
if (pVM->selm.s.GCPtrGuestLdt != RTRCPTR_MAX)
{
rc = PGMHandlerVirtualDeregister(pVM, pVCpu, pVM->selm.s.GCPtrGuestLdt, false /*fHypervisor*/);
AssertRC(rc);
pVM->selm.s.GCPtrGuestLdt = RTRCPTR_MAX;
}
pVM->selm.s.cbLdtLimit = 0;
return VINF_SUCCESS;
}
/*
* Get the LDT selector.
*/
/** @todo this is wrong, use CPUMGetGuestLdtrEx */
PX86DESC pDesc = &pVM->selm.s.paGdtR3[SelLdt >> X86_SEL_SHIFT];
RTGCPTR GCPtrLdt = X86DESC_BASE(pDesc);
uint32_t cbLdt = X86DESC_LIMIT_G(pDesc);
/*
* Validate it.
*/
if ( !cbLdt
|| SelLdt >= pVM->selm.s.GuestGdtr.cbGdt
|| pDesc->Gen.u1DescType
|| pDesc->Gen.u4Type != X86_SEL_TYPE_SYS_LDT)
{
AssertMsg(!cbLdt, ("Invalid LDT %04x!\n", SelLdt));
/* cbLdt > 0:
* This is quite impossible, so we do as most people do when faced with
* the impossible, we simply ignore it.
*/
CPUMSetHyperLDTR(pVCpu, 0);
if (pVM->selm.s.GCPtrGuestLdt != RTRCPTR_MAX)
{
rc = PGMHandlerVirtualDeregister(pVM, pVCpu, pVM->selm.s.GCPtrGuestLdt, false /*fHypervisor*/);
AssertRC(rc);
pVM->selm.s.GCPtrGuestLdt = RTRCPTR_MAX;
}
return VINF_SUCCESS;
}
/** @todo check what intel does about odd limits. */
AssertMsg(RT_ALIGN(cbLdt + 1, sizeof(X86DESC)) == cbLdt + 1 && cbLdt <= 0xffff, ("cbLdt=%d\n", cbLdt));
/*
* Use the cached guest ldt address if the descriptor has already been modified (see below)
* (this is necessary due to redundant LDT updates; see todo above at GDT sync)
*/
if (MMHyperIsInsideArea(pVM, GCPtrLdt))
GCPtrLdt = pVM->selm.s.GCPtrGuestLdt; /* use the old one */
/** @todo Handle only present LDT segments. */
// if (pDesc->Gen.u1Present)
{
/*
* Check if Guest's LDT address/limit is changed.
*/
if ( GCPtrLdt != pVM->selm.s.GCPtrGuestLdt
|| cbLdt != pVM->selm.s.cbLdtLimit)
{
Log(("SELMR3UpdateFromCPUM: Guest LDT changed to from %RGv:%04x to %RGv:%04x. (GDTR=%016RX64:%04x)\n",
pVM->selm.s.GCPtrGuestLdt, pVM->selm.s.cbLdtLimit, GCPtrLdt, cbLdt, pVM->selm.s.GuestGdtr.pGdt, pVM->selm.s.GuestGdtr.cbGdt));
# ifdef SELM_TRACK_GUEST_LDT_CHANGES
/*
* [Re]Register write virtual handler for guest's GDT.
* In the event of LDT overlapping something, don't install it just assume it's being updated.
*/
if (pVM->selm.s.GCPtrGuestLdt != RTRCPTR_MAX)
{
rc = PGMHandlerVirtualDeregister(pVM, pVCpu, pVM->selm.s.GCPtrGuestLdt, false /*fHypervisor*/);
AssertRC(rc);
}
# ifdef LOG_ENABLED
if (pDesc->Gen.u1Present)
Log(("LDT selector marked not present!!\n"));
# endif
rc = PGMR3HandlerVirtualRegister(pVM, pVCpu, pVM->selm.s.hGuestLdtWriteHandlerType,
GCPtrLdt, GCPtrLdt + cbLdt /* already inclusive */,
NULL /*pvUserR3*/, NIL_RTR0PTR /*pvUserRC*/, NULL /*pszDesc*/);
if (rc == VERR_PGM_HANDLER_VIRTUAL_CONFLICT)
{
/** @todo investigate the various cases where conflicts happen and try avoid them by enh. the instruction emulation. */
pVM->selm.s.GCPtrGuestLdt = RTRCPTR_MAX;
Log(("WARNING: Guest LDT (%RGv:%04x) conflicted with existing access range!! Assumes LDT is begin updated. (GDTR=%016RX64:%04x)\n",
GCPtrLdt, cbLdt, pVM->selm.s.GuestGdtr.pGdt, pVM->selm.s.GuestGdtr.cbGdt));
}
else if (RT_SUCCESS(rc))
pVM->selm.s.GCPtrGuestLdt = GCPtrLdt;
else
{
CPUMSetHyperLDTR(pVCpu, 0);
return rc;
}
# else
pVM->selm.s.GCPtrGuestLdt = GCPtrLdt;
# endif
pVM->selm.s.cbLdtLimit = cbLdt;
}
}
/*
* Calc Shadow LDT base.
*/
unsigned off;
pVM->selm.s.offLdtHyper = off = (GCPtrLdt & PAGE_OFFSET_MASK);
RTGCPTR GCPtrShadowLDT = (RTGCPTR)((RTGCUINTPTR)pVM->selm.s.pvLdtRC + off);
PX86DESC pShadowLDT = (PX86DESC)((uintptr_t)pVM->selm.s.pvLdtR3 + off);
/*
* Enable the LDT selector in the shadow GDT.
*/
pDesc->Gen.u1Present = 1;
pDesc->Gen.u16BaseLow = RT_LOWORD(GCPtrShadowLDT);
pDesc->Gen.u8BaseHigh1 = RT_BYTE3(GCPtrShadowLDT);
pDesc->Gen.u8BaseHigh2 = RT_BYTE4(GCPtrShadowLDT);
pDesc->Gen.u1Available = 0;
pDesc->Gen.u1Long = 0;
if (cbLdt > 0xffff)
{
cbLdt = 0xffff;
pDesc->Gen.u4LimitHigh = 0;
pDesc->Gen.u16LimitLow = pDesc->Gen.u1Granularity ? 0xf : 0xffff;
}
/*
* Set Hyper LDTR and notify TRPM.
*/
CPUMSetHyperLDTR(pVCpu, SelLdt);
LogFlow(("selmR3UpdateShadowLdt: Hyper LDTR %#x\n", SelLdt));
/*
* Loop synchronising the LDT page by page.
*/
/** @todo investigate how intel handle various operations on half present cross page entries. */
off = GCPtrLdt & (sizeof(X86DESC) - 1);
AssertMsg(!off, ("LDT is not aligned on entry size! GCPtrLdt=%08x\n", GCPtrLdt));
/* Note: Do not skip the first selector; unlike the GDT, a zero LDT selector is perfectly valid. */
unsigned cbLeft = cbLdt + 1;
PX86DESC pLDTE = pShadowLDT;
while (cbLeft)
{
/*
* Read a chunk.
*/
unsigned cbChunk = PAGE_SIZE - ((RTGCUINTPTR)GCPtrLdt & PAGE_OFFSET_MASK);
if (cbChunk > cbLeft)
cbChunk = cbLeft;
rc = PGMPhysSimpleReadGCPtr(pVCpu, pShadowLDT, GCPtrLdt, cbChunk);
if (RT_SUCCESS(rc))
{
/*
* Mark page
*/
rc = PGMMapSetPage(pVM, GCPtrShadowLDT & PAGE_BASE_GC_MASK, PAGE_SIZE, X86_PTE_P | X86_PTE_A | X86_PTE_D);
AssertRC(rc);
/*
* Loop thru the available LDT entries.
* Figure out where to start and end and the potential cross pageness of
* things adds a little complexity. pLDTE is updated there and not in the
* 'next' part of the loop. The pLDTEEnd is inclusive.
*/
PX86DESC pLDTEEnd = (PX86DESC)((uintptr_t)pShadowLDT + cbChunk) - 1;
if (pLDTE + 1 < pShadowLDT)
pLDTE = (PX86DESC)((uintptr_t)pShadowLDT + off);
while (pLDTE <= pLDTEEnd)
{
if (pLDTE->Gen.u1Present)
selmGuestToShadowDesc(pVM, pLDTE);
/* Next LDT entry. */
pLDTE++;
}
}
else
{
RT_BZERO(pShadowLDT, cbChunk);
AssertMsg(rc == VERR_PAGE_NOT_PRESENT || rc == VERR_PAGE_TABLE_NOT_PRESENT, ("rc=%Rrc\n", rc));
rc = PGMMapSetPage(pVM, GCPtrShadowLDT & PAGE_BASE_GC_MASK, PAGE_SIZE, 0);
AssertRC(rc);
}
/*
* Advance to the next page.
*/
cbLeft -= cbChunk;
GCPtrShadowLDT += cbChunk;
pShadowLDT = (PX86DESC)((char *)pShadowLDT + cbChunk);
GCPtrLdt += cbChunk;
}
return VINF_SUCCESS;
}
/**
* Checks and updates segment selector registers.
*
* @returns VBox strict status code.
* @retval VINF_EM_RESCHEDULE_REM if a stale register was found.
*
* @param pVM The cross context VM structure.
* @param pVCpu The cross context virtual CPU structure of the calling EMT.
*/
static VBOXSTRICTRC selmR3UpdateSegmentRegisters(PVM pVM, PVMCPU pVCpu)
{
Assert(CPUMIsGuestInProtectedMode(pVCpu));
Assert(VM_IS_RAW_MODE_ENABLED(pVM));
/*
* No stale selectors in V8086 mode.
*/
PCPUMCTX pCtx = CPUMQueryGuestCtxPtr(pVCpu);
if (pCtx->eflags.Bits.u1VM)
return VINF_SUCCESS;
/*
* Check for stale selectors and load hidden register bits where they
* are missing.
*/
uint32_t uCpl = CPUMGetGuestCPL(pVCpu);
VBOXSTRICTRC rcStrict = VINF_SUCCESS;
PCPUMSELREG paSReg = CPUMCTX_FIRST_SREG(pCtx);
for (uint32_t iSReg = 0; iSReg < X86_SREG_COUNT; iSReg++)
{
RTSEL const Sel = paSReg[iSReg].Sel;
if (Sel & X86_SEL_MASK_OFF_RPL)
{
/* Get the shadow descriptor entry corresponding to this. */
static X86DESC const s_NotPresentDesc = { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } };
PCX86DESC pDesc;
if (!(Sel & X86_SEL_LDT))
{
if ((Sel | (sizeof(*pDesc) - 1)) <= pCtx->gdtr.cbGdt)
pDesc = &pVM->selm.s.paGdtR3[Sel >> X86_SEL_SHIFT];
else
pDesc = &s_NotPresentDesc;
}
else
{
if ((Sel | (sizeof(*pDesc) - 1)) <= pVM->selm.s.cbLdtLimit)
pDesc = &((PCX86DESC)((uintptr_t)pVM->selm.s.pvLdtR3 + pVM->selm.s.offLdtHyper))[Sel >> X86_SEL_SHIFT];
else
pDesc = &s_NotPresentDesc;
}
/* Check the segment register. */
if (CPUMSELREG_ARE_HIDDEN_PARTS_VALID(pVCpu, &paSReg[iSReg]))
{
if (!(paSReg[iSReg].fFlags & CPUMSELREG_FLAGS_STALE))
{
/* Did it go stale? */
if (selmIsSRegStale32(&paSReg[iSReg], pDesc, iSReg))
{
Log2(("SELM: Detected stale %s=%#x (was valid)\n", g_aszSRegNms[iSReg], Sel));
STAM_REL_COUNTER_INC(&pVM->selm.s.aStatDetectedStaleSReg[iSReg]);
paSReg[iSReg].fFlags |= CPUMSELREG_FLAGS_STALE;
rcStrict = VINF_EM_RESCHEDULE_REM;
}
}
else
{
/* Did it stop being stale? I.e. did the guest change it things
back to the way they were? */
if (!selmIsSRegStale32(&paSReg[iSReg], pDesc, iSReg))
{
STAM_REL_COUNTER_INC(&pVM->selm.s.StatStaleToUnstaleSReg);
paSReg[iSReg].fFlags &= CPUMSELREG_FLAGS_STALE;
}
else
{
Log2(("SELM: Already stale %s=%#x\n", g_aszSRegNms[iSReg], Sel));
STAM_REL_COUNTER_INC(&pVM->selm.s.aStatAlreadyStaleSReg[iSReg]);
rcStrict = VINF_EM_RESCHEDULE_REM;
}
}
}
/* Load the hidden registers if it's a valid descriptor for the
current segment register. */
else if (selmIsShwDescGoodForSReg(&paSReg[iSReg], pDesc, iSReg, uCpl))
{
selmLoadHiddenSRegFromShadowDesc(&paSReg[iSReg], pDesc);
STAM_COUNTER_INC(&pVM->selm.s.aStatUpdatedSReg[iSReg]);
}
/* It's stale. */
else
{
Log2(("SELM: Detected stale %s=%#x (wasn't valid)\n", g_aszSRegNms[iSReg], Sel));
STAM_REL_COUNTER_INC(&pVM->selm.s.aStatDetectedStaleSReg[iSReg]);
paSReg[iSReg].fFlags = CPUMSELREG_FLAGS_STALE;
rcStrict = VINF_EM_RESCHEDULE_REM;
}
}
/* else: 0 selector, ignore. */
}
return rcStrict;
}
/**
* Updates the Guest GDT & LDT virtualization based on current CPU state.
*
* @returns VBox status code.
* @param pVM The cross context VM structure.
* @param pVCpu The cross context virtual CPU structure.
*/
VMMR3DECL(VBOXSTRICTRC) SELMR3UpdateFromCPUM(PVM pVM, PVMCPU pVCpu)
{
STAM_PROFILE_START(&pVM->selm.s.StatUpdateFromCPUM, a);
AssertReturn(VM_IS_RAW_MODE_ENABLED(pVM), VERR_SELM_HM_IPE);
/*
* GDT sync
*/
int rc;
if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_SELM_SYNC_GDT))
{
rc = selmR3UpdateShadowGdt(pVM, pVCpu);
if (RT_FAILURE(rc))
return rc; /* We're toast, so forget the profiling. */
AssertRCSuccess(rc);
}
/*
* TSS sync
*/
if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_SELM_SYNC_TSS))
{
rc = SELMR3SyncTSS(pVM, pVCpu);
if (RT_FAILURE(rc))
return rc;
AssertRCSuccess(rc);
}
/*
* LDT sync
*/
if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_SELM_SYNC_LDT))
{
rc = selmR3UpdateShadowLdt(pVM, pVCpu);
if (RT_FAILURE(rc))
return rc;
AssertRCSuccess(rc);
}
/*
* Check selector registers.
*/
VBOXSTRICTRC rcStrict = selmR3UpdateSegmentRegisters(pVM, pVCpu);
STAM_PROFILE_STOP(&pVM->selm.s.StatUpdateFromCPUM, a);
return rcStrict;
}
/**
* Synchronize the shadowed fields in the TSS.
*
* At present we're shadowing the ring-0 stack selector & pointer, and the
* interrupt redirection bitmap (if present). We take the lazy approach wrt to
* REM and this function is called both if REM made any changes to the TSS or
* loaded TR.
*
* @returns VBox status code.
* @param pVM The cross context VM structure.
* @param pVCpu The cross context virtual CPU structure.
*/
VMMR3DECL(int) SELMR3SyncTSS(PVM pVM, PVMCPU pVCpu)
{
LogFlow(("SELMR3SyncTSS\n"));
int rc;
AssertReturnStmt(VM_IS_RAW_MODE_ENABLED(pVM), VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_SELM_SYNC_TSS), VINF_SUCCESS);
STAM_PROFILE_START(&pVM->selm.s.StatTSSSync, a);
Assert(VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_SELM_SYNC_TSS));
/*
* Get TR and extract and store the basic info.
*
* Note! The TSS limit is not checked by the LTR code, so we
* have to be a bit careful with it. We make sure cbTss
* won't be zero if TR is valid and if it's NULL we'll
* make sure cbTss is 0.
*/
/** @todo use the hidden bits, not shadow GDT. */
CPUMSELREGHID trHid;
RTSEL SelTss = CPUMGetGuestTR(pVCpu, &trHid);
RTGCPTR GCPtrTss = trHid.u64Base;
uint32_t cbTss = trHid.u32Limit;
Assert( (SelTss & X86_SEL_MASK_OFF_RPL)
|| (cbTss == 0 && GCPtrTss == 0 && trHid.Attr.u == 0 /* TR=0 */)
|| (cbTss == 0xffff && GCPtrTss == 0 && trHid.Attr.n.u1Present && trHid.Attr.n.u4Type == X86_SEL_TYPE_SYS_386_TSS_BUSY /* RESET */));
if (SelTss & X86_SEL_MASK_OFF_RPL)
{
Assert(!(SelTss & X86_SEL_LDT));
Assert(trHid.Attr.n.u1DescType == 0);
Assert( trHid.Attr.n.u4Type == X86_SEL_TYPE_SYS_286_TSS_BUSY
|| trHid.Attr.n.u4Type == X86_SEL_TYPE_SYS_386_TSS_BUSY);
if (!++cbTss)
cbTss = UINT32_MAX;
}
else
{
Assert( (cbTss == 0 && GCPtrTss == 0 && trHid.Attr.u == 0 /* TR=0 */)
|| (cbTss == 0xffff && GCPtrTss == 0 && trHid.Attr.n.u1Present && trHid.Attr.n.u4Type == X86_SEL_TYPE_SYS_386_TSS_BUSY /* RESET */));
cbTss = 0; /* the reset case. */
}
pVM->selm.s.cbGuestTss = cbTss;
pVM->selm.s.fGuestTss32Bit = trHid.Attr.n.u4Type == X86_SEL_TYPE_SYS_386_TSS_AVAIL
|| trHid.Attr.n.u4Type == X86_SEL_TYPE_SYS_386_TSS_BUSY;
/*
* Figure out the size of what need to monitor.
*/
/* We're not interested in any 16-bit TSSes. */
uint32_t cbMonitoredTss = cbTss;
if ( trHid.Attr.n.u4Type != X86_SEL_TYPE_SYS_386_TSS_AVAIL
&& trHid.Attr.n.u4Type != X86_SEL_TYPE_SYS_386_TSS_BUSY)
cbMonitoredTss = 0;
pVM->selm.s.offGuestIoBitmap = 0;
bool fNoRing1Stack = true;
if (cbMonitoredTss)
{
/*
* 32-bit TSS. What we're really keen on is the SS0 and ESP0 fields.
* If VME is enabled we also want to keep an eye on the interrupt
* redirection bitmap.
*/
VBOXTSS Tss;
uint32_t cr4 = CPUMGetGuestCR4(pVCpu);
rc = PGMPhysSimpleReadGCPtr(pVCpu, &Tss, GCPtrTss, RT_UOFFSETOF(VBOXTSS, IntRedirBitmap));
if ( !(cr4 & X86_CR4_VME)
|| ( RT_SUCCESS(rc)
&& Tss.offIoBitmap < sizeof(VBOXTSS) /* too small */
&& Tss.offIoBitmap > cbTss) /* beyond the end */ /** @todo not sure how the partial case is handled; probably not allowed. */
)
/* No interrupt redirection bitmap, just ESP0 and SS0. */
cbMonitoredTss = RT_UOFFSETOF(VBOXTSS, padding_ss0);
else if (RT_SUCCESS(rc))
{
/*
* Everything up to and including the interrupt redirection bitmap. Unfortunately
* this can be quite a large chunk. We use to skip it earlier and just hope it
* was kind of static...
*
* Update the virtual interrupt redirection bitmap while we're here.
* (It is located in the 32 bytes before TR:offIoBitmap.)
*/
cbMonitoredTss = Tss.offIoBitmap;
pVM->selm.s.offGuestIoBitmap = Tss.offIoBitmap;
uint32_t offRedirBitmap = Tss.offIoBitmap - sizeof(Tss.IntRedirBitmap);
rc = PGMPhysSimpleReadGCPtr(pVCpu, &pVM->selm.s.Tss.IntRedirBitmap,
GCPtrTss + offRedirBitmap, sizeof(Tss.IntRedirBitmap));
AssertRC(rc);
/** @todo memset the bitmap on failure? */
Log2(("Redirection bitmap:\n"));
Log2(("%.*Rhxd\n", sizeof(Tss.IntRedirBitmap), &pVM->selm.s.Tss.IntRedirBitmap));
}
else
{
cbMonitoredTss = RT_UOFFSETOF(VBOXTSS, IntRedirBitmap);
pVM->selm.s.offGuestIoBitmap = 0;
/** @todo memset the bitmap? */
}
/*
* Update the ring 0 stack selector and base address.
*/
if (RT_SUCCESS(rc))
{
# ifdef LOG_ENABLED
if (LogIsEnabled())
{
uint32_t ssr0, espr0;
SELMGetRing1Stack(pVM, &ssr0, &espr0);
if ((ssr0 & ~1) != Tss.ss0 || espr0 != Tss.esp0)
{
RTGCPHYS GCPhys = NIL_RTGCPHYS;
rc = PGMGstGetPage(pVCpu, GCPtrTss, NULL, &GCPhys); AssertRC(rc);
Log(("SELMR3SyncTSS: Updating TSS ring 0 stack to %04X:%08X from %04X:%08X; TSS Phys=%RGp)\n",
Tss.ss0, Tss.esp0, (ssr0 & ~1), espr0, GCPhys));
AssertMsg(ssr0 != Tss.ss0,
("ring-1 leak into TSS.SS0! %04X:%08X from %04X:%08X; TSS Phys=%RGp)\n",
Tss.ss0, Tss.esp0, (ssr0 & ~1), espr0, GCPhys));
}
Log(("offIoBitmap=%#x\n", Tss.offIoBitmap));
}
# endif /* LOG_ENABLED */
AssertMsg(!(Tss.ss0 & 3), ("ring-1 leak into TSS.SS0? %04X:%08X\n", Tss.ss0, Tss.esp0));
/* Update our TSS structure for the guest's ring 1 stack */
selmSetRing1Stack(pVM, Tss.ss0 | 1, Tss.esp0);
pVM->selm.s.fSyncTSSRing0Stack = fNoRing1Stack = false;
# ifdef VBOX_WITH_RAW_RING1
/* Update our TSS structure for the guest's ring 2 stack */
if (EMIsRawRing1Enabled(pVM))
{
if ( (pVM->selm.s.Tss.ss2 != ((Tss.ss1 & ~2) | 1))
|| pVM->selm.s.Tss.esp2 != Tss.esp1)
Log(("SELMR3SyncTSS: Updating TSS ring 1 stack to %04X:%08X from %04X:%08X\n", Tss.ss1, Tss.esp1, (pVM->selm.s.Tss.ss2 & ~2) | 1, pVM->selm.s.Tss.esp2));
selmSetRing2Stack(pVM, (Tss.ss1 & ~1) | 2, Tss.esp1);
}
# endif
}
}
/*
* Flush the ring-1 stack and the direct syscall dispatching if we
* cannot obtain SS0:ESP0.
*/
if (fNoRing1Stack)
{
selmSetRing1Stack(pVM, 0 /* invalid SS */, 0);
pVM->selm.s.fSyncTSSRing0Stack = cbMonitoredTss != 0;
/** @todo handle these dependencies better! */
TRPMR3SetGuestTrapHandler(pVM, 0x2E, TRPM_INVALID_HANDLER);
TRPMR3SetGuestTrapHandler(pVM, 0x80, TRPM_INVALID_HANDLER);
}
/*
* Check for monitor changes and apply them.
*/
if ( GCPtrTss != pVM->selm.s.GCPtrGuestTss
|| cbMonitoredTss != pVM->selm.s.cbMonitoredGuestTss)
{
Log(("SELMR3SyncTSS: Guest's TSS is changed to pTss=%RGv cbMonitoredTss=%08X cbGuestTss=%#08x\n",
GCPtrTss, cbMonitoredTss, pVM->selm.s.cbGuestTss));
/* Release the old range first. */
if (pVM->selm.s.GCPtrGuestTss != RTRCPTR_MAX)
{
rc = PGMHandlerVirtualDeregister(pVM, pVCpu, pVM->selm.s.GCPtrGuestTss, false /*fHypervisor*/);
AssertRC(rc);
}
/* Register the write handler if TS != 0. */
if (cbMonitoredTss != 0)
{
# ifdef SELM_TRACK_GUEST_TSS_CHANGES
rc = PGMR3HandlerVirtualRegister(pVM, pVCpu, pVM->selm.s.hGuestTssWriteHandlerType,
GCPtrTss, GCPtrTss + cbMonitoredTss - 1,
NULL /*pvUserR3*/, NIL_RTR0PTR /*pvUserRC*/, NULL /*pszDesc*/);
if (RT_FAILURE(rc))
{
# ifdef VBOX_WITH_RAW_RING1
/** @todo !HACK ALERT!
* Some guest OSes (QNX) share code and the TSS on the same page;
* PGMR3HandlerVirtualRegister doesn't support more than one
* handler, so we kick out the PATM handler as this one is more
* important. Fix this properly in PGMR3HandlerVirtualRegister?
*/
if (rc == VERR_PGM_HANDLER_VIRTUAL_CONFLICT)
{
LogRel(("SELMR3SyncTSS: Virtual handler conflict %RGv -> kick out PATM handler for the higher priority TSS page monitor\n", GCPtrTss));
rc = PGMHandlerVirtualDeregister(pVM, pVCpu, GCPtrTss & PAGE_BASE_GC_MASK, false /*fHypervisor*/);
AssertRC(rc);
rc = PGMR3HandlerVirtualRegister(pVM, pVCpu, pVM->selm.s.hGuestTssWriteHandlerType,
GCPtrTss, GCPtrTss + cbMonitoredTss - 1,
NULL /*pvUserR3*/, NIL_RTR0PTR /*pvUserRC*/, NULL /*pszDesc*/);
if (RT_FAILURE(rc))
{
STAM_PROFILE_STOP(&pVM->selm.s.StatUpdateFromCPUM, a);
return rc;
}
}
# else
STAM_PROFILE_STOP(&pVM->selm.s.StatUpdateFromCPUM, a);
return rc;
# endif
}
# endif /* SELM_TRACK_GUEST_TSS_CHANGES */
/* Update saved Guest TSS info. */
pVM->selm.s.GCPtrGuestTss = GCPtrTss;
pVM->selm.s.cbMonitoredGuestTss = cbMonitoredTss;
pVM->selm.s.GCSelTss = SelTss;
}
else
{
pVM->selm.s.GCPtrGuestTss = RTRCPTR_MAX;
pVM->selm.s.cbMonitoredGuestTss = 0;
pVM->selm.s.GCSelTss = 0;
}
}
VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_SELM_SYNC_TSS);
STAM_PROFILE_STOP(&pVM->selm.s.StatTSSSync, a);
return VINF_SUCCESS;
}
/**
* Compares the Guest GDT and LDT with the shadow tables.
* This is a VBOX_STRICT only function.
*
* @returns VBox status code.
* @param pVM The cross context VM structure.
*/
VMMR3DECL(int) SELMR3DebugCheck(PVM pVM)
{
# ifdef VBOX_STRICT
PVMCPU pVCpu = VMMGetCpu(pVM);
AssertReturn(VM_IS_RAW_MODE_ENABLED(pVM), VERR_SELM_HM_IPE);
/*
* Get GDTR and check for conflict.
*/
VBOXGDTR GDTR;
CPUMGetGuestGDTR(pVCpu, &GDTR);
if (GDTR.cbGdt == 0)
return VINF_SUCCESS;
if (GDTR.cbGdt >= (unsigned)(pVM->selm.s.aHyperSel[SELM_HYPER_SEL_TSS_TRAP08] >> X86_SEL_SHIFT))
Log(("SELMR3DebugCheck: guest GDT size forced us to look for unused selectors.\n"));
if (GDTR.cbGdt != pVM->selm.s.GuestGdtr.cbGdt)
Log(("SELMR3DebugCheck: limits have changed! new=%d old=%d\n", GDTR.cbGdt, pVM->selm.s.GuestGdtr.cbGdt));
/*
* Loop thru the GDT checking each entry.
*/
RTGCPTR GCPtrGDTEGuest = GDTR.pGdt;
PX86DESC pGDTE = pVM->selm.s.paGdtR3;
PX86DESC pGDTEEnd = (PX86DESC)((uintptr_t)pGDTE + GDTR.cbGdt);
while (pGDTE < pGDTEEnd)
{
X86DESC GDTEGuest;
int rc = PGMPhysSimpleReadGCPtr(pVCpu, &GDTEGuest, GCPtrGDTEGuest, sizeof(GDTEGuest));
if (RT_SUCCESS(rc))
{
if (pGDTE->Gen.u1DescType || pGDTE->Gen.u4Type != X86_SEL_TYPE_SYS_LDT)
{
if ( pGDTE->Gen.u16LimitLow != GDTEGuest.Gen.u16LimitLow
|| pGDTE->Gen.u4LimitHigh != GDTEGuest.Gen.u4LimitHigh
|| pGDTE->Gen.u16BaseLow != GDTEGuest.Gen.u16BaseLow
|| pGDTE->Gen.u8BaseHigh1 != GDTEGuest.Gen.u8BaseHigh1
|| pGDTE->Gen.u8BaseHigh2 != GDTEGuest.Gen.u8BaseHigh2
|| pGDTE->Gen.u1DefBig != GDTEGuest.Gen.u1DefBig
|| pGDTE->Gen.u1DescType != GDTEGuest.Gen.u1DescType)
{
unsigned iGDT = pGDTE - pVM->selm.s.paGdtR3;
SELMR3DumpDescriptor(*pGDTE, iGDT << 3, "SELMR3DebugCheck: GDT mismatch, shadow");
SELMR3DumpDescriptor(GDTEGuest, iGDT << 3, "SELMR3DebugCheck: GDT mismatch, guest");
}
}
}
/* Advance to the next descriptor. */
GCPtrGDTEGuest += sizeof(X86DESC);
pGDTE++;
}
/*
* LDT?
*/
RTSEL SelLdt = CPUMGetGuestLDTR(pVCpu);
if ((SelLdt & X86_SEL_MASK_OFF_RPL) == 0)
return VINF_SUCCESS;
Assert(!(SelLdt & X86_SEL_LDT));
if (SelLdt > GDTR.cbGdt)
{
Log(("SELMR3DebugCheck: ldt is out of bound SelLdt=%#x\n", SelLdt));
return VERR_SELM_LDT_OUT_OF_BOUNDS;
}
X86DESC LDTDesc;
int rc = PGMPhysSimpleReadGCPtr(pVCpu, &LDTDesc, GDTR.pGdt + (SelLdt & X86_SEL_MASK), sizeof(LDTDesc));
if (RT_FAILURE(rc))
{
Log(("SELMR3DebugCheck: Failed to read LDT descriptor. rc=%d\n", rc));
return rc;
}
RTGCPTR GCPtrLDTEGuest = X86DESC_BASE(&LDTDesc);
uint32_t cbLdt = X86DESC_LIMIT_G(&LDTDesc);
/*
* Validate it.
*/
if (!cbLdt)
return VINF_SUCCESS;
/** @todo check what intel does about odd limits. */
AssertMsg(RT_ALIGN(cbLdt + 1, sizeof(X86DESC)) == cbLdt + 1 && cbLdt <= 0xffff, ("cbLdt=%d\n", cbLdt));
if ( LDTDesc.Gen.u1DescType
|| LDTDesc.Gen.u4Type != X86_SEL_TYPE_SYS_LDT
|| SelLdt >= pVM->selm.s.GuestGdtr.cbGdt)
{
Log(("SELmR3DebugCheck: Invalid LDT %04x!\n", SelLdt));
return VERR_SELM_INVALID_LDT;
}
/*
* Loop thru the LDT checking each entry.
*/
unsigned off = (GCPtrLDTEGuest & PAGE_OFFSET_MASK);
PX86DESC pLDTE = (PX86DESC)((uintptr_t)pVM->selm.s.pvLdtR3 + off);
PX86DESC pLDTEEnd = (PX86DESC)((uintptr_t)pGDTE + cbLdt);
while (pLDTE < pLDTEEnd)
{
X86DESC LDTEGuest;
rc = PGMPhysSimpleReadGCPtr(pVCpu, &LDTEGuest, GCPtrLDTEGuest, sizeof(LDTEGuest));
if (RT_SUCCESS(rc))
{
if ( pLDTE->Gen.u16LimitLow != LDTEGuest.Gen.u16LimitLow
|| pLDTE->Gen.u4LimitHigh != LDTEGuest.Gen.u4LimitHigh
|| pLDTE->Gen.u16BaseLow != LDTEGuest.Gen.u16BaseLow
|| pLDTE->Gen.u8BaseHigh1 != LDTEGuest.Gen.u8BaseHigh1
|| pLDTE->Gen.u8BaseHigh2 != LDTEGuest.Gen.u8BaseHigh2
|| pLDTE->Gen.u1DefBig != LDTEGuest.Gen.u1DefBig
|| pLDTE->Gen.u1DescType != LDTEGuest.Gen.u1DescType)
{
unsigned iLDT = pLDTE - (PX86DESC)((uintptr_t)pVM->selm.s.pvLdtR3 + off);
SELMR3DumpDescriptor(*pLDTE, iLDT << 3, "SELMR3DebugCheck: LDT mismatch, shadow");
SELMR3DumpDescriptor(LDTEGuest, iLDT << 3, "SELMR3DebugCheck: LDT mismatch, guest");
}
}
/* Advance to the next descriptor. */
GCPtrLDTEGuest += sizeof(X86DESC);
pLDTE++;
}
# else /* !VBOX_STRICT */
NOREF(pVM);
# endif /* !VBOX_STRICT */
return VINF_SUCCESS;
}
/**
* Validates the RawR0 TSS values against the one in the Guest TSS.
*
* @returns true if it matches.
* @returns false and assertions on mismatch..
* @param pVM The cross context VM structure.
*/
VMMR3DECL(bool) SELMR3CheckTSS(PVM pVM)
{
# if defined(VBOX_STRICT) && defined(SELM_TRACK_GUEST_TSS_CHANGES)
PVMCPU pVCpu = VMMGetCpu(pVM);
if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_SELM_SYNC_TSS))
return true;
/*
* Get TR and extract the basic info.
*/
CPUMSELREGHID trHid;
RTSEL SelTss = CPUMGetGuestTR(pVCpu, &trHid);
RTGCPTR GCPtrTss = trHid.u64Base;
uint32_t cbTss = trHid.u32Limit;
Assert( (SelTss & X86_SEL_MASK_OFF_RPL)
|| (cbTss == 0 && GCPtrTss == 0 && trHid.Attr.u == 0 /* TR=0 */)
|| (cbTss == 0xffff && GCPtrTss == 0 && trHid.Attr.n.u1Present && trHid.Attr.n.u4Type == X86_SEL_TYPE_SYS_386_TSS_BUSY /* RESET */));
if (SelTss & X86_SEL_MASK_OFF_RPL)
{
AssertReturn(!(SelTss & X86_SEL_LDT), false);
AssertReturn(trHid.Attr.n.u1DescType == 0, false);
AssertReturn( trHid.Attr.n.u4Type == X86_SEL_TYPE_SYS_286_TSS_BUSY
|| trHid.Attr.n.u4Type == X86_SEL_TYPE_SYS_386_TSS_BUSY,
false);
if (!++cbTss)
cbTss = UINT32_MAX;
}
else
{
AssertReturn( (cbTss == 0 && GCPtrTss == 0 && trHid.Attr.u == 0 /* TR=0 */)
|| (cbTss == 0xffff && GCPtrTss == 0 && trHid.Attr.n.u1Present && trHid.Attr.n.u4Type == X86_SEL_TYPE_SYS_386_TSS_BUSY /* RESET */),
false);
cbTss = 0; /* the reset case. */
}
AssertMsgReturn(pVM->selm.s.cbGuestTss == cbTss, ("%#x %#x\n", pVM->selm.s.cbGuestTss, cbTss), false);
AssertMsgReturn(pVM->selm.s.fGuestTss32Bit == ( trHid.Attr.n.u4Type == X86_SEL_TYPE_SYS_386_TSS_AVAIL
|| trHid.Attr.n.u4Type == X86_SEL_TYPE_SYS_386_TSS_BUSY),
("%RTbool u4Type=%d\n", pVM->selm.s.fGuestTss32Bit, trHid.Attr.n.u4Type),
false);
AssertMsgReturn( pVM->selm.s.GCSelTss == SelTss
|| (!pVM->selm.s.GCSelTss && !(SelTss & X86_SEL_LDT)),
("%#x %#x\n", pVM->selm.s.GCSelTss, SelTss),
false);
AssertMsgReturn( pVM->selm.s.GCPtrGuestTss == GCPtrTss
|| (pVM->selm.s.GCPtrGuestTss == RTRCPTR_MAX && !GCPtrTss),
("%#RGv %#RGv\n", pVM->selm.s.GCPtrGuestTss, GCPtrTss),
false);
/*
* Figure out the size of what need to monitor.
*/
/* We're not interested in any 16-bit TSSes. */
uint32_t cbMonitoredTss = cbTss;
if ( trHid.Attr.n.u4Type != X86_SEL_TYPE_SYS_386_TSS_AVAIL
&& trHid.Attr.n.u4Type != X86_SEL_TYPE_SYS_386_TSS_BUSY)
cbMonitoredTss = 0;
if (cbMonitoredTss)
{
VBOXTSS Tss;
uint32_t cr4 = CPUMGetGuestCR4(pVCpu);
int rc = PGMPhysSimpleReadGCPtr(pVCpu, &Tss, GCPtrTss, RT_UOFFSETOF(VBOXTSS, IntRedirBitmap));
AssertReturn( rc == VINF_SUCCESS
/* Happens early in XP boot during page table switching. */
|| ( (rc == VERR_PAGE_TABLE_NOT_PRESENT || rc == VERR_PAGE_NOT_PRESENT)
&& !(CPUMGetGuestEFlags(pVCpu) & X86_EFL_IF)),
false);
if ( !(cr4 & X86_CR4_VME)
|| ( RT_SUCCESS(rc)
&& Tss.offIoBitmap < sizeof(VBOXTSS) /* too small */
&& Tss.offIoBitmap > cbTss)
)
cbMonitoredTss = RT_UOFFSETOF(VBOXTSS, padding_ss0);
else if (RT_SUCCESS(rc))
{
cbMonitoredTss = Tss.offIoBitmap;
AssertMsgReturn(pVM->selm.s.offGuestIoBitmap == Tss.offIoBitmap,
("%#x %#x\n", pVM->selm.s.offGuestIoBitmap, Tss.offIoBitmap),
false);
/* check the bitmap */
uint32_t offRedirBitmap = Tss.offIoBitmap - sizeof(Tss.IntRedirBitmap);
rc = PGMPhysSimpleReadGCPtr(pVCpu, &Tss.IntRedirBitmap,
GCPtrTss + offRedirBitmap, sizeof(Tss.IntRedirBitmap));
AssertRCReturn(rc, false);
AssertMsgReturn(!memcmp(&Tss.IntRedirBitmap[0], &pVM->selm.s.Tss.IntRedirBitmap[0], sizeof(Tss.IntRedirBitmap)),
("offIoBitmap=%#x cbTss=%#x\n"
" Guest: %.32Rhxs\n"
"Shadow: %.32Rhxs\n",
Tss.offIoBitmap, cbTss,
&Tss.IntRedirBitmap[0],
&pVM->selm.s.Tss.IntRedirBitmap[0]),
false);
}
else
cbMonitoredTss = RT_UOFFSETOF(VBOXTSS, IntRedirBitmap);
/*
* Check SS0 and ESP0.
*/
if ( !pVM->selm.s.fSyncTSSRing0Stack
&& RT_SUCCESS(rc))
{
if ( Tss.esp0 != pVM->selm.s.Tss.esp1
|| Tss.ss0 != (pVM->selm.s.Tss.ss1 & ~1))
{
RTGCPHYS GCPhys;
rc = PGMGstGetPage(pVCpu, GCPtrTss, NULL, &GCPhys); AssertRC(rc);
AssertMsgFailed(("TSS out of sync!! (%04X:%08X vs %04X:%08X (guest)) Tss=%RGv Phys=%RGp\n",
(pVM->selm.s.Tss.ss1 & ~1), pVM->selm.s.Tss.esp1,
Tss.ss1, Tss.esp1, GCPtrTss, GCPhys));
return false;
}
}
AssertMsgReturn(pVM->selm.s.cbMonitoredGuestTss == cbMonitoredTss, ("%#x %#x\n", pVM->selm.s.cbMonitoredGuestTss, cbMonitoredTss), false);
}
else
{
AssertMsgReturn(pVM->selm.s.Tss.ss1 == 0 && pVM->selm.s.Tss.esp1 == 0, ("%04x:%08x\n", pVM->selm.s.Tss.ss1, pVM->selm.s.Tss.esp1), false);
AssertReturn(!pVM->selm.s.fSyncTSSRing0Stack, false);
AssertMsgReturn(pVM->selm.s.cbMonitoredGuestTss == cbMonitoredTss, ("%#x %#x\n", pVM->selm.s.cbMonitoredGuestTss, cbMonitoredTss), false);
}
return true;
# else /* !VBOX_STRICT */
NOREF(pVM);
return true;
# endif /* !VBOX_STRICT */
}
# ifdef VBOX_WITH_SAFE_STR
/**
* Validates the RawR0 TR shadow GDT entry.
*
* @returns true if it matches.
* @returns false and assertions on mismatch..
* @param pVM The cross context VM structure.
*/
VMMR3DECL(bool) SELMR3CheckShadowTR(PVM pVM)
{
# ifdef VBOX_STRICT
PX86DESC paGdt = pVM->selm.s.paGdtR3;
/*
* TSS descriptor
*/
PX86DESC pDesc = &paGdt[pVM->selm.s.aHyperSel[SELM_HYPER_SEL_TSS] >> 3];
RTRCPTR RCPtrTSS = VM_RC_ADDR(pVM, &pVM->selm.s.Tss);
if ( pDesc->Gen.u16BaseLow != RT_LOWORD(RCPtrTSS)
|| pDesc->Gen.u8BaseHigh1 != RT_BYTE3(RCPtrTSS)
|| pDesc->Gen.u8BaseHigh2 != RT_BYTE4(RCPtrTSS)
|| pDesc->Gen.u16LimitLow != sizeof(VBOXTSS) - 1
|| pDesc->Gen.u4LimitHigh != 0
|| (pDesc->Gen.u4Type != X86_SEL_TYPE_SYS_386_TSS_AVAIL && pDesc->Gen.u4Type != X86_SEL_TYPE_SYS_386_TSS_BUSY)
|| pDesc->Gen.u1DescType != 0 /* system */
|| pDesc->Gen.u2Dpl != 0 /* supervisor */
|| pDesc->Gen.u1Present != 1
|| pDesc->Gen.u1Available != 0
|| pDesc->Gen.u1Long != 0
|| pDesc->Gen.u1DefBig != 0
|| pDesc->Gen.u1Granularity != 0 /* byte limit */
)
{
AssertFailed();
return false;
}
# else
RT_NOREF_PV(pVM);
# endif
return true;
}
# endif /* VBOX_WITH_SAFE_STR */
#endif /* VBOX_WITH_RAW_MODE */
/**
* Gets information about a 64-bit selector, SELMR3GetSelectorInfo helper.
*
* See SELMR3GetSelectorInfo for details.
*
* @returns VBox status code, see SELMR3GetSelectorInfo for details.
*
* @param pVCpu The cross context virtual CPU structure.
* @param Sel The selector to get info about.
* @param pSelInfo Where to store the information.
*/
static int selmR3GetSelectorInfo64(PVMCPU pVCpu, RTSEL Sel, PDBGFSELINFO pSelInfo)
{
/*
* Read it from the guest descriptor table.
*/
/** @todo this is bogus wrt the LDT/GDT limit on long selectors. */
X86DESC64 Desc;
RTGCPTR GCPtrDesc;
if (!(Sel & X86_SEL_LDT))
{
/* GDT */
VBOXGDTR Gdtr;
CPUMGetGuestGDTR(pVCpu, &Gdtr);
if ((Sel | X86_SEL_RPL_LDT) > Gdtr.cbGdt)
return VERR_INVALID_SELECTOR;
GCPtrDesc = Gdtr.pGdt + (Sel & X86_SEL_MASK);
}
else
{
/* LDT */
uint64_t GCPtrBase;
uint32_t cbLimit;
CPUMGetGuestLdtrEx(pVCpu, &GCPtrBase, &cbLimit);
if ((Sel | X86_SEL_RPL_LDT) > cbLimit)
return VERR_INVALID_SELECTOR;
/* calc the descriptor location. */
GCPtrDesc = GCPtrBase + (Sel & X86_SEL_MASK);
}
/* read the descriptor. */
int rc = PGMPhysSimpleReadGCPtr(pVCpu, &Desc, GCPtrDesc, sizeof(Desc));
if (RT_FAILURE(rc))
{
rc = PGMPhysSimpleReadGCPtr(pVCpu, &Desc, GCPtrDesc, sizeof(X86DESC));
if (RT_FAILURE(rc))
return rc;
Desc.au64[1] = 0;
}
/*
* Extract the base and limit
* (We ignore the present bit here, which is probably a bit silly...)
*/
pSelInfo->Sel = Sel;
pSelInfo->fFlags = DBGFSELINFO_FLAGS_LONG_MODE;
pSelInfo->u.Raw64 = Desc;
if (Desc.Gen.u1DescType)
{
/*
* 64-bit code selectors are wide open, it's not possible to detect
* 64-bit data or stack selectors without also dragging in assumptions
* about current CS (i.e. that's we're executing in 64-bit mode). So,
* the selinfo user needs to deal with this in the context the info is
* used unfortunately.
*/
if ( Desc.Gen.u1Long
&& !Desc.Gen.u1DefBig
&& (Desc.Gen.u4Type & X86_SEL_TYPE_CODE))
{
/* Note! We ignore the segment limit hacks that was added by AMD. */
pSelInfo->GCPtrBase = 0;
pSelInfo->cbLimit = ~(RTGCUINTPTR)0;
}
else
{
pSelInfo->cbLimit = X86DESC_LIMIT_G(&Desc);
pSelInfo->GCPtrBase = X86DESC_BASE(&Desc);
}
pSelInfo->SelGate = 0;
}
else if ( Desc.Gen.u4Type == AMD64_SEL_TYPE_SYS_LDT
|| Desc.Gen.u4Type == AMD64_SEL_TYPE_SYS_TSS_AVAIL
|| Desc.Gen.u4Type == AMD64_SEL_TYPE_SYS_TSS_BUSY)
{
/* Note. LDT descriptors are weird in long mode, we ignore the footnote
in the AMD manual here as a simplification. */
pSelInfo->GCPtrBase = X86DESC64_BASE(&Desc);
pSelInfo->cbLimit = X86DESC_LIMIT_G(&Desc);
pSelInfo->SelGate = 0;
}
else if ( Desc.Gen.u4Type == AMD64_SEL_TYPE_SYS_CALL_GATE
|| Desc.Gen.u4Type == AMD64_SEL_TYPE_SYS_TRAP_GATE
|| Desc.Gen.u4Type == AMD64_SEL_TYPE_SYS_INT_GATE)
{
pSelInfo->cbLimit = X86DESC64_BASE(&Desc);
pSelInfo->GCPtrBase = Desc.Gate.u16OffsetLow
| ((uint32_t)Desc.Gate.u16OffsetHigh << 16)
| ((uint64_t)Desc.Gate.u32OffsetTop << 32);
pSelInfo->SelGate = Desc.Gate.u16Sel;
pSelInfo->fFlags |= DBGFSELINFO_FLAGS_GATE;
}
else
{
pSelInfo->cbLimit = 0;
pSelInfo->GCPtrBase = 0;
pSelInfo->SelGate = 0;
pSelInfo->fFlags |= DBGFSELINFO_FLAGS_INVALID;
}
if (!Desc.Gen.u1Present)
pSelInfo->fFlags |= DBGFSELINFO_FLAGS_NOT_PRESENT;
return VINF_SUCCESS;
}
/**
* Worker for selmR3GetSelectorInfo32 and SELMR3GetShadowSelectorInfo that
* interprets a legacy descriptor table entry and fills in the selector info
* structure from it.
*
* @param pSelInfo Where to store the selector info. Only the fFlags and
* Sel members have been initialized.
* @param pDesc The legacy descriptor to parse.
*/
DECLINLINE(void) selmR3SelInfoFromDesc32(PDBGFSELINFO pSelInfo, PCX86DESC pDesc)
{
pSelInfo->u.Raw64.au64[1] = 0;
pSelInfo->u.Raw = *pDesc;
if ( pDesc->Gen.u1DescType
|| !(pDesc->Gen.u4Type & 4))
{
pSelInfo->cbLimit = X86DESC_LIMIT_G(pDesc);
pSelInfo->GCPtrBase = X86DESC_BASE(pDesc);
pSelInfo->SelGate = 0;
}
else if (pDesc->Gen.u4Type != X86_SEL_TYPE_SYS_UNDEFINED4)
{
pSelInfo->cbLimit = 0;
if (pDesc->Gen.u4Type == X86_SEL_TYPE_SYS_TASK_GATE)
pSelInfo->GCPtrBase = 0;
else
pSelInfo->GCPtrBase = pDesc->Gate.u16OffsetLow
| (uint32_t)pDesc->Gate.u16OffsetHigh << 16;
pSelInfo->SelGate = pDesc->Gate.u16Sel;
pSelInfo->fFlags |= DBGFSELINFO_FLAGS_GATE;
}
else
{
pSelInfo->cbLimit = 0;
pSelInfo->GCPtrBase = 0;
pSelInfo->SelGate = 0;
pSelInfo->fFlags |= DBGFSELINFO_FLAGS_INVALID;
}
if (!pDesc->Gen.u1Present)
pSelInfo->fFlags |= DBGFSELINFO_FLAGS_NOT_PRESENT;
}
/**
* Gets information about a 64-bit selector, SELMR3GetSelectorInfo helper.
*
* See SELMR3GetSelectorInfo for details.
*
* @returns VBox status code, see SELMR3GetSelectorInfo for details.
*
* @param pVM The cross context VM structure.
* @param pVCpu The cross context virtual CPU structure.
* @param Sel The selector to get info about.
* @param pSelInfo Where to store the information.
*/
static int selmR3GetSelectorInfo32(PVM pVM, PVMCPU pVCpu, RTSEL Sel, PDBGFSELINFO pSelInfo)
{
/*
* Read the descriptor entry
*/
pSelInfo->fFlags = 0;
X86DESC Desc;
if ( !(Sel & X86_SEL_LDT)
&& ( pVM->selm.s.aHyperSel[SELM_HYPER_SEL_CS] == (Sel & X86_SEL_RPL_LDT)
|| pVM->selm.s.aHyperSel[SELM_HYPER_SEL_DS] == (Sel & X86_SEL_RPL_LDT)
|| pVM->selm.s.aHyperSel[SELM_HYPER_SEL_CS64] == (Sel & X86_SEL_RPL_LDT)
|| pVM->selm.s.aHyperSel[SELM_HYPER_SEL_TSS] == (Sel & X86_SEL_RPL_LDT)
|| pVM->selm.s.aHyperSel[SELM_HYPER_SEL_TSS_TRAP08] == (Sel & X86_SEL_RPL_LDT))
)
{
/*
* Hypervisor descriptor.
*/
pSelInfo->fFlags = DBGFSELINFO_FLAGS_HYPER;
if (CPUMIsGuestInProtectedMode(pVCpu))
pSelInfo->fFlags |= DBGFSELINFO_FLAGS_PROT_MODE;
else
pSelInfo->fFlags |= DBGFSELINFO_FLAGS_REAL_MODE;
Desc = pVM->selm.s.paGdtR3[Sel >> X86_SEL_SHIFT];
}
else if (CPUMIsGuestInProtectedMode(pVCpu))
{
/*
* Read it from the guest descriptor table.
*/
pSelInfo->fFlags = DBGFSELINFO_FLAGS_PROT_MODE;
RTGCPTR GCPtrDesc;
if (!(Sel & X86_SEL_LDT))
{
/* GDT */
VBOXGDTR Gdtr;
CPUMGetGuestGDTR(pVCpu, &Gdtr);
if ((Sel | X86_SEL_RPL_LDT) > Gdtr.cbGdt)
return VERR_INVALID_SELECTOR;
GCPtrDesc = Gdtr.pGdt + (Sel & X86_SEL_MASK);
}
else
{
/* LDT */
uint64_t GCPtrBase;
uint32_t cbLimit;
CPUMGetGuestLdtrEx(pVCpu, &GCPtrBase, &cbLimit);
if ((Sel | X86_SEL_RPL_LDT) > cbLimit)
return VERR_INVALID_SELECTOR;
/* calc the descriptor location. */
GCPtrDesc = GCPtrBase + (Sel & X86_SEL_MASK);
}
/* read the descriptor. */
int rc = PGMPhysSimpleReadGCPtr(pVCpu, &Desc, GCPtrDesc, sizeof(Desc));
if (RT_FAILURE(rc))
return rc;
}
else
{
/*
* We're in real mode.
*/
pSelInfo->Sel = Sel;
pSelInfo->GCPtrBase = Sel << 4;
pSelInfo->cbLimit = 0xffff;
pSelInfo->fFlags = DBGFSELINFO_FLAGS_REAL_MODE;
pSelInfo->u.Raw64.au64[0] = 0;
pSelInfo->u.Raw64.au64[1] = 0;
pSelInfo->SelGate = 0;
return VINF_SUCCESS;
}
/*
* Extract the base and limit or sel:offset for gates.
*/
pSelInfo->Sel = Sel;
selmR3SelInfoFromDesc32(pSelInfo, &Desc);
return VINF_SUCCESS;
}
/**
* Gets information about a selector.
*
* Intended for the debugger mostly and will prefer the guest descriptor tables
* over the shadow ones.
*
* @retval VINF_SUCCESS on success.
* @retval VERR_INVALID_SELECTOR if the selector isn't fully inside the
* descriptor table.
* @retval VERR_SELECTOR_NOT_PRESENT if the LDT is invalid or not present. This
* is not returned if the selector itself isn't present, you have to
* check that for yourself (see DBGFSELINFO::fFlags).
* @retval VERR_PAGE_TABLE_NOT_PRESENT or VERR_PAGE_NOT_PRESENT if the
* pagetable or page backing the selector table wasn't present.
* @returns Other VBox status code on other errors.
*
* @param pVM The cross context VM structure.
* @param pVCpu The cross context virtual CPU structure.
* @param Sel The selector to get info about.
* @param pSelInfo Where to store the information.
*/
VMMR3DECL(int) SELMR3GetSelectorInfo(PVM pVM, PVMCPU pVCpu, RTSEL Sel, PDBGFSELINFO pSelInfo)
{
AssertPtr(pSelInfo);
if (CPUMIsGuestInLongMode(pVCpu))
return selmR3GetSelectorInfo64(pVCpu, Sel, pSelInfo);
return selmR3GetSelectorInfo32(pVM, pVCpu, Sel, pSelInfo);
}
/**
* Gets information about a selector from the shadow tables.
*
* This is intended to be faster than the SELMR3GetSelectorInfo() method, but
* requires that the caller ensures that the shadow tables are up to date.
*
* @retval VINF_SUCCESS on success.
* @retval VERR_INVALID_SELECTOR if the selector isn't fully inside the
* descriptor table.
* @retval VERR_SELECTOR_NOT_PRESENT if the LDT is invalid or not present. This
* is not returned if the selector itself isn't present, you have to
* check that for yourself (see DBGFSELINFO::fFlags).
* @retval VERR_PAGE_TABLE_NOT_PRESENT or VERR_PAGE_NOT_PRESENT if the
* pagetable or page backing the selector table wasn't present.
* @returns Other VBox status code on other errors.
*
* @param pVM The cross context VM structure.
* @param Sel The selector to get info about.
* @param pSelInfo Where to store the information.
*
* @remarks Don't use this when in hardware assisted virtualization mode.
*/
VMMR3DECL(int) SELMR3GetShadowSelectorInfo(PVM pVM, RTSEL Sel, PDBGFSELINFO pSelInfo)
{
Assert(pSelInfo);
/*
* Read the descriptor entry
*/
X86DESC Desc;
if (!(Sel & X86_SEL_LDT))
{
/*
* Global descriptor.
*/
Desc = pVM->selm.s.paGdtR3[Sel >> X86_SEL_SHIFT];
pSelInfo->fFlags = pVM->selm.s.aHyperSel[SELM_HYPER_SEL_CS] == (Sel & X86_SEL_MASK_OFF_RPL)
|| pVM->selm.s.aHyperSel[SELM_HYPER_SEL_DS] == (Sel & X86_SEL_MASK_OFF_RPL)
|| pVM->selm.s.aHyperSel[SELM_HYPER_SEL_CS64] == (Sel & X86_SEL_MASK_OFF_RPL)
|| pVM->selm.s.aHyperSel[SELM_HYPER_SEL_TSS] == (Sel & X86_SEL_MASK_OFF_RPL)
|| pVM->selm.s.aHyperSel[SELM_HYPER_SEL_TSS_TRAP08] == (Sel & X86_SEL_MASK_OFF_RPL)
? DBGFSELINFO_FLAGS_HYPER
: 0;
/** @todo check that the GDT offset is valid. */
}
else
{
/*
* Local Descriptor.
*/
PX86DESC paLDT = (PX86DESC)((char *)pVM->selm.s.pvLdtR3 + pVM->selm.s.offLdtHyper);
Desc = paLDT[Sel >> X86_SEL_SHIFT];
/** @todo check if the LDT page is actually available. */
/** @todo check that the LDT offset is valid. */
pSelInfo->fFlags = 0;
}
if (CPUMIsGuestInProtectedMode(VMMGetCpu0(pVM)))
pSelInfo->fFlags |= DBGFSELINFO_FLAGS_PROT_MODE;
else
pSelInfo->fFlags |= DBGFSELINFO_FLAGS_REAL_MODE;
/*
* Extract the base and limit or sel:offset for gates.
*/
pSelInfo->Sel = Sel;
selmR3SelInfoFromDesc32(pSelInfo, &Desc);
return VINF_SUCCESS;
}
/**
* Formats a descriptor.
*
* @param Desc Descriptor to format.
* @param Sel Selector number.
* @param pszOutput Output buffer.
* @param cchOutput Size of output buffer.
*/
static void selmR3FormatDescriptor(X86DESC Desc, RTSEL Sel, char *pszOutput, size_t cchOutput)
{
/*
* Make variable description string.
*/
static struct
{
unsigned cch;
const char *psz;
} const aTypes[32] =
{
#define STRENTRY(str) { sizeof(str) - 1, str }
/* system */
STRENTRY("Reserved0 "), /* 0x00 */
STRENTRY("TSS16Avail "), /* 0x01 */
STRENTRY("LDT "), /* 0x02 */
STRENTRY("TSS16Busy "), /* 0x03 */
STRENTRY("Call16 "), /* 0x04 */
STRENTRY("Task "), /* 0x05 */
STRENTRY("Int16 "), /* 0x06 */
STRENTRY("Trap16 "), /* 0x07 */
STRENTRY("Reserved8 "), /* 0x08 */
STRENTRY("TSS32Avail "), /* 0x09 */
STRENTRY("ReservedA "), /* 0x0a */
STRENTRY("TSS32Busy "), /* 0x0b */
STRENTRY("Call32 "), /* 0x0c */
STRENTRY("ReservedD "), /* 0x0d */
STRENTRY("Int32 "), /* 0x0e */
STRENTRY("Trap32 "), /* 0x0f */
/* non system */
STRENTRY("DataRO "), /* 0x10 */
STRENTRY("DataRO Accessed "), /* 0x11 */
STRENTRY("DataRW "), /* 0x12 */
STRENTRY("DataRW Accessed "), /* 0x13 */
STRENTRY("DataDownRO "), /* 0x14 */
STRENTRY("DataDownRO Accessed "), /* 0x15 */
STRENTRY("DataDownRW "), /* 0x16 */
STRENTRY("DataDownRW Accessed "), /* 0x17 */
STRENTRY("CodeEO "), /* 0x18 */
STRENTRY("CodeEO Accessed "), /* 0x19 */
STRENTRY("CodeER "), /* 0x1a */
STRENTRY("CodeER Accessed "), /* 0x1b */
STRENTRY("CodeConfEO "), /* 0x1c */
STRENTRY("CodeConfEO Accessed "), /* 0x1d */
STRENTRY("CodeConfER "), /* 0x1e */
STRENTRY("CodeConfER Accessed ") /* 0x1f */
#undef SYSENTRY
};
#define ADD_STR(psz, pszAdd) do { strcpy(psz, pszAdd); psz += strlen(pszAdd); } while (0)
char szMsg[128];
char *psz = &szMsg[0];
unsigned i = Desc.Gen.u1DescType << 4 | Desc.Gen.u4Type;
memcpy(psz, aTypes[i].psz, aTypes[i].cch);
psz += aTypes[i].cch;
if (Desc.Gen.u1Present)
ADD_STR(psz, "Present ");
else
ADD_STR(psz, "Not-Present ");
if (Desc.Gen.u1Granularity)
ADD_STR(psz, "Page ");
if (Desc.Gen.u1DefBig)
ADD_STR(psz, "32-bit ");
else
ADD_STR(psz, "16-bit ");
#undef ADD_STR
*psz = '\0';
/*
* Limit and Base and format the output.
*/
uint32_t u32Limit = X86DESC_LIMIT_G(&Desc);
uint32_t u32Base = X86DESC_BASE(&Desc);
RTStrPrintf(pszOutput, cchOutput, "%04x - %08x %08x - base=%08x limit=%08x dpl=%d %s",
Sel, Desc.au32[0], Desc.au32[1], u32Base, u32Limit, Desc.Gen.u2Dpl, szMsg);
}
/**
* Dumps a descriptor.
*
* @param Desc Descriptor to dump.
* @param Sel Selector number.
* @param pszMsg Message to prepend the log entry with.
*/
VMMR3DECL(void) SELMR3DumpDescriptor(X86DESC Desc, RTSEL Sel, const char *pszMsg)
{
#ifdef LOG_ENABLED
if (LogIsEnabled())
{
char szOutput[128];
selmR3FormatDescriptor(Desc, Sel, &szOutput[0], sizeof(szOutput));
Log(("%s: %s\n", pszMsg, szOutput));
}
#else
RT_NOREF3(Desc, Sel, pszMsg);
#endif
}
/**
* Display the shadow gdt.
*
* @param pVM The cross context VM structure.
* @param pHlp The info helpers.
* @param pszArgs Arguments, ignored.
*/
static DECLCALLBACK(void) selmR3InfoGdt(PVM pVM, PCDBGFINFOHLP pHlp, const char *pszArgs)
{
NOREF(pszArgs);
pHlp->pfnPrintf(pHlp, "Shadow GDT (GCAddr=%RRv):\n", MMHyperR3ToRC(pVM, pVM->selm.s.paGdtR3));
for (unsigned iGDT = 0; iGDT < SELM_GDT_ELEMENTS; iGDT++)
{
if (pVM->selm.s.paGdtR3[iGDT].Gen.u1Present)
{
char szOutput[128];
selmR3FormatDescriptor(pVM->selm.s.paGdtR3[iGDT], iGDT << X86_SEL_SHIFT, &szOutput[0], sizeof(szOutput));
const char *psz = "";
if (iGDT == ((unsigned)pVM->selm.s.aHyperSel[SELM_HYPER_SEL_CS] >> X86_SEL_SHIFT))
psz = " HyperCS";
else if (iGDT == ((unsigned)pVM->selm.s.aHyperSel[SELM_HYPER_SEL_DS] >> X86_SEL_SHIFT))
psz = " HyperDS";
else if (iGDT == ((unsigned)pVM->selm.s.aHyperSel[SELM_HYPER_SEL_CS64] >> X86_SEL_SHIFT))
psz = " HyperCS64";
else if (iGDT == ((unsigned)pVM->selm.s.aHyperSel[SELM_HYPER_SEL_TSS] >> X86_SEL_SHIFT))
psz = " HyperTSS";
else if (iGDT == ((unsigned)pVM->selm.s.aHyperSel[SELM_HYPER_SEL_TSS_TRAP08] >> X86_SEL_SHIFT))
psz = " HyperTSSTrap08";
pHlp->pfnPrintf(pHlp, "%s%s\n", szOutput, psz);
}
}
}
/**
* Display the guest gdt.
*
* @param pVM The cross context VM structure.
* @param pHlp The info helpers.
* @param pszArgs Arguments, ignored.
*/
static DECLCALLBACK(void) selmR3InfoGdtGuest(PVM pVM, PCDBGFINFOHLP pHlp, const char *pszArgs)
{
/** @todo SMP support! */
PVMCPU pVCpu = &pVM->aCpus[0];
VBOXGDTR GDTR;
CPUMGetGuestGDTR(pVCpu, &GDTR);
RTGCPTR GCPtrGDT = GDTR.pGdt;
unsigned cGDTs = ((unsigned)GDTR.cbGdt + 1) / sizeof(X86DESC);
pHlp->pfnPrintf(pHlp, "Guest GDT (GCAddr=%RGv limit=%x):\n", GCPtrGDT, GDTR.cbGdt);
for (unsigned iGDT = 0; iGDT < cGDTs; iGDT++, GCPtrGDT += sizeof(X86DESC))
{
X86DESC GDTE;
int rc = PGMPhysSimpleReadGCPtr(pVCpu, &GDTE, GCPtrGDT, sizeof(GDTE));
if (RT_SUCCESS(rc))
{
if (GDTE.Gen.u1Present)
{
char szOutput[128];
selmR3FormatDescriptor(GDTE, iGDT << X86_SEL_SHIFT, &szOutput[0], sizeof(szOutput));
pHlp->pfnPrintf(pHlp, "%s\n", szOutput);
}
}
else if (rc == VERR_PAGE_NOT_PRESENT)
{
if ((GCPtrGDT & PAGE_OFFSET_MASK) + sizeof(X86DESC) - 1 < sizeof(X86DESC))
pHlp->pfnPrintf(pHlp, "%04x - page not present (GCAddr=%RGv)\n", iGDT << X86_SEL_SHIFT, GCPtrGDT);
}
else
pHlp->pfnPrintf(pHlp, "%04x - read error rc=%Rrc GCAddr=%RGv\n", iGDT << X86_SEL_SHIFT, rc, GCPtrGDT);
}
NOREF(pszArgs);
}
/**
* Display the shadow ldt.
*
* @param pVM The cross context VM structure.
* @param pHlp The info helpers.
* @param pszArgs Arguments, ignored.
*/
static DECLCALLBACK(void) selmR3InfoLdt(PVM pVM, PCDBGFINFOHLP pHlp, const char *pszArgs)
{
unsigned cLDTs = ((unsigned)pVM->selm.s.cbLdtLimit + 1) >> X86_SEL_SHIFT;
PX86DESC paLDT = (PX86DESC)((char *)pVM->selm.s.pvLdtR3 + pVM->selm.s.offLdtHyper);
pHlp->pfnPrintf(pHlp, "Shadow LDT (GCAddr=%RRv limit=%#x):\n", pVM->selm.s.pvLdtRC + pVM->selm.s.offLdtHyper, pVM->selm.s.cbLdtLimit);
for (unsigned iLDT = 0; iLDT < cLDTs; iLDT++)
{
if (paLDT[iLDT].Gen.u1Present)
{
char szOutput[128];
selmR3FormatDescriptor(paLDT[iLDT], (iLDT << X86_SEL_SHIFT) | X86_SEL_LDT, &szOutput[0], sizeof(szOutput));
pHlp->pfnPrintf(pHlp, "%s\n", szOutput);
}
}
NOREF(pszArgs);
}
/**
* Display the guest ldt.
*
* @param pVM The cross context VM structure.
* @param pHlp The info helpers.
* @param pszArgs Arguments, ignored.
*/
static DECLCALLBACK(void) selmR3InfoLdtGuest(PVM pVM, PCDBGFINFOHLP pHlp, const char *pszArgs)
{
/** @todo SMP support! */
PVMCPU pVCpu = &pVM->aCpus[0];
uint64_t GCPtrLdt;
uint32_t cbLdt;
RTSEL SelLdt = CPUMGetGuestLdtrEx(pVCpu, &GCPtrLdt, &cbLdt);
if (!(SelLdt & X86_SEL_MASK_OFF_RPL))
{
pHlp->pfnPrintf(pHlp, "Guest LDT (Sel=%x): Null-Selector\n", SelLdt);
return;
}
pHlp->pfnPrintf(pHlp, "Guest LDT (Sel=%x GCAddr=%RX64 limit=%x):\n", SelLdt, GCPtrLdt, cbLdt);
unsigned cLdts = (cbLdt + 1) >> X86_SEL_SHIFT;
for (unsigned iLdt = 0; iLdt < cLdts; iLdt++, GCPtrLdt += sizeof(X86DESC))
{
X86DESC LdtE;
int rc = PGMPhysSimpleReadGCPtr(pVCpu, &LdtE, GCPtrLdt, sizeof(LdtE));
if (RT_SUCCESS(rc))
{
if (LdtE.Gen.u1Present)
{
char szOutput[128];
selmR3FormatDescriptor(LdtE, (iLdt << X86_SEL_SHIFT) | X86_SEL_LDT, &szOutput[0], sizeof(szOutput));
pHlp->pfnPrintf(pHlp, "%s\n", szOutput);
}
}
else if (rc == VERR_PAGE_NOT_PRESENT)
{
if ((GCPtrLdt & PAGE_OFFSET_MASK) + sizeof(X86DESC) - 1 < sizeof(X86DESC))
pHlp->pfnPrintf(pHlp, "%04x - page not present (GCAddr=%RGv)\n", (iLdt << X86_SEL_SHIFT) | X86_SEL_LDT, GCPtrLdt);
}
else
pHlp->pfnPrintf(pHlp, "%04x - read error rc=%Rrc GCAddr=%RGv\n", (iLdt << X86_SEL_SHIFT) | X86_SEL_LDT, rc, GCPtrLdt);
}
NOREF(pszArgs);
}
/**
* Dumps the hypervisor GDT
*
* @param pVM The cross context VM structure.
*/
VMMR3DECL(void) SELMR3DumpHyperGDT(PVM pVM)
{
DBGFR3Info(pVM->pUVM, "gdt", NULL, NULL);
}
/**
* Dumps the hypervisor LDT
*
* @param pVM The cross context VM structure.
*/
VMMR3DECL(void) SELMR3DumpHyperLDT(PVM pVM)
{
DBGFR3Info(pVM->pUVM, "ldt", NULL, NULL);
}
/**
* Dumps the guest GDT
*
* @param pVM The cross context VM structure.
*/
VMMR3DECL(void) SELMR3DumpGuestGDT(PVM pVM)
{
DBGFR3Info(pVM->pUVM, "gdtguest", NULL, NULL);
}
/**
* Dumps the guest LDT
*
* @param pVM The cross context VM structure.
*/
VMMR3DECL(void) SELMR3DumpGuestLDT(PVM pVM)
{
DBGFR3Info(pVM->pUVM, "ldtguest", NULL, NULL);
}
| 40.533873 | 219 | 0.592079 | roughk |
6ac965233eea4057c8273f19e84aafb719c7c993 | 8,132 | cpp | C++ | src/entity/RDimRotatedData.cpp | ouxianghui/ezcam | 195fb402202442b6d035bd70853f2d8c3f615de1 | [
"MIT"
] | 12 | 2021-03-26T03:23:30.000Z | 2021-12-31T10:05:44.000Z | src/entity/RDimRotatedData.cpp | 15831944/ezcam | 195fb402202442b6d035bd70853f2d8c3f615de1 | [
"MIT"
] | null | null | null | src/entity/RDimRotatedData.cpp | 15831944/ezcam | 195fb402202442b6d035bd70853f2d8c3f615de1 | [
"MIT"
] | 9 | 2021-06-23T08:26:40.000Z | 2022-01-20T07:18:10.000Z | /**
* Copyright (c) 2011-2016 by Andrew Mustun. All rights reserved.
*
* This file is part of the QCAD project.
*
* QCAD 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.
*
* QCAD 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 QCAD.
*/
#include "RDimRotatedData.h"
#include "RUnit.h"
RDimRotatedData::RDimRotatedData() : rotation(0.0) {
}
RDimRotatedData::RDimRotatedData(RDocument* document, const RDimRotatedData& data)
: RDimLinearData(document) {
*this = data;
this->document = document;
if (document!=NULL) {
linetypeId = document->getLinetypeByLayerId();
}
}
/**
* \param extensionPoint1 Definition point. Startpoint of the
* first extension line.
* \param extensionPoint2 Definition point. Startpoint of the
* second extension line.
*/
RDimRotatedData::RDimRotatedData(const RDimensionData& dimData,
const RVector& extensionPoint1,
const RVector& extensionPoint2,
double rotation)
: RDimLinearData(dimData, extensionPoint1, extensionPoint2),
rotation(rotation) {
}
RBox RDimRotatedData::getBoundingBox(bool ignoreEmpty) const {
boundingBox = RDimensionData::getBoundingBox(ignoreEmpty);
if (!hasDimensionBlockReference()) {
boundingBox.growToInclude(extensionPoint1);
boundingBox.growToInclude(extensionPoint2);
}
return boundingBox;
}
bool RDimRotatedData::isValid() const {
return RDimLinearData::isValid() && RMath::isNormal(rotation);
}
QList<RRefPoint> RDimRotatedData::getReferencePoints(RS::ProjectionRenderingHint hint) const {
QList<RRefPoint> ret = RDimLinearData::getReferencePoints(hint);
ret.append(extensionPoint1);
ret.append(extensionPoint2);
return ret;
}
bool RDimRotatedData::moveReferencePoint(const RVector& referencePoint, const RVector& targetPoint) {
// if definition point and extension points are on one line,
// move the extension points together with the definition point:
bool moveExtensionPoints = false;
if (referencePoint.equalsFuzzy(definitionPoint)) {
if (RLine(extensionPoint1, extensionPoint2).isOnShape(definitionPoint, false)) {
moveExtensionPoints = true;
}
}
bool ret = RDimLinearData::moveReferencePoint(referencePoint, targetPoint);
if (moveExtensionPoints) {
// move extension points with definition point:
RVector dir = RVector::createPolar(1.0, rotation);
RLine dimLine = RLine(targetPoint, targetPoint + dir);
extensionPoint1 = dimLine.getClosestPointOnShape(extensionPoint1, false);
extensionPoint2 = dimLine.getClosestPointOnShape(extensionPoint2, false);
definitionPoint = RVector::getAverage(extensionPoint1, extensionPoint2);
//recomputeDefinitionPoint(referencePoint, targetPoint);
}
return ret;
}
QList<RVector> RDimRotatedData::getDimPoints() const {
QList<RVector> ret;
RVector dirDim = RVector::createPolar(1.0, rotation);
// construction line for dimension line
RLine dimLine(definitionPoint, definitionPoint + dirDim);
ret.append(dimLine.getClosestPointOnShape(extensionPoint1, false));
ret.append(dimLine.getClosestPointOnShape(extensionPoint2, false));
return ret;
}
/**
* Recompute definition point if extension point(s) have changed.
*/
void RDimRotatedData::recomputeDefinitionPoint(
const RVector& oldExtPoint1, const RVector& oldExtPoint2,
const RVector& newExtPoint1, const RVector& newExtPoint2) {
Q_UNUSED(oldExtPoint1)
Q_UNUSED(oldExtPoint2)
Q_UNUSED(newExtPoint2)
RVector dirDim = RVector::createPolar(1.0, rotation);
// construction line for dimension line
RLine dimLine(definitionPoint, definitionPoint + dirDim);
RVector dimP1 = dimLine.getClosestPointOnShape(newExtPoint1, false);
RVector dimP2 = dimLine.getClosestPointOnShape(newExtPoint2, false);
// make sure the dimension line is movable if dimension point == extension point
if (dimP1.equalsFuzzy(newExtPoint1) || dimP1.equalsFuzzy(newExtPoint2)) {
dimP1 = RVector::getAverage(dimP1, dimP2);
}
if (dimP1.isValid()) {
definitionPoint = dimP1;
}
}
/**
* Recompute definition point if
*/
//void RDimRotatedData::recomputeDefinitionPoint(const RVector& oldDimLineGrip, const RVector& newDimLineGrip) {
// Q_UNUSED(oldDimLineGrip)
// RVector extDir = RVector::createPolar(1.0, rotation);
// // construction line for dimension line
// RLine extLine1(extensionPoint1, extensionPoint1 + extDir);
// RVector dimP1 = extLine1.getClosestPointOnShape(newDimLineGrip, false);
// if (dimP1.isValid()) {
// definitionPoint = dimP1;
// }
//}
bool RDimRotatedData::rotate(double rotation, const RVector& center) {
RDimLinearData::rotate(rotation, center);
//extensionPoint1.rotate(rotation, center);
//extensionPoint2.rotate(rotation, center);
this->rotation = RMath::getNormalizedAngle(this->rotation+rotation);
update();
return true;
}
bool RDimRotatedData::mirror(const RLine& axis) {
RDimLinearData::mirror(axis);
//extensionPoint1.mirror(axis);
//extensionPoint2.mirror(axis);
RLine neutralAxis = axis;
neutralAxis.move(-neutralAxis.getStartPoint());
RVector vec = RVector::createPolar(1.0, rotation);
vec.mirror(neutralAxis);
rotation = vec.getAngle();
update();
return true;
}
QList<QSharedPointer<RShape> > RDimRotatedData::getShapes(const RBox& queryBox, bool ignoreComplex) const {
Q_UNUSED(queryBox)
Q_UNUSED(ignoreComplex)
QSharedPointer<RBlockReferenceEntity> dimBlockReference = getDimensionBlockReference();
if (!dimBlockReference.isNull()) {
// QList<QSharedPointer<RShape> > sps = dimBlockReference->getShapes(queryBox, ignoreComplex);
// for (int i=0; i<sps.length(); i++) {
// qDebug() << "getShapes: from block ref" << *sps.at(i);
// }
return dimBlockReference->getShapes(queryBox, ignoreComplex);
}
QList<QSharedPointer<RShape> > ret;
double dimexo = getDimexo();
double dimexe = getDimexe();
QList<RVector> l = getDimPoints();
RVector dimP1 = l.at(0);
RVector dimP2 = l.at(1);
// definitive dimension line:
ret += getDimensionLineShapes(dimP1, dimP2, true, true);
// extension lines:
RVector vDimexo1, vDimexe1, vDimexo2, vDimexe2;
if (!extensionPoint1.equalsFuzzy(dimP1)) {
double a1 = extensionPoint1.getAngleTo(dimP1);
vDimexe1.setPolar(dimexe, a1);
vDimexo1.setPolar(dimexo, a1);
RLine line(extensionPoint1+vDimexo1, dimP1+vDimexe1);
ret.append(QSharedPointer<RLine>(new RLine(line)));
}
if (!extensionPoint2.equalsFuzzy(dimP2)) {
double a2 = extensionPoint2.getAngleTo(dimP2);
vDimexe2.setPolar(dimexe, a2);
vDimexo2.setPolar(dimexo, a2);
RLine line(extensionPoint2+vDimexo2, dimP2+vDimexe2);
ret.append(QSharedPointer<RLine>(new RLine(line)));
}
return ret;
}
double RDimRotatedData::getMeasuredValue() const {
// direction of dimension line
RVector dirDim;
dirDim.setPolar(1.0, rotation);
RLine dimLine(definitionPoint, definitionPoint + dirDim);
RVector dimP1 = dimLine.getClosestPointOnShape(extensionPoint1, false);
RVector dimP2 = dimLine.getClosestPointOnShape(extensionPoint2, false);
// Definitive dimension line:
return dimP1.getDistanceTo(dimP2);
}
QString RDimRotatedData::getAutoLabel() const {
double distance = getMeasuredValue();
distance *= linearFactor;
return formatLabel(distance);
}
| 32.790323 | 112 | 0.704624 | ouxianghui |
6aca79894399faf0e51e287fba0621118c79a152 | 13,793 | cpp | C++ | test/cilk/test_sort.cpp | sawansib/Sniper | 45ec1eeb09b81a7250bc1a1aaa452f16b2b7f497 | [
"MIT"
] | 1 | 2021-04-22T05:27:08.000Z | 2021-04-22T05:27:08.000Z | test/cilk/test_sort.cpp | sawansib/SNIPER | 45ec1eeb09b81a7250bc1a1aaa452f16b2b7f497 | [
"MIT"
] | null | null | null | test/cilk/test_sort.cpp | sawansib/SNIPER | 45ec1eeb09b81a7250bc1a1aaa452f16b2b7f497 | [
"MIT"
] | null | null | null | /* test_sort.cpp -*-C++-*-
*
*************************************************************************
*
* Copyright (C) 2012 Intel Corporation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Intel Corporation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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.
*************************************************************************/
#define NOMINMAX
#define _CRT_SECURE_NO_WARNINGS
#define _SCL_SECURE_NO_WARNINGS
#include "sort.h" /* Put header to be tested first to improve odds of detecting missing header. */
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cassert>
#include <cmath>
#include <string>
#include <cilk/cilk.h>
#include <cilk/reducer_opadd.h>
#include <cilk/cilk_api.h>
#include "cilktest_harness.h"
#include "cilktest_timing.h"
#include "sim_api.h"
unsigned Random() {
return rand()*(RAND_MAX+1u)+rand();
}
enum TEST_MODE {
CHECK_STABILITY = 1,
EXPONENTIAL_DISTRIBUTION = 2,
UNIFORM_DISTRIBUTION = 3,
STRING_KEY = 4
};
template <int MODE>
struct ModeTypes {
static const char* SequenceName; // Full, lengthy name.
static const char* SequenceNameShort; // Shorter name, read in by performance testing scripts.
};
template <>
const char* ModeTypes<CHECK_STABILITY>::SequenceName = "stability_check_uniform distribution of (char,int)";
template <>
const char* ModeTypes<CHECK_STABILITY>::SequenceNameShort = "stability_check";
template <>
const char* ModeTypes<EXPONENTIAL_DISTRIBUTION>::SequenceName = "exponential distribution of double";
template <>
const char* ModeTypes<EXPONENTIAL_DISTRIBUTION>::SequenceNameShort = "exponential_double";
template <>
const char* ModeTypes<UNIFORM_DISTRIBUTION>::SequenceName = "uniform distribution of int";
template <>
const char* ModeTypes<UNIFORM_DISTRIBUTION>::SequenceNameShort = "uniform_int";
template <>
const char* ModeTypes<STRING_KEY>::SequenceName = "strings";
template <>
const char* ModeTypes<STRING_KEY>::SequenceNameShort = "strings";
// Test that checks stability of sort and checks for construct/assign/destruct errors
cilk::reducer_opadd<int> KeyCount;
/// Data type used to check stability of the sort.
class StableCheckT {
char value;
size_t index;
StableCheckT* self;
StableCheckT( int value_, size_t index_ )
: value(value_&0xF), index(index_), self(this) {++KeyCount;}
public:
friend bool operator<( const StableCheckT& x,
const StableCheckT& y ) {
return x.value<y.value;
}
// Function to call to fill in index with a "random" value.
static StableCheckT get_random_t( size_t index ) {
return StableCheckT(rand(), index);
}
friend int IndexOf( const StableCheckT& x ) {
assert(x.self==&x);
return x.index;
}
StableCheckT() : self(this) {
++KeyCount;
}
StableCheckT( const StableCheckT& x ) : value(x.value), index(x.index), self(this) {
assert(x.self==&x);
++KeyCount;
}
void operator=( const StableCheckT& x ) {
assert( self==this );
assert( x.self==&x );
value = x.value;
index = x.index;
}
~StableCheckT() {
assert(self==this);
--KeyCount;
self = NULL;
}
};
// Used to flip between two signatures for sort
static unsigned Chooser;
// Class that defines the various sorts we want to test on a
// particular data-type T.
template <typename T>
class Sorter {
public:
// Class that defines random-access iterator
class iter: public std::iterator<std::random_access_iterator_tag,T> {
T* m_ptr;
public:
explicit iter(T* ptr) : m_ptr(ptr) {}
friend ptrdiff_t operator-( iter i, iter j ) {return i.m_ptr-j.m_ptr;}
friend iter operator-( iter i, ptrdiff_t j ) {return iter(i.m_ptr-j);}
friend iter operator+( iter i, ptrdiff_t j ) {return iter(i.m_ptr+j);}
friend bool operator<( iter i, iter j ) {return i.m_ptr<j.m_ptr;}
friend bool operator==( iter i, iter j ) {return i.m_ptr==j.m_ptr;}
friend bool operator!=( iter i, iter j ) {return i.m_ptr!=j.m_ptr;}
T& operator*() const {return *m_ptr;}
T& operator[]( ptrdiff_t j ) const {return m_ptr[j];}
iter operator--() {--m_ptr; return *this;}
iter operator++() {++m_ptr; return *this;}
iter operator--(int) {return iter(m_ptr--);}
iter operator++(int) {return iter(m_ptr++);}
iter operator+=( ptrdiff_t j ) {m_ptr+=j; return *this;}
};
static void stl_sort( T* first, T* last ) {
std::sort(first,last);
}
static void cilk_quicksort ( T* first, T* last ) {
if( Chooser++&1 )
cilkpub::cilk_sort_in_place(iter(first),iter(last));
else
cilkpub::cilk_sort_in_place(first,last,std::less<T>());
}
static void cilk_samplesort ( T* first, T* last ) {
if( Chooser++&1 )
cilkpub::cilk_sort(iter(first),iter(last));
else
cilkpub::cilk_sort(first,last,std::less<T>());
}
};
template <typename T, int MODE>
struct TestData {
size_t M;
size_t N;
T *Unsorted;
T *Expected;
T *Actual;
// Construct the test data.
TestData(size_t M_, size_t N_);
// Destroy the data.
~TestData();
// Generate a "random" element for a specified index.
static T MakeRandomT(size_t idx);
};
template <typename T, int MODE>
TestData<T, MODE>::TestData(size_t M_, size_t N_)
: M(M_)
, N(N_)
{
Unsorted = new T[M*N];
Expected = new T[M*N];
Actual = new T[M*N];
for( size_t i=0; i<M; ++i ) {
for( size_t j=0; j<N; ++j ) {
Unsorted[i*N+j] = MakeRandomT(j);
}
std::copy( Unsorted+i*N, Unsorted+(i+1)*N, Expected+i*N );
if( cilkpub::cilk_is_sorted(Expected+i*N, Expected+(i+1)*N) ) {
REPORT("Error for %s: input sequence already sorted\n",ModeTypes<MODE>::SequenceName);
}
std::stable_sort( Expected+i*N, Expected+(i+1)*N );
if( !cilkpub::cilk_is_sorted(Expected+i*N, Expected+(i+1)*N) ) {
REPORT("Error for %s: cilk_is_sorted returned false when it should be true\n",ModeTypes<MODE>::SequenceName);
}
}
}
template <typename T, int MODE>
TestData<T, MODE>::~TestData() {
delete[] Unsorted;
delete[] Expected;
delete[] Actual;
}
template <>
StableCheckT
TestData<StableCheckT, CHECK_STABILITY>::MakeRandomT( size_t idx )
{
return StableCheckT::get_random_t(idx);
}
template <>
double
TestData<double, EXPONENTIAL_DISTRIBUTION>::MakeRandomT( size_t ) {
return std::log(double(Random()+1));
}
template <>
int
TestData<int, UNIFORM_DISTRIBUTION>::MakeRandomT( size_t ) {
return Random();
}
typedef std::string StringT;
template <>
StringT
TestData<StringT, STRING_KEY>::MakeRandomT( size_t ) {
char buffer[20];
sprintf(buffer,"%d",int(Random()));
return buffer;
}
template <typename S>
void TestSort( TestData<StableCheckT, CHECK_STABILITY>& data,
S sortToBeTested,
const char* what,
bool shouldBeStable=false )
{
unsigned long long t0, t1;
std::copy( data.Unsorted,
data.Unsorted+ data.M * data.N,
data.Actual );
// Warm up run-time
sortToBeTested(data.Actual,
data.Actual + data.N);
t0 = CILKTEST_GETTICKS();
for( size_t i=1; i < data.M; ++i ) {
KeyCount.set_value(0);
sortToBeTested(data.Actual+i*data.N,
data.Actual+(i+1)*data.N);
TEST_ASSERT_EQ(KeyCount.get_value(), 0);
}
t1 = CILKTEST_GETTICKS();
if (!CILKTEST_PERF_RUN()) {
// Check for correctness if we aren't measuring performance.
for( size_t k=0; k< data.M * data.N; ++k ) {
if((data.Actual[k] < data.Expected[k]) ||
(data.Expected[k] < data.Actual[k])) {
REPORT("Error for %s\n", what);
TEST_ASSERT(0);
return;
}
if( shouldBeStable ) {
if( IndexOf(data.Actual[k])!=IndexOf(data.Expected[k]) ) {
REPORT("Stability error for %s\n", what);
TEST_ASSERT(0);
return;
}
}
}
}
CILKTEST_REMARK(2,
"%30s\t%5.2f\n",
what,
(t1-t0) * 1.0e-3);
// If we are executing a performance run, report the time.
if (CILKTEST_PERF_RUN()) {
CILKPUB_PERF_REPORT_TIME(stdout,
what,
__cilkrts_get_nworkers(),
t1 - t0,
ModeTypes<CHECK_STABILITY>::SequenceNameShort,
NULL);
}
}
template<typename S, typename T, int MODE>
void TestSort( TestData<T, MODE>& data,
S sortToBeTested,
const char* what)
{
unsigned long long t0, t1;
std::copy( data.Unsorted,
data.Unsorted+ data.M * data.N,
data.Actual );
// Warm up run-time
sortToBeTested(data.Actual,
data.Actual + data.N);
t0 = CILKTEST_GETTICKS();
SimRoiStart();
SimNamedMarker(1, "begin");
for( size_t i=1; i < data.M; ++i ) {
sortToBeTested(data.Actual+i*data.N,
data.Actual+(i+1)*data.N);
}
// End of Sniper simulation.
SimNamedMarker(2, "end");
SimRoiEnd();
t1 = CILKTEST_GETTICKS();
// Check correctness if we aren't running a performance test.
if (!CILKTEST_PERF_RUN()) {
for( size_t k=0; k< data.M * data.N; ++k ) {
if((data.Actual[k] < data.Expected[k]) ||
(data.Expected[k] < data.Actual[k])) {
REPORT("Error for %s\n",what);
TEST_ASSERT(0);
return;
}
}
}
CILKTEST_REMARK(2,
"%30s\t%5.2f\n",
what,
(t1 - t0) * 1.0e-3);
// If we are executing a performance run, report the time.
if (CILKTEST_PERF_RUN()) {
CILKPUB_PERF_REPORT_TIME(stdout,
what,
__cilkrts_get_nworkers(),
t1 - t0,
ModeTypes<MODE>::SequenceNameShort,
NULL);
}
}
template <typename T, int MODE>
void run_test_sorts(size_t M, size_t N)
{
TestData<T, MODE> data(M, N);
CILKTEST_REMARK(2,
"Testing for %d sorts of length %d for %s\n",
int(data.M-1),
int(data.N),
ModeTypes<MODE>::SequenceName);
// Skip the other sorts.
// // Test the serial sort if we aren't measuring performance, or if
// // P = 1. Otherwise, the serial sort takes too long.
// if (!CILKTEST_PERF_RUN() ||
// (__cilkrts_get_nworkers() == 1)) {
// // Test serial sort
// TestSort(data, Sorter<T>::stl_sort,"STL sort");
// }
// // Test Cilk Plus sorts.
// TestSort(data, Sorter<T>::cilk_quicksort, "Cilk Plus quicksort");
TestSort(data, Sorter<T>::cilk_samplesort, "Cilk Plus samplesort");
}
int main( int argc, char* argv[] ) {
#if 0
// Small defaults for debugging
size_t M = 5;
size_t N = 50;
#else
// Big defaults for timing
size_t M = 2;
// size_t N = 1000000;
size_t N = 10000;
#endif
++M; // Add one for the warmup sort
srand(2);
fprintf(stderr, "Testing sample sort. M=%d, N = %d\n", M, N);
// run_test_sorts<int, UNIFORM_DISTRIBUTION>(M, N);
run_test_sorts<double, EXPONENTIAL_DISTRIBUTION>(M, N);
// run_test_sorts<StringT, STRING_KEY>(M, N);
// run_test_sorts<StableCheckT, CHECK_STABILITY>(M, N);
return 0;
}
| 31.708046 | 122 | 0.575364 | sawansib |
6acfbfd777a1bf81985eb453055ead3ebd08facc | 7,342 | hpp | C++ | SRC/Modules/DJI-Drone-Interface/DroneServer/DroneServer/DroneComms.hpp | parthiv-krishna/Recon | 99e75a9bd02dd6c35061107a5f496c56f0aaecff | [
"BSD-3-Clause"
] | null | null | null | SRC/Modules/DJI-Drone-Interface/DroneServer/DroneServer/DroneComms.hpp | parthiv-krishna/Recon | 99e75a9bd02dd6c35061107a5f496c56f0aaecff | [
"BSD-3-Clause"
] | null | null | null | SRC/Modules/DJI-Drone-Interface/DroneServer/DroneServer/DroneComms.hpp | parthiv-krishna/Recon | 99e75a9bd02dd6c35061107a5f496c56f0aaecff | [
"BSD-3-Clause"
] | null | null | null | #pragma once
//System Includes
#include <vector>
#include <string>
#include <cstdint>
//External Includes
#include <opencv2/opencv.hpp>
//Project Includes
//#include "Drone.hpp" // Circular dependency
#include "DroneDataStructures.h"
namespace DroneInterface {
//Packet for holding binary, serialized packet data
class Packet {
public:
std::vector<uint8_t> m_data; //Buffer containing the full serialized packet
Packet() = default;
~Packet() = default;
void Clear(void);
//Utilities for stream parsing
bool IsFinished(void);
bool BytesNeeded(uint32_t & ByteCount); //Get num bytes needed to finish packet (returns false if more bytes needed before we can answer)
//Packet construction utilities
void AddHeader(uint32_t Size, uint8_t PID); //Take total packet size and PID and add sync, size, and PID fields to m_data
void AddHash(void); //Based on current contents of m_data (which should be fully populated except for the hash field) compute and add hash field
//Packet decoding utilities
bool GetPID(uint8_t & PID) const; //Returns false if not enough data to decode PID
bool CheckHash(void) const; //Returns true if m_data passes hash check and false otherwise
bool CheckHashSizeAndPID(uint8_t PID) const; //Returns true if PID matches, size matches advertised size, and hash is good.
private:
//These fields used only for IsFinished() and BytesNeeded()
bool M_highLevelFieldsValid = false;
uint32_t m_size; //Only valid when M_highLevelFieldsValid = true
uint8_t m_PID; //Only valid when M_highLevelFieldsValid = true
};
//The classes that follow implement packets specified in the ICD. For precise definitions of each field, refer to the ICD
class Packet_CoreTelemetry {
public:
uint8_t IsFlying;
double Latitude;
double Longitude;
double Altitude;
double HAG;
float V_N;
float V_E;
float V_D;
double Yaw;
double Pitch;
double Roll;
Packet_CoreTelemetry() = default;
~Packet_CoreTelemetry() = default;
bool operator==(Packet_CoreTelemetry const & Other) const; //If switching to C++20, default this
void Serialize(Packet & TargetPacket) const; //Populate Packet from fields
bool Deserialize(Packet const & SourcePacket); //Populate fields from Packet
};
class Packet_ExtendedTelemetry {
public:
uint16_t GNSSSatCount;
uint8_t GNSSSignal;
uint8_t MaxHeight;
uint8_t MaxDist;
uint8_t BatLevel;
uint8_t BatWarning;
uint8_t WindLevel;
uint8_t DJICam;
uint8_t FlightMode;
uint16_t MissionID;
std::string DroneSerial;
Packet_ExtendedTelemetry() = default;
~Packet_ExtendedTelemetry() = default;
bool operator==(Packet_ExtendedTelemetry const & Other) const; //If switching to C++20, default this
void Serialize(Packet & TargetPacket) const; //Populate Packet from fields
bool Deserialize(Packet const & SourcePacket); //Populate fields from Packet
};
class Packet_Image {
public:
float TargetFPS;
cv::Mat Frame;
Packet_Image() = default;
~Packet_Image() = default;
bool operator==(Packet_Image const & Other) const; //If switching to C++20, default this
void Serialize(Packet & TargetPacket) const; //Populate Packet from fields
bool Deserialize(Packet const & SourcePacket); //Populate fields from Packet
};
class Packet_Acknowledgment {
public:
uint8_t Positive;
uint8_t SourcePID;
Packet_Acknowledgment() = default;
~Packet_Acknowledgment() = default;
bool operator==(Packet_Acknowledgment const & Other) const; //If switching to C++20, default this
void Serialize(Packet & TargetPacket) const; //Populate Packet from fields
bool Deserialize(Packet const & SourcePacket); //Populate fields from Packet
};
class Packet_MessageString {
public:
uint8_t Type;
std::string Message;
Packet_MessageString() = default;
~Packet_MessageString() = default;
bool operator==(Packet_MessageString const & Other) const; //If switching to C++20, default this
void Serialize(Packet & TargetPacket) const; //Populate Packet from fields
bool Deserialize(Packet const & SourcePacket); //Populate fields from Packet
};
class Packet_EmergencyCommand {
public:
uint8_t Action;
Packet_EmergencyCommand() = default;
~Packet_EmergencyCommand() = default;
bool operator==(Packet_EmergencyCommand const & Other) const; //If switching to C++20, default this
void Serialize(Packet & TargetPacket) const; //Populate Packet from fields
bool Deserialize(Packet const & SourcePacket); //Populate fields from Packet
};
class Packet_CameraControl {
public:
uint8_t Action;
float TargetFPS;
Packet_CameraControl() = default;
~Packet_CameraControl() = default;
bool operator==(Packet_CameraControl const & Other) const; //If switching to C++20, default this
void Serialize(Packet & TargetPacket) const; //Populate Packet from fields
bool Deserialize(Packet const & SourcePacket); //Populate fields from Packet
};
//Note: With this packet we use the existing Waypoint struct from Drone.hpp instead of essentially duplicating it.
//The meanings of the fields of a Waypoint object are defined in Drone.hpp. Since we use radians there and the ICD
//uses degrees for angle fields (to match the DJI API) we must convert when serializing and deserializing.
class Packet_ExecuteWaypointMission {
public:
uint8_t LandAtEnd;
uint8_t CurvedFlight;
std::vector<Waypoint> Waypoints;
Packet_ExecuteWaypointMission() = default;
~Packet_ExecuteWaypointMission() = default;
bool operator==(Packet_ExecuteWaypointMission const & Other) const; //If switching to C++20, default this
void Serialize(Packet & TargetPacket) const; //Populate Packet from fields
bool Deserialize(Packet const & SourcePacket); //Populate fields from Packet
};
class Packet_VirtualStickCommand {
public:
uint8_t Mode;
float Yaw;
float V_x;
float V_y;
float HAG;
float timeout;
Packet_VirtualStickCommand() = default;
~Packet_VirtualStickCommand() = default;
bool operator==(Packet_VirtualStickCommand const & Other) const; //If switching to C++20, default this
void Serialize(Packet & TargetPacket) const; //Populate Packet from fields
bool Deserialize(Packet const & SourcePacket); //Populate fields from Packet
};
//Stream Operators - used to print packet contents in human-readable form
std::ostream & operator<<(std::ostream & Str, Packet_CoreTelemetry const & v);
std::ostream & operator<<(std::ostream & Str, Packet_ExtendedTelemetry const & v);
std::ostream & operator<<(std::ostream & Str, Packet_Image const & v);
std::ostream & operator<<(std::ostream & Str, Packet_Acknowledgment const & v);
std::ostream & operator<<(std::ostream & Str, Packet_MessageString const & v);
std::ostream & operator<<(std::ostream & Str, Packet_EmergencyCommand const & v);
std::ostream & operator<<(std::ostream & Str, Packet_CameraControl const & v);
//std::ostream & operator<<(std::ostream & Str, Packet_ExecuteWaypointMission const & v);
std::ostream & operator<<(std::ostream & Str, Packet_VirtualStickCommand const & v);
} | 36.71 | 147 | 0.718741 | parthiv-krishna |
6ad8a207151c8c52bae03a8a8c99575c32decbf2 | 79,552 | cpp | C++ | systems/plants/inverseKinBackend.cpp | cmmccann/drake | 0a124c044357d5a29ec7e536acb747cfa5682eba | [
"BSD-3-Clause"
] | 1 | 2020-01-12T14:32:29.000Z | 2020-01-12T14:32:29.000Z | systems/plants/inverseKinBackend.cpp | cmmccann/drake | 0a124c044357d5a29ec7e536acb747cfa5682eba | [
"BSD-3-Clause"
] | null | null | null | systems/plants/inverseKinBackend.cpp | cmmccann/drake | 0a124c044357d5a29ec7e536acb747cfa5682eba | [
"BSD-3-Clause"
] | null | null | null | #include <math.h>
#include <float.h>
#include <stdlib.h>
#include <cstdio>
#include <cstring>
#include <iostream>
namespace snopt {
#include "snopt.hh"
#include "snfilewrapper.hh"
#include "snoptProblem.hh"
}
#undef abs
#undef max
#undef min
#include "RigidBodyIK.h"
#include "RigidBodyManipulator.h"
#include "constraint/RigidBodyConstraint.h"
#include "IKoptions.h"
#include "inverseKinBackend.h"
#include <Eigen/LU>
//Only for debugging purpose
//#include "mat.h"
using namespace Eigen;
using namespace std;
static RigidBodyManipulator* model = nullptr;
static SingleTimeKinematicConstraint** st_kc_array = nullptr;
static MultipleTimeKinematicConstraint** mt_kc_array = nullptr;
static QuasiStaticConstraint* qsc_ptr = nullptr;
static MatrixXd q_nom;
static VectorXd q_nom_i;
static MatrixXd Q;
static MatrixXd Qa;
static MatrixXd Qv;
static bool qscActiveFlag;
static snopt::integer nx;
static snopt::integer nF;
static snopt::integer nG;
static snopt::integer* nc_array;
static snopt::integer* nG_array;
static snopt::integer* nA_array;
static int nq;
static double *t = nullptr;
static double *t_samples = nullptr;
static double* ti = nullptr;
static int num_st_kc;
static int num_mt_kc;
static int num_st_lpc;
static int num_mt_lpc;
static int* mt_kc_nc;
static int* st_lpc_nc;
static int* mt_lpc_nc;
static int nT;
static int num_qsc_pts;
static bool fixInitialState;
// The following variables are used in inverseKinTraj only
static snopt::integer* qfree_idx;
static snopt::integer* qdotf_idx;
static snopt::integer* qdot0_idx;
static VectorXd q0_fixed;
static VectorXd qdot0_fixed;
static snopt::integer qstart_idx;
static snopt::integer num_qfree;
static snopt::integer num_qdotfree;
static MatrixXd velocity_mat;
static MatrixXd velocity_mat_qd0;
static MatrixXd velocity_mat_qdf;
static MatrixXd accel_mat;
static MatrixXd accel_mat_qd0;
static MatrixXd accel_mat_qdf;
static VectorXd* t_inbetween;
static snopt::integer num_inbetween_tSamples;
static MatrixXd* dqInbetweendqknot;
static MatrixXd* dqInbetweendqd0;
static MatrixXd* dqInbetweendqdf;
static snopt::integer* qknot_qsamples_idx;
/* Remeber to delete this*/
static snopt::integer nF_tmp;
static snopt::integer nG_tmp;
static snopt::integer nx_tmp;
static void gevalNumerical(void (*func_ptr)(const VectorXd &, VectorXd &),const VectorXd &x, VectorXd &c, MatrixXd &dc,int order = 2)
{
int nx = x.rows();
(*func_ptr)(x,c);
int nc = c.rows();
dc.resize(nc,nx);
double err = 1e-10;
for(int i = 0;i<nx;i++)
{
VectorXd dx = VectorXd::Zero(nx);
dx(i) = err;
VectorXd c1(nc);
(*func_ptr)(x+dx,c1);
if(order == 1)
{
for(int j = 0;j<nc;j++)
{
dc(j,i) = (c1(j)-c(j))/err;
}
}
else if(order == 2)
{
VectorXd c2(nc);
(*func_ptr)(x-dx,c2);
for(int j = 0;j<nc;j++)
{
dc(j,i) = (c1(j)-c2(j))/(2*err);
}
}
}
}
static void IK_constraint_fun(double* x,double* c, double* G)
{
double* qsc_weights=nullptr;
if(qscActiveFlag)
{
qsc_weights = x+nq;
}
int nc_accum = 0;
int ng_accum = 0;
int nc;
for(int i = 0;i<num_st_kc;i++)
{
nc = st_kc_array[i]->getNumConstraint(ti);
VectorXd cnst(nc);
MatrixXd dcnst(nc,nq);
st_kc_array[i]->eval(ti,cnst,dcnst);
memcpy(&c[nc_accum],cnst.data(),sizeof(double)*nc);
memcpy(&G[ng_accum],dcnst.data(),sizeof(double)*nc*nq);
nc_accum += nc;
ng_accum += nc*nq;
}
for(int i = 0;i<num_st_lpc;i++)
{
nc_accum += st_lpc_nc[i];
}
if(qscActiveFlag)
{
int num_qsc_cnst = qsc_ptr->getNumConstraint(ti);
VectorXd cnst(num_qsc_cnst-1);
MatrixXd dcnst(num_qsc_cnst-1,nq+num_qsc_pts);
qsc_ptr->eval(ti,qsc_weights,cnst,dcnst);
memcpy(c+nc_accum,cnst.data(),sizeof(double)*(num_qsc_cnst-1));
c[nc_accum+num_qsc_cnst-1] = 0.0;
memcpy(G+ng_accum,dcnst.data(),sizeof(double)*dcnst.size());
nc_accum += num_qsc_cnst;
ng_accum += dcnst.size();
}
}
static void IK_cost_fun(double* x, double &J, double* dJ)
{
VectorXd q(nq);
memcpy(q.data(),x,sizeof(double)*nq);
VectorXd q_err = q-q_nom_i;
J = q_err.transpose()*Q*q_err;
VectorXd dJ_vec = 2*q_err.transpose()*Q;
memcpy(dJ, dJ_vec.data(),sizeof(double)*nq);
}
static int snoptIKfun(snopt::integer *Status, snopt::integer *n, snopt::doublereal x[],
snopt::integer *needF, snopt::integer *neF, snopt::doublereal F[],
snopt::integer *needG, snopt::integer *neG, snopt::doublereal G[],
char *cu, snopt::integer *lencu,
snopt::integer iu[], snopt::integer *leniu,
snopt::doublereal ru[], snopt::integer *lenru)
{
double* q = x;
model->doKinematics(q);
IK_cost_fun(x,F[0],G);
IK_constraint_fun(x,&F[1],&G[nq]);
return 0;
}
static void IKtraj_cost_fun(MatrixXd q,const VectorXd &qdot0,const VectorXd &qdotf,double &J,double* dJ)
{
MatrixXd dJ_vec = MatrixXd::Zero(1,nq*(num_qfree+num_qdotfree));
MatrixXd qdot(nq*nT,1);
MatrixXd qddot(nq*nT,1);
q.resize(nq*nT,1);
qdot.block(0,0,nq,1) = qdot0;
qdot.block(nq,0,nq*(nT-2),1) = velocity_mat*q+velocity_mat_qd0*qdot0+velocity_mat_qdf*qdotf;
qdot.block(nq*(nT-1),0,nq,1) = qdotf;
qddot = accel_mat*q+accel_mat_qd0*qdot0+accel_mat_qdf*qdotf;
q.resize(nq,nT);
qdot.resize(nq,nT);
qddot.resize(nq,nT);
MatrixXd q_diff = q.block(0,qstart_idx,nq,num_qfree)-q_nom.block(0,qstart_idx,nq,num_qfree);
MatrixXd tmp1 = 0.5*Qa*qddot;
MatrixXd tmp2 = tmp1.cwiseProduct(qddot);
J = tmp2.sum();
MatrixXd tmp3 = 0.5*Qv*qdot;
MatrixXd tmp4 = tmp3.cwiseProduct(qdot);
J += tmp4.sum();
MatrixXd tmp5 = 0.5*Q*q_diff;
MatrixXd tmp6 = tmp5.cwiseProduct(q_diff);
J += tmp6.sum();
MatrixXd dJdqd = 2*tmp3.block(0,1,nq,nT-2);//[dJdqd(2) dJdqd(3) dJdqd(nT-1)]
dJdqd.resize(1,nq*(nT-2));
dJ_vec.block(0,0,1,nq*num_qfree) = dJdqd*velocity_mat.block(0,nq*qstart_idx,(nT-2)*nq,nq*num_qfree);
MatrixXd dJdqdiff = 2*tmp5;
dJdqdiff.resize(1,nq*num_qfree);
dJ_vec.block(0,0,1,nq*num_qfree) += dJdqdiff;
MatrixXd dJdqdd = 2.0*tmp1;
dJdqdd.resize(1,nq*nT);
dJ_vec.block(0,0,1,nq*num_qfree) += dJdqdd*accel_mat.block(0,nq*qstart_idx,nq*nT,nq*num_qfree);
MatrixXd dJdqdotf;
dJdqdotf = dJdqdd*accel_mat_qdf+qdotf.transpose()*Qv+dJdqd*velocity_mat_qdf;
dJdqdotf.resize(1,nq);
if(fixInitialState)
{
dJ_vec.block(0,nq*num_qfree,1,nq) = dJdqdotf;
}
else
{
MatrixXd dJdqdot0;
dJdqdot0 = dJdqdd*accel_mat_qd0+qdot0.transpose()*Qv+dJdqd*velocity_mat_qd0;
dJdqdot0.resize(1,nq);
dJ_vec.block(0,nq*num_qfree,1,nq) = dJdqdot0;
dJ_vec.block(0,nq*num_qfree+nq,1,nq) = dJdqdotf;
}
memcpy(dJ,dJ_vec.data(),sizeof(double)*nq*(num_qfree+num_qdotfree));
}
static int snoptIKtrajfun(snopt::integer *Status, snopt::integer *n, snopt::doublereal x[],
snopt::integer *needF, snopt::integer *neF, snopt::doublereal F[],
snopt::integer *needG, snopt::integer *neG, snopt::doublereal G[],
char *cu, snopt::integer *lencu,
snopt::integer iu[], snopt::integer *leniu,
snopt::doublereal ru[], snopt::integer *lenru)
{
VectorXd qdotf = VectorXd::Zero(nq);
VectorXd qdot0 = VectorXd::Zero(nq);
MatrixXd q(nq,nT);
for(int i = 0;i<nq;i++)
{
qdotf(i) = x[qdotf_idx[i]];
}
if(fixInitialState)
{
qdot0 = qdot0_fixed;
q.col(0) = q0_fixed;
}
else
{
for(int i = 0;i<nq;i++)
{
qdot0(i) = x[qdot0_idx[i]];
}
}
for(int i = 0;i<nq*num_qfree;i++)
{
q(nq*qstart_idx+i) = x[qfree_idx[i]];
}
IKtraj_cost_fun(q,qdot0,qdotf,F[0],G);
int nf_cum = 1;
int nG_cum = nq*(num_qfree+num_qdotfree);
for(int i = qstart_idx;i<nT;i++)
{
double* qi;
if(qscActiveFlag)
{
qi = x+(i-qstart_idx)*(nq+num_qsc_pts);
}
else
{
qi = x+(i-qstart_idx)*nq;
}
model->doKinematics(qi);
ti = &t[i];
IK_constraint_fun(qi,F+nf_cum,G+nG_cum);
nf_cum += nc_array[i];
nG_cum += nG_array[i];
}
MatrixXd q_inbetween = MatrixXd::Zero(nq,num_inbetween_tSamples);
MatrixXd q_samples = MatrixXd::Zero(nq,num_inbetween_tSamples+nT);
int inbetween_idx = 0;
for(int i = 0;i<nT-1;i++)
{
q.resize(nq*nT,1);
MatrixXd q_inbetween_block_tmp = dqInbetweendqknot[i]*q+dqInbetweendqd0[i]*qdot0+dqInbetweendqdf[i]*qdotf;
q_inbetween_block_tmp.resize(nq,t_inbetween[i].size());
q_inbetween.block(0,inbetween_idx,nq,t_inbetween[i].size()) = q_inbetween_block_tmp;
q.resize(nq,nT);
for(int j = 0;j<t_inbetween[i].size();j++)
{
double t_j = t_inbetween[i](j)+t[i];
double* qi = q_inbetween.data()+(inbetween_idx+j)*nq;
model->doKinematics(qi);
for(int k = 0;k<num_st_kc;k++)
{
if(st_kc_array[k]->isTimeValid(&t_j))
{
int nc = st_kc_array[k]->getNumConstraint(&t_j);
VectorXd c_k(nc);
MatrixXd dc_k(nc,nq);
st_kc_array[k]->eval(&t_j,c_k,dc_k);
memcpy(F+nf_cum,c_k.data(),sizeof(double)*nc);
MatrixXd dc_kdx = MatrixXd::Zero(nc,nq*(num_qfree+num_qdotfree));
dc_kdx.block(0,0,nc,nq*num_qfree) = dc_k*dqInbetweendqknot[i].block(nq*j,nq*qstart_idx,nq,nq*num_qfree);
if(!fixInitialState)
{
dc_kdx.block(0,nq*num_qfree,nc,nq) = dc_k*dqInbetweendqd0[i].block(nq*j,0,nq,nq);
dc_kdx.block(0,nq*num_qfree+nq,nc,nq) = dc_k*dqInbetweendqdf[i].block(nq*j,0,nq,nq);
}
else
{
dc_kdx.block(0,nq*num_qfree,nc,nq) = dc_k*dqInbetweendqdf[i].block(nq*j,0,nq,nq);
}
memcpy(G+nG_cum,dc_kdx.data(),sizeof(double)*dc_kdx.size());
nf_cum += nc;
nG_cum += nc*nq*(num_qfree+num_qdotfree);
}
}
}
q_samples.col(inbetween_idx+i) = q.col(i);
q_samples.block(0,inbetween_idx+i+1,nq,t_inbetween[i].size()) = q_inbetween.block(0,inbetween_idx,nq,t_inbetween[i].size());
inbetween_idx += t_inbetween[i].size();
}
q_samples.col(nT+num_inbetween_tSamples-1) = q.col(nT-1);
for(int i = 0;i<num_mt_kc;i++)
{
VectorXd mtkc_c(mt_kc_nc[i]);
MatrixXd mtkc_dc(mt_kc_nc[i],nq*(num_qfree+num_inbetween_tSamples));
mt_kc_array[i]->eval(t_samples+qstart_idx,num_qfree+num_inbetween_tSamples,q_samples.block(0,qstart_idx,nq,num_qfree+num_inbetween_tSamples),mtkc_c,mtkc_dc);
memcpy(F+nf_cum,mtkc_c.data(),sizeof(double)*mt_kc_nc[i]);
MatrixXd mtkc_dc_dx = MatrixXd::Zero(mt_kc_nc[i],nq*(num_qfree+num_qdotfree));
for(int j = qstart_idx;j<nT;j++)
{
mtkc_dc_dx.block(0,(j-qstart_idx)*nq,mt_kc_nc[i],nq) = mtkc_dc.block(0,(qknot_qsamples_idx[j]-qstart_idx)*nq,mt_kc_nc[i],nq);
}
for(int j = 0;j<nT-1;j++)
{
MatrixXd dc_ij = mtkc_dc.block(0,nq*(qknot_qsamples_idx[j]+1-qstart_idx),mt_kc_nc[i],nq*t_inbetween[j].size());
mtkc_dc_dx.block(0,0,mt_kc_nc[i],nq*num_qfree) += dc_ij*dqInbetweendqknot[j].block(0,qstart_idx*nq,nq*t_inbetween[j].size(),nq*num_qfree);
if(fixInitialState)
{
mtkc_dc_dx.block(0,nq*num_qfree,mt_kc_nc[i],nq) += dc_ij*dqInbetweendqdf[j];
}
else
{
mtkc_dc_dx.block(0,nq*num_qfree,mt_kc_nc[i],nq) += dc_ij*dqInbetweendqd0[j];
mtkc_dc_dx.block(0,nq*num_qfree+nq,mt_kc_nc[i],nq) += dc_ij*dqInbetweendqdf[j];
}
}
memcpy(G+nG_cum,mtkc_dc_dx.data(),sizeof(double)*mtkc_dc_dx.size());
nf_cum += mt_kc_nc[i];
nG_cum += mt_kc_nc[i]*nq*(num_qfree+num_qdotfree);
}
for(int i = 0;i<num_mt_lpc;i++)
{
nf_cum += mt_lpc_nc[i];
}
return 0;
}
static void snoptIKtraj_userfun(const VectorXd &x_vec, VectorXd &c_vec, VectorXd &G_vec)
{
snopt::doublereal* x = new snopt::doublereal[nx_tmp];
for(int i = 0;i<nx_tmp;i++)
{
x[i] = x_vec(i);
}
snopt::doublereal* F = new snopt::doublereal[nF_tmp];
snopt::doublereal* G = new snopt::doublereal[nG_tmp];
snopt::integer Status = 0;
snopt::integer n = nx_tmp;
snopt::integer needF = 1;
snopt::integer neF = nF_tmp;
snopt::integer needG = 1;
snopt::integer neG = nG_tmp;
char *cu = nullptr;
snopt::integer lencu = 0;
snopt::integer *iu = nullptr;
snopt::integer leniu = 0;
snopt::doublereal *ru = nullptr;
snopt::integer lenru = 0;
snoptIKtrajfun(&Status,&n,x,&needF, &neF, F, &needG, &neG, G, cu, &lencu, iu, &leniu, ru, &lenru);
c_vec.resize(nF_tmp,1);
for(int i = 0;i<nF_tmp;i++)
{
c_vec(i) = F[i];
}
G_vec.resize(nG_tmp,1);
for(int i = 0;i<nG_tmp;i++)
{
G_vec(i) = G[i];
}
delete[] x;
delete[] F;
delete[] G;
}
static void snoptIKtraj_fevalfun(const VectorXd &x, VectorXd &c)
{
VectorXd G;
snoptIKtraj_userfun(x,c,G);
}
template <typename DerivedA, typename DerivedB, typename DerivedC, typename DerivedD, typename DerivedE>
void inverseKinBackend(RigidBodyManipulator* model_input, const int mode, const int nT_input, const double* t_input, const MatrixBase<DerivedA> &q_seed, const MatrixBase<DerivedB> &q_nom_input, const int num_constraints, RigidBodyConstraint** const constraint_array, MatrixBase<DerivedC> &q_sol, MatrixBase<DerivedD> &qdot_sol, MatrixBase<DerivedE> &qddot_sol, int* INFO, vector<string> &infeasible_constraint, const IKoptions &ikoptions)
{
model = model_input;
nT = nT_input;
t = const_cast<double*>(t_input);
nq = model->num_dof;
q_nom = q_nom_input;
if(q_seed.rows() != nq || q_seed.cols() != nT || q_nom.rows() != nq || q_nom.cols() != nT)
{
cerr<<"Drake:inverseKinBackend: q_seed and q_nom must be of size nq x nT"<<endl;
}
num_st_kc = 0;
num_mt_kc = 0;
num_st_lpc = 0;
num_mt_lpc = 0;
int num_qsc = 0;
st_kc_array = new SingleTimeKinematicConstraint*[num_constraints];
mt_kc_array = new MultipleTimeKinematicConstraint*[num_constraints];
SingleTimeLinearPostureConstraint** st_lpc_array = new SingleTimeLinearPostureConstraint*[num_constraints];
MultipleTimeLinearPostureConstraint** mt_lpc_array = new MultipleTimeLinearPostureConstraint*[num_constraints];
qsc_ptr = nullptr;
MatrixXd joint_limit_min(nq,nT);
MatrixXd joint_limit_max(nq,nT);
for(int i = 0;i<nT;i++)
{
joint_limit_min.col(i) = model->joint_limit_min;
joint_limit_max.col(i) = model->joint_limit_max;
}
for(int i = 0;i<num_constraints;i++)
{
RigidBodyConstraint* constraint = constraint_array[i];
int constraint_category = constraint->getCategory();
if(constraint_category == RigidBodyConstraint::SingleTimeKinematicConstraintCategory)
{
st_kc_array[num_st_kc] = static_cast<SingleTimeKinematicConstraint*>(constraint);
num_st_kc++;
}
else if(constraint_category == RigidBodyConstraint::MultipleTimeKinematicConstraintCategory)
{
mt_kc_array[num_mt_kc] = static_cast<MultipleTimeKinematicConstraint*>(constraint);
num_mt_kc++;
}
else if(constraint_category == RigidBodyConstraint::QuasiStaticConstraintCategory)
{
num_qsc++;
if(num_qsc>1)
{
cerr<<"Drake:inverseKinBackend:current implementation supports at most one QuasiStaticConstraint"<<endl;
}
qsc_ptr = static_cast<QuasiStaticConstraint*>(constraint);
}
else if(constraint_category == RigidBodyConstraint::PostureConstraintCategory)
{
VectorXd joint_min, joint_max;
PostureConstraint* pc = static_cast<PostureConstraint*>(constraint);
for(int j = 0;j<nT;j++)
{
pc->bounds(&t[j],joint_min,joint_max);
for(int k = 0;k<nq;k++)
{
joint_limit_min(k,j) = (joint_limit_min(k,j)>joint_min[k]? joint_limit_min(k,j):joint_min[k]);
joint_limit_max(k,j) = (joint_limit_max(k,j)<joint_max[k]? joint_limit_max(k,j):joint_max[k]);
if(joint_limit_min(k,j)>joint_limit_max(k,j))
{
cerr<<"Drake:inverseKinBackend:BadInputs Some posture constraint has lower bound larger than the upper bound of other posture constraint for joint "<<k<< " at "<<j<<"'th time "<<endl;
}
}
}
}
else if(constraint_category == RigidBodyConstraint::MultipleTimeLinearPostureConstraintCategory)
{
mt_lpc_array[num_mt_lpc] = static_cast<MultipleTimeLinearPostureConstraint*>(constraint);
num_mt_lpc++;
}
else if(constraint_category == RigidBodyConstraint::SingleTimeLinearPostureConstraintCategory)
{
st_lpc_array[num_st_lpc] = static_cast<SingleTimeLinearPostureConstraint*>(constraint);
num_st_lpc++;
}
}
if(qsc_ptr == nullptr)
{
qscActiveFlag = false;
num_qsc_pts = 0;
}
else
{
qscActiveFlag = qsc_ptr->isActive();
num_qsc_pts = qsc_ptr->getNumWeights();
}
ikoptions.getQ(Q);
snopt::integer SNOPT_MajorIterationsLimit = static_cast<snopt::integer>(ikoptions.getMajorIterationsLimit());
snopt::integer SNOPT_IterationsLimit = static_cast<snopt::integer>(ikoptions.getIterationsLimit());
double SNOPT_MajorFeasibilityTolerance = ikoptions.getMajorFeasibilityTolerance();
double SNOPT_MajorOptimalityTolerance = ikoptions.getMajorOptimalityTolerance();
snopt::integer SNOPT_SuperbasicsLimit = static_cast<snopt::integer>(ikoptions.getSuperbasicsLimit());
bool debug_mode = ikoptions.getDebug();
bool sequentialSeedFlag = ikoptions.getSequentialSeedFlag();
snopt::integer* INFO_snopt = nullptr;
if(mode == 1)
{
INFO_snopt= new snopt::integer[nT];
for(int j = 0;j<nT;j++)
{
INFO_snopt[j] = 0;
}
}
else if(mode == 2)
{
INFO_snopt = new snopt::integer[1];
INFO_snopt[0] = 0;
}
q_sol.resize(nq,nT);
qdot_sol.resize(nq,nT);
qddot_sol.resize(nq,nT);
VectorXi* iCfun_array = new VectorXi[nT];
VectorXi* jCvar_array = new VectorXi[nT];
nc_array = new snopt::integer[nT];
nG_array = new snopt::integer[nT];
nA_array = new snopt::integer[nT];
for(int i = 0;i<nT;i++)
{
nc_array[i] = 0;
nG_array[i] = 0;
nA_array[i] = 0;
}
VectorXd* A_array = new VectorXd[nT];
VectorXi* iAfun_array = new VectorXi[nT];
VectorXi* jAvar_array = new VectorXi[nT];
VectorXd* Cmin_array = new VectorXd[nT];
VectorXd* Cmax_array = new VectorXd[nT];
vector<string>* Cname_array = new vector<string>[nT];
for(int i =0;i<nT;i++)
{
Cmin_array[i].resize(0);
Cmax_array[i].resize(0);
iCfun_array[i].resize(0);
jCvar_array[i].resize(0);
A_array[i].resize(0);
iAfun_array[i].resize(0);
jAvar_array[i].resize(0);
}
for(int i = 0;i<nT;i++)
{
for(int j = 0;j<num_st_kc;j++)
{
if(st_kc_array[j]->isTimeValid(&t[i]))
{
int nc = st_kc_array[j]->getNumConstraint(&t[i]);
VectorXd lb,ub;
lb.resize(nc);
ub.resize(nc);
st_kc_array[j]->bounds(&t[i],lb,ub);
Cmin_array[i].conservativeResize(Cmin_array[i].size()+nc);
Cmin_array[i].tail(nc) = lb;
Cmax_array[i].conservativeResize(Cmax_array[i].size()+nc);
Cmax_array[i].tail(nc) = ub;
iCfun_array[i].conservativeResize(iCfun_array[i].size()+nc*nq);
jCvar_array[i].conservativeResize(jCvar_array[i].size()+nc*nq);
VectorXi iCfun_append(nc);
VectorXi jCvar_append(nc);
for(int k = 0;k<nc;k++)
{
iCfun_append(k) = nc_array[i]+k+1; //use 1-index;
}
for(int k = 0;k<nq;k++)
{
iCfun_array[i].segment(nG_array[i]+k*nc,nc) = iCfun_append;
jCvar_append = VectorXi::Constant(nc,k+1); // use 1-index
jCvar_array[i].segment(nG_array[i]+k*nc,nc) = jCvar_append;
}
nc_array[i] = nc_array[i]+nc;
nG_array[i] = nG_array[i]+nq*nc;
if(debug_mode)
{
vector<string> constraint_name;
st_kc_array[j]->name(&t[i],constraint_name);
Cname_array[i].insert(Cname_array[i].end(),constraint_name.begin(),constraint_name.end());
}
}
}
st_lpc_nc = new int[num_st_lpc];
for(int j = 0;j<num_st_lpc;j++)
{
st_lpc_nc[j] = st_lpc_array[j]->getNumConstraint(&t[i]);
VectorXd lb(st_lpc_nc[j]);
VectorXd ub(st_lpc_nc[j]);
st_lpc_array[j]->bounds(&t[i],lb,ub);
Cmin_array[i].conservativeResize(Cmin_array[i].size()+st_lpc_nc[j]);
Cmin_array[i].tail(st_lpc_nc[j]) = lb;
Cmax_array[i].conservativeResize(Cmax_array[i].size()+st_lpc_nc[j]);
Cmax_array[i].tail(st_lpc_nc[j]) = ub;
VectorXi iAfun,jAvar;
VectorXd A;
st_lpc_array[j]->geval(&t[i],iAfun,jAvar,A);
iAfun_array[i].conservativeResize(iAfun_array[i].size()+iAfun.size());
iAfun_array[i].tail(iAfun.size()) = iAfun+VectorXi::Constant(iAfun.size(),nc_array[i]+1); //use 1-indx
jAvar_array[i].conservativeResize(jAvar_array[i].size()+jAvar.size());
jAvar_array[i].tail(jAvar.size()) = jAvar+VectorXi::Ones(jAvar.size());// use 1-indx
A_array[i].conservativeResize(A_array[i].size()+A.size());
A_array[i].tail(A.size()) = A;
nc_array[i] += st_lpc_nc[j];
nA_array[i] += A.size();
if(debug_mode)
{
vector<string> constraint_name;
st_lpc_array[j]->name(&t[i],constraint_name);
Cname_array[i].insert(Cname_array[i].end(),constraint_name.begin(),constraint_name.end());
}
}
if(qscActiveFlag)
{
int num_qsc_cnst = qsc_ptr->getNumConstraint(&t[i]);
iCfun_array[i].conservativeResize(iCfun_array[i].size()+(num_qsc_cnst-1)*(nq+num_qsc_pts));
jCvar_array[i].conservativeResize(jCvar_array[i].size()+(num_qsc_cnst-1)*(nq+num_qsc_pts));
iAfun_array[i].conservativeResize(iAfun_array[i].size()+num_qsc_pts);
jAvar_array[i].conservativeResize(jAvar_array[i].size()+num_qsc_pts);
A_array[i].conservativeResize(A_array[i].size()+num_qsc_pts);
for(int k=0;k<nq+num_qsc_pts;k++)
{
for(int l = 0;l<num_qsc_cnst-1;l++)
{
iCfun_array[i](nG_array[i]+(num_qsc_cnst-1)*k+l) = nc_array[i]+l+1;
jCvar_array[i](nG_array[i]+(num_qsc_cnst-1)*k+l) = k+1;
}
}
iAfun_array[i].tail(num_qsc_pts) = VectorXi::Constant(num_qsc_pts,nc_array[i]+num_qsc_cnst);
for(int k = 0;k<num_qsc_pts;k++)
{
jAvar_array[i](nA_array[i]+k) = nq+k+1;
}
A_array[i].tail(num_qsc_pts) = VectorXd::Ones(num_qsc_pts);
Cmin_array[i].conservativeResize(Cmin_array[i].size()+num_qsc_cnst);
Cmax_array[i].conservativeResize(Cmax_array[i].size()+num_qsc_cnst);
VectorXd qsc_lb(num_qsc_cnst);
VectorXd qsc_ub(num_qsc_cnst);
VectorXd qsc_lb_tmp(num_qsc_cnst-1);
VectorXd qsc_ub_tmp(num_qsc_cnst-1);
qsc_ptr->bounds(&t[i],qsc_lb_tmp,qsc_ub_tmp);
qsc_lb.head(num_qsc_cnst-1) = qsc_lb_tmp;
qsc_lb(num_qsc_cnst-1) = 1.0;
qsc_ub.head(num_qsc_cnst-1) = qsc_ub_tmp;
qsc_ub(num_qsc_cnst-1) = 1.0;
Cmin_array[i].tail(num_qsc_cnst) = qsc_lb;
Cmax_array[i].tail(num_qsc_cnst) = qsc_ub;
nc_array[i] += num_qsc_cnst;
nG_array[i] += (num_qsc_cnst-1)*(nq+num_qsc_pts);
nA_array[i] += num_qsc_pts;
if(debug_mode)
{
vector<string> constraint_name;
qsc_ptr->name(&t[i],constraint_name);
for(int k = 0;k<num_qsc_cnst-1;k++)
{
Cname_array[i].push_back(constraint_name[k]);
}
string qsc_weights_cnst_name;
if(&t[i]!= nullptr)
{
char qsc_name_buffer[200];
sprintf(qsc_name_buffer,"quasi static constraint weights at time %7.3f", t[i]);
qsc_weights_cnst_name = string(qsc_name_buffer);
}
else
{
char qsc_name_buffer[200];
sprintf(qsc_name_buffer,"quasi static constraint weights");
qsc_weights_cnst_name = string(qsc_name_buffer);
}
Cname_array[i].push_back(qsc_weights_cnst_name);
}
}
if(mode == 1)
{
if(!qscActiveFlag)
{
nx = nq;
}
else
{
nx = nq+num_qsc_pts;
}
nG = nq + nG_array[i];
snopt::integer* iGfun = new snopt::integer[nG];
snopt::integer* jGvar = new snopt::integer[nG];
for(int k = 0;k<nq;k++)
{
iGfun[k] = 1;
jGvar[k] = (snopt::integer) k+1;
}
for(int k = nq;k<nG;k++)
{
iGfun[k] = iCfun_array[i][k-nq]+1;
jGvar[k] = jCvar_array[i][k-nq];
}
nF = nc_array[i]+1;
snopt::integer lenA = A_array[i].size();
snopt::integer* iAfun;
snopt::integer* jAvar;
snopt::doublereal* A;
if(lenA == 0)
{
iAfun = nullptr;
jAvar = nullptr;
A = nullptr;
}
else
{
A = new snopt::doublereal[lenA];
iAfun = new snopt::integer[lenA];
jAvar = new snopt::integer[lenA];
for(int k = 0;k<lenA;k++)
{
A[k] = A_array[i](k);
iAfun[k] = iAfun_array[i](k)+1;
jAvar[k] = jAvar_array[i](k);
}
}
snopt::doublereal* xlow = new snopt::doublereal[nx];
snopt::doublereal* xupp = new snopt::doublereal[nx];
for(int k = 0;k<nq;k++)
{
xlow[k] = joint_limit_min(k,i);
xupp[k] = joint_limit_max(k,i);
}
//memcpy(xlow,joint_limit_min.col(i).data(),sizeof(double)*nq);
//memcpy(xupp,joint_limit_max.col(i).data(),sizeof(double)*nq);
if(qscActiveFlag)
{
for(int k = 0;k<num_qsc_pts;k++)
{
xlow[nq+k] = 0.0;
xupp[nq+k] = 1.0;
}
}
snopt::doublereal* Flow = new snopt::doublereal[nF];
snopt::doublereal* Fupp = new snopt::doublereal[nF];
Flow[0] = 0;
Fupp[0] = 1.0/0.0;
for(int k = 0;k<nc_array[i];k++)
{
Flow[1+k] = Cmin_array[i](k);
Fupp[1+k] = Cmax_array[i](k);
}
//memcpy(&Flow[1],Cmin_array[i].data(),sizeof(double)*nc_array[i]);
//memcpy(&Fupp[1],Cmax_array[i].data(),sizeof(double)*nc_array[i]);
ti = const_cast<double*>(&t[i]);
q_nom_i = q_nom.col(i);
snopt::doublereal* x = new snopt::doublereal[nx];
if(!sequentialSeedFlag)
{
for(int k=0;k<nq;k++)
{
x[k] = q_seed(k,i);
}
//memcpy(x,q_seed.col(i).data(),sizeof(double)*nq);
}
else
{
if(i == 0)
{
for(int k = 0;k<nq;k++)
{
x[k] = q_seed(k,i);
}
//memcpy(x,q_seed.col(i).data(),sizeof(double)*nq);
}
else
{
if(INFO_snopt[i-1]>10)
{
for(int k = 0;k<nq;k++)
{
x[k] = q_seed(k,i);
}
//memcpy(x,q_seed.col(i).data(),sizeof(double)*nq);
}
else
{
for(int k = 0;k<nq;k++)
{
x[k] = q_sol(k,i-1);
}
//memcpy(x,q_sol.col(i-1).data(),sizeof(double)*nq);
}
}
}
if(qscActiveFlag)
{
for(int j = 0;j<num_qsc_pts;j++)
{
x[nq+j] = 1.0/num_qsc_pts;
}
}
snopt::integer minrw,miniw,mincw;
snopt::integer lenrw = 10000000, leniw = 500000, lencw = 500;
snopt::doublereal* rw;
rw = (snopt::doublereal*) std::calloc(lenrw,sizeof(snopt::doublereal));
//doublereal rw[lenrw];
snopt::integer* iw;
iw = (snopt::integer*) std::calloc(lenrw,sizeof(snopt::integer));
char cw[8*lencw];
snopt::integer Cold = 0; //, Basis = 1, Warm = 2;
snopt::doublereal *xmul = new snopt::doublereal[nx];
snopt::integer *xstate = new snopt::integer[nx];
for(int j = 0;j<nx;j++)
{
xstate[j] = 0;
}
snopt::doublereal *F = new snopt::doublereal[nF];
snopt::doublereal *Fmul = new snopt::doublereal[nF];
snopt::integer *Fstate = new snopt::integer[nF];
for(int j = 0;j<nF;j++)
{
Fstate[j] = 0;
}
snopt::doublereal ObjAdd = 0.0;
snopt::integer ObjRow = 1;
snopt::integer nxname = 1, nFname = 1, npname = 0;
char* xnames = new char[nxname*8];
char* Fnames = new char[nFname*8];
char Prob[200];
// char printname[200];
// char specname[200];
// snopt::integer iSpecs = -1, spec_len;
snopt::integer iSumm = -1;
snopt::integer iPrint = -1; //, prnt_len;
snopt::integer nS, nInf;
snopt::doublereal sInf;
/*sprintf(specname, "%s","ik.spc");
sprintf(printname, "%s","ik.out");
sprintf(Prob,"%s","ik");
prnt_len = strlen(printname);
spec_len = strlen(specname);
npname = strlen(Prob);
snopenappend_(&iPrint,printname, &INFO_snopt[i], prnt_len);*/
snopt::sninit_(&iPrint,&iSumm,cw,&lencw,iw,&leniw,rw,&lenrw,8*500);
//snopt::snfilewrapper_(specname,&iSpecs,&INFO_snopt[i],cw,&lencw,iw,&leniw,rw,&lenrw,spec_len,8*lencw);
char strOpt1[200] = "Derivative option";
snopt::integer DerOpt = 1, strOpt_len = strlen(strOpt1);
snopt::snseti_(strOpt1,&DerOpt,&iPrint,&iSumm,&INFO_snopt[i],cw,&lencw,iw,&leniw,rw,&lenrw,strOpt_len,8*500);
char strOpt2[200] = "Major optimality tolerance";
strOpt_len = strlen(strOpt2);
snopt::snsetr_(strOpt2,&SNOPT_MajorOptimalityTolerance,&iPrint,&iSumm,&INFO_snopt[i],cw,&lencw,iw,&leniw,rw,&lenrw,strOpt_len,8*500);
char strOpt3[200] = "Major feasibility tolerance";
strOpt_len = strlen(strOpt3);
snopt::snsetr_(strOpt3,&SNOPT_MajorFeasibilityTolerance,&iPrint,&iSumm,&INFO_snopt[i],cw,&lencw,iw,&leniw,rw,&lenrw,strOpt_len,8*500);
char strOpt4[200] = "Superbasics limit";
strOpt_len = strlen(strOpt4);
snopt::snseti_(strOpt4,&SNOPT_SuperbasicsLimit,&iPrint,&iSumm,&INFO_snopt[i],cw,&lencw,iw,&leniw,rw,&lenrw,strOpt_len,8*500);
char strOpt5[200] = "Major iterations limit";
strOpt_len = strlen(strOpt5);
snopt::snseti_(strOpt5,&SNOPT_MajorIterationsLimit,&iPrint,&iSumm,&INFO_snopt[i],cw,&lencw,iw,&leniw,rw,&lenrw,strOpt_len,8*500);
char strOpt6[200] = "Iterations limit";
strOpt_len = strlen(strOpt6);
snopt::snseti_(strOpt6,&SNOPT_IterationsLimit,&iPrint,&iSumm,&INFO_snopt[i],cw,&lencw,iw,&leniw,rw,&lenrw,strOpt_len,8*500);
//debug only
/*
double* f = new double[nF];
double* G = new double[nG];
model->doKinematics(x);
IK_cost_fun(x,f[0],G);
IK_constraint_fun(x,&f[1],&G[nq]);
mxArray* f_ptr = mxCreateDoubleMatrix(nF,1,mxREAL);
mxArray* G_ptr = mxCreateDoubleMatrix(nG,1,mxREAL);
memcpy(mxGetPr(f_ptr),f,sizeof(double)*(nF));
memcpy(mxGetPr(G_ptr),G,sizeof(double)*(nG));
mxSetCell(plhs[0],0,f_ptr);
mxSetCell(plhs[0],1,G_ptr);
printf("get f,G\n");
double* iGfun_tmp = new double[nG];
double* jGvar_tmp = new double[nG];
mxArray* iGfun_ptr = mxCreateDoubleMatrix(nG,1,mxREAL);
mxArray* jGvar_ptr = mxCreateDoubleMatrix(nG,1,mxREAL);
for(int k = 0;k<nG;k++)
{
iGfun_tmp[k] = (double) iGfun[k];
jGvar_tmp[k] = (double) jGvar[k];
}
memcpy(mxGetPr(iGfun_ptr),iGfun_tmp,sizeof(double)*nG);
memcpy(mxGetPr(jGvar_ptr),jGvar_tmp,sizeof(double)*nG);
mxSetCell(plhs[0],2,iGfun_ptr);
mxSetCell(plhs[0],3,jGvar_ptr);
printf("get iGfun jGvar\n");
mxArray* Fupp_ptr = mxCreateDoubleMatrix(nF,1,mxREAL);
mxArray* Flow_ptr = mxCreateDoubleMatrix(nF,1,mxREAL);
memcpy(mxGetPr(Fupp_ptr),Fupp,sizeof(double)*nF);
memcpy(mxGetPr(Flow_ptr),Flow,sizeof(double)*nF);
mxSetCell(plhs[0],4,Fupp_ptr);
mxSetCell(plhs[0],5,Flow_ptr);
printf("get Fupp Flow\n");
mxArray* xupp_ptr = mxCreateDoubleMatrix(nx,1,mxREAL);
mxArray* xlow_ptr = mxCreateDoubleMatrix(nx,1,mxREAL);
memcpy(mxGetPr(xupp_ptr),xupp,sizeof(double)*nx);
memcpy(mxGetPr(xlow_ptr),xlow,sizeof(double)*nx);
mxSetCell(plhs[0],6,xupp_ptr);
mxSetCell(plhs[0],7,xlow_ptr);
printf("get xupp xlow\n");
mxArray* iAfun_ptr = mxCreateDoubleMatrix(lenA,1,mxREAL);
mxArray* jAvar_ptr = mxCreateDoubleMatrix(lenA,1,mxREAL);
mxArray* A_ptr = mxCreateDoubleMatrix(lenA,1,mxREAL);
double* iAfun_tmp = new double[lenA];
double* jAvar_tmp = new double[lenA];
for(int k = 0;k<lenA;k++)
{
iAfun_tmp[k] = (double) iAfun[k];
jAvar_tmp[k] = (double) jAvar[k];
}
memcpy(mxGetPr(iAfun_ptr),iAfun_tmp,sizeof(double)*lenA);
memcpy(mxGetPr(jAvar_ptr),jAvar_tmp,sizeof(double)*lenA);
memcpy(mxGetPr(A_ptr),A,sizeof(double)*lenA);
mxSetCell(plhs[0],8,iAfun_ptr);
mxSetCell(plhs[0],9,jAvar_ptr);
mxSetCell(plhs[0],10,A_ptr);
printf("get iAfun jAvar A\n");
mxArray* nF_ptr = mxCreateDoubleScalar((double) nF);
mxSetCell(plhs[0],11,nF_ptr);*/
snopt::snopta_
( &Cold, &nF, &nx, &nxname, &nFname,
&ObjAdd, &ObjRow, Prob, snoptIKfun,
iAfun, jAvar, &lenA, &lenA, A,
iGfun, jGvar, &nG, &nG,
xlow, xupp, xnames, Flow, Fupp, Fnames,
x, xstate, xmul, F, Fstate, Fmul,
&INFO_snopt[i], &mincw, &miniw, &minrw,
&nS, &nInf, &sInf,
cw, &lencw, iw, &leniw, rw, &lenrw,
cw, &lencw, iw, &leniw, rw, &lenrw,
npname, 8*nxname, 8*nFname,
8*500, 8*500);
//snclose_(&iPrint);
//snclose_(&iSpecs);
vector<string> Fname(Cname_array[i]);
if(debug_mode)
{
string objective_name("Objective");
vector<string>::iterator it = Fname.begin();
Fname.insert(it,objective_name);
}
if(INFO_snopt[i] == 13 || INFO_snopt[i] == 31 || INFO_snopt[i] == 32)
{
double *ub_err = new double[nF];
double *lb_err = new double[nF];
double max_lb_err = -1.0/0.0;
double max_ub_err = -1.0/0.0;
bool *infeasible_constraint_idx = new bool[nF];
ub_err[0] = -1.0/0.0;
lb_err[0] = -1.0/0.0;
infeasible_constraint_idx[0] = false;
for(int j = 1;j<nF;j++)
{
ub_err[j] = F[j]-Fupp[j];
lb_err[j] = Flow[j]-F[j];
if(ub_err[j]>max_ub_err)
max_ub_err = ub_err[j];
if(lb_err[j]>max_lb_err)
max_lb_err = lb_err[j];
infeasible_constraint_idx[j] = ub_err[j]>5e-5 | lb_err[j] > 5e-5;
}
max_ub_err = (max_ub_err>0.0? max_ub_err: 0.0);
max_lb_err = (max_lb_err>0.0? max_lb_err: 0.0);
if(max_ub_err+max_lb_err>1e-4)
{
if(debug_mode)
{
for(int j = 1;j<nF;j++)
{
if(infeasible_constraint_idx[j])
{
infeasible_constraint.push_back(Fname[j]);
}
}
}
}
else if(INFO_snopt[i] == 13)
{
INFO_snopt[i] = 4;
}
else if(INFO_snopt[i] == 31)
{
INFO_snopt[i] = 5;
}
else if(INFO_snopt[i] == 32)
{
INFO_snopt[i] = 6;
}
delete[] ub_err;
delete[] lb_err;
delete[] infeasible_constraint_idx;
}
memcpy(q_sol.col(i).data(),x,sizeof(double)*nq);
INFO[i] = static_cast<int>(INFO_snopt[i]);
if(INFO[i]<10)
{
for(int j = 0;j<nq;j++)
{
q_sol(j,i) = q_sol(j,i)>joint_limit_min(j,i)?q_sol(j,i):joint_limit_min(j,i);
q_sol(j,i) = q_sol(j,i)<joint_limit_max(j,i)?q_sol(j,i):joint_limit_max(j,i);
}
}
delete[] xmul; delete[] xstate; delete[] xnames;
delete[] F; delete[] Fmul; delete[] Fstate; delete[] Fnames;
delete[] iGfun; delete[] jGvar;
if(lenA>0)
{
delete[] iAfun; delete[] jAvar; delete[] A;
}
delete[] x; delete[] xlow; delete[] xupp; delete[] Flow; delete[] Fupp;
}
}
if(mode == 2)
{
double* dt = new double[nT-1];
for(int j = 0;j<nT-1;j++)
{
dt[j] = t[j+1]-t[j];
}
double* dt_ratio = new double[nT-2];
for(int j = 0;j<nT-2;j++)
{
dt_ratio[j] = dt[j]/dt[j+1];
}
ikoptions.getQa(Qa);
ikoptions.getQv(Qv);
VectorXd q0_lb(nq);
VectorXd q0_ub(nq);
ikoptions.getq0(q0_lb,q0_ub);
VectorXd qd0_lb(nq);
VectorXd qd0_ub(nq);
ikoptions.getqd0(qd0_lb,qd0_ub);
VectorXd qd0_seed = (qd0_lb+qd0_ub)/2;
VectorXd qdf_lb(nq);
VectorXd qdf_ub(nq);
ikoptions.getqdf(qdf_lb,qdf_ub);
VectorXd qdf_seed = (qdf_lb+qdf_ub)/2;
fixInitialState = ikoptions.getFixInitialState();
if(fixInitialState)
{
q0_fixed.resize(nq);
q0_fixed = q_seed.col(0);
qdot0_fixed.resize(nq);
qdot0_fixed = (qd0_lb+qd0_ub)/2;
qstart_idx = 1;
num_qfree = nT-1;
num_qdotfree = 1;
}
else
{
q0_fixed.resize(0);
qdot0_fixed.resize(0);
qstart_idx = 0;
num_qfree = nT;
num_qdotfree = 2;
}
// This part can be rewritten using the sparse matrix if efficiency becomes a concern
MatrixXd velocity_mat1 = MatrixXd::Zero(nq*nT,nq*nT);
MatrixXd velocity_mat2 = MatrixXd::Zero(nq*nT,nq*nT);
velocity_mat1.block(0,0,nq,nq) = MatrixXd::Identity(nq,nq);
velocity_mat1.block(nq*(nT-1),nq*(nT-1),nq,nq) = MatrixXd::Identity(nq,nq);
for(int j = 1;j<nT-1;j++)
{
double val_tmp1 = dt[j-1];
double val_tmp2 = dt[j-1]*(2.0+2.0*dt_ratio[j-1]);
double val_tmp3 = dt[j-1]*dt_ratio[j-1];
double val_tmp4 = 3.0-3.0*dt_ratio[j-1]*dt_ratio[j-1];
double val_tmp5 = 3.0-val_tmp4;
for(int k = 0;k<nq;k++)
{
velocity_mat1(j*nq+k,(j-1)*nq+k) = val_tmp1;
velocity_mat1(j*nq+k,j*nq+k) = val_tmp2;
velocity_mat1(j*nq+k,(j+1)*nq+k) = val_tmp3;
velocity_mat2(j*nq+k,(j-1)*nq+k) = -3.0;
velocity_mat2(j*nq+k,j*nq+k) = val_tmp4;
velocity_mat2(j*nq+k,(j+1)*nq+k) = val_tmp5;
}
}
velocity_mat.resize(nq*(nT-2),nq*nT);
velocity_mat = velocity_mat1.inverse().block(nq,0,nq*(nT-2),nq*nT)*velocity_mat2;
MatrixXd velocity_mat1_middle_inv = (velocity_mat1.block(nq,nq,nq*(nT-2),nq*(nT-2))).inverse();
velocity_mat_qd0 = -velocity_mat1_middle_inv*velocity_mat1.block(nq,0,nq*(nT-2),nq);
velocity_mat_qdf = -velocity_mat1_middle_inv*velocity_mat1.block(nq,nq*(nT-1),nq*(nT-2),nq);
MatrixXd accel_mat1 = MatrixXd::Zero(nq*nT,nq*nT);
MatrixXd accel_mat2 = MatrixXd::Zero(nq*nT,nq*nT);
for(int j = 0;j<nT-1;j++)
{
double val_tmp1 = -6.0/(dt[j]*dt[j]);
double val_tmp2 = -val_tmp1;
double val_tmp3 = -4.0/dt[j];
double val_tmp4 = 0.5*val_tmp3;
for(int k = 0;k<nq;k++)
{
accel_mat1(j*nq+k,j*nq+k) = val_tmp1;
accel_mat1(j*nq+k,(j+1)*nq+k) = val_tmp2;
accel_mat2(j*nq+k,j*nq+k) = val_tmp3;
accel_mat2(j*nq+k,(j+1)*nq+k) = val_tmp4;
}
}
for(int k = 0;k<nq;k++)
{
double val_tmp1 = 6.0/(dt[nT-2]*dt[nT-2]);
double val_tmp2 = -val_tmp1;
double val_tmp3 = 2.0/dt[nT-2];
double val_tmp4 = 4.0/dt[nT-2];
accel_mat1((nT-1)*nq+k,(nT-2)*nq+k) = val_tmp1;
accel_mat1((nT-1)*nq+k,(nT-1)*nq+k) = val_tmp2;
accel_mat2((nT-1)*nq+k,(nT-2)*nq+k) = val_tmp3;
accel_mat2((nT-1)*nq+k,(nT-1)*nq+k) = val_tmp4;
}
accel_mat.resize(nq*nT,nq*nT);
accel_mat = accel_mat1+accel_mat2.block(0,nq,nq*nT,nq*(nT-2))*velocity_mat;
accel_mat_qd0.resize(nq*nT,nq);
accel_mat_qd0 = accel_mat2.block(0,0,nq*nT,nq)+accel_mat2.block(0,nq,nq*nT,nq*(nT-2))*velocity_mat_qd0;
accel_mat_qdf.resize(nq*nT,nq);
accel_mat_qdf = accel_mat2.block(0,(nT-1)*nq,nT*nq,nq)+accel_mat2.block(0,nq,nq*nT,nq*(nT-2))*velocity_mat_qdf;
qfree_idx = new snopt::integer[nq*num_qfree];
qdotf_idx = new snopt::integer[nq];
if(!fixInitialState)
{
qdot0_idx = new snopt::integer [nq];
}
else
{
qdot0_idx = nullptr;
}
int qdot_idx_start = 0;
if(qscActiveFlag)
{
nx= nq*(num_qfree+num_qdotfree)+num_qsc_pts*num_qfree;
for(int j = 0;j<num_qfree;j++)
{
for(int k = 0;k<nq;k++)
{
qfree_idx[j*nq+k] = j*(nq+num_qsc_pts)+k;
}
}
qdot_idx_start = (nq+num_qsc_pts)*num_qfree;
}
else
{
nx = nq*(num_qfree+num_qdotfree);
for(int j = 0;j<num_qfree*nq;j++)
{
qfree_idx[j] = j;
}
qdot_idx_start = nq*num_qfree;
}
if(!fixInitialState)
{
for(int j = 0;j<nq;j++)
{
qdot0_idx[j] = qdot_idx_start+j;
qdotf_idx[j] = qdot_idx_start+nq+j;
}
}
else
{
for(int j = 0;j<nq;j++)
{
qdotf_idx[j] = qdot_idx_start+j;
}
}
snopt::doublereal* xlow = new snopt::doublereal[nx];
snopt::doublereal* xupp = new snopt::doublereal[nx];
for(int j = 0;j<num_qfree;j++)
{
if(qscActiveFlag)
{
for(int k = 0;k<nq;k++)
{
xlow[j*(nq+num_qsc_pts)+k] = joint_limit_min((j+qstart_idx)*nq+k);
xupp[j*(nq+num_qsc_pts)+k] = joint_limit_max((j+qstart_idx)*nq+k);
}
//memcpy(xlow+j*(nq+num_qsc_pts),joint_limit_min.data()+(j+qstart_idx)*nq,sizeof(double)*nq);
//memcpy(xupp+j*(nq+num_qsc_pts),joint_limit_max.data()+(j+qstart_idx)*nq,sizeof(double)*nq);
for(int k = 0;k<num_qsc_pts;k++)
{
xlow[j*(nq+num_qsc_pts)+nq+k] = 0.0;
xupp[j*(nq+num_qsc_pts)+nq+k] = 1.0;
}
}
else
{
for(int k = 0;k<nq;k++)
{
xlow[j*nq+k] = joint_limit_min(k,j+qstart_idx);
xupp[j*nq+k] = joint_limit_max(k,j+qstart_idx);
}
//memcpy(xlow+j*nq,joint_limit_min.col(j+qstart_idx).data(),sizeof(double)*nq);
//memcpy(xupp+j*nq,joint_limit_max.col(j+qstart_idx).data(),sizeof(double)*nq);
}
}
if(fixInitialState)
{
for(int k = 0; k<nq; k++)
{
xlow[qdotf_idx[0]+k] = qdf_lb(k);
xupp[qdotf_idx[0]+k] = qdf_ub(k);
}
//memcpy(xlow+qdotf_idx[0],qdf_lb.data(),sizeof(double)*nq);
//memcpy(xupp+qdotf_idx[0],qdf_ub.data(),sizeof(double)*nq);
}
else
{
for(int k = 0;k<nq;k++)
{
xlow[qdot0_idx[0]+k] = qd0_lb(k);
xupp[qdot0_idx[0]+k] = qd0_ub(k);
xlow[qdotf_idx[0]+k] = qdf_lb(k);
xupp[qdotf_idx[0]+k] = qdf_ub(k);
}
//memcpy(xlow+qdot0_idx[0], qd0_lb.data(),sizeof(double)*nq);
//memcpy(xupp+qdot0_idx[0], qd0_ub.data(),sizeof(double)*nq);
//memcpy(xlow+qdotf_idx[0], qdf_lb.data(),sizeof(double)*nq);
//memcpy(xupp+qdotf_idx[0], qdf_ub.data(),sizeof(double)*nq);
}
set<double> t_set(t,t+nT);
VectorXd inbetween_tSamples;
inbetween_tSamples.resize(0);
t_inbetween = new VectorXd[nT-1];
for(int i = 0;i<nT-1;i++)
{
t_inbetween[i].resize(0);
}
{
RowVectorXd inbetween_tSamples_tmp;
ikoptions.getAdditionaltSamples(inbetween_tSamples_tmp);
int num_inbetween_tSamples_tmp = inbetween_tSamples_tmp.cols();
int knot_idx = 0;
for(int i = 0;i<num_inbetween_tSamples_tmp;i++)
{
if(inbetween_tSamples_tmp(i)>t[0] && inbetween_tSamples_tmp(i)<t[nT-1] && t_set.find(inbetween_tSamples_tmp(i))==t_set.end())
{
inbetween_tSamples.conservativeResize(inbetween_tSamples.size()+1);
inbetween_tSamples(inbetween_tSamples.size()-1) = (inbetween_tSamples_tmp(i));
{
while(t[knot_idx+1]<inbetween_tSamples_tmp(i))
{
knot_idx++;
}
t_inbetween[knot_idx].conservativeResize(t_inbetween[knot_idx].size()+1);
t_inbetween[knot_idx](t_inbetween[knot_idx].size()-1) = (inbetween_tSamples_tmp(i)-t[knot_idx]);
}
}
}
}
num_inbetween_tSamples = inbetween_tSamples.size();
qknot_qsamples_idx = new snopt::integer[nT];
t_samples = new double[nT+num_inbetween_tSamples];
{
int t_samples_idx = 0;
for(int i = 0;i<nT-1;i++)
{
qknot_qsamples_idx[i] = t_samples_idx;
t_samples[t_samples_idx] = t[i];
for(int j = 0;j<t_inbetween[i].size();j++)
{
t_samples[t_samples_idx+1+j] = t_inbetween[i](j)+t[i];
}
t_samples_idx += 1+t_inbetween[i].size();
}
qknot_qsamples_idx[nT-1] = nT+num_inbetween_tSamples-1;
t_samples[nT+num_inbetween_tSamples-1] = t[nT-1];
}
dqInbetweendqknot = new MatrixXd[nT-1];
dqInbetweendqd0 = new MatrixXd[nT-1];
dqInbetweendqdf = new MatrixXd[nT-1];
for(int i = 0;i<nT-1;i++)
{
VectorXd dt_ratio_inbetween_i = t_inbetween[i]/dt[i];
int nt_sample_inbetween_i = t_inbetween[i].size();
dqInbetweendqknot[i] = MatrixXd::Zero(nt_sample_inbetween_i*nq,nq*nT);
dqInbetweendqdf[i] = MatrixXd::Zero(nt_sample_inbetween_i*nq,nq);
dqInbetweendqdf[i] = MatrixXd::Zero(nt_sample_inbetween_i*nq,nq);
MatrixXd dq_idqdknot_i = MatrixXd::Zero(nt_sample_inbetween_i*nq,nq);
MatrixXd dq_idqdknot_ip1 = MatrixXd::Zero(nt_sample_inbetween_i*nq,nq);
for(int j = 0;j<nt_sample_inbetween_i;j++)
{
double val1 = 1.0-3.0*pow(dt_ratio_inbetween_i[j],2)+2.0*pow(dt_ratio_inbetween_i[j],3);
double val2 = 3.0*pow(dt_ratio_inbetween_i[j],2)-2.0*pow(dt_ratio_inbetween_i[j],3);
double val3 = (1.0-2.0*dt_ratio_inbetween_i[j]+pow(dt_ratio_inbetween_i[j],2))*t_inbetween[i](j);
double val4 = (pow(dt_ratio_inbetween_i[j],2)-dt_ratio_inbetween_i[j])*t_inbetween[i](j);
for(int k = 0;k<nq;k++)
{
dqInbetweendqknot[i](j*nq+k,i*nq+k) = val1;
dqInbetweendqknot[i](j*nq+k,(i+1)*nq+k) = val2;
dq_idqdknot_i(j*nq+k,k) = val3;
dq_idqdknot_ip1(j*nq+k,k) = val4;
}
}
if(i>=1 && i<=nT-3)
{
dqInbetweendqknot[i] += dq_idqdknot_i*velocity_mat.block((i-1)*nq,0,nq,nq*nT)+dq_idqdknot_ip1*velocity_mat.block(i*nq,0,nq,nq*nT);
dqInbetweendqd0[i] = dq_idqdknot_i*velocity_mat_qd0.block((i-1)*nq,0,nq,nq)+dq_idqdknot_ip1*velocity_mat_qd0.block(i*nq,0,nq,nq);
dqInbetweendqdf[i] = dq_idqdknot_i*velocity_mat_qdf.block((i-1)*nq,0,nq,nq)+dq_idqdknot_ip1*velocity_mat_qdf.block(i*nq,0,nq,nq);
}
else if(i == 0 && i != nT-2)
{
dqInbetweendqknot[i] += dq_idqdknot_ip1*velocity_mat.block(i*nq,0,nq,nq*nT);
dqInbetweendqd0[i] = dq_idqdknot_i+dq_idqdknot_ip1*velocity_mat_qd0.block(i*nq,0,nq,nq);
dqInbetweendqdf[i] = dq_idqdknot_ip1*velocity_mat_qdf.block(i*nq,0,nq,nq);
}
else if(i == nT-2&& i != 0)
{
dqInbetweendqknot[i] += dq_idqdknot_i*velocity_mat.block((i-1)*nq,0,nq,nq*nT);
dqInbetweendqd0[i] = dq_idqdknot_i*velocity_mat_qd0.block((i-1)*nq,0,nq,nq);
dqInbetweendqdf[i] = dq_idqdknot_i*velocity_mat_qdf.block((i-1)*nq,0,nq,nq)+dq_idqdknot_ip1;
}
else if(i == 0 && i == nT-2)
{
dqInbetweendqd0[i] = dq_idqdknot_i;
dqInbetweendqdf[i] = dq_idqdknot_ip1;
}
}
snopt::integer* nc_inbetween_array = new snopt::integer[num_inbetween_tSamples];
snopt::integer* nG_inbetween_array = new snopt::integer[num_inbetween_tSamples];
VectorXd* Cmin_inbetween_array = new VectorXd[num_inbetween_tSamples];
VectorXd* Cmax_inbetween_array = new VectorXd[num_inbetween_tSamples];
VectorXi* iCfun_inbetween_array = new VectorXi[num_inbetween_tSamples];
VectorXi* jCvar_inbetween_array = new VectorXi[num_inbetween_tSamples];
vector<string>* Cname_inbetween_array = new vector<string>[num_inbetween_tSamples];
for(int i = 0;i<num_inbetween_tSamples;i++)
{
nc_inbetween_array[i] = 0;
nG_inbetween_array[i] = 0;
Cmin_inbetween_array[i].resize(0);
Cmax_inbetween_array[i].resize(0);
iCfun_inbetween_array[i].resize(0);
jCvar_inbetween_array[i].resize(0);
for(int j = 0;j<num_st_kc;j++)
{
double* t_inbetween_ptr = inbetween_tSamples.data()+i;
int nc = st_kc_array[j]->getNumConstraint(t_inbetween_ptr);
VectorXd lb(nc,1);
VectorXd ub(nc,1);
st_kc_array[j]->bounds(t_inbetween_ptr,lb,ub);
Cmin_inbetween_array[i].conservativeResize(Cmin_inbetween_array[i].size()+nc);
Cmin_inbetween_array[i].tail(nc) = lb;
Cmax_inbetween_array[i].conservativeResize(Cmax_inbetween_array[i].size()+nc);
Cmax_inbetween_array[i].tail(nc) = ub;
iCfun_inbetween_array[i].conservativeResize(iCfun_inbetween_array[i].size()+nc*nq*(num_qfree+num_qdotfree));
jCvar_inbetween_array[i].conservativeResize(jCvar_inbetween_array[i].size()+nc*nq*(num_qfree+num_qdotfree));
VectorXi iCfun_append = VectorXi::Zero(nc*nq*(num_qfree+num_qdotfree));
VectorXi jCvar_append = VectorXi::Zero(nc*nq*(num_qfree+num_qdotfree));
for(int k = 0;k<nq*(num_qfree+num_qdotfree);k++)
{
for(int l = 0;l<nc;l++)
{
iCfun_append(k*nc+l) = nc_inbetween_array[i]+l;
}
}
iCfun_inbetween_array[i].tail(nc*nq*(num_qfree+num_qdotfree)) = iCfun_append;
for(int k = 0;k<nq*num_qfree;k++)
{
for(int l = 0;l<nc;l++)
{
jCvar_append(k*nc+l) = qfree_idx[k];
}
}
if(fixInitialState)
{
for(int k = nq*num_qfree;k<nq*num_qfree+nq;k++)
{
for(int l = 0;l<nc;l++)
{
jCvar_append(k*nc+l) = qdotf_idx[k-nq*num_qfree];
}
}
}
else
{
for(int k = nq*num_qfree;k<nq*num_qfree+nq;k++)
{
for(int l = 0;l<nc;l++)
{
jCvar_append(k*nc+l) = qdot0_idx[k-nq*num_qfree];
}
}
for(int k = nq*num_qfree+nq;k<nq*num_qfree+2*nq;k++)
{
for(int l = 0;l<nc;l++)
{
jCvar_append(k*nc+l) = qdotf_idx[k-nq*num_qfree-nq];
}
}
}
jCvar_inbetween_array[i].tail(nc*nq*(num_qfree+num_qdotfree)) = jCvar_append;
nc_inbetween_array[i] += nc;
nG_inbetween_array[i] += nc*nq*(num_qfree+num_qdotfree);
if(debug_mode)
{
vector<string> constraint_name;
st_kc_array[j]->name(t_inbetween_ptr,constraint_name);
Cname_inbetween_array[i].insert(Cname_inbetween_array[i].end(),constraint_name.begin(),constraint_name.end());
}
}
}
// parse the constraint for MultipleTimeLinearPostureConstraint at time t
mt_lpc_nc = new int[num_mt_lpc];
int* mtlpc_nA = new int[num_mt_lpc];
VectorXi* mtlpc_iAfun = new VectorXi[num_mt_lpc];
VectorXi* mtlpc_jAvar = new VectorXi[num_mt_lpc];
VectorXd* mtlpc_A = new VectorXd[num_mt_lpc];
VectorXd* mtlpc_lb = new VectorXd[num_mt_lpc];
VectorXd* mtlpc_ub = new VectorXd[num_mt_lpc];
for(int j = 0;j<num_mt_lpc;j++)
{
mt_lpc_nc[j] = mt_lpc_array[j]->getNumConstraint(t,nT);
VectorXi mtlpc_iAfun_j;
VectorXi mtlpc_jAvar_j;
VectorXd mtlpc_A_j;
mt_lpc_array[j]->geval(t,nT,mtlpc_iAfun_j,mtlpc_jAvar_j,mtlpc_A_j);
VectorXd mtlpc_lb_j;
VectorXd mtlpc_ub_j;
mt_lpc_array[j]->bounds(t,nT,mtlpc_lb_j,mtlpc_ub_j);
vector<bool> valid_t_flag = mt_lpc_array[j]->isTimeValid(t,nT);
if(fixInitialState && valid_t_flag.at(0))
{
int num_mtlpc_q0idx = 0;
for(int k = 0;k<mtlpc_A_j.size();k++)
{
if(mtlpc_jAvar_j(k)<nq)
{
num_mtlpc_q0idx++;
}
}
mtlpc_iAfun[j].resize(mtlpc_A_j.size()-num_mtlpc_q0idx);
mtlpc_jAvar[j].resize(mtlpc_A_j.size()-num_mtlpc_q0idx);
mtlpc_A[j].resize(mtlpc_A_j.size()-num_mtlpc_q0idx);
SparseMatrix<double> mtlpc_q0_gradmat;
mtlpc_q0_gradmat.resize(mt_lpc_nc[j],nq);
mtlpc_q0_gradmat.reserve(num_mtlpc_q0idx);
int mtlpc_A_j_ind = 0;
for(int k = 0;k<mtlpc_A_j.size();k++)
{
if(mtlpc_jAvar_j(k)>=nq)
{
mtlpc_iAfun[j](mtlpc_A_j_ind) = mtlpc_iAfun_j(k);
mtlpc_jAvar[j](mtlpc_A_j_ind) = qfree_idx[mtlpc_jAvar_j(k)-nq];
mtlpc_A[j](mtlpc_A_j_ind) = mtlpc_A_j(k);
mtlpc_A_j_ind++;
}
else
{
mtlpc_q0_gradmat.insert(mtlpc_iAfun_j(k),mtlpc_jAvar_j(k)) = mtlpc_A_j(k);
}
}
mtlpc_ub[j] = mtlpc_ub_j-mtlpc_q0_gradmat*q0_fixed;
mtlpc_lb[j] = mtlpc_lb_j-mtlpc_q0_gradmat*q0_fixed;
mtlpc_nA[j] = mtlpc_A_j.size()-num_mtlpc_q0idx;
}
else
{
mtlpc_A[j] = mtlpc_A_j;
mtlpc_iAfun[j] = mtlpc_iAfun_j;
mtlpc_jAvar[j].resize(mtlpc_A_j.size());
for(int k = 0;k<mtlpc_A_j.size();k++)
{
mtlpc_jAvar[j](k) = qfree_idx[mtlpc_jAvar_j(k)-nq*qstart_idx];
}
mtlpc_ub[j] = mtlpc_ub_j;
mtlpc_lb[j] = mtlpc_lb_j;
mtlpc_nA[j] = mtlpc_A_j.size();
}
}
nF = 1;
nG = nq*(num_qfree+num_qdotfree);
snopt::integer lenA = 0;
for(int j = qstart_idx;j<nT;j++)
{
nF += nc_array[j];
nG += nG_array[j];
lenA += nA_array[j];
}
for(int j = 0;j<num_inbetween_tSamples;j++)
{
nF += nc_inbetween_array[j];
nG += nG_inbetween_array[j];
}
mt_kc_nc = new int[num_mt_kc];
for(int j = 0;j<num_mt_kc;j++)
{
mt_kc_nc[j] = mt_kc_array[j]->getNumConstraint(t_samples+qstart_idx,num_qfree+num_inbetween_tSamples);
nF += mt_kc_nc[j];
nG += mt_kc_nc[j]*nq*(num_qfree+num_qdotfree);
}
for(int j = 0;j<num_mt_lpc;j++)
{
nF += mt_lpc_nc[j];
lenA += mtlpc_nA[j];
}
snopt::doublereal* Flow = new snopt::doublereal[nF];
snopt::doublereal* Fupp = new snopt::doublereal[nF];
string* Fname = new string[nF];
snopt::integer* iGfun = new snopt::integer[nG];
snopt::integer* jGvar = new snopt::integer[nG];
snopt::integer* iAfun;
snopt::integer* jAvar;
snopt::doublereal* A;
if(lenA>0)
{
iAfun = new snopt::integer[lenA];
jAvar = new snopt::integer[lenA];
A = new snopt::doublereal[lenA];
}
else
{
iAfun = nullptr;
jAvar = nullptr;
A = nullptr;
}
Flow[0] = -1.0/0.0;
Fupp[0] = 1.0/0.0;
if(debug_mode)
{
Fname[0] = string("Objective");
}
for(int j = 0;j<nq*num_qfree;j++)
{
iGfun[j] = 1;
jGvar[j] = qfree_idx[j]+1;//C interface uses 1 index
}
for(int j = 0;j<nq;j++)
{
if(fixInitialState)
{
iGfun[j+nq*num_qfree] = 1;
jGvar[j+nq*num_qfree] = qdotf_idx[j]+1;//C interface uses 1 index
}
else
{
iGfun[j+nq*num_qfree] = 1;
jGvar[j+nq*num_qfree] = qdot0_idx[j]+1;
iGfun[j+nq+nq*num_qfree] = 1;
jGvar[j+nq+nq*num_qfree] = qdotf_idx[j]+1;
}
}
snopt::integer nf_cum = 1;
snopt::integer nG_cum = nq*(num_qfree+num_qdotfree);
snopt::integer nA_cum = 0;
int x_start_idx = 0;
for(int j = qstart_idx;j<nT;j++)
{
for(int k = 0;k<nc_array[j];k++)
{
Flow[nf_cum+k] = Cmin_array[j](k);
Fupp[nf_cum+k] = Cmax_array[j](k);
}
//memcpy(Flow+nf_cum,Cmin_array[j].data(),sizeof(double)*nc_array[j]);
//memcpy(Fupp+nf_cum,Cmax_array[j].data(),sizeof(double)*nc_array[j]);
if(debug_mode)
{
for(int k = 0;k<Cname_array[j].size();k++)
{
Fname[nf_cum+k] = Cname_array[j][k];
}
}
for(int k = 0;k<nG_array[j];k++)
{
iGfun[nG_cum+k] = nf_cum+iCfun_array[j][k];
jGvar[nG_cum+k] = x_start_idx+jCvar_array[j][k];
}
for(int k = 0;k<nA_array[j];k++)
{
iAfun[nA_cum+k] = nf_cum+iAfun_array[j][k];
jAvar[nA_cum+k] = x_start_idx+jAvar_array[j][k];
A[nA_cum+k] = A_array[j][k];
}
nf_cum += nc_array[j];
nG_cum += nG_array[j];
nA_cum += nA_array[j];
if(qscActiveFlag)
{
x_start_idx += nq+num_qsc_pts;
}
else
{
x_start_idx += nq;
}
}
// parse the inbetween samples constraints
//
for(int j = 0;j<num_inbetween_tSamples;j++)
{
for(int k = 0;k<nc_inbetween_array[j];k++)
{
Flow[nf_cum+k] = Cmin_inbetween_array[j](k);
Fupp[nf_cum+k] = Cmax_inbetween_array[j](k);
}
//memcpy(Flow+nf_cum,Cmin_inbetween_array[j].data(),sizeof(double)*nc_inbetween_array[j]);
//memcpy(Fupp+nf_cum,Cmax_inbetween_array[j].data(),sizeof(double)*nc_inbetween_array[j]);
if(debug_mode)
{
for(int k = 0;k<nc_inbetween_array[j];k++)
{
Fname[nf_cum+k] = Cname_inbetween_array[j][k];
}
}
for(int k = 0;k<nG_inbetween_array[j];k++)
{
iGfun[nG_cum+k] = nf_cum+iCfun_inbetween_array[j][k]+1;
jGvar[nG_cum+k] = jCvar_inbetween_array[j][k]+1;
}
nf_cum += nc_inbetween_array[j];
nG_cum += nG_inbetween_array[j];
}
//
// Parse MultipleTimeKinematicConstraint.
for(int j = 0;j<num_mt_kc;j++)
{
VectorXd mtkc_lb(mt_kc_nc[j]);
VectorXd mtkc_ub(mt_kc_nc[j]);
mt_kc_array[j]->bounds(t_samples+qstart_idx,num_qfree+num_inbetween_tSamples,mtkc_lb,mtkc_ub);
for(int k = 0;k<mt_kc_nc[j];k++)
{
Flow[nf_cum+k] = mtkc_lb(k);
Fupp[nf_cum+k] = mtkc_ub(k);
}
//memcpy(Flow+nf_cum,mtkc_lb.data(),sizeof(double)*mt_kc_nc[j]);
//memcpy(Fupp+nf_cum,mtkc_ub.data(),sizeof(double)*mt_kc_nc[j]);
vector<string> mtkc_name;
mt_kc_array[j]->name(t_samples+qstart_idx,num_qfree+num_inbetween_tSamples,mtkc_name);
if(debug_mode)
{
for(int k = 0;k<mt_kc_nc[j];k++)
{
Fname[nf_cum+k] = mtkc_name[k];
}
}
for(int l = 0;l<nq*(num_qfree+num_qdotfree);l++)
{
for(int k = 0;k<mt_kc_nc[j];k++)
{
iGfun[nG_cum+l*mt_kc_nc[j]+k] = nf_cum+k+1;
}
}
for(int l = 0;l<nq*num_qfree;l++)
{
for(int k = 0;k<mt_kc_nc[j];k++)
{
jGvar[nG_cum+l*mt_kc_nc[j]+k] = qfree_idx[l]+1;
}
}
if(fixInitialState)
{
for(int l = nq*num_qfree;l<nq*num_qfree+nq;l++)
{
for(int k = 0;k<mt_kc_nc[j];k++)
{
jGvar[nG_cum+l*mt_kc_nc[j]+k] = qdotf_idx[l-nq*num_qfree]+1;
}
}
}
else
{
for(int l=nq*num_qfree;l<nq*num_qfree+nq;l++)
{
for(int k = 0;k<mt_kc_nc[j];k++)
{
jGvar[nG_cum+l*mt_kc_nc[j]+k] = qdot0_idx[l-nq*num_qfree]+1;
}
}
for(int l = nq*num_qfree+nq;l<nq*num_qfree+2*nq;l++)
{
for(int k = 0;k<mt_kc_nc[j];k++)
{
jGvar[nG_cum+l*mt_kc_nc[j]+k] = qdotf_idx[l-nq*num_qfree-nq]+1;
}
}
}
nf_cum += mt_kc_nc[j];
nG_cum += mt_kc_nc[j]*nq*(num_qfree+num_qdotfree);
}
// parse MultipleTimeLinearPostureConstraint for t
for(int j = 0;j<num_mt_lpc;j++)
{
for(int k = 0;k<mtlpc_nA[j];k++)
{
iAfun[nA_cum+k] = nf_cum+mtlpc_iAfun[j](k)+1;
jAvar[nA_cum+k] = mtlpc_jAvar[j](k)+1;
A[nA_cum+k] = mtlpc_A[j](k);
}
for(int k = 0;k<mt_lpc_nc[j];k++)
{
Fupp[nf_cum+k] = mtlpc_ub[j](k);
Flow[nf_cum+k] = mtlpc_lb[j](k);
}
nf_cum += mt_lpc_nc[j];
nA_cum += mtlpc_nA[j];
}
snopt::doublereal* x = new snopt::doublereal[nx];
if(qscActiveFlag)
{
for(int j = 0;j<num_qfree;j++)
{
for(int k = 0;k<nq;k++)
{
x[j*(nq+num_qsc_pts)+k] = q_seed((j+qstart_idx)*nq+k);
}
//memcpy(x+j*(nq+num_qsc_pts),q_seed.data()+(j+qstart_idx)*nq,sizeof(double)*nq);
for(int k = 0;k<num_qsc_pts;k++)
{
x[j*(nq+num_qsc_pts)+nq+k] = 1.0/num_qsc_pts;
}
}
}
else
{
for(int j = 0;j<nq*num_qfree;j++)
{
x[j] = q_seed(nq*qstart_idx+j);
}
//memcpy(x,q_seed.data()+nq*qstart_idx,sizeof(double)*nq*num_qfree);
}
if(fixInitialState)
{
for(int j = 0;j<nq;j++)
{
x[qdotf_idx[0]+j] = qdf_seed(j);
}
//memcpy(x+qdotf_idx[0],qdf_seed.data(),sizeof(double)*nq);
}
else
{
for(int j = 0;j<nq;j++)
{
x[qdot0_idx[0]+j] = qd0_seed(j);
x[qdotf_idx[0]+j] = qdf_seed(j);
}
//memcpy(x+qdot0_idx[0],qd0_seed.data(),sizeof(double)*nq);
//memcpy(x+qdotf_idx[0],qdf_seed.data(),sizeof(double)*nq);
}
for(int i = 0;i<nx;i++)
{
if(std::isnan(x[i]))
{
x[i] = 0.0;
}
}
snopt::integer minrw,miniw,mincw;
snopt::integer lenrw = 20000000, leniw = 2000000, lencw = 5000;
snopt::doublereal* rw;
rw = (snopt::doublereal*) std::calloc(lenrw,sizeof(snopt::doublereal));
snopt::integer* iw;
iw = (snopt::integer*) std::calloc(leniw,sizeof(snopt::integer));
char cw[8*lencw];
snopt::integer Cold = 0; //, Basis = 1; //, Warm = 2;
snopt::doublereal *xmul = new snopt::doublereal[nx];
snopt::integer *xstate = new snopt::integer[nx];
for(int j = 0;j<nx;j++)
{
xstate[j] = 0;
}
snopt::doublereal *F = new snopt::doublereal[nF];
snopt::doublereal *Fmul = new snopt::doublereal[nF];
snopt::integer *Fstate = new snopt::integer[nF];
for(int j = 0;j<nF;j++)
{
Fstate[j] = 0;
}
snopt::doublereal ObjAdd = 0.0;
snopt::integer ObjRow = 1;
snopt::integer nxname = 1, nFname = 1, npname = 0;
char* xnames = new char[nxname*8];
char* Fnames = new char[nFname*8];
char Prob[200];
// snopt::integer iSpecs = -1, spec_len;
snopt::integer iSumm = -1;
snopt::integer iPrint = -1; //, prnt_len;
snopt::integer nS, nInf;
snopt::doublereal sInf;
snopt::sninit_(&iPrint,&iSumm,cw,&lencw,iw,&leniw,rw,&lenrw,8*500);
char strOpt1[200] = "Derivative option";
snopt::integer DerOpt = 1, strOpt_len = strlen(strOpt1);
snopt::snseti_(strOpt1,&DerOpt,&iPrint,&iSumm,INFO_snopt,cw,&lencw,iw,&leniw,rw,&lenrw,strOpt_len,8*500);
char strOpt2[200] = "Major optimality tolerance";
strOpt_len = strlen(strOpt2);
snopt::snsetr_(strOpt2,&SNOPT_MajorOptimalityTolerance,&iPrint,&iSumm,INFO_snopt,cw,&lencw,iw,&leniw,rw,&lenrw,strOpt_len,8*500);
char strOpt3[200] = "Major feasibility tolerance";
strOpt_len = strlen(strOpt3);
snopt::snsetr_(strOpt3,&SNOPT_MajorFeasibilityTolerance,&iPrint,&iSumm,INFO_snopt,cw,&lencw,iw,&leniw,rw,&lenrw,strOpt_len,8*500);
char strOpt4[200] = "Superbasics limit";
strOpt_len = strlen(strOpt4);
snopt::snseti_(strOpt4,&SNOPT_SuperbasicsLimit,&iPrint,&iSumm,INFO_snopt,cw,&lencw,iw,&leniw,rw,&lenrw,strOpt_len,8*500);
char strOpt5[200] = "Major iterations limit";
strOpt_len = strlen(strOpt5);
snopt::snseti_(strOpt5,&SNOPT_MajorIterationsLimit,&iPrint,&iSumm,INFO_snopt,cw,&lencw,iw,&leniw,rw,&lenrw,strOpt_len,8*500);
char strOpt6[200] = "Iterations limit";
strOpt_len = strlen(strOpt6);
snopt::snseti_(strOpt6,&SNOPT_IterationsLimit,&iPrint,&iSumm,INFO_snopt,cw,&lencw,iw,&leniw,rw,&lenrw,strOpt_len,8*500);
//debug only
/*MATFile *pmat;
pmat = matOpen("inverseKinBackend_cpp.mat","w");
if(pmat == NULL)
{
printf("Error creating mat file\n");
}
nx_tmp = nx;
nG_tmp = nG;
nF_tmp = nF;
printf("start to debug\n");
VectorXd f_vec(nF,1);
VectorXd G_vec(nG,1);
VectorXd x_vec(nx,1);
for(int i = 0;i<nx;i++)
{
x_vec(i) = x[i];
}
snoptIKtraj_userfun(x_vec,f_vec,G_vec);
mxArray* f_ptr = mxCreateDoubleMatrix(nF,1,mxREAL);
mxArray* G_ptr = mxCreateDoubleMatrix(nG,1,mxREAL);
memcpy(mxGetPr(f_ptr),f_vec.data(),sizeof(double)*(nF));
memcpy(mxGetPr(G_ptr),G_vec.data(),sizeof(double)*(nG));
matPutVariable(pmat,"f",f_ptr);
matPutVariable(pmat,"G",G_ptr);
printf("got f,G\n");
double* iGfun_tmp = new double[nG];
double* jGvar_tmp = new double[nG];
mxArray* iGfun_ptr = mxCreateDoubleMatrix(nG,1,mxREAL);
mxArray* jGvar_ptr = mxCreateDoubleMatrix(nG,1,mxREAL);
for(int k = 0;k<nG;k++)
{
iGfun_tmp[k] = (double) iGfun[k];
jGvar_tmp[k] = (double) jGvar[k];
}
memcpy(mxGetPr(iGfun_ptr),iGfun_tmp,sizeof(double)*nG);
memcpy(mxGetPr(jGvar_ptr),jGvar_tmp,sizeof(double)*nG);
matPutVariable(pmat,"iGfun",iGfun_ptr);
matPutVariable(pmat,"jGvar",jGvar_ptr);
printf("got iGfun jGar\n");
mxArray* Fupp_ptr = mxCreateDoubleMatrix(nF,1,mxREAL);
memcpy(mxGetPr(Fupp_ptr),Fupp,sizeof(double)*nF);
matPutVariable(pmat,"Fupp",Fupp_ptr);
mxArray* Flow_ptr = mxCreateDoubleMatrix(nF,1,mxREAL);
memcpy(mxGetPr(Flow_ptr),Flow,sizeof(double)*nF);
matPutVariable(pmat,"Flow",Flow_ptr);
printf("got Fupp Flow\n");
mxArray* xupp_ptr = mxCreateDoubleMatrix(nx,1,mxREAL);
mxArray* xlow_ptr = mxCreateDoubleMatrix(nx,1,mxREAL);
memcpy(mxGetPr(xupp_ptr),xupp,sizeof(double)*nx);
memcpy(mxGetPr(xlow_ptr),xlow,sizeof(double)*nx);
matPutVariable(pmat,"xupp",xupp_ptr);
matPutVariable(pmat,"xlow",xlow_ptr);
printf("got xupp xlow\n");
mxArray* qd0_lb_ptr = mxCreateDoubleMatrix(nq,1,mxREAL);
mxArray* qd0_ub_ptr = mxCreateDoubleMatrix(nq,1,mxREAL);
memcpy(mxGetPr(qd0_lb_ptr),qd0_lb.data(),sizeof(double)*nq);
memcpy(mxGetPr(qd0_ub_ptr),qd0_ub.data(),sizeof(double)*nq);
matPutVariable(pmat,"qd0_lb",qd0_lb_ptr);
matPutVariable(pmat,"qd0_ub",qd0_ub_ptr);
mxArray* iAfun_ptr = mxCreateDoubleMatrix(lenA,1,mxREAL);
mxArray* jAvar_ptr = mxCreateDoubleMatrix(lenA,1,mxREAL);
mxArray* A_ptr = mxCreateDoubleMatrix(lenA,1,mxREAL);
double* iAfun_tmp = new double[lenA];
double* jAvar_tmp = new double[lenA];
for(int k = 0;k<lenA;k++)
{
iAfun_tmp[k] = (double) iAfun[k];
jAvar_tmp[k] = (double) jAvar[k];
}
memcpy(mxGetPr(iAfun_ptr),iAfun_tmp,sizeof(double)*lenA);
memcpy(mxGetPr(jAvar_ptr),jAvar_tmp,sizeof(double)*lenA);
memcpy(mxGetPr(A_ptr),A,sizeof(double)*lenA);
matPutVariable(pmat,"iAfun",iAfun_ptr);
matPutVariable(pmat,"jAvar",jAvar_ptr);
matPutVariable(pmat,"A",A_ptr);
printf("got iAfun jAvar A\n");
mxArray* velocity_mat_ptr = mxCreateDoubleMatrix(nq*(nT-2),nq*nT,mxREAL);
memcpy(mxGetPr(velocity_mat_ptr),velocity_mat.data(),sizeof(double)*nq*(nT-2)*nq*nT);
matPutVariable(pmat,"velocity_mat",velocity_mat_ptr);
mxArray* velocity_mat_qd0_ptr = mxCreateDoubleMatrix(nq*(nT-2),nq,mxREAL);
memcpy(mxGetPr(velocity_mat_qd0_ptr),velocity_mat_qd0.data(),sizeof(double)*velocity_mat_qd0.size());
matPutVariable(pmat,"velocity_mat_qd0",velocity_mat_qd0_ptr);
mxArray* velocity_mat_qdf_ptr = mxCreateDoubleMatrix(nq*(nT-2),nq,mxREAL);
memcpy(mxGetPr(velocity_mat_qdf_ptr),velocity_mat_qdf.data(),sizeof(double)*velocity_mat_qdf.size());
matPutVariable(pmat,"velocity_mat_qdf",velocity_mat_qdf_ptr);
mxArray* accel_mat_ptr = mxCreateDoubleMatrix(nq*nT,nq*nT,mxREAL);
memcpy(mxGetPr(accel_mat_ptr),accel_mat.data(),sizeof(double)*accel_mat.size());
matPutVariable(pmat,"accel_mat",accel_mat_ptr);
mxArray* accel_mat_qd0_ptr = mxCreateDoubleMatrix(nq*nT,nq,mxREAL);
memcpy(mxGetPr(accel_mat_qd0_ptr),accel_mat_qd0.data(),sizeof(double)*accel_mat_qd0.size());
matPutVariable(pmat,"accel_mat_qd0",accel_mat_qd0_ptr);
mxArray* accel_mat_qdf_ptr = mxCreateDoubleMatrix(nq*nT,nq,mxREAL);
memcpy(mxGetPr(accel_mat_qdf_ptr),accel_mat_qdf.data(),sizeof(double)*accel_mat_qdf.size());
matPutVariable(pmat,"accel_mat_qdf",accel_mat_qdf_ptr);
mxArray** dqInbetweendqknot_ptr = new mxArray*[nT-1];
mxArray** dqInbetweendqd0_ptr = new mxArray*[nT-1];
mxArray** dqInbetweendqdf_ptr = new mxArray*[nT-1];
mwSize cell_dim[1] = {nT-1};
mxArray* dqInbetweendqknot_cell = mxCreateCellArray(1,cell_dim);
mxArray* dqInbetweendqd0_cell = mxCreateCellArray(1,cell_dim);
mxArray* dqInbetweendqdf_cell = mxCreateCellArray(1,cell_dim);
for(int i = 0;i<nT-1;i++)
{
dqInbetweendqknot_ptr[i] = mxCreateDoubleMatrix(nq*t_inbetween[i].size(),nq*nT,mxREAL);
dqInbetweendqd0_ptr[i] = mxCreateDoubleMatrix(nq*t_inbetween[i].size(),nq,mxREAL);
dqInbetweendqdf_ptr[i] = mxCreateDoubleMatrix(nq*t_inbetween[i].size(),nq,mxREAL);
memcpy(mxGetPr(dqInbetweendqknot_ptr[i]),dqInbetweendqknot[i].data(),sizeof(double)*dqInbetweendqknot[i].size());
memcpy(mxGetPr(dqInbetweendqd0_ptr[i]),dqInbetweendqd0[i].data(),sizeof(double)*dqInbetweendqd0[i].size());
memcpy(mxGetPr(dqInbetweendqdf_ptr[i]),dqInbetweendqdf[i].data(),sizeof(double)*dqInbetweendqdf[i].size());
mxSetCell(dqInbetweendqknot_cell,i,dqInbetweendqknot_ptr[i]);
mxSetCell(dqInbetweendqd0_cell,i,dqInbetweendqd0_ptr[i]);
mxSetCell(dqInbetweendqdf_cell,i,dqInbetweendqdf_ptr[i]);
}
matPutVariable(pmat,"dqInbetweendqknot",dqInbetweendqknot_cell);
matPutVariable(pmat,"dqInbetweendqd0",dqInbetweendqd0_cell);
matPutVariable(pmat,"dqInbetweendqdf",dqInbetweendqdf_cell);
delete[] dqInbetweendqknot_ptr; delete[] dqInbetweendqd0_ptr; delete[] dqInbetweendqdf_ptr;
printf("get dqInbetweendqknot\n");
mxArray** iCfun_inbetween_ptr = new mxArray*[num_inbetween_tSamples];
mxArray** jCvar_inbetween_ptr = new mxArray*[num_inbetween_tSamples];
cell_dim[0] = num_inbetween_tSamples;
mxArray* iCfun_inbetween_cell = mxCreateCellArray(1,cell_dim);
mxArray* jCvar_inbetween_cell = mxCreateCellArray(1,cell_dim);
for(int i = 0;i<num_inbetween_tSamples;i++)
{
iCfun_inbetween_ptr[i] = mxCreateDoubleMatrix(nG_inbetween_array[i],1,mxREAL);
jCvar_inbetween_ptr[i] = mxCreateDoubleMatrix(nG_inbetween_array[i],1,mxREAL);
double* iCfun_inbetween_i_double = new double[nG_inbetween_array[i]];
double* jCvar_inbetween_i_double = new double[nG_inbetween_array[i]];
for(int j = 0;j<nG_inbetween_array[i];j++)
{
iCfun_inbetween_i_double[j] = (double) iCfun_inbetween_array[i](j)+1;
jCvar_inbetween_i_double[j] = (double) jCvar_inbetween_array[i](j)+1;
}
memcpy(mxGetPr(iCfun_inbetween_ptr[i]),iCfun_inbetween_i_double,sizeof(double)*nG_inbetween_array[i]);
memcpy(mxGetPr(jCvar_inbetween_ptr[i]),jCvar_inbetween_i_double,sizeof(double)*nG_inbetween_array[i]);
mxSetCell(iCfun_inbetween_cell,i,iCfun_inbetween_ptr[i]);
mxSetCell(jCvar_inbetween_cell,i,jCvar_inbetween_ptr[i]);
delete[] iCfun_inbetween_i_double; delete[] jCvar_inbetween_i_double;
}
matPutVariable(pmat,"iCfun_inbetween",iCfun_inbetween_cell);
matPutVariable(pmat,"jCvar_inbetween",jCvar_inbetween_cell);
delete[] iCfun_inbetween_ptr; delete[] jCvar_inbetween_ptr;
printf("get iCfun_inbetween\n");
matClose(pmat);
// end of debugging
*/
snopt::snopta_
( &Cold, &nF, &nx, &nxname, &nFname,
&ObjAdd, &ObjRow, Prob, snoptIKtrajfun,
iAfun, jAvar, &lenA, &lenA, A,
iGfun, jGvar, &nG, &nG,
xlow, xupp, xnames, Flow, Fupp, Fnames,
x, xstate, xmul, F, Fstate, Fmul,
INFO_snopt, &mincw, &miniw, &minrw,
&nS, &nInf, &sInf,
cw, &lencw, iw, &leniw, rw, &lenrw,
cw, &lencw, iw, &leniw, rw, &lenrw,
npname, 8*nxname, 8*nFname,
8*500, 8*500);
if(*INFO_snopt == 41)
{
nx_tmp = nx;
nG_tmp = nG;
nF_tmp = nF;
MatrixXd df_numerical(nF,nx);
VectorXd x_vec(nx_tmp);
memcpy(x_vec.data(),x,sizeof(double)*nx);
VectorXd c_vec(nF_tmp);
VectorXd G_vec(nG_tmp);
snoptIKtraj_userfun(x_vec,c_vec,G_vec);
MatrixXd df_userfun = MatrixXd::Zero(nF,nx);
for(int i = 0;i<nG;i++)
{
df_userfun(iGfun[i]-1,jGvar[i]-1) = G_vec(i);
}
gevalNumerical(&snoptIKtraj_fevalfun,x_vec,c_vec,df_numerical);
MatrixXd df_err = df_userfun-df_numerical;
df_err = df_err.cwiseAbs();
int max_err_row,max_err_col;
double max_err;
max_err = df_err.maxCoeff(&max_err_row,&max_err_col);
printf("The maximum gradient numerical error is %e, in row %d, col %d\nuser gradient is %e\n2nd order numerical gradient is %e\n",max_err,max_err_row+1,max_err_col+1,df_userfun(max_err_row,max_err_col),df_numerical(max_err_row,max_err_col));
MatrixXd df_numerical2;
gevalNumerical(&snoptIKtraj_fevalfun,x_vec,c_vec,df_numerical2,1);
printf("1st order numerical gradient is %e\n",df_numerical2(max_err_row,max_err_col));
// double err = 1e-10;
VectorXd x_vec_err(nx_tmp);
x_vec_err = VectorXd::Zero(nx_tmp);
x_vec_err(max_err_col) = 1e-10;
VectorXd G_vec1(nG_tmp);
VectorXd G_vec2(nG_tmp);
MatrixXd df_err2 = df_err.block(1,0,nF-1,nx);
printf("The maximum gradient numerical error, except in the cost function, is %e\n",df_err2.maxCoeff());
}
VectorXd qdot0(nq);
VectorXd qdotf(nq);
if(fixInitialState)
{
q_sol.block(0,0,nq,1) = q0_fixed;
}
for(int j = 0;j<nq*num_qfree;j++)
{
q_sol(j+nq*qstart_idx) = x[qfree_idx[j]];
}
for(int j = 0;j<nq;j++)
{
qdotf(j) = x[qdotf_idx[j]];
}
if(!fixInitialState)
{
for(int j = 0;j<nq;j++)
{
qdot0(j) = x[qdot0_idx[j]];
}
}
else
{
qdot0 = qdot0_fixed;
}
if(*INFO_snopt<10)
{
for(int i=0; i<nT;i++)
{
for(int j = 0;j<nq;j++)
{
q_sol(j,i) = q_sol(j,i)>joint_limit_min(j,i)?q_sol(j,i):joint_limit_min(j,i);
q_sol(j,i) = q_sol(j,i)<joint_limit_max(j,i)?q_sol(j,i):joint_limit_max(j,i);
}
}
}
qdot_sol.block(0,0,nq,1) = qdot0;
qdot_sol.block(0,nT-1,nq,1) = qdotf;
MatrixXd q_sol_tmp = q_sol;
q_sol_tmp.resize(nq*nT,1);
MatrixXd qdot_sol_tmp = velocity_mat*q_sol_tmp;
qdot_sol_tmp.resize(nq,nT-2);
qdot_sol.block(0,1,nq,nT-2) = qdot_sol_tmp;
MatrixXd qddot_sol_tmp(nq*nT,1);
qddot_sol_tmp= accel_mat*q_sol_tmp+accel_mat_qd0*qdot0+accel_mat_qdf*qdotf;
qddot_sol_tmp.resize(nq,nT);
qddot_sol = qddot_sol_tmp;
if(*INFO_snopt == 13 || *INFO_snopt == 31 || *INFO_snopt == 32)
{
double *ub_err = new double[nF];
double *lb_err = new double[nF];
double max_lb_err = -1.0/0.0;
double max_ub_err = -1.0/0.0;
bool *infeasible_constraint_idx = new bool[nF];
ub_err[0] = -1.0/0.0;
lb_err[0] = -1.0/0.0;
infeasible_constraint_idx[0] = false;
for(int j = 1;j<nF;j++)
{
ub_err[j] = F[j]-Fupp[j];
lb_err[j] = Flow[j]-F[j];
if(ub_err[j]>max_ub_err)
max_ub_err = ub_err[j];
if(lb_err[j]>max_lb_err)
max_lb_err = lb_err[j];
infeasible_constraint_idx[j] = ub_err[j]>5e-5 | lb_err[j] > 5e-5;
}
max_ub_err = (max_ub_err>0.0? max_ub_err: 0.0);
max_lb_err = (max_lb_err>0.0? max_lb_err: 0.0);
if(max_ub_err+max_lb_err>1e-4)
{
if(debug_mode)
{
for(int j = 1;j<nF;j++)
{
if(infeasible_constraint_idx[j])
{
infeasible_constraint.push_back(Fname[j]);
}
}
}
}
else if(*INFO_snopt == 13)
{
*INFO_snopt = 4;
}
else if(*INFO_snopt == 31)
{
*INFO_snopt = 5;
}
else if(*INFO_snopt == 32)
{
*INFO_snopt = 6;
}
delete[] ub_err;
delete[] lb_err;
delete[] infeasible_constraint_idx;
}
*INFO = static_cast<int>(*INFO_snopt);
delete rw;
delete[] xmul; delete[] xstate; delete[] xnames;
delete[] F; delete[] Fmul; delete[] Fstate; delete[] Fnames;
delete[] iGfun; delete[] jGvar;
if(!fixInitialState)
{
delete[] qdot0_idx;
}
if(lenA>0)
{
delete[] iAfun; delete[] jAvar; delete[] A;
}
delete[] x; delete[] xlow; delete[] xupp; delete[] Flow; delete[] Fupp; delete[] Fname;
delete[] dt; delete[] dt_ratio;
delete[] t_inbetween; delete[] t_samples; delete[] dqInbetweendqknot; delete[] dqInbetweendqd0; delete[] dqInbetweendqdf;
delete[] nc_inbetween_array; delete[] nG_inbetween_array; delete[] Cmin_inbetween_array; delete[] Cmax_inbetween_array;
delete[] iCfun_inbetween_array; delete[] jCvar_inbetween_array;
delete[] qknot_qsamples_idx;
delete[] mt_lpc_nc; delete[] mtlpc_nA; delete[] mtlpc_iAfun; delete[] mtlpc_jAvar; delete[] mtlpc_A; delete[] mtlpc_lb; delete[] mtlpc_ub;
}
if (INFO_snopt) delete[] INFO_snopt;
delete[] iAfun_array; delete[] jAvar_array; delete[] A_array;
if(mode == 2)
{
delete[] qfree_idx; delete[] qdotf_idx;
delete[] mt_kc_nc;
}
delete[] iCfun_array; delete[] jCvar_array;
delete[] Cmin_array; delete[] Cmax_array; delete[] Cname_array;
delete[] nc_array; delete[] nG_array; delete[] nA_array;
delete[] st_lpc_nc;
delete[] st_kc_array;
delete[] mt_kc_array;
delete[] st_lpc_array;
delete[] mt_lpc_array;
}
template void inverseKinBackend(RigidBodyManipulator* model, const int mode, const int nT, const double* t, const MatrixBase<Map<MatrixXd>> &q_seed, const MatrixBase<Map<MatrixXd>> &q_nom, const int num_constraints, RigidBodyConstraint** const constraint_array, MatrixBase<Map<MatrixXd>> &q_sol, MatrixBase<Map<MatrixXd>> &qdot_sol, MatrixBase<Map<MatrixXd>> &qddot_sol, int* INFO, vector<string> &infeasible_constraint, const IKoptions &ikoptions);
template void inverseKinBackend(RigidBodyManipulator* model, const int mode, const int nT, const double* t, const MatrixBase<MatrixXd> &q_seed, const MatrixBase<MatrixXd> &q_nom, const int num_constraints, RigidBodyConstraint** const constraint_array, MatrixBase<MatrixXd> &q_sol, MatrixBase<MatrixXd> &qdot_sol, MatrixBase<MatrixXd> &qddot_sol, int* INFO, vector<string> &infeasible_constraint, const IKoptions &ikoptions);
template void inverseKinBackend(RigidBodyManipulator* model, const int mode, const int nT, const double* t, const MatrixBase<Map<MatrixXd>> &q_seed, const MatrixBase<Map<MatrixXd>> &q_nom, const int num_constraints, RigidBodyConstraint** const constraint_array, MatrixBase<Map<MatrixXd>> &q_sol, MatrixBase<MatrixXd> &qdot_sol, MatrixBase<MatrixXd> &qddot_sol, int* INFO, vector<string> &infeasible_constraint, const IKoptions &ikoptions);
template void inverseKinBackend(RigidBodyManipulator* model, const int mode, const int nT, const double* t, const MatrixBase<Map<VectorXd>> &q_seed, const MatrixBase<Map<VectorXd>> &q_nom, const int num_constraints, RigidBodyConstraint** const constraint_array, MatrixBase<Map<VectorXd>> &q_sol, MatrixBase<Map<VectorXd>> &qdot_sol, MatrixBase<Map<VectorXd>> &qddot_sol, int* INFO, vector<string> &infeasible_constraint, const IKoptions &ikoptions);
template void inverseKinBackend(RigidBodyManipulator* model, const int mode, const int nT, const double* t, const MatrixBase<VectorXd> &q_seed, const MatrixBase<VectorXd> &q_nom, const int num_constraints, RigidBodyConstraint** const constraint_array, MatrixBase<VectorXd> &q_sol, MatrixBase<VectorXd> &qdot_sol, MatrixBase<VectorXd> &qddot_sol, int* INFO, vector<string> &infeasible_constraint, const IKoptions &ikoptions);
template void inverseKinBackend(RigidBodyManipulator* model, const int mode, const int nT, const double* t, const MatrixBase<Map<VectorXd>> &q_seed, const MatrixBase<Map<VectorXd>> &q_nom, const int num_constraints, RigidBodyConstraint** const constraint_array, MatrixBase<Map<VectorXd>> &q_sol, MatrixBase<VectorXd> &qdot_sol, MatrixBase<VectorXd> &qddot_sol, int* INFO, vector<string> &infeasible_constraint, const IKoptions &ikoptions);
| 36.325114 | 449 | 0.623039 | cmmccann |
6ae164f940897ef7a7809a325a0115e512703c1b | 643 | cpp | C++ | Source/Catastrophe_VS/Interactable/BaseClasses/InteractableObject.cpp | Enderderder/Catastrophe_VerticalSlice | 679a04e86db363c3bca642512b86f5b2a8cca1be | [
"MIT"
] | null | null | null | Source/Catastrophe_VS/Interactable/BaseClasses/InteractableObject.cpp | Enderderder/Catastrophe_VerticalSlice | 679a04e86db363c3bca642512b86f5b2a8cca1be | [
"MIT"
] | null | null | null | Source/Catastrophe_VS/Interactable/BaseClasses/InteractableObject.cpp | Enderderder/Catastrophe_VerticalSlice | 679a04e86db363c3bca642512b86f5b2a8cca1be | [
"MIT"
] | null | null | null | // Fill out your copyright notice in the Description page of Project Settings.
#include "InteractableObject.h"
#include "SimpleInteractableAnimated.h"
#include "SimpleInteractableStatic.h"
#include "Components/BoxComponent.h"
// Add default functionality here for any IInteractableObject functions that are not pure virtual.
void IInteractableObject::OnInteract_Implementation(class APlayerCharacter* _actor)
{
/// Interface Template function should not have any implementation
}
void IInteractableObject::OnUnInteract_Implementation(class APlayerCharacter* _actor)
{
/// Interface Template function should not have any implementation
}
| 33.842105 | 98 | 0.822706 | Enderderder |
6ae38fc40d71626ff45e82f13d0a74b14d28301d | 2,332 | cpp | C++ | Code/DataStructures/Tests/AllocatorTests.cpp | kvarcg/data_structures | 2646f00302813dcd5ca8d8136799066654761fc3 | [
"MIT"
] | null | null | null | Code/DataStructures/Tests/AllocatorTests.cpp | kvarcg/data_structures | 2646f00302813dcd5ca8d8136799066654761fc3 | [
"MIT"
] | null | null | null | Code/DataStructures/Tests/AllocatorTests.cpp | kvarcg/data_structures | 2646f00302813dcd5ca8d8136799066654761fc3 | [
"MIT"
] | null | null | null | // global includes //////////////////////////////
#include "Global.h"
#include "DataStructureTests.h"
#include "Allocators.h"
namespace DS {
template <typename Alloc1, typename Alloc2, typename T, std::size_t N>
void compareAllocators() {
Alloc1 al1;
Alloc1 al2;
T* v1 = static_cast<T*>(al1.allocate(N));
T* v2 = static_cast<T*>(al2.allocate(N));
for (std::size_t i = 0; i < N; ++i) {
al1.construct(&v1[i], i);
al2.construct(&v2[i], i);
}
for (std::size_t i = 0; i < N; ++i) {
T* v1_element = static_cast<T*>(&v1[i]);
T* v2_element = static_cast<T*>(&v2[i]);
// same data
X_ASSERT_IF_FALSE(*v1_element == *v2_element);
// different pointers
X_ASSERT_IF_FALSE(v1_element != v2_element);
}
for (std::size_t i = 0; i < N; ++i) {
al1.destroy(&v1[i]);
al2.destroy(&v2[i]);
}
al1.deallocate(v1, N);
al2.deallocate(v2, N);
}
template <typename Alloc, typename T, std::size_t N>
void testAllocator() {
Alloc al;
T* v = static_cast<T*>(al.allocate(N));
for (std::size_t i = 0; i < N; ++i) {
al.construct(&v[i], i);
}
for (std::size_t i = 0; i < N; ++i) {
al.destroy(&v[i]);
}
al.deallocate(v, N);
}
namespace TESTS {
void testAllocators() {
X_DEBUG_COMMENT("Started %s", __func__);
constexpr int element_size = 100;
testAllocator<std::allocator<GenericTestObject>, GenericTestObject, element_size>();
testAllocator<DS::AllocatorSimple<GenericTestObject>, GenericTestObject, element_size>();
testAllocator<DS::AllocatorDefault<GenericTestObject>, GenericTestObject, element_size>();
compareAllocators<std::allocator<GenericTestObject>, DS::AllocatorSimple<GenericTestObject>, GenericTestObject, element_size>();
compareAllocators<std::allocator<GenericTestObject>, DS::AllocatorDefault<GenericTestObject>, GenericTestObject, element_size>();
X_DEBUG_COMMENT("Finished %s", __func__);
}
} // namespace TESTS
} // namespace DS
int main() {
DS::TESTS::testAllocators();
return 0;
}
| 33.314286 | 141 | 0.56175 | kvarcg |
6ae6c680d69bb55b69673a944363a726a019ec22 | 4,435 | cpp | C++ | src/grafix/ImageFilter_ImageMagick.cpp | pfedick/pplib | afd01f0df6e2e63bb12bfef0a0667464b0845d1f | [
"BSD-2-Clause"
] | 1 | 2019-10-27T15:01:57.000Z | 2019-10-27T15:01:57.000Z | src/grafix/ImageFilter_ImageMagick.cpp | pfedick/pplib | afd01f0df6e2e63bb12bfef0a0667464b0845d1f | [
"BSD-2-Clause"
] | 5 | 2016-02-01T19:03:33.000Z | 2022-02-06T15:27:01.000Z | src/grafix/ImageFilter_ImageMagick.cpp | pfedick/pplib | afd01f0df6e2e63bb12bfef0a0667464b0845d1f | [
"BSD-2-Clause"
] | 1 | 2019-09-18T09:52:18.000Z | 2019-09-18T09:52:18.000Z | /*******************************************************************************
* This file is part of "Patrick's Programming Library", Version 7 (PPL7).
* Web: http://www.pfp.de/ppl/
*
* $Author$
* $Revision$
* $Date$
* $Id$
*
*******************************************************************************
* Copyright (c) 2013, Patrick Fedick <patrick@pfp.de>
* 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 HOLDER 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 AND 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 "prolog_ppl7.h"
#ifdef HAVE_STDIO_H
#include <stdio.h>
#endif
#ifdef HAVE_STDLIB_H
#include <stdlib.h>
#endif
#ifdef HAVE_STRING_H
#include <string.h>
#endif
#ifdef HAVE_IMAGEMAGICK
#include <wand/MagickWand.h>
#endif
#include "ppl7.h"
#include "ppl7-grafix.h"
namespace ppl7 {
namespace grafix {
/*!\class ImageFilter_ImageMagick
* \ingroup PPLGroupGrafik
* \brief Import-/Export-Filter für diverse Formate
*/
ImageFilter_ImageMagick::ImageFilter_ImageMagick()
{
#ifdef HAVE_IMAGEMAGICK
MagickWandGenesis();
#endif
}
ImageFilter_ImageMagick::~ImageFilter_ImageMagick()
{
#ifdef HAVE_IMAGEMAGICK
MagickWandTerminus();
#endif
}
int ImageFilter_ImageMagick::ident(FileObject &file, IMAGE &img)
{
#ifdef HAVE_IMAGEMAGICK
try {
MagickWand *wand=NewMagickWand();
if (!wand) return 0;
const void *blob=file.map();
MagickBooleanType ok=MagickPingImageBlob(wand, blob, file.size());
if (ok) {
img.bitdepth=MagickGetImageDepth(wand);
img.width=MagickGetImageWidth(wand);
img.height=MagickGetImageHeight(wand);
img.pitch=0;
img.format=RGBFormat::unknown;
ImageType t=MagickGetImageType(wand);
switch (t) {
case TrueColorType: img.format=RGBFormat::X8R8G8B8; break;
case TrueColorMatteType: img.format=RGBFormat::A8R8G8B8; break;
case GrayscaleType: img.format=RGBFormat::GREY8; break;
case GrayscaleMatteType: img.format=RGBFormat::GREYALPHA32; break;
case PaletteType: img.format=RGBFormat::Palette; break;
case PaletteMatteType: img.format=RGBFormat::Palette; break;
default: img.format=RGBFormat::unknown; break;
}
img.format=RGBFormat::A8R8G8B8;
printf ("MagickImage erkannt. bitdepth=%i, width=%i, height=%i\n",img.bitdepth,
img.width,img.height);
printf ("Pitch: %i, format: %s\n",img.pitch,(const char*) img.format.name());
}
DestroyMagickWand(wand);
if (ok) return 1;
return 0;
} catch (...) {
return 0;
}
#endif
return 0;
}
void ImageFilter_ImageMagick::load(FileObject &file, Drawable &surface, IMAGE &img)
{
#ifdef HAVE_IMAGEMAGICK
MagickWand *wand=NewMagickWand();
if (!wand) throw NullPointerException();
const void *blob=file.map();
MagickBooleanType ok=MagickReadImageBlob(wand,blob,file.size());
if (!ok) {
DestroyMagickWand(wand);
throw UnknownImageFormatException();
}
#endif
}
void ImageFilter_ImageMagick::save (const Drawable &surface, FileObject &file, const AssocArray ¶m)
{
}
String ImageFilter_ImageMagick::name()
{
return "ImageMagick";
}
String ImageFilter_ImageMagick::description()
{
return "Import Filter with ImageMagick";
}
} // EOF namespace grafix
} // EOF namespace ppl7
| 28.612903 | 103 | 0.699211 | pfedick |
6aeaca1e479e3b12c3d7d8c095d07d3166ea0f9c | 2,031 | hpp | C++ | include/preform/multi_misc_float.hpp | mgradysaunders/preform | ab5713d95653bd647d2985cdcd2c9e0e9a05f488 | [
"BSD-2-Clause"
] | null | null | null | include/preform/multi_misc_float.hpp | mgradysaunders/preform | ab5713d95653bd647d2985cdcd2c9e0e9a05f488 | [
"BSD-2-Clause"
] | null | null | null | include/preform/multi_misc_float.hpp | mgradysaunders/preform | ab5713d95653bd647d2985cdcd2c9e0e9a05f488 | [
"BSD-2-Clause"
] | null | null | null | /* Copyright (c) 2018-20 M. Grady Saunders
*
* 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 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.
*/
/*+-+*/
#if !DOXYGEN
#if !(__cplusplus >= 201703L)
#error "preform/multi_misc_float.hpp requires >=C++17"
#endif // #if !(__cplusplus >= 201703L)
#endif // #if !DOXYGEN
#pragma once
#ifndef PREFORM_MULTI_MISC_FLOAT_HPP
#define PREFORM_MULTI_MISC_FLOAT_HPP
#include <preform/misc_float.hpp>
#include <preform/multi.hpp>
namespace pre {
/**
* @defgroup multi_misc_float Multi-dimensional array (miscellaneous float)
*
* `<preform/multi_misc_float.hpp>`
*
* __C++ version__: >=C++17
*/
/**@{*/
/**@}*/
} // namespace pre
#if !DOXYGEN
#include "multi_misc_float.inl"
#endif // #if !DOXYGEN
#endif // #ifndef PREFORM_MULTI_MISC_FLOAT_HPP
| 32.758065 | 77 | 0.736091 | mgradysaunders |
6aeb1f5dba7459387e0eb39434944abac25dd5dc | 518 | cpp | C++ | Source/Engine/Space/Private/Scene.cpp | clones1201/Space | 624c4588fe73ff1c0fff3d91324334023bc735ff | [
"MIT"
] | null | null | null | Source/Engine/Space/Private/Scene.cpp | clones1201/Space | 624c4588fe73ff1c0fff3d91324334023bc735ff | [
"MIT"
] | null | null | null | Source/Engine/Space/Private/Scene.cpp | clones1201/Space | 624c4588fe73ff1c0fff3d91324334023bc735ff | [
"MIT"
] | 1 | 2021-11-11T02:05:54.000Z | 2021-11-11T02:05:54.000Z | #include "Log.h"
#include "Game.h"
#include "Scene.h"
namespace Space
{
Float4x4 PerspectiveCamera::GetViewMatrix() const
{
Float4x4 ret;
Matrix m = MatrixPerspectiveFovLH(m_FieldOfView,m_Aspect, 0.1f, 1000.0f);
StoreFloat4x4(&ret, m);
return ret;
}
Float4x4 OrthographicCamera::GetViewMatrix() const
{
Float4x4 ret;
Matrix m = MatrixOrthographicLH(m_OrthoWidth, m_OrthoWidth / m_Aspect, 0.1f, 1000.0f);
StoreFloat4x4(&ret, m);
return ret;
}
void SceneManager::Tick(float elaspTime)
{
}
} | 18.5 | 88 | 0.718147 | clones1201 |
6aee775d2ace671cdbc912ebe24cc50c9c0422e5 | 726 | cpp | C++ | competitive_programming/programming_contests/uri/angry_ducks.cpp | LeandroTk/Algorithms | 569ed68eba3eeff902f8078992099c28ce4d7cd6 | [
"MIT"
] | 205 | 2018-12-01T17:49:49.000Z | 2021-12-22T07:02:27.000Z | competitive_programming/programming_contests/uri/angry_ducks.cpp | LeandroTk/Algorithms | 569ed68eba3eeff902f8078992099c28ce4d7cd6 | [
"MIT"
] | 2 | 2020-01-01T16:34:29.000Z | 2020-04-26T19:11:13.000Z | competitive_programming/programming_contests/uri/angry_ducks.cpp | LeandroTk/Algorithms | 569ed68eba3eeff902f8078992099c28ce4d7cd6 | [
"MIT"
] | 50 | 2018-11-28T20:51:36.000Z | 2021-11-29T04:08:25.000Z | // https://www.urionlinejudge.com.br/judge/en/problems/view/1163
#include <stdio.h>
#include <math.h>
#define PI 3.14159
#define g 9.80665
double rad(double angle) {
return (angle / 180.0) * PI;
}
int main() {
double h, alfa, v, t, Vx, Vy, x, aux1, aux2, p1, p2;
int n;
char character;
while (scanf("%lf %lf %lf %d", &h, &p1, &p2, &n) > 0) {
aux1 = (2*h)/g;
for (; n > 0; n--) {
scanf("%lf %lf", &alfa, &v);
Vx = v * cosf(rad(alfa));
Vy = v * sinf(rad(alfa));
aux2 = Vy/g;
t = sqrtf(aux1 + powf(aux2, 2)) + aux2;
x = Vx * t;
character = (x >= p1 && x <= p2) ? 'D': 'N';
printf("%.5lf -> %cUCK\n", x, character);
}
}
return 0;
}
| 17.707317 | 64 | 0.487603 | LeandroTk |
6af103ccc228de4d2875f04d0e503263cfd5d66f | 15,972 | cpp | C++ | ThirdLib/glslang/External/spirv-tools/source/opt/dead_branch_elim_pass.cpp | winddyhe/WindGE | 377438805cd92bdb435eae8a137699fa8e0b1105 | [
"MIT"
] | 4 | 2016-11-22T17:53:36.000Z | 2019-05-04T14:28:45.000Z | ThirdLib/glslang/External/spirv-tools/source/opt/dead_branch_elim_pass.cpp | winddyhe/WindGE | 377438805cd92bdb435eae8a137699fa8e0b1105 | [
"MIT"
] | null | null | null | ThirdLib/glslang/External/spirv-tools/source/opt/dead_branch_elim_pass.cpp | winddyhe/WindGE | 377438805cd92bdb435eae8a137699fa8e0b1105 | [
"MIT"
] | null | null | null | // Copyright (c) 2017 The Khronos Group Inc.
// Copyright (c) 2017 Valve Corporation
// Copyright (c) 2017 LunarG Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "dead_branch_elim_pass.h"
#include "cfa.h"
#include "iterator.h"
namespace spvtools {
namespace opt {
namespace {
const uint32_t kBranchCondTrueLabIdInIdx = 1;
const uint32_t kBranchCondFalseLabIdInIdx = 2;
const uint32_t kSelectionMergeMergeBlockIdInIdx = 0;
const uint32_t kLoopMergeMergeBlockIdInIdx = 0;
const uint32_t kLoopMergeContinueBlockIdInIdx = 1;
} // anonymous namespace
uint32_t DeadBranchElimPass::MergeBlockIdIfAny(
const ir::BasicBlock& blk, uint32_t* cbid) const {
auto merge_ii = blk.cend();
--merge_ii;
uint32_t mbid = 0;
*cbid = 0;
if (merge_ii != blk.cbegin()) {
--merge_ii;
if (merge_ii->opcode() == SpvOpLoopMerge) {
mbid = merge_ii->GetSingleWordInOperand(kLoopMergeMergeBlockIdInIdx);
*cbid = merge_ii->GetSingleWordInOperand(kLoopMergeContinueBlockIdInIdx);
}
else if (merge_ii->opcode() == SpvOpSelectionMerge) {
mbid = merge_ii->GetSingleWordInOperand(
kSelectionMergeMergeBlockIdInIdx);
}
}
return mbid;
}
void DeadBranchElimPass::ComputeStructuredSuccessors(ir::Function* func) {
// If header, make merge block first successor. If a loop header, make
// the second successor the continue target.
for (auto& blk : *func) {
uint32_t cbid;
uint32_t mbid = MergeBlockIdIfAny(blk, &cbid);
if (mbid != 0) {
block2structured_succs_[&blk].push_back(id2block_[mbid]);
if (cbid != 0)
block2structured_succs_[&blk].push_back(id2block_[cbid]);
}
// add true successors
blk.ForEachSuccessorLabel([&blk, this](uint32_t sbid) {
block2structured_succs_[&blk].push_back(id2block_[sbid]);
});
}
}
void DeadBranchElimPass::ComputeStructuredOrder(
ir::Function* func, std::list<ir::BasicBlock*>* order) {
// Compute structured successors and do DFS
ComputeStructuredSuccessors(func);
auto ignore_block = [](cbb_ptr) {};
auto ignore_edge = [](cbb_ptr, cbb_ptr) {};
auto get_structured_successors = [this](const ir::BasicBlock* block) {
return &(block2structured_succs_[block]); };
// TODO(greg-lunarg): Get rid of const_cast by making moving const
// out of the cfa.h prototypes and into the invoking code.
auto post_order = [&](cbb_ptr b) {
order->push_front(const_cast<ir::BasicBlock*>(b)); };
spvtools::CFA<ir::BasicBlock>::DepthFirstTraversal(
&*func->begin(), get_structured_successors, ignore_block, post_order,
ignore_edge);
}
bool DeadBranchElimPass::GetConstCondition(uint32_t condId, bool* condVal) {
bool condIsConst;
ir::Instruction* cInst = def_use_mgr_->GetDef(condId);
switch (cInst->opcode()) {
case SpvOpConstantFalse: {
*condVal = false;
condIsConst = true;
} break;
case SpvOpConstantTrue: {
*condVal = true;
condIsConst = true;
} break;
case SpvOpLogicalNot: {
bool negVal;
condIsConst = GetConstCondition(cInst->GetSingleWordInOperand(0),
&negVal);
if (condIsConst)
*condVal = !negVal;
} break;
default: {
condIsConst = false;
} break;
}
return condIsConst;
}
bool DeadBranchElimPass::GetConstInteger(uint32_t selId, uint32_t* selVal) {
ir::Instruction* sInst = def_use_mgr_->GetDef(selId);
uint32_t typeId = sInst->type_id();
ir::Instruction* typeInst = def_use_mgr_->GetDef(typeId);
if (!typeInst || (typeInst->opcode() != SpvOpTypeInt)) return false;
// TODO(greg-lunarg): Support non-32 bit ints
if (typeInst->GetSingleWordInOperand(0) != 32)
return false;
if (sInst->opcode() == SpvOpConstant) {
*selVal = sInst->GetSingleWordInOperand(0);
return true;
}
else if (sInst->opcode() == SpvOpConstantNull) {
*selVal = 0;
return true;
}
return false;
}
void DeadBranchElimPass::AddBranch(uint32_t labelId, ir::BasicBlock* bp) {
std::unique_ptr<ir::Instruction> newBranch(
new ir::Instruction(SpvOpBranch, 0, 0,
{{spv_operand_type_t::SPV_OPERAND_TYPE_ID, {labelId}}}));
def_use_mgr_->AnalyzeInstDefUse(&*newBranch);
bp->AddInstruction(std::move(newBranch));
}
void DeadBranchElimPass::AddSelectionMerge(uint32_t labelId,
ir::BasicBlock* bp) {
std::unique_ptr<ir::Instruction> newMerge(
new ir::Instruction(SpvOpSelectionMerge, 0, 0,
{{spv_operand_type_t::SPV_OPERAND_TYPE_ID, {labelId}},
{spv_operand_type_t::SPV_OPERAND_TYPE_LITERAL_INTEGER, {0}}}));
def_use_mgr_->AnalyzeInstDefUse(&*newMerge);
bp->AddInstruction(std::move(newMerge));
}
void DeadBranchElimPass::AddBranchConditional(uint32_t condId,
uint32_t trueLabId, uint32_t falseLabId, ir::BasicBlock* bp) {
std::unique_ptr<ir::Instruction> newBranchCond(
new ir::Instruction(SpvOpBranchConditional, 0, 0,
{{spv_operand_type_t::SPV_OPERAND_TYPE_ID, {condId}},
{spv_operand_type_t::SPV_OPERAND_TYPE_ID, {trueLabId}},
{spv_operand_type_t::SPV_OPERAND_TYPE_ID, {falseLabId}}}));
def_use_mgr_->AnalyzeInstDefUse(&*newBranchCond);
bp->AddInstruction(std::move(newBranchCond));
}
void DeadBranchElimPass::KillAllInsts(ir::BasicBlock* bp) {
bp->ForEachInst([this](ir::Instruction* ip) {
KillNamesAndDecorates(ip);
def_use_mgr_->KillInst(ip);
});
}
bool DeadBranchElimPass::GetSelectionBranch(ir::BasicBlock* bp,
ir::Instruction** branchInst, ir::Instruction** mergeInst,
uint32_t *condId) {
auto ii = bp->end();
--ii;
*branchInst = &*ii;
if (ii == bp->begin())
return false;
--ii;
*mergeInst = &*ii;
if ((*mergeInst)->opcode() != SpvOpSelectionMerge)
return false;
// SPIR-V says the terminator for an OpSelectionMerge must be
// either a conditional branch or a switch.
assert((*branchInst)->opcode() == SpvOpBranchConditional ||
(*branchInst)->opcode() == SpvOpSwitch);
// Both BranchConidtional and Switch have their conditional value at 0.
*condId = (*branchInst)->GetSingleWordInOperand(0);
return true;
}
bool DeadBranchElimPass::HasNonPhiRef(uint32_t labelId) {
analysis::UseList* uses = def_use_mgr_->GetUses(labelId);
if (uses == nullptr)
return false;
for (auto u : *uses)
if (u.inst->opcode() != SpvOpPhi)
return true;
return false;
}
bool DeadBranchElimPass::EliminateDeadBranches(ir::Function* func) {
// Traverse blocks in structured order
std::list<ir::BasicBlock*> structuredOrder;
ComputeStructuredOrder(func, &structuredOrder);
std::unordered_set<ir::BasicBlock*> elimBlocks;
bool modified = false;
for (auto bi = structuredOrder.begin(); bi != structuredOrder.end(); ++bi) {
// Skip blocks that are already in the elimination set
if (elimBlocks.find(*bi) != elimBlocks.end())
continue;
// Skip blocks that don't have conditional branch preceded
// by OpSelectionMerge
ir::Instruction* br;
ir::Instruction* mergeInst;
uint32_t condId;
if (!GetSelectionBranch(*bi, &br, &mergeInst, &condId))
continue;
// If constant condition/selector, replace conditional branch/switch
// with unconditional branch and delete merge
uint32_t liveLabId;
if (br->opcode() == SpvOpBranchConditional) {
bool condVal;
if (!GetConstCondition(condId, &condVal))
continue;
liveLabId = (condVal == true) ?
br->GetSingleWordInOperand(kBranchCondTrueLabIdInIdx) :
br->GetSingleWordInOperand(kBranchCondFalseLabIdInIdx);
}
else {
assert(br->opcode() == SpvOpSwitch);
// Search switch operands for selector value, set liveLabId to
// corresponding label, use default if not found
uint32_t selVal;
if (!GetConstInteger(condId, &selVal))
continue;
uint32_t icnt = 0;
uint32_t caseVal;
br->ForEachInOperand(
[&icnt,&caseVal,&selVal,&liveLabId](const uint32_t* idp) {
if (icnt == 1) {
// Start with default label
liveLabId = *idp;
}
else if (icnt > 1) {
if (icnt % 2 == 0) {
caseVal = *idp;
}
else {
if (caseVal == selVal)
liveLabId = *idp;
}
}
++icnt;
});
}
const uint32_t mergeLabId =
mergeInst->GetSingleWordInOperand(kSelectionMergeMergeBlockIdInIdx);
AddBranch(liveLabId, *bi);
def_use_mgr_->KillInst(br);
def_use_mgr_->KillInst(mergeInst);
modified = true;
// Initialize live block set to the live label
std::unordered_set<uint32_t> liveLabIds;
liveLabIds.insert(liveLabId);
// Iterate to merge block adding dead blocks to elimination set
auto dbi = bi;
++dbi;
uint32_t dLabId = (*dbi)->id();
while (dLabId != mergeLabId) {
if (liveLabIds.find(dLabId) == liveLabIds.end()) {
// Kill use/def for all instructions and mark block for elimination
KillAllInsts(*dbi);
elimBlocks.insert(*dbi);
}
else {
// Mark all successors as live
(*dbi)->ForEachSuccessorLabel([&liveLabIds](const uint32_t succId){
liveLabIds.insert(succId);
});
// Mark merge and continue blocks as live
(*dbi)->ForMergeAndContinueLabel([&liveLabIds](const uint32_t succId){
liveLabIds.insert(succId);
});
}
++dbi;
dLabId = (*dbi)->id();
}
// If merge block is unreachable, continue eliminating blocks until
// a live block or last block is reached.
while (!HasNonPhiRef(dLabId)) {
KillAllInsts(*dbi);
elimBlocks.insert(*dbi);
++dbi;
if (dbi == structuredOrder.end())
break;
dLabId = (*dbi)->id();
}
// If last block reached, look for next dead branch
if (dbi == structuredOrder.end())
continue;
// Create set of dead predecessors in preparation for phi update.
// Add the header block if the live branch is not the merge block.
std::unordered_set<ir::BasicBlock*> deadPreds(elimBlocks);
if (liveLabId != dLabId)
deadPreds.insert(*bi);
// Update phi instructions in terminating block.
for (auto pii = (*dbi)->begin(); ; ++pii) {
// Skip NoOps, break at end of phis
SpvOp op = pii->opcode();
if (op == SpvOpNop)
continue;
if (op != SpvOpPhi)
break;
// Count phi's live predecessors with lcnt and remember last one
// with lidx.
uint32_t lcnt = 0;
uint32_t lidx = 0;
uint32_t icnt = 0;
pii->ForEachInId(
[&deadPreds,&icnt,&lcnt,&lidx,this](uint32_t* idp) {
if (icnt % 2 == 1) {
if (deadPreds.find(id2block_[*idp]) == deadPreds.end()) {
++lcnt;
lidx = icnt - 1;
}
}
++icnt;
});
// If just one live predecessor, replace resultid with live value id.
uint32_t replId;
if (lcnt == 1) {
replId = pii->GetSingleWordInOperand(lidx);
}
else {
// Otherwise create new phi eliminating dead predecessor entries
assert(lcnt > 1);
replId = TakeNextId();
std::vector<ir::Operand> phi_in_opnds;
icnt = 0;
uint32_t lastId;
pii->ForEachInId(
[&deadPreds,&icnt,&phi_in_opnds,&lastId,this](uint32_t* idp) {
if (icnt % 2 == 1) {
if (deadPreds.find(id2block_[*idp]) == deadPreds.end()) {
phi_in_opnds.push_back(
{spv_operand_type_t::SPV_OPERAND_TYPE_ID, {lastId}});
phi_in_opnds.push_back(
{spv_operand_type_t::SPV_OPERAND_TYPE_ID, {*idp}});
}
}
else {
lastId = *idp;
}
++icnt;
});
std::unique_ptr<ir::Instruction> newPhi(new ir::Instruction(
SpvOpPhi, pii->type_id(), replId, phi_in_opnds));
def_use_mgr_->AnalyzeInstDefUse(&*newPhi);
pii = pii.InsertBefore(std::move(newPhi));
++pii;
}
const uint32_t phiId = pii->result_id();
KillNamesAndDecorates(phiId);
(void)def_use_mgr_->ReplaceAllUsesWith(phiId, replId);
def_use_mgr_->KillInst(&*pii);
}
}
// Erase dead blocks
for (auto ebi = func->begin(); ebi != func->end(); )
if (elimBlocks.find(&*ebi) != elimBlocks.end())
ebi = ebi.Erase();
else
++ebi;
return modified;
}
void DeadBranchElimPass::Initialize(ir::Module* module) {
module_ = module;
// Initialize function and block maps
id2block_.clear();
block2structured_succs_.clear();
// Initialize block map
for (auto& fn : *module_)
for (auto& blk : fn)
id2block_[blk.id()] = &blk;
// TODO(greg-lunarg): Reuse def/use from previous passes
def_use_mgr_.reset(new analysis::DefUseManager(consumer(), module_));
// Initialize next unused Id.
InitNextId();
// Initialize extension whitelist
InitExtensions();
};
bool DeadBranchElimPass::AllExtensionsSupported() const {
// If any extension not in whitelist, return false
for (auto& ei : module_->extensions()) {
const char* extName = reinterpret_cast<const char*>(
&ei.GetInOperand(0).words[0]);
if (extensions_whitelist_.find(extName) == extensions_whitelist_.end())
return false;
}
return true;
}
Pass::Status DeadBranchElimPass::ProcessImpl() {
// Current functionality assumes structured control flow.
// TODO(greg-lunarg): Handle non-structured control-flow.
if (!module_->HasCapability(SpvCapabilityShader))
return Status::SuccessWithoutChange;
// Do not process if module contains OpGroupDecorate. Additional
// support required in KillNamesAndDecorates().
// TODO(greg-lunarg): Add support for OpGroupDecorate
for (auto& ai : module_->annotations())
if (ai.opcode() == SpvOpGroupDecorate)
return Status::SuccessWithoutChange;
// Do not process if any disallowed extensions are enabled
if (!AllExtensionsSupported())
return Status::SuccessWithoutChange;
// Collect all named and decorated ids
FindNamedOrDecoratedIds();
// Process all entry point functions
ProcessFunction pfn = [this](ir::Function* fp) {
return EliminateDeadBranches(fp);
};
bool modified = ProcessEntryPointCallTree(pfn, module_);
FinalizeNextId();
return modified ? Status::SuccessWithChange : Status::SuccessWithoutChange;
}
DeadBranchElimPass::DeadBranchElimPass() {}
Pass::Status DeadBranchElimPass::Process(ir::Module* module) {
Initialize(module);
return ProcessImpl();
}
void DeadBranchElimPass::InitExtensions() {
extensions_whitelist_.clear();
extensions_whitelist_.insert({
"SPV_AMD_shader_explicit_vertex_parameter",
"SPV_AMD_shader_trinary_minmax",
"SPV_AMD_gcn_shader",
"SPV_KHR_shader_ballot",
"SPV_AMD_shader_ballot",
"SPV_AMD_gpu_shader_half_float",
"SPV_KHR_shader_draw_parameters",
"SPV_KHR_subgroup_vote",
"SPV_KHR_16bit_storage",
"SPV_KHR_device_group",
"SPV_KHR_multiview",
"SPV_NVX_multiview_per_view_attributes",
"SPV_NV_viewport_array2",
"SPV_NV_stereo_view_rendering",
"SPV_NV_sample_mask_override_coverage",
"SPV_NV_geometry_shader_passthrough",
"SPV_AMD_texture_gather_bias_lod",
"SPV_KHR_storage_buffer_storage_class",
"SPV_KHR_variable_pointers",
"SPV_AMD_gpu_shader_int16",
"SPV_KHR_post_depth_coverage",
"SPV_KHR_shader_atomic_counter_ops",
});
}
} // namespace opt
} // namespace spvtools
| 32.864198 | 79 | 0.66435 | winddyhe |
6af231a0ae239e1ce749a10f97a8414cd80c6bdf | 26,366 | cpp | C++ | dlib/gui_widgets/fonts.cpp | ckproc/dlib-19.7 | 0ca40f5e85de2436e557bee9a805d3987d2d9507 | [
"BSL-1.0"
] | null | null | null | dlib/gui_widgets/fonts.cpp | ckproc/dlib-19.7 | 0ca40f5e85de2436e557bee9a805d3987d2d9507 | [
"BSL-1.0"
] | 4 | 2018-02-27T15:44:25.000Z | 2018-02-28T01:26:03.000Z | dlib/gui_widgets/fonts.cpp | ckproc/dlib-19.7 | 0ca40f5e85de2436e557bee9a805d3987d2d9507 | [
"BSL-1.0"
] | null | null | null | // Copyright (C) 2005 Davis E. King (davis@dlib.net), and Nils Labugt, Keita Mochizuki
// License: Boost Software License See LICENSE.txt for the full license.
#ifndef DLIB_FONTs_CPP_
#define DLIB_FONTs_CPP_
#include "fonts.h"
#include <fstream>
#include <memory>
#include <sstream>
#include "../serialize.h"
#include "../base64.h"
#include "../compress_stream.h"
#include "../tokenizer.h"
#include "nativefont.h"
namespace dlib
{
// ----------------------------------------------------------------------------------------
const std::string get_decoded_string_with_default_font_data()
{
dlib::base64::kernel_1a base64_coder;
dlib::compress_stream::kernel_1ea compressor;
std::ostringstream sout;
std::istringstream sin;
/*
SOURCE BDF FILE (helvR12.bdf) COMMENTS
COMMENT $XConsortium: helvR12.bdf,v 1.15 95/01/26 18:02:58 gildea Exp $
COMMENT $Id: helvR12.bdf,v 1.26 2004-11-28 20:08:46+00 mgk25 Rel $
COMMENT
COMMENT +
COMMENT Copyright 1984-1989, 1994 Adobe Systems Incorporated.
COMMENT Copyright 1988, 1994 Digital Equipment Corporation.
COMMENT
COMMENT Adobe is a trademark of Adobe Systems Incorporated which may be
COMMENT registered in certain jurisdictions.
COMMENT Permission to use these trademarks is hereby granted only in
COMMENT association with the images described in this file.
COMMENT
COMMENT Permission to use, copy, modify, distribute and sell this software
COMMENT and its documentation for any purpose and without fee is hereby
COMMENT granted, provided that the above copyright notices appear in all
COMMENT copies and that both those copyright notices and this permission
COMMENT notice appear in supporting documentation, and that the names of
COMMENT Adobe Systems and Digital Equipment Corporation not be used in
COMMENT advertising or publicity pertaining to distribution of the software
COMMENT without specific, written prior permission. Adobe Systems and
COMMENT Digital Equipment Corporation make no representations about the
COMMENT suitability of this software for any purpose. It is provided "as
COMMENT is" without express or implied warranty.
COMMENT -
*/
// The base64 encoded data we want to decode and return.
sout << "AXF+zOQzCgGitrKiOCGEL4hlIv1ZenWJyjMQ4rJ6f/oPMeHqsZn+8XnpehwFQTz3dtUGlZRAUoOa";
sout << "uVo8UiplcFxuK69A+94rpMCMAyEeeOwZ/tRzkX4eKuU3L4xtsJDknMiYUNKaMrYimb1QJ0E+SRqQ";
sout << "wATrMTecYNZvJJm02WibiwE4cJ5scvkHNl4KJT5QfdwRdGopTyUVdZvRvtbTLLjsJP0fQEQLqemf";
sout << "qPE4kDD79ehrBIwLO1Y6TzxtrrIoQR57zlwTUyLenqRtSN3VLtjWYd82cehRIlTLtuxBg2s+zZVq";
sout << "jNlNnYTSM+Swy06qnQgg+Dt0lhtlB9shR1OAlcfCtTW6HKoBk/FGeDmjTGW4bNCGv7RjgM6TlLDg";
sout << "ZYSSA6ZCCAKBgE++U32gLHCCiVkPTkkp9P6ioR+e3SSKRNm9p5MHf+ZQ3LJkW8KFJ/K9gKT1yvyv";
sout << "F99pAvOOq16tHRFvzBs+xZj/mUpH0lGIS7kLWr9oP2KuccVrz25aJn3kDruwTYoD+CYlOqtPO0Mv";
sout << "dEI0LUR0Ykp1M2rWo76fJ/fpzHjV7737hjkNPJ13nO72RMDr4R5V3uG7Dw7Ng+vGX3WgJZ4wh1JX";
sout << "pl2VMqC5JXccctzvnQvnuvBvRm7THgwQUgMKKT3WK6afUUVlJy8DHKuU4k1ibfVMxAmrwKdTUX2w";
sout << "cje3A05Qji3aop65qEdwgI5O17HIVoRQOG/na+XRMowOfUvI4H8Z4+JGACfRrQctgYDAM9eJzm8i";
sout << "PibyutmJfZBGg0a3oC75S5R9lTxEjPocnEyJRYNnmVnVAmKKbTbTsznuaD+D1XhPdr2t3A4bRTsp";
sout << "toKKtlFnd9YGwLWwONDwLnoQ/IXwyF7txrRHNSVToh772U0Aih/yn5vnmcMF750eiMzRAgXu5sbR";
sout << "VXEOVCiLgVevN5umkvjZt1eGTSSzDMrIvnv4nyOfaFsD+I76wQfgLqd71rheozGtjNc0AOTx4Ggc";
sout << "eUSFHTDAVfTExBzckurtyuIAqF986a0JLHCtsDpBa2wWNuiQYOH3/LX1zkdU2hdamhBW774bpEwr";
sout << "dguMxxOeDGOBgIlM5gxXGYXSf5IN3fUAEPfOPRxB7T+tpjFnWd7cg+JMabci3zhJ9ANaYT7HGeTX";
sout << "bulKnGHjYrR1BxdK3YeliogQRU4ytmxlyL5zlNFU/759mA8XSfIPMEZn9Vxkb00q1htF7REiDcr3";
sout << "kW1rtPAc7VQNEhT54vK/YF6rMvjO7kBZ/vLYo7E8e8hDKEnY8ucrC3KGmeo31Gei74BBcEbvJBd3";
sout << "/YAaIKgXWwU2wSUw9wLq2RwGwyguvKBx0J/gn27tjcVAHorRBwxzPpk8r+YPyN+SifSzEL7LEy1G";
sout << "lPHxmXTrcqnH9qraeAqXJUJvU8SJJpf/tmsAE+XSKD/kpVBnT5qXsJ1SRFS7MtfPjE1j/NYbaQBI";
sout << "bOrh81zaYCEJR0IKHWCIsu/MC3zKXfkxFgQ9XpYAuWjSSK64YpgkxSMe8VG8yYvigOw2ODg/z4FU";
sout << "+HpnEKF/M/mKfLKK1i/8BV7xcYVHrhEww1QznoFklJs/pEg3Kd5PE1lRii6hvTn6McVAkw+YbH9q";
sout << "/sg4gFIAvai64hMcZ1oIZYppj3ZN6KMdyhK5s4++ZS/YOV2nNhW73ovivyi2Tjg7lxjJJtsYrLKb";
sout << "zIN1slOICKYwBq42TFBcFXaZ6rf0Czd09tL+q6A1Ztgr3BNuhCenjhWN5ji0LccGYZo6bLTggRG/";
sout << "Uz6K3CBBU/byLs79c5qCohrr7rlpDSdbuR+aJgNiWoU6T0i2Tvua6h51LcWEHy5P2n146/Ae2di4";
sout << "eh20WQvclrsgm1oFTGD0Oe85GKOTA7vvwKmLBc1wwA0foTuxzVgj0TMTFBiYLTLG4ujUyBYy1N6e";
sout << "H8EKi8H+ZAlqezrjABO3BQr33ewdZL5IeJ4w7gdGUDA6+P+7cODcBW50X9++6YTnKctuEw6aXBpy";
sout << "GgcMfPE61G8YKBbFGFic3TVvGCLvre1iURv+F+hU4/ee6ILuPnpYnSXX2iCIK/kmkBse8805d4Qe";
sout << "DG/8rBW9ojvAgc0jX7CatPEMHGkcz+KIZoKMI7XXK4PJpGQUdq6EdIhJC4koXEynjwwXMeC+jJqH";
sout << "agwrlDNssq/8AA==";
// Put the data into the istream sin
sin.str(sout.str());
sout.str("");
// Decode the base64 text into its compressed binary form
base64_coder.decode(sin,sout);
sin.clear();
sin.str(sout.str());
sout.str("");
// Decompress the data into its original form
compressor.decompress(sin,sout);
// Return the decoded and decompressed data
return sout.str();
}
default_font::
default_font (
)
{
using namespace std;
l = new letter[256];
try
{
istringstream sin(get_decoded_string_with_default_font_data());
for (int i = 0; i < 256; ++i)
{
deserialize(l[i],sin);
}
}
catch (...)
{
delete [] l;
throw;
}
}
// ----------------------------------------------------------------------------------------
void serialize (
const letter& item,
std::ostream& out
)
{
try
{
serialize(item.w,out);
serialize(item.count,out);
for (unsigned long i = 0; i < item.count; ++i)
{
serialize(item.points[i].x,out);
serialize(item.points[i].y,out);
}
}
catch (serialization_error e)
{
throw serialization_error(e.info + "\n while serializing object of type letter");
}
}
void deserialize (
letter& item,
std::istream& in
)
{
try
{
if (item.points)
delete [] item.points;
deserialize(item.w,in);
deserialize(item.count,in);
if (item.count > 0)
item.points = new letter::point[item.count];
else
item.points = 0;
for (unsigned long i = 0; i < item.count; ++i)
{
deserialize(item.points[i].x,in);
deserialize(item.points[i].y,in);
}
}
catch (serialization_error e)
{
item.w = 0;
item.count = 0;
item.points = 0;
throw serialization_error(e.info + "\n while deserializing object of type letter");
}
}
// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------
namespace bdf_font_helpers
{
class bdf_parser
{
public:
bdf_parser( std::istream& in ) : in_( in )
{
std::string str_tmp;
int int_tmp;
str_tmp = "STARTFONT"; int_tmp = STARTFONT; keyword_map.add( str_tmp, int_tmp );
str_tmp = "FONTBOUNDINGBOX";int_tmp = FONTBOUNDINGBOX; keyword_map.add( str_tmp, int_tmp );
str_tmp = "DWIDTH"; int_tmp = DWIDTH; keyword_map.add( str_tmp, int_tmp );
str_tmp = "CHARS"; int_tmp = CHARS; keyword_map.add( str_tmp, int_tmp );
str_tmp = "STARTCHAR"; int_tmp = STARTCHAR; keyword_map.add( str_tmp, int_tmp );
str_tmp = "ENCODING"; int_tmp = ENCODING; keyword_map.add( str_tmp, int_tmp );
str_tmp = "BBX"; int_tmp = BBX; keyword_map.add( str_tmp, int_tmp );
str_tmp = "BITMAP"; int_tmp = BITMAP; keyword_map.add( str_tmp, int_tmp );
str_tmp = "ENDCHAR"; int_tmp = ENDCHAR; keyword_map.add( str_tmp, int_tmp );
str_tmp = "ENDFONT"; int_tmp = ENDFONT; keyword_map.add( str_tmp, int_tmp );
str_tmp = "DEFAULT_CHAR"; int_tmp = DEFAULT_CHAR; keyword_map.add( str_tmp, int_tmp );
tokzr.set_identifier_token( tokzr.uppercase_letters(), tokzr.uppercase_letters() + "_" );
tokzr.set_stream( in );
}
enum bdf_enums
{
NO_KEYWORD = 0,
STARTFONT = 1,
FONTBOUNDINGBOX = 2,
DWIDTH = 4,
DEFAULT_CHAR = 8,
CHARS = 16,
STARTCHAR = 32,
ENCODING = 64,
BBX = 128,
BITMAP = 256,
ENDCHAR = 512,
ENDFONT = 1024
};
struct header_info
{
int FBBx, FBBy, Xoff, Yoff;
int dwx0, dwy0;
bool has_global_dw;
long default_char;
};
struct char_info
{
int dwx0, dwy0;
int BBw, BBh, BBxoff0x, BByoff0y;
array2d<char> bitmap;
bool has_dw;
};
bool parse_header( header_info& info )
{
if ( required_keyword( STARTFONT ) == false )
return false; // parse_error: required keyword missing
info.has_global_dw = false;
int find = FONTBOUNDINGBOX | DWIDTH | DEFAULT_CHAR;
int stop = CHARS | STARTCHAR | ENCODING | BBX | BITMAP | ENDCHAR | ENDFONT;
int res;
while ( 1 )
{
res = find_keywords( find | stop );
if ( res & FONTBOUNDINGBOX )
{
in_ >> info.FBBx >> info.FBBy >> info.Xoff >> info.Yoff;
if ( in_.fail() )
return false; // parse_error
find &= ~FONTBOUNDINGBOX;
continue;
}
if ( res & DWIDTH )
{
in_ >> info.dwx0 >> info.dwy0;
if ( in_.fail() )
return false; // parse_error
find &= ~DWIDTH;
info.has_global_dw = true;
continue;
}
if ( res & DEFAULT_CHAR )
{
in_ >> info.default_char;
if ( in_.fail() )
return false; // parse_error
find &= ~DEFAULT_CHAR;
continue;
}
if ( res & NO_KEYWORD )
return false; // parse_error: unexpected EOF
break;
}
if ( res != CHARS || ( find & FONTBOUNDINGBOX ) )
return false; // parse_error: required keyword missing or unexpeced keyword
return true;
}
int parse_glyph( char_info& info, unichar& enc )
{
info.has_dw = false;
int e;
int res;
while ( 1 )
{
res = find_keywords( ENCODING );
if ( res != ENCODING )
return 0; // no more glyphs
in_ >> e;
if ( in_.fail() )
return -1; // parse_error
if ( e >= static_cast<int>(enc) )
break;
}
int find = BBX | DWIDTH;
int stop = STARTCHAR | ENCODING | BITMAP | ENDCHAR | ENDFONT;
while ( 1 )
{
res = find_keywords( find | stop );
if ( res & BBX )
{
in_ >> info.BBw >> info.BBh >> info.BBxoff0x >> info.BByoff0y;
if ( in_.fail() )
return -1; // parse_error
find &= ~BBX;
continue;
}
if ( res & DWIDTH )
{
in_ >> info.dwx0 >> info.dwy0;
if ( in_.fail() )
return -1; // parse_error
find &= ~DWIDTH;
info.has_dw = true;
continue;
}
if ( res & NO_KEYWORD )
return -1; // parse_error: unexpected EOF
break;
}
if ( res != BITMAP || ( find != NO_KEYWORD ) )
return -1; // parse_error: required keyword missing or unexpeced keyword
unsigned h = info.BBh;
unsigned w = ( info.BBw + 7 ) / 8 * 2;
info.bitmap.set_size( h, w );
for ( unsigned r = 0;r < h;r++ )
{
trim();
std::string str = "";
extract_hex(str);
if(str.size() < w)
return -1; // parse_error
for ( unsigned c = 0;c < w;c++ )
info.bitmap[r][c] = str[c];
}
if ( in_.fail() )
return -1; // parse_error
if ( required_keyword( ENDCHAR ) == false )
return -1; // parse_error: required keyword missing
enc = e;
return 1;
}
private:
map<std::string, int>::kernel_1a_c keyword_map;
tokenizer::kernel_1a_c tokzr;
std::istream& in_;
void extract_hex(std::string& str)
{
int type;
std::string token;
while ( 1 )
{
type = tokzr.peek_type();
if ( type == tokenizer::kernel_1a_c::IDENTIFIER || type == tokenizer::kernel_1a_c::NUMBER )
{
tokzr.get_token( type, token );
str += token;
continue;
}
break;
}
}
void trim()
{
int type;
std::string token;
while ( 1 )
{
type = tokzr.peek_type();
if ( type == tokenizer::kernel_1a_c::WHITE_SPACE || type == tokenizer::kernel_1a_c::END_OF_LINE )
{
tokzr.get_token( type, token );
continue;
}
break;
}
}
bool required_keyword( int kw )
{
int type;
std::string token;
while ( 1 )
{
tokzr.get_token( type, token );
if ( type == tokenizer::kernel_1a_c::WHITE_SPACE || type == tokenizer::kernel_1a_c::END_OF_LINE )
continue;
if ( type != tokenizer::kernel_1a_c::IDENTIFIER || keyword_map.is_in_domain( token ) == false || ( keyword_map[token] & kw ) == 0 )
return false;
break;
}
return true;
}
int find_keywords( int find )
{
int type;
std::string token;
while ( 1 )
{
tokzr.get_token( type, token );
if ( type == tokenizer::kernel_1a_c::END_OF_FILE )
return NO_KEYWORD;
if ( type == tokenizer::kernel_1a_c::IDENTIFIER && keyword_map.is_in_domain( token ) == true )
{
int kw = keyword_map[token];
if ( kw & find )
return kw;
}
}
return true;
}
};
}
// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------
// bdf_font functions
// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------
bdf_font::bdf_font(
long default_char_
) :
default_char(0),
is_initialized( false ),
right_overflow_( 0 ),
has_global_width( false ),
specified_default_char( default_char_ )
{
// make sure gl contains at least one letter
gl.resize(1);
}
// ----------------------------------------------------------------------------------------
void bdf_font::adjust_metrics(
)
{
if ( is_initialized == false )
return;
// set starting values for fbb
if ( gl[default_char].num_of_points() > 0 )
{
letter& g = gl[default_char];
fbb.set_top( g[0].y );
fbb.set_bottom( g[0].y );
fbb.set_left( g[0].x );
fbb.set_right( g[0].x );
}
else
{
// ok, the default char was a space
// let's just choose some safe arbitrary values then...
fbb.set_top( 10000 );
fbb.set_bottom( -10000 );
fbb.set_left( 10000 );
fbb.set_right( -10000 );
}
right_overflow_ = 0;
for ( unichar n = 0; n < gl.size(); n++ )
{
letter& g = gl[n];
unsigned short nr_pts = g.num_of_points();
for ( unsigned short k = 0;k < nr_pts;k++ )
{
fbb.set_top( std::min( fbb.top(), (long)g[k].y ) );
fbb.set_left( std::min( fbb.left(), (long)g[k].x ) );
fbb.set_bottom( std::max( fbb.bottom(), (long)g[k].y ) );
fbb.set_right( std::max( fbb.right(), (long)g[k].x ) );
right_overflow_ = std::max( right_overflow_, (unsigned long)(g[k].x - g.width()) ); // superfluous?
}
}
}
// ----------------------------------------------------------------------------------------
long bdf_font::
read_bdf_file(
std::istream& in,
unichar max_enc,
unichar min_enc
)
{
using namespace bdf_font_helpers;
bdf_parser parser( in );
bdf_parser::header_info hinfo;
bdf_parser::char_info cinfo;
gl.resize(max_enc+1);
hinfo.default_char = - 1;
if ( is_initialized == false || static_cast<std::streamoff>(in.tellg()) == std::ios::beg )
{
if ( parser.parse_header( hinfo ) == false )
return 0; // parse_error: invalid or missing header
}
else
{
// not start of file, so use values from previous read.
hinfo.has_global_dw = has_global_width;
hinfo.dwx0 = global_width;
}
int res;
unichar nr_letters_added = 0;
unsigned width;
for ( unichar n = min_enc; n <= max_enc; n++ )
{
if ( in.eof() )
break;
long pos = in.tellg();
res = parser.parse_glyph( cinfo, n );
if ( res < 0 )
return 0; // parse_error
if ( res == 0 )
continue;
if ( n > max_enc )
{
in.seekg( pos );
break;
}
if ( cinfo.has_dw == false )
{
if ( hinfo.has_global_dw == false )
return 0; // neither width info for the glyph, nor for the font as a whole (monospace).
width = hinfo.dwx0;
}
else
width = cinfo.dwx0;
if ( bitmap_to_letter( cinfo.bitmap, n, width, cinfo.BBxoff0x, cinfo.BByoff0y ) == false )
return 0;
nr_letters_added++;
if ( is_initialized == false )
{
// Bonding rectangle for the font.
fbb.set_top( -( hinfo.Yoff + hinfo.FBBy - 1 ) );
fbb.set_bottom( -hinfo.Yoff );
fbb.set_left( hinfo.Xoff );
fbb.set_right( hinfo.Xoff + hinfo.FBBx - 1 );
// We need to compute this after all the glyphs are loaded.
right_overflow_ = 0;
// set this to something valid now, just in case.
default_char = n;
// Save any global width in case we later read from the same file.
has_global_width = hinfo.has_global_dw;
if ( has_global_width )
global_width = hinfo.dwx0;
// dont override value specified in the constructor with value specified in the file
if ( specified_default_char < 0 && hinfo.default_char >= 0 )
specified_default_char = hinfo.default_char;
is_initialized = true;
}
}
if ( is_initialized == false )
return 0; // Not a single glyph was found within the specified range.
if ( specified_default_char >= 0 )
default_char = specified_default_char;
// no default char specified, try find something sane.
else
default_char = 0;
return nr_letters_added;
}
// ----------------------------------------------------------------------------------------
bool bdf_font::
bitmap_to_letter(
array2d<char>& bitmap,
unichar enc,
unsigned long width,
int x_offset,
int y_offset
)
{
unsigned nr_points = 0;
bitmap.reset();
while ( bitmap.move_next() )
{
unsigned char ch = bitmap.element();
if ( ch > '9' )
ch -= 'A' - '9' - 1;
ch -= '0';
if ( ch > 0xF )
return false; // parse error: invalid hex digit
bitmap.element() = ch;
if ( ch & 8 )
nr_points++;
if ( ch & 4 )
nr_points++;
if ( ch & 2 )
nr_points++;
if ( ch & 1 )
nr_points++;
}
letter( width, nr_points ).swap(gl[enc]);
unsigned index = 0;
for ( int r = 0;r < bitmap.nr();r++ )
{
for ( int c = 0;c < bitmap.nc();c++ )
{
int x = x_offset + c * 4;
int y = -( y_offset + bitmap.nr() - r - 1 );
char ch = bitmap[r][c];
letter& glyph = gl[enc];
if ( ch & 8 )
{
glyph[index] = letter::point( x, y );
right_overflow_ = std::max( right_overflow_, x - width );
index++;
}
if ( ch & 4 )
{
glyph[index] = letter::point( x + 1, y );
right_overflow_ = std::max( right_overflow_, x + 1 - width );
index++;
}
if ( ch & 2 )
{
glyph[index] = letter::point( x + 2, y );
right_overflow_ = std::max( right_overflow_, x + 2 - width );
index++;
}
if ( ch & 1 )
{
glyph[index] = letter::point( x + 3, y );
right_overflow_ = std::max( right_overflow_, x + 3 - width );
index++;
}
}
}
return true;
}
// ----------------------------------------------------------------------------------------
const std::shared_ptr<font> get_native_font (
)
{
return nativefont::native_font::get_font();
}
// ----------------------------------------------------------------------------------------
}
#endif // DLIB_FONTs_CPP_
| 39.118694 | 152 | 0.446067 | ckproc |
6af3f4ea91f2254da0bf57d598136da9f329f3c9 | 2,271 | cpp | C++ | libcaf_core/src/init_global_meta_objects.cpp | jsiwek/actor-framework | 06cd2836f4671725cb7eaa22b3cc115687520fc1 | [
"BSL-1.0",
"BSD-3-Clause"
] | 4 | 2019-05-03T05:38:15.000Z | 2020-08-25T15:23:19.000Z | libcaf_core/src/init_global_meta_objects.cpp | jsiwek/actor-framework | 06cd2836f4671725cb7eaa22b3cc115687520fc1 | [
"BSL-1.0",
"BSD-3-Clause"
] | null | null | null | libcaf_core/src/init_global_meta_objects.cpp | jsiwek/actor-framework | 06cd2836f4671725cb7eaa22b3cc115687520fc1 | [
"BSL-1.0",
"BSD-3-Clause"
] | null | null | null | /******************************************************************************
* ____ _ _____ *
* / ___| / \ | ___| C++ *
* | | / _ \ | |_ Actor *
* | |___ / ___ \| _| Framework *
* \____/_/ \_|_| *
* *
* Copyright 2011-2020 Dominik Charousset *
* *
* Distributed under the terms and conditions of the BSD 3-Clause License or *
* (at your option) under the terms and conditions of the Boost Software *
* License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *
* *
* If you did not receive a copy of the license files, see *
* http://opensource.org/licenses/BSD-3-Clause and *
* http://www.boost.org/LICENSE_1_0.txt. *
******************************************************************************/
#include "caf/init_global_meta_objects.hpp"
#include "caf/actor.hpp"
#include "caf/actor_addr.hpp"
#include "caf/actor_control_block.hpp"
#include "caf/actor_system.hpp"
#include "caf/byte_buffer.hpp"
#include "caf/config_value.hpp"
#include "caf/downstream_msg.hpp"
#include "caf/error.hpp"
#include "caf/group.hpp"
#include "caf/ipv4_address.hpp"
#include "caf/ipv4_endpoint.hpp"
#include "caf/ipv4_subnet.hpp"
#include "caf/ipv6_address.hpp"
#include "caf/ipv6_endpoint.hpp"
#include "caf/ipv6_subnet.hpp"
#include "caf/message.hpp"
#include "caf/message_id.hpp"
#include "caf/node_id.hpp"
#include "caf/system_messages.hpp"
#include "caf/timespan.hpp"
#include "caf/timestamp.hpp"
#include "caf/unit.hpp"
#include "caf/upstream_msg.hpp"
#include "caf/uri.hpp"
namespace caf::core {
void init_global_meta_objects() {
caf::init_global_meta_objects<id_block::core_module>();
}
} // namespace caf::core
| 42.849057 | 80 | 0.467195 | jsiwek |
6afbde42b46c1fe8c0e609634934f2b5a3fa0fea | 3,553 | hpp | C++ | src/xpcc/ui/menu/view_stack.hpp | walmis/xpcc | 1d87c4434530c6aeac923f57d379aeaf32e11e1e | [
"BSD-3-Clause"
] | null | null | null | src/xpcc/ui/menu/view_stack.hpp | walmis/xpcc | 1d87c4434530c6aeac923f57d379aeaf32e11e1e | [
"BSD-3-Clause"
] | null | null | null | src/xpcc/ui/menu/view_stack.hpp | walmis/xpcc | 1d87c4434530c6aeac923f57d379aeaf32e11e1e | [
"BSD-3-Clause"
] | null | null | null | // coding: utf-8
// ----------------------------------------------------------------------------
/* Copyright (c) 2013, Roboterclub Aachen e.V.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Roboterclub Aachen e.V. 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 ROBOTERCLUB AACHEN E.V. ''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 ROBOTERCLUB AACHEN E.V. 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.
*/
// ----------------------------------------------------------------------------
#ifndef XPCC__VIEWSTACK_HPP
#define XPCC__VIEWSTACK_HPP
#include "../display/graphic_display.hpp"
#include "../../container/stack.hpp"
#include "../../container/linked_list.hpp"
#include "menu_buttons.hpp"
#include "abstract_view.hpp"
namespace xpcc
{
/**
* \brief Stack which handles the displaying
* of views on the graphic display.
*
* This class also deallocates the views passed
* to the stack.
*
* \ingroup display_menu
* \author Thorsten Lajewski
*/
class ViewStack
{
public:
ViewStack(xpcc::GraphicDisplay* display);
virtual ~ViewStack();
/**
* @brief get the top view from the stack
* @return pointer to view from stack
*/
inline xpcc::AbstractView*
get()
{
return this->stack.get();
}
/**
* @brief push new view on top of stack the new
* view will be displayed instead of the old
* one
*
* @param view next displayed view
*/
inline void
push(xpcc::AbstractView* view)
{
this->stack.push(view);
this->getDisplay().clear();
xpcc::AbstractView* top = this->get();
top->draw();
this->display->update();
}
/**
* @brief getDisplay access underlying GraphicDisplay
*/
inline xpcc::GraphicDisplay&
getDisplay()
{
return *this->display;
}
/**
* @brief pop remove top view from the stack. The removed
* view is deleted
*/
void
pop();
virtual void
update();
/**
* @brief shortButtonPress pass the button press to the current top view
* @param button the pressed button
*/
void
shortButtonPress(xpcc::MenuButtons::Button button);
private:
xpcc::GraphicDisplay* display;
xpcc::Stack< xpcc::AbstractView* , xpcc::LinkedList< xpcc::AbstractView* > > stack;
};
}
#endif // XPCC__VIEWSTACK_HPP
| 28.886179 | 85 | 0.663946 | walmis |
1394ddae0ee9cddc9dc32ee80045723270df1d17 | 942 | cpp | C++ | src/shared/state/CheckPoint.cpp | samhanic/plt | 3fdbcd6fb945e6e680216bbf72e51cef7785d874 | [
"CC0-1.0"
] | 1 | 2019-09-18T20:45:56.000Z | 2019-09-18T20:45:56.000Z | src/shared/state/CheckPoint.cpp | samhanic/plt | 3fdbcd6fb945e6e680216bbf72e51cef7785d874 | [
"CC0-1.0"
] | null | null | null | src/shared/state/CheckPoint.cpp | samhanic/plt | 3fdbcd6fb945e6e680216bbf72e51cef7785d874 | [
"CC0-1.0"
] | null | null | null | #include "CheckPoint.h"
#include <algorithm>
using namespace state;
CheckPoint::CheckPoint (CheckPointTypeId checkPointTypeId, int newX, int newY, int newTileCode):MapTile(CHECKPOINT, newX, newY, newTileCode) {
position.setX(newX);
position.setY(newY);
if (checkPointTypeId==CP_ONE) checkPointFigure = 1;
if (checkPointTypeId==CP_TWO) checkPointFigure = 2;
if (checkPointTypeId==CP_THREE) checkPointFigure = 3;
if (checkPointTypeId==CP_FOUR) checkPointFigure = 4;
if (checkPointTypeId==CP_FIVE) checkPointFigure = 5;
}
bool CheckPoint::isVisited (Robot robot) {
std::vector<int> v = robot.getVisitedCheckpoints();
if (std::find(v.begin(), v.end(), checkPointFigure) != v.end()){
return true;
}
return false;
}
int CheckPoint::getCheckPointFigure(){
return checkPointFigure;
}
void CheckPoint::setCheckPointFigure (int checkPointFigure){
this->checkPointFigure = checkPointFigure;
}
| 29.4375 | 142 | 0.726115 | samhanic |
139b22f7b7ab51418d928f042933c4aa041be399 | 1,025 | hxx | C++ | Legolas/BlockMatrix/Structures/Diagonal/DiagonalScalarContainer.hxx | LaurentPlagne/Legolas | fdf533528baf7ab5fcb1db15d95d2387b3e3723c | [
"MIT"
] | null | null | null | Legolas/BlockMatrix/Structures/Diagonal/DiagonalScalarContainer.hxx | LaurentPlagne/Legolas | fdf533528baf7ab5fcb1db15d95d2387b3e3723c | [
"MIT"
] | null | null | null | Legolas/BlockMatrix/Structures/Diagonal/DiagonalScalarContainer.hxx | LaurentPlagne/Legolas | fdf533528baf7ab5fcb1db15d95d2387b3e3723c | [
"MIT"
] | 1 | 2021-02-11T14:43:25.000Z | 2021-02-11T14:43:25.000Z | #ifndef __LEGOLAS_DIAGONALSCALARCONTAINER_HXX__
#define __LEGOLAS_DIAGONALSCALARCONTAINER_HXX__
#include "Legolas/BlockMatrix/Matrix.hxx"
namespace Legolas{
class DiagonalScalarContainer{
public:
template <class SCALAR>
class Engine: public Matrix{
public:
typedef SCALAR RealType;
typedef Engine<SCALAR> Container;
private:
typedef Legolas::MultiVector<SCALAR,1> DiagonalData;
DiagonalData diagonalData_;
public:
inline Engine():Matrix(),diagonalData_(){}
inline Engine(const VirtualMatrixShape & virtualMatrixShape):Matrix(virtualMatrixShape),
diagonalData_(virtualMatrixShape.nrows()){}
inline Engine(const Container & container):Matrix(container),
diagonalData_(container.diagonalData_){}
inline const SCALAR & diagonalGetElement(int i) const{ return diagonalData_[i];}
inline SCALAR & diagonalGetElement(int i){ return diagonalData_[i];}
};
};
}
#endif
| 23.837209 | 94 | 0.687805 | LaurentPlagne |
13a47bd6e9050c5758f64c9e2beba08d38f95cdc | 628 | cpp | C++ | Sorting and Searching/Nearest Smaller Values.cpp | razouq/cses | 82534f4ac37a690b5cd72ab094d5276bd01dd64e | [
"MIT"
] | 3 | 2021-03-14T18:47:13.000Z | 2021-03-19T09:59:56.000Z | Sorting and Searching/Nearest Smaller Values.cpp | razouq/cses | 82534f4ac37a690b5cd72ab094d5276bd01dd64e | [
"MIT"
] | null | null | null | Sorting and Searching/Nearest Smaller Values.cpp | razouq/cses | 82534f4ac37a690b5cd72ab094d5276bd01dd64e | [
"MIT"
] | null | null | null | #include "bits/stdc++.h"
#pragma GCC optimize ("O3")
#pragma GCC target ("sse4")
#define ll long long
#define ull unsigned long long
#define F first
#define S second
#define PB push_back
#define POB pop_back
using namespace std;
int main(){
// freopen("input.in", "r", stdin);
// freopen("output.out", "w", stdout);
ios::sync_with_stdio(0);
cin.tie();
int n;
cin>>n;
stack<pair<ll, int>> s;
for(int i = 0; i < n; i++) {
ll x;
cin>>x;
while(!s.empty() && (s.top()).F >= x) {
s.pop();
}
if(s.empty()) {
cout<<0<<" ";
} else {
cout<<s.top().S<<" ";
}
s.push({x, i+1});
}
return 0;
}
| 14.952381 | 41 | 0.555732 | razouq |
13acf9686beb0db0e1b73adb066a38d3950105ba | 445 | cpp | C++ | leetcodes/MaxProfitStock.cpp | DaechurJeong/Private_Proj | 66eec4d22372166af7f7643a9b1307ca7e5ce21a | [
"MIT"
] | null | null | null | leetcodes/MaxProfitStock.cpp | DaechurJeong/Private_Proj | 66eec4d22372166af7f7643a9b1307ca7e5ce21a | [
"MIT"
] | null | null | null | leetcodes/MaxProfitStock.cpp | DaechurJeong/Private_Proj | 66eec4d22372166af7f7643a9b1307ca7e5ce21a | [
"MIT"
] | 2 | 2020-04-21T23:52:31.000Z | 2020-04-24T13:37:28.000Z | #include <iostream>
#include <vector>
int maxProfit(std::vector<int>& prices) {
int min = prices[0], res = 0;
for (int i = 1; i < prices.size(); ++i) {
if (min > prices[i]) {
min = prices[i];
}
else if (prices[i] - min > res) {
res = prices[i] - min;
}
}
return res;
}
int main(void)
{
std::vector<int> input{ 7,1,5,3,6,4 };
//std::vector<int> input{ 7,6,4,3,1 };
std::cout << maxProfit(input) << std::endl;
return 0;
} | 17.8 | 44 | 0.559551 | DaechurJeong |
13b101a172f2cf45551130e236a256177a073fc8 | 3,182 | cpp | C++ | Unreal/CtaCpp/Runtime/Scripts/Combat/EquipmentSystem.cpp | areilly711/CtaApi | 8c7a80c48f2a6d02fb6680a5d8f62e6ff7da8d4c | [
"MIT"
] | 3 | 2021-06-02T16:44:02.000Z | 2022-01-24T20:20:10.000Z | Unreal/CtaCpp/Runtime/Scripts/Combat/EquipmentSystem.cpp | areilly711/CtaApi | 8c7a80c48f2a6d02fb6680a5d8f62e6ff7da8d4c | [
"MIT"
] | null | null | null | Unreal/CtaCpp/Runtime/Scripts/Combat/EquipmentSystem.cpp | areilly711/CtaApi | 8c7a80c48f2a6d02fb6680a5d8f62e6ff7da8d4c | [
"MIT"
] | null | null | null | #include "EquipmentSystem.h"
namespace Cta::Combat
{
int EquipmentSystem::Equip(Entity owner, Entity item)
{
EquipmentSlot tempVar = EquipmentSlot();
tempVar.value = FindEmptySlot(owner);
return Equip(owner, item, tempVar);
}
int EquipmentSystem::Equip(Entity owner, Entity item, EquipmentSlot slot)
{
if (m_entityEquipment->find(owner) == m_entityEquipment->end())
{
List<Entity> tempVar();
m_entityEquipment->emplace(owner, &tempVar);
}
m_entityEquipment[owner]->push_back(item);
return slot.value;
}
void EquipmentSystem::Unequip(Entity owner, Entity item)
{
if (EntityExists(owner))
{
m_entityEquipment[owner]->Remove(item);
}
}
Cta::Entity EquipmentSystem::GetItemFromSlot(Entity owner, int slot)
{
Entity item = Entity::Null;
if (!EntityExists(owner))
{
Logger::LogErrorFormat(L"Entity {0} doesn't have equipment", {GetEntityName(owner)});
return item;
}
List<Entity> *items = m_entityEquipment[owner];
for (int i = 0; i < items->size(); i++)
{
if (getEcs()->HasComponent<EquipmentSlot>(items[i]))
{
EquipmentSlot eSlot = getEcs()->GetComponent<EquipmentSlot>(items[i]);
if (eSlot.value == slot)
{
item = items[i];
break;
}
}
}
if (item == Entity::Null)
{
Logger::LogErrorFormat(L"Entity {0} doesn't have item in slot {1}", {GetEntityName(owner), slot});
}
return item;
}
bool EquipmentSystem::HasItem(Entity owner, Entity item)
{
return m_entityEquipment->find(owner) != m_entityEquipment->end() && std::find(m_entityEquipment[owner]->begin(), m_entityEquipment[owner]->end(), item) != m_entityEquipment[owner]->end();
}
bool EquipmentSystem::EntityExists(Entity entity)
{
return m_entityEquipment->find(entity) != m_entityEquipment->end();
}
int EquipmentSystem::FindEmptySlot(Entity owner)
{
if (!EntityExists(owner))
{
return 0;
}
int highest = -1;
List<Entity> *items = m_entityEquipment[owner];
for (int i = 0; i < items->size(); i++)
{
if (getEcs()->HasComponent<EquipmentSlot>(items[i]))
{
EquipmentSlot eSlot = getEcs()->GetComponent<EquipmentSlot>(items[i]);
if (highest < eSlot.value)
{
highest = eSlot.value;
break;
}
}
}
highest += 1;
return highest;
}
Cta::Entity EquipmentSystem::GetOwner(Entity item)
{
for (auto kvp : *m_entityEquipment)
{
if (std::find(kvp->Value->begin(), kvp->Value->end(), item) != kvp->Value->end())
{
return kvp->getKey();
}
}
Logger::LogWarningFormat(L"Item {0} does not have an owner", {GetEntityName(item)});
return Entity::Null;
}
int EquipmentSystem::GetItemSlot(Entity owner, Entity item)
{
if (!EntityExists(owner))
{
Logger::LogErrorFormat(L"Entity {0} doesn't have equipment", {GetEntityName(owner)});
return 0;
}
List<Entity> *items = m_entityEquipment[owner];
int index = items->FindIndex([&] (i)
{
return i == item;
});
if (index == -1)
{
Logger::LogErrorFormat(L"Entity {0} doesn't own item {1}", {GetEntityName(owner), GetEntityName(item)});
return 0;
}
EquipmentSlot slot = getEcs()->GetComponent<EquipmentSlot>(items[index]);
return slot.value;
}
}
| 23.057971 | 190 | 0.658705 | areilly711 |
13b42752d9f06e8a1da421922a9b9b6cc3db6241 | 1,981 | cpp | C++ | src/kits/debugger/debug_info/DwarfFunctionDebugInfo.cpp | stasinek/BHAPI | 5d9aa61665ae2cc5c6e34415957d49a769325b2b | [
"BSD-3-Clause",
"MIT"
] | 3 | 2018-05-21T15:32:32.000Z | 2019-03-21T13:34:55.000Z | src/kits/debugger/debug_info/DwarfFunctionDebugInfo.cpp | stasinek/BHAPI | 5d9aa61665ae2cc5c6e34415957d49a769325b2b | [
"BSD-3-Clause",
"MIT"
] | null | null | null | src/kits/debugger/debug_info/DwarfFunctionDebugInfo.cpp | stasinek/BHAPI | 5d9aa61665ae2cc5c6e34415957d49a769325b2b | [
"BSD-3-Clause",
"MIT"
] | null | null | null | /*
* Copyright 2009, Ingo Weinhold, ingo_weinhold@gmx.de.
* Distributed under the terms of the MIT License.
*/
#include <DwarfFunctionDebugInfo.h>
#include <DebugInfoEntries.h>
#include <DwarfImageDebugInfo.h>
#include <LocatableFile.h>
#include <TargetAddressRangeList.h>
DwarfFunctionDebugInfo::DwarfFunctionDebugInfo(
DwarfImageDebugInfo* imageDebugInfo, CompilationUnit* compilationUnit,
DIESubprogram* subprogramEntry, TargetAddressRangeList* addressRanges,
const BString& name, LocatableFile* sourceFile,
const SourceLocation& sourceLocation)
:
fImageDebugInfo(imageDebugInfo),
fCompilationUnit(compilationUnit),
fSubprogramEntry(subprogramEntry),
fAddressRanges(addressRanges),
fName(name),
fSourceFile(sourceFile),
fSourceLocation(sourceLocation)
{
fImageDebugInfo->AcquireReference();
fAddressRanges->AcquireReference();
if (fSourceFile != NULL)
fSourceFile->AcquireReference();
}
DwarfFunctionDebugInfo::~DwarfFunctionDebugInfo()
{
if (fSourceFile != NULL)
fSourceFile->ReleaseReference();
fAddressRanges->ReleaseReference();
fImageDebugInfo->ReleaseReference();
}
SpecificImageDebugInfo*
DwarfFunctionDebugInfo::GetSpecificImageDebugInfo() const
{
return fImageDebugInfo;
}
target_addr_t
DwarfFunctionDebugInfo::Address() const
{
return fAddressRanges->LowestAddress() + fImageDebugInfo->RelocationDelta();
}
target_size_t
DwarfFunctionDebugInfo::Size() const
{
return fAddressRanges->CoveringRange().Size();
}
const BString&
DwarfFunctionDebugInfo::Name() const
{
return fName;
}
const BString&
DwarfFunctionDebugInfo::PrettyName() const
{
return fName;
}
bool DwarfFunctionDebugInfo::IsMain() const
{
return fSubprogramEntry->IsMain();
}
LocatableFile*
DwarfFunctionDebugInfo::SourceFile() const
{
return fSourceFile;
}
SourceLocation
DwarfFunctionDebugInfo::SourceStartLocation() const
{
return fSourceLocation;
}
SourceLocation
DwarfFunctionDebugInfo::SourceEndLocation() const
{
return fSourceLocation;
}
| 18.688679 | 77 | 0.797072 | stasinek |
13b550ddbf434b17366d20effce06df1d5f336db | 9,992 | cpp | C++ | Libs/JUCE/modules/dRowAudio/network/dRowAudio_CURLEasySession.cpp | djh-/LaunchpadLights | 2a6827c558ff289413925cbba8705e75d1dd410b | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null | Libs/JUCE/modules/dRowAudio/network/dRowAudio_CURLEasySession.cpp | djh-/LaunchpadLights | 2a6827c558ff289413925cbba8705e75d1dd410b | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 1 | 2021-12-10T23:30:18.000Z | 2021-12-10T23:30:18.000Z | JuceLibraryCode/modules/dRowAudio/network/dRowAudio_CURLEasySession.cpp | danielhaaser/LaunchpadLights | 2a6827c558ff289413925cbba8705e75d1dd410b | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 1 | 2021-07-29T19:03:22.000Z | 2021-07-29T19:03:22.000Z | /*
==============================================================================
This file is part of the dRowAudio JUCE module
Copyright 2004-13 by dRowAudio.
------------------------------------------------------------------------------
dRowAudio is provided under the terms of The MIT License (MIT):
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.
==============================================================================
*/
#if DROWAUDIO_USE_CURL
} //namespace drow
#if JUCE_WINDOWS
#include "curl/include/curl/curl.h"
#else
#include <curl/curl.h>
#endif
namespace drow {
//==============================================================================
CURLEasySession::CURLEasySession()
: handle (CURLManager::getInstance()->createEasyCurlHandle()),
remotePath (String::empty),
progress (1.0f)
{
enableFullDebugging (true);
curl_easy_setopt (handle, CURLOPT_NOPROGRESS, false);
}
CURLEasySession::CURLEasySession (String localPath,
String remotePath,
bool upload,
String username,
String password)
: handle (CURLManager::getInstance()->createEasyCurlHandle())
{
handle = CURLManager::getInstance()->createEasyCurlHandle();
enableFullDebugging (true);
curl_easy_setopt (handle, CURLOPT_NOPROGRESS, false);
setLocalFile (localPath);
setRemotePath (remotePath);
setUserNameAndPassword (username, password);
beginTransfer (upload);
}
CURLEasySession::~CURLEasySession()
{
CURLManager::getInstance()->removeTimeSliceClient (this);
if (CURLManager::getInstance()->getNumClients() == 0)
CURLManager::getInstance()->stopThread (1000);
CURLManager::getInstance()->cleanUpEasyCurlHandle (handle);
}
//==============================================================================
void CURLEasySession::setInputStream (InputStream* newInputStream)
{
localFile = File::nonexistent;
inputStream = newInputStream;
}
void CURLEasySession::setLocalFile (File newLocalFile)
{
localFile = newLocalFile;
inputStream = localFile.createInputStream();
}
void CURLEasySession::setRemotePath (String newRemotePath)
{
remotePath = newRemotePath;
if (remotePath.getLastCharacters (1) == "/")
remotePath = remotePath << localFile.getFileName();
curl_easy_setopt (handle, CURLOPT_URL, remotePath.toUTF8().getAddress());
}
void CURLEasySession::setUserNameAndPassword (String username, String password)
{
userNameAndPassword = username << ":" << password;
curl_easy_setopt (handle, CURLOPT_USERPWD, userNameAndPassword.toUTF8().getAddress());
}
//==============================================================================
String CURLEasySession::getCurrentWorkingDirectory()
{
char url[1000];
CURLcode res = curl_easy_getinfo (handle, CURLINFO_EFFECTIVE_URL, url);
if (res == CURLE_OK && CharPointer_ASCII::isValidString (url, 1000))
return String (url);
else
return String::empty;
}
StringArray CURLEasySession::getDirectoryListing()
{
String remoteUrl (remotePath.upToLastOccurrenceOf ("/", true, false));
curl_easy_setopt (handle, CURLOPT_URL, remoteUrl.toUTF8().getAddress());
directoryContentsList.setSize (0);
curl_easy_setopt (handle, CURLOPT_PROGRESSFUNCTION, 0L);
curl_easy_setopt (handle, CURLOPT_UPLOAD, 0L);
curl_easy_setopt (handle, CURLOPT_DIRLISTONLY, 1L);
curl_easy_setopt (handle, CURLOPT_WRITEDATA, this);
curl_easy_setopt (handle, CURLOPT_WRITEFUNCTION, directoryListingCallback);
// perform the tranfer
progress = 0.0f;
CURLcode result = curl_easy_perform (handle);
reset();
if (result == CURLE_OK)
{
StringArray list;
list.addLines (directoryContentsList.toString().trim());
return list;
}
else
{
return StringArray (curl_easy_strerror (result));
}
}
// not yet ready
//String CURLEasySession::getContentType()
//{
// char *ct;
//
// CURLcode result = curl_easy_getinfo (handle, CURLINFO_CONTENT_TYPE, &ct);
//
// if (CURLE_OK == result)// && ct != nullptr)
// {
// DBG("CURLE_OK: " + remotePath);
// return ct;
// }
// else
// {
// DBG("CURLE_NOT_OK");
// return String::empty;
// }
//}
//==============================================================================
void CURLEasySession::enableFullDebugging (bool shouldEnableFullDebugging)
{
curl_easy_setopt (handle, CURLOPT_VERBOSE, shouldEnableFullDebugging ? 1L : 0L);
}
void CURLEasySession::beginTransfer (bool transferIsUpload, bool performOnBackgroundThread)
{
isUpload = transferIsUpload;
shouldStopTransfer = false;
if (performOnBackgroundThread)
{
CURLManager::getInstance()->addTimeSliceClient (this);
CURLManager::getInstance()->startThread();
}
else
{
performTransfer (isUpload);
}
}
void CURLEasySession::stopTransfer()
{
shouldStopTransfer = true;
}
void CURLEasySession::reset()
{
curl_easy_reset (handle);
curl_easy_setopt (handle, CURLOPT_URL, remotePath.toUTF8().getAddress());
curl_easy_setopt (handle, CURLOPT_USERPWD, userNameAndPassword.toUTF8().getAddress());
curl_easy_setopt (handle, CURLOPT_NOPROGRESS, false);
}
//==============================================================================
void CURLEasySession::addListener (CURLEasySession::Listener* const listener)
{
listeners.add (listener);
}
void CURLEasySession::removeListener (CURLEasySession::Listener* const listener)
{
listeners.remove (listener);
}
//==============================================================================
int CURLEasySession::useTimeSlice()
{
performTransfer (isUpload);
return -1;
}
//==============================================================================
size_t CURLEasySession::writeCallback (void* sourcePointer, size_t blockSize, size_t numBlocks, CURLEasySession* session)
{
if (session != nullptr)
{
if (session->outputStream->failedToOpen())
{
/* failure, can't open file to write */
return ! (blockSize * numBlocks); // return a value not equal to (blockSize * numBlocks)
}
session->outputStream->write (sourcePointer, blockSize * numBlocks);
return blockSize * numBlocks;
}
return ! (blockSize * numBlocks); // return a value not equal to (blockSize * numBlocks)
}
size_t CURLEasySession::readCallback (void* destinationPointer, size_t blockSize, size_t numBlocks, CURLEasySession* session)
{
if (session != nullptr)
{
if (session->inputStream.get() == nullptr)
{
return CURL_READFUNC_ABORT; /* failure, can't open file to read */
}
return session->inputStream->read (destinationPointer, blockSize * numBlocks);
}
return CURL_READFUNC_ABORT;
}
size_t CURLEasySession::directoryListingCallback (void* sourcePointer, size_t blockSize, size_t numBlocks, CURLEasySession* session)
{
if (session != nullptr)
{
session->directoryContentsList.append (sourcePointer, (int) (blockSize * numBlocks));
return blockSize * numBlocks;
}
return ! (blockSize * numBlocks); // return a positive value not equal to (blockSize * numBlocks)
}
int CURLEasySession::internalProgressCallback (CURLEasySession* session, double dltotal, double dlnow, double /*ultotal*/, double ulnow)
{
session->progress = (float) (session->isUpload ? (ulnow / session->inputStream->getTotalLength()) : (dlnow / dltotal));
session->listeners.call (&CURLEasySession::Listener::transferProgressUpdate, session);
return (int) session->shouldStopTransfer;
}
//==============================================================================
int CURLEasySession::performTransfer (bool transferIsUpload)
{
curl_easy_setopt (handle, CURLOPT_URL, remotePath.toUTF8().getAddress());
curl_easy_setopt (handle, CURLOPT_UPLOAD, (long) transferIsUpload);
curl_easy_setopt (handle, CURLOPT_PROGRESSDATA, this);
curl_easy_setopt (handle, CURLOPT_PROGRESSFUNCTION, internalProgressCallback);
if (transferIsUpload == true)
{
// sets the pointer to be passed to the read callback
curl_easy_setopt (handle, CURLOPT_READDATA, this);
curl_easy_setopt (handle, CURLOPT_READFUNCTION, readCallback);
inputStream->setPosition (0);
}
else
{
// sets the pointer to be passed to the write callback
curl_easy_setopt (handle, CURLOPT_WRITEDATA, this);
curl_easy_setopt (handle, CURLOPT_WRITEFUNCTION, writeCallback);
// create local file to recieve transfer
if (localFile.existsAsFile())
localFile = localFile.getNonexistentSibling();
outputStream = localFile.createOutputStream();
}
//perform the transfer
progress = 0.0f;
listeners.call (&CURLEasySession::Listener::transferAboutToStart, this);
CURLcode result = curl_easy_perform (handle);
// delete the streams to flush the buffers
outputStream = nullptr;
listeners.call (&CURLEasySession::Listener::transferEnded, this);
return result;
}
#endif | 31.031056 | 136 | 0.659027 | djh- |
13b99d577f9e441e4fe164142e0015d26d8b7d0a | 1,215 | hpp | C++ | src/utility/calculate_nnz.hpp | spraetor/amdis2 | 53c45c81a65752a8fafbb54f9ae6724a86639dcd | [
"MIT"
] | 2 | 2018-07-04T16:44:04.000Z | 2021-01-03T07:26:27.000Z | src/utility/calculate_nnz.hpp | spraetor/amdis2 | 53c45c81a65752a8fafbb54f9ae6724a86639dcd | [
"MIT"
] | null | null | null | src/utility/calculate_nnz.hpp | spraetor/amdis2 | 53c45c81a65752a8fafbb54f9ae6724a86639dcd | [
"MIT"
] | null | null | null | #pragma once
namespace AMDiS
{
inline void calculate_nnz(const DOFMatrix& matrix, std::vector<size_t>& nnz_per_row)
{
std::vector<std::set<DegreeOfFreefom>> nnz(nnz_per_row.size());
std::vector<DegreeOfFreedom> rowIndices, colIndices;
const FiniteElemSpace* rowFeSpace = matrix.getRowFeSpace(),
colFeSpace = matrix.getColFeSpace();
TraverseStack stack;
ElInfo* elInfo = stack.traverseFirst(rowFeSpace->getMesh(), -1, Mesh::CALL_LEAF_EL);
while (elInfo)
{
rowFeSpace->getBasisFcts()->getLocalIndices(elInfo->getElement(),
rowFeSpace->getAdmin(),
rowIndices);
if (rowFeSpace == colFeSpace)
{
colIndices = rowIndices;
}
else
{
colFeSpace->getBasisFcts()->getLocalIndices(elInfo->getElement(),
colFeSpace->getAdmin(),
colIndices);
}
for (size_t r = 0; r < rowIndices.size(); r++)
for (size_t c = 0; c < rowIndices.size(); c++)
nnz[rowIndices[r]].insert(colIndices[c]);
elInfo = stack.traverseNext(elInfo);
}
for (size_t r = 0; r < nnz.size(); r++)
nnz_per_row[r] = nnz[r].size();
}
} // end namspace AMDiS
| 28.928571 | 88 | 0.604115 | spraetor |
13be938cb22af95f5e19db949409597d794c2057 | 12,572 | cpp | C++ | compendium/DeclarativeServices/src/manager/ReferenceManagerImpl.cpp | githubforsank/CppMicroServices | e6ae266cd02b7145f17bc2499e5e8234e4ff76c2 | [
"Apache-2.0"
] | 1 | 2019-11-01T02:57:31.000Z | 2019-11-01T02:57:31.000Z | compendium/DeclarativeServices/src/manager/ReferenceManagerImpl.cpp | githubforsank/CppMicroServices | e6ae266cd02b7145f17bc2499e5e8234e4ff76c2 | [
"Apache-2.0"
] | 1 | 2019-11-05T12:51:59.000Z | 2019-11-05T12:51:59.000Z | compendium/DeclarativeServices/src/manager/ReferenceManagerImpl.cpp | githubforsank/CppMicroServices | e6ae266cd02b7145f17bc2499e5e8234e4ff76c2 | [
"Apache-2.0"
] | null | null | null | /*=============================================================================
Library: CppMicroServices
Copyright (c) The CppMicroServices developers. See the COPYRIGHT
file at the top-level directory of this distribution and at
https://github.com/CppMicroServices/CppMicroServices/COPYRIGHT .
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 <cassert>
#include "cppmicroservices/ServiceReference.h"
#include "cppmicroservices/LDAPProp.h"
#include "cppmicroservices/servicecomponent/ComponentConstants.hpp"
#include "ReferenceManagerImpl.hpp"
using cppmicroservices::logservice::SeverityLevel;
using cppmicroservices::service::component::ComponentConstants::REFERENCE_SCOPE_PROTOTYPE_REQUIRED;
using cppmicroservices::Constants::SERVICE_SCOPE;
using cppmicroservices::Constants::SCOPE_PROTOTYPE;
namespace cppmicroservices {
namespace scrimpl {
/**
* @brief Returns the LDAPFilter of the reference metadata
* @param refMetadata The metadata representing a service reference
* @returns a LDAPFilter object corresponding to the @p refMetadata
*/
LDAPFilter GetReferenceLDAPFilter(const metadata::ReferenceMetadata& refMetadata)
{
LDAPPropExpr expr;
expr = (LDAPProp(cppmicroservices::Constants::OBJECTCLASS) == refMetadata.interfaceName);
if(!refMetadata.target.empty())
{
expr &= LDAPPropExpr(refMetadata.target);
}
if(refMetadata.scope == REFERENCE_SCOPE_PROTOTYPE_REQUIRED)
{
expr &= (LDAPProp(SERVICE_SCOPE) == SCOPE_PROTOTYPE);
}
return LDAPFilter(expr);
}
ReferenceManagerImpl::ReferenceManagerImpl(const metadata::ReferenceMetadata& metadata,
const cppmicroservices::BundleContext& bc,
std::shared_ptr<cppmicroservices::logservice::LogService> logger)
: metadata(metadata)
, tracker(nullptr)
, logger(std::move(logger))
{
if(!bc || !this->logger)
{
throw std::invalid_argument("Failed to create object, Invalid arguments passed to constructor");
}
try
{
tracker = std::make_unique<ServiceTracker<void>>(bc, GetReferenceLDAPFilter(metadata), this);
tracker->Open();
}
catch(...)
{
logger->Log(SeverityLevel::LOG_ERROR, "could not open service tracker for " + metadata.interfaceName, std::current_exception());
tracker.reset();
throw std::current_exception();
}
}
void ReferenceManagerImpl::StopTracking()
{
try
{
tracker->Close();
}
catch(...)
{
logger->Log(SeverityLevel::LOG_ERROR, "Exception caught while closing service tracker for " + metadata.interfaceName, std::current_exception());
}
}
std::set<cppmicroservices::ServiceReferenceBase> ReferenceManagerImpl::GetBoundReferences() const
{
auto boundRefsHandle = boundRefs.lock();
return std::set<cppmicroservices::ServiceReferenceBase>(boundRefsHandle->begin(), boundRefsHandle->end());
}
std::set<cppmicroservices::ServiceReferenceBase> ReferenceManagerImpl::GetTargetReferences() const
{
auto matchedRefsHandle = matchedRefs.lock();
return std::set<cppmicroservices::ServiceReferenceBase>(matchedRefsHandle->begin(), matchedRefsHandle->end());
}
// util method to extract service-id from a given reference
long GetServiceId(const ServiceReferenceBase& sRef)
{
auto idAny = sRef.GetProperty(cppmicroservices::Constants::SERVICE_ID);
return cppmicroservices::any_cast<long>(idAny);
}
bool ReferenceManagerImpl::IsOptional() const
{
return (metadata.minCardinality == 0);
}
bool ReferenceManagerImpl::IsSatisfied() const
{
return (boundRefs.lock()->size() >= metadata.minCardinality);
}
ReferenceManagerImpl::~ReferenceManagerImpl()
{
StopTracking();
}
struct dummyRefObj {
};
bool ReferenceManagerImpl::UpdateBoundRefs()
{
auto matchedRefsHandle = matchedRefs.lock(); // acquires lock on matchedRefs
const auto matchedRefsHandleSize = matchedRefsHandle->size();
if(matchedRefsHandleSize >= metadata.minCardinality)
{
auto boundRefsHandle = boundRefs.lock(); // acquires lock on boundRefs
std::copy_n(matchedRefsHandle->rbegin(),
std::min(metadata.maxCardinality, matchedRefsHandleSize),
std::inserter(*(boundRefsHandle),
boundRefsHandle->begin()));
return true;
}
return false;
// release locks on matchedRefs and boundRefs
}
// This method implements the following algorithm
//
// if reference becomes satisfied
// Copy service references from #matchedRefs to #boundRefs
// send a SATISFIED notification to listeners
// else if reference is already satisfied
// if policyOption is reluctant
// ignore the new servcie
// else if policyOption is GREEDY
// if the new service is better than any of the existing services in #boundRefs
// send UNSATISFIED notification to listeners
// clear #boundRefs
// copy #matchedRefs to #boundRefs
// send a SATISFIED notification to listeners
// endif
// endif
// endif
void ReferenceManagerImpl::ServiceAdded(const cppmicroservices::ServiceReferenceBase& reference)
{
std::vector<RefChangeNotification> notifications;
if(!reference)
{
logger->Log(SeverityLevel::LOG_DEBUG, "ServiceAdded: service with id " + std::to_string(GetServiceId(reference)) + " has already been unregistered, no-op");
return;
}
// const auto minCardinality = metadata.minCardinality;
// const auto maxCardinality = metadata.maxCardinality;
// auto prevSatisfied = false;
// auto becomesSatisfied = false;
auto replacementNeeded = false;
auto notifySatisfied = false;
auto serviceIdToUnbind = -1;
if(!IsSatisfied())
{
notifySatisfied = UpdateBoundRefs(); // becomes satisfied if return value is true
}
else // previously satisfied
{
if (metadata.policyOption == "greedy")
{
auto boundRefsHandle = boundRefs.lock(); // acquire lock on boundRefs
if (boundRefsHandle->find(reference) == boundRefsHandle->end()) // reference is not bound yet
{
if (!boundRefsHandle->empty())
{
const ServiceReferenceBase& minBound = *(boundRefsHandle->begin());
if (minBound < reference)
{
replacementNeeded = true;
serviceIdToUnbind = GetServiceId(minBound);
}
}
else
{
replacementNeeded = IsOptional();
}
}
}
}
if(replacementNeeded)
{
logger->Log(SeverityLevel::LOG_DEBUG, "Notify UNSATISFIED for reference " + metadata.name);
RefChangeNotification notification{metadata.name, RefEvent::BECAME_UNSATISFIED};
notifications.push_back(std::move(notification));
// The following "clear and copy" strategy is sufficient for
// updating the boundRefs for static binding policy
if(0 < serviceIdToUnbind)
{
auto boundRefsHandle = boundRefs.lock();
boundRefsHandle->clear();
}
notifySatisfied = UpdateBoundRefs();
}
if(notifySatisfied)
{
logger->Log(SeverityLevel::LOG_DEBUG, "Notify SATISFIED for reference " + metadata.name);
RefChangeNotification notification{metadata.name, RefEvent::BECAME_SATISFIED};
notifications.push_back(std::move(notification));
}
BatchNotifyAllListeners(notifications);
}
cppmicroservices::InterfaceMapConstPtr ReferenceManagerImpl::AddingService(const cppmicroservices::ServiceReference<void>& reference)
{
{ // acquire lock on matchedRefs
auto matchedRefsHandle = matchedRefs.lock();
matchedRefsHandle->insert(reference);
} // release lock on matchedRefs
// After updating the bound references on this thread, notifying listeners happens on a separate thread
// see "synchronous" section in https://osgi.org/download/r6/osgi.core-6.0.0.pdf#page=432
ServiceAdded(reference);
// A non-null object must be returned to indicate to the ServiceTracker that
// we are tracking the service and need to be called back when the service is removed.
return MakeInterfaceMap<dummyRefObj>(std::make_shared<dummyRefObj>());
}
void ReferenceManagerImpl::ModifiedService(const cppmicroservices::ServiceReference<void>& /*reference*/,
const cppmicroservices::InterfaceMapConstPtr& /*service*/)
{
// no-op since there is no use case for property update
}
/**
*This method implements the following algorithm
*
* If the removed service is found in the #boundRefs
* send a UNSATISFIED notification to listeners
* clear the #boundRefs member
* copy #matchedRefs to #boundRefs
* if reference is still satisfied
* send a SATISFIED notification to listeners
* endif
* endif
*/
void ReferenceManagerImpl::ServiceRemoved(const cppmicroservices::ServiceReferenceBase& reference)
{
auto removeBoundRef = false;
std::vector<RefChangeNotification> notifications;
{ // acquire lock on boundRefs
auto boundRefsHandle = boundRefs.lock();
auto itr = boundRefsHandle->find(reference);
removeBoundRef = (itr != boundRefsHandle->end());
} // end lock on boundRefs
if(removeBoundRef)
{
logger->Log(SeverityLevel::LOG_DEBUG, "Notify UNSATISFIED for reference " + metadata.name);
RefChangeNotification notification { metadata.name, RefEvent::BECAME_UNSATISFIED };
notifications.push_back(std::move(notification));
{
auto boundRefsHandle = boundRefs.lock();
boundRefsHandle->clear();
}
auto notifySatisfied = UpdateBoundRefs();
if(notifySatisfied)
{
logger->Log(SeverityLevel::LOG_DEBUG, "Notify SATISFIED for reference " + metadata.name);
RefChangeNotification notification{metadata.name, RefEvent::BECAME_SATISFIED};
notifications.push_back(std::move(notification));
}
BatchNotifyAllListeners(notifications);
}
}
/**
* If a target service is available to replace the bound service which became unavailable,
* the component configuration must be reactivated and the replacement service is bound to
* the new component instance.
*/
void ReferenceManagerImpl::RemovedService(const cppmicroservices::ServiceReference<void>& reference,
const cppmicroservices::InterfaceMapConstPtr& /*service*/)
{
{ // acquire lock on matchedRefs
auto matchedRefsHandle = matchedRefs.lock();
matchedRefsHandle->erase(reference);
} // release lock on matchedRefs
// After updating the bound references on this thread, notifying listeners happens on a separate thread
// see "synchronous" section in https://osgi.org/download/r6/osgi.core-6.0.0.pdf#page=432
ServiceRemoved(reference);
}
std::atomic<cppmicroservices::ListenerTokenId> ReferenceManagerImpl::tokenCounter(0);
/**
* Method is used to register a listener for callbacks
*/
cppmicroservices::ListenerTokenId ReferenceManagerImpl::RegisterListener(std::function<void(const RefChangeNotification&)> notify)
{
auto notifySatisfied = UpdateBoundRefs();
if(notifySatisfied)
{
RefChangeNotification notification { metadata.name, RefEvent::BECAME_SATISFIED };
notify(notification);
}
cppmicroservices::ListenerTokenId retToken = ++tokenCounter;
{
auto listenerMapHandle = listenersMap.lock();
listenerMapHandle->emplace(retToken, notify);
}
return retToken;
}
/**
* Method is used to remove a registered listener
*/
void ReferenceManagerImpl::UnregisterListener(cppmicroservices::ListenerTokenId token)
{
auto listenerMapHandle = listenersMap.lock();
listenerMapHandle->erase(token);
}
/**
* Method used to notify all listeners
*/
void ReferenceManagerImpl::BatchNotifyAllListeners(const std::vector<RefChangeNotification>& notifications) noexcept
{
if (notifications.empty() || listenersMap.lock()->empty())
{
return;
}
RefMgrListenerMap listenersMapCopy;
{
auto listenerMapHandle = listenersMap.lock();
listenersMapCopy = *listenerMapHandle; // copy the listeners map
}
for(auto& listenerPair : listenersMapCopy)
{
for (auto const& notification : notifications)
{
listenerPair.second(notification);
}
}
}
}
}
| 33.886792 | 160 | 0.716115 | githubforsank |
13c0e93ab6b9940659bff4ce15c8e9b82f85d487 | 457 | cpp | C++ | tools/tests/test.cpp | justintime32/osquery | 721dd1ed624b25738c2471dae617d7868df8fb0d | [
"BSD-3-Clause"
] | 23 | 2016-12-07T15:26:58.000Z | 2019-07-18T21:39:06.000Z | tools/tests/test.cpp | justintime32/osquery | 721dd1ed624b25738c2471dae617d7868df8fb0d | [
"BSD-3-Clause"
] | 4 | 2016-12-07T06:18:36.000Z | 2017-01-19T19:39:38.000Z | tools/tests/test.cpp | Acidburn0zzz/osquery | 1cedf8d57310b4ac3ae0a39fe33dce00699f4a3b | [
"BSD-3-Clause"
] | 5 | 2017-06-26T11:54:37.000Z | 2019-02-18T01:23:02.000Z | /*
* Copyright (c) 2014-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include <iostream>
#include <string>
int main(int argc, char* argv[]) {
auto s = "foobar";
std::cout << s << std::endl;
return 0;
}
| 24.052632 | 79 | 0.676149 | justintime32 |
13c157dda00a5f330e19717ae13d2d38285fd4fb | 1,120 | cpp | C++ | 2017-08-14-practice/J.cpp | tangjz/Three-Investigators | 46dc9b2f0fbb4fe89b075a81feaacc33feeb1b52 | [
"MIT"
] | 3 | 2018-04-02T06:00:51.000Z | 2018-05-29T04:46:29.000Z | 2017-08-14-practice/J.cpp | tangjz/Three-Investigators | 46dc9b2f0fbb4fe89b075a81feaacc33feeb1b52 | [
"MIT"
] | 2 | 2018-03-31T17:54:30.000Z | 2018-05-02T11:31:06.000Z | 2017-08-14-practice/J.cpp | tangjz/Three-Investigators | 46dc9b2f0fbb4fe89b075a81feaacc33feeb1b52 | [
"MIT"
] | 2 | 2018-10-07T00:08:06.000Z | 2021-06-28T11:02:59.000Z | #include<bits/stdc++.h>
using namespace std;
#define pb push_back
#define mkp make_pair
#define fi first
#define se second
#define ll long long
#define M 1000000007
#define all(a) a.begin(), a.end()
const int maxn = 100100;
int n, k;
vector<pair<int, int> >g[maxn];
int dp[maxn], ddp[maxn];
void dfs(int t, int fa){
for(auto e : g[t]){
int v = e.fi;
if(v == fa) continue;
dfs(v, t);
}
vector<int> vec;
for(auto e : g[t]){
int v = e.fi, c = e.se;
if(v == fa) continue;
vec.pb(dp[v] + c);
}
sort(all(vec));
reverse(all(vec));
int m = min(k - 1, (int)vec.size());
for(int i = 0; i < m; ++i) dp[t] += vec[i];
ddp[t] = dp[t];
for(auto e : g[t]){
int v = e.fi, c = e.se;
if(v == fa) continue;
if(m && dp[v] + c >= vec[m - 1])
ddp[t] = max(ddp[t], dp[t] - (dp[v] + c) + (m < vec.size() ? vec[m] : 0) + (ddp[v] + c));
else ddp[t] = max(ddp[t], dp[t] + (ddp[v] + c));
}
}
int main(){
scanf("%d%d", &n, &k);
for(int i = 1; i < n; ++i){
static int u, v, c;
scanf("%d%d%d", &u, &v, &c);
g[u].pb(mkp(v, c));
g[v].pb(mkp(u, c));
}
dfs(0, -1);
printf("%d\n", ddp[0]);
return 0;
}
| 20.363636 | 92 | 0.516071 | tangjz |
13c92eb7f5333ecbfaff3059a04bd3c2b2cd29d1 | 1,460 | hpp | C++ | include/RED4ext/Types/generated/AI/behavior/ActionMoveOnSplineNodeDefinition.hpp | Cyberpunk-Extended-Development-Team/RED4ext.SDK | 2dc828c761d87a1b4235ce9ca4fbdf9fb4312fae | [
"MIT"
] | 1 | 2021-02-01T23:07:50.000Z | 2021-02-01T23:07:50.000Z | include/RED4ext/Types/generated/AI/behavior/ActionMoveOnSplineNodeDefinition.hpp | Cyberpunk-Extended-Development-Team/RED4ext.SDK | 2dc828c761d87a1b4235ce9ca4fbdf9fb4312fae | [
"MIT"
] | null | null | null | include/RED4ext/Types/generated/AI/behavior/ActionMoveOnSplineNodeDefinition.hpp | Cyberpunk-Extended-Development-Team/RED4ext.SDK | 2dc828c761d87a1b4235ce9ca4fbdf9fb4312fae | [
"MIT"
] | null | null | null | #pragma once
// This file is generated from the Game's Reflection data
#include <cstdint>
#include <RED4ext/Common.hpp>
#include <RED4ext/REDhash.hpp>
#include <RED4ext/Handle.hpp>
#include <RED4ext/Types/generated/AI/behavior/ActionTreeNodeDefinition.hpp>
namespace RED4ext
{
namespace AI { struct ArgumentMapping; }
namespace AI::behavior {
struct ActionMoveOnSplineNodeDefinition : AI::behavior::ActionTreeNodeDefinition
{
static constexpr const char* NAME = "AIbehaviorActionMoveOnSplineNodeDefinition";
static constexpr const char* ALIAS = NAME;
Handle<AI::ArgumentMapping> spline; // 40
Handle<AI::ArgumentMapping> strafingTarget; // 50
Handle<AI::ArgumentMapping> movementType; // 60
Handle<AI::ArgumentMapping> ignoreNavigation; // 70
Handle<AI::ArgumentMapping> snapToTerrain; // 80
Handle<AI::ArgumentMapping> rotateEntity; // 90
Handle<AI::ArgumentMapping> startFromClosestPoint; // A0
Handle<AI::ArgumentMapping> useStart; // B0
Handle<AI::ArgumentMapping> useStop; // C0
Handle<AI::ArgumentMapping> reverse; // D0
uint8_t unkE0[0xF0 - 0xE0]; // E0
Handle<AI::ArgumentMapping> isBackAndForth; // F0
Handle<AI::ArgumentMapping> isInfinite; // 100
Handle<AI::ArgumentMapping> numberOfLoops; // 110
Handle<AI::ArgumentMapping> useOffMeshLinkReservation; // 120
};
RED4EXT_ASSERT_SIZE(ActionMoveOnSplineNodeDefinition, 0x130);
} // namespace AI::behavior
} // namespace RED4ext
| 36.5 | 85 | 0.746575 | Cyberpunk-Extended-Development-Team |
13caa66fffe35bf8301c3c98bee48b5a7f564459 | 2,863 | cpp | C++ | Yis/src/Yis/Core/Application.cpp | alalba221/Yis | aac89d953e1edb558ec09dc73beecb05edc05c76 | [
"Apache-2.0"
] | null | null | null | Yis/src/Yis/Core/Application.cpp | alalba221/Yis | aac89d953e1edb558ec09dc73beecb05edc05c76 | [
"Apache-2.0"
] | null | null | null | Yis/src/Yis/Core/Application.cpp | alalba221/Yis | aac89d953e1edb558ec09dc73beecb05edc05c76 | [
"Apache-2.0"
] | null | null | null | #include "yspch.h"
#include "Application.h"
#include "Yis/Core/Events/ApplicationEvent.h"
#include "Yis/Renderer/Renderer.h"
#include "Input.h"
//#include <imgui/imgui.h>
#include <Windows.h>
namespace Yis {
#define BIND_ENVENT_FN(x) std::bind(&x, this, std::placeholders::_1)
Application* Application::s_Instance = nullptr;
Application::Application()
{
YS_CORE_ASSERT(!s_Instance, "Application already exists!");
s_Instance = this;
m_Window = std::unique_ptr<Window>(Window::Create());
m_Window->SetEventCallback(BIND_ENVENT_FN(Application::OnEvent));
m_ImGuiLayer = new ImGuiLayer();
PushOverLay(m_ImGuiLayer);
Renderer::Init();
}
void Application::PushLayer(Layer* layer)
{
m_LayerStack.PushLayer(layer);
layer->OnAttach();
}
void Application::PushOverLay(Layer* overlay)
{
m_LayerStack.PushOverlay(overlay);
overlay->OnAttach();
}
void Application::PopLayer(Layer* layer)
{
m_LayerStack.PopLayer(layer);
}
void Application::PopOverlay(Layer* overlay)
{
}
void Application::RenderImGui()
{
m_ImGuiLayer->Begin();
for (Layer* layer : m_LayerStack)
layer->OnImGuiRender();
m_ImGuiLayer->End();
}
std::string Application::OpenFile(const std::string& filter) const
{
//OPENFILENAMEA ofn; // common dialog box structure
//CHAR szFile[260] = { 0 }; // if using TCHAR macros
//// Initialize OPENFILENAME
//ZeroMemory(&ofn, sizeof(OPENFILENAME));
//ofn.lStructSize = sizeof(OPENFILENAME);
//ofn.hwndOwner = glfwGetWin32Window((GLFWwindow*)m_Window->GetNativeWindow());
//ofn.lpstrFile = szFile;
//ofn.nMaxFile = sizeof(szFile);
//ofn.lpstrFilter = "All\0*.*\0";
//ofn.nFilterIndex = 1;
//ofn.lpstrFileTitle = NULL;
//ofn.nMaxFileTitle = 0;
//ofn.lpstrInitialDir = NULL;
//ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;
//if (GetOpenFileNameA(&ofn) == TRUE)
//{
// return ofn.lpstrFile;
//}
return std::string();
}
void Application::OnEvent(Event& e)
{
EventDispatcher dispatcher(e);
dispatcher.Dispatch<WindowCloseEvent>(BIND_ENVENT_FN(Application::OnWindowClose));
for (auto it = m_LayerStack.end(); it != m_LayerStack.begin();)
{
(*--it)->OnEvent(e);
if (e.Handled)
{
break;
}
}
}
bool Application::OnWindowClose(WindowCloseEvent& e)
{
m_Running = false;
return true;
}
bool Application::OnWindowResize(WindowResizeEvent& e)
{
return false;
}
Application::~Application()
{
}
void Application::Run()
{
while (m_Running)
{
for (Layer* layer : m_LayerStack)
{
auto [x, y] = Input::GetMousePosition();
layer->OnUpdate();
}
Application* app = this;
YS_RENDER_1(app, {
app->RenderImGui();
YS_CORE_INFO("Command Application RenderImGui");
});
Renderer::Get().WaitAndRender();
//RenderImGui();
m_Window->OnUpdate();
}
}
} | 21.051471 | 84 | 0.670975 | alalba221 |
13ce14e24404a5882b3ff8b84fe2eb34a3980e9e | 2,345 | cc | C++ | test/test_singals.cc | williammc/SignalX | 9ccb9517a3a2ec6cef114ef929847d880625ad37 | [
"BSD-3-Clause"
] | null | null | null | test/test_singals.cc | williammc/SignalX | 9ccb9517a3a2ec6cef114ef929847d880625ad37 | [
"BSD-3-Clause"
] | null | null | null | test/test_singals.cc | williammc/SignalX | 9ccb9517a3a2ec6cef114ef929847d880625ad37 | [
"BSD-3-Clause"
] | null | null | null | #include "signalx/signalx.h"
#include <memory>
#include <iostream>
#include <vector>
struct Foo {
Foo() { a = 1; }
int a;
};
/// deriving Observer for automatic disconnection management
struct Sample /*: public sigx::Observer*/ {
bool slot1(const char* e) const {
std::cout << e << std::endl;
return true;
}
bool slot2(const char* e, std::size_t n) {
std::cout << e << " [on line: " << n << "]" << std::endl;
return true;
}
static bool slot3(const char* e) {
std::cout << e << std::endl;
return true;
}
static void slot4_1(std::shared_ptr<Foo> f) {
printf("Foo:%d\n", f->a);
}
};
void slot4_2(std::shared_ptr<Foo> f) {
printf("Foo:%d\n", f->a);
}
bool slot5(const char* e, std::size_t n) {
std::cout << e << " [on line: " << n << "]" << std::endl;
return false;
}
int main() {
Sample sample;
// Declare sigx::Signals using function signature syntax
sigx::Signal<bool(const char*)> signal1;
sigx::Signal<bool(const char*, std::size_t)> signal2;
sigx::Signal<bool(const char*, std::size_t, int)> signal3;
sigx::Signal<void(std::shared_ptr<Foo>)> signal4;
// Connect member functions to sigx::Signals
signal1.connect<Sample, &Sample::slot1>(&sample);
signal2.connect<Sample, &Sample::slot2>(&sample);
// Connect a static member function
signal1.connect<Sample::slot3>();
// Connect a free function
signal2.connect<slot5>();
signal4.connect<slot4_2>();
signal4.connect<Sample::slot4_1>();
// Emit Signals
signal1("signal 1");
signal2("signal 2", __LINE__);
auto f = std::make_shared<Foo>();
signal4(f);
std::vector<bool> status;
// Emit Signals and accumulate SRVs (signal return values)
signal1("signal 1 again modified", [&](bool srv) {
status.push_back(srv);
});
// Disconnect member functions from a sigx::Signal
signal1.disconnect<Sample, &Sample::slot1>(sample);
signal2.disconnect<Sample, &Sample::slot2>(sample);
// Disconnect a static member function
signal1.disconnect<Sample::slot3>();
// Disconnect a free function
signal2.disconnect<slot5>();
signal4.disconnect<slot4_2>();
signal4.disconnect<Sample::slot4_1>();
// Emit again to test disconnects
signal1("THIS SHOULD NOT APPEAR");
signal2("THIS SHOULD NOT APPEAR", __LINE__);
signal4(f);
// std::cin.get(); // Pause the screen
} | 24.175258 | 61 | 0.649467 | williammc |
13cf2bf70a392e9658429807149aa776d4915b43 | 2,116 | cpp | C++ | tests/test_multireturn.cpp | yanwei1983/luatinkerE | 363ae33caea606205a8c4e62bfbb118503ca667b | [
"MIT"
] | 74 | 2016-03-04T17:33:50.000Z | 2022-03-28T09:57:10.000Z | tests/test_multireturn.cpp | yanwei1983/luatinkerE | 363ae33caea606205a8c4e62bfbb118503ca667b | [
"MIT"
] | 10 | 2016-04-08T16:47:59.000Z | 2022-02-16T09:40:44.000Z | tests/test_multireturn.cpp | yanwei1983/luatinkerE | 363ae33caea606205a8c4e62bfbb118503ca667b | [
"MIT"
] | 28 | 2016-04-28T07:37:44.000Z | 2022-02-14T14:25:11.000Z | #include "lua_tinker.h"
#include"test.h"
std::tuple<int, int> push_tuple()
{
return std::make_tuple(7,10);
}
bool test_tuple(std::tuple<int, int> tuple)
{
return std::get<0>(tuple) == 8 && std::get<1>(tuple) == 9;
}
LUA_TEST(multireturn)
{
g_test_func_set["test_lua_multireturn"] = [L]()->bool
{
std::string luabuf =
R"(function test_lua_multireturn()
return 1,2.0,3,4.0,"5"
end
)";
lua_tinker::dostring(L, luabuf.c_str());
int c = 0;
double d = 0.0;
char e = 0;
float f = 0.0;
std::string g;
std::tie(c, d, e, f, g) = lua_tinker::call< std::tuple<int, double, char, float, std::string> >(L, "test_lua_multireturn");
return c == 1 && d == 2.0 && e == 3 && f == 4.0 && g == "5";
};
g_test_func_set["test_lua_multireturn_err"] = [L]()->bool
{
std::string luabuf =
R"(function test_lua_multireturn_err()
error("this is my test error");
end
)";
lua_tinker::dostring(L, luabuf.c_str());
lua_tinker::set_error_callback(L, [](lua_State *L) -> int
{
std::string errinfo(lua_tostring(L, -1));
if (errinfo != "[string \"lua_tinker::dobuffer()\"]:2: this is my test error")
{
lua_tinker::on_error(L);
}
return 0;
});
int c = 0;
double d = 0.0;
char e = 0;
float f = 0.0;
std::string g;
std::tie(c, d, e, f, g) = lua_tinker::call< std::tuple<int, double, char, float, std::string> >(L, "test_lua_multireturn_err");
lua_tinker::set_error_callback(L, &lua_tinker::on_error);
return true;
};
g_test_func_set["test_push_tuple"] = [L]()->bool
{
std::string luabuf =
R"(function test_push_tuple()
local tuple_table = push_tuple();
return tuple_table[1] == 7 and tuple_table[2] == 10;
end
)";
lua_tinker::dostring(L, luabuf.c_str());
return lua_tinker::call<bool>(L, "test_push_tuple");
};
g_test_func_set["test_get_tuple"] = [L]()->bool
{
std::string luabuf =
R"(function test_get_tuple()
local tuple_table = {8, 9};
return test_tuple(tuple_table);
end
)";
lua_tinker::dostring(L, luabuf.c_str());
return lua_tinker::call<bool>(L, "test_get_tuple");
};
}
| 22.510638 | 129 | 0.614839 | yanwei1983 |
13dff8e8786fb963dbf8a2b345bd2774472c2303 | 2,868 | cpp | C++ | src/main.cpp | qistoph/BedLed | 0c239c3b848da4a79175c44b4c80b9e72a93fa29 | [
"MIT"
] | 1 | 2019-02-06T17:12:02.000Z | 2019-02-06T17:12:02.000Z | src/main.cpp | qistoph/BedLed | 0c239c3b848da4a79175c44b4c80b9e72a93fa29 | [
"MIT"
] | 1 | 2019-10-06T20:51:08.000Z | 2019-10-06T20:51:08.000Z | src/main.cpp | qistoph/BedLed | 0c239c3b848da4a79175c44b4c80b9e72a93fa29 | [
"MIT"
] | 2 | 2018-03-14T16:35:09.000Z | 2019-10-06T20:05:41.000Z | // NOTE!!!
// Uses:
// ATTinyCore (https://github.com/SpenceKonde/ATTinyCore)
// TinyDebugSerial (https://github.com/qistoph/TinyDebugSerial) + modified to use PB2 on F_CPU<=8MHz
// Fuse/Core config:
// Timer 1 Clock: 64MHz
// Clock: 8MHz internal
// E:FF H:D7 L:E2
//TODO:
// Check datasheet page 99 for required frequency
#include <Arduino.h>
#include "settings.h"
#include "buttons.h"
#include "lightcontrol.h"
#include "touchcontrol.h"
#include "sleep.h"
#ifndef SIGRD // used in boot.h by boot_signature_byte_get_short(addr)
#define SIGRD RSIG
#endif
TinyDebugSerial TDSerial;
bool deepSleepEnabled = true;
void setup() {
// put your setup code here, to run once:
OSCCAL = 0x58;
MySerial.begin(9600);
Serial.println(F("Running setup"));
buttonsSetup();
lightSetup();
// Setup interrupts
*digitalPinToPCICR(BTN1_PIN) |= _BV(digitalPinToPCICRbit(BTN1_PIN)); // Enable PIN interrupts in general and btn1 pin
*digitalPinToPCICR(BTN2_PIN) |= _BV(digitalPinToPCICRbit(BTN2_PIN)); //TODO: remove? (because same register in ATTiny)
*digitalPinToPCMSK(BTN1_PIN) |= _BV(digitalPinToPCMSKbit(BTN1_PIN)); // Enable interrupt on button 1
*digitalPinToPCMSK(BTN2_PIN) |= _BV(digitalPinToPCMSKbit(BTN2_PIN)); // Enable interrupt on button 2
MySerial.println(F("Blink LED"));
lightOn();
delay(500);
lightOff();
}
uint8_t wasTouching = false;
unsigned long loopStart = 0;
unsigned long sleepAt = 0;
unsigned long eeStart = 0;
bool startEe = false;
extern bool lightIsOn;
// Interrupt handler, called for button and RF interrupts
ISR(PCINT0_vect) {
}
void loop() {
loopStart = millis();
uint8_t stableTouch = buttonsReadTouch();
if(stableTouch != wasTouching) {
//Serial.print("stableTouch: ");
//Serial.println(stableTouch);
// state change
if(stableTouch && !wasTouching) {
// Release -> Touch
MySerial.println(F("Touch"));
onTouch();
} else if(!stableTouch && wasTouching) {
// Touch -> Release
MySerial.println(F("Release"));
onTouchRelease();
}
wasTouching = stableTouch;
} else if(stableTouch) {
// Still touching
onTouching();
}
if(stableTouch == 3) {
if(eeStart == 0) {
eeStart = millis() + 2000;
startEe = true;
} else if(millis() > eeStart && startEe) {
MySerial.println(F("EASTER EGG MODE!"));
easterEgg();
startEe = false;
}
} else {
eeStart = 0;
}
touchLoop();
// Serial.print(F("lightIsOn: "));
// Serial.println(lightIsOn);
// Serial.print(F("stableTouch: "));
// Serial.println(stableTouch);
// Serial.print(F("deepSleepEnabled: "));
// Serial.println(deepSleepEnabled);
if(!lightIsOn && !stableTouch && millis() > sleepAt && deepSleepEnabled) {
deepSleep();
sleepAt = millis() + 100; // Allow at least 100ms to detect button presses before sleeping again
}
}
| 25.157895 | 120 | 0.671548 | qistoph |
13e1f1519e375f4a7e546d33eddd4946ba567878 | 6,941 | cpp | C++ | src/mongo/db/repl/oplogreader.cpp | baiyanghese/mongo | 89fcbab94c7103105e8c72f654a5774a066bdb90 | [
"Apache-2.0"
] | 1 | 2015-11-06T05:42:37.000Z | 2015-11-06T05:42:37.000Z | src/mongo/db/repl/oplogreader.cpp | baiyanghese/mongo | 89fcbab94c7103105e8c72f654a5774a066bdb90 | [
"Apache-2.0"
] | null | null | null | src/mongo/db/repl/oplogreader.cpp | baiyanghese/mongo | 89fcbab94c7103105e8c72f654a5774a066bdb90 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright (C) 2012 10gen Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the GNU Affero General Public License in all respects for
* all of the code used other than as permitted herein. If you modify file(s)
* with this exception, you may extend this exception to your version of the
* file(s), but you are not obligated to do so. If you do not wish to do so,
* delete this exception statement from your version. If you delete this
* exception statement from all source files in the program, then also delete
* it in the license file.
*/
#include "mongo/db/repl/oplogreader.h"
#include <boost/shared_ptr.hpp>
#include <string>
#include "mongo/base/counter.h"
#include "mongo/client/dbclientinterface.h"
#include "mongo/db/auth/authorization_manager.h"
#include "mongo/db/auth/authorization_manager_global.h"
#include "mongo/db/auth/authorization_session.h"
#include "mongo/db/commands/server_status_metric.h"
#include "mongo/db/auth/security_key.h"
#include "mongo/db/dbhelpers.h"
#include "mongo/db/jsobj.h"
#include "mongo/db/repl/rs.h" // theReplSet
#include "mongo/util/assert_util.h"
#include "mongo/util/log.h"
namespace mongo {
namespace repl {
//number of readers created;
// this happens when the source source changes, a reconfig/network-error or the cursor dies
static Counter64 readersCreatedStats;
static ServerStatusMetricField<Counter64> displayReadersCreated(
"repl.network.readersCreated",
&readersCreatedStats );
static const BSONObj userReplQuery = fromjson("{\"user\":\"repl\"}");
bool replAuthenticate(DBClientBase *conn) {
if (!getGlobalAuthorizationManager()->isAuthEnabled())
return true;
if (!isInternalAuthSet())
return false;
return authenticateInternalUser(conn);
}
bool replHandshake(DBClientConnection *conn, const BSONObj& me) {
string myname = getHostName();
BSONObjBuilder cmd;
cmd.appendAs( me["_id"] , "handshake" );
if (theReplSet) {
cmd.append("member", theReplSet->selfId());
cmd.append("config", theReplSet->myConfig().asBson());
}
BSONObj res;
bool ok = conn->runCommand( "admin" , cmd.obj() , res );
// ignoring for now on purpose for older versions
LOG( ok ? 1 : 0 ) << "replHandshake res not: " << ok << " res: " << res << endl;
return true;
}
OplogReader::OplogReader() {
_tailingQueryOptions = QueryOption_SlaveOk;
_tailingQueryOptions |= QueryOption_CursorTailable | QueryOption_OplogReplay;
/* TODO: slaveOk maybe shouldn't use? */
_tailingQueryOptions |= QueryOption_AwaitData;
readersCreatedStats.increment();
}
bool OplogReader::commonConnect(const string& hostName) {
if( conn() == 0 ) {
_conn = shared_ptr<DBClientConnection>(new DBClientConnection(false,
0,
tcp_timeout));
string errmsg;
if ( !_conn->connect(hostName.c_str(), errmsg) ||
(getGlobalAuthorizationManager()->isAuthEnabled() &&
!replAuthenticate(_conn.get())) ) {
resetConnection();
log() << "repl: " << errmsg << endl;
return false;
}
}
return true;
}
bool OplogReader::connect(const std::string& hostName) {
if (conn()) {
return true;
}
if (!commonConnect(hostName)) {
return false;
}
return true;
}
bool OplogReader::connect(const std::string& hostName, const BSONObj& me) {
if (conn()) {
return true;
}
if (!commonConnect(hostName)) {
return false;
}
if (!replHandshake(_conn.get(), me)) {
return false;
}
return true;
}
bool OplogReader::connect(const mongo::OID& rid, const int from, const string& to) {
if (conn() != 0) {
return true;
}
if (commonConnect(to)) {
log() << "handshake between " << from << " and " << to << endl;
return passthroughHandshake(rid, from);
}
return false;
}
bool OplogReader::passthroughHandshake(const mongo::OID& rid, const int nextOnChainId) {
BSONObjBuilder cmd;
cmd.append("handshake", rid);
if (theReplSet) {
const Member* chainedMember = theReplSet->findById(nextOnChainId);
if (chainedMember != NULL) {
cmd.append("config", chainedMember->config().asBson());
}
}
cmd.append("member", nextOnChainId);
BSONObj res;
return conn()->runCommand("admin", cmd.obj(), res);
}
void OplogReader::query(const char *ns,
Query query,
int nToReturn,
int nToSkip,
const BSONObj* fields) {
cursor.reset(
_conn->query(ns, query, nToReturn, nToSkip, fields, QueryOption_SlaveOk).release()
);
}
void OplogReader::tailingQuery(const char *ns, const BSONObj& query, const BSONObj* fields ) {
verify( !haveCursor() );
LOG(2) << "repl: " << ns << ".find(" << query.toString() << ')' << endl;
cursor.reset( _conn->query( ns, query, 0, 0, fields, _tailingQueryOptions ).release() );
}
void OplogReader::tailingQueryGTE(const char *ns, OpTime optime, const BSONObj* fields ) {
BSONObjBuilder gte;
gte.appendTimestamp("$gte", optime.asDate());
BSONObjBuilder query;
query.append("ts", gte.done());
tailingQuery(ns, query.done(), fields);
}
} // namespace repl
} // namespace mongo
| 35.778351 | 98 | 0.597032 | baiyanghese |
13e2d8b4578587b543320a8f5ece996eebd38f8f | 15,089 | cpp | C++ | render-lib/Renderer/Renderers/Vulkan/Backend/CommandListHandlerVK.cpp | firesgc/NovusCore-Client | 406010cfeca88b82363debe7dd9ca8d5e839b7f4 | [
"MIT"
] | null | null | null | render-lib/Renderer/Renderers/Vulkan/Backend/CommandListHandlerVK.cpp | firesgc/NovusCore-Client | 406010cfeca88b82363debe7dd9ca8d5e839b7f4 | [
"MIT"
] | null | null | null | render-lib/Renderer/Renderers/Vulkan/Backend/CommandListHandlerVK.cpp | firesgc/NovusCore-Client | 406010cfeca88b82363debe7dd9ca8d5e839b7f4 | [
"MIT"
] | null | null | null | #include "CommandListHandlerVK.h"
#include "RenderDeviceVK.h"
#include <queue>
#include <vector>
#include <cassert>
#include <vulkan/vulkan.h>
#include <Utils/DebugHandler.h>
#include <tracy/TracyVulkan.hpp>
#include <tracy/Tracy.hpp>
namespace Renderer
{
namespace Backend
{
struct CommandList
{
std::vector<VkSemaphore> waitSemaphores;
std::vector<VkSemaphore> signalSemaphores;
VkCommandBuffer commandBuffer;
VkCommandPool commandPool;
tracy::VkCtxManualScope* tracyScope = nullptr;
GraphicsPipelineID boundGraphicsPipeline = GraphicsPipelineID::Invalid();
ComputePipelineID boundComputePipeline = ComputePipelineID::Invalid();
i8 renderPassOpenCount = 0;
QueueType queueType = QueueType::Graphics;
};
struct CommandListFamily
{
std::queue<CommandListID> availableCommandLists;
FrameResource<std::queue<CommandListID>, 2> closedCommandLists;
};
struct CommandListHandlerVKData : ICommandListHandlerVKData
{
std::vector<CommandList> commandLists;
std::array<CommandListFamily, QueueType::COUNT> commandListFamilies;
u8 frameIndex = 0;
FrameResource<VkFence, 2> frameFences;
};
void CommandListHandlerVK::Init(RenderDeviceVK* device)
{
_device = device;
CommandListHandlerVKData* data = new CommandListHandlerVKData();
_data = data;
VkFenceCreateInfo fenceInfo = {};
fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
fenceInfo.flags = VK_FENCE_CREATE_SIGNALED_BIT;
for (u32 i = 0; i < data->frameFences.Num; i++)
{
vkCreateFence(_device->_device, &fenceInfo, nullptr, &data->frameFences.Get(i));
}
}
void CommandListHandlerVK::FlipFrame()
{
CommandListHandlerVKData& data = static_cast<CommandListHandlerVKData&>(*_data);
data.frameIndex++;
if (data.frameIndex >= data.commandListFamilies[0].closedCommandLists.Num)
{
data.frameIndex = 0;
}
}
void CommandListHandlerVK::ResetCommandBuffers()
{
CommandListHandlerVKData& data = static_cast<CommandListHandlerVKData&>(*_data);
for (u32 i = 0; i < data.commandListFamilies.size(); i++)
{
std::queue<CommandListID>& closedCommandLists = data.commandListFamilies[i].closedCommandLists.Get(data.frameIndex);
while (!closedCommandLists.empty())
{
CommandListID commandListID = closedCommandLists.front();
closedCommandLists.pop();
CommandList& commandList = data.commandLists[static_cast<CommandListID::type>(commandListID)];
// Reset commandlist
vkResetCommandPool(_device->_device, commandList.commandPool, 0);
// Push the commandlist into availableCommandLists
data.commandListFamilies[i].availableCommandLists.push(commandListID);
}
}
}
CommandListID CommandListHandlerVK::BeginCommandList(QueueType queueType)
{
CommandListHandlerVKData& data = static_cast<CommandListHandlerVKData&>(*_data);
u32 queueTypeIndex = static_cast<u32>(queueType);
CommandListID id;
if (!data.commandListFamilies[queueTypeIndex].availableCommandLists.empty())
{
id = data.commandListFamilies[queueTypeIndex].availableCommandLists.front();
data.commandListFamilies[queueTypeIndex].availableCommandLists.pop();
CommandList& commandList = data.commandLists[static_cast<CommandListID::type>(id)];
VkCommandBufferBeginInfo beginInfo = {};
beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
beginInfo.flags = 0; // Optional
beginInfo.pInheritanceInfo = nullptr; // Optional
if (vkBeginCommandBuffer(commandList.commandBuffer, &beginInfo) != VK_SUCCESS)
{
DebugHandler::PrintFatal("Failed to begin recording command buffer!");
}
}
else
{
return CreateCommandList(queueType);
}
return id;
}
void CommandListHandlerVK::EndCommandList(CommandListID id, VkFence fence)
{
ZoneScopedC(tracy::Color::Red3);
CommandListHandlerVKData& data = static_cast<CommandListHandlerVKData&>(*_data);
CommandList& commandList = data.commandLists[static_cast<CommandListID::type>(id)];
{
ZoneScopedNC("Submit", tracy::Color::Red3);
VkQueue queue = nullptr;
switch (commandList.queueType)
{
case QueueType::Graphics:
queue = _device->_graphicsQueue;
break;
case QueueType::Transfer:
queue = _device->_transferQueue;
break;
default:
DebugHandler::PrintFatal("Tried to EndCommandList with unknown QueueType, did we add a QueueType without updating this function?");
break;
}
// Validate command list
if (commandList.renderPassOpenCount != 0)
{
DebugHandler::PrintFatal("We found unmatched calls to BeginPipeline in your commandlist, for every BeginPipeline you need to also EndPipeline!");
}
// Close command list
if (vkEndCommandBuffer(commandList.commandBuffer) != VK_SUCCESS)
{
DebugHandler::PrintFatal("Failed to record command buffer!");
}
// Execute command list
VkSubmitInfo submitInfo = {};
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &commandList.commandBuffer;
u32 numWaitSemaphores = static_cast<u32>(commandList.waitSemaphores.size());
std::vector<VkPipelineStageFlags> dstStageMasks(numWaitSemaphores);
for (VkPipelineStageFlags& dstStageMask : dstStageMasks)
{
dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
}
submitInfo.waitSemaphoreCount = numWaitSemaphores;
submitInfo.pWaitSemaphores = commandList.waitSemaphores.data();
submitInfo.pWaitDstStageMask = dstStageMasks.data();
submitInfo.signalSemaphoreCount = static_cast<u32>(commandList.signalSemaphores.size());
submitInfo.pSignalSemaphores = commandList.signalSemaphores.data();
vkQueueSubmit(queue, 1, &submitInfo, fence);
}
commandList.waitSemaphores.clear();
commandList.signalSemaphores.clear();
commandList.boundGraphicsPipeline = GraphicsPipelineID::Invalid();
u32 queueTypeIndex = static_cast<u32>(commandList.queueType);
data.commandListFamilies[queueTypeIndex].closedCommandLists.Get(data.frameIndex).push(id);
}
VkCommandBuffer CommandListHandlerVK::GetCommandBuffer(CommandListID id)
{
CommandListHandlerVKData& data = static_cast<CommandListHandlerVKData&>(*_data);
// Lets make sure this id exists
assert(data.commandLists.size() > static_cast<CommandListID::type>(id));
CommandList& commandList = data.commandLists[static_cast<CommandListID::type>(id)];
return commandList.commandBuffer;
}
void CommandListHandlerVK::AddWaitSemaphore(CommandListID id, VkSemaphore semaphore)
{
CommandListHandlerVKData& data = static_cast<CommandListHandlerVKData&>(*_data);
// Lets make sure this id exists
assert(data.commandLists.size() > static_cast<CommandListID::type>(id));
CommandList& commandList = data.commandLists[static_cast<CommandListID::type>(id)];
commandList.waitSemaphores.push_back(semaphore);
}
void CommandListHandlerVK::AddSignalSemaphore(CommandListID id, VkSemaphore semaphore)
{
CommandListHandlerVKData& data = static_cast<CommandListHandlerVKData&>(*_data);
// Lets make sure this id exists
assert(data.commandLists.size() > static_cast<CommandListID::type>(id));
CommandList& commandList = data.commandLists[static_cast<CommandListID::type>(id)];
commandList.signalSemaphores.push_back(semaphore);
}
void CommandListHandlerVK::SetBoundGraphicsPipeline(CommandListID id, GraphicsPipelineID pipelineID)
{
CommandListHandlerVKData& data = static_cast<CommandListHandlerVKData&>(*_data);
// Lets make sure this id exists
assert(data.commandLists.size() > static_cast<CommandListID::type>(id));
CommandList& commandList = data.commandLists[static_cast<CommandListID::type>(id)];
commandList.boundGraphicsPipeline = pipelineID;
}
void CommandListHandlerVK::SetBoundComputePipeline(CommandListID id, ComputePipelineID pipelineID)
{
CommandListHandlerVKData& data = static_cast<CommandListHandlerVKData&>(*_data);
// Lets make sure this id exists
assert(data.commandLists.size() > static_cast<CommandListID::type>(id));
CommandList& commandList = data.commandLists[static_cast<CommandListID::type>(id)];
commandList.boundComputePipeline = pipelineID;
}
GraphicsPipelineID CommandListHandlerVK::GetBoundGraphicsPipeline(CommandListID id)
{
CommandListHandlerVKData& data = static_cast<CommandListHandlerVKData&>(*_data);
// Lets make sure this id exists
assert(data.commandLists.size() > static_cast<CommandListID::type>(id));
return data.commandLists[static_cast<CommandListID::type>(id)].boundGraphicsPipeline;
}
ComputePipelineID CommandListHandlerVK::GetBoundComputePipeline(CommandListID id)
{
CommandListHandlerVKData& data = static_cast<CommandListHandlerVKData&>(*_data);
// Lets make sure this id exists
assert(data.commandLists.size() > static_cast<CommandListID::type>(id));
return data.commandLists[static_cast<CommandListID::type>(id)].boundComputePipeline;
}
i8 CommandListHandlerVK::GetRenderPassOpenCount(CommandListID id)
{
CommandListHandlerVKData& data = static_cast<CommandListHandlerVKData&>(*_data);
CommandList& commandList = data.commandLists[static_cast<CommandListID::type>(id)];
return commandList.renderPassOpenCount;
}
void CommandListHandlerVK::SetRenderPassOpenCount(CommandListID id, i8 count)
{
CommandListHandlerVKData& data = static_cast<CommandListHandlerVKData&>(*_data);
CommandList& commandList = data.commandLists[static_cast<CommandListID::type>(id)];
commandList.renderPassOpenCount = count;
}
tracy::VkCtxManualScope*& CommandListHandlerVK::GetTracyScope(CommandListID id)
{
CommandListHandlerVKData& data = static_cast<CommandListHandlerVKData&>(*_data);
// Lets make sure this id exists
assert(data.commandLists.size() > static_cast<CommandListID::type>(id));
return data.commandLists[static_cast<CommandListID::type>(id)].tracyScope;
}
VkFence CommandListHandlerVK::GetCurrentFence()
{
CommandListHandlerVKData& data = static_cast<CommandListHandlerVKData&>(*_data);
return data.frameFences.Get(data.frameIndex);
}
CommandListID CommandListHandlerVK::CreateCommandList(QueueType queueType)
{
CommandListHandlerVKData& data = static_cast<CommandListHandlerVKData&>(*_data);
size_t id = data.commandLists.size();
assert(id < CommandListID::MaxValue());
CommandList commandList;
commandList.queueType = queueType;
// Create commandpool
QueueFamilyIndices queueFamilyIndices = _device->FindQueueFamilies(_device->_physicalDevice);
u32 queueFamilyIndex = 0;
switch (queueType)
{
case QueueType::Graphics:
queueFamilyIndex = queueFamilyIndices.graphicsFamily.value();
break;
case QueueType::Transfer:
queueFamilyIndex = queueFamilyIndices.transferFamily.value();
break;
default:
DebugHandler::PrintFatal("Tried to create a CommandList with an unknown QueueType, did we add a QueueType without updating this function?");
break;
}
VkCommandPoolCreateInfo poolInfo = {};
poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
poolInfo.queueFamilyIndex = queueFamilyIndices.graphicsFamily.value();
poolInfo.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
if (vkCreateCommandPool(_device->_device, &poolInfo, nullptr, &commandList.commandPool) != VK_SUCCESS)
{
DebugHandler::PrintFatal("Failed to create command pool!");
}
// Create commandlist
VkCommandBufferAllocateInfo allocInfo = {};
allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
allocInfo.commandPool = commandList.commandPool;
allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
allocInfo.commandBufferCount = 1;
if (vkAllocateCommandBuffers(_device->_device, &allocInfo, &commandList.commandBuffer) != VK_SUCCESS)
{
DebugHandler::PrintFatal("Failed to allocate command buffers!");
}
// Open commandlist
VkCommandBufferBeginInfo beginInfo = {};
beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
beginInfo.flags = 0; // Optional
beginInfo.pInheritanceInfo = nullptr; // Optional
if (vkBeginCommandBuffer(commandList.commandBuffer, &beginInfo) != VK_SUCCESS)
{
DebugHandler::PrintFatal("Failed to begin recording command buffer!");
}
data.commandLists.push_back(commandList);
return CommandListID(static_cast<CommandListID::type>(id));
}
}
} | 39.5 | 165 | 0.625621 | firesgc |
13e5ded67832c599f05dc08ab274e6c4edf952e7 | 2,303 | cpp | C++ | tc 160+/LuckyCounter.cpp | ibudiselic/contest-problem-solutions | 88082981b4d87da843472e3ca9ed5f4c42b3f0aa | [
"BSD-2-Clause"
] | 3 | 2015-05-25T06:24:37.000Z | 2016-09-10T07:58:00.000Z | tc 160+/LuckyCounter.cpp | ibudiselic/contest-problem-solutions | 88082981b4d87da843472e3ca9ed5f4c42b3f0aa | [
"BSD-2-Clause"
] | null | null | null | tc 160+/LuckyCounter.cpp | ibudiselic/contest-problem-solutions | 88082981b4d87da843472e3ca9ed5f4c42b3f0aa | [
"BSD-2-Clause"
] | 5 | 2015-05-25T06:24:40.000Z | 2021-08-19T19:22:29.000Z | #include <algorithm>
#include <cassert>
#include <cstdio>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <cstring>
using namespace std;
class LuckyCounter {
public:
int countLuckyMoments(vector <string> moments) {
int sol = 0;
for (int i=0; i<(int)moments.size(); ++i) {
const string &s = moments[i];
sol += (s[0]==s[3] && s[1]==s[4]) || (s[0]==s[1] && s[3]==s[4]) || (s[0]==s[4] && s[1]==s[3]);
}
return sol;
}
// BEGIN CUT HERE
public:
void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); }
private:
template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); }
void verify_case(int Case, const int &Expected, const int &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } }
void test_case_0() { string Arr0[] = {"12:21", "11:10"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 1; verify_case(0, Arg1, countLuckyMoments(Arg0)); }
void test_case_1() { string Arr0[] = {"00:00", "00:59", "23:00"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 1; verify_case(1, Arg1, countLuckyMoments(Arg0)); }
void test_case_2() { string Arr0[] = {"12:34"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 0; verify_case(2, Arg1, countLuckyMoments(Arg0)); }
void test_case_3() { string Arr0[] = {"12:11", "22:22", "00:01", "03:30", "15:15", "16:00"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 3; verify_case(3, Arg1, countLuckyMoments(Arg0)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main()
{
LuckyCounter ___test;
___test.run_test(-1);
}
// END CUT HERE
| 44.288462 | 309 | 0.565784 | ibudiselic |
13e83c5d77f4c208fe58e3b8265e2a1da7dc1b50 | 5,227 | cpp | C++ | tests/test_packet.cpp | clickp4/bmv2 | aca47e23c968353a9ffd27e9b6305f41cefadf6b | [
"Apache-2.0"
] | 2 | 2018-08-29T22:58:07.000Z | 2018-08-30T01:44:30.000Z | tests/test_packet.cpp | clickp4/bmv2 | aca47e23c968353a9ffd27e9b6305f41cefadf6b | [
"Apache-2.0"
] | null | null | null | tests/test_packet.cpp | clickp4/bmv2 | aca47e23c968353a9ffd27e9b6305f41cefadf6b | [
"Apache-2.0"
] | 4 | 2016-06-22T23:39:02.000Z | 2022-03-26T13:53:51.000Z | /* Copyright 2013-present Barefoot Networks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Antonin Bas (antonin@barefootnetworks.com)
*
*/
#include <gtest/gtest.h>
#include <vector>
#include <bm/bm_sim/packet.h>
using namespace bm;
TEST(CopyIdGenerator, Test) {
CopyIdGenerator gen;
packet_id_t packet_id = 0;
ASSERT_EQ(0u, gen.get(packet_id));
ASSERT_EQ(1u, gen.add_one(packet_id));
ASSERT_EQ(1u, gen.get(packet_id));
ASSERT_EQ(2u, gen.add_one(packet_id));
gen.remove_one(packet_id);
ASSERT_EQ(1u, gen.get(packet_id));
gen.reset(packet_id);
ASSERT_EQ(0u, gen.get(packet_id));
}
class PHVSourceTest : public PHVSourceIface {
public:
explicit PHVSourceTest(size_t size)
: phv_factories(size, nullptr), created(size, 0u), destroyed(size, 0u) { }
size_t get_created(size_t cxt) {
return created.at(cxt);
}
size_t get_destroyed(size_t cxt) {
return destroyed.at(cxt);
}
private:
std::unique_ptr<PHV> get_(size_t cxt) override {
assert(phv_factories[cxt]);
++count;
++created.at(cxt);
return phv_factories[cxt]->create();
}
void release_(size_t cxt, std::unique_ptr<PHV> phv) override {
// let the PHV be destroyed
(void) cxt; (void) phv;
--count;
++destroyed.at(cxt);
}
void set_phv_factory_(size_t cxt, const PHVFactory *factory) override {
phv_factories.at(cxt) = factory;
}
size_t phvs_in_use_(size_t cxt) override {
return count;
}
std::vector<const PHVFactory *> phv_factories;
size_t count{0};
std::vector<size_t> created;
std::vector<size_t> destroyed;
};
// Google Test fixture for Packet tests
class PacketTest : public ::testing::Test {
protected:
PHVFactory phv_factory;
std::unique_ptr<PHVSourceTest> phv_source{nullptr};
PacketTest()
: phv_source(new PHVSourceTest(2)) { }
virtual void SetUp() {
phv_source->set_phv_factory(0, &phv_factory);
phv_source->set_phv_factory(1, &phv_factory);
}
// virtual void TearDown() { }
Packet get_packet(size_t cxt, packet_id_t id = 0) {
// dummy packet, never parsed
return Packet::make_new(cxt, 0, id, 0, 0, PacketBuffer(), phv_source.get());
}
};
TEST_F(PacketTest, Packet) {
const size_t first_cxt = 0;
const size_t other_cxt = 1;
ASSERT_EQ(0u, phv_source->get_created(first_cxt));
ASSERT_EQ(0u, phv_source->get_created(other_cxt));
auto packet = get_packet(first_cxt);
ASSERT_EQ(1u, phv_source->get_created(first_cxt));
ASSERT_EQ(0u, phv_source->get_created(other_cxt));
}
TEST_F(PacketTest, ChangeContext) {
const size_t first_cxt = 0;
const size_t other_cxt = 1;
auto packet = get_packet(first_cxt);
ASSERT_EQ(1u, phv_source->get_created(first_cxt));
ASSERT_EQ(0u, phv_source->get_created(other_cxt));
packet.change_context(other_cxt);
ASSERT_EQ(1u, phv_source->get_created(first_cxt));
ASSERT_EQ(1u, phv_source->get_destroyed(first_cxt));
ASSERT_EQ(1u, phv_source->get_created(other_cxt));
ASSERT_EQ(0u, phv_source->get_destroyed(other_cxt));
}
TEST_F(PacketTest, Truncate) {
const size_t cxt = 0;
const size_t first_length = 128;
std::vector<char> data;
data.reserve(first_length);
for (size_t i = 0; i < first_length; i++) {
data.push_back(static_cast<char>(i));
}
Packet pkt_1 = Packet::make_new(
cxt, 0, 0, 0, 0,
PacketBuffer(first_length, data.data(), first_length),
phv_source.get());
const size_t truncated_length_small = 47;
ASSERT_LT(truncated_length_small, first_length);
pkt_1.truncate(truncated_length_small);
ASSERT_EQ(truncated_length_small, pkt_1.get_data_size());
ASSERT_TRUE(std::equal(
data.begin(), data.begin() + pkt_1.get_data_size(), pkt_1.data()));
Packet pkt_2 = Packet::make_new(
cxt, 0, 0, 0, 0,
PacketBuffer(first_length, data.data(), first_length),
phv_source.get());
const size_t truncated_length_big = 200;
ASSERT_GT(truncated_length_big, first_length);
pkt_2.truncate(truncated_length_big);
ASSERT_EQ(first_length, pkt_2.get_data_size());
ASSERT_TRUE(std::equal(
data.begin(), data.begin() + pkt_2.get_data_size(), pkt_2.data()));
}
TEST_F(PacketTest, PacketRegisters) {
const uint64_t v1 = 0u;
const uint64_t v2 = 6789u;
const size_t idx = 0u;
ASSERT_LT(idx, Packet::nb_registers);
auto packet = get_packet(0);
packet.set_register(idx, v1);
ASSERT_EQ(v1, packet.get_register(idx));
packet.set_register(idx, v2);
ASSERT_EQ(v2, packet.get_register(idx));
}
TEST_F(PacketTest, Exit) {
auto packet = get_packet(0);
ASSERT_FALSE(packet.is_marked_for_exit());
packet.mark_for_exit();
ASSERT_TRUE(packet.is_marked_for_exit());
packet.reset_exit();
ASSERT_FALSE(packet.is_marked_for_exit());
}
| 28.407609 | 80 | 0.710733 | clickp4 |
13e8f63b268076ea015fffc4d56766ab7e2bb026 | 7,339 | cpp | C++ | chrono/chrono-dev/src/demos/sensor/demo_SEN_vis_materials.cpp | ShuoHe97/CS239-Final-Project | 6558db26d00abb0eb2f6c82b9b6025386ecf19b9 | [
"BSD-3-Clause"
] | 1 | 2020-12-18T08:28:52.000Z | 2020-12-18T08:28:52.000Z | chrono/chrono-dev/src/demos/sensor/demo_SEN_vis_materials.cpp | ShuoHe97/CS239-Final-Project | 6558db26d00abb0eb2f6c82b9b6025386ecf19b9 | [
"BSD-3-Clause"
] | null | null | null | chrono/chrono-dev/src/demos/sensor/demo_SEN_vis_materials.cpp | ShuoHe97/CS239-Final-Project | 6558db26d00abb0eb2f6c82b9b6025386ecf19b9 | [
"BSD-3-Clause"
] | null | null | null | // =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2019 projectchrono.org
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Asher Elmquist
// =============================================================================
//
// Chrono demonstration of a camera sensor
//
//
// =============================================================================
#include <cmath>
#include <cstdio>
#include <iomanip>
#include "chrono/assets/ChTriangleMeshShape.h"
#include "chrono/assets/ChVisualMaterial.h"
#include "chrono/assets/ChVisualization.h"
#include "chrono/geometry/ChTriangleMeshConnected.h"
#include "chrono/physics/ChBodyEasy.h"
#include "chrono/physics/ChSystemNSC.h"
#include "chrono/utils/ChUtilsCreators.h"
#include "chrono_thirdparty/filesystem/path.h"
#include "chrono_sensor/ChCameraSensor.h"
#include "chrono_sensor/ChSensorManager.h"
#include "chrono_sensor/filters/ChFilterAccess.h"
#include "chrono_sensor/filters/ChFilterGrayscale.h"
#include "chrono_sensor/filters/ChFilterSave.h"
#include "chrono_sensor/filters/ChFilterVisualize.h"
using namespace chrono;
using namespace chrono::geometry;
using namespace chrono::sensor;
float end_time = 100.0f;
int main(int argc, char* argv[]) {
GetLog() << "Copyright (c) 2019 projectchrono.org\nChrono version: " << CHRONO_VERSION << "\n\n";
// -----------------
// Create the system
// -----------------
ChSystemNSC mphysicalSystem;
int x_dim = 11;
int y_dim = 7;
for (int i = 0; i < x_dim; i++) {
for (int j = 0; j < y_dim; j++) {
auto sphere1 = std::make_shared<ChBodyEasySphere>(.4, 1000, false, true);
sphere1->SetPos({0, i - (x_dim / 2.), j - (y_dim / 2.)});
sphere1->SetBodyFixed(true);
auto sphere_asset1 = sphere1->GetAssets()[0];
if (std::shared_ptr<ChVisualization> visual_asset =
std::dynamic_pointer_cast<ChVisualization>(sphere_asset1)) {
auto color = std::make_shared<ChVisualMaterial>();
color->SetDiffuseColor({.9, .2, .2});
color->SetSpecularColor({1, 1, 1});
color->SetFresnelExp(j);
color->SetFresnelMin(2. * i / y_dim - 1);
color->SetFresnelMax(2. * i / y_dim);
visual_asset->material_list.push_back(color);
}
mphysicalSystem.Add(sphere1);
}
}
// auto sphere1 = std::make_shared<ChBodyEasySphere>(.75, 1000, false, true);
// sphere1->SetPos({0, -2, 0});
// sphere1->SetBodyFixed(true);
// auto sphere_asset1 = sphere1->GetAssets()[0];
// if (std::shared_ptr<ChVisualization> visual_asset = std::dynamic_pointer_cast<ChVisualization>(sphere_asset1)) {
// auto color = std::make_shared<ChVisualMaterial>();
// color->SetDiffuseColor({1, 0, 0});
// color->SetSpecularColor({.8, 0, 0});
// color->SetFresnelExp(1.);
// color->SetFresnelMin(.8);
// color->SetFresnelMax(1.);
// visual_asset->material_list.push_back(color);
// }
// mphysicalSystem.Add(sphere1);
auto sphere2 = std::make_shared<ChBodyEasySphere>(.001, 1000, false, true);
sphere2->SetPos({0, 0, 0});
sphere2->SetBodyFixed(true);
auto sphere_asset2 = sphere2->GetAssets()[0];
if (std::shared_ptr<ChVisualization> visual_asset = std::dynamic_pointer_cast<ChVisualization>(sphere_asset2)) {
auto color = std::make_shared<ChVisualMaterial>();
color->SetDiffuseColor({.5, .2, .2});
color->SetSpecularColor({1, 1, 1});
color->SetFresnelExp(5);
color->SetFresnelMin(0);
color->SetFresnelMax(1);
visual_asset->material_list.push_back(color);
}
mphysicalSystem.Add(sphere2);
// auto sphere3 = std::make_shared<ChBodyEasySphere>(.75, 1000, false, true);
// sphere3->SetPos({0, 2, 0});
// sphere3->SetBodyFixed(true);
// auto sphere_asset3 = sphere3->GetAssets()[0];
// if (std::shared_ptr<ChVisualization> visual_asset = std::dynamic_pointer_cast<ChVisualization>(sphere_asset3)) {
// auto color = std::make_shared<ChVisualMaterial>();
// color->SetDiffuseColor({1, 0, 0});
// color->SetSpecularColor({.2, .0, .0});
// color->SetFresnelExp(10.);
// color->SetFresnelMin(0);
// color->SetFresnelMax(.2);
// visual_asset->material_list.push_back(color);
// }
// mphysicalSystem.Add(sphere3);
// -----------------------
// Create a sensor manager
// -----------------------
auto manager = std::make_shared<ChSensorManager>(&mphysicalSystem);
manager->scene->AddPointLight({-100, 0, 100}, {1, 1, 1}, 500);
manager->scene->GetBackground().has_texture = true;
manager->scene->GetBackground().env_tex = "sensor/textures/cloud_layers_8k.hdr";
manager->scene->GetBackground().has_changed = true;
// ------------------------------------------------
// Create a camera and add it to the sensor manager
// ------------------------------------------------
auto cam = std::make_shared<ChCameraSensor>(
sphere2, // body camera is attached to
30, // update rate in Hz
chrono::ChFrame<double>({-12, 0, 0}, Q_from_AngAxis(0, {0, 1, 0})), // offset pose
1920, // image width
1080, // image height
CH_C_PI / 3, 9. / 16. * CH_C_PI / 3); // FOV
cam->SetName("Camera Sensor");
// --------------------------------------------------------------------
// Create a filter graph for post-processing the images from the camera
// --------------------------------------------------------------------
// we want to visualize this sensor right after rendering, so add the visualize filter to the filter list.
cam->FilterList().push_back(std::make_shared<ChFilterVisualize>("For user display"));
// add sensor to the manager
manager->AddSensor(cam);
// ---------------
// Simulate system
// ---------------
float orbit_radius = 10.f;
float orbit_rate = 0.5;
float ch_time = 0.0;
double render_time = 0;
std::chrono::high_resolution_clock::time_point t1 = std::chrono::high_resolution_clock::now();
while (ch_time < end_time) {
manager->Update();
mphysicalSystem.DoStepDynamics(0.001);
ch_time = (float)mphysicalSystem.GetChTime();
}
std::chrono::high_resolution_clock::time_point t2 = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> wall_time = std::chrono::duration_cast<std::chrono::duration<double>>(t2 - t1);
std::cout << "Simulation time: " << ch_time << "s, wall time: " << wall_time.count() << "s.\n";
return 0;
}
| 41.698864 | 119 | 0.557433 | ShuoHe97 |
13ed57089b84a59d225bf6c2ca97512ed7c9f10a | 1,462 | cc | C++ | books/principles/data-structure/tree/test-LCRS-tree.cc | BONITA-KWKim/algorithm | 94a45c929505e574c06d235d18da4625cc243343 | [
"Unlicense"
] | 1 | 2020-06-24T07:34:55.000Z | 2020-06-24T07:34:55.000Z | books/principles/data-structure/tree/test-LCRS-tree.cc | BONITA-KWKim/algorithm | 94a45c929505e574c06d235d18da4625cc243343 | [
"Unlicense"
] | null | null | null | books/principles/data-structure/tree/test-LCRS-tree.cc | BONITA-KWKim/algorithm | 94a45c929505e574c06d235d18da4625cc243343 | [
"Unlicense"
] | null | null | null | #include "gtest/gtest.h"
#include "LCRS-tree.h"
LCRSNode *make_test_tree(void);
void remove_test_tree (LCRSNode *root);
TEST(LCRSTreeTEST, testCreateNode)
{
char test = 'a';
LCRSTree *tree = new LCRSTree();
LCRSNode *node = tree->create_LCRS_node(test);
EXPECT_EQ(NULL, node->left);
EXPECT_EQ(NULL, node->right);
EXPECT_EQ(test, node->data);
}
LCRSNode *make_test_tree (void)
{
LCRSTree *tree = new LCRSTree();
LCRSNode *root = tree->create_LCRS_node('a');
LCRSNode *node1 = tree->create_LCRS_node('b');
LCRSNode *node2 = tree->create_LCRS_node('c');
LCRSNode *node3 = tree->create_LCRS_node('d');
LCRSNode *node4 = tree->create_LCRS_node('e');
LCRSNode *node5 = tree->create_LCRS_node('f');
LCRSNode *node6 = tree->create_LCRS_node('g');
LCRSNode *node7 = tree->create_LCRS_node('h');
/// a
/// b - c ---- d
/// e - f g
/// h
tree->add_child(root, node1);
tree->add_child(root, node2);
tree->add_child(root, node3);
tree->add_child(node2, node4);
tree->add_child(node2, node5);
tree->add_child(node3, node6);
tree->add_child(node5, node7);
}
void remove_test_tree (LCRSNode *root)
{
LCRSTree *tree = new LCRSTree();
tree->destroy_LCRS_tree(root);
}
int main(int argc, char *argv[])
{
LCRSTree *tree = new LCRSTree();
tree->version_info();
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
} | 24.366667 | 50 | 0.635431 | BONITA-KWKim |
13ee1c331cf0c806639b8ff9d05d6418eee90436 | 6,362 | cpp | C++ | Modules/QtWidgetsExt/src/QmitkNumberPropertyEditor.cpp | zhaomengxiao/MITK | a09fd849a4328276806008bfa92487f83a9e2437 | [
"BSD-3-Clause"
] | 1 | 2022-03-03T12:03:32.000Z | 2022-03-03T12:03:32.000Z | Modules/QtWidgetsExt/src/QmitkNumberPropertyEditor.cpp | zhaomengxiao/MITK | a09fd849a4328276806008bfa92487f83a9e2437 | [
"BSD-3-Clause"
] | 1 | 2021-12-22T10:19:02.000Z | 2021-12-22T10:19:02.000Z | Modules/QtWidgetsExt/src/QmitkNumberPropertyEditor.cpp | zhaomengxiao/MITK_lancet | a09fd849a4328276806008bfa92487f83a9e2437 | [
"BSD-3-Clause"
] | 1 | 2020-11-27T09:41:18.000Z | 2020-11-27T09:41:18.000Z | /*============================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.
Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.
============================================================================*/
#include "QmitkNumberPropertyEditor.h"
#include <QTextStream>
#include <mitkRenderingManager.h>
#define DT_SHORT 1
#define DT_INT 2
#define DT_FLOAT 3
#define DT_DOUBLE 4
#define ROUND(x) (((x) > 0) ? int((x) + 0.5) : int((x)-0.5))
#define ROUND_SHORT(x) (((x) > 0) ? short((x) + 0.5) : short((x)-0.5))
QmitkNumberPropertyEditor::QmitkNumberPropertyEditor(mitk::IntProperty *property, QWidget *parent)
: QSpinBox(parent), PropertyEditor(property), m_IntProperty(property), m_DataType(DT_INT)
{
initialize();
}
QmitkNumberPropertyEditor::QmitkNumberPropertyEditor(mitk::FloatProperty *property, QWidget *parent)
: QSpinBox(parent), PropertyEditor(property), m_FloatProperty(property), m_DataType(DT_FLOAT)
{
initialize();
}
QmitkNumberPropertyEditor::QmitkNumberPropertyEditor(mitk::DoubleProperty *property, QWidget *parent)
: QSpinBox(parent), PropertyEditor(property), m_DoubleProperty(property), m_DataType(DT_DOUBLE)
{
initialize();
}
QmitkNumberPropertyEditor::~QmitkNumberPropertyEditor()
{
}
void QmitkNumberPropertyEditor::initialize()
{ // only to be called from constructors
// spinbox settings
setSuffix("");
// protected
m_DecimalPlaces = 0;
m_FactorPropertyToSpinbox = 1.0;
m_FactorSpinboxToDisplay = 1.0;
m_ShowPercents = false;
// private
m_SelfChangeLock = false;
connect(this, SIGNAL(valueChanged(int)), this, SLOT(onValueChanged(int)));
// display current value of our property
DisplayNumber();
}
void QmitkNumberPropertyEditor::adjustFactors(short newDecimalPlaces, bool newShowPercents)
{
int oldMax = maxValue();
int oldMin = minValue();
m_DecimalPlaces = newDecimalPlaces;
m_ShowPercents = newShowPercents;
m_FactorPropertyToSpinbox = pow(10.0, m_DecimalPlaces);
m_FactorSpinboxToDisplay = 1.0 / m_FactorPropertyToSpinbox;
if (m_ShowPercents)
{
m_FactorPropertyToSpinbox *= 100.0;
setSuffix("%");
}
else
{
setSuffix("");
}
setMinValue(oldMin);
setMaxValue(oldMax);
}
short QmitkNumberPropertyEditor::getDecimalPlaces() const
{
return m_DecimalPlaces;
}
void QmitkNumberPropertyEditor::setDecimalPlaces(short places)
{
switch (m_DataType)
{
case DT_FLOAT:
case DT_DOUBLE:
{
adjustFactors(places, m_ShowPercents);
DisplayNumber();
break;
}
default:
break;
}
}
bool QmitkNumberPropertyEditor::getShowPercent() const
{
return m_ShowPercents;
}
void QmitkNumberPropertyEditor::setShowPercent(bool showPercent)
{
if (showPercent == m_ShowPercents)
return; // nothing to change
switch (m_DataType)
{
case DT_FLOAT:
case DT_DOUBLE:
{
adjustFactors(m_DecimalPlaces, showPercent);
break;
}
default:
{
break;
}
}
DisplayNumber();
}
int QmitkNumberPropertyEditor::minValue() const
{
return ROUND(QSpinBox::minimum() / m_FactorPropertyToSpinbox);
}
void QmitkNumberPropertyEditor::setMinValue(int value)
{
QSpinBox::setMinimum(ROUND(value * m_FactorPropertyToSpinbox));
}
int QmitkNumberPropertyEditor::maxValue() const
{
return ROUND(QSpinBox::maximum() / m_FactorPropertyToSpinbox);
}
void QmitkNumberPropertyEditor::setMaxValue(int value)
{
QSpinBox::setMaximum(ROUND(value * m_FactorPropertyToSpinbox));
}
double QmitkNumberPropertyEditor::doubleValue() const
{
return static_cast<double>((QSpinBox::value()) / m_FactorPropertyToSpinbox);
}
void QmitkNumberPropertyEditor::setDoubleValue(double value)
{
QSpinBox::setValue(ROUND(value * m_FactorPropertyToSpinbox));
}
QString QmitkNumberPropertyEditor::textFromValue(int value) const
{
QString displayedText;
QTextStream stream(&displayedText);
double d(value * m_FactorSpinboxToDisplay);
if (m_DecimalPlaces > 0)
{
stream.setRealNumberPrecision(m_DecimalPlaces);
stream << d;
}
else
{
stream << ROUND(d);
}
return displayedText;
}
int QmitkNumberPropertyEditor::valueFromText(const QString &text) const
{
return ROUND(text.toDouble() / m_FactorSpinboxToDisplay);
}
void QmitkNumberPropertyEditor::onValueChanged(int value)
{
if (m_SelfChangeLock)
return; // valueChanged is even emitted, when this widget initiates a change to its value
// this may be useful some times, but in this use, it would be wrong:
// (A) is an editor with 3 decimal places
// (B) is an editor with 2 decimal places
// User changes A's displayed value to 4.002
// A's onValueChanged gets called, sets the associated Property to 4.002
// B's onPropertyChanged gets called, sets its display to 4.00
// B's onValueChanged gets called and sets the associated Property to 4.00
// A's onPropertyChanged gets called, sets its display to 4.000
BeginModifyProperty();
double newValue(value / m_FactorPropertyToSpinbox);
switch (m_DataType)
{
case DT_INT:
{
m_IntProperty->SetValue(ROUND(newValue));
break;
}
case DT_FLOAT:
{
m_FloatProperty->SetValue(newValue);
break;
}
case DT_DOUBLE:
{
m_DoubleProperty->SetValue(newValue);
break;
}
}
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
EndModifyProperty();
}
void QmitkNumberPropertyEditor::PropertyChanged()
{
DisplayNumber();
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}
void QmitkNumberPropertyEditor::PropertyRemoved()
{
m_Property = nullptr;
}
void QmitkNumberPropertyEditor::DisplayNumber()
{
if (!m_Property)
return;
m_SelfChangeLock = true;
switch (m_DataType)
{
case DT_INT:
{
int i = m_IntProperty->GetValue();
QSpinBox::setValue(i);
break;
}
case DT_FLOAT:
{
float f = m_FloatProperty->GetValue();
setDoubleValue(f);
break;
}
case DT_DOUBLE:
{
double d = m_DoubleProperty->GetValue();
setDoubleValue(d);
break;
}
default:
break;
}
m_SelfChangeLock = false;
}
| 22.967509 | 101 | 0.687205 | zhaomengxiao |
13f2406c65a5f3015cedb730e69b3a5dfbf1d140 | 5,298 | cpp | C++ | FrameProcessor.cpp | merfii/Slurry | 92b23ea2b764252fc90c2af741debdffb9a96106 | [
"MIT"
] | 4 | 2019-12-04T02:56:35.000Z | 2022-01-05T14:14:37.000Z | FrameProcessor.cpp | merfii/Slurry | 92b23ea2b764252fc90c2af741debdffb9a96106 | [
"MIT"
] | null | null | null | FrameProcessor.cpp | merfii/Slurry | 92b23ea2b764252fc90c2af741debdffb9a96106 | [
"MIT"
] | 2 | 2018-11-06T03:54:00.000Z | 2018-12-06T12:13:30.000Z | #pragma execution_character_set("utf-8")
#include <opencv2\opencv.hpp>
#include "Slurry.h"
#include "SystemParameter.h"
#include "CameraController.h"
#include "FrameProcessor.h"
#include "FrmProcessorDisp.h"
cv::Mat FrameProcessor::rmapA[2];
cv::Mat FrameProcessor::rmapB[2];
FrameProcessor::FrameProcessor():
useless(false)
{
}
FrameProcessor::~FrameProcessor()
{
}
void FrameProcessor::Process(FramePacket *fp)
{
switch (fp->channIdx)
{
case CAMERA_GRAY_A:
ProcessGrayA(fp);
break;
case CAMERA_GRAY_B:
ProcessGrayB(fp);
break;
case CAMERA_COLOR_A:
ProcessColorA(fp);
break;
case CAMERA_COLOR_B:
ProcessColorB(fp);
break;
}
}
void FrameProcessor::ProcessGrayA(FramePacket *fp)
{
;
}
void FrameProcessor::ProcessGrayB(FramePacket *fp)
{
;
}
void FrameProcessor::ProcessColorA(FramePacket *fp)
{
;
}
void FrameProcessor::ProcessColorB(FramePacket *fp)
{
;
}
/*
void FrameProcessor::LoadCameraParameters()
{
CameraParameter *paramA = SystemParameter::GetCameraColorAParam();
cv::Mat cameraMatrixA = paramA->cameraMatrix;
cv::Mat distCoeffsA = paramA->distCoeffs;
try{
initUndistortRectifyMap(cameraMatrixA, distCoeffsA, Mat(), cameraMatrixA, paramA->imageSize, CV_32FC1, rmapA[0], rmapA[1]);
// initUndistortRectifyMap(cameraMatrixB, distCoeffsB, Mat(), cameraMatrixB, paramB->imageSize, CV_32FC1, rmapB[0], rmapB[1]);
}
catch (const cv::Exception& e)
{
std::cout << e.msg;
}
}
*/
bool FrameProcessor::isUseless() const
{
return useless;
}
void FrameProcessor::setUseless(bool noUse)
{
useless = noUse;
}
#include <iostream>
#include <opencv2/highgui.hpp>
static void maxRow(Mat& dat, Mat& maxId, Mat& maxVal);
static Mat findCentroid(Mat& diff, Mat& initId);
//求两帧图像之间的激光点 返回Nx1 channel=2 矩阵 每行为x y坐标
Mat FrameProcessor::laserLineDetect(cv::Mat diff)
{
if (diff.empty())
return Mat();
CV_Assert(diff.channels() == 3);
Mat BGR_Planes[3], div2, maxId, maxRowVal;
int thresh;
split(diff, BGR_Planes);
//addWeighted(BGR_Planes[0], 0.5, BGR_Planes[2], 0.5, 0, diff); //饱和加 20ms
diff = BGR_Planes[0] / 2 + BGR_Planes[2]/3; /// 2 + BGR_Planes[2] / 2; //16ms
/*
cv::resize(diff, div2, cv::Size(), 1, 0.5);
cv::reduce(diff, maxRow, 0, cv::ReduceTypes::REDUCE_MAX); //每列计算一个最大值
cv::Scalar avg = cv::sum(maxRow) / maxRow.size().width;
thresh = avg(0) * 4 /5; // x0.8
cout << "Avg: " << thresh << endl;
*/
//为了加快速度,先纵向寻找最大点,然后精细计算灰度重心
//int64_t t1 = cv::getTickCount();
maxRow(diff, maxId, maxRowVal);
//qDebug() << "maxRow dt" <<(cv::getTickCount() - t1) / cv::getTickFrequency() * 1000 << endl;; //ms
//cout << "Max ID: " << maxId.colRange(cv::Range(0,10)) << endl;
return findCentroid(diff, maxId);
}
static void maxRow(Mat& dat, Mat& maxId, Mat& maxVal) //求每一列最大值及行号
{
CV_Assert(dat.channels() == 1 && dat.type() == CV_8UC1);
maxId = Mat::ones(1, dat.cols, CV_32SC1);
maxId = -maxId;
maxVal = Mat::zeros(1, dat.cols, CV_8UC1);
uint8_t *pmax = maxVal.ptr<uint8_t>(0);
int32_t *pid = maxId.ptr<int32_t>(0);
for (int row = 0; row < dat.rows; row++)
{
uint8_t *pdat = dat.ptr<uint8_t>(row);
for (int j = 0; j < dat.cols; j++)
{
if (pdat[j] > pmax[j])
{
pmax[j] = pdat[j];
pid[j] = row;
}
}
}
}
//Gaussian kernel 系数 sigma=2
#define GAUSSIAN_SUM(r,c) \
diff.at<uint8_t>(r - 6, j) * 3 + \
diff.at<uint8_t>(r - 5, j) * 10 + \
diff.at<uint8_t>(r - 4, j) * 30 + \
diff.at<uint8_t>(r - 3, j) * 70 + \
diff.at<uint8_t>(r - 2, j) * 120 + \
diff.at<uint8_t>(r - 1, j) * 170 + \
diff.at<uint8_t>(r, j) * 200 + \
diff.at<uint8_t>(r + 1, j) * 170 + \
diff.at<uint8_t>(r + 2, j) * 120 + \
diff.at<uint8_t>(r + 3, j) * 70 + \
diff.at<uint8_t>(r + 4, j) * 30 + \
diff.at<uint8_t>(r + 5, j) * 10 + \
diff.at<uint8_t>(r + 6, j) * 3
bool sort_comp(cv::Point3d a, cv::Point3d b) {
return (a.z < b.z);
}
#define FIND_CENTROID_ALPHA 0.1 //删去最小的10%数据
#define FIND_CENTROID_MINIMUM 10000 //最小亮度过滤
static Mat findCentroid(Mat& diff, Mat& initId)
{
Mat retval;
std::vector<cv::Point3d> points;
cv::Point3d point;
double thresh;
for (int j = 0; j < diff.cols; j++)
{
int cidx = initId.at<int>(j);
if ( cidx < 16 || cidx > diff.rows - 16)
{
continue;
}
double maxnum = 0; int maxId =-1;
for (int delt = -6; delt < 6; delt++)
{
double num = GAUSSIAN_SUM(cidx + delt, j);
if (num > maxnum)
{
maxnum = num;
maxId = cidx + delt;
}
}
//高斯加权后的灰度重心 亚像素级
double w1, w2, w3;
w1 = GAUSSIAN_SUM(maxId - 1, j);
w2 = maxnum;
w3 = GAUSSIAN_SUM(maxId + 1, j);
point.x = j;
point.y = (w1*(maxId - 1) + w2*maxId + w3*(maxId + 1)) / (w1 + w2 + w3);
point.z = w2;
points.push_back(point);
}
if (points.size() < 8)
{
return retval;
}
else
{
std::vector<cv::Point3d> points_sort;
points_sort.assign(points.begin(), points.end());
std::sort(points_sort.begin(), points_sort.end(), sort_comp);
thresh = points_sort[(int)(points_sort.size()*FIND_CENTROID_ALPHA)].z;
thresh = thresh > FIND_CENTROID_MINIMUM ? thresh : FIND_CENTROID_MINIMUM;
// cout << thresh << endl;
}
retval.create(points.size(), 1, CV_64FC2);
int count = 0;
for (const cv::Point3d &p : points)
{
if (p.z < thresh)
continue;
retval.ptr<double>(count)[0] = p.x;
retval.ptr<double>(count)[1] = p.y;
count++;
}
retval.resize(count);
return retval;
} | 21.892562 | 127 | 0.64345 | merfii |
13f7f7ed219f89cfd455a2b2a798557ffb42a89a | 3,273 | cpp | C++ | main.cpp | DnJuses/Qt-easy-host-director | 5a9c9ef560fac4034505b3c6f54db90e782df74a | [
"MIT"
] | 1 | 2018-12-09T18:05:45.000Z | 2018-12-09T18:05:45.000Z | main.cpp | DnJuses/Qt-easy-host-director | 5a9c9ef560fac4034505b3c6f54db90e782df74a | [
"MIT"
] | null | null | null | main.cpp | DnJuses/Qt-easy-host-director | 5a9c9ef560fac4034505b3c6f54db90e782df74a | [
"MIT"
] | null | null | null | #include "module_hostdirector/HostDirector.h"
#include "module_hostdirector/utility/HostDirectorFileWriter.h"
#include "module_hostdirector/utility/HostDirectorErrorHandler.h"
#include "module_passwordforms/confirmationform/PasswordConfirmationForm.h"
#include "module_passwordforms/creationform/PasswordCreationForm.h"
#include <QApplication>
#include <QtCore>
#include <QMessageBox>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QCoreApplication::setOrganizationName("Suvo softworks");
QCoreApplication::setApplicationName("Host Director");
QTranslator languageTranslator;
QTranslator qtTranslator;
if(languageTranslator.load("hdir_" + QLocale::system().name(), "translations")
&& qtTranslator.load("qt_" + QLocale::system().name(), QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
{
app.installTranslator(&languageTranslator);
app.installTranslator(&qtTranslator);
}
QSystemSemaphore singleApp("<uniq id>", 1);
singleApp.acquire();
#ifndef Q_OS_WIN32
QSharedMemory unixFixLeak("<uniq id 2>");
if(unixFixLeak.attach())
unixFixLeak.detach();
#endif
QSharedMemory AppSM("<uniq id 2>");
bool appIsRunning = false;
if(AppSM.attach())
{
appIsRunning = true;
}
else
{
AppSM.create(1);
appIsRunning = false;
}
singleApp.release();
if(appIsRunning)
{
HostDirectorErrorHandler::dispatchError(ErrorTypes::ErrorValue::APP_ALREADY_RUNNING);
return 0;
}
if(!AbstractPasswordForm::isPasswordExists())
{
QMessageBox::StandardButton confirm;
confirm = QMessageBox::question(nullptr,
QApplication::tr("Password manager"),
QApplication::tr("It seems like you don't have any passwords with you. Want to create one?"),
QMessageBox::Yes | QMessageBox::No,
QMessageBox::Yes);
if(confirm == QMessageBox::Yes)
{
PasswordCreationForm create;
create.exec();
}
}
if(HostDirectorFileWriter::isCopyExists())
{
QMessageBox::StandardButton confirm;
confirm = QMessageBox::question(nullptr,
QApplication::tr("Host director"),
QApplication::tr("The application was closed in wrong way and changes still in effect. To undo them, press 'Ok' and type in your password."),
QMessageBox::Yes | QMessageBox::No,
QMessageBox::Yes);
if(confirm == QMessageBox::Yes)
{
if(AbstractPasswordForm::isPasswordExists())
{
PasswordConfirmationForm confirmForm;
confirmForm.exec();
if(confirmForm.isCorrect())
{
HostDirectorFileWriter::eraseConfigurationUnpair();
}
}
else
{
HostDirectorFileWriter::eraseConfigurationUnpair();
}
}
}
HostDirector w;
w.show();
return app.exec();
}
| 35.967033 | 181 | 0.589368 | DnJuses |
13f81320c3ce60784f4c1423a9b8ae6d0d5d4968 | 1,696 | cpp | C++ | Engine/src/Render/Font/icFontDX9.cpp | binofet/ice | dee91da76df8b4f46ed4727d901819d8d20aefe3 | [
"MIT"
] | null | null | null | Engine/src/Render/Font/icFontDX9.cpp | binofet/ice | dee91da76df8b4f46ed4727d901819d8d20aefe3 | [
"MIT"
] | null | null | null | Engine/src/Render/Font/icFontDX9.cpp | binofet/ice | dee91da76df8b4f46ed4727d901819d8d20aefe3 | [
"MIT"
] | null | null | null | #include "Render/Font/icFontDX9.h"
#ifdef ICDX9
ICRESULT icFontDX9::Initialize(const char* szFileName, const int size,
class icGXDevice* pDevice)
{
//_font = NULL;
//icGXDeviceDX9* pDevice = (icGXDeviceDX9*)pContent->GetDevice();
//if (pDevice)
//{
// D3DXCreateFont(pDevice->GetDevice(),
// size,
// 0,
// FW_NORMAL,
// 1,
// false,
// DEFAULT_CHARSET,
// OUT_DEFAULT_PRECIS,
// ANTIALIASED_QUALITY,
// DEFAULT_PITCH|FF_DONTCARE,
// "Arial",
// &_font);
// return _font ? IC_OK : IC_FAIL_GEN;
//}
return IC_FAIL_NO_DEVICE;
}
ICRESULT icFontDX9::Print(const icVector2Int& v2ScreenPos,
const icColor& color,
const char* buff)
{
//int width, height;
//RECT font_rect = {0,0,width,height}; //sets the size of our font surface rect
////set the destination for our text, by moving the font rect.
//SetRect(&font_rect, //our font rect
// v2ScreenPos.x, //Left
// v2ScreenPos.y, //Top
// width, //width
// height //height
//);
////draw our text
//_font->DrawText(NULL, //pSprite
// text.c_str(), //pString
// -1, //Count
// &font_rect, //pRect
// DT_LEFT|DT_NOCLIP,//Format,
// color.ARGB());
return IC_OK;
}
ICRESULT icFontDX9::Printf(const icVector2Int& v2ScreenPos,
const icColor& color,
const char* buff, ...)
{
return IC_OK;
}
#endif // ICDX9 | 26.920635 | 85 | 0.508844 | binofet |
13f936492d5c47ced149aa17b4f1be4c971ce38e | 1,759 | cpp | C++ | src/bug_15.cpp | happanda/advent_2017 | 9e705f3088d79dac0caa471154ae88ed5106b2d2 | [
"MIT"
] | null | null | null | src/bug_15.cpp | happanda/advent_2017 | 9e705f3088d79dac0caa471154ae88ed5106b2d2 | [
"MIT"
] | null | null | null | src/bug_15.cpp | happanda/advent_2017 | 9e705f3088d79dac0caa471154ae88ed5106b2d2 | [
"MIT"
] | null | null | null | #include "advent.h"
struct Generator15
{
Generator15(long long seed, long long factor, long long base, int check = 1)
: mSeed(seed)
, mBase(base)
, mFactor(factor)
, mCheck(check)
{
}
long long genNext()
{
mSeed = (mSeed * mFactor) % mBase;
return mSeed;
}
long long genNextModified()
{
do
{
mSeed = (mSeed * mFactor) % mBase;
} while (mSeed % mCheck != 0);
return mSeed;
}
private:
long long mSeed{ 0 };
long long const mBase{ 1 };
long long const mFactor{ 0 };
int mCheck{ 1 };
};
void BugFix<15>::solve1st()
{
long long seed0{ 0 }, seed1{ 0 };
*mIn >> seed0 >> seed1;
Generator15 gen0(seed0, 16807, 2147483647);
Generator15 gen1(seed1, 48271, 2147483647);
int equalCount{ 0 };
const size_t total = 40'000'000;
const long long twoPow = 65535;
for (size_t i = 0; i < total; ++i)
{
long long const gen0Next = gen0.genNext();
long long const gen1Next = gen1.genNext();
//*mOut << gen0Next << "\t" << gen1Next << std::endl;
long long one = gen0Next & twoPow;
long long two = gen1Next & twoPow;
if (one == two)
++equalCount;
}
*mOut << equalCount << std::endl;
}
void BugFix<15>::solve2nd()
{
long long seed0{ 0 }, seed1{ 0 };
*mIn >> seed0 >> seed1;
Generator15 gen0(seed0, 16807, 2147483647, 4);
Generator15 gen1(seed1, 48271, 2147483647, 8);
int equalCount{ 0 };
const size_t total = 5'000'000;
const long long twoPow = 65535;
for (size_t i = 0; i < total; ++i)
{
long long const gen0Next = gen0.genNextModified();
long long const gen1Next = gen1.genNextModified();
//*mOut << gen0Next << "\t" << gen1Next << std::endl;
long long one = gen0Next & twoPow;
long long two = gen1Next & twoPow;
if (one == two)
++equalCount;
}
*mOut << equalCount << std::endl;
} | 20.694118 | 77 | 0.63104 | happanda |
13fbbb17a8ed2771706da56ef61636581c4eb2b2 | 1,340 | cc | C++ | 洛谷/提高-/CF808C.cc | OFShare/Algorithm-challenger | 43336871a5e48f8804d6e737c813d9d4c0dc2731 | [
"MIT"
] | 67 | 2019-07-14T05:38:41.000Z | 2021-12-23T11:52:51.000Z | 洛谷/提高-/CF808C.cc | OFShare/Algorithm-challenger | 43336871a5e48f8804d6e737c813d9d4c0dc2731 | [
"MIT"
] | null | null | null | 洛谷/提高-/CF808C.cc | OFShare/Algorithm-challenger | 43336871a5e48f8804d6e737c813d9d4c0dc2731 | [
"MIT"
] | 12 | 2020-01-16T10:48:01.000Z | 2021-06-11T16:49:04.000Z | /*
* Author : OFShare
* E-mail : OFShare@outlook.com
* Created Time : 2020-05-03 00:18:05 AM
* File Name : CF808C.cc
*/
#include <bits/stdc++.h>
#define ll long long
void debug() {
#ifdef Acui
freopen("data.in", "r", stdin);
freopen("data.out", "w", stdout);
#endif
}
const int N = 1e2 + 5;
int n, w;
struct Node {
int cap, id, volume;
}A[N];
int main() {
scanf("%d %d", &n, &w);
int sum = 0;
for (int i = 1; i <= n; ++i) {
scanf("%d", &A[i].cap);
A[i].id = i;
A[i].volume = A[i].cap;
sum += std::ceil(A[i].cap / 2.0);
}
if (sum > w) printf("-1"), exit(0);
std::sort(A + 1, A + 1 + n, [](const Node &lhs, const Node &rhs) {
return lhs.volume > rhs.volume;
});
for (int i = 1; i <= n; ++i) {
A[i].cap = std::ceil(A[i].volume / 2.0);
w -= A[i].cap;
}
// 模拟, 注意不能超过杯子容量, 排序后贪心的选择前面的杯子尽量装
for (int i = 1; i <= n; ++i) {
int left = A[i].volume - A[i].cap;
if (left <= w) A[i].cap = A[i].volume, w -= left;
else A[i].cap += w, w = 0;
}
// for (int i = 1; i <= n; ++i) {
// std::cout << "id: " << A[i].id << "cap: " << A[i].cap << std::endl;
// }
std::sort(A + 1, A + 1 + n, [](const Node &lhs, const Node &rhs) {
return lhs.id < rhs.id;
});
for (int i = 1; i <= n; ++i) {
printf("%d ", A[i].cap);
}
return 0;
}
| 22.333333 | 74 | 0.470896 | OFShare |
13fc9bc26f362c3818cab5a09da7948b5466e3fa | 5,192 | cpp | C++ | deployment/configenv/xml_jlibpt/SWThorCluster.cpp | davidarcher/HPCC-Platform | fa817ab9ea7d8154ac08bc780ce9ce673f3e51e3 | [
"Apache-2.0"
] | 286 | 2015-01-03T12:45:17.000Z | 2022-03-25T18:12:57.000Z | deployment/configenv/xml_jlibpt/SWThorCluster.cpp | davidarcher/HPCC-Platform | fa817ab9ea7d8154ac08bc780ce9ce673f3e51e3 | [
"Apache-2.0"
] | 9,034 | 2015-01-02T08:49:19.000Z | 2022-03-31T20:34:44.000Z | deployment/configenv/xml_jlibpt/SWThorCluster.cpp | cloLN/HPCC-Platform | 42ffb763a1cdcf611d3900831973d0a68e722bbe | [
"Apache-2.0"
] | 208 | 2015-01-02T03:27:28.000Z | 2022-02-11T05:54:52.000Z | /*##############################################################################
HPCC SYSTEMS software Copyright (C) 2018 HPCC Systems®.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
############################################################################## */
#include "SWThorCluster.hpp"
//#include "deployutils.hpp"
namespace ech
{
SWThorCluster::SWThorCluster(const char* name, EnvHelper * envHelper):SWProcess(name, envHelper)
{
//roxieOnDemand = true;
m_instanceElemName.clear().append("ThorSlaveProcess");
m_masterInstanceElemName.clear().append("ThorMasterProcess");
}
IPropertyTree * SWThorCluster::addComponent(IPropertyTree *params)
{
const char* clone = params->queryProp("@clone");
if (clone)
{
return SWProcess::cloneComponent(params);
}
IPropertyTree *pCompTree = SWProcess::addComponent(params);
assert(pCompTree);
removeInstancesFromComponent(pCompTree);
// Some of following may already be handled by AttributesFromXSD
// Add <SwapNode /> <Debug/> and <SSH />
return pCompTree;
}
IPropertyTree * SWThorCluster::cloneComponent(IPropertyTree *params)
{
IPropertyTree * targetNode = SWProcess::cloneComponent(params);
removeInstancesFromComponent(targetNode);
return targetNode;
}
void SWThorCluster::checkInstanceAttributes(IPropertyTree *instanceNode, IPropertyTree *parent)
{
const char *ip = instanceNode->queryProp(XML_ATTR_NETADDRESS);
if (ip) instanceNode->removeProp(XML_ATTR_NETADDRESS);
}
const char* SWThorCluster::getInstanceXMLTagName(const char* name)
{
const char* selectorName = (StringBuffer(name).toLowerCase()).str();
if (!strcmp(selectorName, "instance-master"))
return m_masterInstanceElemName.str();
return m_instanceElemName.str();
}
void SWThorCluster::addInstances(IPropertyTree *parent, IPropertyTree *params)
{
const char * instanceXMLTagName = getInstanceXMLTagName(params->queryProp("@selector"));
StringBuffer xpath;
if (!stricmp(instanceXMLTagName, "ThorMasterProcess"))
{
const char* key = params->queryProp("@key");
IPropertyTree * masterNode = parent->queryPropTree("ThorMasterProcess");
if (masterNode)
throw MakeStringException(CfgEnvErrorCode::InvalidParams, "Cannot add thor master. There is already a master node in cluster \"%s\".", key);
}
SWProcess::addInstances(parent, params);
if (!stricmp(instanceXMLTagName, "ThorMasterProcess"))
{
IPropertyTree * masterNode = parent->queryPropTree("ThorMasterProcess");
parent->setProp("@computer", masterNode->queryProp("@computer"));
}
}
void SWThorCluster::updateComputerAttribute(const char *newName, const char *oldName)
{
IPropertyTree *software = m_envHelper->getEnvTree()->queryPropTree("Software");
Owned<IPropertyTreeIterator> compIter = software->getElements(m_processName);
ForEach (*compIter)
{
IPropertyTree *comp = &compIter->query();
if (!stricmp(oldName, comp->queryProp("@computer")))
{
comp->setProp("@computer", newName);
}
}
}
void SWThorCluster::computerUpdated(IPropertyTree *computerNode, const char *oldName, const char *oldIp,
const char* instanceXMLTagName)
{
SWProcess::computerUpdated(computerNode, oldName, oldIp);
SWProcess::computerUpdated(computerNode, oldName, oldIp, m_masterInstanceElemName.str());
updateComputerAttribute(computerNode->queryProp(XML_ATTR_NAME), oldName);
}
void SWThorCluster::computerDeleted(const char *ipAddress, const char *computerName, const char* instanceXMLTagName)
{
SWProcess::computerDeleted(ipAddress, computerName, instanceXMLTagName);
SWProcess::computerDeleted(ipAddress, computerName, m_masterInstanceElemName.str());
updateComputerAttribute("", computerName);
}
void SWThorCluster::removeInstancesFromComponent(IPropertyTree *compNode)
{
Owned<IPropertyTreeIterator> masterIter = compNode->getElements("ThorMasterProcess");
ForEach(*masterIter)
{
compNode->removeTree(&masterIter->query());
}
compNode->setProp("@computer", "");
Owned<IPropertyTreeIterator> slaveIter = compNode->getElements("ThorSlaveProcess");
ForEach(*slaveIter)
{
compNode->removeTree(&slaveIter->query());
}
}
void SWThorCluster::addInstance(IPropertyTree *computerNode, IPropertyTree *parent, IPropertyTree *attrs, const char* instanceTagXMLName)
{
SWProcess::addInstance(computerNode, parent, attrs, instanceTagXMLName);
SWProcess *ftslaveHandler = (SWProcess*)m_envHelper->getEnvSWComp("ftslave");
IPropertyTree *ftslaveComp = m_envHelper->getEnvTree()->queryPropTree("Software/FTSlaveProcess[1]");
ftslaveHandler->addInstance(computerNode, ftslaveComp, NULL, "Instance");
}
}
| 34.384106 | 149 | 0.724191 | davidarcher |
13fd24ce2a47de8d7edc81578368fecb931ff9f5 | 1,188 | cpp | C++ | Game/Source/Game/src/BossRoom.cpp | SweetheartSquad/GameJam2016 | e5787a6521add448fde8182ada0bce250ba831ea | [
"MIT"
] | null | null | null | Game/Source/Game/src/BossRoom.cpp | SweetheartSquad/GameJam2016 | e5787a6521add448fde8182ada0bce250ba831ea | [
"MIT"
] | null | null | null | Game/Source/Game/src/BossRoom.cpp | SweetheartSquad/GameJam2016 | e5787a6521add448fde8182ada0bce250ba831ea | [
"MIT"
] | null | null | null | #pragma once
#include <BossRoom.h>
#include <MeshFactory.h>
#include <MeshInterface.h>
#include <MY_ResourceManager.h>
#include <Resource.h>
BossRoom::BossRoom(Shader * _shader) :
Room(_shader)
{
mesh->replaceTextures(getRoomTex());
}
BossRoom::~BossRoom(){
}
Texture * BossRoom::getRoomTex(){
// grab a random floor texture
std::stringstream ss;
ss << "assets/textures/rooms/boss.png";//"assets/textures/rooms/" << roomTexIdx.pop() << ".png";
Texture * res = new Texture(ss.str(), false, true, true);
res->load();
return res;
}
MeshEntity * BossRoom::getFurnitureSet(){
// grab a random furniture set
int idx = 1;
/*
std::stringstream ssTex;
ssTex << "assets/textures/furnitureSets/" << idx << ".png";
Texture * tex = new Texture(ssTex.str(), false, true, false);
tex->load();
*/
std::stringstream ssObj;
ssObj << "assets/meshes/furnitureSets/boss.obj";
MeshEntity * res = new MeshEntity(MY_ResourceManager::globalAssets->getMesh("BOSS")->meshes.at(0), getShader());
Texture * tex = new Texture("assets/textures/furnitureSets/boss.png", false, true, false);
tex->load();
res->mesh->pushTexture2D(tex);
res->mesh->setScaleMode(GL_NEAREST);
return res;
} | 23.76 | 113 | 0.692761 | SweetheartSquad |
cd039533a0ed7d2f51715442fd1c3211cb402780 | 7,804 | cpp | C++ | ARDUINO_CODE/ic_display.cpp | Allabakshu-shaik/Mercedes-POC | b338c471870830ba4b4fb26e4dc1097e0882a8e2 | [
"MIT"
] | 46 | 2020-01-08T16:38:46.000Z | 2022-03-30T21:08:07.000Z | ARDUINO_CODE/ic_display.cpp | Allabakshu-shaik/Mercedes-POC | b338c471870830ba4b4fb26e4dc1097e0882a8e2 | [
"MIT"
] | 2 | 2020-03-28T08:26:29.000Z | 2020-08-06T10:52:57.000Z | ARDUINO_CODE/ic_display.cpp | Allabakshu-shaik/Mercedes-POC | b338c471870830ba4b4fb26e4dc1097e0882a8e2 | [
"MIT"
] | 9 | 2020-03-13T20:53:02.000Z | 2021-08-31T08:50:20.000Z | #include "ic_display.h"
#include "can.h"
IC_DISPLAY::IC_DISPLAY(CANBUS_COMMUNICATOR *can) {
canB = can;
}
uint8_t IC_DISPLAY::current_page = IC_PAGE_AUDIO;
bool IC_DISPLAY::can_fit_body_text(const char *text) {
int length = 0;
for (uint8_t i = 0; i < strlen(text); i++) {
length += pgm_read_byte_near(CHAR_WIDTHS + text[i]);
}
return (length - 1) <= DISPLAY_WIDTH_PX; // -1 as last char doesn't need 1 pixel padding
}
uint8_t IC_DISPLAY::getChecksum(uint8_t len, uint8_t* payload) {
uint8_t cs = 0xFF;
for (uint8_t i = 0; i <= len; i++) cs -= i + payload[i];
return cs;
}
void IC_DISPLAY::setHeader(uint8_t p, const char* text, uint8_t fmt) {
if (strlen(text) == 0) return;
DPRINTLN(F("-- Update header --"));
uint8_t str_len = min(strlen(text), 20);
buffer_size = str_len + 3;
buffer[0] = p; // Page number
buffer[1] = 0x29; // Package 29 (Header text update)
buffer[2] = fmt; // Text justification
for (uint8_t i = 0; i < str_len; i++) {
buffer[i+3] = text[i];
}
buffer[buffer_size] = 0x00;
buffer[buffer_size+1] = getChecksum(buffer_size, buffer);
buffer_size+=2;
sendBytes(0,0);
}
void IC_DISPLAY::setBody(uint8_t p, const char* text, uint8_t fmt = IC_TEXT_FMT_CENTER_JUSTIFICATION) {
if (strlen(text) == 0) return;
DPRINTLN(F("-- Update body --"));
uint8_t str_len = min(strlen(text), 32);
buffer_size = str_len + 7; // Not including CS bit
buffer[0] = p; // Page number
buffer[1] = 0x26; // Package 26 (Body text update)
buffer[2] = 0x01;
buffer[3] = 0x00;
buffer[4] = 0x01; // Number of strings (1 only)
buffer[5] = str_len + 2;
buffer[6] = fmt;
for (uint8_t i = 0; i < str_len; i++) {
buffer[i+7] = text[i];
}
buffer[buffer_size] = 0x00; // End of string
buffer[buffer_size+1] = getChecksum(buffer_size, buffer);
buffer_size+=2;
sendBytes(0,0);
}
void IC_DISPLAY::setBodyTel(uint8_t numStrs, const char* lines[]){
uint8_t charCount = 0;
uint8_t strsToUse = 0;
for (uint8_t i = 0; i < numStrs; i++) {
charCount += strlen(lines[i]) + 2;
if (charCount < 55) {
strsToUse++;
}
}
if (strsToUse == 0) {
return;
}
DPRINTLN(F("-- Update body --"));
buffer_size = charCount + 5; // Not including CS bit
buffer[0] = IC_PAGE_TELEPHONE; // Page number
buffer[1] = 0x26; // Package 26 (Body text update)
buffer[2] = 0x01;
buffer[3] = 0x00;
buffer[4] = strsToUse; // Number of strings (1 only)
uint8_t index = 5;
for (uint8_t i = 0; i < strsToUse; i++) {
buffer[index] = strlen(lines[i]) + 2;
buffer[index+1] = IC_TEXT_FMT_CENTER_JUSTIFICATION | IC_TEXT_FMT_HIGHLIGHTED;
index += 2;
for (uint8_t x = 0; x < strlen(lines[i]); x++) {
buffer[index] = lines[i][x];
index++;
}
}
buffer[buffer_size] = 0x00; // End of string
buffer[buffer_size+1] = getChecksum(buffer_size, buffer);
buffer_size+=2;
sendBytes(0,0);
}
void IC_DISPLAY::processIcResponse(can_frame *r) {
if (r->can_id == 0x1D0) {
DPRINTLN(IC_TO_AGW_STR+*canB->frame_to_string(r, false));
// Some data relating to navigation sent to AGW
if (r->data[0] == 0x06 && r->data[2] == 0x27) {
// Audio Page
if (r->data[1] == 0x03 && r->data[6] == 0xC4) { // Move in
current_page = IC_PAGE_AUDIO;
}
else if (r->data[1] == 0x03 && r->data[6] == 0xC3) { // Move out
current_page = IC_PAGE_OTHER;
}
// Telephone page
if (r->data[1] == 0x05 && r->data[6] == 0xC2) { // Move in
current_page = IC_PAGE_TELEPHONE;
}
else if (r->data[1] == 0x05 && r->data[6] == 0xC1) { // Move out
current_page = IC_PAGE_OTHER;
}
}
}
}
void IC_DISPLAY::initPage(uint8_t p, const char* header, uint8_t fmt, uint8_t upper_Symbol, uint8_t lower_Symbol, uint8_t numLines=1) {
DPRINTLN(F("-- Init page --"));
uint8_t str_len = min(strlen(header), 20);
buffer_size = str_len + 17; // Not including CS bit
buffer[0] = p; // Page number
buffer[1] = 0x24; // Package 24 (Init page)
buffer[2] = 0x02;
buffer[3] = 0x60;
buffer[4] = 0x00;
buffer[5] = numLines;
buffer[6] = 0x00;
buffer[7] = 0x00;
buffer[8] = 0x00;
buffer[9] = 0x13;
buffer[10] = IC_SYMB_UP_ARROW; // Upper symbol (Above text)
buffer[11] = 0x01;
buffer[12] = IC_SYMB_UP_ARROW; // Lower symbol (Under text)
buffer[13] = 0x02;
buffer[14] = 0x00;
buffer[15] = str_len;
buffer[16] = fmt;
for (uint8_t i = 0; i < str_len; i++) {
buffer[i+17] = header[i];
}
buffer[buffer_size] = 0x00; // End of string
buffer[buffer_size+1] = getChecksum(buffer_size, buffer);
buffer_size+=2;
sendBytes(400,400);
}
void IC_DISPLAY::sendBytes(int pre_delay, int post_delay) {
wait(pre_delay);
x.can_id = SEND_CAN_ID;
x.can_dlc = 0x08;
if (buffer_size == 0) {
return;
} else if (buffer_size >= 55) {
Serial.println(F("Payload too big!"));
return;
}
if (buffer_size < 8) {
x.data[0] = buffer_size;
for (uint8_t i = 0; i < buffer_size; i++) x.data[i+1] = buffer[i];
DPRINTLN(AGW_TO_IC_STR+*canB->frame_to_string(&x, false));
canB->sendToBus(&x);
wait(post_delay);
return;
} else {
x.data[0] = 0x10;
x.data[1] = buffer_size;
for (uint8_t i = 2; i < 8; i++) x.data[i] = buffer[i-2];
DPRINTLN(AGW_TO_IC_STR+*canB->frame_to_string(&x, false));
canB->sendToBus(&x);
wait(5);
x.data[0] = 0x21;
for (uint8_t i = 1; i < 8; i++) x.data[i] = buffer[i+5];
DPRINTLN(AGW_TO_IC_STR+*canB->frame_to_string(&x, false));
canB->sendToBus(&x);
wait(2);
if (buffer_size > 13) {
x.data[0] = 0x22;
for (uint8_t i = 1; i < 8; i++) x.data[i] = buffer[i+12];
DPRINTLN(AGW_TO_IC_STR+*canB->frame_to_string(&x, false));
canB->sendToBus(&x);
wait(2);
}
if (buffer_size > 20) {
x.data[0] = 0x23;
for (uint8_t i = 1; i < 8; i++) x.data[i] = buffer[i+19];
DPRINTLN(AGW_TO_IC_STR+*canB->frame_to_string(&x, false));
canB->sendToBus(&x);
wait(2);
}
if (buffer_size > 27) {
x.data[0] = 0x24;
for (uint8_t i = 1; i < 8; i++) x.data[i] = buffer[i+26];
DPRINTLN(AGW_TO_IC_STR+*canB->frame_to_string(&x, false));
canB->sendToBus(&x);
wait(2);
}
if (buffer_size > 34) {
x.data[0] = 0x25;
for (uint8_t i = 1; i < 8; i++) x.data[i] = buffer[i+33];
DPRINTLN(AGW_TO_IC_STR+*canB->frame_to_string(&x, false));
canB->sendToBus(&x);
wait(2);
}
if (buffer_size > 41) {
x.data[0] = 0x26;
for (uint8_t i = 1; i < 8; i++) x.data[i] = buffer[i+40];
DPRINTLN(AGW_TO_IC_STR+*canB->frame_to_string(&x, false));
canB->sendToBus(&x);
wait(2);
}
if (buffer_size > 48) {
x.data[0] = 0x27;
for (uint8_t i = 1; i < 8; i++) x.data[i] = buffer[i+47];
DPRINTLN(AGW_TO_IC_STR+*canB->frame_to_string(&x, false));
canB->sendToBus(&x);
wait(2);
}
delay(post_delay+10);
}
}
void IC_DISPLAY::wait(uint8_t msec) {
unsigned long endTime = millis() + msec;
while (millis() <= endTime) {
processIcResponse(canB->read_frame());
}
} | 33.067797 | 135 | 0.545105 | Allabakshu-shaik |
cd04566d3d73dde6f37d0b276fede7f783fc5539 | 3,841 | cpp | C++ | src/image.cpp | ceilors/flamebutter | 8e8c24be3237d898d44d7684b6784611b43fef2c | [
"BSD-3-Clause"
] | null | null | null | src/image.cpp | ceilors/flamebutter | 8e8c24be3237d898d44d7684b6784611b43fef2c | [
"BSD-3-Clause"
] | null | null | null | src/image.cpp | ceilors/flamebutter | 8e8c24be3237d898d44d7684b6784611b43fef2c | [
"BSD-3-Clause"
] | null | null | null | #include "image.hpp"
PNGImage::PNGImage(FILE *f) {
color_channels = 0;
png_byte header[8];
fread(header, 1, 8, f);
int is_png = !png_sig_cmp(header, 0, 8);
if (!is_png) {
fclose(f);
throw std::runtime_error("is not png");
}
png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
if (!png_ptr) {
fclose(f);
throw std::runtime_error("png_create_read_struct problem");
}
png_infop info_ptr = png_create_info_struct(png_ptr);
if (!info_ptr) {
png_destroy_read_struct(&png_ptr, (png_infopp)NULL, (png_infopp)NULL);
fclose(f);
throw std::runtime_error("png_create_info_struct problem");
}
png_infop end_info = png_create_info_struct(png_ptr);
if (!end_info) {
png_destroy_read_struct(&png_ptr, (png_infopp)NULL, (png_infopp)NULL);
fclose(f);
throw std::runtime_error("png_create_info_struct problem");
}
if (setjmp(png_jmpbuf(png_ptr))) {
png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
fclose(f);
throw std::runtime_error("setjmp problem");
}
png_init_io(png_ptr, f);
png_set_sig_bytes(png_ptr, 8);
png_read_info(png_ptr, info_ptr);
size.x = png_get_image_width(png_ptr, info_ptr);
size.y = png_get_image_height(png_ptr, info_ptr);
auto color_type = png_get_color_type(png_ptr, info_ptr);
auto bit_depth = png_get_bit_depth(png_ptr, info_ptr);
if (bit_depth == 16) {
png_set_strip_16(png_ptr);
}
if (color_type == PNG_COLOR_TYPE_PALETTE) {
png_set_palette_to_rgb(png_ptr);
}
// PNG_COLOR_TYPE_GRAY_ALPHA is always 8 or 16bit depth.
if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8) {
png_set_expand_gray_1_2_4_to_8(png_ptr);
}
if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) {
png_set_tRNS_to_alpha(png_ptr);
}
// These color_type don't have an alpha channel then fill it with 0xff.
if (color_type == PNG_COLOR_TYPE_RGB || color_type == PNG_COLOR_TYPE_GRAY || color_type == PNG_COLOR_TYPE_PALETTE) {
png_set_filler(png_ptr, 0xFF, PNG_FILLER_AFTER);
// use RGBA palette
color_channels = 4;
}
if (color_type == PNG_COLOR_TYPE_GRAY || color_type == PNG_COLOR_TYPE_GRAY_ALPHA) {
png_set_gray_to_rgb(png_ptr);
// use RGB palette
color_channels = 3;
}
png_read_update_info(png_ptr, info_ptr);
int row_bytes = png_get_rowbytes(png_ptr, info_ptr);
raw = (uint8_t *)new png_byte[row_bytes * size.y];
if (!raw) {
png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
fclose(f);
throw std::runtime_error("empty raw data");
}
png_bytepp row_pointers = new png_bytep[size.y];
if (!row_pointers) {
png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
delete[] raw;
fclose(f);
throw std::runtime_error("row_pointers problem");
}
for (uint32_t i = 0; i < (uint32_t)size.y; ++i) {
row_pointers[i] = raw + i * row_bytes;
}
png_read_image(png_ptr, row_pointers);
png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
delete[] row_pointers;
}
PNGImage::PNGImage(const char *image) {
FILE *f = fopen(image, "r");
if (!f) {
throw std::runtime_error("fopen problem");
}
new (this) PNGImage(f);
fclose(f);
}
RAWImage::RAWImage(const char *image) {
FILE *f = fopen(image, "r");
if (!f) {
throw std::runtime_error("fopen problem");
}
uint32_t pitch = 0;
color_channels = 4;
fread(&pitch, sizeof(uint32_t), 1, f);
size.x = pitch / color_channels;
fread(&(size.y), sizeof(uint32_t), 1, f);
raw = new uint8_t[pitch * size.y];
fread(raw, pitch * size.y, 1, f);
fclose(f);
} | 33.112069 | 120 | 0.643062 | ceilors |
cd07399a444da03fe90d7ff64b4f8cda126e7c00 | 93 | cpp | C++ | src/ListItem.cpp | timre13/list-maker | ebedbfcefa626af98f746c16fd46f6dafa81d70b | [
"BSD-2-Clause"
] | null | null | null | src/ListItem.cpp | timre13/list-maker | ebedbfcefa626af98f746c16fd46f6dafa81d70b | [
"BSD-2-Clause"
] | null | null | null | src/ListItem.cpp | timre13/list-maker | ebedbfcefa626af98f746c16fd46f6dafa81d70b | [
"BSD-2-Clause"
] | null | null | null | #include "ListItem.h"
ListItem::ListItem(const Glib::ustring &text)
: m_text{text}
{
}
| 11.625 | 45 | 0.666667 | timre13 |
cd075ded8ac56c4fb695c84cc0826915b32f2e2f | 1,101 | hpp | C++ | src/libs/rendering/opengl/Shader.hpp | JKot-Coder/OpenDemo | 8b9554914f5bab08df47e032486ca668a560c97c | [
"BSD-3-Clause"
] | null | null | null | src/libs/rendering/opengl/Shader.hpp | JKot-Coder/OpenDemo | 8b9554914f5bab08df47e032486ca668a560c97c | [
"BSD-3-Clause"
] | null | null | null | src/libs/rendering/opengl/Shader.hpp | JKot-Coder/OpenDemo | 8b9554914f5bab08df47e032486ca668a560c97c | [
"BSD-3-Clause"
] | null | null | null | #pragma once
#include "common/Math.hpp"
#include "rendering/Shader.hpp"
#include "rendering/opengl/Render.hpp"
namespace OpenDemo
{
namespace Common
{
class Stream;
}
namespace Rendering
{
namespace OpenGL
{
class Shader final : public Rendering::Shader
{
public:
Shader();
virtual ~Shader() override;
virtual bool LinkSource(const std::shared_ptr<Stream>& stream) override;
virtual void Bind() const override;
virtual void SetParam(Uniform::Type uType, const Vector4& value, int count = 1) const override;
virtual void SetParam(Uniform::Type uType, const Matrix4& value, int count = 1) const override;
//virtual void SetParam(Uniform::Type uType, const Common::Basis& value, int count = 1) const override;
private:
GLuint _id;
std::array<GLint, Uniform::UNIFORM_MAX> _uniformID = {};
bool checkLink() const;
};
}
}
} | 27.525 | 119 | 0.563124 | JKot-Coder |
9984044eea45e1b83c9dceed6ecad4d015ca9e56 | 1,433 | hxx | C++ | src/control/ai/mod_attack/aim_basic_aim.hxx | AltSysrq/Abendstern | 106e1ad2457f7bfd90080eecf49a33f6079f8e1e | [
"BSD-3-Clause"
] | null | null | null | src/control/ai/mod_attack/aim_basic_aim.hxx | AltSysrq/Abendstern | 106e1ad2457f7bfd90080eecf49a33f6079f8e1e | [
"BSD-3-Clause"
] | null | null | null | src/control/ai/mod_attack/aim_basic_aim.hxx | AltSysrq/Abendstern | 106e1ad2457f7bfd90080eecf49a33f6079f8e1e | [
"BSD-3-Clause"
] | 1 | 2022-01-29T11:54:41.000Z | 2022-01-29T11:54:41.000Z | /**
* @file
* @author Jason Lingle
* @brief Contains class AIM_BasicAim AI module
*/
#ifndef AIM_BASIC_AIM_HXX_
#define AIM_BASIC_AIM_HXX_
#include <libconfig.h++>
#include "src/control/ai/aimod.hxx"
/**
* attack/basic_aim: Aim at the target, leading it as necessary.
*
* Set throttle according to normalised dot-
* product between target facing us and
* the vector between the target and us.
* @section config Configuration
* <table>
* <tr>
* <td>attack_speed</td> <td>float</td>
* <td>Indicates appropriate speed for attacking. Defaults to 0.0005f.</td>
* </tr>
* </table>
*
* @section svars State Variables
* <table>
* <tr>
* <td>suggest_target_offset_x</td><td>float</td> <td>Offset to add to target X. Defaults to 0.0f.</td>
* </tr><tr>
* <td>suggest_target_offset_y</td><td>float</td> <td>Offset to add to target Y. Defaults to 0.0f.</td>
* </tr><tr>
* <td>suggest_angle_offset</td> <td>float</td> <td>Offset to add to angle to target. Defaults to 0.0f</td>
* </tr><tr>
* <td>shot_quality</td> <td>float</td> <td>
* 1.0 indicates perfect shot; anything less than 0 indicates
* no chance of hitting </td>
* </tr>
* </table>
*/
class AIM_BasicAim: public AIModule {
float speed;
public:
/** AIM standard constructor. */
AIM_BasicAim(AIControl*, const libconfig::Setting&);
virtual void action();
};
#endif /* AIM_BASIC_AIM_HXX_ */
| 28.098039 | 112 | 0.653873 | AltSysrq |
998970e62a1f1f755dea91147fecaf6cd2fabf1e | 951 | cpp | C++ | worker/src/Master/Worker/ChannelRequest.cpp | idarkblue/mediasoup | f77bbd3680c122a2a4f15836b746e53e4b8571d0 | [
"0BSD"
] | null | null | null | worker/src/Master/Worker/ChannelRequest.cpp | idarkblue/mediasoup | f77bbd3680c122a2a4f15836b746e53e4b8571d0 | [
"0BSD"
] | null | null | null | worker/src/Master/Worker/ChannelRequest.cpp | idarkblue/mediasoup | f77bbd3680c122a2a4f15836b746e53e4b8571d0 | [
"0BSD"
] | null | null | null | #include "ChannelRequest.hpp"
namespace pingos {
uint64_t ChannelRequest::requestId = 0;
ChannelRequest::ChannelRequest(const std::string method)
{
this->Init(method);
}
ChannelRequest::~ChannelRequest()
{
}
void ChannelRequest::Init(const std::string method)
{
this->id = ChannelRequest::requestId++;
this->method = method;
this->jsonInternal = json::object();
this->jsonData = json::object();
}
void ChannelRequest::SetInternal(json &jsonObject)
{
this->jsonInternal = jsonObject;
}
void ChannelRequest::SetData(json &jsonObject)
{
this->jsonData = jsonObject;
}
uint64_t ChannelRequest::GetId()
{
return this->id;
}
std::string ChannelRequest::GetMethod()
{
return this->method;
}
void ChannelRequest::FillJson(json &jsonObject)
{
jsonObject["id"] = this->id;
jsonObject["method"] = this->method;
jsonObject["internal"] = this->jsonInternal;
jsonObject["data"] = this->jsonData;
}
}
| 17.290909 | 56 | 0.690852 | idarkblue |
998e46cb8284e5a536e1004b5bdda5eb677c2edc | 5,588 | cpp | C++ | Sources/Application/Application.cpp | ValentinCamus/GIR-Engine | 1aa8f6d44f65a00bc19e932ecd5ce98136015ee0 | [
"MIT"
] | 4 | 2020-01-21T14:51:29.000Z | 2020-02-26T17:02:40.000Z | Sources/Application/Application.cpp | ValentinCamus/GIR-Engine | 1aa8f6d44f65a00bc19e932ecd5ce98136015ee0 | [
"MIT"
] | null | null | null | Sources/Application/Application.cpp | ValentinCamus/GIR-Engine | 1aa8f6d44f65a00bc19e932ecd5ce98136015ee0 | [
"MIT"
] | 3 | 2020-02-18T10:55:46.000Z | 2021-11-14T12:02:44.000Z | #include "Application.hpp"
#include <IO/FileSystem/FileSystem.hpp>
#include <IO/Loader/ModelLoader.hpp>
#include <IO/Loader/SceneLoader.hpp>
#include <Engine/Camera/Camera.hpp>
#include <Engine/Light/DirectionalLight.hpp>
#include <Engine/Light/SpotLight.hpp>
#include <Engine/Light/PointLight.hpp>
#include <IO/Saver/ImageWriter.hpp>
#define INITIAL_VIEWPORT_WIDTH 500
#define INITIAL_VIEWPORT_HEIGHT 500
namespace gir
{
Application::Application(const char* name, unsigned int width, unsigned int height)
{
// Initialize GLFW window
m_window.Init(name, width, height);
m_window.SetupEventsCallback(this);
}
void Application::Run()
{
m_isRunning = true;
m_gui.Init(m_window.Get());
m_input.Init(m_window.Get());
while (m_isRunning)
{
// Per-frame time logic
auto currentTime = m_window.GetTime();
auto deltaTime = float(m_time - currentTime);
m_time = currentTime;
m_window.PollEvents();
Prepare(deltaTime);
Draw(deltaTime);
m_gui.BeginFrame();
ImGuiDraw(deltaTime);
m_gui.EndFrame();
m_window.SwapBuffers();
}
m_gui.Shutdown();
m_window.Shutdown();
}
void Application::Stop() { m_isRunning = false; }
void Application::Setup()
{
m_viewport.Init(INITIAL_VIEWPORT_WIDTH, INITIAL_VIEWPORT_HEIGHT);
m_scene = SceneLoader::Load(FileSystem::GetProjectDir() + "/Scenes/Sponza.json");
m_renderer = std::make_unique<Renderer>(static_cast<ERenderMode>(m_lightingWidget.GetLightingMode()),
INITIAL_VIEWPORT_WIDTH,
INITIAL_VIEWPORT_HEIGHT);
}
void Application::Shutdown() { m_viewport.Shutdown(); }
void Application::Prepare(float deltaTime)
{
m_cameraController.SetCamera(&m_scene->GetCamera());
bool dragging = m_input.IsMouseButtonPressed(GLFW_MOUSE_BUTTON_MIDDLE);
if (dragging && !m_cameraController.isMouseDragged())
m_cameraController.SetMousePosition(m_input.GetMouseX(), m_input.GetMouseY());
m_cameraController.SetMouseDragged(dragging);
if (m_input.IsKeyPressed(GLFW_KEY_W)) m_cameraController.MoveForward(deltaTime);
if (m_input.IsKeyPressed(GLFW_KEY_S)) m_cameraController.MoveBackward(deltaTime);
if (m_input.IsKeyPressed(GLFW_KEY_D)) m_cameraController.MoveRight(deltaTime);
if (m_input.IsKeyPressed(GLFW_KEY_A)) m_cameraController.MoveLeft(deltaTime);
if (m_input.IsKeyPressed(GLFW_KEY_Q)) m_cameraController.MoveUp(deltaTime);
if (m_input.IsKeyPressed(GLFW_KEY_E)) m_cameraController.MoveDown(deltaTime);
// Reload shaders
if (m_input.IsKeyPressed(GLFW_KEY_F5))
{
unsigned width = m_viewport.GetFramebuffer()->GetTexture(0)->GetWidth();
unsigned height = m_viewport.GetFramebuffer()->GetTexture(0)->GetHeight();
m_renderer =
std::make_unique<Renderer>(static_cast<ERenderMode>(m_lightingWidget.GetLightingMode()), width, height);
}
if (m_input.IsKeyPressed(GLFW_KEY_F6))
{
Framebuffer* framebuffer = m_viewport.GetFramebuffer();
framebuffer->Bind();
ImageWriter::Save(framebuffer, false);
framebuffer->Unbind();
}
}
void Application::Draw(float deltaTime)
{
unsigned viewportWidth = m_viewport.GetFramebuffer()->GetTexture(0)->GetWidth();
unsigned viewportHeight = m_viewport.GetFramebuffer()->GetTexture(0)->GetHeight();
Camera& camera = m_scene->GetCamera();
if (camera.GetWidth() != viewportWidth || camera.GetHeight() != viewportHeight)
{
camera.SetWidth(viewportWidth);
camera.SetHeight(viewportHeight);
m_renderer->ResizeGBuffer(viewportWidth, viewportHeight);
}
m_renderer->SetRenderMode(static_cast<ERenderMode>(m_lightingWidget.GetLightingMode()));
m_renderer->Draw(m_viewport.GetFramebuffer(), m_scene.get());
}
void Application::ImGuiDraw(float deltaTime)
{
const Camera& camera = m_scene->GetCamera();
SceneComponent* selectedComponent = m_sceneWidget.GetSelectedComponent();
m_sceneWidget.SetScene(m_scene.get());
m_transformEditor.SetSceneComponent(selectedComponent);
m_lightingWidget.SetLight(dynamic_cast<Light*>(selectedComponent));
m_viewport.DrawGizmo(camera.GetProjectionMatrix(), camera.GetViewMatrix(), selectedComponent);
m_viewport.Draw();
m_lightingWidget.Draw();
m_statsWidget.Draw();
m_transformEditor.Draw();
m_sceneWidget.Draw();
}
void Application::OnWindowClosed() { Stop(); }
void Application::OnMouseMoved(double xPos, double yPos)
{
if (m_scene)
{
if (m_input.IsMouseButtonPressed(GLFW_MOUSE_BUTTON_3))
{
m_cameraController.SetCamera(&m_scene->GetCamera());
m_cameraController.DragMouse(static_cast<float>(xPos), static_cast<float>(yPos));
}
}
}
void Application::OnMouseScrolled(double xOffset, double yOffset)
{
if (m_scene)
{
m_cameraController.SetCamera(&m_scene->GetCamera());
m_cameraController.Zoom(static_cast<float>(yOffset));
}
}
} // namespace gir | 34.073171 | 120 | 0.641911 | ValentinCamus |
998ed94ee96719c741e7161c3217b8f0d3eb4761 | 512 | cpp | C++ | 2021/day04/part1.cpp | mfederczuk/advent-of-code-2020 | 4406692ee1c63b00a9c83029b15c857eed86432e | [
"Apache-2.0"
] | 2 | 2021-01-11T17:46:19.000Z | 2021-01-11T17:47:07.000Z | 2021/day04/part1.cpp | mfederczuk/advent-of-code-2020 | 4406692ee1c63b00a9c83029b15c857eed86432e | [
"Apache-2.0"
] | null | null | null | 2021/day04/part1.cpp | mfederczuk/advent-of-code-2020 | 4406692ee1c63b00a9c83029b15c857eed86432e | [
"Apache-2.0"
] | 1 | 2020-12-02T16:00:59.000Z | 2020-12-02T16:00:59.000Z | /*
* Copyright (c) 2021 Michael Federczuk
*
* SPDX-License-Identifier: MPL-2.0 AND Apache-2.0
*/
#include "../aoc2021.hpp"
#include "bingo_board.hpp"
#include "day04_utils.hpp"
#include <istream>
aoc2021::ANSWER aoc2021::solution(std::istream& input_file) {
day04_input input;
input_file >> input;
for(const int nr : input.get_nrs()) {
for(bingo_board& board : input.get_boards()) {
board.mark(nr);
if(board.has_bingo()) {
return board.calculate_score(nr);
}
}
}
return INVALID;
}
| 18.285714 | 61 | 0.675781 | mfederczuk |
998f107ecfff40c1742923247548e102dd20d1ad | 2,370 | cpp | C++ | 33.park/33.cpp | teryokhin/bsu-famcs-algo-solutions | 69fe6b08f1836aa04c3bab85ab975593182aa0ea | [
"MIT"
] | null | null | null | 33.park/33.cpp | teryokhin/bsu-famcs-algo-solutions | 69fe6b08f1836aa04c3bab85ab975593182aa0ea | [
"MIT"
] | null | null | null | 33.park/33.cpp | teryokhin/bsu-famcs-algo-solutions | 69fe6b08f1836aa04c3bab85ab975593182aa0ea | [
"MIT"
] | null | null | null | #include <iostream>
#include <fstream>
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <climits>
#include <vector>
#include <iomanip>
#include <algorithm>
#include <string>
#include <stack>
#include <ctime>
#include <queue>
#include <set>
#include <map>
#define INF 2000000011
typedef long long ll;
using namespace std;
struct Tree {
Tree* next;
Tree* prev;
int x, y;
Tree(int x, int y, Tree* prev, Tree* next): x(x), y(y), prev(prev), next(next) {}
};
int main()
{
cin.tie(0);
ios_base::sync_with_stdio(false);
//#ifndef _DEBUG
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
//#endif // _DEBUG
int n, x, y, parkX, parkY;
cin >> n >> parkX >> parkY;
vector< pair<int, int> > trees;
trees.reserve(n);
set<int> yCoords;
yCoords.insert(0); yCoords.insert(parkY);
for (int i = 0; i < n; i++) {
cin >> x >> y;
trees.push_back(make_pair(x, y));
yCoords.insert(y);
}
sort(trees.begin(), trees.end());
int maxRect = 0;
Tree* lastTree;
map<int, vector<Tree*> > treesByY;
for (auto y1=yCoords.begin(); y1 != yCoords.end(); y1++){
int maxDeltaX = 0;
treesByY.clear();
lastTree = new Tree(0, *y1, nullptr, nullptr);
for (auto tree: trees)
if (tree.second > *y1){
maxDeltaX = max(maxDeltaX, tree.first-lastTree->x);
lastTree->next = new Tree(tree.first, tree.second, lastTree, nullptr);
treesByY[tree.second].push_back(lastTree->next);
lastTree = lastTree->next;
}
maxDeltaX = max(maxDeltaX, parkX-lastTree->x);
lastTree->next = new Tree(parkX, *y1, lastTree, nullptr);
lastTree = lastTree->next;
maxRect = max(maxRect, (parkY-*y1)*maxDeltaX);
for (auto y2=yCoords.rbegin(); *y2 != *y1; y2++){
for (Tree* tree_ptr : treesByY[*y2]) {
Tree* prev = tree_ptr->prev;
Tree* next = tree_ptr->next;
maxDeltaX = max(maxDeltaX, next->x - prev->x);
prev->next = next;
next->prev = prev;
delete tree_ptr;
}
maxRect = max(maxRect, (*y2-*y1)*maxDeltaX);
}
}
cout << maxRect;
return 0;
} | 26.333333 | 86 | 0.546414 | teryokhin |
999040a7db7e79da384f98037cf3f835a1bcafbc | 21,563 | cc | C++ | src/atlas/meshgenerator/RegularMeshGenerator.cc | mlange05/atlas | d8198435a9e39fbf67bfc467fe734203414af608 | [
"Apache-2.0"
] | null | null | null | src/atlas/meshgenerator/RegularMeshGenerator.cc | mlange05/atlas | d8198435a9e39fbf67bfc467fe734203414af608 | [
"Apache-2.0"
] | null | null | null | src/atlas/meshgenerator/RegularMeshGenerator.cc | mlange05/atlas | d8198435a9e39fbf67bfc467fe734203414af608 | [
"Apache-2.0"
] | null | null | null |
#include <algorithm>
#include <cmath>
#include <limits>
#include <numeric>
#include <vector>
#include "eckit/utils/Hash.h"
#include "atlas/array/Array.h"
#include "atlas/array/ArrayView.h"
#include "atlas/array/IndexView.h"
#include "atlas/field/Field.h"
#include "atlas/grid/Distribution.h"
#include "atlas/grid/Grid.h"
#include "atlas/grid/Partitioner.h"
#include "atlas/library/config.h"
#include "atlas/mesh/ElementType.h"
#include "atlas/mesh/Elements.h"
#include "atlas/mesh/HybridElements.h"
#include "atlas/mesh/Mesh.h"
#include "atlas/mesh/Nodes.h"
#include "atlas/meshgenerator/RegularMeshGenerator.h"
#include "atlas/parallel/mpi/mpi.h"
#include "atlas/runtime/Log.h"
#include "atlas/util/CoordinateEnums.h"
#define DEBUG_OUTPUT 0
#define DEBUG_OUTPUT_DETAIL 0
using Topology = atlas::mesh::Nodes::Topology;
namespace atlas {
namespace meshgenerator {
RegularMeshGenerator::RegularMeshGenerator( const eckit::Parametrisation& p ) {
configure_defaults();
// options copied from Structured MeshGenerator
size_t nb_parts;
if ( p.get( "nb_parts", nb_parts ) ) options.set( "nb_parts", nb_parts );
size_t part;
if ( p.get( "part", part ) ) options.set( "part", part );
std::string partitioner;
if ( p.get( "partitioner", partitioner ) ) {
if ( not grid::Partitioner::exists( partitioner ) ) {
Log::warning() << "Atlas does not have support for partitioner " << partitioner << ". "
<< "Defaulting to use partitioner EqualRegions" << std::endl;
partitioner = "equal_regions";
}
options.set( "partitioner", partitioner );
}
// options specifically for this MeshGenerator
bool periodic_x;
if ( p.get( "periodic_x", periodic_x ) ) options.set( "periodic_x", periodic_x );
bool periodic_y;
if ( p.get( "periodic_y", periodic_y ) ) options.set( "periodic_y", periodic_y );
bool biperiodic;
if ( p.get( "biperiodic", biperiodic ) ) {
options.set( "periodic_x", biperiodic );
options.set( "periodic_y", biperiodic );
}
}
void RegularMeshGenerator::configure_defaults() {
// This option sets number of parts the mesh will be split in
options.set( "nb_parts", mpi::comm().size() );
// This option sets the part that will be generated
options.set( "part", mpi::comm().rank() );
// This options sets the default partitioner
std::string partitioner;
if ( grid::Partitioner::exists( "trans" ) && mpi::comm().size() > 1 )
partitioner = "trans";
else
partitioner = "checkerboard";
options.set<std::string>( "partitioner", partitioner );
// Options for for periodic grids
options.set<bool>( "periodic_x", false );
options.set<bool>( "periodic_y", false );
}
void RegularMeshGenerator::generate( const Grid& grid, Mesh& mesh ) const {
ASSERT( !mesh.generated() );
const grid::RegularGrid rg = grid::RegularGrid( grid );
if ( !rg ) throw eckit::BadCast( "RegularMeshGenerator can only work with a Regular grid", Here() );
size_t nb_parts = options.get<size_t>( "nb_parts" );
std::string partitioner_type = "checkerboard";
options.get( "checkerboard", partitioner_type );
// if ( rg->nlat()%2 == 1 ) partitioner_factory = "equal_regions"; // Odd
// number of latitudes
// if ( nb_parts == 1 || eckit::mpi::size() == 1 ) partitioner_factory =
// "equal_regions"; // Only one part --> Trans is slower
grid::Partitioner partitioner( partitioner_type, nb_parts );
grid::Distribution distribution( partitioner.partition( grid ) );
generate( grid, distribution, mesh );
}
void RegularMeshGenerator::hash( eckit::Hash& h ) const {
h.add( "RegularMeshGenerator" );
options.hash( h );
}
void RegularMeshGenerator::generate( const Grid& grid, const grid::Distribution& distribution, Mesh& mesh ) const {
const grid::RegularGrid rg = grid::RegularGrid( grid );
if ( !rg ) throw eckit::BadCast( "Grid could not be cast to a Regular", Here() );
ASSERT( !mesh.generated() );
if ( grid.size() != distribution.partition().size() ) {
std::stringstream msg;
msg << "Number of points in grid (" << grid.size()
<< ") different from "
"number of points in grid distribution ("
<< distribution.partition().size() << ")";
throw eckit::AssertionFailed( msg.str(), Here() );
}
// clone some grid properties
setGrid( mesh, rg, distribution );
generate_mesh( rg, distribution, mesh );
}
void RegularMeshGenerator::generate_mesh( const grid::RegularGrid& rg, const std::vector<int>& parts,
// const Region& region,
Mesh& mesh ) const {
int mypart = options.get<size_t>( "part" );
int nparts = options.get<size_t>( "nb_parts" );
int nx = rg.nx();
int ny = rg.ny();
bool periodic_x = options.get<bool>( "periodic_x" ) or rg.periodic();
bool periodic_y = options.get<bool>( "periodic_y" );
Log::debug() << Here() << " periodic_x = " << periodic_x << std::endl;
Log::debug() << Here() << " periodic_y = " << periodic_y << std::endl;
// for asynchronous output
#if DEBUG_OUTPUT
sleep( mypart );
#endif
// this function should do the following:
// - define nodes with
// mesh.nodes().resize(nnodes);
// mesh::Nodes& nodes = mesh.nodes();
// following properties should be defined:
// array::ArrayView<double,2> xy ( nodes.xy() );
// array::ArrayView<gidx_t,1> glb_idx ( nodes.global_index() );
// array::ArrayView<int, 1> part ( nodes.partition() );
// array::ArrayView<int, 1> ghost ( nodes.ghost() );
// array::ArrayView<int, 1> flags ( nodes.flags() );
// - define cells (only quadrilaterals for now) with
// mesh.cells().add( new mesh::temporary::Quadrilateral(), nquads );
// further define cells with
// array::ArrayView<gidx_t,1> cells_glb_idx( mesh.cells().global_index()
// );
// array::ArrayView<int,1> cells_part( mesh.cells().partition() );
// - define connectivity with
// mesh::HybridElements::Connectivity& node_connectivity =
// mesh.cells().node_connectivity();
// node_connectivity.set( jcell, quad_nodes );
// where quad_nodes is a 4-element integer array containing the LOCAL
// indices of the nodes
// Start with calculating number of quadrilaterals
// The rule do determine if a cell belongs to a proc is the following: if the
// lowerleft corner of the cell belongs to that proc.
// so we loop over all gridpoints, select those that belong to the proc, and
// determine the number of cells
int ii_glb; // global index
int ncells;
// vector of local indices: necessary for remote indices of ghost nodes
std::vector<int> local_idx( rg.size(), -1 );
std::vector<int> current_idx( nparts, 0 ); // index counter for each proc
// determine rectangle (ix_min:ix_max) x (iy_min:iy_max) surrounding the nodes
// on this processor
int ix_min, ix_max, iy_min, iy_max, ix_glb, iy_glb, ix, iy;
int nnodes_nonghost, nnodes; // number of nodes: non-ghost; total; inside
// surrounding rectangle
int nnodes_SR, ii;
// loop over all points to determine local indices and surroundig rectangle
ix_min = nx + 1;
ix_max = 0;
iy_min = ny + 1;
iy_max = 0;
nnodes_nonghost = 0;
ii_glb = 0;
for ( iy = 0; iy < ny; iy++ ) {
for ( ix = 0; ix < nx; ix++ ) {
local_idx[ii_glb] = current_idx[parts[ii_glb]]++; // store local index on
// the local proc of
// this point
if ( parts[ii_glb] == mypart ) {
++nnodes_nonghost; // non-ghost node: belongs to this part
ix_min = std::min( ix_min, ix );
ix_max = std::max( ix_max, ix );
iy_min = std::min( iy_min, iy );
iy_max = std::max( iy_max, iy );
}
++ii_glb; // global index
}
}
// add one row/column for ghost nodes (which include periodicity points)
ix_max = ix_max + 1;
iy_max = iy_max + 1;
#if DEBUG_OUTPUT_DETAIL
std::cout << "[" << mypart << "] : "
<< "SR = " << ix_min << ":" << ix_max << " x " << iy_min << ":" << iy_max << std::endl;
#endif
// dimensions of surrounding rectangle (SR)
int nxl = ix_max - ix_min + 1;
int nyl = iy_max - iy_min + 1;
// upper estimate for number of nodes
nnodes_SR = nxl * nyl;
// partitions and local indices in SR
std::vector<int> parts_SR( nnodes_SR, -1 );
std::vector<int> local_idx_SR( nnodes_SR, -1 );
std::vector<bool> is_ghost_SR( nnodes_SR, true );
ii = 0; // index inside SR
for ( iy = 0; iy < nyl; iy++ ) {
iy_glb = ( iy_min + iy ); // global y-index
for ( ix = 0; ix < nxl; ix++ ) {
ix_glb = ( ix_min + ix ); // global x-index
is_ghost_SR[ii] = !( ( parts_SR[ii] == mypart ) && ix < nxl - 1 && iy < nyl - 1 );
if ( ix_glb < nx && iy_glb < ny ) {
ii_glb = (iy_glb)*nx + ix_glb; // global index
parts_SR[ii] = parts[ii_glb];
local_idx_SR[ii] = local_idx[ii_glb];
is_ghost_SR[ii] = !( ( parts_SR[ii] == mypart ) && ix < nxl - 1 && iy < nyl - 1 );
}
else if ( ix_glb == nx && iy_glb < ny ) {
// take properties from the point to the left
parts_SR[ii] = parts[iy_glb * nx + ix_glb - 1];
local_idx_SR[ii] = -1;
is_ghost_SR[ii] = true;
}
else if ( iy_glb == ny && ix_glb < nx ) {
// take properties from the point below
parts_SR[ii] = parts[( iy_glb - 1 ) * nx + ix_glb];
local_idx_SR[ii] = -1;
is_ghost_SR[ii] = true;
}
else {
// take properties from the point belowleft
parts_SR[ii] = parts[( iy_glb - 1 ) * nx + ix_glb - 1];
local_idx_SR[ii] = -1;
is_ghost_SR[ii] = true;
}
++ii;
}
}
#if DEBUG_OUTPUT_DETAIL
std::cout << "[" << mypart << "] : "
<< "parts_SR = ";
for ( ii = 0; ii < nnodes_SR; ii++ )
std::cout << parts_SR[ii] << ",";
std::cout << std::endl;
std::cout << "[" << mypart << "] : "
<< "local_idx_SR = ";
for ( ii = 0; ii < nnodes_SR; ii++ )
std::cout << local_idx_SR[ii] << ",";
std::cout << std::endl;
std::cout << "[" << mypart << "] : "
<< "is_ghost_SR = ";
for ( ii = 0; ii < nnodes_SR; ii++ )
std::cout << is_ghost_SR[ii] << ",";
std::cout << std::endl;
#endif
// vectors marking nodes that are necessary for this proc's cells
std::vector<bool> is_node_SR( nnodes_SR, false );
// determine number of cells and number of nodes
nnodes = 0;
ncells = 0;
for ( iy = 0; iy < nyl - 1; iy++ ) { // don't loop into ghost/periodicity row
for ( ix = 0; ix < nxl - 1; ix++ ) { // don't loop into ghost/periodicity column
ii = iy * nxl + ix;
if ( !is_ghost_SR[ii] ) {
// mark this node as being used
if ( !is_node_SR[ii] ) {
++nnodes;
is_node_SR[ii] = true;
}
// check if this node is the lowerleft corner of a new cell
if ( ( ix_min + ix < nx - 1 || periodic_x ) && ( iy_min + iy < ny - 1 || periodic_y ) ) {
++ncells;
// mark lowerright corner
ii = iy * nxl + ix + 1;
if ( !is_node_SR[ii] ) {
++nnodes;
is_node_SR[ii] = true;
}
// mark upperleft corner
ii = ( iy + 1 ) * nxl + ix;
if ( !is_node_SR[ii] ) {
++nnodes;
is_node_SR[ii] = true;
}
// mark upperright corner
ii = ( iy + 1 ) * nxl + ix + 1;
if ( !is_node_SR[ii] ) {
++nnodes;
is_node_SR[ii] = true;
}
}
// periodic points are always needed, even if they don't belong to a
// cell
ii = iy * nxl + ix + 1;
if ( periodic_x && ix_min + ix == nx - 1 && !is_node_SR[ii] ) {
++nnodes;
is_node_SR[ii] = true;
}
ii = ( iy + 1 ) * nxl + ix;
if ( periodic_y && iy_min + iy == ny - 1 && !is_node_SR[ii] ) {
++nnodes;
is_node_SR[ii] = true;
}
ii = ( iy + 1 ) * nxl + ix + 1;
if ( periodic_x && periodic_y && ix_min + ix == nx - 1 && iy_min + iy == ny - 1 && !is_node_SR[ii] ) {
++nnodes;
is_node_SR[ii] = true;
}
}
}
}
#if DEBUG_OUTPUT_DETAIL
std::cout << "[" << mypart << "] : "
<< "nnodes = " << nnodes << std::endl;
std::cout << "[" << mypart << "] : "
<< "is_node_SR = ";
for ( ii = 0; ii < nnodes_SR; ii++ )
std::cout << is_node_SR[ii] << ",";
std::cout << std::endl;
#endif
// define nodes and associated properties
mesh.nodes().resize( nnodes );
mesh::Nodes& nodes = mesh.nodes();
auto xy = array::make_view<double, 2>( nodes.xy() );
auto lonlat = array::make_view<double, 2>( nodes.lonlat() );
auto glb_idx = array::make_view<gidx_t, 1>( nodes.global_index() );
auto remote_idx = array::make_indexview<idx_t, 1>( nodes.remote_index() );
auto part = array::make_view<int, 1>( nodes.partition() );
auto ghost = array::make_view<int, 1>( nodes.ghost() );
auto flags = array::make_view<int, 1>( nodes.flags() );
// define cells and associated properties
mesh.cells().add( new mesh::temporary::Quadrilateral(), ncells );
int quad_begin = mesh.cells().elements( 0 ).begin();
auto cells_part = array::make_view<int, 1>( mesh.cells().partition() );
mesh::HybridElements::Connectivity& node_connectivity = mesh.cells().node_connectivity();
idx_t quad_nodes[4];
int jcell = quad_begin;
int inode, inode_nonghost, inode_ghost;
// global indices for periodicity points
inode = nx * ny;
std::vector<int> glb_idx_px( ny + 1, -1 );
std::vector<int> glb_idx_py( nx + 1, -1 );
if ( periodic_x ) {
for ( iy = 0; iy < ny + ( periodic_y ? 1 : 0 ); iy++ ) {
glb_idx_px[iy] = inode++;
}
}
if ( periodic_y ) {
for ( ix = 0; ix < nx; ix++ ) {
glb_idx_py[ix] = inode++;
}
}
// loop over nodes and set properties
ii = 0;
inode_nonghost = 0;
inode_ghost = nnodes_nonghost; // ghost nodes start counting after nonghost nodes
for ( iy = 0; iy < nyl; iy++ ) {
for ( ix = 0; ix < nxl; ix++ ) {
// node properties
if ( is_node_SR[ii] ) {
// set node counter
if ( is_ghost_SR[ii] ) { inode = inode_ghost++; }
else {
inode = inode_nonghost++;
}
// global index
ix_glb = ( ix_min + ix ); // don't take modulus here: periodicity points
// have their own global index.
iy_glb = ( iy_min + iy );
if ( ix_glb < nx && iy_glb < ny ) {
ii_glb = iy_glb * nx + ix_glb; // no periodic point
}
else {
if ( ix_glb == nx ) {
// periodicity point in x-direction
ii_glb = glb_idx_px[iy_glb];
}
else {
// periodicity point in x-direction
ii_glb = glb_idx_py[ix_glb];
}
}
glb_idx( inode ) = ii_glb + 1; // starting from 1
// grid coordinates
double _xy[2];
if ( iy_glb < ny ) {
// normal calculation
rg.xy( ix_glb, iy_glb, _xy );
}
else {
// for periodic_y grids, iy_glb==ny lies outside the range of
// latitudes in the Structured grid...
// so we extrapolate from two other points -- this is okay for regular
// grids with uniform spacing.
double xy1[2], xy2[2];
rg.xy( ix_glb, iy_glb - 1, xy1 );
rg.xy( ix_glb, iy_glb - 2, xy2 );
_xy[0] = 2 * xy1[0] - xy2[0];
_xy[1] = 2 * xy1[1] - xy2[1];
}
xy( inode, LON ) = _xy[LON];
xy( inode, LAT ) = _xy[LAT];
// geographic coordinates by using projection
rg.projection().xy2lonlat( _xy );
lonlat( inode, LON ) = _xy[LON];
lonlat( inode, LAT ) = _xy[LAT];
// part
part( inode ) = parts_SR[ii];
// ghost nodes
ghost( inode ) = is_ghost_SR[ii];
// flags
Topology::reset( flags( inode ) );
if ( ghost( inode ) ) {
Topology::set( flags( inode ), Topology::GHOST );
remote_idx( inode ) = local_idx_SR[ii];
// change local index -- required for cells
local_idx_SR[ii] = inode;
}
else {
remote_idx( inode ) = -1;
}
#if DEBUG_OUTPUT_DETAIL
std::cout << "[" << mypart << "] : "
<< "New node "
<< "\n\t";
std::cout << "[" << mypart << "] : "
<< "\tinode=" << inode << "; ix_glb=" << ix_glb << "; iy_glb=" << iy_glb
<< "; glb_idx=" << ii_glb << std::endl;
std::cout << "[" << mypart << "] : "
<< "\tglon=" << lonlat( inode, 0 ) << "; glat=" << lonlat( inode, 1 )
<< "; glb_idx=" << glb_idx( inode ) << std::endl;
#endif
}
++ii;
}
}
// loop over nodes and define cells
for ( iy = 0; iy < nyl - 1; iy++ ) { // don't loop into ghost/periodicity row
for ( ix = 0; ix < nxl - 1; ix++ ) { // don't loop into ghost/periodicity column
ii = iy * nxl + ix;
if ( !is_ghost_SR[ii] ) {
if ( ( ix_min + ix < nx - 1 || periodic_x ) && ( iy_min + iy < ny - 1 || periodic_y ) ) {
// define cell corners (local indices)
quad_nodes[0] = local_idx_SR[ii];
quad_nodes[3] = local_idx_SR[iy * nxl + ix + 1]; // point to the right
quad_nodes[2] = local_idx_SR[( iy + 1 ) * nxl + ix + 1]; // point above right
quad_nodes[1] = local_idx_SR[( iy + 1 ) * nxl + ix]; // point above
node_connectivity.set( jcell, quad_nodes );
cells_part( jcell ) = mypart;
#if DEBUG_OUTPUT_DETAIL
std::cout << "[" << mypart << "] : "
<< "New quad " << jcell << "\n\t";
std::cout << "[" << mypart << "] : " << quad_nodes[0] << "," << quad_nodes[1] << ","
<< quad_nodes[2] << "," << quad_nodes[3] << std::endl;
#endif
++jcell;
}
}
}
}
#if DEBUG_OUTPUT
// list nodes
for ( inode = 0; inode < nnodes; inode++ ) {
std::cout << "[" << mypart << "] : "
<< " node " << inode << ": ghost = " << ghost( inode ) << ", glb_idx = " << glb_idx( inode ) - 1
<< ", part = " << part( inode ) << ", lon = " << lonlat( inode, 0 )
<< ", lat = " << lonlat( inode, 1 ) << ", remote_idx = " << remote_idx( inode ) << std::endl;
}
int* cell_nodes;
for ( jcell = 0; jcell < ncells; jcell++ ) {
std::cout << "[" << mypart << "] : "
<< " cell " << jcell << ": " << node_connectivity( jcell, 0 ) << "," << node_connectivity( jcell, 1 )
<< "," << node_connectivity( jcell, 2 ) << "," << node_connectivity( jcell, 3 ) << std::endl;
}
#endif
generateGlobalElementNumbering( mesh );
nodes.metadata().set( "parallel", true );
}
namespace {
static MeshGeneratorBuilder<RegularMeshGenerator> __RegularMeshGenerator( "regular" );
}
} // namespace meshgenerator
} // namespace atlas
| 40.005566 | 119 | 0.49738 | mlange05 |
9991bc1951c5eee646573b4e822efff0bc3016b3 | 13,236 | cpp | C++ | src/cpp/lib/QtWidgets/QTableWidgetItem/qtablewidgetitem_wrap.cpp | sharingcookies/nodegui | 481062423e52779ea7628999b249c1e77f7f2c6b | [
"MIT"
] | null | null | null | src/cpp/lib/QtWidgets/QTableWidgetItem/qtablewidgetitem_wrap.cpp | sharingcookies/nodegui | 481062423e52779ea7628999b249c1e77f7f2c6b | [
"MIT"
] | null | null | null | src/cpp/lib/QtWidgets/QTableWidgetItem/qtablewidgetitem_wrap.cpp | sharingcookies/nodegui | 481062423e52779ea7628999b249c1e77f7f2c6b | [
"MIT"
] | null | null | null | #include "QtWidgets/QTableWidgetItem/qtablewidgetitem_wrap.h"
#include "Extras/Utils/nutils.h"
#include "QtCore/QSize/qsize_wrap.h"
#include "QtCore/QVariant/qvariant_wrap.h"
#include "QtGui/QBrush/qbrush_wrap.h"
#include "QtGui/QFont/qfont_wrap.h"
#include "QtGui/QIcon/qicon_wrap.h"
#include "core/Component/component_wrap.h"
Napi::FunctionReference QTableWidgetItemWrap::constructor;
Napi::Object QTableWidgetItemWrap::init(Napi::Env env, Napi::Object exports) {
Napi::HandleScope scope(env);
char CLASSNAME[] = "QTableWidgetItem";
Napi::Function func = DefineClass(
env, CLASSNAME,
{InstanceMethod("row", &QTableWidgetItemWrap::row),
InstanceMethod("column", &QTableWidgetItemWrap::column),
InstanceMethod("setBackground", &QTableWidgetItemWrap::setBackground),
InstanceMethod("background", &QTableWidgetItemWrap::background),
InstanceMethod("setCheckState", &QTableWidgetItemWrap::setCheckState),
InstanceMethod("checkState", &QTableWidgetItemWrap::checkState),
InstanceMethod("setData", &QTableWidgetItemWrap::setData),
InstanceMethod("data", &QTableWidgetItemWrap::data),
InstanceMethod("setFlags", &QTableWidgetItemWrap::setFlags),
InstanceMethod("flags", &QTableWidgetItemWrap::flags),
InstanceMethod("setFont", &QTableWidgetItemWrap::setFont),
InstanceMethod("font", &QTableWidgetItemWrap::font),
InstanceMethod("setForeground", &QTableWidgetItemWrap::setForeground),
InstanceMethod("foreground", &QTableWidgetItemWrap::foreground),
InstanceMethod("setIcon", &QTableWidgetItemWrap::setIcon),
InstanceMethod("icon", &QTableWidgetItemWrap::icon),
InstanceMethod("setSelected", &QTableWidgetItemWrap::setSelected),
InstanceMethod("isSelected", &QTableWidgetItemWrap::isSelected),
InstanceMethod("setSizeHint", &QTableWidgetItemWrap::setSizeHint),
InstanceMethod("sizeHint", &QTableWidgetItemWrap::sizeHint),
InstanceMethod("setStatusTip", &QTableWidgetItemWrap::setStatusTip),
InstanceMethod("statusTip", &QTableWidgetItemWrap::statusTip),
InstanceMethod("setText", &QTableWidgetItemWrap::setText),
InstanceMethod("text", &QTableWidgetItemWrap::text),
InstanceMethod("setTextAlignment",
&QTableWidgetItemWrap::setTextAlignment),
InstanceMethod("textAlignment", &QTableWidgetItemWrap::textAlignment),
InstanceMethod("setToolTip", &QTableWidgetItemWrap::setToolTip),
InstanceMethod("toolTip", &QTableWidgetItemWrap::toolTip),
InstanceMethod("setWhatsThis", &QTableWidgetItemWrap::setWhatsThis),
InstanceMethod("whatsThis", &QTableWidgetItemWrap::whatsThis),
InstanceMethod("type$", &QTableWidgetItemWrap::type),
COMPONENT_WRAPPED_METHODS_EXPORT_DEFINE(QTableWidgetItemWrap)});
constructor = Napi::Persistent(func);
exports.Set(CLASSNAME, func);
return exports;
}
QTableWidgetItem* QTableWidgetItemWrap::getInternalInstance() {
return this->instance;
}
QTableWidgetItemWrap::~QTableWidgetItemWrap() {
if (!this->disableDeletion) {
delete this->instance;
}
}
QTableWidgetItemWrap::QTableWidgetItemWrap(const Napi::CallbackInfo& info)
: Napi::ObjectWrap<QTableWidgetItemWrap>(info) {
Napi::Env env = info.Env();
Napi::HandleScope scope(env);
if (info.Length() > 0 && info[0].IsExternal()) {
// --- if external ---
this->instance = info[0].As<Napi::External<QTableWidgetItem>>().Data();
if (info.Length() == 2) {
this->disableDeletion = info[1].As<Napi::Boolean>().Value();
}
} else {
if (info.Length() == 1) {
QString text =
QString::fromUtf8(info[0].As<Napi::String>().Utf8Value().c_str());
this->instance = new QTableWidgetItem(text);
} else if (info.Length() == 0) {
this->instance = new QTableWidgetItem();
} else {
Napi::TypeError::New(env,
"QTableWidgetItemWrap: Wrong number of arguments")
.ThrowAsJavaScriptException();
}
}
this->rawData = extrautils::configureComponent(this->getInternalInstance());
}
Napi::Value QTableWidgetItemWrap::row(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
Napi::HandleScope scope(env);
int state = static_cast<int>(this->instance->row());
return Napi::Number::New(env, state);
}
Napi::Value QTableWidgetItemWrap::column(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
Napi::HandleScope scope(env);
int state = static_cast<int>(this->instance->column());
return Napi::Number::New(env, state);
}
Napi::Value QTableWidgetItemWrap::setBackground(
const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
Napi::HandleScope scope(env);
Napi::Object brushObject = info[0].As<Napi::Object>();
QBrushWrap* brushWrap = Napi::ObjectWrap<QBrushWrap>::Unwrap(brushObject);
this->instance->setBackground(*brushWrap->getInternalInstance());
return env.Null();
}
Napi::Value QTableWidgetItemWrap::background(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
Napi::HandleScope scope(env);
QBrush brush = this->instance->background();
auto instance = QBrushWrap::constructor.New(
{Napi::External<QBrush>::New(env, new QBrush(brush))});
return instance;
}
Napi::Value QTableWidgetItemWrap::setCheckState(
const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
Napi::HandleScope scope(env);
int state = info[0].As<Napi::Number>().Int32Value();
this->instance->setCheckState(static_cast<Qt::CheckState>(state));
return env.Null();
}
Napi::Value QTableWidgetItemWrap::checkState(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
Napi::HandleScope scope(env);
int state = static_cast<int>(this->instance->checkState());
return Napi::Number::New(env, state);
}
Napi::Value QTableWidgetItemWrap::setData(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
Napi::HandleScope scope(env);
int role = info[0].As<Napi::Number>().Int32Value();
Napi::Object variantObject = info[1].As<Napi::Object>();
QVariantWrap* variantWrap =
Napi::ObjectWrap<QVariantWrap>::Unwrap(variantObject);
this->instance->setData(role, *variantWrap->getInternalInstance());
return env.Null();
}
Napi::Value QTableWidgetItemWrap::data(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
Napi::HandleScope scope(env);
int role = info[0].As<Napi::Number>().Int32Value();
QVariant data = this->instance->data(role);
auto instance = QVariantWrap::constructor.New(
{Napi::External<QVariant>::New(env, new QVariant(data))});
return instance;
}
Napi::Value QTableWidgetItemWrap::setFlags(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
Napi::HandleScope scope(env);
int flags = info[0].As<Napi::Number>().Int32Value();
this->instance->setFlags(static_cast<Qt::ItemFlags>(flags));
return env.Null();
}
Napi::Value QTableWidgetItemWrap::flags(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
Napi::HandleScope scope(env);
int flags = static_cast<int>(this->instance->flags());
return Napi::Number::New(env, flags);
}
Napi::Value QTableWidgetItemWrap::setFont(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
Napi::HandleScope scope(env);
Napi::Object fontObject = info[0].As<Napi::Object>();
QFontWrap* fontWrap = Napi::ObjectWrap<QFontWrap>::Unwrap(fontObject);
this->instance->setFont(*fontWrap->getInternalInstance());
return env.Null();
}
Napi::Value QTableWidgetItemWrap::font(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
Napi::HandleScope scope(env);
QFont font = this->instance->font();
auto instance = QFontWrap::constructor.New(
{Napi::External<QFont>::New(env, new QFont(font))});
return instance;
}
Napi::Value QTableWidgetItemWrap::setForeground(
const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
Napi::HandleScope scope(env);
Napi::Object brushObject = info[0].As<Napi::Object>();
QBrushWrap* brushWrap = Napi::ObjectWrap<QBrushWrap>::Unwrap(brushObject);
this->instance->setForeground(*brushWrap->getInternalInstance());
return env.Null();
}
Napi::Value QTableWidgetItemWrap::foreground(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
Napi::HandleScope scope(env);
QBrush brush = this->instance->foreground();
auto instance = QBrushWrap::constructor.New(
{Napi::External<QBrush>::New(env, new QBrush(brush))});
return instance;
}
Napi::Value QTableWidgetItemWrap::setIcon(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
Napi::HandleScope scope(env);
Napi::Object iconObject = info[0].As<Napi::Object>();
QIconWrap* iconWrap = Napi::ObjectWrap<QIconWrap>::Unwrap(iconObject);
this->instance->setIcon(*iconWrap->getInternalInstance());
return env.Null();
}
Napi::Value QTableWidgetItemWrap::icon(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
Napi::HandleScope scope(env);
QIcon icon = this->instance->icon();
auto instance = QIconWrap::constructor.New(
{Napi::External<QIcon>::New(env, new QIcon(icon))});
return instance;
}
Napi::Value QTableWidgetItemWrap::setSelected(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
Napi::HandleScope scope(env);
bool select = info[0].As<Napi::Boolean>().Value();
this->instance->setSelected(select);
return env.Null();
}
Napi::Value QTableWidgetItemWrap::isSelected(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
Napi::HandleScope scope(env);
return Napi::Boolean::New(env, this->instance->isSelected());
}
Napi::Value QTableWidgetItemWrap::setSizeHint(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
Napi::HandleScope scope(env);
Napi::Object sizeObject = info[0].As<Napi::Object>();
QSizeWrap* sizeWrap = Napi::ObjectWrap<QSizeWrap>::Unwrap(sizeObject);
this->instance->setSizeHint(*sizeWrap->getInternalInstance());
return env.Null();
}
Napi::Value QTableWidgetItemWrap::sizeHint(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
Napi::HandleScope scope(env);
QSize size = this->instance->sizeHint();
auto instance = QSizeWrap::constructor.New({Napi::External<QSize>::New(
env, new QSize(size.width(), size.height()))});
return instance;
}
Napi::Value QTableWidgetItemWrap::setStatusTip(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
Napi::HandleScope scope(env);
std::string statusTip = info[0].As<Napi::String>().Utf8Value();
this->instance->setStatusTip(QString::fromUtf8(statusTip.c_str()));
return env.Null();
}
Napi::Value QTableWidgetItemWrap::statusTip(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
Napi::HandleScope scope(env);
std::string statusTip = this->instance->text().toStdString();
return Napi::String::New(env, statusTip);
}
Napi::Value QTableWidgetItemWrap::setText(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
Napi::HandleScope scope(env);
std::string text = info[0].As<Napi::String>().Utf8Value();
this->instance->setText(QString::fromUtf8(text.c_str()));
return env.Null();
}
Napi::Value QTableWidgetItemWrap::text(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
Napi::HandleScope scope(env);
std::string text = this->instance->text().toStdString();
return Napi::String::New(env, text);
}
Napi::Value QTableWidgetItemWrap::setTextAlignment(
const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
Napi::HandleScope scope(env);
int alignment = info[0].As<Napi::Number>().Int32Value();
this->instance->setTextAlignment(alignment);
return env.Null();
}
Napi::Value QTableWidgetItemWrap::textAlignment(
const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
Napi::HandleScope scope(env);
int alignment = this->instance->textAlignment();
return Napi::Number::New(env, alignment);
}
Napi::Value QTableWidgetItemWrap::setToolTip(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
Napi::HandleScope scope(env);
std::string toolTip = info[0].As<Napi::String>().Utf8Value();
this->instance->setToolTip(QString::fromUtf8(toolTip.c_str()));
return env.Null();
}
Napi::Value QTableWidgetItemWrap::toolTip(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
Napi::HandleScope scope(env);
std::string toolTip = this->instance->toolTip().toStdString();
return Napi::String::New(env, toolTip);
}
Napi::Value QTableWidgetItemWrap::setWhatsThis(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
Napi::HandleScope scope(env);
std::string whatsThis = info[0].As<Napi::String>().Utf8Value();
this->instance->setWhatsThis(QString::fromUtf8(whatsThis.c_str()));
return env.Null();
}
Napi::Value QTableWidgetItemWrap::whatsThis(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
Napi::HandleScope scope(env);
std::string whatsThis = this->instance->whatsThis().toStdString();
return Napi::String::New(env, whatsThis);
}
Napi::Value QTableWidgetItemWrap::type(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
Napi::HandleScope scope(env);
return Napi::Number::New(env, this->instance->type());
}
| 35.108753 | 80 | 0.706331 | sharingcookies |
9993161620eb5e1a06840d586f9c4906a0d7824d | 8,286 | cpp | C++ | wxWidgets-2.9.1/src/common/radiocmn.cpp | slagusev/gamekit | a6e97fcf2a9c3b9b9799bc12c3643818503ffc7d | [
"MIT"
] | 1 | 2017-01-16T11:53:44.000Z | 2017-01-16T11:53:44.000Z | wxWidgets-2.9.1/src/common/radiocmn.cpp | slagusev/gamekit | a6e97fcf2a9c3b9b9799bc12c3643818503ffc7d | [
"MIT"
] | null | null | null | wxWidgets-2.9.1/src/common/radiocmn.cpp | slagusev/gamekit | a6e97fcf2a9c3b9b9799bc12c3643818503ffc7d | [
"MIT"
] | null | null | null | ///////////////////////////////////////////////////////////////////////////////
// Name: src/common/radiocmn.cpp
// Purpose: wxRadioBox methods common to all ports
// Author: Vadim Zeitlin
// Modified by:
// Created: 03.06.01
// RCS-ID: $Id$
// Copyright: (c) 2001 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
// Licence: wxWindows licence
///////////////////////////////////////////////////////////////////////////////
// ============================================================================
// declarations
// ============================================================================
// ----------------------------------------------------------------------------
// headers
// ----------------------------------------------------------------------------
// For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#if wxUSE_RADIOBOX
#ifndef WX_PRECOMP
#include "wx/radiobox.h"
#endif //WX_PRECOMP
#if wxUSE_TOOLTIPS
#include "wx/tooltip.h"
#endif // wxUSE_TOOLTIPS
#if wxUSE_HELP
#include "wx/cshelp.h"
#endif
// ============================================================================
// implementation
// ============================================================================
void wxRadioBoxBase::SetMajorDim(unsigned int majorDim, long style)
{
wxCHECK_RET( majorDim != 0, wxT("major radiobox dimension can't be 0") );
m_majorDim = majorDim;
int minorDim = (GetCount() + m_majorDim - 1) / m_majorDim;
if ( style & wxRA_SPECIFY_COLS )
{
m_numCols = majorDim;
m_numRows = minorDim;
}
else // wxRA_SPECIFY_ROWS
{
m_numCols = minorDim;
m_numRows = majorDim;
}
}
int wxRadioBoxBase::GetNextItem(int item, wxDirection dir, long style) const
{
const int itemStart = item;
int count = GetCount(),
numCols = GetColumnCount(),
numRows = GetRowCount();
bool horz = (style & wxRA_SPECIFY_COLS) != 0;
do
{
switch ( dir )
{
case wxUP:
if ( horz )
{
item -= numCols;
}
else // vertical layout
{
if ( !item-- )
item = count - 1;
}
break;
case wxLEFT:
if ( horz )
{
if ( !item-- )
item = count - 1;
}
else // vertical layout
{
item -= numRows;
}
break;
case wxDOWN:
if ( horz )
{
item += numCols;
}
else // vertical layout
{
if ( ++item == count )
item = 0;
}
break;
case wxRIGHT:
if ( horz )
{
if ( ++item == count )
item = 0;
}
else // vertical layout
{
item += numRows;
}
break;
default:
wxFAIL_MSG( wxT("unexpected wxDirection value") );
return wxNOT_FOUND;
}
// ensure that the item is in range [0..count)
if ( item < 0 )
{
// first map the item to the one in the same column but in the last
// row
item += count;
// now there are 2 cases: either it is the first item of the last
// row in which case we need to wrap again and get to the last item
// or we can just go to the previous item
if ( item % (horz ? numCols : numRows) )
item--;
else
item = count - 1;
}
else if ( item >= count )
{
// same logic as above
item -= count;
// ... except that we need to check if this is not the last item,
// not the first one
if ( (item + 1) % (horz ? numCols : numRows) )
item++;
else
item = 0;
}
wxASSERT_MSG( item < count && item >= 0,
wxT("logic error in wxRadioBox::GetNextItem()") );
}
// we shouldn't select the non-active items, continue looking for a
// visible and shown one unless we came back to the item we started from in
// which case bail out to avoid infinite loop
while ( !(IsItemShown(item) && IsItemEnabled(item)) && item != itemStart );
return item;
}
#if wxUSE_TOOLTIPS
void wxRadioBoxBase::SetItemToolTip(unsigned int item, const wxString& text)
{
wxASSERT_MSG( item < GetCount(), wxT("Invalid item index") );
// extend the array to have entries for all our items on first use
if ( !m_itemsTooltips )
{
m_itemsTooltips = new wxToolTipArray;
m_itemsTooltips->resize(GetCount());
}
wxToolTip *tooltip = (*m_itemsTooltips)[item];
bool changed = true;
if ( text.empty() )
{
if ( tooltip )
{
// delete the tooltip
wxDELETE(tooltip);
}
else // nothing to do
{
changed = false;
}
}
else // non empty tooltip text
{
if ( tooltip )
{
// just change the existing tooltip text, don't change the tooltip
tooltip->SetTip(text);
changed = false;
}
else // no tooltip yet
{
// create the new one
tooltip = new wxToolTip(text);
}
}
if ( changed )
{
(*m_itemsTooltips)[item] = tooltip;
DoSetItemToolTip(item, tooltip);
}
}
void
wxRadioBoxBase::DoSetItemToolTip(unsigned int WXUNUSED(item),
wxToolTip * WXUNUSED(tooltip))
{
// per-item tooltips not implemented by default
}
#endif // wxUSE_TOOLTIPS
wxRadioBoxBase::~wxRadioBoxBase()
{
#if wxUSE_TOOLTIPS
if ( m_itemsTooltips )
{
const size_t n = m_itemsTooltips->size();
for ( size_t i = 0; i < n; i++ )
delete (*m_itemsTooltips)[i];
delete m_itemsTooltips;
}
#endif // wxUSE_TOOLTIPS
}
#if wxUSE_HELP
// set helptext for a particular item
void wxRadioBoxBase::SetItemHelpText(unsigned int n, const wxString& helpText)
{
wxCHECK_RET( n < GetCount(), wxT("Invalid item index") );
if ( m_itemsHelpTexts.empty() )
{
// once-only initialization of the array: reserve space for all items
m_itemsHelpTexts.Add(wxEmptyString, GetCount());
}
m_itemsHelpTexts[n] = helpText;
}
// retrieve helptext for a particular item
wxString wxRadioBoxBase::GetItemHelpText( unsigned int n ) const
{
wxCHECK_MSG( n < GetCount(), wxEmptyString, wxT("Invalid item index") );
return m_itemsHelpTexts.empty() ? wxString() : m_itemsHelpTexts[n];
}
// return help text for the item for which wxEVT_HELP was generated.
wxString wxRadioBoxBase::DoGetHelpTextAtPoint(const wxWindow *derived,
const wxPoint& pt,
wxHelpEvent::Origin origin) const
{
int item;
switch ( origin )
{
case wxHelpEvent::Origin_HelpButton:
item = GetItemFromPoint(pt);
break;
case wxHelpEvent::Origin_Keyboard:
item = GetSelection();
break;
default:
wxFAIL_MSG( "unknown help even origin" );
// fall through
case wxHelpEvent::Origin_Unknown:
// this value is used when we're called from GetHelpText() for the
// radio box itself, so don't return item-specific text in this case
item = wxNOT_FOUND;
}
if ( item != wxNOT_FOUND )
{
wxString text = GetItemHelpText(static_cast<unsigned int>(item));
if( !text.empty() )
return text;
}
return derived->wxWindowBase::GetHelpTextAtPoint(pt, origin);
}
#endif // wxUSE_HELP
#endif // wxUSE_RADIOBOX
| 26.990228 | 80 | 0.480932 | slagusev |
9995c7c99a8b021c850d7e6f0bb6ec99f5c5bbf9 | 2,139 | cpp | C++ | apps/tests/test_rank2.cpp | mtaillefumier/SIRIUS | 50ec1c202c019113c5660f1966b170dec9dfd4d4 | [
"BSD-2-Clause"
] | 77 | 2016-03-18T08:38:30.000Z | 2022-03-11T14:06:25.000Z | apps/tests/test_rank2.cpp | simonpintarelli/SIRIUS | f4b5c4810af2a3ea1e67992d65750535227da84b | [
"BSD-2-Clause"
] | 240 | 2016-04-12T16:39:11.000Z | 2022-03-31T08:46:12.000Z | apps/tests/test_rank2.cpp | simonpintarelli/SIRIUS | f4b5c4810af2a3ea1e67992d65750535227da84b | [
"BSD-2-Clause"
] | 43 | 2016-03-18T17:45:07.000Z | 2022-02-28T05:27:59.000Z | #include <sirius.h>
using namespace sirius;
void f1(int num_gvec, int lmmax, int num_atoms)
{
mdarray<double_complex, 3> alm(num_gvec, lmmax, num_atoms);
mdarray<double_complex, 2> o(num_gvec, num_gvec);
alm.randomize();
o.zero();
Timer t("rank2_update");
for (int ia = 0; ia < num_atoms; ia++)
{
for (int lm = 0; lm < lmmax; lm++)
{
#pragma omp parallel for schedule(static)
for (int ig2 = 0; ig2 < num_gvec; ig2++)
{
for (int ig1 = 0; ig1 < num_gvec; ig1++)
{
o(ig1, ig2) += conj(alm(ig1, lm, ia)) * alm(ig2, lm, ia);
}
}
}
}
double tval = t.stop();
printf("\n");
printf("execution time (sec) : %12.6f\n", tval);
printf("performance (GFlops) : %12.6f\n", 8e-9 * num_gvec * num_gvec * lmmax * num_atoms / tval);
}
void f2(int num_gvec, int lmmax, int num_atoms)
{
mdarray<double_complex, 3> alm(num_gvec, lmmax, num_atoms);
mdarray<double_complex, 2> o(num_gvec, num_gvec);
alm.randomize();
o.zero();
Timer t("zgemm");
blas<cpu>::gemm(0, 2, num_gvec, num_gvec, lmmax * num_atoms, alm.ptr(), alm.ld(), alm.ptr(), alm.ld(), o.ptr(), o.ld());
double tval = t.stop();
printf("\n");
printf("execution time (sec) : %12.6f\n", tval);
printf("performance (GFlops) : %12.6f\n", 8e-9 * num_gvec * num_gvec * lmmax * num_atoms / tval);
}
int main(int argn, char** argv)
{
cmd_args args;
args.register_key("--NG=", "{int} number of G-vectors");
args.register_key("--NL=", "{int} number of lm components");
args.register_key("--NA=", "{int} number of atoms");
args.parse_args(argn, argv);
if (argn == 1)
{
printf("Usage: %s [options]\n", argv[0]);
args.print_help();
exit(0);
}
Platform::initialize(1);
int num_gvec = args.value<int>("NG");
int lmmax = args.value<int>("NL");
int num_atoms = args.value<int>("NA");
f1(num_gvec, lmmax, num_atoms);
f2(num_gvec, lmmax, num_atoms);
Timer::print();
Platform::finalize();
}
| 26.7375 | 124 | 0.555867 | mtaillefumier |
9997546f1c3133fc8afa4efee81f60c65a33c5ce | 56,391 | cpp | C++ | src/plugPikiOgawa/ogMemChk.cpp | doldecomp/pikmin | 8c8c20721ecb2a19af8e50a4bdebdba90c9a27ed | [
"Unlicense"
] | 27 | 2021-09-28T00:33:11.000Z | 2021-11-18T19:38:40.000Z | src/plugPikiOgawa/ogMemChk.cpp | doldecomp/pikmin | 8c8c20721ecb2a19af8e50a4bdebdba90c9a27ed | [
"Unlicense"
] | null | null | null | src/plugPikiOgawa/ogMemChk.cpp | doldecomp/pikmin | 8c8c20721ecb2a19af8e50a4bdebdba90c9a27ed | [
"Unlicense"
] | null | null | null | #include "types.h"
/*
* --INFO--
* Address: ........
* Size: 00009C
*/
void _Error(char*, ...)
{
// UNUSED FUNCTION
}
/*
* --INFO--
* Address: ........
* Size: 0000F4
*/
void _Print(char*, ...)
{
// UNUSED FUNCTION
}
/*
* --INFO--
* Address: 8018D04C
* Size: 0009D0
*/
zen::ogScrMemChkMgr::ogScrMemChkMgr()
{
/*
.loc_0x0:
mflr r0
stw r0, 0x4(r1)
stwu r1, -0xA0(r1)
stmw r26, 0x88(r1)
li r28, 0
addi r31, r3, 0
stb r28, 0x0(r3)
li r3, 0xF8
bl -0x146068
addi r29, r3, 0
mr. r0, r29
beq- .loc_0x84
addi r26, r29, 0
addi r3, r1, 0x80
li r4, 0
li r5, 0
li r6, 0x280
li r7, 0x1E0
bl 0x26594
lis r4, 0x726F
addi r7, r4, 0x6F74
addi r8, r1, 0x80
addi r3, r26, 0
li r4, 0
li r5, 0x8
li r6, 0x1
bl 0x23918
lis r3, 0x802E
addi r0, r3, 0x7E0
stw r0, 0x0(r29)
stb r28, 0xEC(r29)
stw r28, 0xF0(r29)
stw r28, 0xF4(r29)
.loc_0x84:
stw r29, 0x24(r31)
lis r3, 0x802D
addi r4, r3, 0x5CC8
lwz r3, 0x24(r31)
li r5, 0
li r6, 0
li r7, 0x1
bl 0x25B14
lwz r3, 0x24(r31)
lis r4, 0x626C
addi r4, r4, 0x636B
lwz r12, 0x0(r3)
li r5, 0x1
lwz r12, 0x34(r12)
mtlr r12
blrl
stw r3, 0x28(r31)
li r0, 0xFF
li r3, 0x4C4
lwz r4, 0x28(r31)
stb r0, 0xF0(r4)
bl -0x146120
addi r28, r3, 0
mr. r3, r28
beq- .loc_0xF8
li r4, 0x20
li r5, 0x80
li r6, 0x80
bl 0x5C780
.loc_0xF8:
stw r28, 0xC(r31)
li r28, 0
li r3, 0xF8
stw r28, 0x10(r31)
stw r28, 0x14(r31)
bl -0x146154
addi r29, r3, 0
mr. r0, r29
beq- .loc_0x170
addi r26, r29, 0
addi r3, r1, 0x74
li r4, 0
li r5, 0
li r6, 0x280
li r7, 0x1E0
bl 0x264A8
lis r4, 0x726F
addi r7, r4, 0x6F74
addi r8, r1, 0x74
addi r3, r26, 0
li r4, 0
li r5, 0x8
li r6, 0x1
bl 0x2382C
lis r3, 0x802E
addi r0, r3, 0x7E0
stw r0, 0x0(r29)
stb r28, 0xEC(r29)
stw r28, 0xF0(r29)
stw r28, 0xF4(r29)
.loc_0x170:
stw r29, 0x2C(r31)
lis r3, 0x802D
addi r4, r3, 0x5CE0
lwz r3, 0x2C(r31)
li r5, 0x1
li r6, 0x1
li r7, 0x1
bl 0x25A28
lwz r27, 0x2C(r31)
lis r28, 0x7368
addi r4, r28, 0x6F6D
addi r3, r27, 0
lwz r12, 0x0(r27)
li r5, 0x1
lwz r12, 0x34(r12)
mtlr r12
blrl
stw r3, 0x74(r31)
addi r3, r27, 0
addi r4, r28, 0x6F74
lwz r12, 0x0(r27)
li r5, 0x1
lwz r12, 0x34(r12)
mtlr r12
blrl
stw r3, 0x78(r31)
addi r3, r27, 0
addi r4, r28, 0x6368
lwz r12, 0x0(r27)
li r5, 0x1
lwz r12, 0x34(r12)
mtlr r12
blrl
stw r3, 0x80(r31)
addi r3, r27, 0
addi r4, r28, 0x6F69
lwz r12, 0x0(r27)
li r5, 0x1
lwz r12, 0x34(r12)
mtlr r12
blrl
stw r3, 0x84(r31)
addi r3, r27, 0
addi r4, r28, 0x6F6B
lwz r12, 0x0(r27)
li r5, 0x1
lwz r12, 0x34(r12)
mtlr r12
blrl
stw r3, 0x88(r31)
addi r3, r27, 0
addi r4, r28, 0x6F73
lwz r12, 0x0(r27)
li r5, 0x1
lwz r12, 0x34(r12)
mtlr r12
blrl
stw r3, 0x7C(r31)
addi r3, r27, 0
lis r4, 0x68
lwz r12, 0x0(r27)
addi r4, r4, 0x6169
li r5, 0x1
lwz r12, 0x34(r12)
mtlr r12
blrl
stw r3, 0xAC(r31)
addi r3, r27, 0
lis r4, 0x69
lwz r12, 0x0(r27)
addi r4, r4, 0x6965
li r5, 0x1
lwz r12, 0x34(r12)
mtlr r12
blrl
stw r3, 0xB0(r31)
addi r3, r27, 0
lis r4, 0x6861
lwz r12, 0x0(r27)
addi r4, r4, 0x6963
li r5, 0x1
lwz r12, 0x34(r12)
mtlr r12
blrl
stw r3, 0xB4(r31)
addi r3, r27, 0
lis r4, 0x6969
lwz r12, 0x0(r27)
addi r4, r4, 0x6563
li r5, 0x1
lwz r12, 0x34(r12)
mtlr r12
blrl
stw r3, 0xB8(r31)
addi r3, r27, 0
addi r4, r28, 0x7566
lwz r12, 0x0(r27)
li r5, 0x1
lwz r12, 0x34(r12)
mtlr r12
blrl
stw r3, 0x8C(r31)
addi r3, r27, 0
addi r4, r28, 0x7369
lwz r12, 0x0(r27)
li r5, 0x1
lwz r12, 0x34(r12)
mtlr r12
blrl
stw r3, 0x90(r31)
addi r3, r27, 0
addi r4, r28, 0x7878
lwz r12, 0x0(r27)
li r5, 0x1
lwz r12, 0x34(r12)
mtlr r12
blrl
stw r3, 0x94(r31)
addi r3, r27, 0
lis r4, 0x7361
lwz r12, 0x0(r27)
addi r4, r4, 0x7269
li r5, 0x1
lwz r12, 0x34(r12)
mtlr r12
blrl
stw r3, 0xEC(r31)
addi r3, r27, 0
lis r4, 0x6D65
lwz r12, 0x0(r27)
addi r4, r4, 0x6D6F
li r5, 0x1
lwz r12, 0x34(r12)
mtlr r12
blrl
stw r3, 0xF0(r31)
addi r3, r27, 0
lis r4, 0x6272
lwz r12, 0x0(r27)
addi r4, r4, 0x6F6D
li r5, 0x1
lwz r12, 0x34(r12)
mtlr r12
blrl
stw r3, 0xF4(r31)
addi r3, r27, 0
lis r4, 0x6B61
lwz r12, 0x0(r27)
addi r4, r4, 0x696D
li r5, 0x1
lwz r12, 0x34(r12)
mtlr r12
blrl
stw r3, 0xF8(r31)
addi r3, r27, 0
lis r4, 0x696A
lwz r12, 0x0(r27)
addi r4, r4, 0x6F6D
li r5, 0x1
lwz r12, 0x34(r12)
mtlr r12
blrl
stw r3, 0xFC(r31)
addi r3, r27, 0
lis r4, 0x6E61
lwz r12, 0x0(r27)
addi r4, r4, 0x696D
li r5, 0x1
lwz r12, 0x34(r12)
mtlr r12
blrl
stw r3, 0x100(r31)
addi r3, r27, 0
lis r4, 0x6669
lwz r12, 0x0(r27)
addi r4, r4, 0x6C65
li r5, 0x1
lwz r12, 0x34(r12)
mtlr r12
blrl
stw r3, 0x104(r31)
addi r3, r27, 0
lis r4, 0x796E
lwz r12, 0x0(r27)
addi r4, r4, 0x5F77
li r5, 0x1
lwz r12, 0x34(r12)
mtlr r12
blrl
stw r3, 0x98(r31)
addi r3, r27, 0
lis r4, 0x6370
lwz r12, 0x0(r27)
addi r4, r4, 0x736C
li r5, 0x1
lwz r12, 0x34(r12)
mtlr r12
blrl
stw r3, 0x9C(r31)
lis r3, 0x6162
addi r4, r3, 0x746E
lwz r3, 0x2C(r31)
li r5, 0x1
lwz r12, 0x0(r3)
lwz r12, 0x34(r12)
mtlr r12
blrl
stw r3, 0xA4(r31)
li r3, 0x12C
bl -0x1464FC
addi r28, r3, 0
mr. r3, r28
beq- .loc_0x4D0
lwz r4, 0xA4(r31)
lfs f1, -0x4F00(r2)
bl -0xE2F4
.loc_0x4D0:
stw r28, 0xA0(r31)
lis r3, 0x6D61
li r30, 0
lwz r6, 0xA4(r31)
addi r4, r3, 0x696E
li r5, 0x1
lbz r0, 0xC(r6)
rlwimi r0,r30,7,24,24
stb r0, 0xC(r6)
lwz r3, 0x2C(r31)
lwz r12, 0x0(r3)
lwz r12, 0x34(r12)
mtlr r12
blrl
stw r3, 0xA8(r31)
lis r3, 0x6375
addi r4, r3, 0x7273
lwz r3, 0x74(r31)
li r5, 0x1
lbz r0, 0xC(r3)
rlwimi r0,r30,7,24,24
stb r0, 0xC(r3)
lwz r3, 0x78(r31)
lbz r0, 0xC(r3)
rlwimi r0,r30,7,24,24
stb r0, 0xC(r3)
lwz r3, 0x80(r31)
lbz r0, 0xC(r3)
rlwimi r0,r30,7,24,24
stb r0, 0xC(r3)
lwz r3, 0x7C(r31)
lbz r0, 0xC(r3)
rlwimi r0,r30,7,24,24
stb r0, 0xC(r3)
lwz r3, 0x84(r31)
lbz r0, 0xC(r3)
rlwimi r0,r30,7,24,24
stb r0, 0xC(r3)
lwz r3, 0x88(r31)
lbz r0, 0xC(r3)
rlwimi r0,r30,7,24,24
stb r0, 0xC(r3)
lwz r3, 0x8C(r31)
lbz r0, 0xC(r3)
rlwimi r0,r30,7,24,24
stb r0, 0xC(r3)
lwz r3, 0x90(r31)
lbz r0, 0xC(r3)
rlwimi r0,r30,7,24,24
stb r0, 0xC(r3)
lwz r3, 0x94(r31)
lbz r0, 0xC(r3)
rlwimi r0,r30,7,24,24
stb r0, 0xC(r3)
lwz r3, 0xEC(r31)
lbz r0, 0xC(r3)
rlwimi r0,r30,7,24,24
stb r0, 0xC(r3)
lwz r3, 0xF0(r31)
lbz r0, 0xC(r3)
rlwimi r0,r30,7,24,24
stb r0, 0xC(r3)
lwz r3, 0xF4(r31)
lbz r0, 0xC(r3)
rlwimi r0,r30,7,24,24
stb r0, 0xC(r3)
lwz r3, 0xF8(r31)
lbz r0, 0xC(r3)
rlwimi r0,r30,7,24,24
stb r0, 0xC(r3)
lwz r3, 0xFC(r31)
lbz r0, 0xC(r3)
rlwimi r0,r30,7,24,24
stb r0, 0xC(r3)
lwz r3, 0xFC(r31)
lbz r0, 0xC(r3)
rlwimi r0,r30,7,24,24
stb r0, 0xC(r3)
lwz r3, 0x104(r31)
lbz r0, 0xC(r3)
rlwimi r0,r30,7,24,24
stb r0, 0xC(r3)
lwz r3, 0x2C(r31)
lwz r12, 0x0(r3)
lwz r12, 0x34(r12)
mtlr r12
blrl
stw r3, 0xC0(r31)
li r3, 0x12C
bl -0x14667C
addi r28, r3, 0
mr. r3, r28
beq- .loc_0x650
lwz r4, 0xC0(r31)
lfs f1, -0x4EFC(r2)
bl -0xE474
.loc_0x650:
stw r28, 0xBC(r31)
li r3, 0x418
bl -0x1466A0
addi r28, r3, 0
mr. r3, r28
beq- .loc_0x670
lwz r4, 0x74(r31)
bl -0xD328
.loc_0x670:
stw r28, 0x34(r31)
li r3, 0x418
bl -0x1466C0
addi r28, r3, 0
mr. r3, r28
beq- .loc_0x690
lwz r4, 0x80(r31)
bl -0xD348
.loc_0x690:
stw r28, 0x40(r31)
li r3, 0x418
bl -0x1466E0
addi r28, r3, 0
mr. r3, r28
beq- .loc_0x6B0
lwz r4, 0x78(r31)
bl -0xD368
.loc_0x6B0:
stw r28, 0x38(r31)
li r3, 0x418
bl -0x146700
addi r28, r3, 0
mr. r3, r28
beq- .loc_0x6D0
lwz r4, 0x7C(r31)
bl -0xD388
.loc_0x6D0:
stw r28, 0x3C(r31)
li r3, 0x418
bl -0x146720
addi r28, r3, 0
mr. r3, r28
beq- .loc_0x6F0
lwz r4, 0x84(r31)
bl -0xD3A8
.loc_0x6F0:
stw r28, 0x44(r31)
li r3, 0x418
bl -0x146740
addi r28, r3, 0
mr. r3, r28
beq- .loc_0x710
lwz r4, 0x88(r31)
bl -0xD3C8
.loc_0x710:
stw r28, 0x48(r31)
li r3, 0x418
bl -0x146760
addi r28, r3, 0
mr. r3, r28
beq- .loc_0x730
lwz r4, 0x8C(r31)
bl -0xD3E8
.loc_0x730:
stw r28, 0x4C(r31)
li r3, 0x418
bl -0x146780
addi r28, r3, 0
mr. r3, r28
beq- .loc_0x750
lwz r4, 0x90(r31)
bl -0xD408
.loc_0x750:
stw r28, 0x50(r31)
li r3, 0x418
bl -0x1467A0
addi r28, r3, 0
mr. r3, r28
beq- .loc_0x770
lwz r4, 0x94(r31)
bl -0xD428
.loc_0x770:
stw r28, 0x54(r31)
li r3, 0x418
bl -0x1467C0
addi r28, r3, 0
mr. r3, r28
beq- .loc_0x790
lwz r4, 0xEC(r31)
bl -0xD448
.loc_0x790:
stw r28, 0x58(r31)
li r3, 0x418
bl -0x1467E0
addi r28, r3, 0
mr. r3, r28
beq- .loc_0x7B0
lwz r4, 0xF0(r31)
bl -0xD468
.loc_0x7B0:
stw r28, 0x5C(r31)
li r3, 0x418
bl -0x146800
addi r28, r3, 0
mr. r3, r28
beq- .loc_0x7D0
lwz r4, 0xF4(r31)
bl -0xD488
.loc_0x7D0:
stw r28, 0x60(r31)
li r3, 0x418
bl -0x146820
addi r28, r3, 0
mr. r3, r28
beq- .loc_0x7F0
lwz r4, 0xF8(r31)
bl -0xD4A8
.loc_0x7F0:
stw r28, 0x64(r31)
li r3, 0x418
bl -0x146840
addi r28, r3, 0
mr. r3, r28
beq- .loc_0x810
lwz r4, 0xFC(r31)
bl -0xD4C8
.loc_0x810:
stw r28, 0x68(r31)
li r3, 0x418
bl -0x146860
addi r28, r3, 0
mr. r3, r28
beq- .loc_0x830
lwz r4, 0x100(r31)
bl -0xD4E8
.loc_0x830:
stw r28, 0x6C(r31)
li r3, 0x418
bl -0x146880
addi r28, r3, 0
mr. r3, r28
beq- .loc_0x850
lwz r4, 0x104(r31)
bl -0xD508
.loc_0x850:
stw r28, 0x70(r31)
lis r3, 0x666F
li r0, -0x1
lwz r6, 0x58(r31)
addi r4, r3, 0x6D74
li r5, 0x1
stw r6, 0x30(r31)
stw r0, 0x1C(r31)
stw r0, 0x20(r31)
lwz r3, 0x2C(r31)
lwz r12, 0x0(r3)
lwz r12, 0x34(r12)
mtlr r12
blrl
mr r28, r3
lwz r3, 0x2C(r31)
lis r4, 0x63
lwz r12, 0x0(r3)
addi r4, r4, 0x7773
li r5, 0x1
lwz r12, 0x34(r12)
mtlr r12
blrl
mr r29, r3
lwz r3, 0x2C(r31)
lis r4, 0x7274
lwz r12, 0x0(r3)
addi r4, r4, 0x7279
li r5, 0x1
lwz r12, 0x34(r12)
mtlr r12
blrl
mr r30, r3
lwz r3, 0x2C(r31)
lis r4, 0x7365
lwz r12, 0x0(r3)
addi r4, r4, 0x5F63
li r5, 0x1
lwz r12, 0x34(r12)
mtlr r12
blrl
addi r26, r3, 0
li r3, 0xC4
bl -0x146944
addi r27, r3, 0
mr. r3, r27
beq- .loc_0x928
lwz r4, 0x2C(r31)
mr r7, r26
lwz r5, 0xB4(r31)
li r8, 0
lwz r6, 0xB8(r31)
li r9, 0
bl 0x8EF4
.loc_0x928:
stw r27, 0xD4(r31)
li r4, 0
li r3, 0x54
lbz r0, 0xC(r28)
rlwimi r0,r4,7,24,24
stb r0, 0xC(r28)
lbz r0, 0xC(r29)
rlwimi r0,r4,7,24,24
stb r0, 0xC(r29)
lbz r0, 0xC(r30)
rlwimi r0,r4,7,24,24
stb r0, 0xC(r30)
lwz r4, 0xAC(r31)
lwz r0, 0x10C(r4)
stw r0, 0xD8(r31)
lwz r4, 0xB0(r31)
lwz r0, 0x10C(r4)
stw r0, 0xDC(r31)
lwz r0, 0x10C(r28)
stw r0, 0xE0(r31)
lwz r0, 0x10C(r29)
stw r0, 0xE4(r31)
lwz r0, 0x10C(r30)
stw r0, 0xE8(r31)
bl -0x1469D0
addi r27, r3, 0
mr. r3, r27
beq- .loc_0x99C
bl 0x5FB8
.loc_0x99C:
stw r27, 0x18(r31)
addi r3, r31, 0
li r4, 0x1
bl 0x2C4
addi r3, r31, 0
li r4, 0
bl 0x2F0
mr r3, r31
lmw r26, 0x88(r1)
lwz r0, 0xA4(r1)
addi r1, r1, 0xA0
mtlr r0
blr
*/
}
/*
* --INFO--
* Address: ........
* Size: 000034
*/
void zen::ogScrMemChkMgr::SetNitaku_Y_N()
{
// UNUSED FUNCTION
}
/*
* --INFO--
* Address: ........
* Size: 000034
*/
void zen::ogScrMemChkMgr::SetNitaku_W_R()
{
// UNUSED FUNCTION
}
/*
* --INFO--
* Address: ........
* Size: 000034
*/
void zen::ogScrMemChkMgr::SetNitaku_F_N()
{
// UNUSED FUNCTION
}
/*
* --INFO--
* Address: ........
* Size: 0000C4
*/
void zen::ogScrMemChkMgr::StartSub()
{
// UNUSED FUNCTION
}
/*
* --INFO--
* Address: 8018DA1C
* Size: 000258
*/
void zen::ogScrMemChkMgr::StatusCheck()
{
/*
.loc_0x0:
mflr r0
stw r0, 0x4(r1)
stwu r1, -0xB8(r1)
stw r31, 0xB4(r1)
mr r31, r3
lwz r0, 0xD8(r3)
lwz r3, 0xAC(r3)
stw r0, 0x10C(r3)
lwz r0, 0xDC(r31)
lwz r3, 0xB0(r31)
stw r0, 0x10C(r3)
lwz r0, 0xD8(r31)
lwz r3, 0xB4(r31)
stw r0, 0x10C(r3)
lwz r0, 0xDC(r31)
lwz r3, 0xB8(r31)
stw r0, 0x10C(r3)
lwz r0, 0x1C(r31)
cmpwi r0, 0xB
beq- .loc_0xB0
bge- .loc_0xFC
cmpwi r0, 0xA
bge- .loc_0x60
b .loc_0xFC
.loc_0x60:
li r0, 0xA
stw r0, 0x20(r31)
li r0, 0x1
addi r3, r31, 0
stw r0, 0x1C(r31)
lwz r4, 0x48(r31)
bl .loc_0x258
lwz r0, 0xE0(r31)
lwz r3, 0xAC(r31)
stw r0, 0x10C(r3)
lwz r0, 0xDC(r31)
lwz r3, 0xB0(r31)
stw r0, 0x10C(r3)
lwz r0, 0xE0(r31)
lwz r3, 0xB4(r31)
stw r0, 0x10C(r3)
lwz r0, 0xDC(r31)
lwz r3, 0xB8(r31)
stw r0, 0x10C(r3)
b .loc_0xFC
.loc_0xB0:
li r0, 0xB
stw r0, 0x20(r31)
li r0, 0x1
addi r3, r31, 0
stw r0, 0x1C(r31)
lwz r4, 0x44(r31)
bl .loc_0x258
lwz r0, 0xE0(r31)
lwz r3, 0xAC(r31)
stw r0, 0x10C(r3)
lwz r0, 0xDC(r31)
lwz r3, 0xB0(r31)
stw r0, 0x10C(r3)
lwz r0, 0xE0(r31)
lwz r3, 0xB4(r31)
stw r0, 0x10C(r3)
lwz r0, 0xDC(r31)
lwz r3, 0xB8(r31)
stw r0, 0x10C(r3)
.loc_0xFC:
lwz r0, 0x1C(r31)
cmplwi r0, 0x12
bgt- .loc_0x220
lis r3, 0x802D
addi r3, r3, 0x5CF8
rlwinm r0,r0,2,0,29
lwzx r0, r3, r0
mtctr r0
bctr
mr r3, r31
lwz r4, 0x58(r31)
bl .loc_0x258
b .loc_0x23C
mr r3, r31
lwz r4, 0x6C(r31)
bl .loc_0x258
b .loc_0x23C
mr r3, r31
lwz r4, 0x64(r31)
bl .loc_0x258
lwz r0, 0xE4(r31)
lwz r3, 0xAC(r31)
stw r0, 0x10C(r3)
lwz r0, 0xE8(r31)
lwz r3, 0xB0(r31)
stw r0, 0x10C(r3)
lwz r0, 0xE4(r31)
lwz r3, 0xB4(r31)
stw r0, 0x10C(r3)
lwz r0, 0xE8(r31)
lwz r3, 0xB8(r31)
stw r0, 0x10C(r3)
b .loc_0x23C
mr r3, r31
lwz r4, 0x68(r31)
bl .loc_0x258
lwz r0, 0xE4(r31)
lwz r3, 0xAC(r31)
stw r0, 0x10C(r3)
lwz r0, 0xE8(r31)
lwz r3, 0xB0(r31)
stw r0, 0x10C(r3)
lwz r0, 0xE4(r31)
lwz r3, 0xB4(r31)
stw r0, 0x10C(r3)
lwz r0, 0xE8(r31)
lwz r3, 0xB8(r31)
stw r0, 0x10C(r3)
b .loc_0x23C
mr r3, r31
lwz r4, 0x5C(r31)
bl .loc_0x258
b .loc_0x23C
mr r3, r31
lwz r4, 0x60(r31)
bl .loc_0x258
b .loc_0x23C
mr r3, r31
lwz r4, 0x70(r31)
bl .loc_0x258
b .loc_0x23C
mr r3, r31
lwz r4, 0x4C(r31)
bl .loc_0x258
b .loc_0x23C
mr r3, r31
lwz r4, 0x50(r31)
bl .loc_0x258
b .loc_0x23C
mr r3, r31
lwz r4, 0x54(r31)
bl .loc_0x258
b .loc_0x23C
.loc_0x220:
lwz r5, 0x30(r31)
li r4, 0
lwz r3, 0x8(r5)
lbz r0, 0xC(r3)
rlwimi r0,r4,7,24,24
stb r0, 0xC(r3)
stw r4, 0x0(r5)
.loc_0x23C:
lfs f0, -0x4EF8(r2)
stfs f0, 0xC8(r31)
lwz r0, 0xBC(r1)
lwz r31, 0xB4(r1)
addi r1, r1, 0xB8
mtlr r0
blr
.loc_0x258:
*/
}
/*
* --INFO--
* Address: 8018DC74
* Size: 000044
*/
void zen::ogScrMemChkMgr::setPCtex(zen::TypingTextMgr*)
{
/*
.loc_0x0:
mflr r0
li r6, 0
stw r0, 0x4(r1)
stwu r1, -0x8(r1)
lwz r7, 0x30(r3)
lwz r5, 0x8(r7)
lbz r0, 0xC(r5)
rlwimi r0,r6,7,24,24
stb r0, 0xC(r5)
stw r6, 0x0(r7)
stw r4, 0x30(r3)
lwz r3, 0x30(r3)
bl -0xD884
lwz r0, 0xC(r1)
addi r1, r1, 0x8
mtlr r0
blr
*/
}
/*
* --INFO--
* Address: 8018DCB8
* Size: 000038
*/
void zen::ogScrMemChkMgr::DispYesNo(bool)
{
/*
.loc_0x0:
rlwinm. r0,r4,0,24,31
beq- .loc_0x20
lwz r3, 0x98(r3)
li r4, 0x1
lbz r0, 0xC(r3)
rlwimi r0,r4,7,24,24
stb r0, 0xC(r3)
blr
.loc_0x20:
lwz r3, 0x98(r3)
li r4, 0
lbz r0, 0xC(r3)
rlwimi r0,r4,7,24,24
stb r0, 0xC(r3)
blr
*/
}
/*
* --INFO--
* Address: 8018DCF0
* Size: 000038
*/
void zen::ogScrMemChkMgr::DispAcup(bool)
{
/*
.loc_0x0:
rlwinm. r0,r4,0,24,31
beq- .loc_0x20
lwz r3, 0x9C(r3)
li r4, 0x1
lbz r0, 0xC(r3)
rlwimi r0,r4,7,24,24
stb r0, 0xC(r3)
blr
.loc_0x20:
lwz r3, 0x9C(r3)
li r4, 0
lbz r0, 0xC(r3)
rlwimi r0,r4,7,24,24
stb r0, 0xC(r3)
blr
*/
}
/*
* --INFO--
* Address: ........
* Size: 000040
*/
void zen::ogScrMemChkMgr::MakeDefFileStart()
{
// UNUSED FUNCTION
}
/*
* --INFO--
* Address: ........
* Size: 00008C
*/
void zen::ogScrMemChkMgr::RepairFileStart()
{
// UNUSED FUNCTION
}
/*
* --INFO--
* Address: 8018DD28
* Size: 000224
*/
void zen::ogScrMemChkMgr::start()
{
/*
.loc_0x0:
mflr r0
stw r0, 0x4(r1)
stwu r1, -0x70(r1)
stw r31, 0x6C(r1)
addi r31, r3, 0
stw r30, 0x68(r1)
stw r29, 0x64(r1)
li r29, 0
stw r28, 0x60(r1)
stb r29, 0x0(r3)
stw r29, 0x1C(r3)
bl -0xF504
rlwinm. r0,r3,0,24,31
bne- .loc_0x44
li r0, 0x8
stw r0, 0x1C(r31)
b .loc_0x15C
.loc_0x44:
lis r3, 0x803A
subi r30, r3, 0x2848
addi r28, r30, 0x24
addi r3, r28, 0
li r4, 0
bl -0x119E90
cmpwi r3, -0x2
bne- .loc_0x70
li r0, 0x9
stw r0, 0x1C(r31)
b .loc_0x15C
.loc_0x70:
cmpwi r3, -0x5
bne- .loc_0x84
li r0, 0xA
stw r0, 0x1C(r31)
b .loc_0x15C
.loc_0x84:
cmpwi r3, -0x4
bne- .loc_0x98
li r0, 0xB
stw r0, 0x1C(r31)
b .loc_0x15C
.loc_0x98:
cmpwi r3, -0x3
bne- .loc_0xAC
li r0, 0xC
stw r0, 0x1C(r31)
b .loc_0x15C
.loc_0xAC:
cmpwi r3, -0x6
bne- .loc_0xC0
li r0, 0xD
stw r0, 0x1C(r31)
b .loc_0x15C
.loc_0xC0:
cmpwi r3, -0x8
bne- .loc_0xD4
li r0, 0xE
stw r0, 0x1C(r31)
b .loc_0x15C
.loc_0xD4:
lwz r0, 0x5C(r30)
cmpwi r0, 0
bge- .loc_0xFC
lwz r3, 0x18(r31)
bl 0x5EF0
li r0, 0xF
stw r0, 0x1C(r31)
lfs f0, -0x4EF8(r2)
stfs f0, 0xC8(r31)
b .loc_0x15C
.loc_0xFC:
mr r3, r28
bl -0x1179CC
rlwinm. r0,r3,0,24,31
beq- .loc_0x15C
mr r3, r28
bl -0x11793C
li r0, 0x10
stw r0, 0x1C(r31)
lwz r5, 0x30(r31)
lwz r4, 0x4C(r31)
lwz r3, 0x8(r5)
lbz r0, 0xC(r3)
rlwimi r0,r29,7,24,24
stb r0, 0xC(r3)
stw r29, 0x0(r5)
stw r4, 0x30(r31)
lwz r3, 0x30(r31)
bl -0xDA48
lfs f0, -0x4EF8(r2)
stfs f0, 0xC8(r31)
lwz r3, 0x98(r31)
lbz r0, 0xC(r3)
rlwimi r0,r29,7,24,24
stb r0, 0xC(r3)
.loc_0x15C:
lwz r4, 0x30(r31)
li r30, 0
lwz r3, 0x8(r4)
lbz r0, 0xC(r3)
rlwimi r0,r30,7,24,24
stb r0, 0xC(r3)
stw r30, 0x0(r4)
lwz r4, 0x30(r31)
lwz r3, 0xC0(r31)
lwz r7, 0x8(r4)
lwz r12, 0x0(r3)
lha r4, 0x116(r7)
lwz r12, 0x14(r12)
subi r5, r4, 0x18
lha r0, 0x1A(r7)
lha r6, 0x114(r7)
mtlr r12
lha r4, 0x18(r7)
add r5, r0, r5
add r4, r4, r6
blrl
lwz r3, 0xBC(r31)
bl -0xE860
lwz r3, 0xA4(r31)
li r4, 0x1
lbz r0, 0xC(r3)
rlwimi r0,r30,7,24,24
stb r0, 0xC(r3)
lwz r3, 0x9C(r31)
lbz r0, 0xC(r3)
rlwimi r0,r30,7,24,24
stb r0, 0xC(r3)
lwz r3, 0x98(r31)
lbz r0, 0xC(r3)
rlwimi r0,r4,7,24,24
stb r0, 0xC(r3)
lwz r3, 0xD4(r31)
bl 0x8D30
li r0, 0x3
sth r0, 0x8(r31)
mr r3, r31
bl -0x50C
lwz r0, 0x74(r1)
lwz r31, 0x6C(r1)
lwz r30, 0x68(r1)
lwz r29, 0x64(r1)
lwz r28, 0x60(r1)
addi r1, r1, 0x70
mtlr r0
blr
*/
}
/*
* --INFO--
* Address: 8018DF4C
* Size: 000190
*/
void zen::ogScrMemChkMgr::DebugStart(int)
{
/*
.loc_0x0:
mflr r0
cmpwi r4, 0x1
stw r0, 0x4(r1)
li r0, 0x1
stwu r1, -0x70(r1)
stw r31, 0x6C(r1)
addi r31, r3, 0
stw r30, 0x68(r1)
stb r0, 0x0(r3)
stw r4, 0x4(r3)
blt- .loc_0x170
cmpwi r4, 0x9
bgt- .loc_0x170
addi r0, r4, 0x7
cmpwi r4, 0x8
stw r0, 0x1C(r31)
bne- .loc_0x60
lwz r3, 0x18(r31)
bl 0x5D68
li r0, 0xF
stw r0, 0x1C(r31)
lfs f0, -0x4EF8(r2)
stfs f0, 0xC8(r31)
b .loc_0xC4
.loc_0x60:
cmpwi r4, 0x9
bne- .loc_0xC4
lis r3, 0x803A
subi r3, r3, 0x2848
addi r3, r3, 0x24
bl -0x117AC4
li r0, 0x10
stw r0, 0x1C(r31)
li r30, 0
lwz r5, 0x30(r31)
lwz r4, 0x4C(r31)
lwz r3, 0x8(r5)
lbz r0, 0xC(r3)
rlwimi r0,r30,7,24,24
stb r0, 0xC(r3)
stw r30, 0x0(r5)
stw r4, 0x30(r31)
lwz r3, 0x30(r31)
bl -0xDBD4
lfs f0, -0x4EF8(r2)
stfs f0, 0xC8(r31)
lwz r3, 0x98(r31)
lbz r0, 0xC(r3)
rlwimi r0,r30,7,24,24
stb r0, 0xC(r3)
.loc_0xC4:
lwz r4, 0x30(r31)
li r30, 0
lwz r3, 0x8(r4)
lbz r0, 0xC(r3)
rlwimi r0,r30,7,24,24
stb r0, 0xC(r3)
stw r30, 0x0(r4)
lwz r4, 0x30(r31)
lwz r3, 0xC0(r31)
lwz r7, 0x8(r4)
lwz r12, 0x0(r3)
lha r4, 0x116(r7)
lwz r12, 0x14(r12)
subi r5, r4, 0x18
lha r0, 0x1A(r7)
lha r6, 0x114(r7)
mtlr r12
lha r4, 0x18(r7)
add r5, r0, r5
add r4, r4, r6
blrl
lwz r3, 0xBC(r31)
bl -0xE9EC
lwz r3, 0xA4(r31)
li r4, 0x1
lbz r0, 0xC(r3)
rlwimi r0,r30,7,24,24
stb r0, 0xC(r3)
lwz r3, 0x9C(r31)
lbz r0, 0xC(r3)
rlwimi r0,r30,7,24,24
stb r0, 0xC(r3)
lwz r3, 0x98(r31)
lbz r0, 0xC(r3)
rlwimi r0,r4,7,24,24
stb r0, 0xC(r3)
lwz r3, 0xD4(r31)
bl 0x8BA4
li r0, 0x3
sth r0, 0x8(r31)
mr r3, r31
bl -0x698
b .loc_0x178
.loc_0x170:
mr r3, r31
bl -0x398
.loc_0x178:
lwz r0, 0x74(r1)
lwz r31, 0x6C(r1)
lwz r30, 0x68(r1)
addi r1, r1, 0x70
mtlr r0
blr
*/
}
/*
* --INFO--
* Address: ........
* Size: 000120
*/
void zen::ogScrMemChkMgr::FormatEffectStart()
{
// UNUSED FUNCTION
}
/*
* --INFO--
* Address: ........
* Size: 000020
*/
void zen::ogScrMemChkMgr::checkTypingAll()
{
// UNUSED FUNCTION
}
/*
* --INFO--
* Address: ........
* Size: 0000A8
*/
void zen::ogScrMemChkMgr::checkErrNitaku(zen::ogNitakuMgr*, Controller*)
{
// UNUSED FUNCTION
}
/*
* --INFO--
* Address: ........
* Size: 000100
*/
void zen::ogScrMemChkMgr::setNoCard()
{
// UNUSED FUNCTION
}
/*
* --INFO--
* Address: 8018E0DC
* Size: 000EC4
*/
void zen::ogScrMemChkMgr::update(Controller*)
{
/*
.loc_0x0:
mflr r0
stw r0, 0x4(r1)
stwu r1, -0x378(r1)
stw r31, 0x374(r1)
mr r31, r3
stw r30, 0x370(r1)
stw r29, 0x36C(r1)
stw r28, 0x368(r1)
addi r28, r4, 0
lwz r3, 0x1C(r3)
cmpwi r3, -0x1
bne- .loc_0x34
b .loc_0xEA4
.loc_0x34:
cmpwi r3, 0
bne- .loc_0x4C
li r0, 0x15
stw r0, 0x1C(r31)
lwz r3, 0x1C(r31)
b .loc_0xEA4
.loc_0x4C:
cmpwi r3, 0x13
blt- .loc_0x64
li r0, -0x1
stw r0, 0x1C(r31)
lwz r3, 0x1C(r31)
b .loc_0xEA4
.loc_0x64:
lwz r3, 0x2DEC(r13)
lfs f1, 0xC8(r31)
lfs f0, 0x28C(r3)
fadds f0, f1, f0
stfs f0, 0xC8(r31)
bl -0xF904
rlwinm. r0,r3,0,24,31
addi r29, r3, 0
bne- .loc_0x168
lwz r0, 0x1C(r31)
cmpwi r0, 0x8
beq- .loc_0x168
li r0, 0x8
stw r0, 0x1C(r31)
mr r3, r31
bl 0xF34
lwz r3, 0x98(r31)
li r30, 0
lbz r0, 0xC(r3)
rlwimi r0,r30,7,24,24
stb r0, 0xC(r3)
lwz r3, 0xA4(r31)
lbz r0, 0xC(r3)
rlwimi r0,r30,7,24,24
stb r0, 0xC(r3)
lwz r3, 0x9C(r31)
lbz r0, 0xC(r3)
rlwimi r0,r30,7,24,24
stb r0, 0xC(r3)
lwz r0, 0xD8(r31)
lwz r3, 0xAC(r31)
stw r0, 0x10C(r3)
lwz r0, 0xDC(r31)
lwz r3, 0xB0(r31)
stw r0, 0x10C(r3)
lwz r0, 0xD8(r31)
lwz r3, 0xB4(r31)
stw r0, 0x10C(r3)
lwz r0, 0xDC(r31)
lwz r3, 0xB8(r31)
stw r0, 0x10C(r3)
lwz r3, 0xD4(r31)
bl 0x8A60
lwz r5, 0x30(r31)
lwz r4, 0x58(r31)
lwz r3, 0x8(r5)
lbz r0, 0xC(r3)
rlwimi r0,r30,7,24,24
stb r0, 0xC(r3)
stw r30, 0x0(r5)
stw r4, 0x30(r31)
lwz r3, 0x30(r31)
bl -0xDDF0
lwz r3, 0x10(r31)
cmplwi r3, 0
beq- .loc_0x150
lwz r0, 0x80(r3)
ori r0, r0, 0x2
stw r0, 0x80(r3)
.loc_0x150:
lwz r3, 0x14(r31)
cmplwi r3, 0
beq- .loc_0x168
lwz r0, 0x80(r3)
ori r0, r0, 0x2
stw r0, 0x80(r3)
.loc_0x168:
lwz r0, 0x1C(r31)
cmplwi r0, 0x12
bgt- .loc_0xE28
lis r3, 0x802D
addi r3, r3, 0x5D44
rlwinm r0,r0,2,0,29
lwzx r0, r3, r0
mtctr r0
bctr
rlwinm. r0,r29,0,24,31
beq- .loc_0x1A4
mr r3, r31
bl -0x54C
lwz r3, 0x1C(r31)
b .loc_0xEA4
.loc_0x1A4:
lwz r4, 0x30(r31)
lwz r3, 0xD4(r31)
lwz r0, 0x0(r4)
cmpwi r0, 0x2
bne- .loc_0x1C0
li r0, 0x1
b .loc_0x1C4
.loc_0x1C0:
li r0, 0
.loc_0x1C4:
rlwinm. r0,r0,0,24,31
beq- .loc_0x210
lwz r5, 0x98(r31)
li r4, 0x1
lbz r0, 0xC(r5)
rlwimi r0,r4,7,24,24
addi r4, r28, 0
stb r0, 0xC(r5)
bl 0x8B98
cmpwi r3, 0x6
bne- .loc_0x1FC
li r0, 0x13
stw r0, 0x1C(r31)
b .loc_0xE28
.loc_0x1FC:
cmpwi r3, 0x5
bne- .loc_0xE28
li r0, 0x14
stw r0, 0x1C(r31)
b .loc_0xE28
.loc_0x210:
lwz r3, 0x98(r31)
li r4, 0
lbz r0, 0xC(r3)
rlwimi r0,r4,7,24,24
stb r0, 0xC(r3)
b .loc_0xE28
lwz r0, 0xE4(r31)
lwz r3, 0xAC(r31)
stw r0, 0x10C(r3)
lwz r0, 0xE8(r31)
lwz r3, 0xB0(r31)
stw r0, 0x10C(r3)
lwz r0, 0xE4(r31)
lwz r3, 0xB4(r31)
stw r0, 0x10C(r3)
lwz r0, 0xE8(r31)
lwz r3, 0xB8(r31)
stw r0, 0x10C(r3)
lwz r4, 0x30(r31)
lwz r3, 0xD4(r31)
lwz r0, 0x0(r4)
cmpwi r0, 0x2
bne- .loc_0x274
li r0, 0x1
b .loc_0x278
.loc_0x274:
li r0, 0
.loc_0x278:
rlwinm. r0,r0,0,24,31
beq- .loc_0x2C4
lwz r5, 0x98(r31)
li r4, 0x1
lbz r0, 0xC(r5)
rlwimi r0,r4,7,24,24
addi r4, r28, 0
stb r0, 0xC(r5)
bl 0x8AE4
cmpwi r3, 0x6
bne- .loc_0x2B0
li r0, 0x13
stw r0, 0x1C(r31)
b .loc_0xE28
.loc_0x2B0:
cmpwi r3, 0x5
bne- .loc_0xE28
li r0, 0x14
stw r0, 0x1C(r31)
b .loc_0xE28
.loc_0x2C4:
lwz r3, 0x98(r31)
li r4, 0
lbz r0, 0xC(r3)
rlwimi r0,r4,7,24,24
stb r0, 0xC(r3)
b .loc_0xE28
lwz r0, 0xE4(r31)
lwz r3, 0xAC(r31)
stw r0, 0x10C(r3)
lwz r0, 0xE8(r31)
lwz r3, 0xB0(r31)
stw r0, 0x10C(r3)
lwz r0, 0xE4(r31)
lwz r3, 0xB4(r31)
stw r0, 0x10C(r3)
lwz r0, 0xE8(r31)
lwz r3, 0xB8(r31)
stw r0, 0x10C(r3)
lwz r4, 0x30(r31)
lwz r3, 0xD4(r31)
lwz r0, 0x0(r4)
cmpwi r0, 0x2
bne- .loc_0x328
li r0, 0x1
b .loc_0x32C
.loc_0x328:
li r0, 0
.loc_0x32C:
rlwinm. r0,r0,0,24,31
beq- .loc_0x378
lwz r5, 0x98(r31)
li r4, 0x1
lbz r0, 0xC(r5)
rlwimi r0,r4,7,24,24
addi r4, r28, 0
stb r0, 0xC(r5)
bl 0x8A30
cmpwi r3, 0x6
bne- .loc_0x364
li r0, 0x13
stw r0, 0x1C(r31)
b .loc_0xE28
.loc_0x364:
cmpwi r3, 0x5
bne- .loc_0xE28
li r0, 0x14
stw r0, 0x1C(r31)
b .loc_0xE28
.loc_0x378:
lwz r3, 0x98(r31)
li r4, 0
lbz r0, 0xC(r3)
rlwimi r0,r4,7,24,24
stb r0, 0xC(r3)
b .loc_0xE28
lwz r0, 0xE4(r31)
lwz r3, 0xAC(r31)
stw r0, 0x10C(r3)
lwz r0, 0xE8(r31)
lwz r3, 0xB0(r31)
stw r0, 0x10C(r3)
lwz r0, 0xE4(r31)
lwz r3, 0xB4(r31)
stw r0, 0x10C(r3)
lwz r0, 0xE8(r31)
lwz r3, 0xB8(r31)
stw r0, 0x10C(r3)
lwz r4, 0x30(r31)
lwz r3, 0xD4(r31)
lwz r0, 0x0(r4)
cmpwi r0, 0x2
bne- .loc_0x3DC
li r0, 0x1
b .loc_0x3E0
.loc_0x3DC:
li r0, 0
.loc_0x3E0:
rlwinm. r0,r0,0,24,31
beq- .loc_0x42C
lwz r5, 0x98(r31)
li r4, 0x1
lbz r0, 0xC(r5)
rlwimi r0,r4,7,24,24
addi r4, r28, 0
stb r0, 0xC(r5)
bl 0x897C
cmpwi r3, 0x6
bne- .loc_0x418
li r0, 0x13
stw r0, 0x1C(r31)
b .loc_0xE28
.loc_0x418:
cmpwi r3, 0x5
bne- .loc_0xE28
li r0, 0x14
stw r0, 0x1C(r31)
b .loc_0xE28
.loc_0x42C:
lwz r3, 0x98(r31)
li r4, 0
lbz r0, 0xC(r3)
rlwimi r0,r4,7,24,24
stb r0, 0xC(r3)
b .loc_0xE28
lwz r4, 0x30(r31)
lwz r3, 0xD4(r31)
lwz r0, 0x0(r4)
cmpwi r0, 0x2
bne- .loc_0x460
li r0, 0x1
b .loc_0x464
.loc_0x460:
li r0, 0
.loc_0x464:
rlwinm. r0,r0,0,24,31
beq- .loc_0x4B0
lwz r5, 0x98(r31)
li r4, 0x1
lbz r0, 0xC(r5)
rlwimi r0,r4,7,24,24
addi r4, r28, 0
stb r0, 0xC(r5)
bl 0x88F8
cmpwi r3, 0x6
bne- .loc_0x49C
li r0, 0x13
stw r0, 0x1C(r31)
b .loc_0xE28
.loc_0x49C:
cmpwi r3, 0x5
bne- .loc_0xE28
li r0, 0x14
stw r0, 0x1C(r31)
b .loc_0xE28
.loc_0x4B0:
lwz r3, 0x98(r31)
li r4, 0
lbz r0, 0xC(r3)
rlwimi r0,r4,7,24,24
stb r0, 0xC(r3)
b .loc_0xE28
lwz r3, 0x30(r31)
lwz r0, 0x0(r3)
cmpwi r0, 0x2
bne- .loc_0x4E0
li r0, 0x1
b .loc_0x4E4
.loc_0x4E0:
li r0, 0
.loc_0x4E4:
rlwinm. r0,r0,0,24,31
beq- .loc_0x544
li r0, 0x2
stw r0, 0x1C(r31)
lwz r0, 0xE0(r31)
lwz r3, 0xAC(r31)
stw r0, 0x10C(r3)
lwz r0, 0xDC(r31)
lwz r3, 0xB0(r31)
stw r0, 0x10C(r3)
lwz r0, 0xE0(r31)
lwz r3, 0xB4(r31)
stw r0, 0x10C(r3)
lwz r0, 0xDC(r31)
lwz r3, 0xB8(r31)
stw r0, 0x10C(r3)
lwz r3, 0xD4(r31)
bl 0x8644
lwz r3, 0x98(r31)
li r4, 0x1
lbz r0, 0xC(r3)
rlwimi r0,r4,7,24,24
stb r0, 0xC(r3)
b .loc_0xE28
.loc_0x544:
lwz r3, 0x98(r31)
li r4, 0
lbz r0, 0xC(r3)
rlwimi r0,r4,7,24,24
stb r0, 0xC(r3)
b .loc_0xE28
lwz r3, 0xD4(r31)
mr r4, r28
bl 0x8818
cmpwi r3, 0x4
blt- .loc_0xE28
cmpwi r3, 0x5
bne- .loc_0x5B8
lwz r6, 0x30(r31)
li r4, 0
lwz r5, 0x34(r31)
lwz r3, 0x8(r6)
lbz r0, 0xC(r3)
rlwimi r0,r4,7,24,24
stb r0, 0xC(r3)
stw r4, 0x0(r6)
stw r5, 0x30(r31)
lwz r3, 0x30(r31)
bl -0xE25C
li r0, 0x3
stw r0, 0x1C(r31)
lfs f0, -0x4EF8(r2)
stfs f0, 0xC8(r31)
b .loc_0xE28
.loc_0x5B8:
lfs f0, -0x4EF8(r2)
stfs f0, 0xC4(r31)
lwz r0, 0x20(r31)
cmpwi r0, 0xA
bne- .loc_0x60C
lwz r6, 0x30(r31)
li r4, 0
lwz r5, 0x64(r31)
lwz r3, 0x8(r6)
lbz r0, 0xC(r3)
rlwimi r0,r4,7,24,24
stb r0, 0xC(r3)
stw r4, 0x0(r6)
stw r5, 0x30(r31)
lwz r3, 0x30(r31)
bl -0xE2B0
li r0, 0xA
stw r0, 0x1C(r31)
lwz r3, 0xD4(r31)
bl 0x8568
b .loc_0x65C
.loc_0x60C:
cmpwi r0, 0xB
bne- .loc_0x654
lwz r6, 0x30(r31)
li r4, 0
lwz r5, 0x68(r31)
lwz r3, 0x8(r6)
lbz r0, 0xC(r3)
rlwimi r0,r4,7,24,24
stb r0, 0xC(r3)
stw r4, 0x0(r6)
stw r5, 0x30(r31)
lwz r3, 0x30(r31)
bl -0xE2F8
li r0, 0xB
stw r0, 0x1C(r31)
lwz r3, 0xD4(r31)
bl 0x8520
b .loc_0x65C
.loc_0x654:
li r0, 0x1
stw r0, 0x1C(r31)
.loc_0x65C:
lfs f0, -0x4EF8(r2)
stfs f0, 0xC8(r31)
b .loc_0xE28
lwz r3, 0x30(r31)
lwz r0, 0x0(r3)
cmpwi r0, 0x2
bne- .loc_0x680
li r0, 0x1
b .loc_0x684
.loc_0x680:
li r0, 0
.loc_0x684:
rlwinm. r0,r0,0,24,31
beq- .loc_0x6E4
li r0, 0x4
stw r0, 0x1C(r31)
lwz r0, 0xD8(r31)
lwz r3, 0xAC(r31)
stw r0, 0x10C(r3)
lwz r0, 0xDC(r31)
lwz r3, 0xB0(r31)
stw r0, 0x10C(r3)
lwz r0, 0xD8(r31)
lwz r3, 0xB4(r31)
stw r0, 0x10C(r3)
lwz r0, 0xDC(r31)
lwz r3, 0xB8(r31)
stw r0, 0x10C(r3)
lwz r3, 0xD4(r31)
bl 0x84A4
lwz r3, 0x98(r31)
li r4, 0x1
lbz r0, 0xC(r3)
rlwimi r0,r4,7,24,24
stb r0, 0xC(r3)
b .loc_0xE28
.loc_0x6E4:
lwz r3, 0x98(r31)
li r4, 0
lbz r0, 0xC(r3)
rlwimi r0,r4,7,24,24
stb r0, 0xC(r3)
b .loc_0xE28
lwz r3, 0xD4(r31)
mr r4, r28
bl 0x8678
cmpwi r3, 0x4
blt- .loc_0xE28
cmpwi r3, 0x5
bne- .loc_0x86C
lwz r5, 0x30(r31)
li r28, 0
lwz r4, 0x40(r31)
lwz r3, 0x8(r5)
lbz r0, 0xC(r3)
rlwimi r0,r28,7,24,24
stb r0, 0xC(r3)
stw r28, 0x0(r5)
stw r4, 0x30(r31)
lwz r3, 0x30(r31)
bl -0xE3FC
li r0, 0x5
stw r0, 0x1C(r31)
lis r8, 0x4330
addi r5, r1, 0x334
lwz r3, 0x98(r31)
li r4, 0x27
li r6, 0
lbz r0, 0xC(r3)
rlwimi r0,r28,7,24,24
li r7, 0
stb r0, 0xC(r3)
lwz r3, 0x9C(r31)
lbz r0, 0xC(r3)
rlwimi r0,r28,7,24,24
stb r0, 0xC(r3)
lfs f0, -0x4EF8(r2)
stfs f0, 0xC8(r31)
lwz r9, 0xA8(r31)
stfs f0, 0x33C(r1)
stfs f0, 0x338(r1)
stfs f0, 0x334(r1)
lfs f1, 0xD78(r13)
lfs f0, 0xD7C(r13)
stfs f1, 0x334(r1)
stfs f0, 0x338(r1)
lfs f0, 0xD80(r13)
stfs f0, 0x33C(r1)
lha r10, 0x18(r9)
lha r3, 0x1C(r9)
xoris r0, r10, 0x8000
lfd f4, -0x4EF0(r2)
stw r0, 0x364(r1)
sub r3, r3, r10
xoris r0, r3, 0x8000
lfs f3, -0x4EFC(r2)
stw r0, 0x35C(r1)
lfs f2, -0x4EF4(r2)
stw r8, 0x358(r1)
lfd f0, 0x358(r1)
stw r8, 0x360(r1)
fsubs f0, f0, f4
lfd f1, 0x360(r1)
fsubs f1, f1, f4
fmuls f0, f0, f3
fadds f0, f1, f0
stfs f0, 0x334(r1)
lha r10, 0x1A(r9)
lha r3, 0x1E(r9)
xoris r0, r10, 0x8000
stw r0, 0x354(r1)
sub r3, r3, r10
xoris r0, r3, 0x8000
stw r0, 0x34C(r1)
stw r8, 0x348(r1)
lfd f0, 0x348(r1)
stw r8, 0x350(r1)
fsubs f0, f0, f4
lfd f1, 0x350(r1)
fsubs f1, f1, f4
fmuls f0, f0, f3
fadds f0, f1, f0
fsubs f0, f2, f0
stfs f0, 0x338(r1)
lwz r3, 0xC(r31)
bl 0x5B21C
stw r3, 0x10(r31)
addi r5, r1, 0x334
li r4, 0x28
lwz r3, 0xC(r31)
li r6, 0
li r7, 0
bl 0x5B200
stw r3, 0x14(r31)
b .loc_0xE28
.loc_0x86C:
lwz r0, 0x20(r31)
cmpwi r0, 0xA
bne- .loc_0x8A8
lwz r6, 0x30(r31)
li r4, 0
lwz r5, 0x48(r31)
lwz r3, 0x8(r6)
lbz r0, 0xC(r3)
rlwimi r0,r4,7,24,24
stb r0, 0xC(r3)
stw r4, 0x0(r6)
stw r5, 0x30(r31)
lwz r3, 0x30(r31)
bl -0xE55C
b .loc_0x8DC
.loc_0x8A8:
cmpwi r0, 0xB
bne- .loc_0x8DC
lwz r6, 0x30(r31)
li r4, 0
lwz r5, 0x44(r31)
lwz r3, 0x8(r6)
lbz r0, 0xC(r3)
rlwimi r0,r4,7,24,24
stb r0, 0xC(r3)
stw r4, 0x0(r6)
stw r5, 0x30(r31)
lwz r3, 0x30(r31)
bl -0xE594
.loc_0x8DC:
lfs f0, -0x4EF8(r2)
li r0, 0x1
stfs f0, 0xC8(r31)
stw r0, 0x1C(r31)
b .loc_0xE28
lwz r3, 0x98(r31)
li r4, 0
li r5, 0x1
lbz r0, 0xC(r3)
rlwimi r0,r4,7,24,24
stb r0, 0xC(r3)
lwz r3, 0x9C(r31)
lbz r0, 0xC(r3)
rlwimi r0,r5,7,24,24
stb r0, 0xC(r3)
lwz r3, 0x30(r31)
lwz r0, 0x0(r3)
cmpwi r0, 0x2
bne- .loc_0x92C
b .loc_0x930
.loc_0x92C:
mr r5, r4
.loc_0x930:
rlwinm. r0,r5,0,24,31
beq- .loc_0xE28
lfs f1, 0xC8(r31)
lfs f0, -0x4EE8(r2)
fcmpo cr0, f1, f0
ble- .loc_0xE28
lwz r4, 0x10(r31)
lis r3, 0x803A
subi r3, r3, 0x2848
lwz r0, 0x80(r4)
addi r3, r3, 0x24
li r28, 0x1
ori r0, r0, 0x2
stw r0, 0x80(r4)
lwz r4, 0x14(r31)
lwz r0, 0x80(r4)
ori r0, r0, 0x2
stw r0, 0x80(r4)
bl -0x118E38
cmpwi r3, 0
beq- .loc_0x988
li r28, 0
.loc_0x988:
rlwinm. r0,r28,0,24,31
beq- .loc_0x9E4
lwz r6, 0x30(r31)
li r4, 0
lwz r5, 0x38(r31)
lwz r3, 0x8(r6)
lbz r0, 0xC(r3)
rlwimi r0,r4,7,24,24
stb r0, 0xC(r3)
stw r4, 0x0(r6)
stw r5, 0x30(r31)
lwz r3, 0x30(r31)
bl -0xE674
lwz r3, 0xA4(r31)
li r4, 0x1
lbz r0, 0xC(r3)
rlwimi r0,r4,7,24,24
stb r0, 0xC(r3)
lwz r3, 0xA0(r31)
bl -0xF434
li r0, 0x6
stw r0, 0x1C(r31)
b .loc_0xE28
.loc_0x9E4:
lwz r6, 0x30(r31)
li r4, 0
lwz r5, 0x3C(r31)
lwz r3, 0x8(r6)
lbz r0, 0xC(r3)
rlwimi r0,r4,7,24,24
stb r0, 0xC(r3)
stw r4, 0x0(r6)
stw r5, 0x30(r31)
lwz r3, 0x30(r31)
bl -0xE6C8
lwz r3, 0xA4(r31)
li r4, 0x1
lbz r0, 0xC(r3)
rlwimi r0,r4,7,24,24
stb r0, 0xC(r3)
lwz r3, 0xA0(r31)
bl -0xF488
li r0, 0x7
stw r0, 0x1C(r31)
b .loc_0xE28
lwz r3, 0x98(r31)
li r5, 0
li r4, 0x1
lbz r0, 0xC(r3)
rlwimi r0,r5,7,24,24
stb r0, 0xC(r3)
lwz r3, 0x9C(r31)
lbz r0, 0xC(r3)
rlwimi r0,r4,7,24,24
stb r0, 0xC(r3)
lwz r3, 0xA0(r31)
bl -0xF3F8
lis r3, 0x100
lwz r4, 0x28(r28)
addi r0, r3, 0x1000
and. r0, r4, r0
beq- .loc_0xE28
li r3, 0x111
bl -0xE97E8
lfs f0, -0x4EF8(r2)
lis r3, 0x803A
subi r3, r3, 0x2848
stfs f0, 0xC4(r31)
lwz r0, 0x5C(r3)
cmpwi r0, 0
bge- .loc_0xABC
lwz r3, 0x18(r31)
bl 0x517C
li r0, 0xF
stw r0, 0x1C(r31)
lfs f0, -0x4EF8(r2)
stfs f0, 0xC8(r31)
b .loc_0xE28
.loc_0xABC:
li r0, 0x15
stw r0, 0x1C(r31)
b .loc_0xE28
lwz r3, 0xA0(r31)
bl -0xF460
lis r3, 0x100
lwz r4, 0x28(r28)
addi r0, r3, 0x1000
and. r0, r4, r0
beq- .loc_0xE28
li r3, 0x111
bl -0xE9850
lfs f0, -0x4EF8(r2)
li r0, -0x1
addi r3, r31, 0
stfs f0, 0xC4(r31)
stw r0, 0x1C(r31)
bl -0xEB4
b .loc_0xE28
lwz r3, 0x18(r31)
mr r4, r28
bl 0x51FC
cmpwi r3, 0x4
bne- .loc_0xB28
li r0, 0x15
stw r0, 0x1C(r31)
b .loc_0xE28
.loc_0xB28:
cmpwi r3, 0x5
bne- .loc_0xE28
lwz r6, 0x30(r31)
li r4, 0
lwz r5, 0x68(r31)
lwz r3, 0x8(r6)
lbz r0, 0xC(r3)
rlwimi r0,r4,7,24,24
stb r0, 0xC(r3)
stw r4, 0x0(r6)
stw r5, 0x30(r31)
lwz r3, 0x30(r31)
bl -0xE814
li r0, 0xB
stw r0, 0x1C(r31)
lwz r0, 0xD8(r31)
lwz r3, 0xAC(r31)
stw r0, 0x10C(r3)
lwz r0, 0xDC(r31)
lwz r3, 0xB0(r31)
stw r0, 0x10C(r3)
lwz r0, 0xD8(r31)
lwz r3, 0xB4(r31)
stw r0, 0x10C(r3)
lwz r0, 0xDC(r31)
lwz r3, 0xB8(r31)
stw r0, 0x10C(r3)
lwz r3, 0xD4(r31)
bl 0x7FD4
lfs f0, -0x4EF8(r2)
stfs f0, 0xC4(r31)
stfs f0, 0xC8(r31)
b .loc_0xE28
lwz r3, 0x98(r31)
li r4, 0
li r5, 0x1
lbz r0, 0xC(r3)
rlwimi r0,r4,7,24,24
stb r0, 0xC(r3)
lwz r3, 0x9C(r31)
lbz r0, 0xC(r3)
rlwimi r0,r5,7,24,24
stb r0, 0xC(r3)
lwz r3, 0x30(r31)
lwz r0, 0x0(r3)
cmpwi r0, 0x2
bne- .loc_0xBE8
b .loc_0xBEC
.loc_0xBE8:
mr r5, r4
.loc_0xBEC:
rlwinm. r0,r5,0,24,31
beq- .loc_0xE28
lfs f1, 0xC8(r31)
lfs f0, -0x4EE4(r2)
fcmpo cr0, f1, f0
ble- .loc_0xE28
lis r3, 0x803A
subi r3, r3, 0x2848
addi r3, r3, 0x24
bl -0x1182C4
rlwinm r0,r3,0,24,31
cntlzw r0, r0
rlwinm. r0,r0,27,24,31
beq- .loc_0xC5C
li r0, 0x11
stw r0, 0x1C(r31)
li r4, 0
lwz r6, 0x30(r31)
lwz r5, 0x50(r31)
lwz r3, 0x8(r6)
lbz r0, 0xC(r3)
rlwimi r0,r4,7,24,24
stb r0, 0xC(r3)
stw r4, 0x0(r6)
stw r5, 0x30(r31)
lwz r3, 0x30(r31)
bl -0xE910
b .loc_0xC90
.loc_0xC5C:
li r0, 0x12
stw r0, 0x1C(r31)
li r4, 0
lwz r6, 0x30(r31)
lwz r5, 0x54(r31)
lwz r3, 0x8(r6)
lbz r0, 0xC(r3)
rlwimi r0,r4,7,24,24
stb r0, 0xC(r3)
stw r4, 0x0(r6)
stw r5, 0x30(r31)
lwz r3, 0x30(r31)
bl -0xE948
.loc_0xC90:
lfs f0, -0x4EF8(r2)
stfs f0, 0xC8(r31)
lwz r3, 0xA0(r31)
bl -0xF6FC
b .loc_0xE28
lwz r3, 0x98(r31)
li r4, 0
li r5, 0x1
lbz r0, 0xC(r3)
rlwimi r0,r4,7,24,24
stb r0, 0xC(r3)
lwz r3, 0x9C(r31)
lbz r0, 0xC(r3)
rlwimi r0,r5,7,24,24
stb r0, 0xC(r3)
lwz r3, 0x30(r31)
lwz r0, 0x0(r3)
cmpwi r0, 0x2
bne- .loc_0xCE0
b .loc_0xCE4
.loc_0xCE0:
mr r5, r4
.loc_0xCE4:
rlwinm. r0,r5,0,24,31
beq- .loc_0xE28
lwz r3, 0xA4(r31)
li r4, 0x1
lbz r0, 0xC(r3)
rlwimi r0,r4,7,24,24
stb r0, 0xC(r3)
lwz r3, 0xA0(r31)
bl -0xF698
lis r3, 0x100
lwz r4, 0x28(r28)
addi r0, r3, 0x1000
and. r0, r4, r0
beq- .loc_0xE28
li r3, 0x111
bl -0xE9A88
li r0, 0x15
stw r0, 0x1C(r31)
b .loc_0xE28
lwz r3, 0x98(r31)
li r4, 0
li r5, 0x1
lbz r0, 0xC(r3)
rlwimi r0,r4,7,24,24
stb r0, 0xC(r3)
lwz r3, 0x9C(r31)
lbz r0, 0xC(r3)
rlwimi r0,r5,7,24,24
stb r0, 0xC(r3)
lwz r3, 0x30(r31)
lwz r0, 0x0(r3)
cmpwi r0, 0x2
bne- .loc_0xD6C
b .loc_0xD70
.loc_0xD6C:
mr r5, r4
.loc_0xD70:
rlwinm. r0,r5,0,24,31
beq- .loc_0xE28
lwz r3, 0xA4(r31)
li r4, 0x1
lbz r0, 0xC(r3)
rlwimi r0,r4,7,24,24
stb r0, 0xC(r3)
lwz r3, 0xA0(r31)
bl -0xF724
lis r3, 0x100
lwz r4, 0x28(r28)
addi r0, r3, 0x1000
and. r0, r4, r0
beq- .loc_0xE28
li r3, 0x111
bl -0xE9B14
lwz r6, 0x30(r31)
li r4, 0
lwz r5, 0x68(r31)
lwz r3, 0x8(r6)
lbz r0, 0xC(r3)
rlwimi r0,r4,7,24,24
stb r0, 0xC(r3)
stw r4, 0x0(r6)
stw r5, 0x30(r31)
lwz r3, 0x30(r31)
bl -0xEA94
li r0, 0xB
stw r0, 0x1C(r31)
lwz r0, 0xE4(r31)
lwz r3, 0xAC(r31)
stw r0, 0x10C(r3)
lwz r0, 0xE8(r31)
lwz r3, 0xB0(r31)
stw r0, 0x10C(r3)
lwz r0, 0xE4(r31)
lwz r3, 0xB4(r31)
stw r0, 0x10C(r3)
lwz r0, 0xE8(r31)
lwz r3, 0xB8(r31)
stw r0, 0x10C(r3)
lwz r3, 0xD4(r31)
bl 0x7D54
lfs f0, -0x4EF8(r2)
stfs f0, 0xC4(r31)
stfs f0, 0xC8(r31)
.loc_0xE28:
mr r3, r31
bl 0x1A8
lwz r3, 0x1C(r31)
cmpwi r3, 0x13
blt- .loc_0xE40
b .loc_0xEA4
.loc_0xE40:
lwz r3, 0xC(r31)
bl 0x5AC68
lwz r3, 0x2C(r31)
bl 0x23C28
lwz r3, 0xBC(r31)
bl -0xF7E8
lwz r3, 0x30(r31)
bl -0xE59C
lwz r4, 0x30(r31)
lwz r3, 0xC0(r31)
lwz r7, 0x8(r4)
lwz r12, 0x0(r3)
lha r4, 0x116(r7)
lwz r12, 0x14(r12)
subi r5, r4, 0x18
lha r0, 0x1A(r7)
lha r6, 0x114(r7)
mtlr r12
lha r4, 0x18(r7)
add r5, r0, r5
add r4, r4, r6
blrl
lwz r3, 0x24(r31)
bl 0x23BD8
lwz r3, 0x1C(r31)
.loc_0xEA4:
lwz r0, 0x37C(r1)
lwz r31, 0x374(r1)
lwz r30, 0x370(r1)
lwz r29, 0x36C(r1)
lwz r28, 0x368(r1)
addi r1, r1, 0x378
mtlr r0
blr
*/
}
/*
* --INFO--
* Address: 8018EFA0
* Size: 000110
*/
void zen::ogScrMemChkMgr::draw(Graphics&)
{
/*
.loc_0x0:
mflr r0
stw r0, 0x4(r1)
stwu r1, -0x100(r1)
stw r31, 0xFC(r1)
addi r31, r4, 0
stw r30, 0xF8(r1)
mr r30, r3
lwz r0, 0x1C(r3)
cmpwi r0, -0x1
beq- .loc_0xF8
cmpwi r0, 0x13
bge- .loc_0xF8
lha r3, 0x8(r30)
cmpwi r3, 0
ble- .loc_0x48
subi r0, r3, 0x1
sth r0, 0x8(r30)
b .loc_0xF8
.loc_0x48:
lfs f1, -0x4EE0(r2)
addi r3, r1, 0x10
lfs f2, -0x4F00(r2)
li r4, 0
lfs f3, -0x4EDC(r2)
li r5, 0
li r6, 0x280
li r7, 0x1E0
bl 0x21188
addi r3, r1, 0x10
bl 0x21290
lwz r3, 0x24(r30)
addi r6, r1, 0x10
li r4, 0
li r5, 0
bl 0x23EB0
lwz r3, 0x1C(r30)
subi r0, r3, 0x8
cmplwi r0, 0xD
bgt- .loc_0xC0
lis r3, 0x802D
addi r3, r3, 0x5D90
rlwinm r0,r0,2,0,29
lwzx r0, r3, r0
mtctr r0
bctr
lwz r3, 0x18(r30)
mr r4, r31
bl 0x50E4
b .loc_0xE0
.loc_0xC0:
lwz r3, 0x2C(r30)
addi r6, r1, 0x10
li r4, 0
li r5, 0
bl 0x23E64
lwz r3, 0xC(r30)
mr r4, r31
bl 0x5AB30
.loc_0xE0:
lis r3, 0x802E
addi r0, r3, 0x698
lis r3, 0x802E
stw r0, 0x10(r1)
addi r0, r3, 0x5D4
stw r0, 0x10(r1)
.loc_0xF8:
lwz r0, 0x104(r1)
lwz r31, 0xFC(r1)
lwz r30, 0xF8(r1)
addi r1, r1, 0x100
mtlr r0
blr
*/
}
/*
* --INFO--
* Address: 8018F0B0
* Size: 000144
*/
void zen::ogScrMemChkMgr::setErrorMessage()
{
/*
.loc_0x0:
lwz r4, 0xEC(r3)
li r5, 0
lbz r0, 0xC(r4)
rlwimi r0,r5,7,24,24
stb r0, 0xC(r4)
lwz r4, 0x100(r3)
lbz r0, 0xC(r4)
rlwimi r0,r5,7,24,24
stb r0, 0xC(r4)
lwz r4, 0xF8(r3)
lbz r0, 0xC(r4)
rlwimi r0,r5,7,24,24
stb r0, 0xC(r4)
lwz r4, 0xFC(r3)
lbz r0, 0xC(r4)
rlwimi r0,r5,7,24,24
stb r0, 0xC(r4)
lwz r4, 0xF0(r3)
lbz r0, 0xC(r4)
rlwimi r0,r5,7,24,24
stb r0, 0xC(r4)
lwz r4, 0xF4(r3)
lbz r0, 0xC(r4)
rlwimi r0,r5,7,24,24
stb r0, 0xC(r4)
lwz r4, 0x104(r3)
lbz r0, 0xC(r4)
rlwimi r0,r5,7,24,24
stb r0, 0xC(r4)
lwz r4, 0x1C(r3)
subi r0, r4, 0x8
cmplwi r0, 0x6
bgtlr-
lis r4, 0x802D
addi r4, r4, 0x5DC8
rlwinm r0,r0,2,0,29
lwzx r0, r4, r0
mtctr r0
bctr
lwz r3, 0xEC(r3)
li r4, 0x1
lbz r0, 0xC(r3)
rlwimi r0,r4,7,24,24
stb r0, 0xC(r3)
blr
lwz r3, 0x100(r3)
li r4, 0x1
lbz r0, 0xC(r3)
rlwimi r0,r4,7,24,24
stb r0, 0xC(r3)
blr
lwz r3, 0xF8(r3)
li r4, 0x1
lbz r0, 0xC(r3)
rlwimi r0,r4,7,24,24
stb r0, 0xC(r3)
blr
lwz r3, 0xFC(r3)
li r4, 0x1
lbz r0, 0xC(r3)
rlwimi r0,r4,7,24,24
stb r0, 0xC(r3)
blr
lwz r3, 0xF0(r3)
li r4, 0x1
lbz r0, 0xC(r3)
rlwimi r0,r4,7,24,24
stb r0, 0xC(r3)
blr
lwz r3, 0xF4(r3)
li r4, 0x1
lbz r0, 0xC(r3)
rlwimi r0,r4,7,24,24
stb r0, 0xC(r3)
blr
lwz r3, 0x104(r3)
li r4, 0x1
lbz r0, 0xC(r3)
rlwimi r0,r4,7,24,24
stb r0, 0xC(r3)
blr
*/
}
| 21.65553 | 72 | 0.445834 | doldecomp |
999b58fbe9d4d5df8957295ec48722cdc36a28f0 | 1,344 | cpp | C++ | Main course/Homework1/Problem 2/Source files/Error.cpp | nia-flo/FMI-OOP | 9d6ab384b5b7a48e76965ca5bff1e6a995b1bcba | [
"MIT"
] | null | null | null | Main course/Homework1/Problem 2/Source files/Error.cpp | nia-flo/FMI-OOP | 9d6ab384b5b7a48e76965ca5bff1e6a995b1bcba | [
"MIT"
] | null | null | null | Main course/Homework1/Problem 2/Source files/Error.cpp | nia-flo/FMI-OOP | 9d6ab384b5b7a48e76965ca5bff1e6a995b1bcba | [
"MIT"
] | null | null | null | #pragma warning (disable : 4996)
#include "Error.hpp"
Error::Error()
{
this->message = nullptr;
}
Error::Error(ErrorType type, const char* message = "")
{
this->type = type;
this->setMessage(message);
}
Error::Error(const Error& error)
{
this->Copy(error);
}
Error& Error::operator=(const Error& error)
{
delete[] this->message;
this->Copy(error);
return *this;
}
Error::~Error()
{
delete[] this->message;
}
bool Error::hasMessage() const
{
return (this->type != ErrorType::None);
}
const char* Error::getMessage() const
{
if (this->type == ErrorType::None)
{
return nullptr;
}
return this->message;
}
ErrorType Error::getType() const
{
return this->type;
}
Error Error::newNone()
{
Error error(ErrorType::None);
return error;
}
Error Error::newBuildFailed(const char* message)
{
Error error(ErrorType::BuildFailed, message);
return error;
}
Error Error::newWarning(const char* message)
{
Error error(ErrorType::Warning, message);
return error;
}
Error Error::newFailedAssertion(const char* message)
{
Error error(ErrorType::FailedAssertion, message);
return error;
}
void Error::setMessage(const char* message)
{
this->message = new char[strlen(message) + 1];
strcpy(this->message, message);
}
void Error::Copy(const Error& error)
{
this->type = error.type;
this->setMessage(error.message);
}
| 14.297872 | 54 | 0.689732 | nia-flo |
99a006008cbdbbe1b663573492920864f2d6aa5a | 3,204 | cpp | C++ | src/Systems/DX11RenderSystem/DX11RenderIndexBuffer.cpp | irov/Mengine | b76e9f8037325dd826d4f2f17893ac2b236edad8 | [
"MIT"
] | 39 | 2016-04-21T03:25:26.000Z | 2022-01-19T14:16:38.000Z | src/Systems/DX11RenderSystem/DX11RenderIndexBuffer.cpp | irov/Mengine | b76e9f8037325dd826d4f2f17893ac2b236edad8 | [
"MIT"
] | 23 | 2016-06-28T13:03:17.000Z | 2022-02-02T10:11:54.000Z | src/Systems/DX11RenderSystem/DX11RenderIndexBuffer.cpp | irov/Mengine | b76e9f8037325dd826d4f2f17893ac2b236edad8 | [
"MIT"
] | 14 | 2016-06-22T20:45:37.000Z | 2021-07-05T12:25:19.000Z | #include "DX11RenderIndexBuffer.h"
#include "Interface/MemoryServiceInterface.h"
#include "DX11RenderEnum.h"
#include "DX11RenderErrorHelper.h"
#include "Kernel/Assertion.h"
#include "Kernel/AssertionMemoryPanic.h"
#include "Kernel/Logger.h"
#include "Kernel/Documentable.h"
#include "Kernel/DocumentHelper.h"
#include "Kernel/DocumentableHelper.h"
#include "stdex/memorycopy.h"
namespace Mengine
{
//////////////////////////////////////////////////////////////////////////
DX11RenderIndexBuffer::DX11RenderIndexBuffer()
{
}
//////////////////////////////////////////////////////////////////////////
DX11RenderIndexBuffer::~DX11RenderIndexBuffer()
{
}
//////////////////////////////////////////////////////////////////////////
bool DX11RenderIndexBuffer::initialize( uint32_t _indexSize, EBufferType _bufferType )
{
m_format = Helper::getD3DIndexFormat();
return this->initializeBuffer( _indexSize, _bufferType );
}
//////////////////////////////////////////////////////////////////////////
void DX11RenderIndexBuffer::finalize()
{
this->finalizeBuffer();
}
//////////////////////////////////////////////////////////////////////////
uint32_t DX11RenderIndexBuffer::getIndexCount() const
{
return this->getElementsCount();
}
//////////////////////////////////////////////////////////////////////////
uint32_t DX11RenderIndexBuffer::getIndexSize() const
{
return this->getElementSize();
}
//////////////////////////////////////////////////////////////////////////
bool DX11RenderIndexBuffer::resize( uint32_t _indexCount )
{
// TODO: in D3D11 we can create static bufferes without lock - if we provide data pointer on creation
return this->resizeBuffer( D3D11_BIND_INDEX_BUFFER, _indexCount, nullptr );
}
//////////////////////////////////////////////////////////////////////////
MemoryInterfacePtr DX11RenderIndexBuffer::lock( uint32_t _offset, uint32_t _count )
{
return this->lockBuffer( _offset, _count );
}
//////////////////////////////////////////////////////////////////////////
bool DX11RenderIndexBuffer::unlock()
{
return this->unlockBuffer();
}
//////////////////////////////////////////////////////////////////////////
bool DX11RenderIndexBuffer::draw( const void * _buffer, uint32_t _offset, uint32_t _count )
{
return this->drawBuffer( _buffer, _offset, _count );
}
//////////////////////////////////////////////////////////////////////////
void DX11RenderIndexBuffer::enable( const ID3D11DeviceContextPtr & _pImmediateContext )
{
UINT sOffset = 0;
ID3D11Buffer * pD3DBuffer = m_pD3DBuffer.Get();
_pImmediateContext->IASetIndexBuffer( pD3DBuffer, m_format, sOffset );
}
//////////////////////////////////////////////////////////////////////////
void DX11RenderIndexBuffer::disable( const ID3D11DeviceContextPtr & _pImmediateContext )
{
_pImmediateContext->IASetIndexBuffer( nullptr, m_format, 0 );
}
//////////////////////////////////////////////////////////////////////////
} | 38.142857 | 109 | 0.476592 | irov |
99a64c2046bd3797e2f38619fa843fa176b32fab | 4,997 | cpp | C++ | unit_tests/stencil_composition/structured_grids/test_expandable_parameters.cpp | aurianer/gridtools | 5f99471bf36215e2a53317d2c7844bf057231ffa | [
"BSD-3-Clause"
] | null | null | null | unit_tests/stencil_composition/structured_grids/test_expandable_parameters.cpp | aurianer/gridtools | 5f99471bf36215e2a53317d2c7844bf057231ffa | [
"BSD-3-Clause"
] | null | null | null | unit_tests/stencil_composition/structured_grids/test_expandable_parameters.cpp | aurianer/gridtools | 5f99471bf36215e2a53317d2c7844bf057231ffa | [
"BSD-3-Clause"
] | null | null | null | /*
* GridTools
*
* Copyright (c) 2014-2019, ETH Zurich
* All rights reserved.
*
* Please, refer to the LICENSE file in the root directory.
* SPDX-License-Identifier: BSD-3-Clause
*/
#include <gtest/gtest.h>
#include <gridtools/stencil_composition/cartesian.hpp>
#include <gridtools/tools/cartesian_fixture.hpp>
using namespace gridtools;
using namespace cartesian;
using namespace expressions;
struct expandable_parameters : computation_fixture<> {
expandable_parameters() : computation_fixture<>(13, 9, 7) {}
using storages_t = std::vector<storage_type>;
template <class Comp, class... Args>
void run_computation(Comp comp, Args &&... args) const {
expandable_run<2>(comp, backend_t(), make_grid(), std::forward<Args>(args)...);
}
void verify(storages_t const &expected, storages_t const &actual) const {
EXPECT_EQ(expected.size(), actual.size());
for (size_t i = 0; i != expected.size(); ++i)
computation_fixture<>::verify(expected[i], actual[i]);
}
};
struct expandable_parameters_copy : expandable_parameters {
storages_t out = {make_storage(1.), make_storage(2.), make_storage(3.), make_storage(4.), make_storage(5.)};
storages_t in = {make_storage(-1.), make_storage(-2.), make_storage(-3.), make_storage(-4.), make_storage(-5.)};
template <class Functor>
void run_computation() {
expandable_parameters::run_computation(
[](auto out, auto in) { return execute_parallel().stage(Functor(), out, in); }, out, in);
}
~expandable_parameters_copy() { verify(in, out); }
};
struct copy_functor {
typedef inout_accessor<0> out;
typedef in_accessor<1> in;
typedef make_param_list<out, in> param_list;
template <typename Evaluation>
GT_FUNCTION static void apply(Evaluation &eval) {
eval(out{}) = eval(in{});
}
};
TEST_F(expandable_parameters_copy, copy) { run_computation<copy_functor>(); }
struct copy_functor_with_expression {
typedef inout_accessor<0> out;
typedef in_accessor<1> in;
typedef make_param_list<out, in> param_list;
template <typename Evaluation>
GT_FUNCTION static void apply(Evaluation &eval) {
// use an expression which is equivalent to a copy to simplify the check
eval(out{}) = eval(2. * in{} - in{});
}
};
TEST_F(expandable_parameters_copy, copy_with_expression) { run_computation<copy_functor_with_expression>(); }
struct call_proc_copy_functor {
typedef inout_accessor<0> out;
typedef in_accessor<1> in;
typedef make_param_list<out, in> param_list;
template <typename Evaluation>
GT_FUNCTION static void apply(Evaluation &eval) {
call_proc<copy_functor>::with(eval, out(), in());
}
};
TEST_F(expandable_parameters_copy, call_proc_copy) { run_computation<call_proc_copy_functor>(); }
struct call_copy_functor {
typedef inout_accessor<0> out;
typedef in_accessor<1> in;
typedef make_param_list<out, in> param_list;
template <typename Evaluation>
GT_FUNCTION static void apply(Evaluation &eval) {
eval(out()) = call<copy_functor>::with(eval, in());
}
};
TEST_F(expandable_parameters_copy, call_copy) { run_computation<call_copy_functor>(); }
struct shift_functor {
typedef inout_accessor<0, extent<0, 0, 0, 0, -1, 0>> out;
typedef make_param_list<out> param_list;
template <typename Evaluation>
GT_FUNCTION static void apply(Evaluation &eval) {
eval(out()) = eval(out(0, 0, -1));
}
};
struct call_shift_functor {
typedef inout_accessor<0, extent<0, 0, 0, 0, -1, 0>> out;
typedef make_param_list<out> param_list;
template <typename Evaluation>
GT_FUNCTION static void apply(Evaluation &eval, axis<1>::full_interval::modify<1, 0>) {
call_proc<shift_functor>::with(eval, out());
}
template <typename Evaluation>
GT_FUNCTION static void apply(Evaluation &, axis<1>::full_interval::first_level) {}
};
TEST_F(expandable_parameters, call_shift) {
auto expected = [&](float_type value) { return make_storage([=](int_t, int_t, int_t) { return value; }); };
auto in = [&](float_type value) {
return make_storage([=](int_t, int_t, int_t k) { return k == 0 ? value : -1; });
};
storages_t actual = {in(14), in(15), in(16), in(17), in(18)};
run_computation([](auto x) { return execute_forward().stage(call_shift_functor(), x); }, actual);
verify({expected(14), expected(15), expected(16), expected(17), expected(18)}, actual);
}
TEST_F(expandable_parameters, caches) {
storages_t out = {make_storage(1.), make_storage(2.), make_storage(3.), make_storage(4.), make_storage(5.)};
auto in = make_storage(42.);
run_computation(
[](auto in, auto out) {
GT_DECLARE_TMP(float_type, tmp);
return execute_parallel().ij_cached(tmp).stage(copy_functor(), tmp, in).stage(copy_functor(), out, tmp);
},
in,
out);
verify({in, in, in, in, in}, out);
}
| 32.448052 | 116 | 0.675005 | aurianer |
99a8b5ca9f288db3306f8e5f8240b60a2c75a06a | 663 | cpp | C++ | plugins/opengl/src/convert/color_base_type.cpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | 2 | 2016-01-27T13:18:14.000Z | 2018-05-11T01:11:32.000Z | plugins/opengl/src/convert/color_base_type.cpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | null | null | null | plugins/opengl/src/convert/color_base_type.cpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | 3 | 2018-05-11T01:11:34.000Z | 2021-04-24T19:47:45.000Z | // Copyright Carl Philipp Reh 2006 - 2019.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <sge/opengl/color_base_type.hpp>
#include <sge/opengl/color_format.hpp>
#include <sge/opengl/convert/color_base_type.hpp>
#include <sge/opengl/convert/color_base_type_sge.hpp>
#include <sge/opengl/convert/color_format.hpp>
sge::opengl::color_base_type
sge::opengl::convert::color_base_type(sge::opengl::color_format const _format)
{
return sge::opengl::convert::color_base_type_sge(sge::opengl::convert::color_format(_format));
}
| 39 | 96 | 0.757164 | cpreh |
99aa51c3cc729e4252172bb14fabf9321e1c26de | 215 | cpp | C++ | test/CommandTest.cpp | jonathanabrahams/helloworldcpp | 52b00f47ef637557a74f3a98e88e64c39e8a45fa | [
"Apache-2.0"
] | null | null | null | test/CommandTest.cpp | jonathanabrahams/helloworldcpp | 52b00f47ef637557a74f3a98e88e64c39e8a45fa | [
"Apache-2.0"
] | null | null | null | test/CommandTest.cpp | jonathanabrahams/helloworldcpp | 52b00f47ef637557a74f3a98e88e64c39e8a45fa | [
"Apache-2.0"
] | null | null | null | #include "Command/MockICommand.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
using ::testing::AtLeast;
TEST( CommandTest, mock_icommand )
{
MockICommand cmd;
EXPECT_CALL( cmd, execute() ).Times(0);
} | 21.5 | 43 | 0.706977 | jonathanabrahams |
99ac6de728b5e321f59e511f91795163db9d3371 | 5,436 | hpp | C++ | include/RAJA/policy/openmp/forall.hpp | jonesholger/RAJA | e1f3de7f71637383665379c97802481bfce9318f | [
"BSD-3-Clause"
] | 1 | 2020-04-28T20:35:12.000Z | 2020-04-28T20:35:12.000Z | include/RAJA/policy/openmp/forall.hpp | jonesholger/RAJA | e1f3de7f71637383665379c97802481bfce9318f | [
"BSD-3-Clause"
] | null | null | null | include/RAJA/policy/openmp/forall.hpp | jonesholger/RAJA | e1f3de7f71637383665379c97802481bfce9318f | [
"BSD-3-Clause"
] | 1 | 2020-06-07T13:26:40.000Z | 2020-06-07T13:26:40.000Z | /*!
******************************************************************************
*
* \file
*
* \brief Header file containing RAJA index set and segment iteration
* template methods for OpenMP.
*
* These methods should work on any platform that supports OpenMP.
*
******************************************************************************
*/
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// Copyright (c) 2016-20, Lawrence Livermore National Security, LLC
// and RAJA project contributors. See the RAJA/COPYRIGHT file for details.
//
// SPDX-License-Identifier: (BSD-3-Clause)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
#ifndef RAJA_forall_openmp_HPP
#define RAJA_forall_openmp_HPP
#include "RAJA/config.hpp"
#if defined(RAJA_ENABLE_OPENMP)
#include <iostream>
#include <type_traits>
#include <omp.h>
#include "RAJA/util/types.hpp"
#include "RAJA/internal/fault_tolerance.hpp"
#include "RAJA/index/IndexSet.hpp"
#include "RAJA/index/ListSegment.hpp"
#include "RAJA/index/RangeSegment.hpp"
#include "RAJA/policy/openmp/policy.hpp"
#include "RAJA/pattern/forall.hpp"
#include "RAJA/pattern/region.hpp"
namespace RAJA
{
namespace policy
{
namespace omp
{
///
/// OpenMP parallel for policy implementation
///
template <typename Iterable, typename Func, typename InnerPolicy>
RAJA_INLINE void forall_impl(const omp_parallel_exec<InnerPolicy>&,
Iterable&& iter,
Func&& loop_body)
{
RAJA::region<RAJA::omp_parallel_region>([&]() {
using RAJA::internal::thread_privatize;
auto body = thread_privatize(loop_body);
forall_impl(InnerPolicy{}, iter, body.get_priv());
});
}
///
/// OpenMP for nowait policy implementation
///
template <typename Iterable, typename Func>
RAJA_INLINE void forall_impl(const omp_for_nowait_exec&,
Iterable&& iter,
Func&& loop_body)
{
RAJA_EXTRACT_BED_IT(iter);
#pragma omp for nowait
for (decltype(distance_it) i = 0; i < distance_it; ++i) {
loop_body(begin_it[i]);
}
}
///
/// OpenMP parallel for policy implementation
///
template <typename Iterable, typename Func>
RAJA_INLINE void forall_impl(const omp_for_exec&,
Iterable&& iter,
Func&& loop_body)
{
RAJA_EXTRACT_BED_IT(iter);
#pragma omp for
for (decltype(distance_it) i = 0; i < distance_it; ++i) {
loop_body(begin_it[i]);
}
}
///
/// OpenMP parallel for static policy implementation
///
template <typename Iterable, typename Func, size_t ChunkSize>
RAJA_INLINE void forall_impl(const omp_for_static<ChunkSize>&,
Iterable&& iter,
Func&& loop_body)
{
RAJA_EXTRACT_BED_IT(iter);
#pragma omp for schedule(static, ChunkSize)
for (decltype(distance_it) i = 0; i < distance_it; ++i) {
loop_body(begin_it[i]);
}
}
//
//////////////////////////////////////////////////////////////////////
//
// The following function templates iterate over index set
// segments using omp execution. Segment execution is defined by
// segment execution policy template parameter.
//
//////////////////////////////////////////////////////////////////////
//
/*!
******************************************************************************
*
* \brief Iterate over index set segments using an omp parallel loop and
* segment dependency graph. Individual segment execution will use
* execution policy template parameter.
*
* This method assumes that a task dependency graph has been
* properly set up for each segment in the index set.
*
******************************************************************************
*/
/*
* TODO: Fix this!!!
*/
/*
template <typename SEG_EXEC_POLICY_T, typename LOOP_BODY, typename ...
SEG_TYPES>
RAJA_INLINE void forall(
ExecPolicy<omp_taskgraph_segit, SEG_EXEC_POLICY_T>,
const IndexSet<SEG_TYPES ...>& iset,
LOOP_BODY loop_body)
{
if (!iset.dependencyGraphSet()) {
std::cerr << "\n RAJA IndexSet dependency graph not set , "
<< "FILE: " << __FILE__ << " line: " << __LINE__ << std::endl;
RAJA_ABORT_OR_THROW("IndexSet dependency graph");
}
IndexSet& ncis = (*const_cast<IndexSet*>(&iset));
int num_seg = ncis.getNumSegments();
#pragma omp parallel for schedule(static, 1)
for (int isi = 0; isi < num_seg; ++isi) {
IndexSetSegInfo* seg_info = ncis.getSegmentInfo(isi);
DepGraphNode* task = seg_info->getDepGraphNode();
task->wait();
executeRangeList_forall<SEG_EXEC_POLICY_T>(seg_info, loop_body);
task->reset();
if (task->numDepTasks() != 0) {
for (int ii = 0; ii < task->numDepTasks(); ++ii) {
// Alternateively, we could get the return value of this call
// and actively launch the task if we are the last depedent
// task. In that case, we would not need the semaphore spin
// loop above.
int seg = task->depTaskNum(ii);
DepGraphNode* dep = ncis.getSegmentInfo(seg)->getDepGraphNode();
dep->satisfyOne();
}
}
} // iterate over segments of index set
}
*/
} // namespace omp
} // namespace policy
} // namespace RAJA
#endif // closing endif for if defined(RAJA_ENABLE_OPENMP)
#endif // closing endif for header file include guard
| 27.18 | 79 | 0.585725 | jonesholger |
99aef4b087c02d4d5262f43db7eb358d9dc90b70 | 10,817 | cpp | C++ | src/demos/06_simple_fog/simple_fog.cpp | Shot511/RapidGL | eebad98eb38ea5f554beb75e151c47f5076e7088 | [
"MIT"
] | 1 | 2021-05-18T11:11:15.000Z | 2021-05-18T11:11:15.000Z | src/demos/06_simple_fog/simple_fog.cpp | Shot511/RapidGL | eebad98eb38ea5f554beb75e151c47f5076e7088 | [
"MIT"
] | 2 | 2021-04-24T07:33:38.000Z | 2021-07-08T15:10:26.000Z | src/demos/06_simple_fog/simple_fog.cpp | Shot511/RapidGL | eebad98eb38ea5f554beb75e151c47f5076e7088 | [
"MIT"
] | null | null | null | #include "simple_fog.h"
#include "filesystem.h"
#include "input.h"
#include "util.h"
#include "gui/gui.h"
#include <glm/gtc/matrix_inverse.hpp>
#include <random>
SimpleFog::SimpleFog()
: m_specular_power (120.0f),
m_specular_intenstiy(0.2f),
m_ambient_factor (0.18f),
m_gamma (2.2),
m_dir_light_angles (0.0f, 0.0f),
m_fog_color (0.5),
m_fog_distances (0.01, 30.0),
m_fog_density_exp (0.1),
m_fog_density_exp2 (0.1),
m_fog_equation (FogEquation::LINEAR)
{
m_fog_equation_names = { "fog_factor_linear", "fog_factor_exp", "fog_factor_exp2" };
}
SimpleFog::~SimpleFog()
{
}
void SimpleFog::init_app()
{
/* Initialize all the variables, buffers, etc. here. */
glClearColor(m_fog_color.r, m_fog_color.g, m_fog_color.b, 1.0);
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
glEnable(GL_MULTISAMPLE);
/* Create virtual camera. */
m_camera = std::make_shared<RGL::Camera>(60.0, RGL::Window::getAspectRatio(), 0.01, 100.0);
m_camera->setPosition(1.5, 0.0, 3.0);
/* Initialize lights' properties */
m_dir_light_properties.color = glm::vec3(1.0f);
m_dir_light_properties.intensity = 1.0f;
m_dir_light_properties.setDirection(m_dir_light_angles);
/* Create models. */
m_objects.emplace_back(RGL::StaticModel());
m_objects[0].GenPQTorusKnot(256, 16, 2, 3, 0.75, 0.15);
/* Set model matrices for each model. */
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_real_distribution<> dist(0.0, 1.0);
float step = 2.0;
for (unsigned i = 0; i < 20; ++i)
{
m_objects_model_matrices.emplace_back(glm::translate(glm::mat4(1.0), glm::vec3(step * i, 0.0, -step * i)));
m_objects_colors.emplace_back(dist(gen), dist(gen), dist(gen));
}
/* Add textures to the objects. */
auto default_diffuse_texture = std::make_shared<RGL::Texture2D>();
default_diffuse_texture->Load(RGL::FileSystem::getPath("textures/default_diffuse.png"), true);
m_objects[0].AddTexture(default_diffuse_texture);
/* Create shader. */
std::string dir = "../src/demos/06_simple_fog/";
std::string dir_lighting = "../src/demos/03_lighting/";
m_directional_light_shader = std::make_shared<RGL::Shader>(dir_lighting + "lighting.vert", dir + "lighting-directional_w_fog.frag");
m_directional_light_shader->link();
}
void SimpleFog::input()
{
/* Close the application when Esc is released. */
if (RGL::Input::getKeyUp(RGL::KeyCode::Escape))
{
stop();
}
/* Toggle between wireframe and solid rendering */
if (RGL::Input::getKeyUp(RGL::KeyCode::F2))
{
static bool toggle_wireframe = false;
toggle_wireframe = !toggle_wireframe;
if (toggle_wireframe)
{
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
}
else
{
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
}
}
/* It's also possible to take a screenshot. */
if (RGL::Input::getKeyUp(RGL::KeyCode::F1))
{
/* Specify filename of the screenshot. */
std::string filename = "06_simple_fog";
if (take_screenshot_png(filename, RGL::Window::getWidth() / 2.0, RGL::Window::getHeight() / 2.0))
{
/* If specified folders in the path are not already created, they'll be created automagically. */
std::cout << "Saved " << filename << ".png to " << RGL::FileSystem::getPath("../screenshots/") << std::endl;
}
else
{
std::cerr << "Could not save " << filename << ".png to " << RGL::FileSystem::getPath("../screenshots/") << std::endl;
}
}
}
void SimpleFog::update(double delta_time)
{
/* Update variables here. */
m_camera->update(delta_time);
}
void SimpleFog::render()
{
/* Put render specific code here. Don't update variables here! */
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
auto view_projection = m_camera->m_projection * m_camera->m_view;
/* Render directional light(s) */
m_directional_light_shader->bind();
m_directional_light_shader->setUniform("directional_light.base.color", m_dir_light_properties.color);
m_directional_light_shader->setUniform("directional_light.base.intensity", m_dir_light_properties.intensity);
m_directional_light_shader->setUniform("directional_light.direction", m_dir_light_properties.direction);
m_directional_light_shader->setUniform("cam_pos", m_camera->position());
m_directional_light_shader->setUniform("specular_intensity", m_specular_intenstiy.x);
m_directional_light_shader->setUniform("specular_power", m_specular_power.x);
m_directional_light_shader->setUniform("gamma", m_gamma);
m_directional_light_shader->setUniform("ambient_factor", m_ambient_factor);
m_directional_light_shader->setUniform("fog_color", m_fog_color);
m_directional_light_shader->setSubroutine(RGL::Shader::ShaderType::FRAGMENT, m_fog_equation_names[int(m_fog_equation)]);
if (m_fog_equation == FogEquation::LINEAR)
{
m_directional_light_shader->setUniform("fog_min_distance", m_fog_distances.x);
m_directional_light_shader->setUniform("fog_max_distance", m_fog_distances.y);
}
if (m_fog_equation == FogEquation::EXP)
{
m_directional_light_shader->setUniform("fog_density", m_fog_density_exp);
}
if (m_fog_equation == FogEquation::EXP2)
{
m_directional_light_shader->setUniform("fog_density", m_fog_density_exp2);
}
for (unsigned i = 0; i < m_objects_model_matrices.size(); ++i)
{
m_directional_light_shader->setUniform("model", m_objects_model_matrices[i]);
m_directional_light_shader->setUniform("normal_matrix", glm::mat3(glm::transpose(glm::inverse(m_objects_model_matrices[i]))));
m_directional_light_shader->setUniform("mvp", view_projection * m_objects_model_matrices[i]);
m_directional_light_shader->setUniform("object_color", m_objects_colors[i]);
m_objects[0].Render();
}
}
void SimpleFog::render_gui()
{
/* This method is responsible for rendering GUI using ImGUI. */
/*
* It's possible to call render_gui() from the base class.
* It renders performance info overlay.
*/
CoreApp::render_gui();
/* Create your own GUI using ImGUI here. */
ImVec2 window_pos = ImVec2(RGL::Window::getWidth() - 10.0, 10.0);
ImVec2 window_pos_pivot = ImVec2(1.0f, 0.0f);
ImGui::SetNextWindowPos(window_pos, ImGuiCond_Always, window_pos_pivot);
ImGui::SetNextWindowSize({ 400, 0 });
ImGui::Begin("Info");
{
if (ImGui::CollapsingHeader("Help"))
{
ImGui::Text("Controls info: \n\n"
"F1 - take a screenshot\n"
"F2 - toggle wireframe rendering\n"
"WASDQE - control camera movement\n"
"RMB - press to rotate the camera\n"
"Esc - close the app\n\n");
}
ImGui::Spacing();
ImGui::SetNextItemWidth(ImGui::GetContentRegionAvailWidth() * 0.5f);
ImGui::SliderFloat("Ambient color", &m_ambient_factor, 0.0, 1.0, "%.2f");
ImGui::SliderFloat("Gamma", &m_gamma, 0.0, 10.0, "%.1f");
ImGui::Spacing();
ImGuiTabBarFlags tab_bar_flags = ImGuiTabBarFlags_None;
if (ImGui::BeginTabBar("Lights' properties", tab_bar_flags))
{
if (ImGui::BeginTabItem("Fog"))
{
ImGui::PushItemWidth(ImGui::GetContentRegionAvailWidth() * 0.5f);
{
if (ImGui::BeginCombo("Fog equation", m_fog_equation_names[int(m_fog_equation)].c_str()))
{
for (int i = 0; i < m_fog_equation_names.size(); ++i)
{
bool is_selected = (m_fog_equation == FogEquation(i));
if (ImGui::Selectable(m_fog_equation_names[i].c_str(), is_selected))
{
m_fog_equation = FogEquation(i);
}
if (is_selected)
{
ImGui::SetItemDefaultFocus();
}
}
ImGui::EndCombo();
}
if (ImGui::ColorEdit3("Color", &m_fog_color[0]))
{
glClearColor(m_fog_color.r, m_fog_color.g, m_fog_color.b, 1.0);
}
if (m_fog_equation == FogEquation::LINEAR)
{
if (ImGui::SliderFloat2("Min/Max distance", &m_fog_distances[0], 0.0, 100.0, "%.1f"))
{
if (m_fog_distances.y <= m_fog_distances.x)
{
m_fog_distances.y = m_fog_distances.x + 0.1;
}
}
}
if (m_fog_equation == FogEquation::EXP)
{
ImGui::SliderFloat("Density", &m_fog_density_exp, 0.0, 1.0, "%.3f");
}
if (m_fog_equation == FogEquation::EXP2)
{
ImGui::SliderFloat("Density", &m_fog_density_exp2, 0.0, 1.0, "%.3f");
}
}
ImGui::PopItemWidth();
ImGui::EndTabItem();
}
if (ImGui::BeginTabItem("Directional"))
{
ImGui::PushItemWidth(ImGui::GetContentRegionAvailWidth() * 0.5f);
{
ImGui::ColorEdit3 ("Color", &m_dir_light_properties.color[0]);
ImGui::SliderFloat("Light intensity", &m_dir_light_properties.intensity, 0.0, 10.0, "%.1f");
ImGui::SliderFloat("Specular power", &m_specular_power.x, 1.0, 120.0, "%.0f");
ImGui::SliderFloat("Specular intensity", &m_specular_intenstiy.x, 0.0, 1.0, "%.2f");
if (ImGui::SliderFloat2("Azimuth and Elevation", &m_dir_light_angles[0], -180.0, 180.0, "%.1f"))
{
m_dir_light_properties.setDirection(m_dir_light_angles);
}
}
ImGui::PopItemWidth();
ImGui::EndTabItem();
}
ImGui::EndTabBar();
}
}
ImGui::End();
}
| 37.429066 | 136 | 0.569936 | Shot511 |
99b16c7a350e3d9599a4c935e5bbc78f18410d40 | 1,014 | cpp | C++ | AP325/P-4-1.cpp | Superdanby/YEE | 49a6349dc5644579246623b480777afbf8031fcd | [
"MIT"
] | 1 | 2019-09-07T15:56:05.000Z | 2019-09-07T15:56:05.000Z | AP325/P-4-1.cpp | Superdanby/YEE | 49a6349dc5644579246623b480777afbf8031fcd | [
"MIT"
] | null | null | null | AP325/P-4-1.cpp | Superdanby/YEE | 49a6349dc5644579246623b480777afbf8031fcd | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
constexpr const ll MOD = 1e9 + 9;
ll solve(vector<pair<ll, ll>> &line, vector<ll> &coor, int front, int end,
int lfront, int lend) {
if (front > end) return 0;
int point = (front + end) / 2;
int lans = lfront;
for (int i = lfront + 1; i <= lend; ++i) {
if (line[lans].first * coor[point] + line[lans].second <
line[i].first * coor[point] + line[i].second)
lans = i;
}
ll ans = line[lans].first * coor[point] + line[lans].second;
ans += solve(line, coor, front, point - 1, lfront, lans);
ans += solve(line, coor, point + 1, end, lans, lend);
return ans;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
int cases;
cin >> cases;
vector<int> coins{50, 10, 5, 1};
while (cases--) {
int num;
cin >> num;
int ans = 0;
for (int i = 0; i < coins.size(); ++i) {
ans += num / coins[i];
num %= coins[i];
}
cout << ans << "\n";
}
return 0;
}
| 22.533333 | 74 | 0.554241 | Superdanby |
99b75157d87d2d7e4a753691d2d04f108afa6f2b | 632 | cpp | C++ | sam-project/bakker-et-al-2012/SAM/SAM/tests/src/journal_test.cpp | amirmasoudabdol/bakker-et-al-2012-reproduction-using-sam | 518ab1cebaa80c19a12e92db8ae87386512ae053 | [
"MIT"
] | 1 | 2022-03-25T20:21:41.000Z | 2022-03-25T20:21:41.000Z | sam-project/bakker-et-al-2012/SAM/SAM/tests/src/journal_test.cpp | amirmasoudabdol/bakker-et-al-2012-reproduction-using-sam | 518ab1cebaa80c19a12e92db8ae87386512ae053 | [
"MIT"
] | null | null | null | sam-project/bakker-et-al-2012/SAM/SAM/tests/src/journal_test.cpp | amirmasoudabdol/bakker-et-al-2012-reproduction-using-sam | 518ab1cebaa80c19a12e92db8ae87386512ae053 | [
"MIT"
] | null | null | null | //
// Created by Amir Masoud Abdol on 2019-05-22.
//
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE Journal Tests
#include <boost/test/unit_test.hpp>
namespace tt = boost::test_tools;
#include <armadillo>
#include <iostream>
#include <vector>
#include <algorithm>
#include "sam.h"
#include "test_fixtures.h"
using namespace arma;
using namespace sam;
using namespace std;
bool FLAGS::VERBOSE = false;
bool FLAGS::PROGRESS = false;
bool FLAGS::DEBUG = false;
bool FLAGS::UPDATECONFIG = false;
BOOST_AUTO_TEST_SUITE( constructors )
BOOST_AUTO_TEST_CASE ( simple_journal )
{
}
BOOST_AUTO_TEST_SUITE_END(); | 17.555556 | 46 | 0.746835 | amirmasoudabdol |
99b7c985b4ec3b5e767739ccb945506fad712dc0 | 100 | cpp | C++ | Tema_8_Estructuras_no_lineales/BinaryTree/BinaryTree/BST.cpp | vcubells/tc1031 | 43d328df12194be840e8c83966b814e5625347b3 | [
"MIT"
] | 10 | 2020-08-15T16:54:13.000Z | 2021-10-05T16:24:05.000Z | Tema_8_Estructuras_no_lineales/BinaryTree/BinaryTree/BST.cpp | vcubells/tc1031 | 43d328df12194be840e8c83966b814e5625347b3 | [
"MIT"
] | null | null | null | Tema_8_Estructuras_no_lineales/BinaryTree/BinaryTree/BST.cpp | vcubells/tc1031 | 43d328df12194be840e8c83966b814e5625347b3 | [
"MIT"
] | 4 | 2020-09-05T02:12:52.000Z | 2021-09-22T00:54:25.000Z | //
// BST.cpp
// BinaryTree
//
// Created by Vicente Cubells on 20/10/20.
//
#include "BST.hpp"
| 11.111111 | 43 | 0.6 | vcubells |
99badd73cb71b4b87174faaf0be074633b441346 | 1,702 | hpp | C++ | src/gui.hpp | Sparamoule/Roche | 244fd71ed841576f1c6dad8198312524bc1ff291 | [
"MIT"
] | 7 | 2019-03-15T11:51:56.000Z | 2020-06-20T15:16:06.000Z | src/gui.hpp | PLeLuron/Roche | 244fd71ed841576f1c6dad8198312524bc1ff291 | [
"MIT"
] | 1 | 2019-05-21T15:25:34.000Z | 2019-07-14T14:30:08.000Z | src/gui.hpp | PLeLuron/Roche | 244fd71ed841576f1c6dad8198312524bc1ff291 | [
"MIT"
] | 3 | 2018-12-18T02:05:20.000Z | 2020-03-13T18:17:49.000Z | #pragma once
#include <string>
#include <vector>
#include <map>
#include <set>
class Gui
{
public:
Gui() = default;
~Gui() = default;
typedef uint32_t Handle;
typedef Handle Font;
typedef Handle FontSize;
typedef Handle Image;
Font loadFont(const std::string &filename);
FontSize loadFontSize(Font font, float size);
Image loadImage(const std::string &filename);
void init();
void setText(FontSize fontSize, int posX, int posY, const std::string &text,
uint8_t r, uint8_t g, uint8_t b, uint8_t a);
void setImage(Image img, int posX, int posY, float size);
void display(int width, int height);
protected:
struct Vertex
{
float x,y,u,v;
uint8_t r,g,b,a;
};
struct RenderInfo
{
std::vector<Vertex> vertices;
};
virtual void initGraphics(
int atlasWidth, int atlasHeight,
const std::vector<uint8_t> &atlasData)=0;
virtual void displayGraphics(const RenderInfo &info)=0;
private:
Handle genHandle();
struct GlyphInfo
{
int x0, y0, x1, y1;
int x, y, w, h;
};
struct FontSizeInfo
{
float pixelSize;
float scale;
std::map<int, GlyphInfo> glyphInfo;
};
struct FontInfo
{
std::string filename;
std::map<FontSize, FontSizeInfo> fontSizeInfo;
int ascent, descent, lineGap;
std::map<int, int> advanceWidth;
std::map<int, int> leftSideBearing;
std::map<std::pair<int,int>, int> kernAdvance;
std::vector<int> codepointGlyphs;
std::set<int> allGlyphs;
};
std::map<Font, FontInfo> _fontInfo;
std::map<FontSize, Font> _fontSizes;
struct TextRenderInfo
{
Font font;
FontSize fontSize;
int posX, posY;
std::string text;
uint8_t r,g,b,a;
};
std::vector<TextRenderInfo> _textRenderInfo;
int _atlasWidth, _atlasHeight;
}; | 19.123596 | 78 | 0.701528 | Sparamoule |
99bba2476081e2ddb21537cf9002c8245bbcf5d4 | 1,180 | cpp | C++ | problems/chapter13/tokuma/1305.cpp | tokuma09/algorithm_problems | 58534620df73b230afbeb12de126174362625a78 | [
"CC0-1.0"
] | 1 | 2021-07-07T15:46:58.000Z | 2021-07-07T15:46:58.000Z | problems/chapter13/tokuma/1305.cpp | tokuma09/algorithm_problems | 58534620df73b230afbeb12de126174362625a78 | [
"CC0-1.0"
] | 5 | 2021-06-05T14:16:41.000Z | 2021-07-10T07:08:28.000Z | problems/chapter13/tokuma/1305.cpp | tokuma09/algorithm_problems | 58534620df73b230afbeb12de126174362625a78 | [
"CC0-1.0"
] | null | null | null | // https://qiita.com/drken/items/996d80bcae64649a6580
// 出次数とシンク
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
using Graph = vector<vector<int>>;
int main()
{
//頂点数と辺の数
int N, M;
cin >> N >> M;
// グラフ入力
Graph G(N);
vector<int> deg(N, 0); // 各頂点の出次数
// vに伸びている頂点を走査したいので、逆にする
for (int i = 0; i < M; ++i)
{
int a, b;
cin >> a >> b;
G[b].push_back(a);
++deg[a];
}
// シンクたちをキューに入れる
queue<int> que;
for (int i = 0; i < N; ++i)
{
if (deg[i] == 0)
{
que.push(i);
}
}
// 順序
vector<int> order;
// 探索開始
while (!que.empty())
{
// キューから頂点を取り出す
int v = que.front();
que.pop();
order.push_back(v);
// vに伸びている頂点を探索
for (auto nv : G[v])
{
// 辺(nv, v)の削除;
--deg[nv];
// シンクになれば挿入
if (deg[nv] == 0)
{
que.push(nv);
}
}
}
// 答えをひっくり返す
reverse(order.begin(), order.end());
for (auto v : order)
cout << v << endl;
}
| 16.857143 | 53 | 0.430508 | tokuma09 |
99c15d0ac0fb8e5257c9fdfe0acb497118e8e002 | 943 | hh | C++ | src/Nuxed/Contract/Http/Message/UploadedFileFactoryInterface.hh | tomoki1337/framework | ff06d260c5bf2a78a99b8d17b041de756550f95a | [
"MIT"
] | 1 | 2019-01-25T20:05:55.000Z | 2019-01-25T20:05:55.000Z | src/Nuxed/Contract/Http/Message/UploadedFileFactoryInterface.hh | gitter-badger/framework-27 | 368b734f2753b06b7f19f819185091f896838467 | [
"MIT"
] | null | null | null | src/Nuxed/Contract/Http/Message/UploadedFileFactoryInterface.hh | gitter-badger/framework-27 | 368b734f2753b06b7f19f819185091f896838467 | [
"MIT"
] | null | null | null | <?hh // strict
namespace Nuxed\Contract\Http\Message;
interface UploadedFileFactoryInterface {
/**
* Create a new uploaded file.
*
* If a size is not provided it will be determined by checking the size of
* the file.
*
* @param StreamInterface $stream Underlying stream representing the
* uploaded file content.
* @param int $size in bytes
* @param ?UploadeFileError $error Hack file upload error or null.
* @param string $clientFilename Filename as provided by the client, if any.
* @param string $clientMediaType Media type as provided by the client, if any.
*
* @throws \InvalidArgumentException If the file resource is not readable.
*/
public function createUploadedFile(
StreamInterface $stream,
?int $size = null,
UploadedFileError $error = UploadedFileError::ERROR_OK,
?string $clientFilename = null,
?string $clientMediaType = null,
): UploadedFileInterface;
}
| 32.517241 | 81 | 0.711559 | tomoki1337 |
99c49aa906ef12d1fbe832b23b57c4fd2b5f3165 | 8,352 | cpp | C++ | plugins/protein/src/MoleculeBallifier.cpp | xge/megamol | 1e298dd3d8b153d7468ed446f6b2ed3ac49f0d5b | [
"BSD-3-Clause"
] | null | null | null | plugins/protein/src/MoleculeBallifier.cpp | xge/megamol | 1e298dd3d8b153d7468ed446f6b2ed3ac49f0d5b | [
"BSD-3-Clause"
] | null | null | null | plugins/protein/src/MoleculeBallifier.cpp | xge/megamol | 1e298dd3d8b153d7468ed446f6b2ed3ac49f0d5b | [
"BSD-3-Clause"
] | null | null | null | /*
* MoleculeBallifier.cpp
*
* Copyright (C) 2012 by TU Dresden
* All rights reserved.
*/
#include "MoleculeBallifier.h"
#include "geometry_calls/MultiParticleDataCall.h"
#include "mmcore/param/ColorParam.h"
#include "mmcore/param/EnumParam.h"
#include "mmcore/param/FilePathParam.h"
#include "mmcore/param/FloatParam.h"
#include "protein_calls/MolecularDataCall.h"
using namespace megamol;
using namespace megamol::protein;
using namespace megamol::protein_calls;
using namespace megamol::geocalls;
using namespace megamol::protein_calls;
MoleculeBallifier::MoleculeBallifier(void)
: core::Module()
, outDataSlot("outData", "Sends MultiParticleDataCall data out into the world")
, inDataSlot("inData", "Fetches MolecularDataCall data")
, colorTableFileParam_("colorTableFilename", "")
, coloringModeParam0_("coloringMode0", "")
, coloringModeParam1_("coloringMode1", "")
, cmWeightParam_("colorWeight", "")
, minGradColorParam_("minGradColor", "")
, midGradColorParam_("midGradColor", "")
, maxGradColorParam_("maxGradColor", "")
, specialColorParam_("specialColor", "")
, inHash(0)
, outHash(0)
, data()
, frameOld(-1) {
this->inDataSlot.SetCompatibleCall<MolecularDataCallDescription>();
this->MakeSlotAvailable(&this->inDataSlot);
this->outDataSlot.SetCallback(geocalls::MultiParticleDataCall::ClassName(),
geocalls::MultiParticleDataCall::FunctionName(0), &MoleculeBallifier::getData);
this->outDataSlot.SetCallback(geocalls::MultiParticleDataCall::ClassName(),
geocalls::MultiParticleDataCall::FunctionName(1), &MoleculeBallifier::getExt);
this->MakeSlotAvailable(&this->outDataSlot);
std::string filename("colors.txt");
ProteinColor::ReadColorTableFromFile(filename, fileLookupTable_);
colorTableFileParam_.SetParameter(
new core::param::FilePathParam(filename, core::param::FilePathParam::FilePathFlags_::Flag_File_ToBeCreated));
this->MakeSlotAvailable(&colorTableFileParam_);
curColoringMode0_ = ProteinColor::ColoringMode::ELEMENT;
curColoringMode1_ = ProteinColor::ColoringMode::ELEMENT;
core::param::EnumParam* cm0 = new core::param::EnumParam(static_cast<int>(curColoringMode0_));
core::param::EnumParam* cm1 = new core::param::EnumParam(static_cast<int>(curColoringMode1_));
MolecularDataCall* mol = new MolecularDataCall();
ProteinColor::ColoringMode cMode;
for (uint32_t cCnt = 0; cCnt < static_cast<uint32_t>(ProteinColor::ColoringMode::MODE_COUNT); ++cCnt) {
cMode = static_cast<ProteinColor::ColoringMode>(cCnt);
cm0->SetTypePair(static_cast<int>(cMode), ProteinColor::GetName(cMode).c_str());
cm1->SetTypePair(static_cast<int>(cMode), ProteinColor::GetName(cMode).c_str());
}
delete mol;
coloringModeParam0_ << cm0;
coloringModeParam1_ << cm1;
this->MakeSlotAvailable(&coloringModeParam0_);
this->MakeSlotAvailable(&coloringModeParam1_);
cmWeightParam_.SetParameter(new core::param::FloatParam(0.5f, 0.0f, 1.0f));
this->MakeSlotAvailable(&cmWeightParam_);
minGradColorParam_.SetParameter(new core::param::ColorParam("#146496"));
this->MakeSlotAvailable(&minGradColorParam_);
midGradColorParam_.SetParameter(new core::param::ColorParam("#f0f0f0"));
this->MakeSlotAvailable(&midGradColorParam_);
maxGradColorParam_.SetParameter(new core::param::ColorParam("#ae3b32"));
this->MakeSlotAvailable(&maxGradColorParam_);
specialColorParam_.SetParameter(new core::param::ColorParam("#228B22"));
this->MakeSlotAvailable(&specialColorParam_);
ProteinColor::MakeRainbowColorTable(100, rainbowColors_);
}
/*
*
*/
MoleculeBallifier::~MoleculeBallifier(void) {
this->Release();
}
/*
*
*/
bool MoleculeBallifier::create(void) {
// intentionally empty
return true;
}
/*
*
*/
void MoleculeBallifier::release(void) {
// intentionally empty
}
/*
*
*/
bool MoleculeBallifier::getData(core::Call& c) {
using geocalls::MultiParticleDataCall;
MultiParticleDataCall* ic = dynamic_cast<MultiParticleDataCall*>(&c);
if (ic == NULL)
return false;
MolecularDataCall* oc = this->inDataSlot.CallAs<MolecularDataCall>();
if (oc == NULL)
return false;
// Transfer frame ID plus force flag
oc->SetFrameID(ic->FrameID(), ic->IsFrameForced());
curColoringMode0_ =
static_cast<ProteinColor::ColoringMode>(coloringModeParam0_.Param<core::param::EnumParam>()->Value());
curColoringMode1_ =
static_cast<ProteinColor::ColoringMode>(coloringModeParam1_.Param<core::param::EnumParam>()->Value());
bool updatedColorTable = false;
if (colorTableFileParam_.IsDirty()) {
ProteinColor::ReadColorTableFromFile(
colorTableFileParam_.Param<core::param::FilePathParam>()->Value(), fileLookupTable_);
colorTableFileParam_.ResetDirty();
updatedColorTable = true;
}
if (coloringModeParam0_.IsDirty() || coloringModeParam1_.IsDirty() || cmWeightParam_.IsDirty() ||
minGradColorParam_.IsDirty() || midGradColorParam_.IsDirty() || maxGradColorParam_.IsDirty()) {
coloringModeParam0_.ResetDirty();
coloringModeParam1_.ResetDirty();
cmWeightParam_.ResetDirty();
minGradColorParam_.ResetDirty();
midGradColorParam_.ResetDirty();
maxGradColorParam_.ResetDirty();
updatedColorTable = true;
}
if ((*oc)(0)) {
// Rewrite data if the frame number OR the datahash has changed
if ((this->inHash != oc->DataHash()) || (this->frameOld != static_cast<int>(oc->FrameID())) ||
updatedColorTable) {
this->inHash = oc->DataHash();
this->frameOld = static_cast<int>(oc->FrameID());
this->outHash++;
colorArray_.clear();
unsigned int cnt = oc->AtomCount();
colorArray_.resize(cnt);
this->data.AssertSize(sizeof(float) * 7 * cnt);
float* fData = this->data.As<float>();
this->colorLookupTable_ = {
glm::make_vec3(this->minGradColorParam_.Param<core::param::ColorParam>()->Value().data()),
glm::make_vec3(this->midGradColorParam_.Param<core::param::ColorParam>()->Value().data()),
glm::make_vec3(this->maxGradColorParam_.Param<core::param::ColorParam>()->Value().data())};
ProteinColor::MakeWeightedColorTable(*oc, curColoringMode0_, curColoringMode1_,
cmWeightParam_.Param<core::param::FloatParam>()->Value(),
1.0f - cmWeightParam_.Param<core::param::FloatParam>()->Value(), colorArray_, colorLookupTable_,
fileLookupTable_, rainbowColors_, nullptr, nullptr, true);
for (unsigned int i = 0; i < cnt; i++, fData += 7) {
fData[0] = oc->AtomPositions()[i * 3 + 0];
fData[1] = oc->AtomPositions()[i * 3 + 1];
fData[2] = oc->AtomPositions()[i * 3 + 2];
fData[3] = oc->AtomTypes()[oc->AtomTypeIndices()[i]].Radius();
fData[4] = colorArray_[i].x;
fData[5] = colorArray_[i].y;
fData[6] = colorArray_[i].z;
}
}
ic->SetDataHash(this->outHash);
ic->SetParticleListCount(1);
MultiParticleDataCall::Particles& p = ic->AccessParticles(0);
p.SetCount(this->data.GetSize() / (sizeof(float) * 7));
if (p.GetCount() > 0) {
p.SetVertexData(MultiParticleDataCall::Particles::VERTDATA_FLOAT_XYZR, this->data.At(0), sizeof(float) * 7);
p.SetColourData(MultiParticleDataCall::Particles::COLDATA_FLOAT_RGB, this->data.At(sizeof(float) * 4),
sizeof(float) * 7);
}
}
return true;
}
/*
*
*/
bool MoleculeBallifier::getExt(core::Call& c) {
using geocalls::MultiParticleDataCall;
MultiParticleDataCall* ic = dynamic_cast<MultiParticleDataCall*>(&c);
if (ic == NULL)
return false;
MolecularDataCall* oc = this->inDataSlot.CallAs<MolecularDataCall>();
if (oc == NULL)
return false;
if ((*oc)(1)) {
ic->SetFrameCount(oc->FrameCount());
ic->AccessBoundingBoxes() = oc->AccessBoundingBoxes();
return true;
}
return false;
}
| 36.631579 | 120 | 0.661279 | xge |
99c4cc97c192f78f13d2cb963c408a2777758e25 | 297 | cpp | C++ | main.cpp | piccolo255/pde-pathtracer | d754583a308975b68675076f68f1194cbaa906ca | [
"Unlicense"
] | null | null | null | main.cpp | piccolo255/pde-pathtracer | d754583a308975b68675076f68f1194cbaa906ca | [
"Unlicense"
] | null | null | null | main.cpp | piccolo255/pde-pathtracer | d754583a308975b68675076f68f1194cbaa906ca | [
"Unlicense"
] | null | null | null | #include "plot_window.hpp"
#include <QApplication>
int main(
int argc
, char *argv[]
){
QApplication app( argc, argv );
PlotWindow w;
QCoreApplication::setOrganizationName( "UEC" );
QCoreApplication::setApplicationName( "PDE PathTracer" );
w.show();
return app.exec();
}
| 16.5 | 60 | 0.670034 | piccolo255 |
99c8bddbf02003bfb52a264b3d2ca1d506163810 | 58 | hpp | C++ | src/boost_compute_type_traits_make_vector_type.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 10 | 2018-03-17T00:58:42.000Z | 2021-07-06T02:48:49.000Z | src/boost_compute_type_traits_make_vector_type.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 2 | 2021-03-26T15:17:35.000Z | 2021-05-20T23:55:08.000Z | src/boost_compute_type_traits_make_vector_type.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 4 | 2019-05-28T21:06:37.000Z | 2021-07-06T03:06:52.000Z | #include <boost/compute/type_traits/make_vector_type.hpp>
| 29 | 57 | 0.844828 | miathedev |
99e06083b139e92ee1380651c2373e26a4d176f7 | 349 | cpp | C++ | external/rapidcheck/src/detail/ImplicitParam.cpp | XzoRit/cpp_rapidcheck | 292c9943569e52e29fbd11abd31a965efc699a8e | [
"BSL-1.0"
] | 876 | 2015-01-29T00:48:46.000Z | 2022-03-23T00:24:34.000Z | src/detail/ImplicitParam.cpp | wuerges/rapidcheck | d2e0481b28b77fcd0c7ead9af1e8227ee9982739 | [
"BSD-2-Clause"
] | 199 | 2015-05-18T07:04:40.000Z | 2022-03-23T02:37:15.000Z | src/detail/ImplicitParam.cpp | wuerges/rapidcheck | d2e0481b28b77fcd0c7ead9af1e8227ee9982739 | [
"BSD-2-Clause"
] | 162 | 2015-03-12T20:19:31.000Z | 2022-03-14T08:42:52.000Z | #include "rapidcheck/detail/ImplicitParam.h"
namespace rc {
namespace detail {
ImplicitScope::ImplicitScope() { m_scopes.emplace(); }
ImplicitScope::~ImplicitScope() {
for (auto destructor : m_scopes.top()) {
destructor();
}
m_scopes.pop();
}
ImplicitScope::ScopeStack ImplicitScope::m_scopes;
} // namespace detail
} // namespace rc
| 18.368421 | 54 | 0.713467 | XzoRit |
99e2e6799c9da18cd4e53bc2917cd0347bfe185a | 3,404 | cpp | C++ | Linux_build/wxMultiSpec/xTitleBar.cpp | cas-nctu/multispec | 0bc840bdb073b5feaeec650c2da762cfa34ee37d | [
"Apache-2.0"
] | 11 | 2020-03-10T02:06:00.000Z | 2022-02-17T19:59:50.000Z | Linux_build/wxMultiSpec/xTitleBar.cpp | cas-nctu/multispec | 0bc840bdb073b5feaeec650c2da762cfa34ee37d | [
"Apache-2.0"
] | null | null | null | Linux_build/wxMultiSpec/xTitleBar.cpp | cas-nctu/multispec | 0bc840bdb073b5feaeec650c2da762cfa34ee37d | [
"Apache-2.0"
] | 5 | 2020-05-30T00:59:22.000Z | 2021-12-06T01:37:05.000Z | // MultiSpec
//
// Copyright 1988-2020 Purdue Research Foundation
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at: https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the specific
// language governing permissions and limitations under the License.
//
// MultiSpec is curated by the Laboratory for Applications of Remote Sensing at
// Purdue University in West Lafayette, IN and licensed by Larry Biehl.
//
// File: xTitleBar.cpp : class implementation file
// Class Definition: xTitleBar.h
//
// Authors: Larry L. Biehl
//
// Revision date: 03/20/2019
//
// Language: C++
//
// System: Linux Operating System
//
// Brief description: This file contains functions that relate to the
// CMCoordinateBar class.
/* Template for debugging
int numberChars = sprintf (
(char*)&gTextString3,
" xTitleBar: (): %s",
gEndOfLine);
ListString ((char*)&gTextString3, numberChars, gOutputTextH);
*/
//------------------------------------------------------------------------------------
#include "SMultiSpec.h"
#include "xImageView.h"
#include "xTitleBar.h"
IMPLEMENT_DYNAMIC_CLASS (CMTitleBar, wxPanel)
BEGIN_EVENT_TABLE (CMTitleBar, wxPanel)
EVT_PAINT (CMTitleBar::OnPaint)
END_EVENT_TABLE ()
CMTitleBar::CMTitleBar ()
{
} // end "CMTitleBar"
CMTitleBar::CMTitleBar (
wxWindow* parent)
: wxPanel (parent)
{
#if defined multispec_wxmac
int fontSize = 12;
#else
int fontSize = 9;
#endif
SetFont (wxFont (fontSize,
wxFONTFAMILY_TELETYPE,
wxFONTSTYLE_NORMAL,
wxFONTWEIGHT_NORMAL,
false,
wxEmptyString));
} // end "CMTitleBar"
CMTitleBar::~CMTitleBar ()
{
} // end "~CMTitleBar ()"
void CMTitleBar::InitialUpdate ()
{
} // end "InitialUpdate"
void CMTitleBar::OnPaint (
wxPaintEvent& event)
{
Rect destinationRect;
wxRect updateRect;
// Shifts the device origin so we don't have to worry about the current
// scroll position ourselves
wxPaintDC dc (this);
// Fills the dc with the current bg brush
// Find Out where the window is scrolled to
PrepareDC (dc);
dc.Clear ();
// Sets the scale to be applied when converting from logical units to device
// units
dc.SetUserScale (1, 1);
// Sets the bg brush used in Clear(). Default:wxTRANSPARENT_BRUSH
dc.SetBackground (wxBrush (*wxWHITE));
updateRect = GetClientRect ();
destinationRect.top = updateRect.GetTop ();
destinationRect.left = updateRect.GetLeft ();
destinationRect.bottom = updateRect.GetBottom ();
destinationRect.right = updateRect.GetRight ();
wxPoint scrollOffset;
m_view->m_Canvas->CalcUnscrolledPosition (0, 0, &scrollOffset.x, &scrollOffset.y);
if (scrollOffset.x < 0)
scrollOffset.x = 0;
dc.SetDeviceOrigin (2-scrollOffset.x, 0);
Handle windowInfoHandle = GetWindowInfoHandle (m_view);
DrawSideBySideTitles (&dc,
windowInfoHandle,
m_view,
&destinationRect,
1);
} // end "OnPaint"
| 23.156463 | 86 | 0.664512 | cas-nctu |
99e4a24eaa12b6f5c2b5caf72c63b6703c07641b | 2,622 | cpp | C++ | samples/snippets/cpp/VS_Snippets_Winforms/Classic DataGridTableStyle Example/CPP/source.cpp | hamarb123/dotnet-api-docs | 6aeb55784944a2f1f5e773b657791cbd73a92dd4 | [
"CC-BY-4.0",
"MIT"
] | 421 | 2018-04-01T01:57:50.000Z | 2022-03-28T15:24:42.000Z | samples/snippets/cpp/VS_Snippets_Winforms/Classic DataGridTableStyle Example/CPP/source.cpp | hamarb123/dotnet-api-docs | 6aeb55784944a2f1f5e773b657791cbd73a92dd4 | [
"CC-BY-4.0",
"MIT"
] | 5,797 | 2018-04-02T21:12:23.000Z | 2022-03-31T23:54:38.000Z | samples/snippets/cpp/VS_Snippets_Winforms/Classic DataGridTableStyle Example/CPP/source.cpp | hamarb123/dotnet-api-docs | 6aeb55784944a2f1f5e773b657791cbd73a92dd4 | [
"CC-BY-4.0",
"MIT"
] | 1,482 | 2018-03-31T11:26:20.000Z | 2022-03-30T22:36:45.000Z |
#using <System.Xml.dll>
#using <System.dll>
#using <System.Windows.Forms.dll>
#using <System.Drawing.dll>
#using <System.Data.dll>
using namespace System;
using namespace System::Data;
using namespace System::Drawing;
using namespace System::Windows::Forms;
using namespace System::ComponentModel;
public ref class Form1: public Form
{
protected:
DataGrid^ myDataGrid;
DataSet^ myDataSet;
private:
// <Snippet1>
void AddCustomDataTableStyle()
{
/* Create a new DataGridTableStyle and set
its MappingName to the TableName of a DataTable. */
DataGridTableStyle^ ts1 = gcnew DataGridTableStyle;
ts1->MappingName = "Customers";
/* Add a GridColumnStyle and set its MappingName
to the name of a DataColumn in the DataTable.
Set the HeaderText and Width properties. */
DataGridColumnStyle^ boolCol = gcnew DataGridBoolColumn;
boolCol->MappingName = "Current";
boolCol->HeaderText = "IsCurrent Customer";
boolCol->Width = 150;
ts1->GridColumnStyles->Add( boolCol );
// Add a second column style.
DataGridColumnStyle^ TextCol = gcnew DataGridTextBoxColumn;
TextCol->MappingName = "custName";
TextCol->HeaderText = "Customer Name";
TextCol->Width = 250;
ts1->GridColumnStyles->Add( TextCol );
// Create the second table style with columns.
DataGridTableStyle^ ts2 = gcnew DataGridTableStyle;
ts2->MappingName = "Orders";
// Change the colors.
ts2->ForeColor = Color::Yellow;
ts2->AlternatingBackColor = Color::Blue;
ts2->BackColor = Color::Blue;
// Create new DataGridColumnStyle objects.
DataGridColumnStyle^ cOrderDate = gcnew DataGridTextBoxColumn;
cOrderDate->MappingName = "OrderDate";
cOrderDate->HeaderText = "Order Date";
cOrderDate->Width = 100;
ts2->GridColumnStyles->Add( cOrderDate );
PropertyDescriptorCollection^ pcol = this->BindingContext[ myDataSet,"Customers.custToOrders" ]->GetItemProperties();
DataGridColumnStyle^ csOrderAmount = gcnew DataGridTextBoxColumn( pcol[ "OrderAmount" ],"c",true );
csOrderAmount->MappingName = "OrderAmount";
csOrderAmount->HeaderText = "Total";
csOrderAmount->Width = 100;
ts2->GridColumnStyles->Add( csOrderAmount );
// Add the DataGridTableStyle objects to the collection.
myDataGrid->TableStyles->Add( ts1 );
myDataGrid->TableStyles->Add( ts2 );
}
// </Snippet1>
};
| 34.5 | 124 | 0.653318 | hamarb123 |
99e65bab4e4f4cb17c9b737db371150096a87fe7 | 77,506 | hpp | C++ | STL/map.hpp | colorhistory/cplusplus-general-programming | 3ece924a2ab34711a55a45bc41e2b74384956204 | [
"MIT"
] | 1 | 2019-09-28T09:40:08.000Z | 2019-09-28T09:40:08.000Z | STL/map.hpp | colorhistory/cplusplus-general-programming | 3ece924a2ab34711a55a45bc41e2b74384956204 | [
"MIT"
] | null | null | null | STL/map.hpp | colorhistory/cplusplus-general-programming | 3ece924a2ab34711a55a45bc41e2b74384956204 | [
"MIT"
] | null | null | null | #ifndef MAP_HPP
#define MAP_HPP
namespace GP {
/*
map synopsis
namespace std
{
template <class Key, class T, class Compare = less<Key>,
class Allocator = allocator<pair<const Key, T>>>
class map
{
public:
// types:
typedef Key key_type;
typedef T mapped_type;
typedef pair<const key_type, mapped_type> value_type;
typedef Compare key_compare;
typedef Allocator allocator_type;
typedef typename allocator_type::reference reference;
typedef typename allocator_type::const_reference const_reference;
typedef typename allocator_type::pointer pointer;
typedef typename allocator_type::const_pointer const_pointer;
typedef typename allocator_type::size_type size_type;
typedef typename allocator_type::difference_type difference_type;
typedef implementation-defined iterator;
typedef implementation-defined const_iterator;
typedef std::reverse_iterator<iterator> reverse_iterator;
typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
typedef unspecified node_type; // C++17
typedef INSERT_RETURN_TYPE<iterator, node_type> insert_return_type; // C++17
class value_compare
: public binary_function<value_type, value_type, bool>
{
friend class map;
protected:
key_compare comp;
value_compare(key_compare c);
public:
bool operator()(const value_type& x, const value_type& y) const;
};
// construct/copy/destroy:
map()
noexcept(
is_nothrow_default_constructible<allocator_type>::value &&
is_nothrow_default_constructible<key_compare>::value &&
is_nothrow_copy_constructible<key_compare>::value);
explicit map(const key_compare& comp);
map(const key_compare& comp, const allocator_type& a);
template <class InputIterator>
map(InputIterator first, InputIterator last,
const key_compare& comp = key_compare());
template <class InputIterator>
map(InputIterator first, InputIterator last,
const key_compare& comp, const allocator_type& a);
map(const map& m);
map(map&& m)
noexcept(
is_nothrow_move_constructible<allocator_type>::value &&
is_nothrow_move_constructible<key_compare>::value);
explicit map(const allocator_type& a);
map(const map& m, const allocator_type& a);
map(map&& m, const allocator_type& a);
map(initializer_list<value_type> il, const key_compare& comp = key_compare());
map(initializer_list<value_type> il, const key_compare& comp, const allocator_type& a);
template <class InputIterator>
map(InputIterator first, InputIterator last, const allocator_type& a)
: map(first, last, Compare(), a) {} // C++14
map(initializer_list<value_type> il, const allocator_type& a)
: map(il, Compare(), a) {} // C++14
~map();
map& operator=(const map& m);
map& operator=(map&& m)
noexcept(
allocator_type::propagate_on_container_move_assignment::value &&
is_nothrow_move_assignable<allocator_type>::value &&
is_nothrow_move_assignable<key_compare>::value);
map& operator=(initializer_list<value_type> il);
// iterators:
iterator begin() noexcept;
const_iterator begin() const noexcept;
iterator end() noexcept;
const_iterator end() const noexcept;
reverse_iterator rbegin() noexcept;
const_reverse_iterator rbegin() const noexcept;
reverse_iterator rend() noexcept;
const_reverse_iterator rend() const noexcept;
const_iterator cbegin() const noexcept;
const_iterator cend() const noexcept;
const_reverse_iterator crbegin() const noexcept;
const_reverse_iterator crend() const noexcept;
// capacity:
bool empty() const noexcept;
size_type size() const noexcept;
size_type max_size() const noexcept;
// element access:
mapped_type& operator[](const key_type& k);
mapped_type& operator[](key_type&& k);
mapped_type& at(const key_type& k);
const mapped_type& at(const key_type& k) const;
// modifiers:
template <class... Args>
pair<iterator, bool> emplace(Args&&... args);
template <class... Args>
iterator emplace_hint(const_iterator position, Args&&... args);
pair<iterator, bool> insert(const value_type& v);
pair<iterator, bool> insert( value_type&& v); // C++17
template <class P>
pair<iterator, bool> insert(P&& p);
iterator insert(const_iterator position, const value_type& v);
iterator insert(const_iterator position, value_type&& v); // C++17
template <class P>
iterator insert(const_iterator position, P&& p);
template <class InputIterator>
void insert(InputIterator first, InputIterator last);
void insert(initializer_list<value_type> il);
node_type extract(const_iterator position); // C++17
node_type extract(const key_type& x); // C++17
insert_return_type insert(node_type&& nh); // C++17
iterator insert(const_iterator hint, node_type&& nh); // C++17
template <class... Args>
pair<iterator, bool> try_emplace(const key_type& k, Args&&... args); // C++17
template <class... Args>
pair<iterator, bool> try_emplace(key_type&& k, Args&&... args); // C++17
template <class... Args>
iterator try_emplace(const_iterator hint, const key_type& k, Args&&... args); // C++17
template <class... Args>
iterator try_emplace(const_iterator hint, key_type&& k, Args&&... args); // C++17
template <class M>
pair<iterator, bool> insert_or_assign(const key_type& k, M&& obj); // C++17
template <class M>
pair<iterator, bool> insert_or_assign(key_type&& k, M&& obj); // C++17
template <class M>
iterator insert_or_assign(const_iterator hint, const key_type& k, M&& obj); // C++17
template <class M>
iterator insert_or_assign(const_iterator hint, key_type&& k, M&& obj); // C++17
iterator erase(const_iterator position);
iterator erase(iterator position); // C++14
size_type erase(const key_type& k);
iterator erase(const_iterator first, const_iterator last);
void clear() noexcept;
template<class C2>
void merge(map<Key, T, C2, Allocator>& source); // C++17
template<class C2>
void merge(map<Key, T, C2, Allocator>&& source); // C++17
template<class C2>
void merge(multimap<Key, T, C2, Allocator>& source); // C++17
template<class C2>
void merge(multimap<Key, T, C2, Allocator>&& source); // C++17
void swap(map& m)
noexcept(allocator_traits<allocator_type>::is_always_equal::value &&
is_nothrow_swappable<key_compare>::value); // C++17
// observers:
allocator_type get_allocator() const noexcept;
key_compare key_comp() const;
value_compare value_comp() const;
// map operations:
iterator find(const key_type& k);
const_iterator find(const key_type& k) const;
template<typename K>
iterator find(const K& x); // C++14
template<typename K>
const_iterator find(const K& x) const; // C++14
template<typename K>
size_type count(const K& x) const; // C++14
size_type count(const key_type& k) const;
iterator lower_bound(const key_type& k);
const_iterator lower_bound(const key_type& k) const;
template<typename K>
iterator lower_bound(const K& x); // C++14
template<typename K>
const_iterator lower_bound(const K& x) const; // C++14
iterator upper_bound(const key_type& k);
const_iterator upper_bound(const key_type& k) const;
template<typename K>
iterator upper_bound(const K& x); // C++14
template<typename K>
const_iterator upper_bound(const K& x) const; // C++14
pair<iterator,iterator> equal_range(const key_type& k);
pair<const_iterator,const_iterator> equal_range(const key_type& k) const;
template<typename K>
pair<iterator,iterator> equal_range(const K& x); // C++14
template<typename K>
pair<const_iterator,const_iterator> equal_range(const K& x) const; // C++14
};
template <class Key, class T, class Compare, class Allocator>
bool
operator==(const map<Key, T, Compare, Allocator>& x,
const map<Key, T, Compare, Allocator>& y);
template <class Key, class T, class Compare, class Allocator>
bool
operator< (const map<Key, T, Compare, Allocator>& x,
const map<Key, T, Compare, Allocator>& y);
template <class Key, class T, class Compare, class Allocator>
bool
operator!=(const map<Key, T, Compare, Allocator>& x,
const map<Key, T, Compare, Allocator>& y);
template <class Key, class T, class Compare, class Allocator>
bool
operator> (const map<Key, T, Compare, Allocator>& x,
const map<Key, T, Compare, Allocator>& y);
template <class Key, class T, class Compare, class Allocator>
bool
operator>=(const map<Key, T, Compare, Allocator>& x,
const map<Key, T, Compare, Allocator>& y);
template <class Key, class T, class Compare, class Allocator>
bool
operator<=(const map<Key, T, Compare, Allocator>& x,
const map<Key, T, Compare, Allocator>& y);
// specialized algorithms:
template <class Key, class T, class Compare, class Allocator>
void
swap(map<Key, T, Compare, Allocator>& x, map<Key, T, Compare, Allocator>& y)
noexcept(noexcept(x.swap(y)));
template <class Key, class T, class Compare, class Allocator, class Predicate>
void erase_if(map<Key, T, Compare, Allocator>& c, Predicate pred); // C++20
template <class Key, class T, class Compare = less<Key>,
class Allocator = allocator<pair<const Key, T>>>
class multimap
{
public:
// types:
typedef Key key_type;
typedef T mapped_type;
typedef pair<const key_type,mapped_type> value_type;
typedef Compare key_compare;
typedef Allocator allocator_type;
typedef typename allocator_type::reference reference;
typedef typename allocator_type::const_reference const_reference;
typedef typename allocator_type::size_type size_type;
typedef typename allocator_type::difference_type difference_type;
typedef typename allocator_type::pointer pointer;
typedef typename allocator_type::const_pointer const_pointer;
typedef implementation-defined iterator;
typedef implementation-defined const_iterator;
typedef std::reverse_iterator<iterator> reverse_iterator;
typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
typedef unspecified node_type; // C++17
class value_compare
: public binary_function<value_type,value_type,bool>
{
friend class multimap;
protected:
key_compare comp;
value_compare(key_compare c);
public:
bool operator()(const value_type& x, const value_type& y) const;
};
// construct/copy/destroy:
multimap()
noexcept(
is_nothrow_default_constructible<allocator_type>::value &&
is_nothrow_default_constructible<key_compare>::value &&
is_nothrow_copy_constructible<key_compare>::value);
explicit multimap(const key_compare& comp);
multimap(const key_compare& comp, const allocator_type& a);
template <class InputIterator>
multimap(InputIterator first, InputIterator last, const key_compare& comp);
template <class InputIterator>
multimap(InputIterator first, InputIterator last, const key_compare& comp,
const allocator_type& a);
multimap(const multimap& m);
multimap(multimap&& m)
noexcept(
is_nothrow_move_constructible<allocator_type>::value &&
is_nothrow_move_constructible<key_compare>::value);
explicit multimap(const allocator_type& a);
multimap(const multimap& m, const allocator_type& a);
multimap(multimap&& m, const allocator_type& a);
multimap(initializer_list<value_type> il, const key_compare& comp = key_compare());
multimap(initializer_list<value_type> il, const key_compare& comp,
const allocator_type& a);
template <class InputIterator>
multimap(InputIterator first, InputIterator last, const allocator_type& a)
: multimap(first, last, Compare(), a) {} // C++14
multimap(initializer_list<value_type> il, const allocator_type& a)
: multimap(il, Compare(), a) {} // C++14
~multimap();
multimap& operator=(const multimap& m);
multimap& operator=(multimap&& m)
noexcept(
allocator_type::propagate_on_container_move_assignment::value &&
is_nothrow_move_assignable<allocator_type>::value &&
is_nothrow_move_assignable<key_compare>::value);
multimap& operator=(initializer_list<value_type> il);
// iterators:
iterator begin() noexcept;
const_iterator begin() const noexcept;
iterator end() noexcept;
const_iterator end() const noexcept;
reverse_iterator rbegin() noexcept;
const_reverse_iterator rbegin() const noexcept;
reverse_iterator rend() noexcept;
const_reverse_iterator rend() const noexcept;
const_iterator cbegin() const noexcept;
const_iterator cend() const noexcept;
const_reverse_iterator crbegin() const noexcept;
const_reverse_iterator crend() const noexcept;
// capacity:
bool empty() const noexcept;
size_type size() const noexcept;
size_type max_size() const noexcept;
// modifiers:
template <class... Args>
iterator emplace(Args&&... args);
template <class... Args>
iterator emplace_hint(const_iterator position, Args&&... args);
iterator insert(const value_type& v);
iterator insert( value_type&& v); // C++17
template <class P>
iterator insert(P&& p);
iterator insert(const_iterator position, const value_type& v);
iterator insert(const_iterator position, value_type&& v); // C++17
template <class P>
iterator insert(const_iterator position, P&& p);
template <class InputIterator>
void insert(InputIterator first, InputIterator last);
void insert(initializer_list<value_type> il);
node_type extract(const_iterator position); // C++17
node_type extract(const key_type& x); // C++17
iterator insert(node_type&& nh); // C++17
iterator insert(const_iterator hint, node_type&& nh); // C++17
iterator erase(const_iterator position);
iterator erase(iterator position); // C++14
size_type erase(const key_type& k);
iterator erase(const_iterator first, const_iterator last);
void clear() noexcept;
template<class C2>
void merge(multimap<Key, T, C2, Allocator>& source); // C++17
template<class C2>
void merge(multimap<Key, T, C2, Allocator>&& source); // C++17
template<class C2>
void merge(map<Key, T, C2, Allocator>& source); // C++17
template<class C2>
void merge(map<Key, T, C2, Allocator>&& source); // C++17
void swap(multimap& m)
noexcept(allocator_traits<allocator_type>::is_always_equal::value &&
is_nothrow_swappable<key_compare>::value); // C++17
// observers:
allocator_type get_allocator() const noexcept;
key_compare key_comp() const;
value_compare value_comp() const;
// map operations:
iterator find(const key_type& k);
const_iterator find(const key_type& k) const;
template<typename K>
iterator find(const K& x); // C++14
template<typename K>
const_iterator find(const K& x) const; // C++14
template<typename K>
size_type count(const K& x) const; // C++14
size_type count(const key_type& k) const;
iterator lower_bound(const key_type& k);
const_iterator lower_bound(const key_type& k) const;
template<typename K>
iterator lower_bound(const K& x); // C++14
template<typename K>
const_iterator lower_bound(const K& x) const; // C++14
iterator upper_bound(const key_type& k);
const_iterator upper_bound(const key_type& k) const;
template<typename K>
iterator upper_bound(const K& x); // C++14
template<typename K>
const_iterator upper_bound(const K& x) const; // C++14
pair<iterator,iterator> equal_range(const key_type& k);
pair<const_iterator,const_iterator> equal_range(const key_type& k) const;
template<typename K>
pair<iterator,iterator> equal_range(const K& x); // C++14
template<typename K>
pair<const_iterator,const_iterator> equal_range(const K& x) const; // C++14
};
template <class Key, class T, class Compare, class Allocator>
bool
operator==(const multimap<Key, T, Compare, Allocator>& x,
const multimap<Key, T, Compare, Allocator>& y);
template <class Key, class T, class Compare, class Allocator>
bool
operator< (const multimap<Key, T, Compare, Allocator>& x,
const multimap<Key, T, Compare, Allocator>& y);
template <class Key, class T, class Compare, class Allocator>
bool
operator!=(const multimap<Key, T, Compare, Allocator>& x,
const multimap<Key, T, Compare, Allocator>& y);
template <class Key, class T, class Compare, class Allocator>
bool
operator> (const multimap<Key, T, Compare, Allocator>& x,
const multimap<Key, T, Compare, Allocator>& y);
template <class Key, class T, class Compare, class Allocator>
bool
operator>=(const multimap<Key, T, Compare, Allocator>& x,
const multimap<Key, T, Compare, Allocator>& y);
template <class Key, class T, class Compare, class Allocator>
bool
operator<=(const multimap<Key, T, Compare, Allocator>& x,
const multimap<Key, T, Compare, Allocator>& y);
// specialized algorithms:
template <class Key, class T, class Compare, class Allocator>
void
swap(multimap<Key, T, Compare, Allocator>& x,
multimap<Key, T, Compare, Allocator>& y)
noexcept(noexcept(x.swap(y)));
template <class Key, class T, class Compare, class Allocator, class Predicate>
void erase_if(multimap<Key, T, Compare, Allocator>& c, Predicate pred); // C++20
} // std
*/
#include <__config>
#include <__node_handle>
#include <__tree>
#include <functional>
#include <initializer_list>
#include <iterator>
#include <memory>
#include <type_traits>
#include <utility>
#include <version>
#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
# pragma GCC system_header
#endif
_LIBCPP_BEGIN_NAMESPACE_STD
template <class _Key, class _CP, class _Compare, bool = is_empty<_Compare>::value && !__libcpp_is_final<_Compare>::value>
class __map_value_compare : private _Compare {
public:
__map_value_compare() _NOEXCEPT_(is_nothrow_default_constructible<_Compare>::value) : _Compare() {
}
__map_value_compare(_Compare c) _NOEXCEPT_(is_nothrow_copy_constructible<_Compare>::value) : _Compare(c) {
}
const _Compare& key_comp() const _NOEXCEPT {
return *this;
}
bool operator()(const _CP& __x, const _CP& __y) const {
return static_cast<const _Compare&>(*this)(__x.__get_value().first, __y.__get_value().first);
}
bool operator()(const _CP& __x, const _Key& __y) const {
return static_cast<const _Compare&>(*this)(__x.__get_value().first, __y);
}
bool operator()(const _Key& __x, const _CP& __y) const {
return static_cast<const _Compare&>(*this)(__x, __y.__get_value().first);
}
void swap(__map_value_compare& __y) _NOEXCEPT_(__is_nothrow_swappable<_Compare>::value) {
using _VSTD::swap;
swap(static_cast<_Compare&>(*this), static_cast<_Compare&>(__y));
}
#if _LIBCPP_STD_VER > 11
template <typename _K2>
typename enable_if<__is_transparent<_Compare, _K2>::value, bool>::type operator()(const _K2& __x, const _CP& __y) const {
return static_cast<const _Compare&>(*this)(__x, __y.__get_value().first);
}
template <typename _K2>
typename enable_if<__is_transparent<_Compare, _K2>::value, bool>::type operator()(const _CP& __x, const _K2& __y) const {
return static_cast<const _Compare&>(*this)(__x.__get_value().first, __y);
}
#endif
};
template <class _Key, class _CP, class _Compare>
class __map_value_compare<_Key, _CP, _Compare, false> {
_Compare comp;
public:
__map_value_compare() _NOEXCEPT_(is_nothrow_default_constructible<_Compare>::value) : comp() {
}
__map_value_compare(_Compare c) _NOEXCEPT_(is_nothrow_copy_constructible<_Compare>::value) : comp(c) {
}
const _Compare& key_comp() const _NOEXCEPT {
return comp;
}
bool operator()(const _CP& __x, const _CP& __y) const {
return comp(__x.__get_value().first, __y.__get_value().first);
}
bool operator()(const _CP& __x, const _Key& __y) const {
return comp(__x.__get_value().first, __y);
}
bool operator()(const _Key& __x, const _CP& __y) const {
return comp(__x, __y.__get_value().first);
}
void swap(__map_value_compare& __y) _NOEXCEPT_(__is_nothrow_swappable<_Compare>::value) {
using _VSTD::swap;
swap(comp, __y.comp);
}
#if _LIBCPP_STD_VER > 11
template <typename _K2>
typename enable_if<__is_transparent<_Compare, _K2>::value, bool>::type operator()(const _K2& __x, const _CP& __y) const {
return comp(__x, __y.__get_value().first);
}
template <typename _K2>
typename enable_if<__is_transparent<_Compare, _K2>::value, bool>::type operator()(const _CP& __x, const _K2& __y) const {
return comp(__x.__get_value().first, __y);
}
#endif
};
template <class _Key, class _CP, class _Compare, bool __b>
inline void swap(__map_value_compare<_Key, _CP, _Compare, __b>& __x, __map_value_compare<_Key, _CP, _Compare, __b>& __y)
_NOEXCEPT_(_NOEXCEPT_(__x.swap(__y))) {
__x.swap(__y);
}
template <class _Allocator>
class __map_node_destructor {
typedef _Allocator allocator_type;
typedef allocator_traits<allocator_type> __alloc_traits;
public:
typedef typename __alloc_traits::pointer pointer;
private:
allocator_type& __na_;
__map_node_destructor& operator=(const __map_node_destructor&);
public:
bool __first_constructed;
bool __second_constructed;
explicit __map_node_destructor(allocator_type& __na) _NOEXCEPT : __na_(__na), __first_constructed(false), __second_constructed(false) {
}
#ifndef _LIBCPP_CXX03_LANG
__map_node_destructor(__tree_node_destructor<allocator_type>&& __x) _NOEXCEPT : __na_(__x.__na_),
__first_constructed(__x.__value_constructed),
__second_constructed(__x.__value_constructed) {
__x.__value_constructed = false;
}
#endif // _LIBCPP_CXX03_LANG
void operator()(pointer __p) _NOEXCEPT {
if (__second_constructed)
__alloc_traits::destroy(__na_, _VSTD::addressof(__p->__value_.__get_value().second));
if (__first_constructed)
__alloc_traits::destroy(__na_, _VSTD::addressof(__p->__value_.__get_value().first));
if (__p)
__alloc_traits::deallocate(__na_, __p, 1);
}
};
template <class _Key, class _Tp, class _Compare, class _Allocator>
class map;
template <class _Key, class _Tp, class _Compare, class _Allocator>
class multimap;
template <class _TreeIterator>
class __map_const_iterator;
#ifndef _LIBCPP_CXX03_LANG
template <class _Key, class _Tp>
struct __value_type {
typedef _Key key_type;
typedef _Tp mapped_type;
typedef pair<const key_type, mapped_type> value_type;
typedef pair<key_type&, mapped_type&> __nc_ref_pair_type;
typedef pair<key_type&&, mapped_type&&> __nc_rref_pair_type;
private:
value_type __cc;
public:
value_type& __get_value() {
# if _LIBCPP_STD_VER > 14
return *_VSTD::launder(_VSTD::addressof(__cc));
# else
return __cc;
# endif
}
const value_type& __get_value() const {
# if _LIBCPP_STD_VER > 14
return *_VSTD::launder(_VSTD::addressof(__cc));
# else
return __cc;
# endif
}
__nc_ref_pair_type __ref() {
value_type& __v = __get_value();
return __nc_ref_pair_type(const_cast<key_type&>(__v.first), __v.second);
}
__nc_rref_pair_type __move() {
value_type& __v = __get_value();
return __nc_rref_pair_type(_VSTD::move(const_cast<key_type&>(__v.first)), _VSTD::move(__v.second));
}
__value_type& operator=(const __value_type& __v) {
__ref() = __v.__get_value();
return *this;
}
__value_type& operator=(__value_type&& __v) {
__ref() = __v.__move();
return *this;
}
template <class _ValueTp, class = typename enable_if<__is_same_uncvref<_ValueTp, value_type>::value>::type>
__value_type& operator=(_ValueTp&& __v) {
__ref() = _VSTD::forward<_ValueTp>(__v);
return *this;
}
private:
__value_type() _LIBCPP_EQUAL_DELETE;
~__value_type() _LIBCPP_EQUAL_DELETE;
__value_type(const __value_type& __v) _LIBCPP_EQUAL_DELETE;
__value_type(__value_type&& __v) _LIBCPP_EQUAL_DELETE;
};
#else
template <class _Key, class _Tp>
struct __value_type {
typedef _Key key_type;
typedef _Tp mapped_type;
typedef pair<const key_type, mapped_type> value_type;
private:
value_type __cc;
public:
value_type& __get_value() {
return __cc;
}
const value_type& __get_value() const {
return __cc;
}
private:
__value_type();
__value_type(__value_type const&);
__value_type& operator=(__value_type const&);
~__value_type();
};
#endif // _LIBCPP_CXX03_LANG
template <class _Tp>
struct __extract_key_value_types;
template <class _Key, class _Tp>
struct __extract_key_value_types<__value_type<_Key, _Tp>> {
typedef _Key const __key_type;
typedef _Tp __mapped_type;
};
template <class _TreeIterator>
class __map_iterator {
typedef typename _TreeIterator::_NodeTypes _NodeTypes;
typedef typename _TreeIterator::__pointer_traits __pointer_traits;
_TreeIterator __i_;
public:
typedef bidirectional_iterator_tag iterator_category;
typedef typename _NodeTypes::__map_value_type value_type;
typedef typename _TreeIterator::difference_type difference_type;
typedef value_type& reference;
typedef typename _NodeTypes::__map_value_type_pointer pointer;
__map_iterator() _NOEXCEPT {
}
__map_iterator(_TreeIterator __i) _NOEXCEPT : __i_(__i) {
}
reference operator*() const {
return __i_->__get_value();
}
pointer operator->() const {
return pointer_traits<pointer>::pointer_to(__i_->__get_value());
}
__map_iterator& operator++() {
++__i_;
return *this;
}
__map_iterator operator++(int) {
__map_iterator __t(*this);
++(*this);
return __t;
}
__map_iterator& operator--() {
--__i_;
return *this;
}
__map_iterator operator--(int) {
__map_iterator __t(*this);
--(*this);
return __t;
}
friend bool operator==(const __map_iterator& __x, const __map_iterator& __y) {
return __x.__i_ == __y.__i_;
}
friend bool operator!=(const __map_iterator& __x, const __map_iterator& __y) {
return __x.__i_ != __y.__i_;
}
template <class, class, class, class>
friend class map;
template <class, class, class, class>
friend class multimap;
template <class>
friend class __map_const_iterator;
};
template <class _TreeIterator>
class __map_const_iterator {
typedef typename _TreeIterator::_NodeTypes _NodeTypes;
typedef typename _TreeIterator::__pointer_traits __pointer_traits;
_TreeIterator __i_;
public:
typedef bidirectional_iterator_tag iterator_category;
typedef typename _NodeTypes::__map_value_type value_type;
typedef typename _TreeIterator::difference_type difference_type;
typedef const value_type& reference;
typedef typename _NodeTypes::__const_map_value_type_pointer pointer;
__map_const_iterator() _NOEXCEPT {
}
__map_const_iterator(_TreeIterator __i) _NOEXCEPT : __i_(__i) {
}
__map_const_iterator(__map_iterator<typename _TreeIterator::__non_const_iterator> __i) _NOEXCEPT : __i_(__i.__i_) {
}
reference operator*() const {
return __i_->__get_value();
}
pointer operator->() const {
return pointer_traits<pointer>::pointer_to(__i_->__get_value());
}
__map_const_iterator& operator++() {
++__i_;
return *this;
}
__map_const_iterator operator++(int) {
__map_const_iterator __t(*this);
++(*this);
return __t;
}
__map_const_iterator& operator--() {
--__i_;
return *this;
}
__map_const_iterator operator--(int) {
__map_const_iterator __t(*this);
--(*this);
return __t;
}
friend bool operator==(const __map_const_iterator& __x, const __map_const_iterator& __y) {
return __x.__i_ == __y.__i_;
}
friend bool operator!=(const __map_const_iterator& __x, const __map_const_iterator& __y) {
return __x.__i_ != __y.__i_;
}
template <class, class, class, class>
friend class map;
template <class, class, class, class>
friend class multimap;
template <class, class, class>
friend class __tree_const_iterator;
};
template <class _Key, class _Tp, class _Compare = less<_Key>, class _Allocator = allocator<pair<const _Key, _Tp>>>
class map {
public:
// types:
typedef _Key key_type;
typedef _Tp mapped_type;
typedef pair<const key_type, mapped_type> value_type;
typedef _Compare key_compare;
typedef _Allocator allocator_type;
typedef value_type& reference;
typedef const value_type& const_reference;
static_assert(sizeof(__diagnose_non_const_comparator<_Key, _Compare>()), "");
static_assert((is_same<typename allocator_type::value_type, value_type>::value), "Allocator::value_type must be same type as value_type");
class value_compare : public binary_function<value_type, value_type, bool> {
friend class map;
protected:
key_compare comp;
value_compare(key_compare c) : comp(c) {
}
public:
bool operator()(const value_type& __x, const value_type& __y) const {
return comp(__x.first, __y.first);
}
};
private:
typedef _VSTD::__value_type<key_type, mapped_type> __value_type;
typedef __map_value_compare<key_type, __value_type, key_compare> __vc;
typedef typename __rebind_alloc_helper<allocator_traits<allocator_type>, __value_type>::type __allocator_type;
typedef __tree<__value_type, __vc, __allocator_type> __base;
typedef typename __base::__node_traits __node_traits;
typedef allocator_traits<allocator_type> __alloc_traits;
__base __tree_;
public:
typedef typename __alloc_traits::pointer pointer;
typedef typename __alloc_traits::const_pointer const_pointer;
typedef typename __alloc_traits::size_type size_type;
typedef typename __alloc_traits::difference_type difference_type;
typedef __map_iterator<typename __base::iterator> iterator;
typedef __map_const_iterator<typename __base::const_iterator> const_iterator;
typedef _VSTD::reverse_iterator<iterator> reverse_iterator;
typedef _VSTD::reverse_iterator<const_iterator> const_reverse_iterator;
#if _LIBCPP_STD_VER > 14
typedef __map_node_handle<typename __base::__node, allocator_type> node_type;
typedef __insert_return_type<iterator, node_type> insert_return_type;
#endif
template <class _Key2, class _Value2, class _Comp2, class _Alloc2>
friend class map;
template <class _Key2, class _Value2, class _Comp2, class _Alloc2>
friend class multimap;
map() _NOEXCEPT_(is_nothrow_default_constructible<allocator_type>::value&& is_nothrow_default_constructible<key_compare>::value&&
is_nothrow_copy_constructible<key_compare>::value)
: __tree_(__vc(key_compare())) {
}
explicit map(const key_compare& __comp)
_NOEXCEPT_(is_nothrow_default_constructible<allocator_type>::value&& is_nothrow_copy_constructible<key_compare>::value)
: __tree_(__vc(__comp)) {
}
explicit map(const key_compare& __comp, const allocator_type& __a) : __tree_(__vc(__comp), typename __base::allocator_type(__a)) {
}
template <class _InputIterator>
map(_InputIterator __f, _InputIterator __l, const key_compare& __comp = key_compare()) : __tree_(__vc(__comp)) {
insert(__f, __l);
}
template <class _InputIterator>
map(_InputIterator __f, _InputIterator __l, const key_compare& __comp, const allocator_type& __a)
: __tree_(__vc(__comp), typename __base::allocator_type(__a)) {
insert(__f, __l);
}
#if _LIBCPP_STD_VER > 11
template <class _InputIterator>
map(_InputIterator __f, _InputIterator __l, const allocator_type& __a) : map(__f, __l, key_compare(), __a) {
}
#endif
map(const map& __m) : __tree_(__m.__tree_) {
insert(__m.begin(), __m.end());
}
map& operator=(const map& __m) {
#ifndef _LIBCPP_CXX03_LANG
__tree_ = __m.__tree_;
#else
if (this != &__m) {
__tree_.clear();
__tree_.value_comp() = __m.__tree_.value_comp();
__tree_.__copy_assign_alloc(__m.__tree_);
insert(__m.begin(), __m.end());
}
#endif
return *this;
}
#ifndef _LIBCPP_CXX03_LANG
map(map&& __m) _NOEXCEPT_(is_nothrow_move_constructible<__base>::value) : __tree_(_VSTD::move(__m.__tree_)) {
}
map(map&& __m, const allocator_type& __a);
map& operator=(map&& __m) _NOEXCEPT_(is_nothrow_move_assignable<__base>::value) {
__tree_ = _VSTD::move(__m.__tree_);
return *this;
}
map(initializer_list<value_type> __il, const key_compare& __comp = key_compare()) : __tree_(__vc(__comp)) {
insert(__il.begin(), __il.end());
}
map(initializer_list<value_type> __il, const key_compare& __comp, const allocator_type& __a)
: __tree_(__vc(__comp), typename __base::allocator_type(__a)) {
insert(__il.begin(), __il.end());
}
# if _LIBCPP_STD_VER > 11
map(initializer_list<value_type> __il, const allocator_type& __a) : map(__il, key_compare(), __a) {
}
# endif
map& operator=(initializer_list<value_type> __il) {
__tree_.__assign_unique(__il.begin(), __il.end());
return *this;
}
#endif // _LIBCPP_CXX03_LANG
explicit map(const allocator_type& __a) : __tree_(typename __base::allocator_type(__a)) {
}
map(const map& __m, const allocator_type& __a) : __tree_(__m.__tree_.value_comp(), typename __base::allocator_type(__a)) {
insert(__m.begin(), __m.end());
}
iterator begin() _NOEXCEPT {
return __tree_.begin();
}
const_iterator begin() const _NOEXCEPT {
return __tree_.begin();
}
iterator end() _NOEXCEPT {
return __tree_.end();
}
const_iterator end() const _NOEXCEPT {
return __tree_.end();
}
reverse_iterator rbegin() _NOEXCEPT {
return reverse_iterator(end());
}
const_reverse_iterator rbegin() const _NOEXCEPT {
return const_reverse_iterator(end());
}
reverse_iterator rend() _NOEXCEPT {
return reverse_iterator(begin());
}
const_reverse_iterator rend() const _NOEXCEPT {
return const_reverse_iterator(begin());
}
const_iterator cbegin() const _NOEXCEPT {
return begin();
}
const_iterator cend() const _NOEXCEPT {
return end();
}
const_reverse_iterator crbegin() const _NOEXCEPT {
return rbegin();
}
const_reverse_iterator crend() const _NOEXCEPT {
return rend();
}
_LIBCPP_NODISCARD_AFTER_CXX17 bool empty() const _NOEXCEPT {
return __tree_.size() == 0;
}
size_type size() const _NOEXCEPT {
return __tree_.size();
}
size_type max_size() const _NOEXCEPT {
return __tree_.max_size();
}
mapped_type& operator[](const key_type& __k);
#ifndef _LIBCPP_CXX03_LANG
mapped_type& operator[](key_type&& __k);
#endif
mapped_type& at(const key_type& __k);
const mapped_type& at(const key_type& __k) const;
allocator_type get_allocator() const _NOEXCEPT {
return allocator_type(__tree_.__alloc());
}
key_compare key_comp() const {
return __tree_.value_comp().key_comp();
}
value_compare value_comp() const {
return value_compare(__tree_.value_comp().key_comp());
}
#ifndef _LIBCPP_CXX03_LANG
template <class... _Args>
pair<iterator, bool> emplace(_Args&&... __args) {
return __tree_.__emplace_unique(_VSTD::forward<_Args>(__args)...);
}
template <class... _Args>
iterator emplace_hint(const_iterator __p, _Args&&... __args) {
return __tree_.__emplace_hint_unique(__p.__i_, _VSTD::forward<_Args>(__args)...);
}
template <class _Pp, class = typename enable_if<is_constructible<value_type, _Pp>::value>::type>
pair<iterator, bool> insert(_Pp&& __p) {
return __tree_.__insert_unique(_VSTD::forward<_Pp>(__p));
}
template <class _Pp, class = typename enable_if<is_constructible<value_type, _Pp>::value>::type>
iterator insert(const_iterator __pos, _Pp&& __p) {
return __tree_.__insert_unique(__pos.__i_, _VSTD::forward<_Pp>(__p));
}
#endif // _LIBCPP_CXX03_LANG
pair<iterator, bool> insert(const value_type& __v) {
return __tree_.__insert_unique(__v);
}
iterator insert(const_iterator __p, const value_type& __v) {
return __tree_.__insert_unique(__p.__i_, __v);
}
#ifndef _LIBCPP_CXX03_LANG
pair<iterator, bool> insert(value_type&& __v) {
return __tree_.__insert_unique(_VSTD::move(__v));
}
iterator insert(const_iterator __p, value_type&& __v) {
return __tree_.__insert_unique(__p.__i_, _VSTD::move(__v));
}
void insert(initializer_list<value_type> __il) {
insert(__il.begin(), __il.end());
}
#endif
template <class _InputIterator>
void insert(_InputIterator __f, _InputIterator __l) {
for (const_iterator __e = cend(); __f != __l; ++__f) insert(__e.__i_, *__f);
}
#if _LIBCPP_STD_VER > 14
template <class... _Args>
pair<iterator, bool> try_emplace(const key_type& __k, _Args&&... __args) {
return __tree_.__emplace_unique_key_args(__k, _VSTD::piecewise_construct, _VSTD::forward_as_tuple(__k),
_VSTD::forward_as_tuple(_VSTD::forward<_Args>(__args)...));
}
template <class... _Args>
pair<iterator, bool> try_emplace(key_type&& __k, _Args&&... __args) {
return __tree_.__emplace_unique_key_args(__k, _VSTD::piecewise_construct, _VSTD::forward_as_tuple(_VSTD::move(__k)),
_VSTD::forward_as_tuple(_VSTD::forward<_Args>(__args)...));
}
template <class... _Args>
iterator try_emplace(const_iterator __h, const key_type& __k, _Args&&... __args) {
return __tree_.__emplace_hint_unique_key_args(__h.__i_, __k, _VSTD::piecewise_construct, _VSTD::forward_as_tuple(__k),
_VSTD::forward_as_tuple(_VSTD::forward<_Args>(__args)...));
}
template <class... _Args>
iterator try_emplace(const_iterator __h, key_type&& __k, _Args&&... __args) {
return __tree_.__emplace_hint_unique_key_args(__h.__i_, __k, _VSTD::piecewise_construct, _VSTD::forward_as_tuple(_VSTD::move(__k)),
_VSTD::forward_as_tuple(_VSTD::forward<_Args>(__args)...));
}
template <class _Vp>
pair<iterator, bool> insert_or_assign(const key_type& __k, _Vp&& __v) {
iterator __p = lower_bound(__k);
if (__p != end() && !key_comp()(__k, __p->first)) {
__p->second = _VSTD::forward<_Vp>(__v);
return _VSTD::make_pair(__p, false);
}
return _VSTD::make_pair(emplace_hint(__p, __k, _VSTD::forward<_Vp>(__v)), true);
}
template <class _Vp>
pair<iterator, bool> insert_or_assign(key_type&& __k, _Vp&& __v) {
iterator __p = lower_bound(__k);
if (__p != end() && !key_comp()(__k, __p->first)) {
__p->second = _VSTD::forward<_Vp>(__v);
return _VSTD::make_pair(__p, false);
}
return _VSTD::make_pair(emplace_hint(__p, _VSTD::move(__k), _VSTD::forward<_Vp>(__v)), true);
}
template <class _Vp>
iterator insert_or_assign(const_iterator __h, const key_type& __k, _Vp&& __v) {
iterator __p = lower_bound(__k);
if (__p != end() && !key_comp()(__k, __p->first)) {
__p->second = _VSTD::forward<_Vp>(__v);
return __p;
}
return emplace_hint(__h, __k, _VSTD::forward<_Vp>(__v));
}
template <class _Vp>
iterator insert_or_assign(const_iterator __h, key_type&& __k, _Vp&& __v) {
iterator __p = lower_bound(__k);
if (__p != end() && !key_comp()(__k, __p->first)) {
__p->second = _VSTD::forward<_Vp>(__v);
return __p;
}
return emplace_hint(__h, _VSTD::move(__k), _VSTD::forward<_Vp>(__v));
}
#endif // _LIBCPP_STD_VER > 14
iterator erase(const_iterator __p) {
return __tree_.erase(__p.__i_);
}
iterator erase(iterator __p) {
return __tree_.erase(__p.__i_);
}
size_type erase(const key_type& __k) {
return __tree_.__erase_unique(__k);
}
iterator erase(const_iterator __f, const_iterator __l) {
return __tree_.erase(__f.__i_, __l.__i_);
}
void clear() _NOEXCEPT {
__tree_.clear();
}
#if _LIBCPP_STD_VER > 14
insert_return_type insert(node_type&& __nh) {
_LIBCPP_ASSERT(__nh.empty() || __nh.get_allocator() == get_allocator(), "node_type with incompatible allocator passed to map::insert()");
return __tree_.template __node_handle_insert_unique<node_type, insert_return_type>(_VSTD::move(__nh));
}
iterator insert(const_iterator __hint, node_type&& __nh) {
_LIBCPP_ASSERT(__nh.empty() || __nh.get_allocator() == get_allocator(), "node_type with incompatible allocator passed to map::insert()");
return __tree_.template __node_handle_insert_unique<node_type>(__hint.__i_, _VSTD::move(__nh));
}
node_type extract(key_type const& __key) {
return __tree_.template __node_handle_extract<node_type>(__key);
}
node_type extract(const_iterator __it) {
return __tree_.template __node_handle_extract<node_type>(__it.__i_);
}
template <class _Compare2>
void merge(map<key_type, mapped_type, _Compare2, allocator_type>& __source) {
_LIBCPP_ASSERT(__source.get_allocator() == get_allocator(), "merging container with incompatible allocator");
__tree_.__node_handle_merge_unique(__source.__tree_);
}
template <class _Compare2>
void merge(map<key_type, mapped_type, _Compare2, allocator_type>&& __source) {
_LIBCPP_ASSERT(__source.get_allocator() == get_allocator(), "merging container with incompatible allocator");
__tree_.__node_handle_merge_unique(__source.__tree_);
}
template <class _Compare2>
void merge(multimap<key_type, mapped_type, _Compare2, allocator_type>& __source) {
_LIBCPP_ASSERT(__source.get_allocator() == get_allocator(), "merging container with incompatible allocator");
__tree_.__node_handle_merge_unique(__source.__tree_);
}
template <class _Compare2>
void merge(multimap<key_type, mapped_type, _Compare2, allocator_type>&& __source) {
_LIBCPP_ASSERT(__source.get_allocator() == get_allocator(), "merging container with incompatible allocator");
__tree_.__node_handle_merge_unique(__source.__tree_);
}
#endif
void swap(map& __m) _NOEXCEPT_(__is_nothrow_swappable<__base>::value) {
__tree_.swap(__m.__tree_);
}
iterator find(const key_type& __k) {
return __tree_.find(__k);
}
const_iterator find(const key_type& __k) const {
return __tree_.find(__k);
}
#if _LIBCPP_STD_VER > 11
template <typename _K2>
typename enable_if<__is_transparent<_Compare, _K2>::value, iterator>::type find(const _K2& __k) {
return __tree_.find(__k);
}
template <typename _K2>
typename enable_if<__is_transparent<_Compare, _K2>::value, const_iterator>::type find(const _K2& __k) const {
return __tree_.find(__k);
}
#endif
size_type count(const key_type& __k) const {
return __tree_.__count_unique(__k);
}
#if _LIBCPP_STD_VER > 11
template <typename _K2>
typename enable_if<__is_transparent<_Compare, _K2>::value, size_type>::type count(const _K2& __k) const {
return __tree_.__count_multi(__k);
}
#endif
iterator lower_bound(const key_type& __k) {
return __tree_.lower_bound(__k);
}
const_iterator lower_bound(const key_type& __k) const {
return __tree_.lower_bound(__k);
}
#if _LIBCPP_STD_VER > 11
template <typename _K2>
typename enable_if<__is_transparent<_Compare, _K2>::value, iterator>::type lower_bound(const _K2& __k) {
return __tree_.lower_bound(__k);
}
template <typename _K2>
typename enable_if<__is_transparent<_Compare, _K2>::value, const_iterator>::type lower_bound(const _K2& __k) const {
return __tree_.lower_bound(__k);
}
#endif
iterator upper_bound(const key_type& __k) {
return __tree_.upper_bound(__k);
}
const_iterator upper_bound(const key_type& __k) const {
return __tree_.upper_bound(__k);
}
#if _LIBCPP_STD_VER > 11
template <typename _K2>
typename enable_if<__is_transparent<_Compare, _K2>::value, iterator>::type upper_bound(const _K2& __k) {
return __tree_.upper_bound(__k);
}
template <typename _K2>
typename enable_if<__is_transparent<_Compare, _K2>::value, const_iterator>::type upper_bound(const _K2& __k) const {
return __tree_.upper_bound(__k);
}
#endif
pair<iterator, iterator> equal_range(const key_type& __k) {
return __tree_.__equal_range_unique(__k);
}
pair<const_iterator, const_iterator> equal_range(const key_type& __k) const {
return __tree_.__equal_range_unique(__k);
}
#if _LIBCPP_STD_VER > 11
template <typename _K2>
typename enable_if<__is_transparent<_Compare, _K2>::value, pair<iterator, iterator>>::type equal_range(const _K2& __k) {
return __tree_.__equal_range_multi(__k);
}
template <typename _K2>
typename enable_if<__is_transparent<_Compare, _K2>::value, pair<const_iterator, const_iterator>>::type equal_range(const _K2& __k) const {
return __tree_.__equal_range_multi(__k);
}
#endif
private:
typedef typename __base::__node __node;
typedef typename __base::__node_allocator __node_allocator;
typedef typename __base::__node_pointer __node_pointer;
typedef typename __base::__node_base_pointer __node_base_pointer;
typedef typename __base::__parent_pointer __parent_pointer;
typedef __map_node_destructor<__node_allocator> _Dp;
typedef unique_ptr<__node, _Dp> __node_holder;
#ifdef _LIBCPP_CXX03_LANG
__node_holder __construct_node_with_key(const key_type& __k);
#endif
};
#ifndef _LIBCPP_CXX03_LANG
template <class _Key, class _Tp, class _Compare, class _Allocator>
map<_Key, _Tp, _Compare, _Allocator>::map(map&& __m, const allocator_type& __a)
: __tree_(_VSTD::move(__m.__tree_), typename __base::allocator_type(__a)) {
if (__a != __m.get_allocator()) {
const_iterator __e = cend();
while (!__m.empty()) __tree_.__insert_unique(__e.__i_, __m.__tree_.remove(__m.begin().__i_)->__value_.__move());
}
}
template <class _Key, class _Tp, class _Compare, class _Allocator>
_Tp& map<_Key, _Tp, _Compare, _Allocator>::operator[](const key_type& __k) {
return __tree_.__emplace_unique_key_args(__k, _VSTD::piecewise_construct, _VSTD::forward_as_tuple(__k), _VSTD::forward_as_tuple())
.first->__get_value()
.second;
}
template <class _Key, class _Tp, class _Compare, class _Allocator>
_Tp& map<_Key, _Tp, _Compare, _Allocator>::operator[](key_type&& __k) {
return __tree_
.__emplace_unique_key_args(__k, _VSTD::piecewise_construct, _VSTD::forward_as_tuple(_VSTD::move(__k)), _VSTD::forward_as_tuple())
.first->__get_value()
.second;
}
#else // _LIBCPP_CXX03_LANG
template <class _Key, class _Tp, class _Compare, class _Allocator>
typename map<_Key, _Tp, _Compare, _Allocator>::__node_holder map<_Key, _Tp, _Compare, _Allocator>::__construct_node_with_key(
const key_type& __k) {
__node_allocator& __na = __tree_.__node_alloc();
__node_holder __h(__node_traits::allocate(__na, 1), _Dp(__na));
__node_traits::construct(__na, _VSTD::addressof(__h->__value_.__get_value().first), __k);
__h.get_deleter().__first_constructed = true;
__node_traits::construct(__na, _VSTD::addressof(__h->__value_.__get_value().second));
__h.get_deleter().__second_constructed = true;
return _LIBCPP_EXPLICIT_MOVE(__h); // explicitly moved for C++03
}
template <class _Key, class _Tp, class _Compare, class _Allocator>
_Tp& map<_Key, _Tp, _Compare, _Allocator>::operator[](const key_type& __k) {
__parent_pointer __parent;
__node_base_pointer& __child = __tree_.__find_equal(__parent, __k);
__node_pointer __r = static_cast<__node_pointer>(__child);
if (__child == nullptr) {
__node_holder __h = __construct_node_with_key(__k);
__tree_.__insert_node_at(__parent, __child, static_cast<__node_base_pointer>(__h.get()));
__r = __h.release();
}
return __r->__value_.__get_value().second;
}
#endif // _LIBCPP_CXX03_LANG
template <class _Key, class _Tp, class _Compare, class _Allocator>
_Tp& map<_Key, _Tp, _Compare, _Allocator>::at(const key_type& __k) {
__parent_pointer __parent;
__node_base_pointer& __child = __tree_.__find_equal(__parent, __k);
#ifndef _LIBCPP_NO_EXCEPTIONS
if (__child == nullptr)
throw out_of_range("map::at: key not found");
#endif // _LIBCPP_NO_EXCEPTIONS
return static_cast<__node_pointer>(__child)->__value_.__get_value().second;
}
template <class _Key, class _Tp, class _Compare, class _Allocator>
const _Tp& map<_Key, _Tp, _Compare, _Allocator>::at(const key_type& __k) const {
__parent_pointer __parent;
__node_base_pointer __child = __tree_.__find_equal(__parent, __k);
#ifndef _LIBCPP_NO_EXCEPTIONS
if (__child == nullptr)
throw out_of_range("map::at: key not found");
#endif // _LIBCPP_NO_EXCEPTIONS
return static_cast<__node_pointer>(__child)->__value_.__get_value().second;
}
template <class _Key, class _Tp, class _Compare, class _Allocator>
inline bool operator==(const map<_Key, _Tp, _Compare, _Allocator>& __x, const map<_Key, _Tp, _Compare, _Allocator>& __y) {
return __x.size() == __y.size() && _VSTD::equal(__x.begin(), __x.end(), __y.begin());
}
template <class _Key, class _Tp, class _Compare, class _Allocator>
inline bool operator<(const map<_Key, _Tp, _Compare, _Allocator>& __x, const map<_Key, _Tp, _Compare, _Allocator>& __y) {
return _VSTD::lexicographical_compare(__x.begin(), __x.end(), __y.begin(), __y.end());
}
template <class _Key, class _Tp, class _Compare, class _Allocator>
inline bool operator!=(const map<_Key, _Tp, _Compare, _Allocator>& __x, const map<_Key, _Tp, _Compare, _Allocator>& __y) {
return !(__x == __y);
}
template <class _Key, class _Tp, class _Compare, class _Allocator>
inline bool operator>(const map<_Key, _Tp, _Compare, _Allocator>& __x, const map<_Key, _Tp, _Compare, _Allocator>& __y) {
return __y < __x;
}
template <class _Key, class _Tp, class _Compare, class _Allocator>
inline bool operator>=(const map<_Key, _Tp, _Compare, _Allocator>& __x, const map<_Key, _Tp, _Compare, _Allocator>& __y) {
return !(__x < __y);
}
template <class _Key, class _Tp, class _Compare, class _Allocator>
inline bool operator<=(const map<_Key, _Tp, _Compare, _Allocator>& __x, const map<_Key, _Tp, _Compare, _Allocator>& __y) {
return !(__y < __x);
}
template <class _Key, class _Tp, class _Compare, class _Allocator>
inline void swap(map<_Key, _Tp, _Compare, _Allocator>& __x, map<_Key, _Tp, _Compare, _Allocator>& __y) _NOEXCEPT_(_NOEXCEPT_(__x.swap(__y))) {
__x.swap(__y);
}
#if _LIBCPP_STD_VER > 17
template <class _Key, class _Tp, class _Compare, class _Allocator, class _Predicate>
inline void erase_if(map<_Key, _Tp, _Compare, _Allocator>& __c, _Predicate __pred) {
__libcpp_erase_if_container(__c, __pred);
}
#endif
template <class _Key, class _Tp, class _Compare = less<_Key>, class _Allocator = allocator<pair<const _Key, _Tp>>>
class multimap {
public:
// types:
typedef _Key key_type;
typedef _Tp mapped_type;
typedef pair<const key_type, mapped_type> value_type;
typedef _Compare key_compare;
typedef _Allocator allocator_type;
typedef value_type& reference;
typedef const value_type& const_reference;
static_assert(sizeof(__diagnose_non_const_comparator<_Key, _Compare>()), "");
static_assert((is_same<typename allocator_type::value_type, value_type>::value), "Allocator::value_type must be same type as value_type");
class value_compare : public binary_function<value_type, value_type, bool> {
friend class multimap;
protected:
key_compare comp;
value_compare(key_compare c) : comp(c) {
}
public:
bool operator()(const value_type& __x, const value_type& __y) const {
return comp(__x.first, __y.first);
}
};
private:
typedef _VSTD::__value_type<key_type, mapped_type> __value_type;
typedef __map_value_compare<key_type, __value_type, key_compare> __vc;
typedef typename __rebind_alloc_helper<allocator_traits<allocator_type>, __value_type>::type __allocator_type;
typedef __tree<__value_type, __vc, __allocator_type> __base;
typedef typename __base::__node_traits __node_traits;
typedef allocator_traits<allocator_type> __alloc_traits;
__base __tree_;
public:
typedef typename __alloc_traits::pointer pointer;
typedef typename __alloc_traits::const_pointer const_pointer;
typedef typename __alloc_traits::size_type size_type;
typedef typename __alloc_traits::difference_type difference_type;
typedef __map_iterator<typename __base::iterator> iterator;
typedef __map_const_iterator<typename __base::const_iterator> const_iterator;
typedef _VSTD::reverse_iterator<iterator> reverse_iterator;
typedef _VSTD::reverse_iterator<const_iterator> const_reverse_iterator;
#if _LIBCPP_STD_VER > 14
typedef __map_node_handle<typename __base::__node, allocator_type> node_type;
#endif
template <class _Key2, class _Value2, class _Comp2, class _Alloc2>
friend class map;
template <class _Key2, class _Value2, class _Comp2, class _Alloc2>
friend class multimap;
multimap() _NOEXCEPT_(is_nothrow_default_constructible<allocator_type>::value&& is_nothrow_default_constructible<key_compare>::value&&
is_nothrow_copy_constructible<key_compare>::value)
: __tree_(__vc(key_compare())) {
}
explicit multimap(const key_compare& __comp)
_NOEXCEPT_(is_nothrow_default_constructible<allocator_type>::value&& is_nothrow_copy_constructible<key_compare>::value)
: __tree_(__vc(__comp)) {
}
explicit multimap(const key_compare& __comp, const allocator_type& __a) : __tree_(__vc(__comp), typename __base::allocator_type(__a)) {
}
template <class _InputIterator>
multimap(_InputIterator __f, _InputIterator __l, const key_compare& __comp = key_compare()) : __tree_(__vc(__comp)) {
insert(__f, __l);
}
template <class _InputIterator>
multimap(_InputIterator __f, _InputIterator __l, const key_compare& __comp, const allocator_type& __a)
: __tree_(__vc(__comp), typename __base::allocator_type(__a)) {
insert(__f, __l);
}
#if _LIBCPP_STD_VER > 11
template <class _InputIterator>
multimap(_InputIterator __f, _InputIterator __l, const allocator_type& __a) : multimap(__f, __l, key_compare(), __a) {
}
#endif
multimap(const multimap& __m)
: __tree_(__m.__tree_.value_comp(), __alloc_traits::select_on_container_copy_construction(__m.__tree_.__alloc())) {
insert(__m.begin(), __m.end());
}
multimap& operator=(const multimap& __m) {
#ifndef _LIBCPP_CXX03_LANG
__tree_ = __m.__tree_;
#else
if (this != &__m) {
__tree_.clear();
__tree_.value_comp() = __m.__tree_.value_comp();
__tree_.__copy_assign_alloc(__m.__tree_);
insert(__m.begin(), __m.end());
}
#endif
return *this;
}
#ifndef _LIBCPP_CXX03_LANG
multimap(multimap&& __m) _NOEXCEPT_(is_nothrow_move_constructible<__base>::value) : __tree_(_VSTD::move(__m.__tree_)) {
}
multimap(multimap&& __m, const allocator_type& __a);
multimap& operator=(multimap&& __m) _NOEXCEPT_(is_nothrow_move_assignable<__base>::value) {
__tree_ = _VSTD::move(__m.__tree_);
return *this;
}
multimap(initializer_list<value_type> __il, const key_compare& __comp = key_compare()) : __tree_(__vc(__comp)) {
insert(__il.begin(), __il.end());
}
multimap(initializer_list<value_type> __il, const key_compare& __comp, const allocator_type& __a)
: __tree_(__vc(__comp), typename __base::allocator_type(__a)) {
insert(__il.begin(), __il.end());
}
# if _LIBCPP_STD_VER > 11
multimap(initializer_list<value_type> __il, const allocator_type& __a) : multimap(__il, key_compare(), __a) {
}
# endif
multimap& operator=(initializer_list<value_type> __il) {
__tree_.__assign_multi(__il.begin(), __il.end());
return *this;
}
#endif // _LIBCPP_CXX03_LANG
explicit multimap(const allocator_type& __a) : __tree_(typename __base::allocator_type(__a)) {
}
multimap(const multimap& __m, const allocator_type& __a) : __tree_(__m.__tree_.value_comp(), typename __base::allocator_type(__a)) {
insert(__m.begin(), __m.end());
}
iterator begin() _NOEXCEPT {
return __tree_.begin();
}
const_iterator begin() const _NOEXCEPT {
return __tree_.begin();
}
iterator end() _NOEXCEPT {
return __tree_.end();
}
const_iterator end() const _NOEXCEPT {
return __tree_.end();
}
reverse_iterator rbegin() _NOEXCEPT {
return reverse_iterator(end());
}
const_reverse_iterator rbegin() const _NOEXCEPT {
return const_reverse_iterator(end());
}
reverse_iterator rend() _NOEXCEPT {
return reverse_iterator(begin());
}
const_reverse_iterator rend() const _NOEXCEPT {
return const_reverse_iterator(begin());
}
const_iterator cbegin() const _NOEXCEPT {
return begin();
}
const_iterator cend() const _NOEXCEPT {
return end();
}
const_reverse_iterator crbegin() const _NOEXCEPT {
return rbegin();
}
const_reverse_iterator crend() const _NOEXCEPT {
return rend();
}
_LIBCPP_NODISCARD_AFTER_CXX17 bool empty() const _NOEXCEPT {
return __tree_.size() == 0;
}
size_type size() const _NOEXCEPT {
return __tree_.size();
}
size_type max_size() const _NOEXCEPT {
return __tree_.max_size();
}
allocator_type get_allocator() const _NOEXCEPT {
return allocator_type(__tree_.__alloc());
}
key_compare key_comp() const {
return __tree_.value_comp().key_comp();
}
value_compare value_comp() const {
return value_compare(__tree_.value_comp().key_comp());
}
#ifndef _LIBCPP_CXX03_LANG
template <class... _Args>
iterator emplace(_Args&&... __args) {
return __tree_.__emplace_multi(_VSTD::forward<_Args>(__args)...);
}
template <class... _Args>
iterator emplace_hint(const_iterator __p, _Args&&... __args) {
return __tree_.__emplace_hint_multi(__p.__i_, _VSTD::forward<_Args>(__args)...);
}
template <class _Pp, class = typename enable_if<is_constructible<value_type, _Pp>::value>::type>
iterator insert(_Pp&& __p) {
return __tree_.__insert_multi(_VSTD::forward<_Pp>(__p));
}
template <class _Pp, class = typename enable_if<is_constructible<value_type, _Pp>::value>::type>
iterator insert(const_iterator __pos, _Pp&& __p) {
return __tree_.__insert_multi(__pos.__i_, _VSTD::forward<_Pp>(__p));
}
iterator insert(value_type&& __v) {
return __tree_.__insert_multi(_VSTD::move(__v));
}
iterator insert(const_iterator __p, value_type&& __v) {
return __tree_.__insert_multi(__p.__i_, _VSTD::move(__v));
}
void insert(initializer_list<value_type> __il) {
insert(__il.begin(), __il.end());
}
#endif // _LIBCPP_CXX03_LANG
iterator insert(const value_type& __v) {
return __tree_.__insert_multi(__v);
}
iterator insert(const_iterator __p, const value_type& __v) {
return __tree_.__insert_multi(__p.__i_, __v);
}
template <class _InputIterator>
void insert(_InputIterator __f, _InputIterator __l) {
for (const_iterator __e = cend(); __f != __l; ++__f) __tree_.__insert_multi(__e.__i_, *__f);
}
iterator erase(const_iterator __p) {
return __tree_.erase(__p.__i_);
}
iterator erase(iterator __p) {
return __tree_.erase(__p.__i_);
}
size_type erase(const key_type& __k) {
return __tree_.__erase_multi(__k);
}
iterator erase(const_iterator __f, const_iterator __l) {
return __tree_.erase(__f.__i_, __l.__i_);
}
#if _LIBCPP_STD_VER > 14
iterator insert(node_type&& __nh) {
_LIBCPP_ASSERT(__nh.empty() || __nh.get_allocator() == get_allocator(),
"node_type with incompatible allocator passed to multimap::insert()");
return __tree_.template __node_handle_insert_multi<node_type>(_VSTD::move(__nh));
}
iterator insert(const_iterator __hint, node_type&& __nh) {
_LIBCPP_ASSERT(__nh.empty() || __nh.get_allocator() == get_allocator(),
"node_type with incompatible allocator passed to multimap::insert()");
return __tree_.template __node_handle_insert_multi<node_type>(__hint.__i_, _VSTD::move(__nh));
}
node_type extract(key_type const& __key) {
return __tree_.template __node_handle_extract<node_type>(__key);
}
node_type extract(const_iterator __it) {
return __tree_.template __node_handle_extract<node_type>(__it.__i_);
}
template <class _Compare2>
void merge(multimap<key_type, mapped_type, _Compare2, allocator_type>& __source) {
_LIBCPP_ASSERT(__source.get_allocator() == get_allocator(), "merging container with incompatible allocator");
return __tree_.__node_handle_merge_multi(__source.__tree_);
}
template <class _Compare2>
void merge(multimap<key_type, mapped_type, _Compare2, allocator_type>&& __source) {
_LIBCPP_ASSERT(__source.get_allocator() == get_allocator(), "merging container with incompatible allocator");
return __tree_.__node_handle_merge_multi(__source.__tree_);
}
template <class _Compare2>
void merge(map<key_type, mapped_type, _Compare2, allocator_type>& __source) {
_LIBCPP_ASSERT(__source.get_allocator() == get_allocator(), "merging container with incompatible allocator");
return __tree_.__node_handle_merge_multi(__source.__tree_);
}
template <class _Compare2>
void merge(map<key_type, mapped_type, _Compare2, allocator_type>&& __source) {
_LIBCPP_ASSERT(__source.get_allocator() == get_allocator(), "merging container with incompatible allocator");
return __tree_.__node_handle_merge_multi(__source.__tree_);
}
#endif
void clear() _NOEXCEPT {
__tree_.clear();
}
void swap(multimap& __m) _NOEXCEPT_(__is_nothrow_swappable<__base>::value) {
__tree_.swap(__m.__tree_);
}
iterator find(const key_type& __k) {
return __tree_.find(__k);
}
const_iterator find(const key_type& __k) const {
return __tree_.find(__k);
}
#if _LIBCPP_STD_VER > 11
template <typename _K2>
typename enable_if<__is_transparent<_Compare, _K2>::value, iterator>::type find(const _K2& __k) {
return __tree_.find(__k);
}
template <typename _K2>
typename enable_if<__is_transparent<_Compare, _K2>::value, const_iterator>::type find(const _K2& __k) const {
return __tree_.find(__k);
}
#endif
size_type count(const key_type& __k) const {
return __tree_.__count_multi(__k);
}
#if _LIBCPP_STD_VER > 11
template <typename _K2>
typename enable_if<__is_transparent<_Compare, _K2>::value, size_type>::type count(const _K2& __k) const {
return __tree_.__count_multi(__k);
}
#endif
iterator lower_bound(const key_type& __k) {
return __tree_.lower_bound(__k);
}
const_iterator lower_bound(const key_type& __k) const {
return __tree_.lower_bound(__k);
}
#if _LIBCPP_STD_VER > 11
template <typename _K2>
typename enable_if<__is_transparent<_Compare, _K2>::value, iterator>::type lower_bound(const _K2& __k) {
return __tree_.lower_bound(__k);
}
template <typename _K2>
typename enable_if<__is_transparent<_Compare, _K2>::value, const_iterator>::type lower_bound(const _K2& __k) const {
return __tree_.lower_bound(__k);
}
#endif
iterator upper_bound(const key_type& __k) {
return __tree_.upper_bound(__k);
}
const_iterator upper_bound(const key_type& __k) const {
return __tree_.upper_bound(__k);
}
#if _LIBCPP_STD_VER > 11
template <typename _K2>
typename enable_if<__is_transparent<_Compare, _K2>::value, iterator>::type upper_bound(const _K2& __k) {
return __tree_.upper_bound(__k);
}
template <typename _K2>
typename enable_if<__is_transparent<_Compare, _K2>::value, const_iterator>::type upper_bound(const _K2& __k) const {
return __tree_.upper_bound(__k);
}
#endif
pair<iterator, iterator> equal_range(const key_type& __k) {
return __tree_.__equal_range_multi(__k);
}
pair<const_iterator, const_iterator> equal_range(const key_type& __k) const {
return __tree_.__equal_range_multi(__k);
}
#if _LIBCPP_STD_VER > 11
template <typename _K2>
typename enable_if<__is_transparent<_Compare, _K2>::value, pair<iterator, iterator>>::type equal_range(const _K2& __k) {
return __tree_.__equal_range_multi(__k);
}
template <typename _K2>
typename enable_if<__is_transparent<_Compare, _K2>::value, pair<const_iterator, const_iterator>>::type equal_range(const _K2& __k) const {
return __tree_.__equal_range_multi(__k);
}
#endif
private:
typedef typename __base::__node __node;
typedef typename __base::__node_allocator __node_allocator;
typedef typename __base::__node_pointer __node_pointer;
typedef __map_node_destructor<__node_allocator> _Dp;
typedef unique_ptr<__node, _Dp> __node_holder;
};
#ifndef _LIBCPP_CXX03_LANG
template <class _Key, class _Tp, class _Compare, class _Allocator>
multimap<_Key, _Tp, _Compare, _Allocator>::multimap(multimap&& __m, const allocator_type& __a)
: __tree_(_VSTD::move(__m.__tree_), typename __base::allocator_type(__a)) {
if (__a != __m.get_allocator()) {
const_iterator __e = cend();
while (!__m.empty()) __tree_.__insert_multi(__e.__i_, _VSTD::move(__m.__tree_.remove(__m.begin().__i_)->__value_.__move()));
}
}
#endif
template <class _Key, class _Tp, class _Compare, class _Allocator>
inline bool operator==(const multimap<_Key, _Tp, _Compare, _Allocator>& __x, const multimap<_Key, _Tp, _Compare, _Allocator>& __y) {
return __x.size() == __y.size() && _VSTD::equal(__x.begin(), __x.end(), __y.begin());
}
template <class _Key, class _Tp, class _Compare, class _Allocator>
inline bool operator<(const multimap<_Key, _Tp, _Compare, _Allocator>& __x, const multimap<_Key, _Tp, _Compare, _Allocator>& __y) {
return _VSTD::lexicographical_compare(__x.begin(), __x.end(), __y.begin(), __y.end());
}
template <class _Key, class _Tp, class _Compare, class _Allocator>
inline bool operator!=(const multimap<_Key, _Tp, _Compare, _Allocator>& __x, const multimap<_Key, _Tp, _Compare, _Allocator>& __y) {
return !(__x == __y);
}
template <class _Key, class _Tp, class _Compare, class _Allocator>
inline bool operator>(const multimap<_Key, _Tp, _Compare, _Allocator>& __x, const multimap<_Key, _Tp, _Compare, _Allocator>& __y) {
return __y < __x;
}
template <class _Key, class _Tp, class _Compare, class _Allocator>
inline bool operator>=(const multimap<_Key, _Tp, _Compare, _Allocator>& __x, const multimap<_Key, _Tp, _Compare, _Allocator>& __y) {
return !(__x < __y);
}
template <class _Key, class _Tp, class _Compare, class _Allocator>
inline bool operator<=(const multimap<_Key, _Tp, _Compare, _Allocator>& __x, const multimap<_Key, _Tp, _Compare, _Allocator>& __y) {
return !(__y < __x);
}
template <class _Key, class _Tp, class _Compare, class _Allocator>
inline void swap(multimap<_Key, _Tp, _Compare, _Allocator>& __x, multimap<_Key, _Tp, _Compare, _Allocator>& __y)
_NOEXCEPT_(_NOEXCEPT_(__x.swap(__y))) {
__x.swap(__y);
}
#if _LIBCPP_STD_VER > 17
template <class _Key, class _Tp, class _Compare, class _Allocator, class _Predicate>
inline void erase_if(multimap<_Key, _Tp, _Compare, _Allocator>& __c, _Predicate __pred) {
__libcpp_erase_if_container(__c, __pred);
}
#endif
_LIBCPP_END_NAMESPACE_STD
} // namespace GP
#endif // MAP_HPP
| 39.203844 | 149 | 0.621268 | colorhistory |
99e6737f29370617200af6f96209b976a7ffd22d | 1,502 | hpp | C++ | third-party/Empirical/include/emp/math/distances.hpp | koellingh/empirical-p53-simulator | aa6232f661e8fc65852ab6d3e809339557af521b | [
"MIT"
] | null | null | null | third-party/Empirical/include/emp/math/distances.hpp | koellingh/empirical-p53-simulator | aa6232f661e8fc65852ab6d3e809339557af521b | [
"MIT"
] | null | null | null | third-party/Empirical/include/emp/math/distances.hpp | koellingh/empirical-p53-simulator | aa6232f661e8fc65852ab6d3e809339557af521b | [
"MIT"
] | null | null | null | /**
* @note This file is part of Empirical, https://github.com/devosoft/Empirical
* @copyright Copyright (C) Michigan State University, MIT Software license; see doc/LICENSE.md
* @date 2017-2018
*
* @file distances.hpp
* @brief Library of commonly used distance functions
* @note Status: BETA
*/
#ifndef EMP_DISTANCES_H
#define EMP_DISTANCES_H
#include "math.hpp"
#include "../meta/type_traits.hpp"
namespace emp {
/// Calculate Euclidean distance between two containers
template <typename C>
typename std::enable_if<!emp::is_ptr_type<typename C::value_type>::value, double>::type
EuclideanDistance(C & p1, C & p2) {
emp_assert(p1.size() == p2.size()
&& "Cannot calculate euclidean distance between two containers of different lengths.");
double dist = 0;
for (size_t i = 0; i < p1.size(); ++i) {
dist += pow(p1[i] - p2[i], 2);
}
return sqrt(dist);
}
/// Calculate Euclidean distance between two containers of pointers (de-referencing the pointers)
template <typename C>
typename std::enable_if<emp::is_ptr_type<typename C::value_type>::value, double>::type
EuclideanDistance(C & p1, C & p2) {
emp_assert(p1.size() == p2.size()
&& "Cannot calculate euclidean distance between two containers of different lengths.");
double dist = 0;
for (size_t i = 0; i < p1.size(); ++i) {
dist += emp::Pow(*p1[i] - *p2[i], 2);
}
return sqrt(dist);
}
}
#endif | 28.339623 | 103 | 0.641145 | koellingh |
99e6e3ce55dfb2b5a044271179bf612368f8b5ee | 483 | hpp | C++ | stan/math/rev/meta.hpp | nicokist/math | d47c331a693a3d5ebc4453360743b9353a8e3ed1 | [
"BSD-3-Clause"
] | null | null | null | stan/math/rev/meta.hpp | nicokist/math | d47c331a693a3d5ebc4453360743b9353a8e3ed1 | [
"BSD-3-Clause"
] | null | null | null | stan/math/rev/meta.hpp | nicokist/math | d47c331a693a3d5ebc4453360743b9353a8e3ed1 | [
"BSD-3-Clause"
] | null | null | null | #ifndef STAN_MATH_REV_META_HPP
#define STAN_MATH_REV_META_HPP
#include <stan/math/prim/meta.hpp>
#include <stan/math/rev/meta/arena_type.hpp>
#include <stan/math/rev/meta/is_arena_matrix.hpp>
#include <stan/math/rev/meta/is_var.hpp>
#include <stan/math/rev/meta/is_rev_matrix.hpp>
#include <stan/math/rev/meta/is_vari.hpp>
#include <stan/math/rev/meta/partials_type.hpp>
#include <stan/math/rev/meta/promote_var_matrix.hpp>
#include <stan/math/rev/meta/rev_matrix_type.hpp>
#endif
| 32.2 | 52 | 0.795031 | nicokist |
99e6ef38704fb75b62d0048c9343b39fd37ada75 | 2,899 | cpp | C++ | libraries/audio/src/AbstractAudioInterface.cpp | Penguin-Guru/vircadia | 021268696c73f699364fa93f5d6db03e6b1b8426 | [
"Apache-2.0"
] | 272 | 2021-01-07T03:06:08.000Z | 2022-03-25T03:54:07.000Z | libraries/audio/src/AbstractAudioInterface.cpp | Penguin-Guru/vircadia | 021268696c73f699364fa93f5d6db03e6b1b8426 | [
"Apache-2.0"
] | 1,021 | 2020-12-12T02:33:32.000Z | 2022-03-31T23:36:37.000Z | libraries/audio/src/AbstractAudioInterface.cpp | Penguin-Guru/vircadia | 021268696c73f699364fa93f5d6db03e6b1b8426 | [
"Apache-2.0"
] | 77 | 2020-12-15T06:59:34.000Z | 2022-03-23T22:18:04.000Z | //
// Created by Bradley Austin Davis on 2015/11/18
// Copyright 2013 High Fidelity, Inc.
//
// Distributed under the Apache License, Version 2.0.
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
//
#include "AbstractAudioInterface.h"
#include <Node.h>
#include <NodeType.h>
#include <DependencyManager.h>
#include <NodeList.h>
#include <NLPacket.h>
#include <Transform.h>
#include "AudioConstants.h"
void AbstractAudioInterface::emitAudioPacket(const void* audioData, size_t bytes, quint16& sequenceNumber, bool isStereo,
const Transform& transform, glm::vec3 avatarBoundingBoxCorner, glm::vec3 avatarBoundingBoxScale,
PacketType packetType, QString codecName) {
static std::mutex _mutex;
using Locker = std::unique_lock<std::mutex>;
auto nodeList = DependencyManager::get<NodeList>();
SharedNodePointer audioMixer = nodeList->soloNodeOfType(NodeType::AudioMixer);
if (audioMixer && audioMixer->getActiveSocket()) {
Locker lock(_mutex);
auto audioPacket = NLPacket::create(packetType);
// write sequence number
auto sequence = sequenceNumber++;
audioPacket->writePrimitive(sequence);
// write the codec
audioPacket->writeString(codecName);
if (packetType == PacketType::SilentAudioFrame) {
// pack num silent samples
quint16 numSilentSamples = isStereo ?
AudioConstants::NETWORK_FRAME_SAMPLES_STEREO :
AudioConstants::NETWORK_FRAME_SAMPLES_PER_CHANNEL;
audioPacket->writePrimitive(numSilentSamples);
} else {
// set the mono/stereo byte
quint8 channelFlag = isStereo ? 1 : 0;
audioPacket->writePrimitive(channelFlag);
}
// at this point we'd better be sending the mixer a valid position, or it won't consider us for mixing
assert(!isNaN(transform.getTranslation()));
// pack the three float positions
audioPacket->writePrimitive(transform.getTranslation());
// pack the orientation
audioPacket->writePrimitive(transform.getRotation());
audioPacket->writePrimitive(avatarBoundingBoxCorner);
audioPacket->writePrimitive(avatarBoundingBoxScale);
if (audioPacket->getType() != PacketType::SilentAudioFrame) {
// audio samples have already been packed (written to networkAudioSamples)
int leadingBytes = audioPacket->getPayloadSize();
audioPacket->setPayloadSize(leadingBytes + bytes);
memcpy(audioPacket->getPayload() + leadingBytes, audioData, bytes);
}
nodeList->flagTimeForConnectionStep(LimitedNodeList::ConnectionStep::SendAudioPacket);
nodeList->sendUnreliablePacket(*audioPacket, *audioMixer);
}
}
| 40.263889 | 141 | 0.669541 | Penguin-Guru |
99e711e69ec1d6cbd7d2a2e51b333b14fe8856a3 | 4,679 | cpp | C++ | tests/unit/component/partitioned_vector_view_iterator.cpp | atrantan/hpx | 6c214b2f3e3fc58648513c9f1cfef37fde59333c | [
"BSL-1.0"
] | 1 | 2019-09-26T09:10:13.000Z | 2019-09-26T09:10:13.000Z | tests/unit/component/partitioned_vector_view_iterator.cpp | atrantan/hpx | 6c214b2f3e3fc58648513c9f1cfef37fde59333c | [
"BSL-1.0"
] | null | null | null | tests/unit/component/partitioned_vector_view_iterator.cpp | atrantan/hpx | 6c214b2f3e3fc58648513c9f1cfef37fde59333c | [
"BSL-1.0"
] | null | null | null | // Copyright (c) 2017 Antoine Tran Tan
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <hpx/hpx_main.hpp>
#include <hpx/components/containers/partitioned_vector/partitioned_vector_view.hpp>
#include <hpx/components/containers/partitioned_vector/partitioned_vector_local_view.hpp>
#include <hpx/include/partitioned_vector.hpp>
#include <hpx/lcos/spmd_block.hpp>
#include <hpx/util/lightweight_test.hpp>
#include <cstddef>
#include <string>
#include <type_traits>
#include <utility>
#include <vector>
///////////////////////////////////////////////////////////////////////////////
// Define the vector types to be used.
HPX_REGISTER_PARTITIONED_VECTOR(double);
void bulk_test( hpx::lcos::spmd_block block,
std::size_t size_x,
std::size_t size_y,
std::size_t size_z,
std::size_t elt_size,
std::string vec_name)
{
using const_iterator
= typename std::vector<double>::const_iterator;
using vector_type
= hpx::partitioned_vector<double>;
using view_type
= hpx::partitioned_vector_view<double,3>;
using view_type_iterator
= typename view_type::iterator;
using const_view_type_iterator
= typename view_type::const_iterator;
vector_type my_vector;
my_vector.connect_to(hpx::launch::sync, vec_name);
view_type my_view(block,
my_vector.begin(), my_vector.end(), {size_x,size_y,size_z});
int idx = 0;
// Ensure that only one image is putting data into the different
// partitions
if(block.this_image() == 0)
{
// Traverse all the co-indexed elements
for(auto i = my_view.begin(); i != my_view.end(); i++)
{
// It's a Put operation
*i = std::vector<double>(elt_size,idx++);
}
auto left_it = my_view.begin();
auto right_it = my_view.cbegin();
// Note: Useless computation, since we assign segments to themselves
for(; left_it != my_view.end(); left_it++, right_it++)
{
// Check that dereferencing iterator and const_iterator does not
// retrieve the same type
HPX_TEST((
!std::is_same<decltype(*left_it),decltype(*right_it)>::value));
// It's a Put operation
*left_it = *right_it;
}
}
block.sync_all();
if(block.this_image() == 0)
{
int idx = 0;
for (std::size_t k = 0; k<size_z; k++)
for (std::size_t j = 0; j<size_y; j++)
for (std::size_t i = 0; i<size_x; i++)
{
std::vector<double> result(elt_size,idx);
// It's a Get operation
std::vector<double> value =
(std::vector<double>)my_view(i,j,k);
const_iterator it1 = result.begin(), it2 = value.begin();
const_iterator end1 = result.end();
for (; it1 != end1; ++it1, ++it2)
{
HPX_TEST_EQ(*it1, *it2);
}
idx++;
}
idx = 0;
// Re-check by traversing all the co-indexed elements
for(auto i = my_view.cbegin(); i != my_view.cend(); i++)
{
std::vector<double> result(elt_size,idx);
// It's a Get operation
std::vector<double> value = (std::vector<double>)(*i);
const_iterator it1 = result.begin(), it2 = value.begin();
const_iterator end1 = result.end();
for (; it1 != end1; ++it1, ++it2)
{
HPX_TEST_EQ(*it1, *it2);
}
idx++;
}
}
}
HPX_PLAIN_ACTION(bulk_test, bulk_test_action);
int main()
{
using vector_type
= hpx::partitioned_vector<double>;
const std::size_t size_x = 32;
const std::size_t size_y = 4;
const std::size_t size_z = hpx::get_num_localities(hpx::launch::sync);
const std::size_t elt_size = 4;
const std::size_t num_partitions = size_x*size_y*size_z;
std::size_t raw_size = num_partitions*elt_size;
vector_type my_vector(raw_size,
hpx::container_layout( num_partitions, hpx::find_all_localities() ));
std::string vec_name("my_vector");
my_vector.register_as(hpx::launch::sync, vec_name);
hpx::future<void> join =
hpx::lcos::define_spmd_block("block", 4, bulk_test_action(),
size_x, size_y, size_z, elt_size, vec_name);
join.get();
return 0;
}
| 29.99359 | 89 | 0.569139 | atrantan |
99ecb55fa834903871569bae1e3c8cfcf174ae5e | 334 | hpp | C++ | src/io/register_loader_saver_minimizer.hpp | ruolin/vg | fddf5a0e3172cfc50eb6f8a561dfbe3dbbbaec04 | [
"MIT"
] | 740 | 2016-02-23T02:31:10.000Z | 2022-03-31T20:51:36.000Z | src/io/register_loader_saver_minimizer.hpp | ruolin/vg | fddf5a0e3172cfc50eb6f8a561dfbe3dbbbaec04 | [
"MIT"
] | 2,455 | 2016-02-24T08:17:45.000Z | 2022-03-31T20:19:41.000Z | src/io/register_loader_saver_minimizer.hpp | ruolin/vg | fddf5a0e3172cfc50eb6f8a561dfbe3dbbbaec04 | [
"MIT"
] | 169 | 2016-03-03T15:41:33.000Z | 2022-03-31T04:01:53.000Z | #ifndef VG_IO_REGISTER_LOADER_SAVER_MINIMIZER_HPP_INCLUDED
#define VG_IO_REGISTER_LOADER_SAVER_MINIMIZER_HPP_INCLUDED
/**
* \file register_loader_saver_minimizer.hpp
* Defines IO for minimizer index from stream files.
*/
namespace vg {
namespace io {
using namespace std;
void register_loader_saver_minimizer();
}
}
#endif
| 15.181818 | 58 | 0.808383 | ruolin |
99edc13cf3a5a2203389b7a580eba7858dfe42d0 | 919 | hpp | C++ | engine/audio/Effect.hpp | taida957789/ouzel | a8c1cc74e6151a0f7d7d2c534f8747cba46a36af | [
"Unlicense"
] | 1 | 2021-03-01T13:17:49.000Z | 2021-03-01T13:17:49.000Z | engine/audio/Effect.hpp | taida957789/ouzel | a8c1cc74e6151a0f7d7d2c534f8747cba46a36af | [
"Unlicense"
] | null | null | null | engine/audio/Effect.hpp | taida957789/ouzel | a8c1cc74e6151a0f7d7d2c534f8747cba46a36af | [
"Unlicense"
] | null | null | null | // Copyright 2015-2020 Elviss Strazdins. All rights reserved.
#ifndef OUZEL_AUDIO_EFFECT_HPP
#define OUZEL_AUDIO_EFFECT_HPP
#include <cstdint>
#include "Node.hpp"
namespace ouzel::audio
{
class Audio;
class Mix;
class Effect: public Node
{
friend Mix;
public:
Effect(Audio& initAudio,
std::size_t initProcessorId);
~Effect() override;
Effect(const Effect&) = delete;
Effect& operator=(const Effect&) = delete;
Effect(Effect&&) = delete;
Effect& operator=(Effect&&) = delete;
auto getProcessorId() const noexcept { return processorId; }
auto isEnabled() const noexcept { return enabled; }
void setEnabled(bool newEnabled);
protected:
Audio& audio;
std::size_t processorId = 0;
Mix* mix = nullptr;
bool enabled = true;
};
}
#endif // OUZEL_AUDIO_EFFECT_HPP
| 22.414634 | 68 | 0.622416 | taida957789 |
99efa085a3ecd9456625c8ce3414651cf1eedd88 | 1,528 | cpp | C++ | app/src/common/faboolApi.cpp | smartDIYs/FABOOLDesktop_opensource | 082fc12eacffed2b64f868064ed3809d06db831b | [
"MIT"
] | 6 | 2019-02-17T02:17:45.000Z | 2021-07-16T01:53:41.000Z | app/src/common/faboolApi.cpp | smartDIYs/FABOOLDesktop_opensource | 082fc12eacffed2b64f868064ed3809d06db831b | [
"MIT"
] | null | null | null | app/src/common/faboolApi.cpp | smartDIYs/FABOOLDesktop_opensource | 082fc12eacffed2b64f868064ed3809d06db831b | [
"MIT"
] | 5 | 2018-08-28T07:29:08.000Z | 2020-07-04T13:45:58.000Z | #include "faboolApi.h"
// FaboolAPIResponse
FaboolAPIResponse::FaboolAPIResponse(QNetworkReply *reply, QObject *parent) : QObject(parent)
{
QString responseString = (QString)reply->readAll();
qDebug() << responseString;
if(responseString != ""){
mHasReply = true;
mData = QJsonObject(QJsonDocument::fromJson(responseString.toUtf8()).object());
} else {
mHasReply = false;
}
}
// FaboolAPI
FaboolAPI::FaboolAPI(QObject *parent) : QObject(parent)
{
}
QUrl FaboolAPI::getApiUrl(int version)
{
if(version != 1) {
return QUrl();
}
return QUrl("https://api.smartdiys.com/fabool/v1/");
}
FaboolAPIResponse* FaboolAPI::sendRequest(QUrlQuery query)
{
QNetworkAccessManager *manager = new QNetworkAccessManager();
QUrl url = FaboolAPI::getApiUrl(1);
QNetworkRequest request(url);
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
QEventLoop eventLoop;
connect(manager, SIGNAL(finished(QNetworkReply*)),
&eventLoop, SLOT(quit()));
QNetworkReply *reply = manager->post(request, query.toString(QUrl::FullyEncoded).toUtf8());
eventLoop.exec();
FaboolAPIResponse* response = new FaboolAPIResponse(reply);
return response;
}
FaboolAPIResponse* FaboolAPI::getLatestFaboolDesktopVersionInfo(){
QUrlQuery query;
query.addQueryItem("request", "getLatestFaboolVersionInfo");
query.addQueryItem("appname", "fabooldesktop");
return FaboolAPI::sendRequest(query);
}
| 26.807018 | 95 | 0.701571 | smartDIYs |
99f0fb7f5578ff25a8f132942bdd05bb0fa29fdb | 44,737 | cpp | C++ | SDK/ARKSurvivalEvolved_Purlovia_Character_BP_functions.cpp | 2bite/ARK-SDK | c38ca9925309516b2093ad8c3a70ed9489e1d573 | [
"MIT"
] | 10 | 2020-02-17T19:08:46.000Z | 2021-07-31T11:07:19.000Z | SDK/ARKSurvivalEvolved_Purlovia_Character_BP_functions.cpp | 2bite/ARK-SDK | c38ca9925309516b2093ad8c3a70ed9489e1d573 | [
"MIT"
] | 9 | 2020-02-17T18:15:41.000Z | 2021-06-06T19:17:34.000Z | SDK/ARKSurvivalEvolved_Purlovia_Character_BP_functions.cpp | 2bite/ARK-SDK | c38ca9925309516b2093ad8c3a70ed9489e1d573 | [
"MIT"
] | 3 | 2020-07-22T17:42:07.000Z | 2021-06-19T17:16:13.000Z | // ARKSurvivalEvolved (329.9) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "ARKSurvivalEvolved_Purlovia_Character_BP_parameters.hpp"
namespace sdk
{
//---------------------------------------------------------------------------
//Functions
//---------------------------------------------------------------------------
// Function Purlovia_Character_BP.Purlovia_Character_BP_C.HasSelfBuried
// ()
// Parameters:
// bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData)
bool APurlovia_Character_BP_C::HasSelfBuried()
{
static auto fn = UObject::FindObject<UFunction>("Function Purlovia_Character_BP.Purlovia_Character_BP_C.HasSelfBuried");
APurlovia_Character_BP_C_HasSelfBuried_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function Purlovia_Character_BP.Purlovia_Character_BP_C.BPIsHidden
// ()
// Parameters:
// bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData)
bool APurlovia_Character_BP_C::BPIsHidden()
{
static auto fn = UObject::FindObject<UFunction>("Function Purlovia_Character_BP.Purlovia_Character_BP_C.BPIsHidden");
APurlovia_Character_BP_C_BPIsHidden_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function Purlovia_Character_BP.Purlovia_Character_BP_C.UpdateCollisions
// ()
// Parameters:
// bool buried (Parm, ZeroConstructor, IsPlainOldData)
void APurlovia_Character_BP_C::UpdateCollisions(bool buried)
{
static auto fn = UObject::FindObject<UFunction>("Function Purlovia_Character_BP.Purlovia_Character_BP_C.UpdateCollisions");
APurlovia_Character_BP_C_UpdateCollisions_Params params;
params.buried = buried;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function Purlovia_Character_BP.Purlovia_Character_BP_C.CanUnburyNormal
// ()
// Parameters:
// bool Can (Parm, OutParm, ZeroConstructor, IsPlainOldData)
void APurlovia_Character_BP_C::CanUnburyNormal(bool* Can)
{
static auto fn = UObject::FindObject<UFunction>("Function Purlovia_Character_BP.Purlovia_Character_BP_C.CanUnburyNormal");
APurlovia_Character_BP_C_CanUnburyNormal_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
if (Can != nullptr)
*Can = params.Can;
}
// Function Purlovia_Character_BP.Purlovia_Character_BP_C.Show Mound Out Particles
// ()
void APurlovia_Character_BP_C::Show_Mound_Out_Particles()
{
static auto fn = UObject::FindObject<UFunction>("Function Purlovia_Character_BP.Purlovia_Character_BP_C.Show Mound Out Particles");
APurlovia_Character_BP_C_Show_Mound_Out_Particles_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function Purlovia_Character_BP.Purlovia_Character_BP_C.BPTimerNonDedicated
// ()
void APurlovia_Character_BP_C::BPTimerNonDedicated()
{
static auto fn = UObject::FindObject<UFunction>("Function Purlovia_Character_BP.Purlovia_Character_BP_C.BPTimerNonDedicated");
APurlovia_Character_BP_C_BPTimerNonDedicated_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function Purlovia_Character_BP.Purlovia_Character_BP_C.Update Bury Mesh Transform Variable
// (NetReliable, NetMulticast, MulticastDelegate, Private, NetServer, HasDefaults, DLLImport, BlueprintCallable, Const)
// Parameters:
// bool updateMeshLocation (Parm, ZeroConstructor, IsPlainOldData)
void APurlovia_Character_BP_C::Update_Bury_Mesh_Transform_Variable(bool updateMeshLocation)
{
static auto fn = UObject::FindObject<UFunction>("Function Purlovia_Character_BP.Purlovia_Character_BP_C.Update Bury Mesh Transform Variable");
APurlovia_Character_BP_C_Update_Bury_Mesh_Transform_Variable_Params params;
params.updateMeshLocation = updateMeshLocation;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function Purlovia_Character_BP.Purlovia_Character_BP_C.Show Mound In Particles
// ()
void APurlovia_Character_BP_C::Show_Mound_In_Particles()
{
static auto fn = UObject::FindObject<UFunction>("Function Purlovia_Character_BP.Purlovia_Character_BP_C.Show Mound In Particles");
APurlovia_Character_BP_C_Show_Mound_In_Particles_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function Purlovia_Character_BP.Purlovia_Character_BP_C.Show Bury MoundIfNeeded
// ()
void APurlovia_Character_BP_C::Show_Bury_MoundIfNeeded()
{
static auto fn = UObject::FindObject<UFunction>("Function Purlovia_Character_BP.Purlovia_Character_BP_C.Show Bury MoundIfNeeded");
APurlovia_Character_BP_C_Show_Bury_MoundIfNeeded_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function Purlovia_Character_BP.Purlovia_Character_BP_C.Hide Bury Mound
// ()
void APurlovia_Character_BP_C::Hide_Bury_Mound()
{
static auto fn = UObject::FindObject<UFunction>("Function Purlovia_Character_BP.Purlovia_Character_BP_C.Hide Bury Mound");
APurlovia_Character_BP_C_Hide_Bury_Mound_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function Purlovia_Character_BP.Purlovia_Character_BP_C.RotateToTarget
// (NetRequest, Exec, Event, NetMulticast, MulticastDelegate, Private, NetServer, HasDefaults, DLLImport, BlueprintCallable, Const)
void APurlovia_Character_BP_C::RotateToTarget()
{
static auto fn = UObject::FindObject<UFunction>("Function Purlovia_Character_BP.Purlovia_Character_BP_C.RotateToTarget");
APurlovia_Character_BP_C_RotateToTarget_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function Purlovia_Character_BP.Purlovia_Character_BP_C.IsValidTarget
// ()
// Parameters:
// bool DoWeightCheck (Parm, ZeroConstructor, IsPlainOldData)
// class AActor* Target (Parm, ZeroConstructor, IsPlainOldData)
// bool Valid (Parm, OutParm, ZeroConstructor, IsPlainOldData)
void APurlovia_Character_BP_C::IsValidTarget(bool DoWeightCheck, class AActor* Target, bool* Valid)
{
static auto fn = UObject::FindObject<UFunction>("Function Purlovia_Character_BP.Purlovia_Character_BP_C.IsValidTarget");
APurlovia_Character_BP_C_IsValidTarget_Params params;
params.DoWeightCheck = DoWeightCheck;
params.Target = Target;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
if (Valid != nullptr)
*Valid = params.Valid;
}
// Function Purlovia_Character_BP.Purlovia_Character_BP_C.BlueprintAdjustOutputDamage
// (NetReliable, NetRequest, Exec, Native, NetResponse, NetMulticast, MulticastDelegate, Private, NetServer, HasDefaults, DLLImport, BlueprintCallable, Const)
// Parameters:
// int* AttackIndex (Parm, ZeroConstructor, IsPlainOldData)
// float* OriginalDamageAmount (Parm, ZeroConstructor, IsPlainOldData)
// class AActor** HitActor (Parm, ZeroConstructor, IsPlainOldData)
// class UClass* OutDamageType (Parm, OutParm, ZeroConstructor, IsPlainOldData)
// float OutDamageImpulse (Parm, OutParm, ZeroConstructor, IsPlainOldData)
// float ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData)
float APurlovia_Character_BP_C::BlueprintAdjustOutputDamage(int* AttackIndex, float* OriginalDamageAmount, class AActor** HitActor, class UClass** OutDamageType, float* OutDamageImpulse)
{
static auto fn = UObject::FindObject<UFunction>("Function Purlovia_Character_BP.Purlovia_Character_BP_C.BlueprintAdjustOutputDamage");
APurlovia_Character_BP_C_BlueprintAdjustOutputDamage_Params params;
params.AttackIndex = AttackIndex;
params.OriginalDamageAmount = OriginalDamageAmount;
params.HitActor = HitActor;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
if (OutDamageType != nullptr)
*OutDamageType = params.OutDamageType;
if (OutDamageImpulse != nullptr)
*OutDamageImpulse = params.OutDamageImpulse;
return params.ReturnValue;
}
// Function Purlovia_Character_BP.Purlovia_Character_BP_C.IsBuryAttack
// ()
// Parameters:
// int AttackIndex (Parm, ZeroConstructor, IsPlainOldData)
// bool IsBuryAttack (Parm, OutParm, ZeroConstructor, IsPlainOldData)
void APurlovia_Character_BP_C::IsBuryAttack(int AttackIndex, bool* IsBuryAttack)
{
static auto fn = UObject::FindObject<UFunction>("Function Purlovia_Character_BP.Purlovia_Character_BP_C.IsBuryAttack");
APurlovia_Character_BP_C_IsBuryAttack_Params params;
params.AttackIndex = AttackIndex;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
if (IsBuryAttack != nullptr)
*IsBuryAttack = params.IsBuryAttack;
}
// Function Purlovia_Character_BP.Purlovia_Character_BP_C.BPDoAttack
// ()
// Parameters:
// int* AttackIndex (Parm, ZeroConstructor, IsPlainOldData)
void APurlovia_Character_BP_C::BPDoAttack(int* AttackIndex)
{
static auto fn = UObject::FindObject<UFunction>("Function Purlovia_Character_BP.Purlovia_Character_BP_C.BPDoAttack");
APurlovia_Character_BP_C_BPDoAttack_Params params;
params.AttackIndex = AttackIndex;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function Purlovia_Character_BP.Purlovia_Character_BP_C.TryBury
// ()
// Parameters:
// bool PlayAnim (Parm, ZeroConstructor, IsPlainOldData)
// bool skipBuriedCheck (Parm, ZeroConstructor, IsPlainOldData)
// bool couldBury (Parm, OutParm, ZeroConstructor, IsPlainOldData)
void APurlovia_Character_BP_C::TryBury(bool PlayAnim, bool skipBuriedCheck, bool* couldBury)
{
static auto fn = UObject::FindObject<UFunction>("Function Purlovia_Character_BP.Purlovia_Character_BP_C.TryBury");
APurlovia_Character_BP_C_TryBury_Params params;
params.PlayAnim = PlayAnim;
params.skipBuriedCheck = skipBuriedCheck;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
if (couldBury != nullptr)
*couldBury = params.couldBury;
}
// Function Purlovia_Character_BP.Purlovia_Character_BP_C.Should Show Bury Mound
// ()
// Parameters:
// bool shouldShowMesh (Parm, OutParm, ZeroConstructor, IsPlainOldData)
void APurlovia_Character_BP_C::Should_Show_Bury_Mound(bool* shouldShowMesh)
{
static auto fn = UObject::FindObject<UFunction>("Function Purlovia_Character_BP.Purlovia_Character_BP_C.Should Show Bury Mound");
APurlovia_Character_BP_C_Should_Show_Bury_Mound_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
if (shouldShowMesh != nullptr)
*shouldShowMesh = params.shouldShowMesh;
}
// Function Purlovia_Character_BP.Purlovia_Character_BP_C.BPAdjustDamage
// ()
// Parameters:
// float* IncomingDamage (Parm, ZeroConstructor, IsPlainOldData)
// struct FDamageEvent* TheDamageEvent (Parm)
// class AController** EventInstigator (Parm, ZeroConstructor, IsPlainOldData)
// class AActor** DamageCauser (Parm, ZeroConstructor, IsPlainOldData)
// bool* bIsPointDamage (Parm, ZeroConstructor, IsPlainOldData)
// struct FHitResult* PointHitInfo (Parm)
// float ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData)
float APurlovia_Character_BP_C::BPAdjustDamage(float* IncomingDamage, struct FDamageEvent* TheDamageEvent, class AController** EventInstigator, class AActor** DamageCauser, bool* bIsPointDamage, struct FHitResult* PointHitInfo)
{
static auto fn = UObject::FindObject<UFunction>("Function Purlovia_Character_BP.Purlovia_Character_BP_C.BPAdjustDamage");
APurlovia_Character_BP_C_BPAdjustDamage_Params params;
params.IncomingDamage = IncomingDamage;
params.TheDamageEvent = TheDamageEvent;
params.EventInstigator = EventInstigator;
params.DamageCauser = DamageCauser;
params.bIsPointDamage = bIsPointDamage;
params.PointHitInfo = PointHitInfo;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function Purlovia_Character_BP.Purlovia_Character_BP_C.IsValidSurface
// (NetReliable, Exec, Native, Event, Static, NetMulticast, MulticastDelegate, Private, NetServer, HasDefaults, DLLImport, BlueprintCallable, Const)
// Parameters:
// bool IsValid (Parm, OutParm, ZeroConstructor, IsPlainOldData)
void APurlovia_Character_BP_C::STATIC_IsValidSurface(bool* IsValid)
{
static auto fn = UObject::FindObject<UFunction>("Function Purlovia_Character_BP.Purlovia_Character_BP_C.IsValidSurface");
APurlovia_Character_BP_C_IsValidSurface_Params params;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
if (IsValid != nullptr)
*IsValid = params.IsValid;
}
// Function Purlovia_Character_BP.Purlovia_Character_BP_C.BPCharacterSleeped
// ()
void APurlovia_Character_BP_C::BPCharacterSleeped()
{
static auto fn = UObject::FindObject<UFunction>("Function Purlovia_Character_BP.Purlovia_Character_BP_C.BPCharacterSleeped");
APurlovia_Character_BP_C_BPCharacterSleeped_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function Purlovia_Character_BP.Purlovia_Character_BP_C.BPOnAnimPlayedNotify
// ()
// Parameters:
// class UAnimMontage** AnimMontage (Parm, ZeroConstructor, IsPlainOldData)
// float* InPlayRate (Parm, ZeroConstructor, IsPlainOldData)
// struct FName* StartSectionName (Parm, ZeroConstructor, IsPlainOldData)
// bool* bReplicate (Parm, ZeroConstructor, IsPlainOldData)
// bool* bReplicateToOwner (Parm, ZeroConstructor, IsPlainOldData)
// bool* bForceTickPoseAndServerUpdateMesh (Parm, ZeroConstructor, IsPlainOldData)
// bool* bForceTickPoseOnServer (Parm, ZeroConstructor, IsPlainOldData)
void APurlovia_Character_BP_C::BPOnAnimPlayedNotify(class UAnimMontage** AnimMontage, float* InPlayRate, struct FName* StartSectionName, bool* bReplicate, bool* bReplicateToOwner, bool* bForceTickPoseAndServerUpdateMesh, bool* bForceTickPoseOnServer)
{
static auto fn = UObject::FindObject<UFunction>("Function Purlovia_Character_BP.Purlovia_Character_BP_C.BPOnAnimPlayedNotify");
APurlovia_Character_BP_C_BPOnAnimPlayedNotify_Params params;
params.AnimMontage = AnimMontage;
params.InPlayRate = InPlayRate;
params.StartSectionName = StartSectionName;
params.bReplicate = bReplicate;
params.bReplicateToOwner = bReplicateToOwner;
params.bForceTickPoseAndServerUpdateMesh = bForceTickPoseAndServerUpdateMesh;
params.bForceTickPoseOnServer = bForceTickPoseOnServer;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function Purlovia_Character_BP.Purlovia_Character_BP_C.FinishBuriedJump
// ()
void APurlovia_Character_BP_C::FinishBuriedJump()
{
static auto fn = UObject::FindObject<UFunction>("Function Purlovia_Character_BP.Purlovia_Character_BP_C.FinishBuriedJump");
APurlovia_Character_BP_C_FinishBuriedJump_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function Purlovia_Character_BP.Purlovia_Character_BP_C.CalculateBuryMeshTransform
// (NetRequest, Native, MulticastDelegate, Private, NetServer, HasDefaults, DLLImport, BlueprintCallable, Const)
// Parameters:
// struct UObject_FTransform Transform (Parm, OutParm, IsPlainOldData)
void APurlovia_Character_BP_C::CalculateBuryMeshTransform(struct UObject_FTransform* Transform)
{
static auto fn = UObject::FindObject<UFunction>("Function Purlovia_Character_BP.Purlovia_Character_BP_C.CalculateBuryMeshTransform");
APurlovia_Character_BP_C_CalculateBuryMeshTransform_Params params;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
if (Transform != nullptr)
*Transform = params.Transform;
}
// Function Purlovia_Character_BP.Purlovia_Character_BP_C.BlueprintDrawFloatingHUD
// ()
// Parameters:
// class AShooterHUD** HUD (Parm, ZeroConstructor, IsPlainOldData)
// float* CenterX (Parm, ZeroConstructor, IsPlainOldData)
// float* CenterY (Parm, ZeroConstructor, IsPlainOldData)
// float* DrawScale (Parm, ZeroConstructor, IsPlainOldData)
void APurlovia_Character_BP_C::BlueprintDrawFloatingHUD(class AShooterHUD** HUD, float* CenterX, float* CenterY, float* DrawScale)
{
static auto fn = UObject::FindObject<UFunction>("Function Purlovia_Character_BP.Purlovia_Character_BP_C.BlueprintDrawFloatingHUD");
APurlovia_Character_BP_C_BlueprintDrawFloatingHUD_Params params;
params.HUD = HUD;
params.CenterX = CenterX;
params.CenterY = CenterY;
params.DrawScale = DrawScale;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function Purlovia_Character_BP.Purlovia_Character_BP_C.Get Buried Attack Up Impulse
// (NetReliable, NetRequest, Exec, Native, NetResponse, MulticastDelegate, Private, NetServer, HasDefaults, DLLImport, BlueprintCallable, Const)
// Parameters:
// struct FVector UpImpulse (Parm, OutParm, ZeroConstructor, IsPlainOldData)
void APurlovia_Character_BP_C::Get_Buried_Attack_Up_Impulse(struct FVector* UpImpulse)
{
static auto fn = UObject::FindObject<UFunction>("Function Purlovia_Character_BP.Purlovia_Character_BP_C.Get Buried Attack Up Impulse");
APurlovia_Character_BP_C_Get_Buried_Attack_Up_Impulse_Params params;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
if (UpImpulse != nullptr)
*UpImpulse = params.UpImpulse;
}
// Function Purlovia_Character_BP.Purlovia_Character_BP_C.Get Buried Attack Down Impulse
// (NetReliable, NetRequest, Static, MulticastDelegate, Private, NetServer, HasDefaults, DLLImport, BlueprintCallable, Const)
// Parameters:
// struct FVector Impulse (Parm, OutParm, ZeroConstructor, IsPlainOldData)
void APurlovia_Character_BP_C::STATIC_Get_Buried_Attack_Down_Impulse(struct FVector* Impulse)
{
static auto fn = UObject::FindObject<UFunction>("Function Purlovia_Character_BP.Purlovia_Character_BP_C.Get Buried Attack Down Impulse");
APurlovia_Character_BP_C_Get_Buried_Attack_Down_Impulse_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
if (Impulse != nullptr)
*Impulse = params.Impulse;
}
// Function Purlovia_Character_BP.Purlovia_Character_BP_C.OnRep_isBuried
// ()
void APurlovia_Character_BP_C::OnRep_isBuried()
{
static auto fn = UObject::FindObject<UFunction>("Function Purlovia_Character_BP.Purlovia_Character_BP_C.OnRep_isBuried");
APurlovia_Character_BP_C_OnRep_isBuried_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function Purlovia_Character_BP.Purlovia_Character_BP_C.IsDinoInWater
// ()
// Parameters:
// bool onWater (Parm, OutParm, ZeroConstructor, IsPlainOldData)
void APurlovia_Character_BP_C::IsDinoInWater(bool* onWater)
{
static auto fn = UObject::FindObject<UFunction>("Function Purlovia_Character_BP.Purlovia_Character_BP_C.IsDinoInWater");
APurlovia_Character_BP_C_IsDinoInWater_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
if (onWater != nullptr)
*onWater = params.onWater;
}
// Function Purlovia_Character_BP.Purlovia_Character_BP_C.FinishNormalJump
// ()
void APurlovia_Character_BP_C::FinishNormalJump()
{
static auto fn = UObject::FindObject<UFunction>("Function Purlovia_Character_BP.Purlovia_Character_BP_C.FinishNormalJump");
APurlovia_Character_BP_C_FinishNormalJump_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function Purlovia_Character_BP.Purlovia_Character_BP_C.ApplyNormalJumpImpulse
// (Exec, Native, NetResponse, Static, MulticastDelegate, Private, NetServer, HasDefaults, DLLImport, BlueprintCallable, Const)
void APurlovia_Character_BP_C::STATIC_ApplyNormalJumpImpulse()
{
static auto fn = UObject::FindObject<UFunction>("Function Purlovia_Character_BP.Purlovia_Character_BP_C.ApplyNormalJumpImpulse");
APurlovia_Character_BP_C_ApplyNormalJumpImpulse_Params params;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function Purlovia_Character_BP.Purlovia_Character_BP_C.OnJumped
// ()
void APurlovia_Character_BP_C::OnJumped()
{
static auto fn = UObject::FindObject<UFunction>("Function Purlovia_Character_BP.Purlovia_Character_BP_C.OnJumped");
APurlovia_Character_BP_C_OnJumped_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function Purlovia_Character_BP.Purlovia_Character_BP_C.BlueprintCanAttack
// ()
// Parameters:
// int* AttackIndex (Parm, ZeroConstructor, IsPlainOldData)
// float* Distance (Parm, ZeroConstructor, IsPlainOldData)
// float* attackRangeOffset (Parm, ZeroConstructor, IsPlainOldData)
// class AActor** OtherTarget (Parm, ZeroConstructor, IsPlainOldData)
// bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData)
bool APurlovia_Character_BP_C::BlueprintCanAttack(int* AttackIndex, float* Distance, float* attackRangeOffset, class AActor** OtherTarget)
{
static auto fn = UObject::FindObject<UFunction>("Function Purlovia_Character_BP.Purlovia_Character_BP_C.BlueprintCanAttack");
APurlovia_Character_BP_C_BlueprintCanAttack_Params params;
params.AttackIndex = AttackIndex;
params.Distance = Distance;
params.attackRangeOffset = attackRangeOffset;
params.OtherTarget = OtherTarget;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function Purlovia_Character_BP.Purlovia_Character_BP_C.BPOnMovementModeChangedNotify
// ()
// Parameters:
// TEnumAsByte<EMovementMode>* PrevMovementMode (Parm, ZeroConstructor, IsPlainOldData)
// unsigned char* PreviousCustomMode (Parm, ZeroConstructor, IsPlainOldData)
void APurlovia_Character_BP_C::BPOnMovementModeChangedNotify(TEnumAsByte<EMovementMode>* PrevMovementMode, unsigned char* PreviousCustomMode)
{
static auto fn = UObject::FindObject<UFunction>("Function Purlovia_Character_BP.Purlovia_Character_BP_C.BPOnMovementModeChangedNotify");
APurlovia_Character_BP_C_BPOnMovementModeChangedNotify_Params params;
params.PrevMovementMode = PrevMovementMode;
params.PreviousCustomMode = PreviousCustomMode;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function Purlovia_Character_BP.Purlovia_Character_BP_C.BPNotifyBumpedPawn
// ()
// Parameters:
// class APrimalCharacter** BumpedPawn (Parm, ZeroConstructor, IsPlainOldData)
void APurlovia_Character_BP_C::BPNotifyBumpedPawn(class APrimalCharacter** BumpedPawn)
{
static auto fn = UObject::FindObject<UFunction>("Function Purlovia_Character_BP.Purlovia_Character_BP_C.BPNotifyBumpedPawn");
APurlovia_Character_BP_C_BPNotifyBumpedPawn_Params params;
params.BumpedPawn = BumpedPawn;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function Purlovia_Character_BP.Purlovia_Character_BP_C.Can Unbury
// ()
// Parameters:
// bool canComeOut (Parm, OutParm, ZeroConstructor, IsPlainOldData)
void APurlovia_Character_BP_C::Can_Unbury(bool* canComeOut)
{
static auto fn = UObject::FindObject<UFunction>("Function Purlovia_Character_BP.Purlovia_Character_BP_C.Can Unbury");
APurlovia_Character_BP_C_Can_Unbury_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
if (canComeOut != nullptr)
*canComeOut = params.canComeOut;
}
// Function Purlovia_Character_BP.Purlovia_Character_BP_C.ShouldComeOut
// ()
// Parameters:
// bool comeOut (Parm, OutParm, ZeroConstructor, IsPlainOldData)
void APurlovia_Character_BP_C::ShouldComeOut(bool* comeOut)
{
static auto fn = UObject::FindObject<UFunction>("Function Purlovia_Character_BP.Purlovia_Character_BP_C.ShouldComeOut");
APurlovia_Character_BP_C_ShouldComeOut_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
if (comeOut != nullptr)
*comeOut = params.comeOut;
}
// Function Purlovia_Character_BP.Purlovia_Character_BP_C.Has Conflict with AI
// ()
// Parameters:
// bool hasConflict (Parm, OutParm, ZeroConstructor, IsPlainOldData)
void APurlovia_Character_BP_C::Has_Conflict_with_AI(bool* hasConflict)
{
static auto fn = UObject::FindObject<UFunction>("Function Purlovia_Character_BP.Purlovia_Character_BP_C.Has Conflict with AI");
APurlovia_Character_BP_C_Has_Conflict_with_AI_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
if (hasConflict != nullptr)
*hasConflict = params.hasConflict;
}
// Function Purlovia_Character_BP.Purlovia_Character_BP_C.canBury
// (NetRequest, Native, Event, NetResponse, NetMulticast, MulticastDelegate, Private, NetServer, HasDefaults, DLLImport, BlueprintCallable, Const)
// Parameters:
// bool forceBury (Parm, ZeroConstructor, IsPlainOldData)
// bool canBury (Parm, OutParm, ZeroConstructor, IsPlainOldData)
void APurlovia_Character_BP_C::canBury(bool forceBury, bool* canBury)
{
static auto fn = UObject::FindObject<UFunction>("Function Purlovia_Character_BP.Purlovia_Character_BP_C.canBury");
APurlovia_Character_BP_C_canBury_Params params;
params.forceBury = forceBury;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
if (canBury != nullptr)
*canBury = params.canBury;
}
// Function Purlovia_Character_BP.Purlovia_Character_BP_C.CanPlayBuryAnim
// ()
// Parameters:
// bool canPlayBury (Parm, OutParm, ZeroConstructor, IsPlainOldData)
void APurlovia_Character_BP_C::CanPlayBuryAnim(bool* canPlayBury)
{
static auto fn = UObject::FindObject<UFunction>("Function Purlovia_Character_BP.Purlovia_Character_BP_C.CanPlayBuryAnim");
APurlovia_Character_BP_C_CanPlayBuryAnim_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
if (canPlayBury != nullptr)
*canPlayBury = params.canPlayBury;
}
// Function Purlovia_Character_BP.Purlovia_Character_BP_C.CanJumpAtTarget
// ()
// Parameters:
// bool FoundTarget (Parm, OutParm, ZeroConstructor, IsPlainOldData)
void APurlovia_Character_BP_C::CanJumpAtTarget(bool* FoundTarget)
{
static auto fn = UObject::FindObject<UFunction>("Function Purlovia_Character_BP.Purlovia_Character_BP_C.CanJumpAtTarget");
APurlovia_Character_BP_C_CanJumpAtTarget_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
if (FoundTarget != nullptr)
*FoundTarget = params.FoundTarget;
}
// Function Purlovia_Character_BP.Purlovia_Character_BP_C.BPTimerServer
// ()
void APurlovia_Character_BP_C::BPTimerServer()
{
static auto fn = UObject::FindObject<UFunction>("Function Purlovia_Character_BP.Purlovia_Character_BP_C.BPTimerServer");
APurlovia_Character_BP_C_BPTimerServer_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function Purlovia_Character_BP.Purlovia_Character_BP_C.BPGetMultiUseEntries
// (NetRequest, Native, NetResponse, Static, NetMulticast, MulticastDelegate, Private, NetServer, HasDefaults, DLLImport, BlueprintCallable, Const)
// Parameters:
// class APlayerController** ForPC (Parm, ZeroConstructor, IsPlainOldData)
// TArray<struct FMultiUseEntry> MultiUseEntries (Parm, OutParm, ZeroConstructor, ReferenceParm)
// TArray<struct FMultiUseEntry> ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm)
TArray<struct FMultiUseEntry> APurlovia_Character_BP_C::STATIC_BPGetMultiUseEntries(class APlayerController** ForPC, TArray<struct FMultiUseEntry>* MultiUseEntries)
{
static auto fn = UObject::FindObject<UFunction>("Function Purlovia_Character_BP.Purlovia_Character_BP_C.BPGetMultiUseEntries");
APurlovia_Character_BP_C_BPGetMultiUseEntries_Params params;
params.ForPC = ForPC;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
if (MultiUseEntries != nullptr)
*MultiUseEntries = params.MultiUseEntries;
return params.ReturnValue;
}
// Function Purlovia_Character_BP.Purlovia_Character_BP_C.BPTryMultiUse
// ()
// Parameters:
// class APlayerController** ForPC (Parm, ZeroConstructor, IsPlainOldData)
// int* UseIndex (Parm, ZeroConstructor, IsPlainOldData)
// bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData)
bool APurlovia_Character_BP_C::BPTryMultiUse(class APlayerController** ForPC, int* UseIndex)
{
static auto fn = UObject::FindObject<UFunction>("Function Purlovia_Character_BP.Purlovia_Character_BP_C.BPTryMultiUse");
APurlovia_Character_BP_C_BPTryMultiUse_Params params;
params.ForPC = ForPC;
params.UseIndex = UseIndex;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function Purlovia_Character_BP.Purlovia_Character_BP_C.UserConstructionScript
// ()
void APurlovia_Character_BP_C::UserConstructionScript()
{
static auto fn = UObject::FindObject<UFunction>("Function Purlovia_Character_BP.Purlovia_Character_BP_C.UserConstructionScript");
APurlovia_Character_BP_C_UserConstructionScript_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function Purlovia_Character_BP.Purlovia_Character_BP_C.Bury
// ()
// Parameters:
// bool PlayAnim (Parm, ZeroConstructor, IsPlainOldData)
void APurlovia_Character_BP_C::Bury(bool PlayAnim)
{
static auto fn = UObject::FindObject<UFunction>("Function Purlovia_Character_BP.Purlovia_Character_BP_C.Bury");
APurlovia_Character_BP_C_Bury_Params params;
params.PlayAnim = PlayAnim;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function Purlovia_Character_BP.Purlovia_Character_BP_C.ComeOut_Attack
// ()
// Parameters:
// int Range (Parm, ZeroConstructor, IsPlainOldData)
void APurlovia_Character_BP_C::ComeOut_Attack(int Range)
{
static auto fn = UObject::FindObject<UFunction>("Function Purlovia_Character_BP.Purlovia_Character_BP_C.ComeOut_Attack");
APurlovia_Character_BP_C_ComeOut_Attack_Params params;
params.Range = Range;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function Purlovia_Character_BP.Purlovia_Character_BP_C.ComeOut_Normal
// ()
// Parameters:
// bool PlayAnim (Parm, ZeroConstructor, IsPlainOldData)
void APurlovia_Character_BP_C::ComeOut_Normal(bool PlayAnim)
{
static auto fn = UObject::FindObject<UFunction>("Function Purlovia_Character_BP.Purlovia_Character_BP_C.ComeOut_Normal");
APurlovia_Character_BP_C_ComeOut_Normal_Params params;
params.PlayAnim = PlayAnim;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function Purlovia_Character_BP.Purlovia_Character_BP_C.TryComeOutAttack
// ()
// Parameters:
// int Range (Parm, ZeroConstructor, IsPlainOldData)
void APurlovia_Character_BP_C::TryComeOutAttack(int Range)
{
static auto fn = UObject::FindObject<UFunction>("Function Purlovia_Character_BP.Purlovia_Character_BP_C.TryComeOutAttack");
APurlovia_Character_BP_C_TryComeOutAttack_Params params;
params.Range = Range;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function Purlovia_Character_BP.Purlovia_Character_BP_C.OnComeOut
// ()
void APurlovia_Character_BP_C::OnComeOut()
{
static auto fn = UObject::FindObject<UFunction>("Function Purlovia_Character_BP.Purlovia_Character_BP_C.OnComeOut");
APurlovia_Character_BP_C_OnComeOut_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function Purlovia_Character_BP.Purlovia_Character_BP_C.OnNormalJump
// ()
void APurlovia_Character_BP_C::OnNormalJump()
{
static auto fn = UObject::FindObject<UFunction>("Function Purlovia_Character_BP.Purlovia_Character_BP_C.OnNormalJump");
APurlovia_Character_BP_C_OnNormalJump_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function Purlovia_Character_BP.Purlovia_Character_BP_C.BPUnstasis
// ()
void APurlovia_Character_BP_C::BPUnstasis()
{
static auto fn = UObject::FindObject<UFunction>("Function Purlovia_Character_BP.Purlovia_Character_BP_C.BPUnstasis");
APurlovia_Character_BP_C_BPUnstasis_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function Purlovia_Character_BP.Purlovia_Character_BP_C.OnMovementChanged
// ()
void APurlovia_Character_BP_C::OnMovementChanged()
{
static auto fn = UObject::FindObject<UFunction>("Function Purlovia_Character_BP.Purlovia_Character_BP_C.OnMovementChanged");
APurlovia_Character_BP_C_OnMovementChanged_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function Purlovia_Character_BP.Purlovia_Character_BP_C.BlueprintAnimNotifyCustomEvent
// ()
// Parameters:
// struct FName* CustomEventName (Parm, ZeroConstructor, IsPlainOldData)
// class USkeletalMeshComponent** MeshComp (Parm, ZeroConstructor, IsPlainOldData)
// class UAnimSequenceBase** Animation (Parm, ZeroConstructor, IsPlainOldData)
// class UAnimNotify** AnimNotifyObject (ConstParm, Parm, ZeroConstructor, IsPlainOldData)
void APurlovia_Character_BP_C::BlueprintAnimNotifyCustomEvent(struct FName* CustomEventName, class USkeletalMeshComponent** MeshComp, class UAnimSequenceBase** Animation, class UAnimNotify** AnimNotifyObject)
{
static auto fn = UObject::FindObject<UFunction>("Function Purlovia_Character_BP.Purlovia_Character_BP_C.BlueprintAnimNotifyCustomEvent");
APurlovia_Character_BP_C_BlueprintAnimNotifyCustomEvent_Params params;
params.CustomEventName = CustomEventName;
params.MeshComp = MeshComp;
params.Animation = Animation;
params.AnimNotifyObject = AnimNotifyObject;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function Purlovia_Character_BP.Purlovia_Character_BP_C.UpdateMeshesAfterDelay
// ()
void APurlovia_Character_BP_C::UpdateMeshesAfterDelay()
{
static auto fn = UObject::FindObject<UFunction>("Function Purlovia_Character_BP.Purlovia_Character_BP_C.UpdateMeshesAfterDelay");
APurlovia_Character_BP_C_UpdateMeshesAfterDelay_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function Purlovia_Character_BP.Purlovia_Character_BP_C.ComeOutShortRange
// ()
void APurlovia_Character_BP_C::ComeOutShortRange()
{
static auto fn = UObject::FindObject<UFunction>("Function Purlovia_Character_BP.Purlovia_Character_BP_C.ComeOutShortRange");
APurlovia_Character_BP_C_ComeOutShortRange_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function Purlovia_Character_BP.Purlovia_Character_BP_C.ComeOutLongRange
// ()
// Parameters:
// int Range (Parm, ZeroConstructor, IsPlainOldData)
void APurlovia_Character_BP_C::ComeOutLongRange(int Range)
{
static auto fn = UObject::FindObject<UFunction>("Function Purlovia_Character_BP.Purlovia_Character_BP_C.ComeOutLongRange");
APurlovia_Character_BP_C_ComeOutLongRange_Params params;
params.Range = Range;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function Purlovia_Character_BP.Purlovia_Character_BP_C.OnPurloviaSleeped
// ()
void APurlovia_Character_BP_C::OnPurloviaSleeped()
{
static auto fn = UObject::FindObject<UFunction>("Function Purlovia_Character_BP.Purlovia_Character_BP_C.OnPurloviaSleeped");
APurlovia_Character_BP_C_OnPurloviaSleeped_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function Purlovia_Character_BP.Purlovia_Character_BP_C.PreComeOutActions
// ()
void APurlovia_Character_BP_C::PreComeOutActions()
{
static auto fn = UObject::FindObject<UFunction>("Function Purlovia_Character_BP.Purlovia_Character_BP_C.PreComeOutActions");
APurlovia_Character_BP_C_PreComeOutActions_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function Purlovia_Character_BP.Purlovia_Character_BP_C.TryComeOutNormal
// ()
// Parameters:
// bool PlayAnim (Parm, ZeroConstructor, IsPlainOldData)
// bool forceUnbury (Parm, ZeroConstructor, IsPlainOldData)
void APurlovia_Character_BP_C::TryComeOutNormal(bool PlayAnim, bool forceUnbury)
{
static auto fn = UObject::FindObject<UFunction>("Function Purlovia_Character_BP.Purlovia_Character_BP_C.TryComeOutNormal");
APurlovia_Character_BP_C_TryComeOutNormal_Params params;
params.PlayAnim = PlayAnim;
params.forceUnbury = forceUnbury;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function Purlovia_Character_BP.Purlovia_Character_BP_C.OnBuried
// ()
void APurlovia_Character_BP_C::OnBuried()
{
static auto fn = UObject::FindObject<UFunction>("Function Purlovia_Character_BP.Purlovia_Character_BP_C.OnBuried");
APurlovia_Character_BP_C_OnBuried_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function Purlovia_Character_BP.Purlovia_Character_BP_C.ShowBuryMeshAfterDelay
// ()
void APurlovia_Character_BP_C::ShowBuryMeshAfterDelay()
{
static auto fn = UObject::FindObject<UFunction>("Function Purlovia_Character_BP.Purlovia_Character_BP_C.ShowBuryMeshAfterDelay");
APurlovia_Character_BP_C_ShowBuryMeshAfterDelay_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function Purlovia_Character_BP.Purlovia_Character_BP_C.HideBuryMeshAfterDelay
// ()
void APurlovia_Character_BP_C::HideBuryMeshAfterDelay()
{
static auto fn = UObject::FindObject<UFunction>("Function Purlovia_Character_BP.Purlovia_Character_BP_C.HideBuryMeshAfterDelay");
APurlovia_Character_BP_C_HideBuryMeshAfterDelay_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function Purlovia_Character_BP.Purlovia_Character_BP_C.FastBury
// ()
void APurlovia_Character_BP_C::FastBury()
{
static auto fn = UObject::FindObject<UFunction>("Function Purlovia_Character_BP.Purlovia_Character_BP_C.FastBury");
APurlovia_Character_BP_C_FastBury_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function Purlovia_Character_BP.Purlovia_Character_BP_C.OnClientConnect
// ()
void APurlovia_Character_BP_C::OnClientConnect()
{
static auto fn = UObject::FindObject<UFunction>("Function Purlovia_Character_BP.Purlovia_Character_BP_C.OnClientConnect");
APurlovia_Character_BP_C_OnClientConnect_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function Purlovia_Character_BP.Purlovia_Character_BP_C.OnWildServerConnect
// ()
void APurlovia_Character_BP_C::OnWildServerConnect()
{
static auto fn = UObject::FindObject<UFunction>("Function Purlovia_Character_BP.Purlovia_Character_BP_C.OnWildServerConnect");
APurlovia_Character_BP_C_OnWildServerConnect_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function Purlovia_Character_BP.Purlovia_Character_BP_C.OnTamedServerConnect
// ()
void APurlovia_Character_BP_C::OnTamedServerConnect()
{
static auto fn = UObject::FindObject<UFunction>("Function Purlovia_Character_BP.Purlovia_Character_BP_C.OnTamedServerConnect");
APurlovia_Character_BP_C_OnTamedServerConnect_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function Purlovia_Character_BP.Purlovia_Character_BP_C.ReceiveBeginPlay
// ()
void APurlovia_Character_BP_C::ReceiveBeginPlay()
{
static auto fn = UObject::FindObject<UFunction>("Function Purlovia_Character_BP.Purlovia_Character_BP_C.ReceiveBeginPlay");
APurlovia_Character_BP_C_ReceiveBeginPlay_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function Purlovia_Character_BP.Purlovia_Character_BP_C.ExecuteUbergraph_Purlovia_Character_BP
// ()
// Parameters:
// int EntryPoint (Parm, ZeroConstructor, IsPlainOldData)
void APurlovia_Character_BP_C::ExecuteUbergraph_Purlovia_Character_BP(int EntryPoint)
{
static auto fn = UObject::FindObject<UFunction>("Function Purlovia_Character_BP.Purlovia_Character_BP_C.ExecuteUbergraph_Purlovia_Character_BP");
APurlovia_Character_BP_C_ExecuteUbergraph_Purlovia_Character_BP_Params params;
params.EntryPoint = EntryPoint;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| 31.527132 | 250 | 0.747748 | 2bite |
99f7fa9d204bc081eb5a5dc52ffcc73954983c9b | 12,994 | cc | C++ | examples/containers/parSkipListUniqueElems-lock.cc | ppete/unleashed | 1be4335350d5024684a68a0b4f9c45ef6beb0481 | [
"BSD-3-Clause"
] | null | null | null | examples/containers/parSkipListUniqueElems-lock.cc | ppete/unleashed | 1be4335350d5024684a68a0b4f9c45ef6beb0481 | [
"BSD-3-Clause"
] | null | null | null | examples/containers/parSkipListUniqueElems-lock.cc | ppete/unleashed | 1be4335350d5024684a68a0b4f9c45ef6beb0481 | [
"BSD-3-Clause"
] | null | null | null | #include <thread>
#include <iostream>
#include <sstream>
#include <list>
#include <iomanip>
#include "ucl/unused.hpp"
#ifndef WITHOUT_GC
#define GC_THREADS 1
// #define GC_DEBUG 1
#include <gc/gc.h>
#include "ucl/gc-cxx11/gc_cxx11.hpp" // use GC allocator modified to work with C++11
#endif /* WITHOUT_GC */
#ifdef HTM_ENABLED
#include "ucl/htm-skiplist-lock.hpp"
#else
#include "ucl/skiplist.hpp"
#endif
#ifndef PNOITER
#define PNOITER 1000
#endif /* PNOITER */
#ifndef NUM_THREADS
#define NUM_THREADS 4
#endif /* NUM_THREADS */
#ifndef NUM_RUNS
#define NUM_RUNS 1
#endif /* NUM_RUNS */
#ifdef HTM_ENABLED
#if defined TEST_NO_MANAGER
template <class T>
using default_alloc = htm::just_alloc<T>;
#elif defined TEST_PUB_SCAN_MANAGER
template <class T>
using default_alloc = htm::pub_scan_manager<T>;
#elif defined TEST_REFCOUNT_MANAGER
template <class T>
using default_alloc = htm::ref_counter<T>;
#elif defined TEST_EPOCH_MANAGER
template <class T>
using default_alloc = htm::epoch_manager<T>;
#elif defined TEST_STACKTRACK_MANAGER
template <class T>
using default_alloc = htm::stacktrack_manager<T>;
#else /* undefined MANAGER */
#error "preprocessor define for HTM memory manager is needed (TEST_JUST_ALLOC, TEST_GC_MANAGER, TEST_EPOCH_MANAGER, TEST_PUB_SCAN_MANAGER, TEST_REFCOUNT_MANAGER)"
#endif /* TEST_NO_MANAGER */
#else /* !HTM_ENABLED */
namespace lf = lockfree;
namespace fg = locking;
#if defined TEST_NO_MANAGER
template <class T>
using default_alloc = lf::just_alloc<T>;
#elif defined TEST_GC_MANAGER
template <class T>
using default_alloc = lf::gc_manager<T, gc_allocator_cxx11>;
#elif defined TEST_EPOCH_MANAGER
template <class T>
using default_alloc = lf::epoch_manager<T>;
#elif defined TEST_PUB_SCAN_MANAGER
template <class T>
using default_alloc = lf::pub_scan_manager<T>;
#else /* undefined MANAGER */
#error "preprocessor define for memory manager is needed (TEST_JUST_ALLOC, TEST_GC_MANAGER, TEST_EPOCH_MANAGER, TEST_PUB_SCAN_MANAGER)"
#endif /* TEST_NO_MANAGER */
#endif /* HTM_ENABLED */
#ifndef TEST_MAX_LEVELS
#define TEST_MAX_LEVELS 32
#endif
#ifndef TEST_CONFLICTS
#define TEST_CONFLICTS 0
#endif
static const size_t LEVELS = TEST_MAX_LEVELS;
#if defined HTM_ENABLED
template <class T>
using skiplist = htm::SkipList<T, LEVELS, std::less<T>, default_alloc<T> >;
#elif defined TEST_LF_CONTAINER
template <class T>
using skiplist = lf::skiplist<T, std::less<T>, default_alloc<T>, LEVELS>;
#elif defined TEST_LOCK_CONTAINER
template <class T>
using skiplist = fg::skiplist<T, std::less<T>, default_alloc<T>, LEVELS>;
#else
#error "preprocessor define for container class is needed (HTM_ENABLED, TEST_LF_CONTAINER, TEST_LOCK_CONTAINER)"
#endif
typedef skiplist<int> container_type;
int total_time = 0;
#ifdef HTM_ENABLED
struct OperDesc
{
char op;
int el;
int lv;
OperDesc(char o, int e, int l)
: op(o), el(e), lv(l)
{}
};
#endif /* HTM_ENABLED */
struct alignas(CACHELINESZ) ThreadInfo
{
container_type* container;
size_t num;
size_t fail;
size_t succ;
size_t pnoiter;
size_t num_threads;
size_t num_held_back;
#ifdef HTM_ENABLED
size_t ctrab;
size_t ttlab;
std::vector<OperDesc> ops;
#endif /* HTM_ENABLED */
// unsigned cpunode_start;
// unsigned cpunode_end;
// std::set elemsin;
// std::set elemsout;
ThreadInfo(container_type* r, size_t n, size_t cntiter, size_t cntthreads)
: container(r), num(n), fail(0), succ(0), pnoiter(cntiter), num_threads(cntthreads),
num_held_back(0)
#ifdef HTM_ENABLED
, ctrab(0), ttlab(0), ops()
#endif /* HTM_ENABLED */
// , cpunode_start(0), cpunode_end(0)
{
assert(num < num_threads);
}
ThreadInfo()
: ThreadInfo(nullptr, 0, 0, 0)
{}
};
static
void fail()
{
throw std::logic_error("error");
}
/// counts number of threads that are ready to run
static size_t waiting_threads;
/// waits until all threads have been created and are ready to run
static
void sync_start()
{
assert(waiting_threads);
__sync_fetch_and_sub(&waiting_threads, 1);
while (waiting_threads) __sync_synchronize();
}
/// computes number of operations that a thread will carry out
static
size_t opsPerThread(size_t maxthread, size_t totalops, size_t thrid)
{
assert(maxthread > thrid);
size_t numops = totalops / maxthread;
size_t remops = totalops % maxthread;
if (remops > 0 && thrid < remops) ++numops;
return numops;
}
/// computes number of operations in the main loop; the remainder of
/// operations will be executed prior to the main loop (i.e., insert elements)
static
size_t opsMainLoop(size_t numops)
{
return numops - (numops / 10);
}
/// computes the expected size after all operations have been finished
/// requires deterministic skiplist operations
static
int _expectedSize(size_t maxthread, size_t totalops)
{
int elems = 0;
for (size_t i = 0; i < maxthread; ++i)
{
int numops = opsPerThread(maxthread, totalops, i);
int nummain = opsMainLoop(numops);
// special case when nummain is even and small
// then the insert happens after the delete
if ((numops - nummain == 0) && (nummain % 2 == 0))
elems += numops / 2;
else
elems += (numops - nummain);
// if odd, we insert one more
if (nummain % 2) ++elems;
}
return elems;
}
#if TEST_CONFLICTS
//
// contention at end of list
static
size_t genElem(size_t num, size_t thrid, size_t maxthread, size_t)
{
return num * maxthread + thrid;
}
static
int expectedSize(size_t maxthread, size_t totalops)
{
return _expectedSize(maxthread, totalops);
}
#else
// generate elems so threads operate by and large in disjoint segments of the skiplist
static
int expectedSize(size_t maxthread, size_t totalops)
{
return _expectedSize(maxthread, totalops);
}
static
size_t genElem(size_t num, size_t thrid, size_t, size_t)
{
// note, the multiplier must be adjusted with higher number of elements
return thrid * 2000000 + num;
}
#endif
std::atomic<bool> ptest_failed(false);
static
void container_test_prefix(ThreadInfo& ti)
{
const size_t tinum = ti.num;
size_t numops = opsPerThread(ti.num_threads, ti.pnoiter, tinum);
const size_t threadops = numops;
const size_t nummain = opsMainLoop(numops);
size_t wrid = 0;
try
{
while (numops > nummain)
{
int elem = genElem(++wrid, tinum, ti.num_threads, threadops);
#if HTM_ENABLED
size_t abortctr = 0;
int succ = ti.container->insert(elem, abortctr);
// ti.ops.push_back(OperDesc('i', elem, succ));
if (abortctr > ti.ctrab) ti.ctrab = abortctr;
ti.ttlab += abortctr;
#else
int succ = ti.container->insert(elem);
#endif /* HTM_ENABLED */
assert(succ >= 0), ucl::unused(succ);
++ti.succ;
// std::cout << "added " << elem << " " << succ << std::endl;
--numops;
}
}
catch (int errc)
{
ptest_failed = true;
std::cout << "err: " << errc << std::endl;
}
}
static
void container_test(ThreadInfo& ti)
{
const size_t tinum = ti.num;
size_t numops = opsPerThread(ti.num_threads, ti.pnoiter, tinum);
const size_t threadops = numops;
const size_t nummain = opsMainLoop(numops);
size_t wrid = numops - nummain;
size_t rdid = wrid / 2;
try
{
// set numops to nummain (after prefix has been executed)
numops = nummain;
assert(numops > 0);
while (numops)
{
#if HTM_ENABLED
size_t abortctr = 0;
#endif /* HTM_ENABLED */
if (numops % 2)
{
int elem = genElem(++wrid, tinum, ti.num_threads, threadops);
#if HTM_ENABLED
int succ = ti.container->insert(elem, abortctr);
// ti.ops.push_back(OperDesc('i', elem, succ));
#else
int succ = ti.container->insert(elem);
#endif /* HTM_ENABLED */
assert(succ >= 0), ucl::unused(succ);
++ti.succ;
}
else
{
int elem = genElem(++rdid, tinum, ti.num_threads, threadops);
#if HTM_ENABLED
int succ = ti.container->erase(elem, abortctr);
// ti.ops.push_back(OperDesc('e', elem, succ));
#else
int succ = ti.container->erase(elem);
#endif /* HTM_ENABLED */
if (succ > 0) ++ti.succ; else ++ti.fail;
}
#if HTM_ENABLED
if (abortctr > ti.ctrab) ti.ctrab = abortctr;
ti.ttlab += abortctr;
#endif /* HTM_ENABLED */
--numops;
}
ti.container->getAllocator().release_memory();
ti.num_held_back = ti.container->getAllocator().has_unreleased_memory();
}
catch (int errc)
{
ptest_failed = true;
std::cout << "err: " << errc << std::endl;
}
}
typedef std::chrono::time_point<std::chrono::system_clock> time_point;
static time_point starttime;
void ptest(ThreadInfo *const ti)
{
gc_cxx_thread_context gc_guard;
container_test_prefix(*ti);
sync_start();
if (ti->num == 0) starttime = std::chrono::system_clock::now();
container_test(*ti);
}
void sequential_test(size_t cntoper)
{
container_type cont;
ThreadInfo info(&cont, 0, cntoper, 1);
std::cout << std::endl;
container_test(info);
std::cout << "seq OK" << std::endl;
}
void parallel_test(const size_t cntthreads, const size_t cntoper)
{
std::cout << std::endl;
std::list<std::thread> exp_threads;
std::list<ThreadInfo> thread_info;
container_type cont;
waiting_threads = cntthreads;
// spawn
for (size_t i = 0; i < cntthreads; ++i)
{
thread_info.push_back(ThreadInfo(&cont, i, cntoper, cntthreads));
exp_threads.emplace_back(ptest, &thread_info.back());
}
// join
for (std::thread& thr : exp_threads) thr.join();
time_point endtime = std::chrono::system_clock::now();
int elapsedtime = std::chrono::duration_cast<std::chrono::milliseconds>(endtime-starttime).count();
__sync_synchronize();
const int szlst = std::distance(cont.qbegin(), cont.qend());
std::cout << "elapsed time = " << elapsedtime << "ms" << std::endl;
std::cout << "skiplist size = " << szlst << std::endl;
total_time += elapsedtime;
std::cout << elapsedtime << std::endl;
size_t total_succ = 0;
size_t total_fail = 0;
for (ThreadInfo& info : thread_info)
{
std::cout << "i: " << info.num << " "
<< info.succ << "(" << (info.fail + info.succ) << ")"
//~ << " [ " << thread_info[i].cpunode_start
//~ << " - " << thread_info[i].cpunode_end
<< " ] x "
#if HTM_ENABLED
<< info.ctrab << " < "
<< info.ttlab
#endif /* HTM_ENABLED */
<< " ( " << info.num_held_back << " obj held )"
<< std::endl;
total_succ += info.succ;
total_fail += info.fail;
}
if (expectedSize(cntthreads, cntoper) != szlst)
{
std::cout << "Unexpected size " << expectedSize(cntthreads, cntoper)
<< " <exp != act> " << szlst << std::endl;
fail();
}
#if HTM_ENABLED
size_t total = htm::analysis::stats(cont.getAllocator().statsbegin(), cont.getAllocator().statslimit());
size_t measures = htm::analysis::statsctr(cont.getAllocator().statsbegin(), cont.getAllocator().statslimit());
size_t collects = htm::analysis::collectctr(cont.getAllocator().statsbegin(), cont.getAllocator().statslimit());
float avtxlen = ((float) total) / measures;
std::cerr << "avgtxlen: " << avtxlen << std::endl;
std::cout << avtxlen << " (" << total << "/" << measures << ") "
<< " " << collects
<< std::endl;
if (!htm::skiplist_check(cont.start, cont.limit, std::less<int>()))
{
std::cout << "fail" << std::endl;
fail();
}
#endif /* HTM_ENABLED */
std::cout << szlst << std::endl;
std::cout << "|| o&o." << std::endl;
}
template <class T>
static inline
size_t asNum(const T& t)
{
size_t res = 0;
std::stringstream str;
str << t;
str >> res;
return res;
}
int main(int argc, char** args)
{
#ifndef WITHOUT_GC
GC_INIT();
GC_allow_register_threads();
// GC_find_leak = 1;
#endif /* WITHOUT_GC */
size_t pnoiter = PNOITER;
size_t num_threads = NUM_THREADS;
size_t num_runs = NUM_RUNS;
if (argc > 1) pnoiter = asNum(*(args+1));
if (argc > 2) num_threads = asNum(*(args+2));
if (argc > 3) num_runs = asNum(*(args+3));
// sequential_test(pnoiter);
try
{
std::cout << "*** skiplist test " << pnoiter << "<ops thrds>" << num_threads << std::endl;
std::cout << typeid(container_type).name() << " " << container_type::MAXLEVEL << std::endl;
for (size_t i = 0; i < num_runs; ++i)
{
std::cout << "***** ***** ***** restart ***** " << i << std::endl;
parallel_test(num_threads, pnoiter);
}
std::cerr <<"Average time: "<<total_time/num_runs<<std::endl;
std::cout << std::endl;
}
catch(...)
{
std::cout << "Error caught..." << std::endl;
}
return 0;
}
| 23.412613 | 164 | 0.644143 | ppete |
99f816422451f1694e057ae0be74a6b530bae0c2 | 1,673 | cc | C++ | test/memory_design_test.cc | tdelame/Graphics-Origin | 27b7d6ac72c4cb1858fc85dc18fe864de1496c6d | [
"MIT"
] | null | null | null | test/memory_design_test.cc | tdelame/Graphics-Origin | 27b7d6ac72c4cb1858fc85dc18fe864de1496c6d | [
"MIT"
] | null | null | null | test/memory_design_test.cc | tdelame/Graphics-Origin | 27b7d6ac72c4cb1858fc85dc18fe864de1496c6d | [
"MIT"
] | null | null | null | # include "../graphics-origin/graphics_origin.h"
# include "../graphics-origin/tools/memory.h"
# include <iostream>
# include <vector>
namespace graphics_origin {
namespace test {
static int execute( int argc, char* argv[] )
{
(void)argc;
(void)argv;
const auto page_size = tools::virtual_memory::get_page_size();
std::cout << "page size = " << page_size << std::endl;
tools::allocation_policy::growing_stack allocator( page_size * 40, page_size );
tools::memory_arena<
tools::allocation_policy::growing_stack,
tools::thread_policy::single_thread,
tools::bounds_checking_policy::per_allocation,
tools::memory_tracking_policy::no,
tools::memory_tagging_policy::yes > arena( &allocator );
std::vector< char* > allocations ( page_size * 2, nullptr );
std::cout <<"committed before allocation: " << allocator.get_committed_memory() << std::endl;
for( unsigned int i = 0; i < page_size * 2; ++ i )
{
allocations[ i ] = go_new( char, arena );
}
std::cout <<"committed after allocation : " << allocator.get_committed_memory() << std::endl;
for( unsigned int i = page_size * 2 - 1; i >= (page_size >> 1); -- i )
{
go_delete( allocations[ i ], arena );
}
std::cout <<"committed after delete : " << allocator.get_committed_memory() << std::endl;
allocator.purge();
std::cout <<"committed after purge : " << allocator.get_committed_memory() << std::endl;
return 0;
}
}
}
int main( int argc, char* argv[] )
{
return graphics_origin::test::execute( argc, argv );
}
| 30.981481 | 99 | 0.61327 | tdelame |
99f8c2573e0ae97655bea4f85b7a80e67054c346 | 4,497 | cpp | C++ | test/testmain.cpp | suratovvlad/squaresolver | c64b6125af52ba9df76febcebfff9417ce77541b | [
"MIT"
] | null | null | null | test/testmain.cpp | suratovvlad/squaresolver | c64b6125af52ba9df76febcebfff9417ce77541b | [
"MIT"
] | null | null | null | test/testmain.cpp | suratovvlad/squaresolver | c64b6125af52ba9df76febcebfff9417ce77541b | [
"MIT"
] | null | null | null |
#define CATCH_CONFIG_MAIN
#include <iostream>
#include <catch2/catch.hpp>
#include <thread>
#include "simpletaskgenerator.hpp"
#include "simpletaskconsumer.hpp"
#include <solver.hpp>
#include <quadraticequation.hpp>
TEST_CASE("simple equation, D > 0")
{
auto equation = std::make_shared<QuadraticEquation>();
equation->a_ = 1;
equation->b_ = -8;
equation->c_ = 12;
auto solver = Solver{};
auto roots = solver.solve(equation);
REQUIRE(roots);
REQUIRE(roots->x1_ == 2);
REQUIRE(roots->x2_ == 6);
}
TEST_CASE("simple equation, D == 0")
{
auto equation = std::make_shared<QuadraticEquation>();
equation->a_ = 1;
equation->b_ = 12;
equation->c_ = 36;
auto solver = Solver{};
auto roots = solver.solve(equation);
REQUIRE(roots);
REQUIRE(roots->x1_ == -6);
REQUIRE(roots->x2_ == -6);
}
TEST_CASE("simple equation, D < 0")
{
auto equation = std::make_shared<QuadraticEquation>();
equation->a_ = 1;
equation->b_ = 2;
equation->c_ = 17;
auto solver = Solver{};
auto roots = solver.solve(equation);
REQUIRE(!roots);
}
TEST_CASE("Blocked Queue with simple task")
{
struct Task {
int x;
};
const size_t capacity = 10;
auto blockedQueue = std::make_unique<BlockingQueue<std::unique_ptr<Task>>>(capacity);
for (size_t i = 0; i < capacity; ++i)
{
auto task = std::make_unique<Task>();
task->x = i;
blockedQueue->schedule(task);
}
for (size_t i = 0; i < capacity; ++i)
{
std::unique_ptr<Task> task;
blockedQueue->consume(task);
REQUIRE(task);
REQUIRE(task->x == i);
}
}
TEST_CASE("Blocked Queue with QuadraticEquation")
{
const size_t capacity = 10;
auto blockedQueue = std::make_unique<BlockingQueue<std::unique_ptr<QuadraticEquation>>>(capacity);
for (size_t i = 1; i <= capacity; ++i)
{
auto task = std::make_unique<QuadraticEquation>();
task->a_ = i;
task->b_ = 2 * i;
task->c_ = 4 * i;
blockedQueue->schedule(task);
}
for (size_t i = 1; i <= capacity; ++i)
{
std::unique_ptr<QuadraticEquation> task;
blockedQueue->consume(task);
REQUIRE(task);
REQUIRE(task->a_ == i);
REQUIRE(task->b_ == 2 * i);
REQUIRE(task->c_ == 4 * i);
}
}
TEST_CASE("Blocked Queue with QuadraticEquation 2")
{
const size_t capacity = 10;
auto blockedQueue = std::make_unique<BlockingQueue<QuadraticEquation>>(capacity);
for (size_t i = 1; i <= capacity; ++i)
{
auto task = QuadraticEquation{};
task.a_ = i;
task.b_ = 2 * i;
task.c_ = 4 * i;
blockedQueue->schedule(task);
}
for (size_t i = 1; i <= capacity; ++i)
{
auto task = QuadraticEquation{};
blockedQueue->consume(task);
REQUIRE(task.a_ == i);
REQUIRE(task.b_ == 2 * i);
REQUIRE(task.c_ == 4 * i);
}
}
TEST_CASE("SimpleTaskWorkers")
{
constexpr size_t capacity = 10;
auto tasksQueue = std::make_shared<BlockingQueue<int>>(capacity);
std::cout << "starting producer thread..." << std::endl;
std::thread producerThread(&SimpleTaskGenerator::run, SimpleTaskGenerator{tasksQueue});
std::cout << "starting consumer thread..." << std::endl;
std::thread consumerThread(&SimpleTaskConsumer::run, SimpleTaskConsumer{tasksQueue});
std::cout << "starting consumer thread 2..." << std::endl;
std::thread consumerThread2(&SimpleTaskConsumer::run, SimpleTaskConsumer{tasksQueue});
std::cout << "starting consumer thread 3..." << std::endl;
std::thread consumerThread3(&SimpleTaskConsumer::run, SimpleTaskConsumer{tasksQueue});
std::cout << "starting consumer thread 3..." << std::endl;
std::thread consumerThread4(&SimpleTaskConsumer::run, SimpleTaskConsumer{tasksQueue});
std::chrono::time_point<std::chrono::system_clock> start, end;
std::cout << "waiting for threads to finish..." << std::endl;
start = std::chrono::system_clock::now();
producerThread.join();
consumerThread.join();
consumerThread2.join();
consumerThread3.join();
consumerThread4.join();
end = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds = end - start;
auto x = std::chrono::duration_cast<std::chrono::seconds>(elapsed_seconds);
//to_string
std::cout <<"Spent time (s): " << std::to_string(x.count()) << std::endl;
}
| 26.145349 | 102 | 0.617968 | suratovvlad |
99f9ae927914941b7a44f1224acdd271fc916df8 | 3,952 | cpp | C++ | OpenNeighborhood/src/Elements/AddXboxButton.cpp | ClementDreptin/OpenNeighborhood | 595768263a03d5d2640cf5111a0492311c15a3a0 | [
"Apache-2.0"
] | 7 | 2021-07-03T20:58:01.000Z | 2021-11-03T18:04:20.000Z | OpenNeighborhood/src/Elements/AddXboxButton.cpp | ClementDreptin/OpenNeighborhood | 595768263a03d5d2640cf5111a0492311c15a3a0 | [
"Apache-2.0"
] | 2 | 2021-06-17T14:50:53.000Z | 2021-06-18T21:18:05.000Z | OpenNeighborhood/src/Elements/AddXboxButton.cpp | ClementDreptin/OpenNeighborhood | 595768263a03d5d2640cf5111a0492311c15a3a0 | [
"Apache-2.0"
] | null | null | null | #include "pch.h"
#include "Elements/AddXboxButton.h"
#define MINI_CASE_SENSITIVE
#include <mINI/ini.h>
#include "Render/TextureManager.h"
#include "Xbox/XboxManager.h"
#include "Events/AppEvent.h"
#include "Elements/Xbox.h"
#include "Render/UI.h"
AddXboxButton::AddXboxButton()
: Element("Add Xbox 360", "addXboxButton") {}
void AddXboxButton::OnRender()
{
auto texture = TextureManager::GetTexture(m_TextureName);
if (ImGui::ImageButtonWithText((void *)(intptr_t)texture->GetTextureID(), ImVec2(texture->GetWidth(), texture->GetHeight()), ImVec2(m_Width, m_Height), m_Label.c_str(), ImVec2(m_Padding, m_Padding)))
if (ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left))
OnClick();
ImVec2 center(ImGui::GetIO().DisplaySize.x * 0.5f, ImGui::GetIO().DisplaySize.y * 0.5f);
ImGui::SetNextWindowPos(center, ImGuiCond_Appearing, ImVec2(0.5f, 0.5f));
if (ImGui::BeginPopupModal("Add Xbox 360 ?", nullptr, ImGuiWindowFlags_AlwaysAutoResize))
{
static int bytes[4] = { 192, 168, 1, 100 };
float width = ImGui::CalcItemWidth();
ImGui::PushID("IP");
ImGui::TextUnformatted("IP Address");
ImGui::SameLine();
for (int i = 0; i < 4; i++)
{
ImGui::PushItemWidth(width / 4.0f);
ImGui::PushID(i);
bool invalidByte = false;
if (bytes[i] > 255)
{
// Make values over 255 red, and when focus is lost reset it to 255.
bytes[i] = 255;
invalidByte = true;
ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1.0f, 0.0f, 0.0f, 1.0f));
}
else if (bytes[i] < 0)
{
// Make values below 0 yellow, and when focus is lost reset it to 0.
bytes[i] = 0;
invalidByte = true;
ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1.0f, 1.0f, 0.0f, 1.0f));
}
ImGui::InputInt("##v", &bytes[i], 0, 0, ImGuiInputTextFlags_CharsDecimal);
if (invalidByte)
ImGui::PopStyleColor();
// Call ImGui::SameLine() only for the first 3 inputs
if (i < 3)
ImGui::SameLine();
ImGui::PopID();
ImGui::PopItemWidth();
}
ImGui::PopID();
if (ImGui::Button("OK", ImVec2(120.0f, 0.0f)))
{
std::stringstream ipAddress;
ipAddress << bytes[0] << "." << bytes[1] << "." << bytes[2] << "." << bytes[3];
std::string consoleName;
UI::SetSuccess(XboxManager::CreateConsole(ipAddress.str(), consoleName));
if (UI::IsGood())
CreateXbox(consoleName, ipAddress.str());
else
UI::SetErrorMessage("Couldn't find console");
ImGui::CloseCurrentPopup();
}
ImGui::SetItemDefaultFocus();
ImGui::SameLine();
if (ImGui::Button("Cancel", ImVec2(120, 0)))
ImGui::CloseCurrentPopup();
ImGui::EndPopup();
}
}
void AddXboxButton::OnClick()
{
ImGui::OpenPopup("Add Xbox 360 ?");
}
void AddXboxButton::CreateXbox(const std::string &consoleName, const std::string &ipAddress)
{
auto xboxElement = std::vector<Ref<Element>>();
xboxElement.emplace_back(CreateRef<Xbox>(consoleName, ipAddress));
ContentsChangeEvent event(xboxElement, true);
m_EventCallback(event);
std::string configFilePath = GetExecDir().append("OpenNeighborhood.ini").string();
mINI::INIFile configFile(configFilePath);
mINI::INIStructure config;
struct stat buffer;
if (stat(configFilePath.c_str(), &buffer) == -1)
{
config[consoleName]["ip_address"] = ipAddress;
configFile.generate(config, true);
}
else
{
configFile.read(config);
config[consoleName]["ip_address"] = ipAddress;
configFile.write(config, true);
}
}
| 31.11811 | 203 | 0.582237 | ClementDreptin |
82067ab803a16b8356843bcb014d8e2702349edd | 419 | cpp | C++ | src/3rdPartyLib/SPIRV.cpp | SapphireEngine/Engine | bf5a621ac45d76a2635b804c0d8b023f1114d8f5 | [
"MIT"
] | 2 | 2020-02-03T04:58:17.000Z | 2021-03-13T06:03:52.000Z | src/3rdPartyLib/SPIRV.cpp | SapphireEngine/Engine | bf5a621ac45d76a2635b804c0d8b023f1114d8f5 | [
"MIT"
] | null | null | null | src/3rdPartyLib/SPIRV.cpp | SapphireEngine/Engine | bf5a621ac45d76a2635b804c0d8b023f1114d8f5 | [
"MIT"
] | null | null | null | #include "define.h"
#include <SPIRV_Cross/spirv_cfg.cpp>
#include <SPIRV_Cross/spirv_cpp.cpp>
#include <SPIRV_Cross/spirv_cross.cpp>
#include <SPIRV_Cross/spirv_cross_parsed_ir.cpp>
#include <SPIRV_Cross/spirv_cross_util.cpp>
#include <SPIRV_Cross/spirv_glsl.cpp>
#include <SPIRV_Cross/spirv_hlsl.cpp>
#include <SPIRV_Cross/spirv_msl.cpp>
#include <SPIRV_Cross/spirv_parser.cpp>
#include <SPIRV_Cross/spirv_reflect.cpp> | 38.090909 | 48 | 0.821002 | SapphireEngine |
8207aa5e71819ec62dfc0307590b13da840c7dc0 | 2,539 | cpp | C++ | Examples/source/ExampleMapScene.cpp | boschman32/Crime-Engine | 128529634011d41a1f7fc1a356245d7f7ef77cb3 | [
"MIT"
] | 1 | 2021-07-21T17:14:35.000Z | 2021-07-21T17:14:35.000Z | Examples/source/ExampleMapScene.cpp | boschman32/Crime-Engine | 128529634011d41a1f7fc1a356245d7f7ef77cb3 | [
"MIT"
] | null | null | null | Examples/source/ExampleMapScene.cpp | boschman32/Crime-Engine | 128529634011d41a1f7fc1a356245d7f7ef77cb3 | [
"MIT"
] | 3 | 2021-03-07T15:51:03.000Z | 2021-07-13T20:01:34.000Z | #include "expch.h"
#include "ExampleMapScene.h"
#include "Scenes/IMapScene.h"
#include "Scenes/SceneManager.h"
#include "Utils/ServiceManager.h"
namespace ce
{
namespace examples
{
class SceneA : public IMapScene
{
public:
SceneA(int a_a, float a_b, const std::string& a_c)
: m_a(a_a), m_b(a_b), m_c(a_c)
{
SelectMap("Derpmap!");
};
bool OnSceneSwitched() override
{
CE_CORE_INFO("Switched to different scene dispose of all data!");
return LoadSelectedMap();
}
void OnDispose() override
{
CE_CORE_INFO("We switched to this scene: {0}", GetSceneName());
}
void OnUpdate(float) override
{
}
void OnDraw(cr::RenderLayer&) override
{
}
void OnMapLoaded(std::shared_ptr<LevelMap>&) override
{
}
void OnPlan() override
{
CE_CORE_INFO("Planning started!");
}
void OnSimulation() override
{
CE_CORE_INFO("Simulation started!");
}
void Simulate(float) override
{
CE_CORE_INFO("Simulating!");
}
void Planning(float) override
{
CE_CORE_INFO("Planning!");
}
private:
int m_a;
float m_b;
std::string m_c;
};
class SceneB : public IScene
{
public:
// Inherited via IScene
bool OnSceneSwitched() override
{
return true;
}
void OnDispose() override
{
}
void OnUpdate(float) override
{
}
void OnDraw(cr::RenderLayer&) override
{
}
};
void ExampleMapScene::RunExample()
{
ServiceManager::MakeService<LevelService>();
auto sm = ServiceManager::MakeService<SceneManager>();
sm->AddScene<SceneA>("SceneA", 1, 5.5f, "Test!");
sm->AddScene<SceneB>("SceneB");
int x = 0;
bool running = true;
while(running)
{
sm->Update(0.f);
CE_CORE_INFO("Press 1 to change to 'SceneA' | Press 2 to change to 'SceneB' | Press 3 to exit!");
std::cin >> x;
if(x == 1)
{
auto sceneA = sm->SwitchScene<SceneA>("SceneA");
int y = 0;
CE_CORE_INFO("Press 1 to change to 'Planning' phase | Press 2 to change to 'Simulation' phase");
std::cin >> y;
if(y == 1)
{
sceneA->BeginPlan();
}
else if(y == 2)
{
sceneA->BeginSimulation();
}
}
else if(x == 2)
{
sm->SwitchScene<SceneB>("SceneB");
}
else if(x == 3)
{
running = false;
}
if(sm->GetCurrentScene() != nullptr)
{
CE_CORE_INFO("Current scene is: {0}", sm->GetCurrentScene()->GetSceneName());
}
}
}
}
}
| 16.926667 | 101 | 0.582119 | boschman32 |
820859b320cd376cf595e587ebbab8dfbbb221e7 | 397 | cpp | C++ | mcppalloc_bitmap_allocator/mcppalloc_bitmap_allocator_test/main.cpp | garyfurnish/mcppalloc | 5a6dfc99bab23e7f6aba8d20919d71a6e31c38bf | [
"MIT"
] | null | null | null | mcppalloc_bitmap_allocator/mcppalloc_bitmap_allocator_test/main.cpp | garyfurnish/mcppalloc | 5a6dfc99bab23e7f6aba8d20919d71a6e31c38bf | [
"MIT"
] | null | null | null | mcppalloc_bitmap_allocator/mcppalloc_bitmap_allocator_test/main.cpp | garyfurnish/mcppalloc | 5a6dfc99bab23e7f6aba8d20919d71a6e31c38bf | [
"MIT"
] | null | null | null | #include <mcpputil/mcpputil/declarations.hpp>
// This Must be first.
#include <mcpputil/mcpputil/bandit.hpp>
#ifdef _WIN32
#pragma optimize("", off)
#endif
using namespace bandit;
extern void bitmap_allocator_tests();
go_bandit([]() { bitmap_allocator_tests(); });
int main(int argc, char *argv[])
{
auto ret = bandit::run(argc, argv);
#ifdef _WIN32
::std::cin.get();
#endif
return ret;
}
| 19.85 | 46 | 0.707809 | garyfurnish |
820c4615984b65b6aa748665540866835604e63b | 1,770 | cpp | C++ | apps/myApps/MessageSender/src/ofApp.cpp | nmbakfm/club_projection_mapping | 95dd0d7604fce397fcdf058d09085fb32b184257 | [
"MIT"
] | 1 | 2015-06-16T07:36:55.000Z | 2015-06-16T07:36:55.000Z | apps/myApps/MessageSender/src/ofApp.cpp | nmbakfm/club_projection_mapping | 95dd0d7604fce397fcdf058d09085fb32b184257 | [
"MIT"
] | null | null | null | apps/myApps/MessageSender/src/ofApp.cpp | nmbakfm/club_projection_mapping | 95dd0d7604fce397fcdf058d09085fb32b184257 | [
"MIT"
] | null | null | null | #include "ofApp.h"
//--------------------------------------------------------------
void ofApp::setup(){
ofBackground(0);
xml.load("settings.xml");
string host = xml.getValue("osc:host","localhost");
int port = xml.getValue("osc:port",57688);
sender.setup(host, port);
string text = string( ofBufferFromFile("birthday.txt") );
ofxOscMessage msg;
msg.setAddress("/birthday");
msg.addStringArg(text);
sender.sendMessage(msg);
}
//--------------------------------------------------------------
void ofApp::update(){
}
//--------------------------------------------------------------
void ofApp::draw(){
ofDrawBitmapString("Message sending complete. Press ESC Key And Close This Window", 50, 50);
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
}
| 24.246575 | 96 | 0.369492 | nmbakfm |
8216f1517302a9606733b033ab2654a4fdcd1ae5 | 212 | cpp | C++ | src/page_01/task020.cpp | berlios/pe | 5edd686481666c86a14804cfeae354a267d468be | [
"MIT"
] | null | null | null | src/page_01/task020.cpp | berlios/pe | 5edd686481666c86a14804cfeae354a267d468be | [
"MIT"
] | null | null | null | src/page_01/task020.cpp | berlios/pe | 5edd686481666c86a14804cfeae354a267d468be | [
"MIT"
] | null | null | null | #include <gmpxx.h>
#include "base/digit_manipulation.h"
#include "base/task.h"
TASK(20) {
mpz_class factorial = 1;
for (int i = 1; i <= 100; ++i) {
factorial *= i;
}
return DigitSum(factorial);
}
| 14.133333 | 36 | 0.613208 | berlios |
8217693ab2fb7648633db1278b933e11bd860774 | 5,163 | cpp | C++ | Computer Graphics/src/scene_vertex.cpp | Isain965/graficasComputacionales | 1a7730bc14cb9c366b94c89836a4b89a10a0e578 | [
"MIT"
] | null | null | null | Computer Graphics/src/scene_vertex.cpp | Isain965/graficasComputacionales | 1a7730bc14cb9c366b94c89836a4b89a10a0e578 | [
"MIT"
] | null | null | null | Computer Graphics/src/scene_vertex.cpp | Isain965/graficasComputacionales | 1a7730bc14cb9c366b94c89836a4b89a10a0e578 | [
"MIT"
] | null | null | null | #include "scene_vertex.h"
#include "ifile.h"
#include "time.h"
#include <vector>
#include <iostream>
scene_vertex::~scene_vertex() {
// Borramos la memoria del ejecutable cuando
// la escena deja de existir
glDeleteProgram(shader_program);
}
void scene_vertex::init() {
// ifile es parte del codigo que yo les doy
// El codigo fuente se encuentra en el proyecto Util
// Su unico proposito en la vida es leer archivos de texto
ifile shader_file;
// El metodo read recibe la ruta al archivo de texto a leer
// Si encuentra el archivo, intenta leerlo. En este caso,
// estamos intentando leer un archivo llamado grid,
// dentro de una carpeta shaders.
shader_file.read("shaders/grid.vert");
// Obtenemos los contenidos leidos en el paso anterior
// utilizando el metodo get_contents. Regresa un string
std::string vertex_source = shader_file.get_contents();
// OpenGL es un API de C, por lo que no trabaja con
// strings de C++. Tenemos que hacer un cast a un tipo de
// dato que OpenGL entienda. Podemos usar strings de C (char*)
// o utilizar el tipo de dato definido por OpenGL (GLchar*).
// Preferimos lo segundo.
const GLchar* vertex_source_c = (const GLchar*)vertex_source.c_str();
// Creamos el identificador para un vertex shader,
// utiliznado la funcion glCreateShader. La funcion
// regresa el identificador y lo guardamos en la variable
// vertex_shader.
GLuint vertex_shader = glCreateShader(GL_VERTEX_SHADER);
// Utilizando la funcion glShaderSource, indicamos que queremos
// enviar el codigo fuente del shader. La funcion espera:
// Identificador del shader (vertex_shader)
// Cuantos codigos fuentes queremos manadar (1)
// El c�digo fuente (vertex_source_c)
// La longitud del codigo fuente. Si usamos nullptr, se
// asume que debe continuar leyendo hasta encontrar un nullptr.
glShaderSource(vertex_shader, 1, &vertex_source_c, nullptr);
// Compilamos el codigo fuente contenido en el shader
// con identificador vertex_shader.
glCompileShader(vertex_shader);
// Repetimos el mismo proceso, pero ahora para un
// fragment shader contenido en un archivo llamado
// solid_color.frag dentro de la carpeta shaders.
shader_file.read("shaders/solid_color.frag");
std::string fragment_source = shader_file.get_contents();
const GLchar* fragment_source_c = (const GLchar*)fragment_source.c_str();
// El identificador del shader lo creamos pero para un
// shader de tipo fragment.
GLuint fragment_shader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragment_shader, 1, &fragment_source_c, nullptr);
glCompileShader(fragment_shader);
// Una vez que hemos creado los shaders necesarios,
// creamos el manager utilizando la funcion glCreateProgram
// que regresa el id.
shader_program = glCreateProgram();
// Utilizamos glAttachShader para asociar un shader con el manager
// En este caso, shader_program es manager de vertex_shader
glAttachShader(shader_program, vertex_shader);
// En este caso, shader_program es manager de fragment_shader
glAttachShader(shader_program, fragment_shader);
// Ejecutamos el proceso de linkeo. En esta etapa se busca
// que los shaders puedan trabajar en conjunto y todo este
// definido correctamente.
glLinkProgram(shader_program);
// Tambien deberiamos verificar que el proceso de linkeo
// termine sin errores. Por tiempo, asumimos que el
// resultado fue correcto.
GLint vertex_compiled;
glGetShaderiv(vertex_shader, GL_COMPILE_STATUS, &vertex_compiled);
if (vertex_compiled != GL_TRUE) {
GLint log_length;
glGetShaderiv(vertex_shader, GL_INFO_LOG_LENGTH, &log_length);
std::vector<GLchar> log;
log.resize(log_length);
glGetShaderInfoLog(vertex_shader, log_length, &log_length,
&log[0]);
std::cout << ">>> Errors in Vertex shader\n";
for (int i = 0; i < log.size(); i++) {
std::cout << log[i];
}
std::cout << ">>> END Errors in Vertex shader";
}
GLint fragment_compiled;
glGetShaderiv(fragment_shader, GL_COMPILE_STATUS, &fragment_compiled);
if (fragment_compiled != GL_TRUE) {
GLint log_length;
glGetShaderiv(fragment_shader, GL_INFO_LOG_LENGTH, &log_length);
std::vector<GLchar> log_shader;
log_shader.resize(log_length);
glGetShaderInfoLog(fragment_shader, log_length, &log_length,
&log_shader[0]);
std::cout << ">>> Errors in Fragment shader\n";
for (int i = 0; i < log_shader.size(); i++) {
std::cout << log_shader[i];
}
std::cout << ">>> END Errors in Fragment shader";
}
// Borramos los shaders, porque ya tenemos el ejecutable
glDeleteShader(vertex_shader);
glDeleteShader(fragment_shader);
}
void scene_vertex::awake() {
glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
glEnable(GL_PROGRAM_POINT_SIZE);
}
void scene_vertex::sleep() {
glClearColor(1.0f, 1.0f, 0.5f, 1.0f);
glDisable(GL_PROGRAM_POINT_SIZE);
}
void scene_vertex::mainLoop() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glUseProgram(shader_program);
GLuint time_location = glGetUniformLocation(shader_program, "time");
glUniform1f(time_location, time::elapsed_time().count());
glDrawArrays(GL_LINE_STRIP, 0, 100);
glUseProgram(0);
}
void scene_vertex::resize(int width, int height) {
}
| 35.363014 | 74 | 0.75092 | Isain965 |
821c0059ae96b073cdcda798f94ee7694b7df8d7 | 457 | cpp | C++ | libitm2stm/libitm-5.2.cpp | nmadduri/rstm | 5f4697f987625379d99bca1f32b33ee8e821c8a5 | [
"BSD-3-Clause"
] | 8 | 2016-12-05T19:39:55.000Z | 2021-07-22T07:00:40.000Z | libitm2stm/libitm-5.2.cpp | hlitz/rstm_zsim_tm | 1c66824b124f84c8812ca25f4a9aa225f9f1fa34 | [
"BSD-3-Clause"
] | null | null | null | libitm2stm/libitm-5.2.cpp | hlitz/rstm_zsim_tm | 1c66824b124f84c8812ca25f4a9aa225f9f1fa34 | [
"BSD-3-Clause"
] | 2 | 2018-06-02T07:46:33.000Z | 2020-06-26T02:12:34.000Z | /**
* Copyright (C) 2011
* University of Rochester Department of Computer Science
* and
* Lehigh University Department of Computer Science and Engineering
*
* License: Modified BSD
* Please see the file LICENSE.RSTM for licensing information
*/
// 5.2 Version checking
#include "libitm.h"
int
_ITM_versionCompatible(int i) {
return (i <= _ITM_VERSION_NO);
}
const char*
_ITM_libraryVersion(void) {
return _ITM_VERSION;
}
| 19.041667 | 70 | 0.704595 | nmadduri |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.