hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13 values | lang stringclasses 1 value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 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 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | 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 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
c710f4a5290dcd8d3198b304ce83d93c6791c264 | 13,248 | cpp | C++ | lib/commonAPI/sensor/ext/platform/wm/src/SensorApiDll.cpp | mensfeld/rhodes | 2962610a314ed563a0b7c83fcae6136913a1b033 | [
"MIT"
] | 173 | 2015-01-02T11:14:08.000Z | 2022-03-05T09:54:54.000Z | lib/commonAPI/sensor/ext/platform/wm/src/SensorApiDll.cpp | mensfeld/rhodes | 2962610a314ed563a0b7c83fcae6136913a1b033 | [
"MIT"
] | 263 | 2015-01-05T04:35:22.000Z | 2021-09-07T06:00:02.000Z | lib/commonAPI/sensor/ext/platform/wm/src/SensorApiDll.cpp | watusi/rhodes | 07161cca58ff6a960bbd1b79b36447b819bfa0eb | [
"MIT"
] | 77 | 2015-01-12T20:57:18.000Z | 2022-02-17T15:15:14.000Z | #include "SensorApiDll.h"
namespace sensormodule
{
// Call back function pointer type definitions
typedef DWORD (WINAPI *LPFN_SENSOR_OPEN)(OPEN_MODE eMode, SENSOR_INFO_T * ptSensorInfo, HANDLE * phSensor);
typedef DWORD (WINAPI *LPFN_SENSOR_CLOSE)(HANDLE hSensor);
typedef DWORD (WINAPI *LPFN_SENSOR_FINDFIRST)(SENSOR_INFO_T * ptSensorInfo, HANDLE * phFindHandle);
typedef DWORD (WINAPI *LPFN_SENSOR_FINDNEXT)(HANDLE hFindHandle, SENSOR_INFO_T * ptSensorInfo);
typedef DWORD (WINAPI *LPFN_SENSOR_FINDCLOSE)(HANDLE hFindHandle);
typedef DWORD (WINAPI *LPFN_SENSOR_REGISTERDATANOTIFICATION)(HANDLE hSensor, NOTIFIER_TYPE eNotifierType, LPVOID lpNotifier, DWORD dwNotifyThreshold);
typedef DWORD (WINAPI *LPFN_SENSOR_DEREGISTERDATANOTIFICATION)(HANDLE hSensor);
typedef DWORD (WINAPI *LPFN_SENSOR_STARTSAMPLING)(HANDLE hSensor);
typedef DWORD (WINAPI *LPFN_SENSOR_STOPSAMPLING)(HANDLE hSensor);
typedef DWORD (WINAPI *LPFN_SENSOR_GETPROPERTY)(HANDLE hSensor, SENSOR_PROPERTY eProperty, LONG * pnValue);
typedef DWORD (WINAPI *LPFN_SENSOR_SETPROPERTY)(HANDLE hSensor, SENSOR_PROPERTY eProperty, LONG nValue);
CSensorApiDll::CSensorApiDll(void) :
m_hSensorLibrary(NULL),
m_hSensor(NULL)
{
this->LoadModule();
}
CSensorApiDll::~CSensorApiDll(void)
{
this->UnloadModule();
}
bool CSensorApiDll::SensorAPIsPresent() const
{
if (NULL == m_hSensorLibrary) return false;
// validate if the api's are present
LPFN_SENSOR_OPEN lpfnSENSOR_Open;
LPFN_SENSOR_CLOSE lpfnSENSOR_Close;
LPFN_SENSOR_FINDFIRST lpfnSENSOR_FindFirst;
LPFN_SENSOR_FINDNEXT lpfnSENSOR_FindNext;
LPFN_SENSOR_FINDCLOSE lpfnSENSOR_FindClose;
LPFN_SENSOR_REGISTERDATANOTIFICATION lpfnSENSOR_RegisterDataNotification;
LPFN_SENSOR_DEREGISTERDATANOTIFICATION lpfnSENSOR_DeregisterDataNotification;
LPFN_SENSOR_STARTSAMPLING lpfnSENSOR_StartSampling;
LPFN_SENSOR_STOPSAMPLING lpfnSENSOR_StopSampling;
LPFN_SENSOR_GETPROPERTY lpfnSENSOR_GetProperty;
LPFN_SENSOR_SETPROPERTY lpfnSENSOR_SetProperty;
// Get function pointers from Sensor API library
lpfnSENSOR_Open = (LPFN_SENSOR_OPEN)GetProcAddress(m_hSensorLibrary, TEXT("SENSOR_Open"));
lpfnSENSOR_Close = (LPFN_SENSOR_CLOSE)GetProcAddress(m_hSensorLibrary, TEXT("SENSOR_Close"));
lpfnSENSOR_FindFirst = (LPFN_SENSOR_FINDFIRST)GetProcAddress(m_hSensorLibrary, TEXT("SENSOR_FindFirst"));
lpfnSENSOR_FindNext = (LPFN_SENSOR_FINDNEXT)GetProcAddress(m_hSensorLibrary, TEXT("SENSOR_FindNext"));
lpfnSENSOR_FindClose = (LPFN_SENSOR_FINDCLOSE)GetProcAddress(m_hSensorLibrary, TEXT("SENSOR_FindClose"));
lpfnSENSOR_RegisterDataNotification = (LPFN_SENSOR_REGISTERDATANOTIFICATION)GetProcAddress(m_hSensorLibrary, TEXT("SENSOR_RegisterDataNotification"));
lpfnSENSOR_DeregisterDataNotification = (LPFN_SENSOR_DEREGISTERDATANOTIFICATION)GetProcAddress(m_hSensorLibrary, TEXT("SENSOR_DeregisterDataNotification"));
lpfnSENSOR_StartSampling = (LPFN_SENSOR_STARTSAMPLING)GetProcAddress(m_hSensorLibrary, TEXT("SENSOR_StartSampling"));
lpfnSENSOR_StopSampling = (LPFN_SENSOR_STOPSAMPLING)GetProcAddress(m_hSensorLibrary, TEXT("SENSOR_StopSampling"));
lpfnSENSOR_GetProperty = (LPFN_SENSOR_GETPROPERTY)GetProcAddress(m_hSensorLibrary, TEXT("SENSOR_GetProperty"));
lpfnSENSOR_SetProperty = (LPFN_SENSOR_SETPROPERTY)GetProcAddress(m_hSensorLibrary, TEXT("SENSOR_SetProperty"));
if ((NULL == lpfnSENSOR_Open) ||
(NULL == lpfnSENSOR_Close) ||
(NULL == lpfnSENSOR_FindFirst) ||
(NULL == lpfnSENSOR_FindNext) ||
(NULL == lpfnSENSOR_FindClose) ||
(NULL == lpfnSENSOR_RegisterDataNotification) ||
(NULL == lpfnSENSOR_DeregisterDataNotification) ||
(NULL == lpfnSENSOR_StartSampling) ||
(NULL == lpfnSENSOR_StopSampling) ||
(NULL == lpfnSENSOR_GetProperty) ||
(NULL == lpfnSENSOR_SetProperty))
{
return false;
}
return true;
}
CSensorApiDll::operator HANDLE() const
{
return m_hSensor;
}
DWORD CSensorApiDll::SensorOpen(OPEN_MODE eMode, SENSOR_INFO_T& sensorInfo)
{
DWORD dwResult = ERROR_SUCCESS;
if (NULL == m_hSensorLibrary)
{
dwResult = ERROR_INVALID_HANDLE;
return dwResult;
}
if (NULL != m_hSensor)
{
dwResult = ERROR_ALREADY_EXISTS;
return dwResult;
}
LPFN_SENSOR_OPEN lpfnSENSOR_Open = reinterpret_cast<LPFN_SENSOR_OPEN>(GetProcAddress(m_hSensorLibrary, TEXT("SENSOR_Open")));
if (NULL == lpfnSENSOR_Open)
{
dwResult = ::GetLastError();
return dwResult;
}
dwResult = lpfnSENSOR_Open(eMode, &sensorInfo, &m_hSensor);
return dwResult;
}
DWORD CSensorApiDll::SensorClose()
{
DWORD dwResult = ERROR_SUCCESS;
if ((NULL == m_hSensorLibrary) || (NULL == m_hSensor))
{
dwResult = ERROR_INVALID_HANDLE;
return dwResult;
}
LPFN_SENSOR_CLOSE lpfnSENSOR_Close = reinterpret_cast<LPFN_SENSOR_CLOSE>(GetProcAddress(m_hSensorLibrary, TEXT("SENSOR_Close")));
if (NULL == lpfnSENSOR_Close)
{
dwResult = ::GetLastError();
return dwResult;
}
dwResult = lpfnSENSOR_Close(m_hSensor);
if (E_SENSOR_SUCCESS == dwResult)
{
m_hSensor = NULL;
}
return dwResult;
}
DWORD CSensorApiDll::SensorRegisterDataNotification(NOTIFIER_TYPE eNotifierType, LPVOID lpNotifier, DWORD dwNotifyThreshold)
{
DWORD dwResult = ERROR_SUCCESS;
if ((NULL == m_hSensorLibrary) || (NULL == m_hSensor))
{
dwResult = ERROR_INVALID_HANDLE;
return dwResult;
}
LPFN_SENSOR_REGISTERDATANOTIFICATION lpfnSENSOR_RegisterDataNotification = reinterpret_cast<LPFN_SENSOR_REGISTERDATANOTIFICATION>(::GetProcAddress(m_hSensorLibrary, TEXT("SENSOR_RegisterDataNotification")));
if (NULL == lpfnSENSOR_RegisterDataNotification)
{
dwResult = ::GetLastError();
return dwResult;
}
dwResult = lpfnSENSOR_RegisterDataNotification(m_hSensor, eNotifierType, lpNotifier, dwNotifyThreshold);
return dwResult;
}
DWORD CSensorApiDll::SensorDeregisterDataNotification()
{
DWORD dwResult = ERROR_SUCCESS;
if ((NULL == m_hSensorLibrary) || (NULL == m_hSensor))
{
dwResult = ERROR_INVALID_HANDLE;
return dwResult;
}
LPFN_SENSOR_DEREGISTERDATANOTIFICATION lpfnSENSOR_DeregisterDataNotification = reinterpret_cast<LPFN_SENSOR_DEREGISTERDATANOTIFICATION>(GetProcAddress(m_hSensorLibrary, TEXT("SENSOR_DeregisterDataNotification")));
if (NULL == lpfnSENSOR_DeregisterDataNotification)
{
dwResult = ::GetLastError();
return dwResult;
}
dwResult = lpfnSENSOR_DeregisterDataNotification(m_hSensor);
return dwResult;
}
DWORD CSensorApiDll::SensorStartSampling()
{
DWORD dwResult = ERROR_SUCCESS;
if ((NULL == m_hSensorLibrary) || (NULL == m_hSensor))
{
dwResult = ERROR_INVALID_HANDLE;
return dwResult;
}
LPFN_SENSOR_STARTSAMPLING lpfnSENSOR_StartSampling = reinterpret_cast<LPFN_SENSOR_STARTSAMPLING>(GetProcAddress(m_hSensorLibrary, TEXT("SENSOR_StartSampling")));
if (NULL == lpfnSENSOR_StartSampling)
{
dwResult = ::GetLastError();
return dwResult;
}
dwResult = lpfnSENSOR_StartSampling(m_hSensor);
return dwResult;
}
DWORD CSensorApiDll::SensorStopSampling()
{
DWORD dwResult = ERROR_SUCCESS;
if ((NULL == m_hSensorLibrary) || (NULL == m_hSensor))
{
dwResult = ERROR_INVALID_HANDLE;
return dwResult;
}
LPFN_SENSOR_STOPSAMPLING lpfnSENSOR_StopSampling = reinterpret_cast<LPFN_SENSOR_STOPSAMPLING>(GetProcAddress(m_hSensorLibrary, TEXT("SENSOR_StopSampling")));
if (NULL == lpfnSENSOR_StopSampling)
{
dwResult = ::GetLastError();
return dwResult;
}
dwResult = lpfnSENSOR_StopSampling(m_hSensor);
return dwResult;
}
DWORD CSensorApiDll::SensorGetProperty(SENSOR_PROPERTY eProperty, LONG &nValue)
{
DWORD dwResult = ERROR_SUCCESS;
if ((NULL == m_hSensorLibrary) || (NULL == m_hSensor))
{
dwResult = ERROR_INVALID_HANDLE;
return dwResult;
}
LPFN_SENSOR_GETPROPERTY lpfnSENSOR_GetProperty = reinterpret_cast<LPFN_SENSOR_GETPROPERTY>(GetProcAddress(m_hSensorLibrary, TEXT("SENSOR_GetProperty")));
if (NULL == lpfnSENSOR_GetProperty)
{
dwResult = ::GetLastError();
return dwResult;
}
dwResult = lpfnSENSOR_GetProperty(m_hSensor, eProperty, &nValue);
return dwResult;
}
DWORD CSensorApiDll::SensorSetProperty(SENSOR_PROPERTY eProperty, LONG nValue)
{
DWORD dwResult = ERROR_SUCCESS;
if ((NULL == m_hSensorLibrary) || (NULL == m_hSensor))
{
dwResult = ERROR_INVALID_HANDLE;
return dwResult;
}
LPFN_SENSOR_SETPROPERTY lpfnSENSOR_SetProperty = reinterpret_cast<LPFN_SENSOR_SETPROPERTY>(GetProcAddress(m_hSensorLibrary, TEXT("SENSOR_SetProperty")));
if (NULL == lpfnSENSOR_SetProperty)
{
dwResult = ::GetLastError();
return dwResult;
}
dwResult = lpfnSENSOR_SetProperty(m_hSensor, eProperty, nValue);
return dwResult;
}
DWORD CSensorApiDll::Enumerate(rho::Vector<SENSOR_TYPE>& sensorList)
{
DWORD dwResult = ERROR_SUCCESS;
HMODULE hSensorLibrary = ::LoadLibrary(L"SensorApi.dll");
if (NULL == hSensorLibrary)
{
dwResult = ERROR_INVALID_HANDLE;
return dwResult;
}
LPFN_SENSOR_FINDFIRST lpfnSENSOR_FindFirst = reinterpret_cast<LPFN_SENSOR_FINDFIRST>(GetProcAddress(hSensorLibrary, TEXT("SENSOR_FindFirst")));
LPFN_SENSOR_FINDNEXT lpfnSENSOR_FindNext = reinterpret_cast<LPFN_SENSOR_FINDNEXT>(GetProcAddress(hSensorLibrary, TEXT("SENSOR_FindNext")));
LPFN_SENSOR_FINDCLOSE lpfnSENSOR_FindClose = reinterpret_cast<LPFN_SENSOR_FINDCLOSE>(GetProcAddress(hSensorLibrary, TEXT("SENSOR_FindClose")));
if ((NULL == lpfnSENSOR_FindFirst) || (NULL == lpfnSENSOR_FindNext) || (NULL == lpfnSENSOR_FindClose))
{
dwResult = ERROR_PROC_NOT_FOUND;
}
else
{
HANDLE hFindHandle = NULL;
SENSOR_INFO_T tSensorInfo;
//Initialize the structure to all zeros.
::ZeroMemory(&tSensorInfo, sizeof(SENSOR_INFO_T));
// Sets dwAllocated to the size of the structure.
SI_INIT(&tSensorInfo);
// Enumerating all available sensors.
// It can also be set to a required sensor in which case only FindFirst needs to be called.
tSensorInfo.eType = SENSOR_TYPE_ALL;
//Sets dwUsed to the extent of eType.
SI_SET_USED(&tSensorInfo, eType)
dwResult = lpfnSENSOR_FindFirst(&tSensorInfo, &hFindHandle);
while (E_SENSOR_SUCCESS == dwResult)
{
switch (tSensorInfo.eType)
{
case SENSOR_TYPE_ACCELEROMETER:
case SENSOR_TYPE_ORIENTATION:
case SENSOR_TYPE_TILT_ANGLE:
case SENSOR_TYPE_MOTION:
case SENSOR_TYPE_ECOMPASS:
case SENSOR_TYPE_MAGNETOMETER:
case SENSOR_TYPE_GYROSCOPE:
case SENSOR_TYPE_AMBIENT_LIGHT:
case SENSOR_TYPE_PROXIMITY:
case SENSOR_TYPE_PROXIMITY_LONG_RANGE:
case SENSOR_TYPE_PRESSURE:
case SENSOR_TYPE_TEMPERATURE:
case SENSOR_TYPE_HUMIDITY:
sensorList.addElement(tSensorInfo.eType);
break;
default:
break;
}
dwResult = lpfnSENSOR_FindNext(hFindHandle, &tSensorInfo);
}
dwResult = lpfnSENSOR_FindClose(hFindHandle);
}
if (NULL != hSensorLibrary)
{
::FreeLibrary(hSensorLibrary);
hSensorLibrary = NULL;
}
return dwResult;
}
void CSensorApiDll::ReadyForOpen(SENSOR_TYPE sensorType, SENSOR_INFO_T& sensorInfo)
{
memset(&sensorInfo, 0,sizeof(SENSOR_INFO_T));
SI_INIT(&sensorInfo);// sets the dwallocated field of the structure pointed to &tsensorinfo to the size of the structure.
sensorInfo.eType = sensorType; // modify the field (etype)
SI_SET_USED(&sensorInfo, eType) //Sets the dwUsed field of the structure pointed to &tSensorInfo to the extent of field (eType).
}
DWORD CSensorApiDll::LoadModule()
{
DWORD dwResult = ERROR_SUCCESS;
// load the dll
m_hSensorLibrary = ::LoadLibrary(L"SensorApi.dll");
if (NULL == m_hSensorLibrary)
{
dwResult = ::GetLastError();
return dwResult;
}
// validate if the api's are present
if (false == this->SensorAPIsPresent())
{
UnloadModule();
dwResult = ERROR_PROC_NOT_FOUND;
return dwResult;
}
return dwResult;
}
DWORD CSensorApiDll::UnloadModule()
{
DWORD dwResult = ERROR_SUCCESS;
//TODO:: unregister any subscribed events and sensor handle
//free the sensor module
if (NULL != m_hSensorLibrary)
{
if (FALSE != ::FreeLibrary(m_hSensorLibrary))
m_hSensorLibrary = NULL;
else
dwResult = ::GetLastError();
}
return dwResult;
}
} | 34.590078 | 217 | 0.702295 | [
"vector"
] |
c711071419901e824464d8d709e54fb1ffb54c24 | 414 | cpp | C++ | examples/ds/sqrt-decomposition/example-1.cpp | parth-07/dragon | 2e771d698398303c8ae6d603d28bc3acfa116181 | [
"MIT"
] | 1 | 2021-02-24T17:51:32.000Z | 2021-02-24T17:51:32.000Z | examples/ds/sqrt-decomposition/example-1.cpp | parth-07/dragon | 2e771d698398303c8ae6d603d28bc3acfa116181 | [
"MIT"
] | 1 | 2021-02-24T17:57:04.000Z | 2021-05-17T11:09:40.000Z | examples/ds/sqrt-decomposition/example-1.cpp | parth-07/ds-and-algos | 2e771d698398303c8ae6d603d28bc3acfa116181 | [
"MIT"
] | null | null | null | #include<iostream>
#include<vector>
#include "dragon/ds/sqrt-decomposition.hpp"
using namespace std;
int main()
{
vector<int> a{1,2,3,4,5,6,7,8,9,10};
struct Sum{
int operator()(int a,int b) {
return a+b;
}
};
dragon::SqrtDecomposition<int,Sum> sd(0,a);
cout<<sd.query(1,3)<<"\n";
cout<<sd.query(0,3)<<"\n";
sd.update(2,10);
cout<<sd.query(1,3)<<"\n";
cout<<sd.query(0,3)<<"\n";
} | 19.714286 | 45 | 0.589372 | [
"vector"
] |
c71225aa654d9ae5d10af4c7c440e01ce4d56549 | 6,226 | cpp | C++ | src/kernel/interrupts.cpp | fengjixuchui/popcorn | 86b7c6b298db3ae0c00de5898908506a0fdb032d | [
"BSL-1.0"
] | null | null | null | src/kernel/interrupts.cpp | fengjixuchui/popcorn | 86b7c6b298db3ae0c00de5898908506a0fdb032d | [
"BSL-1.0"
] | null | null | null | src/kernel/interrupts.cpp | fengjixuchui/popcorn | 86b7c6b298db3ae0c00de5898908506a0fdb032d | [
"BSL-1.0"
] | null | null | null | #include <stdint.h>
#include "apic.h"
#include "console.h"
#include "cpu.h"
#include "debug.h"
#include "device_manager.h"
#include "gdt.h"
#include "interrupts.h"
#include "io.h"
#include "log.h"
#include "scheduler.h"
#include "syscall.h"
static const uint16_t PIC1 = 0x20;
static const uint16_t PIC2 = 0xa0;
extern "C" {
void _halt();
void isr_handler(cpu_state*);
void irq_handler(cpu_state*);
#define ISR(i, name) extern void name ();
#define EISR(i, name) extern void name ();
#define UISR(i, name) extern void name ();
#define IRQ(i, q, name) extern void name ();
#include "interrupt_isrs.inc"
#undef IRQ
#undef UISR
#undef EISR
#undef ISR
}
isr
operator+(const isr &lhs, int rhs)
{
using under_t = std::underlying_type<isr>::type;
return static_cast<isr>(static_cast<under_t>(lhs) + rhs);
}
uint8_t
get_irq(unsigned vector)
{
switch (vector) {
#define ISR(i, name)
#define EISR(i, name)
#define UISR(i, name)
#define IRQ(i, q, name) case i : return q;
#include "interrupt_isrs.inc"
#undef IRQ
#undef UISR
#undef EISR
#undef ISR
default: return 0xff;
}
}
static void
disable_legacy_pic()
{
// Mask all interrupts
outb(PIC2+1, 0xfc);
outb(PIC1+1, 0xff);
// Start initialization sequence
outb(PIC1, 0x11); io_wait();
outb(PIC2, 0x11); io_wait();
// Remap into ignore ISRs
outb(PIC1+1, static_cast<uint8_t>(isr::isrIgnore0)); io_wait();
outb(PIC2+1, static_cast<uint8_t>(isr::isrIgnore8)); io_wait();
// Tell PICs about each other
outb(PIC1+1, 0x04); io_wait();
outb(PIC2+1, 0x02); io_wait();
}
static void
enable_serial_interrupts()
{
uint8_t ier = inb(COM1+1);
outb(COM1+1, ier | 0x1);
}
void
interrupts_init()
{
#define ISR(i, name) idt_set_entry(i, reinterpret_cast<uint64_t>(& name), 0x08, 0x8e);
#define EISR(i, name) idt_set_entry(i, reinterpret_cast<uint64_t>(& name), 0x08, 0x8e);
#define UISR(i, name) idt_set_entry(i, reinterpret_cast<uint64_t>(& name), 0x08, 0xee);
#define IRQ(i, q, name) idt_set_entry(i, reinterpret_cast<uint64_t>(& name), 0x08, 0x8e);
#include "interrupt_isrs.inc"
#undef IRQ
#undef UISR
#undef EISR
#undef ISR
disable_legacy_pic();
enable_serial_interrupts();
log::info(logs::boot, "Interrupts enabled.");
}
void
isr_handler(cpu_state *regs)
{
console *cons = console::get();
switch (static_cast<isr>(regs->interrupt & 0xff)) {
case isr::isrDebug: {
cons->set_color(11);
cons->puts("\nDebug Exception:\n");
cons->set_color();
uint64_t dr = 0;
__asm__ __volatile__ ("mov %%dr0, %0" : "=r"(dr));
print_regL("dr0", dr);
__asm__ __volatile__ ("mov %%dr1, %0" : "=r"(dr));
print_regM("dr1", dr);
__asm__ __volatile__ ("mov %%dr2, %0" : "=r"(dr));
print_regM("dr2", dr);
__asm__ __volatile__ ("mov %%dr3, %0" : "=r"(dr));
print_regR("dr3", dr);
__asm__ __volatile__ ("mov %%dr6, %0" : "=r"(dr));
print_regL("dr6", dr);
__asm__ __volatile__ ("mov %%dr7, %0" : "=r"(dr));
print_regR("dr7", dr);
print_regL("rip", regs->rip);
print_regM("rsp", regs->user_rsp);
print_regM("fla", regs->rflags);
_halt();
}
break;
case isr::isrGPFault: {
cons->set_color(9);
cons->puts("\nGeneral Protection Fault:\n");
cons->set_color();
cons->printf(" errorcode: %lx", regs->errorcode);
if (regs->errorcode & 0x01) cons->puts(" external");
int index = (regs->errorcode & 0xffff) >> 4;
if (index) {
switch ((regs->errorcode & 0x07) >> 1) {
case 0:
cons->printf(" GDT[%x]\n", index);
gdt_dump(index);
break;
case 1:
case 3:
cons->printf(" IDT[%x]\n", index);
idt_dump(index);
break;
default:
cons->printf(" LDT[%x]??\n", index);
break;
}
} else {
cons->putc('\n');
}
print_regs(*regs);
/*
print_stacktrace(2);
print_stack(*regs);
*/
}
_halt();
break;
case isr::isrPageFault: {
uintptr_t cr2 = 0;
__asm__ __volatile__ ("mov %%cr2, %0" : "=r"(cr2));
if ((regs->errorcode & 0x9) == 0 &&
page_manager::get()->fault_handler(cr2))
break;
cons->set_color(11);
cons->puts("\nPage Fault:\n");
cons->set_color();
cons->puts(" flags:");
if (regs->errorcode & 0x01) cons->puts(" present");
if (regs->errorcode & 0x02) cons->puts(" write");
if (regs->errorcode & 0x04) cons->puts(" user");
if (regs->errorcode & 0x08) cons->puts(" reserved");
if (regs->errorcode & 0x10) cons->puts(" ip");
cons->puts("\n");
print_regs(*regs);
print_stacktrace(2);
_halt();
}
break;
case isr::isrTimer:
scheduler::get().tick();
break;
case isr::isrLINT0:
cons->puts("\nLINT0\n");
break;
case isr::isrLINT1:
cons->puts("\nLINT1\n");
break;
case isr::isrAssert: {
cons->set_color();
print_regs(*regs);
print_stacktrace(2);
}
_halt();
break;
/*
case isr::isrSyscall:
syscall_dispatch(regs);
break;
*/
case isr::isrSpurious:
// No EOI for the spurious interrupt
return;
case isr::isrIgnore0:
case isr::isrIgnore1:
case isr::isrIgnore2:
case isr::isrIgnore3:
case isr::isrIgnore4:
case isr::isrIgnore5:
case isr::isrIgnore6:
case isr::isrIgnore7:
//cons->printf("\nIGNORED: %02x\n", regs->interrupt);
outb(PIC1, 0x20);
break;
case isr::isrIgnore8:
case isr::isrIgnore9:
case isr::isrIgnoreA:
case isr::isrIgnoreB:
case isr::isrIgnoreC:
case isr::isrIgnoreD:
case isr::isrIgnoreE:
case isr::isrIgnoreF:
//cons->printf("\nIGNORED: %02x\n", regs->interrupt);
outb(PIC1, 0x20);
outb(PIC2, 0x20);
break;
default:
cons->set_color(9);
cons->printf("\nReceived %02x interrupt:\n",
(static_cast<isr>(regs->interrupt)));
cons->set_color();
cons->printf(" ISR: %02lx ERR: %lx\n\n",
regs->interrupt, regs->errorcode);
print_regs(*regs);
print_stacktrace(2);
_halt();
}
*reinterpret_cast<uint32_t *>(0xffffff80fee000b0) = 0;
}
void
irq_handler(cpu_state *regs)
{
console *cons = console::get();
uint8_t irq = get_irq(regs->interrupt);
if (! device_manager::get().dispatch_irq(irq)) {
cons->set_color(11);
cons->printf("\nReceived unknown IRQ: %d (vec %d)\n",
irq, regs->interrupt);
cons->set_color();
print_regs(*regs);
_halt();
}
*reinterpret_cast<uint32_t *>(0xffffff80fee000b0) = 0;
}
| 21.105085 | 90 | 0.637167 | [
"vector"
] |
c722f134b2c20842399ec7e096ce3fab081d3986 | 10,490 | hh | C++ | dune/xt/grid/gridprovider/cube.hh | dune-community/dune-xt | da921524c6fff8d60c715cb4849a0bdd5f020d2b | [
"BSD-2-Clause"
] | 2 | 2020-02-08T04:08:52.000Z | 2020-08-01T18:54:14.000Z | dune/xt/grid/gridprovider/cube.hh | dune-community/dune-xt | da921524c6fff8d60c715cb4849a0bdd5f020d2b | [
"BSD-2-Clause"
] | 35 | 2019-08-19T12:06:35.000Z | 2020-03-27T08:20:39.000Z | dune/xt/grid/gridprovider/cube.hh | dune-community/dune-xt | da921524c6fff8d60c715cb4849a0bdd5f020d2b | [
"BSD-2-Clause"
] | 1 | 2020-02-08T04:09:34.000Z | 2020-02-08T04:09:34.000Z | // This file is part of the dune-xt project:
// https://zivgitlab.uni-muenster.de/ag-ohlberger/dune-community/dune-xt
// Copyright 2009-2021 dune-xt developers and contributors. All rights reserved.
// License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
// or GPL-2.0+ (http://opensource.org/licenses/gpl-license)
// with "runtime exception" (http://www.dune-project.org/license.html)
// Authors:
// Andreas Buhr (2014)
// Barbara Verfürth (2015)
// Felix Schindler (2012 - 2017, 2019 - 2020)
// Kirsten Weber (2012)
// René Fritze (2012 - 2020)
// Tobias Leibner (2014, 2016, 2018, 2020)
#ifndef DUNE_XT_GRID_GRIDPROVIDER_CUBE_HH
#define DUNE_XT_GRID_GRIDPROVIDER_CUBE_HH
#include <array>
#include <memory>
#include <sstream>
#include <type_traits>
#include <vector>
#include <limits>
#include <dune/xt/common/configuration.hh>
#include <dune/xt/common/exceptions.hh>
#include <dune/xt/common/fvector.hh>
#include <dune/xt/common/memory.hh>
#include <dune/xt/common/misc.hh>
#include <dune/xt/grid/grids.hh>
#include <dune/xt/grid/structuredgridfactory.hh>
#include <dune/xt/grid/type_traits.hh>
#include "provider.hh"
namespace Dune::XT::Grid {
static inline std::string cube_gridprovider_id()
{
return "xt.grid.gridprovider.cube";
}
static inline Common::Configuration cube_gridprovider_default_config()
{
Common::Configuration config;
config["type"] = cube_gridprovider_id();
config["lower_left"] = "[0 0 0 0]";
config["upper_right"] = "[1 1 1 1]";
config["num_elements"] = "[8 8 8 8]";
config["num_refinements"] = "0";
config["overlap_size"] = "[1 1 1 1]";
return config;
}
template <class GridType>
class CubeGridProviderFactory
{
static_assert(is_grid<GridType>::value);
template <typename G>
struct ElementVariant;
template <typename G>
struct ElementVariant
{
static constexpr int id = 2;
};
template <int dim, class Coords>
struct ElementVariant<Dune::YaspGrid<dim, Coords>>
{
static constexpr int id = 1;
};
#if HAVE_DUNE_SPGRID
template <class ct, int dim, template <int> class Refinement, class Comm>
struct ElementVariant<Dune::SPGrid<ct, dim, Refinement, Comm>>
{
static constexpr int id = 1;
};
#endif
#if HAVE_DUNE_ALUGRID
template <int dimGrid, int dimWorld, class MpiCommImp>
struct ElementVariant<Dune::ALUGrid<dimGrid, dimWorld, Dune::cube, Dune::conforming, MpiCommImp>>
{
static constexpr int id = 1;
};
template <int dimGrid, int dimWorld, class MpiCommImp>
struct ElementVariant<Dune::ALUGrid<dimGrid, dimWorld, Dune::cube, Dune::nonconforming, MpiCommImp>>
{
static constexpr int id = 1;
};
#endif // HAVE_DUNE_ALUGRID
public:
static constexpr bool available = true;
static std::string static_id()
{
return cube_gridprovider_id();
}
static Common::Configuration default_config()
{
return cube_gridprovider_default_config();
}
/// TODO simplex grid overlap_size
static GridProvider<GridType> create(const FieldVector<typename GridType::ctype, GridType::dimension>& lower_left,
const FieldVector<typename GridType::ctype, GridType::dimension>& upper_right,
const std::array<unsigned int, GridType::dimension>& num_elements,
const unsigned int num_refinements,
const std::array<unsigned int, GridType::dimension>& overlap_size,
MPIHelper::MPICommunicator mpi_comm)
{
static constexpr int variant = ElementVariant<GridType>::id;
static_assert(variant == 1 || variant == 2, "variant has to be 1 or 2!");
for (unsigned int dd = 0; dd < GridType::dimension; ++dd) {
if (!(lower_left[dd] < upper_right[dd]))
DUNE_THROW(Common::Exceptions::wrong_input_given,
"lower_left has to be elementwise smaller than upper_right!\n\nlower_left = "
<< lower_left << "\n\nupper_right = " << upper_right);
}
std::shared_ptr<GridType> grd_ptr(nullptr);
switch (variant) {
case 1:
grd_ptr = XT::Grid::StructuredGridFactory<GridType>::createCubeGrid(
lower_left, upper_right, num_elements, overlap_size, mpi_comm);
break;
case 2:
default:
grd_ptr = XT::Grid::StructuredGridFactory<GridType>::createSimplexGrid(
lower_left, upper_right, num_elements, mpi_comm);
break;
}
grd_ptr->loadBalance();
#if HAVE_ALBERTA
if (!std::is_same<GridType, AlbertaGrid<GridType::dimension, GridType::dimension>>::value)
#endif
grd_ptr->preAdapt();
grd_ptr->globalRefine(boost::numeric_cast<int>(num_refinements));
#if HAVE_ALBERTA
if (!std::is_same<GridType, AlbertaGrid<GridType::dimension, GridType::dimension>>::value)
#endif
grd_ptr->postAdapt();
grd_ptr->loadBalance();
return GridProvider<GridType>(grd_ptr);
} // ... create(...)
static GridProvider<GridType> create(const typename GridType::ctype& lower_left,
const typename GridType::ctype& upper_right,
const unsigned int num_elements,
const unsigned int num_refinements,
const unsigned int overlap_size,
MPIHelper::MPICommunicator mpi_comm)
{
return create(FieldVector<typename GridType::ctype, GridType::dimension>(lower_left),
FieldVector<typename GridType::ctype, GridType::dimension>(upper_right),
Common::make_array<unsigned int, GridType::dimension>(num_elements),
num_refinements,
Common::make_array<unsigned int, GridType::dimension>(overlap_size),
mpi_comm);
} // ... create(...)
static GridProvider<GridType> create(const Common::Configuration& cfg, MPIHelper::MPICommunicator mpi_comm)
{
static constexpr size_t d = GridType::dimension;
auto overlap_size =
cfg.has_key("overlap_size")
? cfg.template get<std::vector<unsigned int>>("overlap_size")
: cube_gridprovider_default_config().template get<std::vector<unsigned int>>("overlap_size");
std::array<unsigned int, d> overlap_size_array;
if (overlap_size.size() >= d) {
overlap_size_array = Common::make_array<unsigned int, d>(overlap_size);
} else if (!overlap_size.empty()) {
overlap_size_array = Common::make_array<unsigned int, d>(overlap_size);
} else {
DUNE_THROW(Common::Exceptions::wrong_input_given,
"overlap_size has to be a single number or a vector with at least "
<< d << "elements, has only " << overlap_size.size() << " elements!");
}
auto lower_left = cfg.get(
"lower_left",
cube_gridprovider_default_config().template get<FieldVector<typename GridType::ctype, GridType::dimension>>(
"lower_left"));
auto upper_right = cfg.get(
"upper_right",
cube_gridprovider_default_config().template get<FieldVector<typename GridType::ctype, GridType::dimension>>(
"upper_right"));
auto num_elements = cfg.get(
"num_elements", cube_gridprovider_default_config().template get<std::vector<unsigned int>>("num_elements"));
std::array<unsigned int, d> num_elements_array;
if (num_elements.size() >= d) {
num_elements_array = Common::make_array<unsigned int, d>(num_elements);
} else if (!num_elements.empty()) {
num_elements_array = Common::make_array<unsigned int, d>(num_elements);
} else {
DUNE_THROW(Common::Exceptions::wrong_input_given,
"num_elements has to be a single number or a vector with at least "
<< d << "elements, has only " << num_elements.size() << " elements!");
}
auto num_refinements =
cfg.get("num_refinements", cube_gridprovider_default_config().template get<unsigned int>("num_refinements"));
return create(lower_left, upper_right, num_elements_array, num_refinements, overlap_size_array, mpi_comm);
} // ... create(...)
}; // struct CubeGridProviderFactory
template <class GridType>
auto make_cube_grid(
const FieldVector<typename GridType::ctype, GridType::dimension>& lower_left,
const FieldVector<typename GridType::ctype, GridType::dimension>& upper_right,
const std::array<unsigned int, GridType::dimension> num_elements =
cube_gridprovider_default_config().template get<std::array<unsigned int, GridType::dimension>>("num_elements"),
const unsigned int num_refinements =
cube_gridprovider_default_config().template get<unsigned int>("num_refinements"),
const std::array<unsigned int, GridType::dimension> overlap_size =
cube_gridprovider_default_config().template get<std::array<unsigned int, GridType::dimension>>("overlap_size"),
MPIHelper::MPICommunicator mpi_comm = MPIHelper::getCommunicator())
{
static_assert(is_grid<GridType>::value);
return CubeGridProviderFactory<GridType>::create(
lower_left, upper_right, num_elements, num_refinements, overlap_size, mpi_comm);
}
template <class GridType>
auto make_cube_grid(
const typename GridType::ctype& lower_left,
const typename GridType::ctype& upper_right,
const unsigned int num_elements =
cube_gridprovider_default_config().template get<std::vector<unsigned int>>("num_elements").at(0),
const unsigned int num_refinements =
cube_gridprovider_default_config().template get<unsigned int>("num_refinements"),
const unsigned int overlap_size =
cube_gridprovider_default_config().template get<std::vector<unsigned int>>("overlap_size").at(0),
MPIHelper::MPICommunicator mpi_comm = MPIHelper::getCommunicator())
{
static_assert(is_grid<GridType>::value);
return CubeGridProviderFactory<GridType>::create(
lower_left, upper_right, num_elements, num_refinements, overlap_size, mpi_comm);
}
template <class GridType>
auto make_cube_grid(const Common::Configuration& cfg = cube_gridprovider_default_config(),
MPIHelper::MPICommunicator mpi_comm = MPIHelper::getCommunicator())
{
static_assert(is_grid<GridType>::value);
return CubeGridProviderFactory<GridType>::create(cfg, mpi_comm);
}
} // namespace Dune::XT::Grid
#endif // DUNE_XT_GRID_GRIDPROVIDER_CUBE_HH
| 39.584906 | 119 | 0.6796 | [
"vector"
] |
d178df0c2332f278ad2fb07c6494db852bb03076 | 6,435 | cpp | C++ | SilveR/R/library/RcppEigen/tinytest/cpp/rcppeigen.cpp | robalexclark/SilveR-Dev | 263008fdb9dc3fdd22bfc6f71b7c092867631563 | [
"MIT"
] | 7 | 2019-04-27T10:26:46.000Z | 2022-02-04T09:57:34.000Z | SilveR/R/library/RcppEigen/tinytest/cpp/rcppeigen.cpp | robalexclark/SilveR-Dev | 263008fdb9dc3fdd22bfc6f71b7c092867631563 | [
"MIT"
] | 14 | 2019-12-28T07:09:11.000Z | 2022-03-28T19:33:50.000Z | SilveR/R/library/RcppEigen/tinytest/cpp/rcppeigen.cpp | robalexclark/SilveR-Dev | 263008fdb9dc3fdd22bfc6f71b7c092867631563 | [
"MIT"
] | 4 | 2019-03-05T05:52:24.000Z | 2020-11-18T07:52:04.000Z |
#include <RcppEigen.h>
// [[Rcpp::depends(RcppEigen)]]
// [[Rcpp::export]]
Rcpp::List fx() {
Rcpp::List vecs = Rcpp::List::create(
Rcpp::_["Vec<complex>"] = Eigen::VectorXcd::Zero(5),
Rcpp::_["Vec<double>"] = Eigen::VectorXd::Zero(5),
Rcpp::_["Vec<float>"] = Eigen::VectorXf::Zero(5),
Rcpp::_["Vec<int>"] = Eigen::VectorXi::Zero(5)
);
// A VectorX<T> behaves as a matrix with one column but is converted to
// a vector object in R, not a matrix of one column. The distinction is
// that VectorX<T> objects are defined at compile time to have one column,
// whereas a MatrixX<T> has a dynamic number of columns that is set to 1
// during execution of the code. A MatrixX<T> object can be resized to have
// a different number of columns. A VectorX<T> object cannot.
Rcpp::List cols = Rcpp::List::create(
Rcpp::_["Col<complex>"] = Eigen::MatrixXcd::Zero(5, 1),
Rcpp::_["Col<double>"] = Eigen::MatrixXd::Zero(5, 1),
Rcpp::_["Col<float>"] = Eigen::MatrixXf::Zero(5, 1),
Rcpp::_["Col<int>"] = Eigen::MatrixXi::Zero(5, 1)
);
Rcpp::List rows = Rcpp::List::create(
Rcpp::_["Row<complex>"] = Eigen::RowVectorXcd::Zero(5),
Rcpp::_["Row<double>"] = Eigen::RowVectorXd::Zero(5),
Rcpp::_["Row<float>"] = Eigen::RowVectorXf::Zero(5),
Rcpp::_["Row<int>"] = Eigen::RowVectorXi::Zero(5)
);
Rcpp::List matrices = Rcpp::List::create(
Rcpp::_["Mat<complex>"] = Eigen::MatrixXcd::Identity(3, 3),
Rcpp::_["Mat<double>"] = Eigen::MatrixXd::Identity(3, 3),
Rcpp::_["Mat<float>"] = Eigen::MatrixXf::Identity(3, 3),
Rcpp::_["Mat<int>"] = Eigen::MatrixXi::Identity(3, 3)
);
// ArrayXX<t> objects have the same structure as matrices but allow
// componentwise arithmetic. A * B is matrix multiplication for
// matrices and componentwise multiplication for arrays.
Rcpp::List arrays2 = Rcpp::List::create(
Rcpp::_["Arr2<complex>"] = Eigen::ArrayXXcd::Zero(3, 3),
Rcpp::_["Arr2<double>"] = Eigen::ArrayXXd::Zero(3, 3),
Rcpp::_["Arr2<float>"] = Eigen::ArrayXXf::Zero(3, 3),
Rcpp::_["Arr2<int>"] = Eigen::ArrayXXi::Zero(3, 3)
);
// ArrayX<t> objects have the same structure as VectorX<T> objects
// but allow componentwise arithmetic, including functions like exp, log,
// sqrt, ...
Rcpp::List arrays1 = Rcpp::List::create(
Rcpp::_["Arr1<complex>"] = Eigen::ArrayXcd::Zero(5),
Rcpp::_["Arr1<double>"] = Eigen::ArrayXd::Zero(5),
Rcpp::_["Arr1<float>"] = Eigen::ArrayXf::Zero(5),
Rcpp::_["Arr1<int>"] = Eigen::ArrayXi::Zero(5)
);
Rcpp::List operations = Rcpp::List::create(
Rcpp::_["Op_seq"] = Eigen::ArrayXd::LinSpaced(6, 1, 10), // arguments are length.out, start, end
Rcpp::_["Op_log"] = Eigen::ArrayXd::LinSpaced(6, 1, 10).log(),
Rcpp::_["Op_exp"] = Eigen::ArrayXd::LinSpaced(6, 1, 10).exp(),
Rcpp::_["Op_sqrt"] = Eigen::ArrayXd::LinSpaced(6, 1, 10).sqrt(),
Rcpp::_["Op_cos"] = Eigen::ArrayXd::LinSpaced(6, 1, 10).cos()
);
Rcpp::List output = Rcpp::List::create(
Rcpp::_["vectors : VectorX<T>"] = vecs,
Rcpp::_["matrices : MatrixX<T>"] = matrices,
Rcpp::_["rows : RowVectorX<T>"] = rows,
Rcpp::_["columns : MatrixX<T>"] = cols,
Rcpp::_["arrays2d : ArrayXX<T>"] = arrays2,
Rcpp::_["arrays1d : ArrayX<T>"] = arrays1,
Rcpp::_["operations : ArrayXd"] = operations
);
return output ;
}
// [[Rcpp::export]]
Rcpp::List fx2(Rcpp::List input) {
Eigen::VectorXi m1 = input[0] ; /* implicit as */
Eigen::VectorXd m2 = input[1] ; /* implicit as */
Eigen::Matrix<unsigned int, Eigen::Dynamic, 1> m3 = input[0] ; /* implicit as */
Eigen::VectorXf m4 = input[1] ; /* implicit as */
Rcpp::List res = Rcpp::List::create(m1.sum(), m2.sum(), m3.sum(), m4.sum());
return res ;
}
// [[Rcpp::export]]
Rcpp::List fx3(Rcpp::List input) {
const Eigen::Map<Eigen::VectorXi> m1 = input[0] ; // maps share storage and do not allow conversion
const Eigen::Map<Eigen::VectorXd> m2 = input[1] ;
Rcpp::List res = Rcpp::List::create(m1.sum(), m2.sum());
return res ;
}
// [[Rcpp::export]]
Rcpp::List fx4(Rcpp::List input) {
const Eigen::Map<Eigen::RowVectorXi> m1 = input[0] ; // maps share storage, do not allow conversion
const Eigen::Map<Eigen::RowVectorXd> m2 = input[1] ;
Rcpp::List res = Rcpp::List::create(m1.sum(), m2.sum());
return res ;
}
// [[Rcpp::export]]
Rcpp::List fx5(Rcpp::List input) {
const Eigen::Map<Eigen::MatrixXi> m1 = input[0]; // maps share storage, do not allow conversion
const Eigen::Map<Eigen::MatrixXd> m2 = input[1] ;
// FIXME: Write a version of as specifically for complex matrices.
// const Eigen::Map<Eigen::MatrixXcd> m3 = input[2] ;
Rcpp::List res = Rcpp::List::create(m1.sum(), m2.sum());//, m3.sum());
return res ;
}
// [[Rcpp::export]]
Rcpp::List fx6(Rcpp::List input) {
const Eigen::MappedSparseMatrix<double> m1 = input[0]; // maps share storage and do not allow conversion
Rcpp::List res = Rcpp::List::create(Rcpp::_["nnz"] = double(m1.nonZeros()),
Rcpp::_["nr"] = double(m1.rows()),
Rcpp::_["nc"] = double(m1.cols()),
Rcpp::_["inSz"] = double(m1.innerSize()),
Rcpp::_["outSz"] = double(m1.outerSize()),
Rcpp::_["sum"] = m1.sum());
return res ;
}
// [[Rcpp::export]]
Rcpp::List fx7(Rcpp::List input) {
const Eigen::SparseMatrix<double> m1 = input[0];
Rcpp::List res = Rcpp::List::create(Rcpp::_["nnz"] = double(m1.nonZeros()),
Rcpp::_["nr"] = double(m1.rows()),
Rcpp::_["nc"] = double(m1.cols()),
Rcpp::_["inSz"] = double(m1.innerSize()),
Rcpp::_["outSz"] = double(m1.outerSize()),
Rcpp::_["sum"] = m1.sum());
return res ;
}
| 40.727848 | 109 | 0.540948 | [
"object",
"vector"
] |
d1809ff5985edf1cf6a5ed1154402d605f12231f | 14,739 | cpp | C++ | test/test_iostream01.cpp | sgothel/jaucpp | c2dbc8cb9fc2752afdbe2b4734650af0ac3fdd4d | [
"MIT"
] | 1 | 2020-12-02T18:14:10.000Z | 2020-12-02T18:14:10.000Z | test/test_iostream01.cpp | sgothel/jaucpp | c2dbc8cb9fc2752afdbe2b4734650af0ac3fdd4d | [
"MIT"
] | null | null | null | test/test_iostream01.cpp | sgothel/jaucpp | c2dbc8cb9fc2752afdbe2b4734650af0ac3fdd4d | [
"MIT"
] | null | null | null | /*
* Author: Sven Gothel <sgothel@jausoft.com>
* Copyright (c) 2021 Gothel Software e.K.
* Copyright (c) 2021 ZAFENA AB
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <iostream>
#include <cassert>
#include <cinttypes>
#include <cstring>
#include <fstream>
#include <iostream>
#include <thread>
#include <pthread.h>
#define CATCH_CONFIG_RUNNER
// #define CATCH_CONFIG_MAIN
#include <catch2/catch_amalgamated.hpp>
#include <jau/test/catch2_ext.hpp>
#include <jau/file_util.hpp>
#include <jau/io_util.hpp>
#include <jau/debug.hpp>
extern "C" {
#include <unistd.h>
}
using namespace jau::fractions_i64_literals;
class TestIOStream01 {
public:
const std::string url_input_root = "http://localhost:8080/";
const std::string basename_10kiB = "testfile_data_10kiB.bin";
TestIOStream01() {
// produce fresh demo data
jau::fs::remove(basename_10kiB, false /* recursive */);
{
std::string one_line = "Hello World, this is a test and I like it. Exactly 100 characters long. 0123456780 abcdefghjklmnop..";
std::ofstream ofs(basename_10kiB, std::ios::out | std::ios::binary);
REQUIRE( ofs.good() == true );
REQUIRE( ofs.is_open() == true );
for(int i=0; i < 1024*10; i+=one_line.size()) { // 10kiB
ofs.write(reinterpret_cast<char*>(one_line.data()), one_line.size());
}
}
std::system("killall mini_httpd");
const std::string cwd = jau::fs::get_cwd();
const std::string cmd = "/usr/sbin/mini_httpd -p 8080 -l "+cwd+"/mini_httpd.log";
jau::PLAIN_PRINT(true, "%s", cmd.c_str());
std::system(cmd.c_str());
}
~TestIOStream01() {
std::system("killall mini_httpd");
}
void test00_protocols() {
{
std::vector<std::string_view> protos = jau::io::uri::supported_protocols();
jau::PLAIN_PRINT(true, "test00_protocols: Supported protocols: %zu: %s", protos.size(), jau::to_string(protos, ",").c_str());
REQUIRE( 0 < protos.size() );
}
{
const std::string url = url_input_root + basename_10kiB;
REQUIRE( false == jau::io::uri::is_local_file_protocol(url) );
REQUIRE( true == jau::io::uri::protocol_supported(url) );
}
{
const std::string url = "https://localhost:8080/" + basename_10kiB;
REQUIRE( false == jau::io::uri::is_local_file_protocol(url) );
REQUIRE( true == jau::io::uri::protocol_supported(url) );
}
{
const std::string url = "file://" + basename_10kiB;
REQUIRE( true == jau::io::uri::is_local_file_protocol(url) );
REQUIRE( true == jau::io::uri::protocol_supported(url) );
}
{
const std::string url = "lala://localhost:8080/" + basename_10kiB;
REQUIRE( false == jau::io::uri::is_local_file_protocol(url) );
REQUIRE( false == jau::io::uri::protocol_supported(url) );
}
{
// sync read_url_stream w/ unknown protocol
const std::string url = "lala://localhost:8080/" + basename_10kiB;
jau::io::secure_vector<uint8_t> buffer(4096);
size_t consumed_calls = 0;
uint64_t consumed_total_bytes = 0;
jau::io::StreamConsumerFunc consume = [&](jau::io::secure_vector<uint8_t>& data, bool is_final) noexcept -> bool {
(void)is_final;
consumed_calls++;
consumed_total_bytes += data.size();
return true;
};
uint64_t http_total_bytes = jau::io::read_url_stream(url, buffer, consume);
REQUIRE( 0 == http_total_bytes );
REQUIRE( consumed_total_bytes == http_total_bytes );
REQUIRE( 0 == consumed_calls );
}
{
// async read_url_stream w/ unknown protocol
const std::string url = "lala://localhost:8080/" + basename_10kiB;
jau::io::ByteRingbuffer rb(0x00, jau::io::BEST_URLSTREAM_RINGBUFFER_SIZE);
jau::relaxed_atomic_bool url_has_content_length;
jau::relaxed_atomic_uint64 url_content_length;
jau::relaxed_atomic_uint64 url_total_read;
jau::io::relaxed_atomic_async_io_result_t result;
std::unique_ptr<std::thread> http_thread = jau::io::read_url_stream(url, rb, url_has_content_length, url_content_length, url_total_read, result);
REQUIRE( nullptr == http_thread );
REQUIRE( url_has_content_length == false );
REQUIRE( url_content_length == 0 );
REQUIRE( url_content_length == url_total_read );
REQUIRE( jau::io::async_io_result_t::FAILED == result );
}
}
void test01_sync_ok() {
const jau::fs::file_stats in_stats(basename_10kiB);
const size_t file_size = in_stats.size();
const std::string url_input = url_input_root + basename_10kiB;
std::ofstream outfile("testfile01_01_out.bin", std::ios::out | std::ios::binary);
REQUIRE( outfile.good() );
REQUIRE( outfile.is_open() );
jau::io::secure_vector<uint8_t> buffer(4096);
size_t consumed_calls = 0;
uint64_t consumed_total_bytes = 0;
jau::io::StreamConsumerFunc consume = [&](jau::io::secure_vector<uint8_t>& data, bool is_final) noexcept -> bool {
consumed_calls++;
consumed_total_bytes += data.size();
outfile.write(reinterpret_cast<char*>(data.data()), data.size());
jau::PLAIN_PRINT(true, "test01_sync_ok #%zu: consumed size %zu, total %" PRIu64 ", capacity %zu, final %d",
consumed_calls, data.size(), consumed_total_bytes, data.capacity(), is_final );
return true;
};
uint64_t http_total_bytes = jau::io::read_url_stream(url_input, buffer, consume);
const uint64_t out_bytes_total = outfile.tellp();
jau::PLAIN_PRINT(true, "test01_sync_ok Done: total %" PRIu64 ", capacity %zu", consumed_total_bytes, buffer.capacity());
REQUIRE( file_size == http_total_bytes );
REQUIRE( consumed_total_bytes == http_total_bytes );
REQUIRE( consumed_total_bytes == out_bytes_total );
}
void test02_sync_404() {
const std::string url_input = url_input_root + "doesnt_exists.txt";
std::ofstream outfile("testfile02_01_out.bin", std::ios::out | std::ios::binary);
REQUIRE( outfile.good() );
REQUIRE( outfile.is_open() );
jau::io::secure_vector<uint8_t> buffer(4096);
size_t consumed_calls = 0;
uint64_t consumed_total_bytes = 0;
jau::io::StreamConsumerFunc consume = [&](jau::io::secure_vector<uint8_t>& data, bool is_final) noexcept -> bool {
consumed_calls++;
consumed_total_bytes += data.size();
outfile.write(reinterpret_cast<char*>(data.data()), data.size());
jau::PLAIN_PRINT(true, "test02_sync_404 #%zu: consumed size %zu, total %" PRIu64 ", capacity %zu, final %d",
consumed_calls, data.size(), consumed_total_bytes, data.capacity(), is_final );
return true;
};
uint64_t http_total_bytes = jau::io::read_url_stream(url_input, buffer, consume);
const uint64_t out_bytes_total = outfile.tellp();
jau::PLAIN_PRINT(true, "test02_sync_404 Done: total %" PRIu64 ", capacity %zu", consumed_total_bytes, buffer.capacity());
REQUIRE( 0 == http_total_bytes );
REQUIRE( consumed_total_bytes == http_total_bytes );
REQUIRE( consumed_total_bytes == out_bytes_total );
}
void test11_async_ok() {
const jau::fs::file_stats in_stats(basename_10kiB);
const size_t file_size = in_stats.size();
const std::string url_input = url_input_root + basename_10kiB;
std::ofstream outfile("testfile11_01_out.bin", std::ios::out | std::ios::binary);
REQUIRE( outfile.good() );
REQUIRE( outfile.is_open() );
constexpr const size_t buffer_size = 4096;
jau::io::ByteRingbuffer rb(0x00, jau::io::BEST_URLSTREAM_RINGBUFFER_SIZE);
jau::relaxed_atomic_bool url_has_content_length;
jau::relaxed_atomic_uint64 url_content_length;
jau::relaxed_atomic_uint64 url_total_read;
jau::io::relaxed_atomic_async_io_result_t result;
std::unique_ptr<std::thread> http_thread = jau::io::read_url_stream(url_input, rb, url_has_content_length, url_content_length, url_total_read, result);
REQUIRE( nullptr != http_thread );
jau::io::secure_vector<uint8_t> buffer(buffer_size);
size_t consumed_loops = 0;
uint64_t consumed_total_bytes = 0;
while( jau::io::async_io_result_t::NONE == result || !rb.isEmpty() ) {
consumed_loops++;
// const size_t consumed_bytes = content_length >= 0 ? std::min(buffer_size, content_length - consumed_total_bytes) : rb.getSize();
const size_t consumed_bytes = rb.getBlocking(buffer.data(), buffer_size, 1, 500_ms);
consumed_total_bytes += consumed_bytes;
jau::PLAIN_PRINT(true, "test11_async_ok.0 #%zu: consumed[this %zu, total %" PRIu64 ", result %d, rb %s",
consumed_loops, consumed_bytes, consumed_total_bytes, result.load(), rb.toString().c_str() );
outfile.write(reinterpret_cast<char*>(buffer.data()), consumed_bytes);
}
const uint64_t out_bytes_total = outfile.tellp();
jau::PLAIN_PRINT(true, "test11_async_ok.X Done: total %" PRIu64 ", result %d, rb %s",
consumed_total_bytes, (int)result.load(), rb.toString().c_str() );
http_thread->join();
REQUIRE( url_has_content_length == true );
REQUIRE( url_content_length == file_size );
REQUIRE( url_content_length == consumed_total_bytes );
REQUIRE( url_content_length == url_total_read );
REQUIRE( url_content_length == out_bytes_total );
REQUIRE( jau::io::async_io_result_t::SUCCESS == result );
}
void test12_async_404() {
const std::string url_input = url_input_root + "doesnt_exists.txt";
std::ofstream outfile("testfile12_01_out.bin", std::ios::out | std::ios::binary);
REQUIRE( outfile.good() );
REQUIRE( outfile.is_open() );
constexpr const size_t buffer_size = 4096;
jau::io::ByteRingbuffer rb(0x00, jau::io::BEST_URLSTREAM_RINGBUFFER_SIZE);
jau::relaxed_atomic_bool url_has_content_length;
jau::relaxed_atomic_uint64 url_content_length;
jau::relaxed_atomic_uint64 url_total_read;
jau::io::relaxed_atomic_async_io_result_t result;
std::unique_ptr<std::thread> http_thread = jau::io::read_url_stream(url_input, rb, url_has_content_length, url_content_length, url_total_read, result);
REQUIRE( nullptr != http_thread );
jau::io::secure_vector<uint8_t> buffer(buffer_size);
size_t consumed_loops = 0;
uint64_t consumed_total_bytes = 0;
while( jau::io::async_io_result_t::NONE == result || !rb.isEmpty() ) {
consumed_loops++;
// const size_t consumed_bytes = content_length >= 0 ? std::min(buffer_size, content_length - consumed_total_bytes) : rb.getSize();
const size_t consumed_bytes = rb.getBlocking(buffer.data(), buffer_size, 1, 500_ms);
consumed_total_bytes += consumed_bytes;
jau::PLAIN_PRINT(true, "test12_async_404.0 #%zu: consumed[this %zu, total %" PRIu64 ", result %d, rb %s",
consumed_loops, consumed_bytes, consumed_total_bytes, result.load(), rb.toString().c_str() );
outfile.write(reinterpret_cast<char*>(buffer.data()), consumed_bytes);
}
const uint64_t out_bytes_total = outfile.tellp();
jau::PLAIN_PRINT(true, "test12_async_404.X Done: total %" PRIu64 ", result %d, rb %s",
consumed_total_bytes, (int)result.load(), rb.toString().c_str() );
http_thread->join();
REQUIRE( url_has_content_length == false );
REQUIRE( url_content_length == 0 );
REQUIRE( url_content_length == consumed_total_bytes );
REQUIRE( url_content_length == url_total_read );
REQUIRE( url_content_length == out_bytes_total );
REQUIRE( jau::io::async_io_result_t::FAILED == result );
}
};
METHOD_AS_TEST_CASE( TestIOStream01::test00_protocols, "TestIOStream01 - test00_protocols");
METHOD_AS_TEST_CASE( TestIOStream01::test01_sync_ok, "TestIOStream01 - test01_sync_ok");
METHOD_AS_TEST_CASE( TestIOStream01::test02_sync_404, "TestIOStream01 - test02_sync_404");
METHOD_AS_TEST_CASE( TestIOStream01::test11_async_ok, "TestIOStream01 - test11_async_ok");
METHOD_AS_TEST_CASE( TestIOStream01::test12_async_404, "TestIOStream01 - test12_async_404");
| 49.13 | 163 | 0.612185 | [
"vector"
] |
d183961cbfce6ea2ce0c92446c19ecb669bd2d74 | 5,765 | cpp | C++ | Classes/Objects/DynamicGameObject.cpp | HoangTrongMinhDuc/JMOK-Game | bd06a8dc166805de0709c61b4acdfcd89b9b3ff8 | [
"MIT"
] | 1 | 2019-07-11T08:06:06.000Z | 2019-07-11T08:06:06.000Z | Classes/Objects/DynamicGameObject.cpp | HoangTrongMinhDuc/JOMK-Game | bd06a8dc166805de0709c61b4acdfcd89b9b3ff8 | [
"MIT"
] | null | null | null | Classes/Objects/DynamicGameObject.cpp | HoangTrongMinhDuc/JOMK-Game | bd06a8dc166805de0709c61b4acdfcd89b9b3ff8 | [
"MIT"
] | 1 | 2021-09-13T12:00:12.000Z | 2021-09-13T12:00:12.000Z | #include "Objects\DynamicGameObject.h"
#include "Helper\TraceImageHelper.h"
DynamicGameObject::DynamicGameObject(string direct) {
string content = FileUtils::getInstance()
->getStringFromFile(direct);
rapidjson::Document document;
document.Parse<0>(content.c_str());
string plistDirect = document["Direct"].GetString();
SpriteFrameCache::getInstance()->addSpriteFramesWithFile(plistDirect);
string defaultImageDirect = document["Default"].GetString();
m_sprite = Sprite::createWithSpriteFrameName(defaultImageDirect);
m_sprite->retain();
m_physicsBodyManager = NULL;
auto value = document.FindMember("PhysicsBodyDirect");
if (value != document.MemberEnd())
m_physicsBodyManager = new PhysicsBodyManager(document["PhysicsBodyDirect"].GetString());
int tag = 1;
for (rapidjson::Value::ConstMemberIterator it = document["Data"].MemberBegin();
it != document["Data"].MemberEnd(); ++it)
{
Vector<SpriteFrame*> animFrames;
string prefix = it->value["Prefix"].GetString(); // Get direct of image
float delay = it->value["Delay"].GetFloat(); // Get delay
int maxIndex = it->value["MaxIndex"].GetInt();
int tag = it->value["Tag"].GetInt();
for (int i = 1; i <= maxIndex; i++) {
string dir = StringUtils::format("%s%d.png", prefix.c_str(), i);
auto frame = SpriteFrameCache::getInstance()->getSpriteFrameByName(dir);
animFrames.pushBack(frame);
if (m_physicsBodyManager != NULL) {
if (defaultImageDirect == dir)
m_physicsBodyManager->setDefaultFrame(frame);
m_physicsBodyManager->add(frame, dir);
}
}
// Create one action
auto animation = Animation::createWithSpriteFrames(animFrames, delay);
//animation->setRestoreOriginalFrame(true);
auto animate = Animate::create(animation);
m_actions[tag] = Repeat::create(animate, 1);
m_actions[tag]->retain();
m_actions[tag]->setTag(tag);
string actionName = it->name.GetString();
m_actionNames[tag] = actionName;
m_actionPriority[tag] = -1;
}
SpriteFrameCache::getInstance()->removeSpriteFramesFromFile(plistDirect);
// init variables
m_countToUpdatePhysicsBody = 0;
SpriteFrameCache::getInstance()->removeSpriteFramesFromFile(plistDirect);
}
void DynamicGameObject::runAction(int actionTag)
{
if (m_sprite->getNumberOfRunningActions() == 0)
m_sprite->runAction(m_actions[actionTag]);
else {
if (m_sprite->getActionByTag(actionTag) == NULL) {
int currentPriority = m_actionPriority[actionTag];
bool isStopAll = true;
for (auto it = m_actions.begin(); it != m_actions.end(); ++it) {
int otherAction = it->first;
if (m_sprite->getActionByTag(otherAction) != NULL
&& m_actionPriority[otherAction] > currentPriority) {
isStopAll = false;
break;
}
}
if (isStopAll) {
m_sprite->stopAllActions();
m_sprite->runAction(m_actions[actionTag]);
}
}
}
}
void DynamicGameObject::runActionWithCallBack(int actionTag, CallFunc *callBack)
{
Sequence *seq = Sequence::create(m_actions[actionTag], callBack, nullptr);
seq->setTag(actionTag);
if (m_sprite->getNumberOfRunningActions() == 0)
m_sprite->runAction(seq);
else {
if (m_sprite->getActionByTag(actionTag) == NULL) {
int currentPriority = m_actionPriority[actionTag];
bool isStopAll = true;
for (auto it = m_actions.begin(); it != m_actions.end(); ++it) {
int otherAction = it->first;
if (m_sprite->getActionByTag(otherAction) != NULL
&& m_actionPriority[otherAction] > currentPriority) {
isStopAll = false;
break;
}
}
if (isStopAll) {
m_sprite->stopAllActions();
m_sprite->runAction(seq);
}
}
}
}
bool DynamicGameObject::isRunningAction(int actionTag)
{
return m_sprite->getActionByTag(actionTag) != NULL;
}
void DynamicGameObject::update(float deltaTime)
{
if (m_physicsBodyManager != NULL) {
if (m_countToUpdatePhysicsBody <= 1)
m_countToUpdatePhysicsBody++;
if (m_countToUpdatePhysicsBody > 1) {
SpriteFrame *sf = m_sprite->getSpriteFrame();
bool flipped = m_sprite->isFlippedX();
if (sf != NULL) {
if (sf != m_currentFrame) {
b2Body *pb = m_physicsBodyManager->get(sf, m_sprite->isFlippedX());
if (pb == NULL)
if (flipped != m_flippedFrame) {
sf = m_currentFrame;
pb = m_physicsBodyManager->get(m_currentFrame, flipped);
}
if (pb != NULL) {
if (m_physicsBody != NULL) {
auto vec = m_physicsBody->GetLinearVelocity();
pb->SetLinearVelocity(vec);
pb->SetTransform(m_physicsBody->GetPosition(), 0);
pb->SetType(m_physicsBody->GetType());
m_physicsWorld->DestroyBody(m_physicsBody);
}
m_countToUpdatePhysicsBody = 0;
m_physicsBody = pb;
m_physicsBody->SetUserData((void*)this);
m_currentFrame = sf;
m_flippedFrame = flipped;
}
}
}
else
if (m_physicsBody != NULL)
m_physicsWorld->DestroyBody(m_physicsBody);
}
}
GameObject::update(deltaTime);
}
void DynamicGameObject::createPhysicsBody(b2World *physicsWorld)
{
if (m_physicsBodyManager == NULL)
GameObject::createPhysicsBody(physicsWorld);
else {
m_physicsWorld = physicsWorld;
m_physicsBodyManager->setPhysicsWorld(physicsWorld);
m_physicsBody = m_physicsBodyManager->getDefault(m_sprite->isFlippedX());
auto pos = b2Helper::asb2Vec2(getPosition());
m_physicsBody->SetTransform(pos, 0);
m_physicsBody->SetUserData(this);
}
}
string DynamicGameObject::getActionName(int actionTag)
{
return m_actionNames[actionTag];
}
void DynamicGameObject::setActionPriority(int actionTag, int priority)
{
m_actionPriority[actionTag] = priority;
}
DynamicGameObject::~DynamicGameObject()
{
for (auto it = m_actions.begin(); it != m_actions.end(); ++it)
it->second->release();
delete m_physicsBodyManager;
} | 28.399015 | 91 | 0.701127 | [
"vector"
] |
d183a10b741f1187e5e3e1412cb7808655a3ab1c | 7,530 | cpp | C++ | kaolin/graphics/nmr/cuda/rasterize_cuda.cpp | Bob-Yeah/kaolin | 7ad34f8158000499a30b8dfa14fb3ed86d2e57a6 | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2020-07-21T16:02:47.000Z | 2020-07-21T16:02:47.000Z | kaolin/graphics/nmr/cuda/rasterize_cuda.cpp | Bob-Yeah/kaolin | 7ad34f8158000499a30b8dfa14fb3ed86d2e57a6 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | kaolin/graphics/nmr/cuda/rasterize_cuda.cpp | Bob-Yeah/kaolin | 7ad34f8158000499a30b8dfa14fb3ed86d2e57a6 | [
"ECL-2.0",
"Apache-2.0"
] | 2 | 2021-08-10T09:19:19.000Z | 2021-11-12T08:18:17.000Z | // MIT License
// Copyright (c) 2017 Hiroharu Kato
// Copyright (c) 2018 Nikos Kolotouros
// A PyTorch implementation of Neural 3D Mesh Renderer (https://github.com/hiroharu-kato/neural_renderer)
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include <torch/torch.h>
#include <vector>
// CUDA forward declarations
std::vector<at::Tensor> forward_face_index_map_cuda(
at::Tensor faces,
at::Tensor face_index_map,
at::Tensor weight_map,
at::Tensor depth_map,
at::Tensor face_inv_map,
at::Tensor faces_inv,
int image_size,
float near,
float far,
int return_rgb,
int return_alpha,
int return_depth);
std::vector<at::Tensor> forward_texture_sampling_cuda(
at::Tensor faces,
at::Tensor textures,
at::Tensor face_index_map,
at::Tensor weight_map,
at::Tensor depth_map,
at::Tensor rgb_map,
at::Tensor sampling_index_map,
at::Tensor sampling_weight_map,
int image_size,
float eps);
at::Tensor backward_pixel_map_cuda(
at::Tensor faces,
at::Tensor face_index_map,
at::Tensor rgb_map,
at::Tensor alpha_map,
at::Tensor grad_rgb_map,
at::Tensor grad_alpha_map,
at::Tensor grad_faces,
int image_size,
float eps,
int return_rgb,
int return_alpha);
at::Tensor backward_textures_cuda(
at::Tensor face_index_map,
at::Tensor sampling_weight_map,
at::Tensor sampling_index_map,
at::Tensor grad_rgb_map,
at::Tensor grad_textures,
int num_faces);
at::Tensor backward_depth_map_cuda(
at::Tensor faces,
at::Tensor depth_map,
at::Tensor face_index_map,
at::Tensor face_inv_map,
at::Tensor weight_map,
at::Tensor grad_depth_map,
at::Tensor grad_faces,
int image_size);
// C++ interface
#define CHECK_CUDA(x) TORCH_CHECK(x.type().is_cuda(), #x " must be a CUDA tensor")
#define CHECK_CONTIGUOUS(x) TORCH_CHECK(x.is_contiguous(), #x " must be contiguous")
#define CHECK_INPUT(x) CHECK_CUDA(x); CHECK_CONTIGUOUS(x)
std::vector<at::Tensor> forward_face_index_map(
at::Tensor faces,
at::Tensor face_index_map,
at::Tensor weight_map,
at::Tensor depth_map,
at::Tensor face_inv_map,
at::Tensor faces_inv,
int image_size,
float near,
float far,
int return_rgb,
int return_alpha,
int return_depth) {
CHECK_INPUT(faces);
CHECK_INPUT(face_index_map);
CHECK_INPUT(weight_map);
CHECK_INPUT(depth_map);
CHECK_INPUT(face_inv_map);
CHECK_INPUT(faces_inv);
return forward_face_index_map_cuda(faces, face_index_map, weight_map,
depth_map, face_inv_map, faces_inv,
image_size, near, far,
return_rgb, return_alpha, return_depth);
}
std::vector<at::Tensor> forward_texture_sampling(
at::Tensor faces,
at::Tensor textures,
at::Tensor face_index_map,
at::Tensor weight_map,
at::Tensor depth_map,
at::Tensor rgb_map,
at::Tensor sampling_index_map,
at::Tensor sampling_weight_map,
int image_size,
float eps) {
CHECK_INPUT(faces);
CHECK_INPUT(textures);
CHECK_INPUT(face_index_map);
CHECK_INPUT(weight_map);
CHECK_INPUT(depth_map);
CHECK_INPUT(rgb_map);
CHECK_INPUT(sampling_index_map);
CHECK_INPUT(sampling_weight_map);
return forward_texture_sampling_cuda(faces, textures, face_index_map,
weight_map, depth_map, rgb_map,
sampling_index_map, sampling_weight_map,
image_size, eps);
}
at::Tensor backward_pixel_map(
at::Tensor faces,
at::Tensor face_index_map,
at::Tensor rgb_map,
at::Tensor alpha_map,
at::Tensor grad_rgb_map,
at::Tensor grad_alpha_map,
at::Tensor grad_faces,
int image_size,
float eps,
int return_rgb,
int return_alpha) {
CHECK_INPUT(faces);
CHECK_INPUT(face_index_map);
CHECK_INPUT(rgb_map);
CHECK_INPUT(alpha_map);
CHECK_INPUT(grad_rgb_map);
CHECK_INPUT(grad_alpha_map);
CHECK_INPUT(grad_faces);
return backward_pixel_map_cuda(faces, face_index_map, rgb_map, alpha_map,
grad_rgb_map, grad_alpha_map, grad_faces,
image_size, eps, return_rgb, return_alpha);
}
at::Tensor backward_textures(
at::Tensor face_index_map,
at::Tensor sampling_weight_map,
at::Tensor sampling_index_map,
at::Tensor grad_rgb_map,
at::Tensor grad_textures,
int num_faces) {
CHECK_INPUT(face_index_map);
CHECK_INPUT(sampling_weight_map);
CHECK_INPUT(sampling_index_map);
CHECK_INPUT(grad_rgb_map);
CHECK_INPUT(grad_textures);
return backward_textures_cuda(face_index_map, sampling_weight_map,
sampling_index_map, grad_rgb_map,
grad_textures, num_faces);
}
at::Tensor backward_depth_map(
at::Tensor faces,
at::Tensor depth_map,
at::Tensor face_index_map,
at::Tensor face_inv_map,
at::Tensor weight_map,
at::Tensor grad_depth_map,
at::Tensor grad_faces,
int image_size) {
CHECK_INPUT(faces);
CHECK_INPUT(depth_map);
CHECK_INPUT(face_index_map);
CHECK_INPUT(face_inv_map);
CHECK_INPUT(weight_map);
CHECK_INPUT(grad_depth_map);
CHECK_INPUT(grad_faces);
return backward_depth_map_cuda(faces, depth_map, face_index_map,
face_inv_map, weight_map,
grad_depth_map, grad_faces,
image_size);
}
PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
m.def("forward_face_index_map", &forward_face_index_map, "FORWARD_FACE_INDEX_MAP (CUDA)");
m.def("forward_texture_sampling", &forward_texture_sampling, "FORWARD_TEXTURE_SAMPLING (CUDA)");
m.def("backward_pixel_map", &backward_pixel_map, "BACKWARD_PIXEL_MAP (CUDA)");
m.def("backward_textures", &backward_textures, "BACKWARD_TEXTURES (CUDA)");
m.def("backward_depth_map", &backward_depth_map, "BACKWARD_DEPTH_MAP (CUDA)");
}
| 33.616071 | 105 | 0.65073 | [
"mesh",
"vector",
"3d"
] |
d18699aa4cf59298f7a1178bbfcfdd93913bda1f | 37,060 | cpp | C++ | carma-messenger-core/cpp_message/src/SPAT_Message.cpp | usdot-fhwa-stol/carma-messenger | 83bad366d80c6124e52dd6ac7b6d3da38a918456 | [
"Apache-2.0"
] | 13 | 2019-12-13T11:51:38.000Z | 2021-04-22T21:16:22.000Z | carma-messenger-core/cpp_message/src/SPAT_Message.cpp | usdot-fhwa-stol/carma-messenger | 83bad366d80c6124e52dd6ac7b6d3da38a918456 | [
"Apache-2.0"
] | 28 | 2020-03-25T00:36:52.000Z | 2022-02-04T15:23:28.000Z | carma-messenger-core/cpp_message/src/SPAT_Message.cpp | usdot-fhwa-stol/carma-messenger | 83bad366d80c6124e52dd6ac7b6d3da38a918456 | [
"Apache-2.0"
] | 8 | 2020-02-02T18:42:42.000Z | 2021-11-20T13:32:31.000Z | /*
* Copyright (C) 2021 LEIDOS.
*
* 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.
*/
/**
* CPP File containing SPAT Message method implementations
*/
#include "SPAT_Message.h"
namespace cpp_message
{
//Convert the SPAT j2735 message to cav_msgs
boost::optional<j2735_msgs::SPAT> SPAT_Message::decode_spat_message(std::vector<uint8_t> &binary_array)
{
//Decode the binary message into SPAT message
j2735_msgs::SPAT output;
//decode results - stored in binary array
asn_dec_rval_t rval;
MessageFrame_t *message = nullptr;
//copy from vector to array
size_t len = binary_array.size();
uint8_t buf[len];
std::copy(binary_array.begin(), binary_array.end(), buf);
//use asn1c lib to decode
rval = uper_decode(0, &asn_DEF_MessageFrame, (void **) &message, buf, len, 0, 0);
//if decode success
if (rval.code == RC_OK)
{
//1. Decode time stamp - Minute of the year
long int *minute_of_the_year = new long int;
bool is_time_stamp_exists;
if (message->value.choice.SPAT.timeStamp)
{
is_time_stamp_exists = true;
minute_of_the_year = message->value.choice.SPAT.timeStamp;
}
else
{
is_time_stamp_exists = false;
*minute_of_the_year = DEFAULT_MINUTE_OF_YEAR_;
ROS_DEBUG_STREAM("Minute of the year value doesn't exist, set to Default");
}
output.time_stamp_exists = is_time_stamp_exists;
output.time_stamp = *minute_of_the_year;
//2. Decode name
size_t str_len = 0;
if(message->value.choice.SPAT.name){
std::string name = "";
str_len = message->value.choice.SPAT.name->size;
for (size_t i = 0; i < str_len; i++)
{
name += message->value.choice.SPAT.name->buf[i];
}
output.name_exists = true;
output.name = name;
}
else{
output.name_exists = false;
}
//3. Decode Intersection
j2735_msgs::IntersectionStateList intersections;
//IntersectionStateList is an array of intersectionState - of size 1-32
for (size_t i = 0; i < message->value.choice.SPAT.intersections.list.count; i++)
{
if(!message->value.choice.SPAT.intersections.list.array[i]){
continue;
}
j2735_msgs::IntersectionState intersection;
IntersectionState_t *state = new IntersectionState_t;
state = message->value.choice.SPAT.intersections.list.array[i];
//Decode intersection name
if (state->name)
{
intersection.name_exists = true;
for (size_t j = 0; j < state->name->size; j++)
{
intersection.name += state->name->buf[i];
}
}
else
{
intersection.name_exists = false;
intersection.name = DEFAULT_STRING_;
ROS_DEBUG_STREAM("Intersection name doesn't exist, set to Default");
}
//Decode id
j2735_msgs::IntersectionReferenceID id;
id.id = state->id.id;
if (state->id.region)
{
id.region_exists = true;
id.region = *state->id.region;
}
else
{
id.region_exists = false;
id.region = j2735_msgs::IntersectionReferenceID::REGION_UNAVAILABLE;
ROS_DEBUG_STREAM("Intersection ID doesn't exist, set to Region Unavailable");
}
intersection.id = id;
//Decode Msg count
intersection.revision = state->revision;
//Decode status
int bit_assigned = 0;
for(size_t t = 0;t< state->status.size;t++){
if(state->status.buf[i] == 1){
bit_assigned = t;
break;
}
}
intersection.status.intersection_status_object = bit_assigned;
//Minute of the year
bool moy_exists = false;
if (state->moy)
{
MinuteOfTheYear_t *moy = new MinuteOfTheYear_t;
moy = state->moy;
intersection.moy = *moy;
intersection.moy_exists = true;
}
else
{
intersection.moy_exists = false;
intersection.moy = j2735_msgs::IntersectionState::MOY_INVALID;
ROS_DEBUG_STREAM("Intersection moy doesn't exis, set to MOY_INVALID");
}
//Time stamp
if (state->timeStamp)
{
DSecond_t *time_stamp = new DSecond_t;
time_stamp = state->timeStamp;
intersection.time_stamp = *time_stamp;
intersection.time_stamp_exists = true;
}
else
{
intersection.time_stamp = j2735_msgs::IntersectionState::TIME_STAMP_UNAVAILABLE;
intersection.time_stamp_exists = false;
ROS_DEBUG_STREAM("Intersection time stamp doesn't exist, value set to TIME_STAMP_UNAVAILABLE");
}
//Enabled lanes list
bool enabled_lanes_exists = false;
if (state->enabledLanes)
{
enabled_lanes_exists = true;
j2735_msgs::EnabledLaneList enabled_lanes_list;
for (size_t j = 0; j < state->enabledLanes->list.count; j++)
{
LaneID_t *enabled_lane_id = new LaneID_t;
enabled_lane_id = state->enabledLanes->list.array[j];
enabled_lanes_list.lane_id_list.push_back(*enabled_lane_id);
}
intersection.enabled_lanes = enabled_lanes_list;
}
else{
intersection.enabled_lanes_exists = false;
}
intersection.enabled_lanes_exists = enabled_lanes_exists;
//MovementList
j2735_msgs::MovementList movement_states;
//movement states is an array of Movement states
for (size_t j = 0; j < state->states.list.count; j++)
{
if(!state->states.list.array[j]){
continue;
}
j2735_msgs::MovementState movement_state;
movement_state.movement_name_exists = false;
if (state->states.list.array[j]->movementName)
{
movement_state.movement_name_exists = true;
size_t len = state->states.list.array[j]->movementName->size;
for (int k = 0; k < len; k++)
{
movement_state.movement_name += state->states.list.array[j]->movementName->buf[k];
}
}
//Signal Group ID
movement_state.signal_group = SIGNAL_GROUP_UNAVAILABLE_;
if (state->states.list.array[j]->signalGroup)
{
movement_state.signal_group = state->states.list.array[j]->signalGroup;
}
//State Time Speed Movement Event List
j2735_msgs::MovementEventList movement_event_list;
for (int k = 0; k < state->states.list.array[j]->state_time_speed.list.count; k++)
{
if(!state->states.list.array[j]->state_time_speed.list.array[k]){
continue;
}
j2735_msgs::MovementEvent movement_event;
//Decode movement event
//1. MovementPhaseState
if(state->states.list.array[j]->state_time_speed.list.array[k]->eventState){
movement_event.event_state.movement_phase_state = state->states.list.array[j]->state_time_speed.list.array[k]->eventState;
}
else{
movement_event.event_state.movement_phase_state = j2735_msgs::MovementPhaseState::UNAVAILABLE;
ROS_DEBUG_STREAM("Movement event - event state, value doesn't exist. Set to default UNAVAILABLE");
}
//2. TimeChangeDetails
movement_event.timing_exists = false;
if (state->states.list.array[j]->state_time_speed.list.array[k]->timing)
{
movement_event.timing_exists = true;
j2735_msgs::TimeChangeDetails timing;
timing.start_time_exists = false;
if (state->states.list.array[j]->state_time_speed.list.array[k]->timing->startTime)
{
timing.start_time_exists = true;
DSRC_TimeMark_t *start_time = new DSRC_TimeMark_t;
start_time = state->states.list.array[j]->state_time_speed.list.array[k]->timing->startTime;
timing.start_time = *start_time;
}
timing.min_end_time = state->states.list.array[j]->state_time_speed.list.array[k]->timing->minEndTime;
timing.max_end_time_exists = false;
if (state->states.list.array[j]->state_time_speed.list.array[k]->timing->maxEndTime)
{
timing.max_end_time_exists = true;
DSRC_TimeMark_t *end_time = new DSRC_TimeMark_t;
end_time = state->states.list.array[j]->state_time_speed.list.array[k]->timing->maxEndTime;
timing.max_end_time = *end_time;
}
timing.likely_time_exists = false;
if (state->states.list.array[j]->state_time_speed.list.array[k]->timing->likelyTime)
{
timing.likely_time_exists = true;
DSRC_TimeMark_t *likely_time = new DSRC_TimeMark_t;
likely_time = state->states.list.array[j]->state_time_speed.list.array[k]->timing->likelyTime;
timing.likely_time = *likely_time;
}
timing.confidence_exists = false;
if (state->states.list.array[j]->state_time_speed.list.array[k]->timing->confidence)
{
timing.confidence_exists = true;
TimeIntervalConfidence_t *confidence = new TimeIntervalConfidence_t;
confidence = state->states.list.array[j]->state_time_speed.list.array[k]->timing->confidence;
timing.confidence = *confidence;
}
timing.next_time_exists = false;
if (state->states.list.array[j]->state_time_speed.list.array[k]->timing->nextTime)
{
timing.next_time_exists = true;
DSRC_TimeMark_t *next_time = new DSRC_TimeMark_t;
next_time = state->states.list.array[j]->state_time_speed.list.array[k]->timing->nextTime;
timing.next_time = *next_time;
}
movement_event.timing = timing;
}
//3. Advisory Speed List
movement_event.speeds_exists = false;
if (state->states.list.array[j]->state_time_speed.list.array[k]->speeds)
{
movement_event.speeds_exists = true;
for (size_t l = 0; l < state->states.list.array[j]->state_time_speed.list.array[k]->speeds->list.count; l++)
{
j2735_msgs::AdvisorySpeed advisory_speed;
advisory_speed.type.advisory_speed_type = state->states.list.array[j]->state_time_speed.list.array[k]->speeds->list.array[l]->type;
advisory_speed.speed_exists = false;
if (state->states.list.array[j]->state_time_speed.list.array[k]->speeds->list.array[l]->speed)
{
advisory_speed.speed_exists = true;
SpeedAdvice_t *speed_advice = new SpeedAdvice_t;
speed_advice = state->states.list.array[j]->state_time_speed.list.array[k]->speeds->list.array[l]->speed;
advisory_speed.speed = *speed_advice;
}
else
{
advisory_speed.speed = j2735_msgs::AdvisorySpeed::SPEED_UNAVAILABLE;
ROS_DEBUG_STREAM("Advisory speed- speed doesn't exist, assigned default value speed_unavailable");
}
SpeedConfidence_t *confidence = new SpeedConfidence_t;
confidence = state->states.list.array[j]->state_time_speed.list.array[k]->speeds->list.array[l]->confidence;
advisory_speed.confidence.speed_confidence = *confidence;
advisory_speed.distance_exists = false;
if (state->states.list.array[j]->state_time_speed.list.array[k]->speeds->list.array[l]->distance)
{
advisory_speed.distance_exists = true;
ZoneLength_t *distance = new ZoneLength_t;
distance = state->states.list.array[j]->state_time_speed.list.array[k]->speeds->list.array[l]->distance;
advisory_speed.distance = *distance;
}
else
{
advisory_speed.distance = j2735_msgs::AdvisorySpeed::DISTANCE_UNKNOWN;
ROS_DEBUG_STREAM("Advisory speed - distance, value doesn't exist, set to default distance_unknown");
}
// RESTRICTION CLASS ID not DEFINED in incoming state message
movement_event.speeds.advisory_speed_list.push_back(advisory_speed);
}
}
movement_event_list.movement_event_list.push_back(movement_event);
}
movement_state.state_time_speed.movement_event_list = movement_event_list.movement_event_list;
movement_states.movement_list.push_back(movement_state);
}
intersection.states = movement_states;
//ManeuverAssistList
j2735_msgs::ManeuverAssistList maneuver_assist_list;
bool maneuver_assist_list_exists = false;
if (state->maneuverAssistList)
{
maneuver_assist_list_exists = true;
}
intersection.maneuever_assist_list_exists = maneuver_assist_list_exists;
intersection.maneuever_assist_list = maneuver_assist_list;
output.intersections.intersection_state_list.push_back(intersection);
}
//4. Regional - not implemented yet
return boost::optional<j2735_msgs::SPAT>(output);
}
ROS_WARN_STREAM("SPAT Message decoding failed");
return boost::optional<j2735_msgs::SPAT>{};
}
boost::optional<std::vector<uint8_t>> SPAT_Message::encode_spat_message(const j2735_msgs::SPAT &plainMessage)
{
//encode result placeholder
uint8_t buffer[2048] = {0};
size_t buffer_size = sizeof(buffer);
asn_enc_rval_t ec;
MessageFrame_t* message;
message = (MessageFrame_t*) calloc(1, sizeof(MessageFrame_t));
//if mem allocation fails
if(!message)
{
ROS_WARN_STREAM("Cannot allocate mem for SPAT encoding");
return boost::optional<std::vector<uint8_t>>{};
}
//set message type to SPAT
message->messageId ;
message->value.present = MessageFrame__value_PR_SPAT;
SPAT* spat_msg;
spat_msg = (SPAT*) calloc(1, sizeof(SPAT));
//Encode timestamp
MinuteOfTheYear_t* timestamp = new MinuteOfTheYear_t;
if(plainMessage.time_stamp_exists){
*timestamp = plainMessage.time_stamp;
}
else{
ROS_DEBUG_STREAM("Encoding, Assigning default timestamp");
*timestamp = DEFAULT_TIME_STAMP_;
}
message->value.choice.SPAT.timeStamp = timestamp;
//encode Descriptive Name
std::string name = DEFAULT_STRING_;
if(plainMessage.name_exists){
name = plainMessage.name;
uint8_t string_content[name.size()];
for(size_t i = 0; i < name.size(); i++){
string_content[i] = name[i];
}
message->value.choice.SPAT.name->buf = string_content;
message->value.choice.SPAT.name->size = name.size();
}
else{
ROS_DEBUG_STREAM("Encoding, name doesn't exist");
}
//Encode Intersections
IntersectionStateList_t* intersectionStateList;
intersectionStateList = new IntersectionStateList_t;
for(size_t i = 0; i < plainMessage.intersections.intersection_state_list.size(); i++)
{
IntersectionState_t* intersectionState;
intersectionState = new IntersectionState_t;
if(plainMessage.intersections.intersection_state_list[i].name_exists){
size_t name_string_size = plainMessage.intersections.intersection_state_list[i].name.size();
uint8_t string_content_name[name_string_size];
for(size_t i = 0; i < name_string_size; i++){
string_content_name[i] = plainMessage.intersections.intersection_state_list[i].name[i];
}
intersectionState->name->buf = string_content_name;
intersectionState->name->size = name_string_size;
}
else{
ROS_DEBUG_STREAM("Intersection state name doesn't exist for state "<< i);
}
//No else condition for name doesn't exist
//Intersection ID - bit string - convert from bit string to int16
intersectionState->id.id = plainMessage.intersections.intersection_state_list[i].id.id;
//Encode Revision
intersectionState->revision = plainMessage.intersections.intersection_state_list[i].revision;
//Encode Intersection Status
//Last 2 bits are reserved
uint8_t status_object[16] = {0};
int bit_to_set = plainMessage.intersections.intersection_state_list[i].status.intersection_status_object;
//Set the bit to 1
if(bit_to_set < 14){
status_object[15 - bit_to_set] = 1;
}
intersectionState->status.buf = status_object;
intersectionState->status.size = 16;
//Encode MinuteoftheYear
MinuteOfTheYear_t* minute_of_year = new MinuteOfTheYear_t;
if(plainMessage.intersections.intersection_state_list[i].moy_exists)
{
*minute_of_year = plainMessage.intersections.intersection_state_list[i].moy;
}
else{
*minute_of_year = plainMessage.intersections.intersection_state_list[i].MOY_INVALID;
}
intersectionState->moy = minute_of_year;
//Encode time stamp
DSecond_t* state_time_stamp = new DSecond_t;
if(plainMessage.intersections.intersection_state_list[i].time_stamp_exists){
*state_time_stamp = plainMessage.intersections.intersection_state_list[i].time_stamp;
}
else{
*state_time_stamp = plainMessage.intersections.intersection_state_list[i].TIME_STAMP_UNAVAILABLE;
}
intersectionState->timeStamp = state_time_stamp;
//Encode Enabled lanes
if(plainMessage.intersections.intersection_state_list[i].enabled_lanes_exists){
EnabledLaneList_t* enabled_lanes = new EnabledLaneList_t;
for(size_t j = 0; j < plainMessage.intersections.intersection_state_list[i].enabled_lanes.lane_id_list.size(); j++){
LaneID_t* lane_id = new LaneID_t;
*lane_id = plainMessage.intersections.intersection_state_list[i].enabled_lanes.lane_id_list[j];
asn_sequence_add(&enabled_lanes->list, lane_id);
}
intersectionState->enabledLanes = enabled_lanes;
}
//Movement List - List of movement states
//Encode Movement State
//1. movement name
MovementList_t* movementStateList = new MovementList_t;
//intersectionState->states.list
for(size_t j =0; j < plainMessage.intersections.intersection_state_list[i].states.movement_list.size(); j++){
MovementState_t* movementstate = new MovementState_t;
//Movement name
if(plainMessage.intersections.intersection_state_list[i].states.movement_list[j].movement_name_exists){
size_t movement_name_size = plainMessage.intersections.intersection_state_list[i].states.movement_list[j].movement_name.size();
uint8_t movement_name_array[movement_name_size];
for(size_t k = 0; k < movement_name_size; k++){
movement_name_array[k] = plainMessage.intersections.intersection_state_list[i].states.movement_list[j].movement_name[k];
}
movementstate->movementName->buf = movement_name_array;
movementstate->movementName->size = movement_name_size;
}
//Signal group
if(plainMessage.intersections.intersection_state_list[i].states.movement_list[j].signal_group){
movementstate->signalGroup = plainMessage.intersections.intersection_state_list[i].states.movement_list[j].signal_group;
}
else{
movementstate->signalGroup = DEFAULT_SIGNAL_GROUP_;
}
//Encode State time speed
MovementEventList_t* movement_event_list = new MovementEventList_t;
for(size_t k = 0; k < plainMessage.intersections.intersection_state_list[i].states.movement_list[j].state_time_speed.movement_event_list.size(); k++){
MovementEvent_t* movement_event = new MovementEvent_t;
movement_event->eventState = plainMessage.intersections.intersection_state_list[i].states.movement_list[j].state_time_speed.movement_event_list[k].event_state.movement_phase_state;
//Time Change Details
if(plainMessage.intersections.intersection_state_list[i].states.movement_list[j].state_time_speed.movement_event_list[k].timing_exists){
TimeChangeDetails_t* time_change_details = new TimeChangeDetails_t;
//start time
DSRC_TimeMark_t* state_start_time = new DSRC_TimeMark_t;
if(plainMessage.intersections.intersection_state_list[i].states.movement_list[j].state_time_speed.movement_event_list[k].timing.start_time_exists){
*state_start_time = plainMessage.intersections.intersection_state_list[i].states.movement_list[j].state_time_speed.movement_event_list[k].timing.start_time;
}
else{
*state_start_time = DEFAULT_TIME_MARK_;
}
time_change_details->startTime = state_start_time;
//min_end_time
DSRC_TimeMark_t* state_min_end_time = new DSRC_TimeMark_t;
*state_min_end_time = plainMessage.intersections.intersection_state_list[i].states.movement_list[j].state_time_speed.movement_event_list[k].timing.min_end_time;
time_change_details->minEndTime = *state_min_end_time;
//max end time
DSRC_TimeMark_t* state_max_end_time = new DSRC_TimeMark_t;
if(plainMessage.intersections.intersection_state_list[i].states.movement_list[j].state_time_speed.movement_event_list[k].timing.max_end_time_exists){
*state_max_end_time = plainMessage.intersections.intersection_state_list[i].states.movement_list[j].state_time_speed.movement_event_list[k].timing.max_end_time;
}
else{
*state_max_end_time = DEFAULT_TIME_MARK_;
}
time_change_details->maxEndTime = state_max_end_time;
//likely time
DSRC_TimeMark_t* state_likely_time = new DSRC_TimeMark_t;
if(plainMessage.intersections.intersection_state_list[i].states.movement_list[j].state_time_speed.movement_event_list[k].timing.likely_time_exists){
*state_likely_time = plainMessage.intersections.intersection_state_list[i].states.movement_list[j].state_time_speed.movement_event_list[k].timing.likely_time;
}
else{
*state_likely_time = DEFAULT_TIME_MARK_;
}
time_change_details->likelyTime = state_likely_time;
//confidence
TimeIntervalConfidence_t* state_confidence = new TimeIntervalConfidence_t;
if(plainMessage.intersections.intersection_state_list[i].states.movement_list[j].state_time_speed.movement_event_list[k].timing.confidence_exists){
*state_confidence = plainMessage.intersections.intersection_state_list[i].states.movement_list[j].state_time_speed.movement_event_list[k].timing.confidence;
}
time_change_details->confidence = state_confidence;
//Else condition not defined
//Time Mark
DSRC_TimeMark_t* next_time = new DSRC_TimeMark_t;
if(plainMessage.intersections.intersection_state_list[i].states.movement_list[j].state_time_speed.movement_event_list[k].timing.next_time_exists){
*next_time = plainMessage.intersections.intersection_state_list[i].states.movement_list[j].state_time_speed.movement_event_list[k].timing.next_time;
}
else{
*next_time = DEFAULT_TIME_MARK_;
}
time_change_details->nextTime = next_time;
movement_event->timing = time_change_details;
}
//Advisory Speed List
if(plainMessage.intersections.intersection_state_list[i].states.movement_list[j].state_time_speed.movement_event_list[k].speeds_exists){
//List of Advisory Speed
AdvisorySpeedList_t* advisory_speed_list = new AdvisorySpeedList_t;
for(size_t l = 0; l < plainMessage.intersections.intersection_state_list[i].states.movement_list[j].state_time_speed.movement_event_list[k].speeds.advisory_speed_list.size(); l++){
AdvisorySpeed_t* advisory_speed = new AdvisorySpeed_t;
advisory_speed->type = plainMessage.intersections.intersection_state_list[i].states.movement_list[j].state_time_speed.movement_event_list[k].speeds.advisory_speed_list[l].type.advisory_speed_type;
SpeedAdvice_t* speed_advice = new SpeedAdvice_t;
if(plainMessage.intersections.intersection_state_list[i].states.movement_list[j].state_time_speed.movement_event_list[k].speeds.advisory_speed_list[l].speed_exists){
*speed_advice = plainMessage.intersections.intersection_state_list[i].states.movement_list[j].state_time_speed.movement_event_list[k].speeds.advisory_speed_list[l].speed;
}
else{
*speed_advice = j2735_msgs::AdvisorySpeed::SPEED_UNAVAILABLE;
}
advisory_speed->speed = speed_advice;
//Speed Confidence
SpeedConfidence_t* speed_confidence = new SpeedConfidence_t;
*speed_confidence = plainMessage.intersections.intersection_state_list[i].states.movement_list[j].state_time_speed.movement_event_list[k].speeds.advisory_speed_list[l].confidence.speed_confidence;
advisory_speed->confidence = speed_confidence;
//Zone length
ZoneLength_t* zone_length = new ZoneLength_t;
if(plainMessage.intersections.intersection_state_list[i].states.movement_list[j].state_time_speed.movement_event_list[k].speeds.advisory_speed_list[l].distance_exists){
*zone_length = plainMessage.intersections.intersection_state_list[i].states.movement_list[j].state_time_speed.movement_event_list[k].speeds.advisory_speed_list[l].distance;
}
else{
*zone_length = j2735_msgs::AdvisorySpeed::DISTANCE_UNKNOWN;
}
advisory_speed->distance = zone_length;
//RestrictionClassId
// RESTRICTION CLASS ID not DEFINED in incoming state message
asn_sequence_add(&movement_event->speeds->list, advisory_speed);
}
}
//Regional Extensions are not yet implemented
asn_sequence_add(&movementstate->state_time_speed.list, movement_event);
}
//Maneuver Assist List - A List of Connection Maneuver Assist
if(plainMessage.intersections.intersection_state_list[i].states.movement_list[j].maneuver_assist_list_exists){
ManeuverAssistList_t* maneuver_assist_list = new ManeuverAssistList_t;
size_t maneuver_assist_list_size = plainMessage.intersections.intersection_state_list[i].states.movement_list[j].maneuver_assist_list.connection_maneuver_assist_list.size();
for(size_t k = 0;k < maneuver_assist_list_size; k++){
ConnectionManeuverAssist_t* connection_assist = new ConnectionManeuverAssist_t;
connection_assist->connectionID = plainMessage.intersections.intersection_state_list[i].states.movement_list[j].maneuver_assist_list.connection_maneuver_assist_list[k].connection_id;
ZoneLength_t* zone_length = new ZoneLength_t;
if(plainMessage.intersections.intersection_state_list[i].states.movement_list[j].maneuver_assist_list.connection_maneuver_assist_list[k].queue_length_exists){
//movement_event
*zone_length = plainMessage.intersections.intersection_state_list[i].states.movement_list[j].maneuver_assist_list.connection_maneuver_assist_list[k].queue_length;
}
else{
*zone_length = DEFAULT_QUEUE_LENGTH_;
}
connection_assist->queueLength = zone_length;
if(plainMessage.intersections.intersection_state_list[i].states.movement_list[j].maneuver_assist_list.connection_maneuver_assist_list[k].wait_on_stop_exists){
*connection_assist->waitOnStop = plainMessage.intersections.intersection_state_list[i].states.movement_list[j].maneuver_assist_list.connection_maneuver_assist_list[k].wait_on_stop;
}
else{
*connection_assist->waitOnStop = false;
}
if(plainMessage.intersections.intersection_state_list[i].states.movement_list[j].maneuver_assist_list.connection_maneuver_assist_list[k].ped_bicycle_detect_exists){
*connection_assist->pedBicycleDetect = plainMessage.intersections.intersection_state_list[i].states.movement_list[j].maneuver_assist_list.connection_maneuver_assist_list[k].ped_bicycle_detect;
}
else{
connection_assist->pedBicycleDetect = false;
}
asn_sequence_add(&maneuver_assist_list->list, connection_assist);
}
intersectionState->maneuverAssistList = maneuver_assist_list;
}
asn_sequence_add(&movementStateList->list, movementstate);
} //MovementState ends
intersectionState->states.list = movementStateList->list;
intersectionState->states.list.size = plainMessage.intersections.intersection_state_list[i].states.movement_list.size();
//RegionalExtensions are not yet implemented in asn1c
asn_sequence_add(&intersectionStateList->list, intersectionState);
}
message->value.choice.SPAT.intersections.list = intersectionStateList->list;
message->value.choice.SPAT.intersections.list.size = plainMessage.intersections.intersection_state_list.size();
//encode message
ec = uper_encode_to_buffer(&asn_DEF_MessageFrame, 0 , message, buffer, buffer_size);
//log a warning if that fails
if(ec.encoded == -1) {
ROS_WARN_STREAM("Encoding for SPAT Message failed");
return boost::optional<std::vector<uint8_t>>{};
}
//copy to byte array msg
size_t array_length=(ec.encoded + 7) / 8;
std::vector<uint8_t> b_array(array_length);
for(size_t i=0;i<array_length;i++)b_array[i]=buffer[i];
//for(size_t i = 0; i < array_length; i++) std::cout<< int(b_array[i])<< ", ";
return boost::optional<std::vector<uint8_t>>(b_array);
}
} | 52.867332 | 224 | 0.556017 | [
"vector"
] |
d188a4171e163c88639c2c35cc2e4107c98c21eb | 2,130 | cpp | C++ | 1056.cpp | hgfeaon/PAT | 3210bdab10eba77b69cdfb7a3c68638f9b7af5ac | [
"BSD-3-Clause"
] | null | null | null | 1056.cpp | hgfeaon/PAT | 3210bdab10eba77b69cdfb7a3c68638f9b7af5ac | [
"BSD-3-Clause"
] | null | null | null | 1056.cpp | hgfeaon/PAT | 3210bdab10eba77b69cdfb7a3c68638f9b7af5ac | [
"BSD-3-Clause"
] | null | null | null | #include <cstdio>
#include <climits>
#include <cstdlib>
#include <vector>
#include <list>
using namespace std;
list<int>::iterator group_pick(list<int> &player, list<int>::iterator &cur, int group_size, vector<int> &W) {
int wmax = INT_MIN;
list<int>::iterator ret = player.end();
int cnt = group_size;
//printf("check group:\n\t");
while (cur != player.end() && cnt > 0) {
--cnt;
//printf(" %d(%d)", *cur, W[*cur]);
if (W[*cur] >= wmax) {
wmax = W[*cur];
ret = cur;
}
cur++;
}
//printf("\n");
return ret;
}
int main() {
int N = 0, G = 0;
scanf("%d%d", &N, &G);
if (N < 1) return 0;
vector<int> W(N, 0);
vector<int> R(N, 0);
vector<int> L;
list<int> P;
for (int i=0; i<N; i++) {
scanf("%d", &W[i]);
}
for (int i=0; i<N; i++) {
int t = 0;
scanf("%d", &t);
P.push_back(t);
}
int level = 0;
int level_cnt = 0;
list<int> tmp;
auto cur = P.begin();
// number of elements in P should be larger than 1 to perform reduce processing
while (G > 1 && ++(cur = P.begin()) != P.end()) {
tmp.clear();
auto cur = P.begin();
while (cur != P.end()) {
list<int>::iterator fat = group_pick(P, cur, G, W);
//printf("pick %d\n", *fat);
tmp.splice(tmp.end(), tmp, fat);
}
swap(tmp, P);
auto iter = tmp.begin();
while (iter != tmp.end()) {
R[*(iter++)] = level;
level_cnt++;
}
L.push_back(level_cnt);
level_cnt = 0;
level++;
}
// now there must be only one element in P, the final winner
L.push_back(1);
R[P.front()] = level;
int sum = 0;
for (int i=L.size() - 1; i>=0; i--) {
//printf("level cnt: %d\n", L[i]);
int next_sum = sum + L[i];
L[i] = sum + 1;
sum = next_sum;
}
int len = R.size();
printf("%d", L[R[0]]);
for (int i=1; i<len; i++) {
printf(" %d", L[R[i]]);
}
return 0;
}
| 23.152174 | 109 | 0.452113 | [
"vector"
] |
d18b41bc39cbb2bd5a928abf624e5ebe9ea04ddb | 5,590 | cpp | C++ | OPHD/UI/PopulationPanel.cpp | OutpostUniverse/OPHD | 152d904eb81143e2ad39ffbacae7350cbe8d6456 | [
"BSD-3-Clause"
] | 31 | 2020-03-19T05:27:06.000Z | 2022-03-27T04:29:23.000Z | OPHD/UI/PopulationPanel.cpp | OutpostUniverse/OPHD | 152d904eb81143e2ad39ffbacae7350cbe8d6456 | [
"BSD-3-Clause"
] | 410 | 2020-02-09T05:31:08.000Z | 2022-01-09T02:03:10.000Z | OPHD/UI/PopulationPanel.cpp | OutpostUniverse/OPHD | 152d904eb81143e2ad39ffbacae7350cbe8d6456 | [
"BSD-3-Clause"
] | 9 | 2020-04-21T19:55:29.000Z | 2022-02-05T01:03:54.000Z | #include "PopulationPanel.h"
#include "../Cache.h"
#include "../Common.h"
#include "../Constants.h"
#include "../Population/Population.h"
#include <NAS2D/Utility.h>
#include <NAS2D/Renderer/Renderer.h>
#include <algorithm>
using namespace NAS2D;
static constexpr int IconSize = 32;
static const auto trendIndex = [](int value)
{
return (value >= 0) ? 0 : 1;
};
static const std::array trend
{
Color{0, 185, 0},
Color::Red
};
static int moraleIndex(int morale)
{
return std::clamp(morale, 0, 999) / 200;
}
static const std::array moraleStringColor
{
Color::Red,
Color::Orange,
Color::Yellow,
Color::White,
Color{0, 185, 0}
};
PopulationPanel::PopulationPanel() :
mFont{fontCache.load(constants::FONT_PRIMARY, constants::FontPrimaryNormal)},
mFontBold{fontCache.load(constants::FONT_PRIMARY_BOLD, constants::FontPrimaryNormal)},
mIcons{imageCache.load("ui/icons.png")},
mSkin
{
imageCache.load("ui/skin/window_top_left.png"),
imageCache.load("ui/skin/window_top_middle.png"),
imageCache.load("ui/skin/window_top_right.png"),
imageCache.load("ui/skin/window_middle_left.png"),
imageCache.load("ui/skin/window_middle_middle.png"),
imageCache.load("ui/skin/window_middle_right.png"),
imageCache.load("ui/skin/window_bottom_left.png"),
imageCache.load("ui/skin/window_bottom_middle.png"),
imageCache.load("ui/skin/window_bottom_right.png")
}
{
constexpr int linesOfText = 14;
constexpr int edgeBuffer = constants::Margin * 2;
const int windowHeight = mFontBold.height() + (mFont.height() * linesOfText) + edgeBuffer;
int largestStringLength = mFontBold.width(constants::MoraleBreakdown);
for (int i = 0; i < moraleStringTableCount(); ++i)
{
const int lengthCompare = mFont.width(moraleString(i));
if (lengthCompare > largestStringLength)
{
largestStringLength = lengthCompare;
}
}
largestStringLength += edgeBuffer + mFont.width("999999");
mPopulationPanelWidth = mFontBold.width(constants::PopulationBreakdown) + edgeBuffer;
const int windowWidth = largestStringLength + edgeBuffer + mPopulationPanelWidth;
size({windowWidth, windowHeight});
}
void PopulationPanel::update()
{
auto& renderer = Utility<Renderer>::get();
mSkin.draw(renderer, mRect);
const int fontHeight = mFont.height();
const int fontBoldHeight = mFontBold.height();
auto position = NAS2D::Point{positionX() + constants::Margin, positionY() + constants::Margin};
// POPULATION
renderer.drawText(mFontBold, constants::PopulationBreakdown, position);
const auto population = mPopulation->getPopulations();
const std::array populationData
{
std::tuple{NAS2D::Rectangle{0, 96, IconSize, IconSize}, population.child, std::string("Children")},
std::tuple{NAS2D::Rectangle{32, 96, IconSize, IconSize}, population.student, std::string("Students")},
std::tuple{NAS2D::Rectangle{64, 96, IconSize, IconSize}, population.worker, std::string("Workers")},
std::tuple{NAS2D::Rectangle{96, 96, IconSize, IconSize}, population.scientist, std::string("Scientists")},
std::tuple{NAS2D::Rectangle{128, 96, IconSize, IconSize}, population.retiree, std::string("Retired")},
};
position.y += fontBoldHeight + constants::Margin;
const auto textOffset = NAS2D::Vector{IconSize + constants::Margin, (IconSize / 2) - (fontHeight / 2)};
for (const auto& [imageRect, personCount, personRole] : populationData)
{
renderer.drawSubImage(mIcons, position, imageRect);
const auto roleCount = std::to_string(personCount);
renderer.drawText(mFont, personRole + ": ", position + textOffset);
const NAS2D::Point<int> labelPosition = {positionX() + mPopulationPanelWidth - mFont.width(roleCount) - constants::Margin , position.y + textOffset.y};
renderer.drawText(mFont, roleCount, labelPosition);
position.y += IconSize + constants::Margin;
}
// DIVIDER LINE
position = NAS2D::Point{positionX() + mPopulationPanelWidth, positionY() + constants::Margin};
renderer.drawLine(position, position + NAS2D::Vector<int>{0, rect().height - 10}, Color::DarkGray);
// MORALE
position.x += constants::Margin;
renderer.drawText(mFontBold, constants::MoraleBreakdown, position);
position.y += fontBoldHeight;
const auto moraleLevel = moraleIndex(mMorale);
renderer.drawText(mFont, moraleString(Morale::Description) + moraleString(moraleLevel), position, moraleStringColor[moraleLevel]);
position.y += fontHeight;
renderer.drawText(mFont, "Current: " + std::to_string(mMorale) + " / Previous: " + std::to_string(mPreviousMorale), position);
position.y += fontHeight;
int capacityPercent = (mResidentialCapacity > 0) ? (population.size() * 100 / mResidentialCapacity) : 0;
const auto housingText = "Housing: " + std::to_string(population.size()) + " / " + std::to_string(mResidentialCapacity) + " (" + std::to_string(capacityPercent) + "%)";
renderer.drawText(mFont, housingText, position, NAS2D::Color::White);
position.y += fontHeight;
renderer.drawText(mFont, "Mean Crime Rate: " + std::to_string(mCrimeRate) + "%", position, NAS2D::Color::White);
position.y += fontHeight + fontHeight / 2;
renderer.drawLine(position, position + NAS2D::Vector<int>{rect().width - mPopulationPanelWidth - constants::Margin * 2, 0}, Color::DarkGray);
position.y += fontHeight / 2;
for (auto& item : mMoraleChangeReasons)
{
renderer.drawText(mFont, item.first, position);
const auto text = formatDiff(item.second);
const NAS2D::Point<int> labelPosition = {rect().x + rect().width - mFont.width(text) - 5 , position.y};
renderer.drawText(mFont, text, labelPosition, trend[trendIndex(item.second)]);
position.y += fontHeight;
}
}
| 33.674699 | 170 | 0.728444 | [
"vector"
] |
d18b88213cd64ac5e84a99b9bb1f6971ae73cbfa | 6,064 | cpp | C++ | Source/SystemQOR/MSWindows/WinQL/Application/ErrorSystem/WinQLDOSError.cpp | mfaithfull/QOR | 0fa51789344da482e8c2726309265d56e7271971 | [
"BSL-1.0"
] | 9 | 2016-05-27T01:00:39.000Z | 2021-04-01T08:54:46.000Z | Source/SystemQOR/MSWindows/WinQL/Application/ErrorSystem/WinQLDOSError.cpp | mfaithfull/QOR | 0fa51789344da482e8c2726309265d56e7271971 | [
"BSL-1.0"
] | 1 | 2016-03-03T22:54:08.000Z | 2016-03-03T22:54:08.000Z | Source/SystemQOR/MSWindows/WinQL/Application/ErrorSystem/WinQLDOSError.cpp | mfaithfull/QOR | 0fa51789344da482e8c2726309265d56e7271971 | [
"BSL-1.0"
] | 4 | 2016-05-27T01:00:43.000Z | 2018-08-19T08:47:49.000Z | //WinQLDOSError.cpp
// Copyright Querysoft Limited 2012 - . All rights reserved.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#include "WinQL/Application/ErrorSystem/WinQLDOSError.h"
#include "WinQL/Application/Threading/WinQLThread.h"
#include <errno.h>
//--------------------------------------------------------------------------------
namespace nsWin32
{
//------------------------------------------------------------------------------
CDOSError::errentry CDOSError::errtable[] =
{
{ ErrorInvalidFunction, EINVAL }, /* 1 */
{ ErrorFileNotFound, ENOENT }, /* 2 */
{ ErrorPathNotFound, ENOENT }, /* 3 */
{ ErrorTooManyOpenFiles, EMFILE }, /* 4 */
{ ErrorAccessDenied, EACCES }, /* 5 */
{ ErrorInvalidHandle, EBADF }, /* 6 */
{ ErrorArenaTrashed, ENOMEM }, /* 7 */
{ ErrorNotEnoughMemory, ENOMEM }, /* 8 */
{ ErrorInvalidBlock, ENOMEM }, /* 9 */
{ ErrorBadEnvironment, E2BIG }, /* 10 */
{ ErrorBadFormat, ENOEXEC }, /* 11 */
{ ErrorInvalidAccess, EINVAL }, /* 12 */
{ ErrorInvalidData, EINVAL }, /* 13 */
{ ErrorInvalidDrive, ENOENT }, /* 15 */
{ ErrorCurrentDirectory, EACCES }, /* 16 */
{ ErrorNotSameDevice, EXDEV }, /* 17 */
{ ErrorNoMoreFiles, ENOENT }, /* 18 */
{ ErrorLockViolation, EACCES }, /* 33 */
{ ErrorBadNetPath, ENOENT }, /* 53 */
{ ErrorNetworkAccessDenied, EACCES }, /* 65 */
{ ErrorBadNetName, ENOENT }, /* 67 */
{ ErrorFileExists, EEXIST }, /* 80 */
{ ErrorCannotMake, EACCES }, /* 82 */
{ ErrorFailI24, EACCES }, /* 83 */
{ ErrorInvalidParameter, EINVAL }, /* 87 */
{ ErrorNoProcSlots, EAGAIN }, /* 89 */
{ ErrorDriveLocked, EACCES }, /* 108 */
{ ErrorBrokenPipe, EPIPE }, /* 109 */
{ ErrorDiskFull, ENOSPC }, /* 112 */
{ ErrorInvalidTargetHandle, EBADF }, /* 114 */
{ ErrorInvalidHandle, EINVAL }, /* 124 */
{ ErrorWaitNoChildren, ECHILD }, /* 128 */
{ ErrorChildNotComplete, ECHILD }, /* 129 */
{ ErrorDirectAccessHandle, EBADF }, /* 130 */
{ ErrorNegativeSeek, EINVAL }, /* 131 */
{ ErrorSeekOnDevice, EACCES }, /* 132 */
{ ErrorDirNotEmpty, ENOTEMPTY }, /* 145 */
{ ErrorNotLocked, EACCES }, /* 158 */
{ ErrorBadPathName, ENOENT }, /* 161 */
{ ErrorMaxThreadsReached, EAGAIN }, /* 164 */
{ ErrorLockFailed, EACCES }, /* 167 */
{ ErrorAlreadyExists, EEXIST }, /* 183 */
{ ErrorFilenameExcedRange, ENOENT }, /* 206 */
{ ErrorNestingNotAllowed, EAGAIN }, /* 215 */
{ ErrorNotEnoughQuota, ENOMEM } /* 1816 */
};
// size of the table
#define ERRTABLESIZE (sizeof(errtable)/sizeof(errtable[0]))
// The following two constants must be the minimum and maximum values in the (contiguous) range of Exec Failure errors.
#define MIN_EXEC_ERROR ErrorInvalidStartingCodeSeg
#define MAX_EXEC_ERROR ErrorInfLoopInRelocChain
// These are the low and high value in the range of errors that are access violations
#define MIN_EACCES_RANGE ErrorWriteProtect
#define MAX_EACCES_RANGE ErrorSharingBufferExceeded
//--------------------------------------------------------------------------------
void CDOSError::MapError( unsigned long ulOSErrNo )
{
Set( ulOSErrNo );
errno = Get_errno_FromOSErr( ulOSErrNo );
}
//--------------------------------------------------------------------------------
void CDOSError::Set( unsigned long ulOSErrNo )
{
CThread* pThread = t_pCurrentWin32Thread;
if( pThread != 0 )
{
pThread->Data().DOSErrorNumber() = ulOSErrNo;
}
}
//--------------------------------------------------------------------------------
int CDOSError::Get_errno_FromOSErr( unsigned long ulOSErrNo )
{
int i;
// check the table for the OS error code
for( i = 0; i < ERRTABLESIZE; ++i )
{
if( ulOSErrNo == errtable[ i ].oscode )
{
return errtable[ i ].errnocode;
}
}
// The error code wasn't in the table. We check for a range of
// EACCES errors or exec failure errors (ENOEXEC). Otherwise
// EINVAL is returned.
if( ulOSErrNo >= MIN_EACCES_RANGE && ulOSErrNo <= MAX_EACCES_RANGE )
{
return EACCESS;
}
else if( ulOSErrNo >= MIN_EXEC_ERROR && ulOSErrNo <= MAX_EXEC_ERROR )
{
return ENOEXEC;
}
else
{
return EINVAL;
}
}
}//nsWin32
| 41.82069 | 119 | 0.568272 | [
"object"
] |
d18b971a046520fa32d1f7d944645c4e945b88b1 | 801 | cpp | C++ | test/main.cpp | thecppzoo/zoo | 6b82e4ba4ca30cd8a71404f2dec946e3bac9e52f | [
"MIT"
] | 32 | 2018-10-23T16:48:00.000Z | 2022-03-25T04:09:32.000Z | test/main.cpp | thecppzoo/zoo | 6b82e4ba4ca30cd8a71404f2dec946e3bac9e52f | [
"MIT"
] | 7 | 2018-11-12T19:54:46.000Z | 2020-06-30T21:40:48.000Z | test/main.cpp | thecppzoo/zoo | 6b82e4ba4ca30cd8a71404f2dec946e3bac9e52f | [
"MIT"
] | 4 | 2017-09-02T16:53:00.000Z | 2020-12-14T09:10:51.000Z | #include <zoo/any.h>
#include <iostream>
#include <unordered_set>
std::unordered_set<void *> registrations;
struct Registers {
double a, b;
Registers() {
std::cout << "Registers(" << this << ")\n";
if(registrations.count(this)) {
std::cout << "error C" << this << std::endl;
throw 0;
}
registrations.insert(this);
}
Registers(const Registers &model) {
std::cout << "Registers(" << this << ", " << &model << ")\n";
if(registrations.count(this)) {
std::cout << "error CC" << this << std::endl;
throw 0;
}
registrations.insert(this);
}
~Registers() {
std::cout << "~Registers(" << this << ")\n";
if(!registrations.count(this)) {
std::cout << "error D" << this << std::endl;
}
}
};
int main(int argc, const char *argv[]) {
zoo::Any bla{Registers{}};
}
| 20.025 | 63 | 0.583021 | [
"model"
] |
d191fd5ab28ba71b114c0fe9a64239fe0d4c9e6b | 2,618 | hpp | C++ | Microsoft.O365.Security.Native.ETW/Errors.hpp | andrewgu/krabsetw | 7ae868c9c1183c9b91c19c4da7764f78f7fcf9ad | [
"MIT"
] | null | null | null | Microsoft.O365.Security.Native.ETW/Errors.hpp | andrewgu/krabsetw | 7ae868c9c1183c9b91c19c4da7764f78f7fcf9ad | [
"MIT"
] | null | null | null | Microsoft.O365.Security.Native.ETW/Errors.hpp | andrewgu/krabsetw | 7ae868c9c1183c9b91c19c4da7764f78f7fcf9ad | [
"MIT"
] | null | null | null | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
#pragma once
namespace Microsoft { namespace O365 { namespace Security { namespace ETW {
/// <summary>
/// Thrown when the ETW trace object is already registered.
/// </summary>
public ref struct TraceAlreadyRegistered : public System::Exception {};
/// <summary>
/// Thrown when an invalid parameter is provided.
/// </summary>
public ref struct InvalidParameter : public System::Exception {};
/// <summary>
/// Thrown when the trace fails to open.
/// </summary>
public ref struct OpenTraceFailure : public System::Exception {};
/// <summary>
/// Thrown when the schema for an event could not be found.
/// </summary>
public ref struct CouldNotFindSchema : public System::Exception {};
/// <summary>
/// Thrown when an error is encountered parsing an ETW property.
/// </summary>
public ref struct ParserException : public System::Exception {
/// <param name="msg">the error message returned while parsing</param>
ParserException(System::String^ msg) : System::Exception(msg) { }
};
/// <summary>
/// Thrown when a requested type does not match the ETW property type.
/// NOTE: This is only thrown in debug builds.
/// </summary>
public ref struct TypeMismatchAssert : public System::Exception {
/// <param name="msg">the error message returned when types mismatched</param>
TypeMismatchAssert(System::String^ msg) : System::Exception(msg) { }
};
/// <summary>
/// Thrown when no trace sessions remaining to register. An existing trace
/// session must be deleted first.
/// </summary>
public ref struct NoTraceSessionsRemaining : public System::Exception {};
#define ExecuteAndConvertExceptions(e) \
try { e; } \
catch (const krabs::trace_already_registered &) \
{ \
throw gcnew TraceAlreadyRegistered; \
} \
catch (const krabs::invalid_parameter &) \
{ \
throw gcnew InvalidParameter; \
} \
catch (const krabs::open_trace_failure &) \
{ \
throw gcnew OpenTraceFailure; \
} \
catch (const krabs::no_trace_sessions_remaining &) \
{ \
throw gcnew NoTraceSessionsRemaining; \
} \
catch (const krabs::need_to_be_admin_failure &) \
{ \
throw gcnew UnauthorizedAccessException("Need to be admin"); \
} \
} } } } | 35.378378 | 101 | 0.628342 | [
"object"
] |
d1993deba3bda87b0e236fc8ffcdf7bbc846bec5 | 578 | cpp | C++ | C++/maximum-sum-circular-subarray.cpp | jaiskid/LeetCode-Solutions | a8075fd69087c5463f02d74e6cea2488fdd4efd1 | [
"MIT"
] | 3,269 | 2018-10-12T01:29:40.000Z | 2022-03-31T17:58:41.000Z | C++/maximum-sum-circular-subarray.cpp | jaiskid/LeetCode-Solutions | a8075fd69087c5463f02d74e6cea2488fdd4efd1 | [
"MIT"
] | 53 | 2018-12-16T22:54:20.000Z | 2022-02-25T08:31:20.000Z | C++/maximum-sum-circular-subarray.cpp | jaiskid/LeetCode-Solutions | a8075fd69087c5463f02d74e6cea2488fdd4efd1 | [
"MIT"
] | 1,236 | 2018-10-12T02:51:40.000Z | 2022-03-30T13:30:37.000Z | // Time: O(n)
// Space: O(1)
class Solution {
public:
int maxSubarraySumCircular(vector<int>& A) {
int total = 0;
int max_sum = numeric_limits<int>::min(), cur_max = 0;
int min_sum = numeric_limits<int>::max(), cur_min = 0;
for (const auto& a : A) {
cur_max = max(cur_max + a, a);
max_sum = max(max_sum, cur_max);
cur_min = min(cur_min + a, a);
min_sum = min(min_sum, cur_min);
total += a;
}
return max_sum >= 0 ? max(max_sum, total - min_sum) : max_sum;
}
};
| 28.9 | 70 | 0.520761 | [
"vector"
] |
d19f3db48d2862d250ad6380f1bb23fc076e474d | 3,881 | cpp | C++ | thirdparty/dmcurl/thirdparty/curlpp/examples/example07.cpp | brinkqiang/luahttpclient | 1c5e0555a80aa15dd0e765a8084d0af83f0a488a | [
"MIT"
] | null | null | null | thirdparty/dmcurl/thirdparty/curlpp/examples/example07.cpp | brinkqiang/luahttpclient | 1c5e0555a80aa15dd0e765a8084d0af83f0a488a | [
"MIT"
] | null | null | null | thirdparty/dmcurl/thirdparty/curlpp/examples/example07.cpp | brinkqiang/luahttpclient | 1c5e0555a80aa15dd0e765a8084d0af83f0a488a | [
"MIT"
] | null | null | null | /**
* \file
* Cookies.
*
*/
#include <string>
#include <sstream>
#include <vector>
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <curlpp/cURLpp.hpp>
#include <curlpp/Easy.hpp>
#define CURLPP_ALLOW_NOT_AVAILABLE
#include <curlpp/Infos.hpp>
#include <curlpp/Options.hpp>
class YesNo
{
public:
explicit YesNo(bool yn) : yesno(yn) {}
std::string operator()() const {
return yesno ? "Yes" : "No";
}
friend std::ostream &operator<<(std::ostream &strm, const YesNo &yn) {
strm << yn();
return strm;
}
private:
bool yesno;
};
struct MyCookie
{
std::string name;
std::string value;
std::string domain;
std::string path;
time_t expires;
bool tail;
bool secure;
};
std::ostream &
operator<<(std::ostream &strm, const MyCookie &cook)
{
strm << "Cookie: '" << cook.name << "' (secure: " << YesNo(cook.secure) << ", tail: "
<< YesNo(cook.tail) << ") for domain: '" << cook.domain << "', "
<< "path: '" << cook.path << "'.\n";
strm << "Value: '" << cook.value << "'.\n";
strm << "Expires: '" << ctime(&cook.expires) << "'.\n";
return strm;
}
std::vector<std::string> &
split_cookie_str(const std::string &str, std::vector<std::string> &in)
{
std::string part;
std::istringstream strm(str);
while (getline(strm, part, '\t'))
in.push_back(part);
return in;
}
std::vector<std::string>
splitCookieStr(const std::string &str)
{
std::vector<std::string> split;
split_cookie_str(str, split);
return split;
}
std::vector<std::string> &
splitCookieStr(const std::string &str, std::vector<std::string> &in)
{
return split_cookie_str(str, in);
}
int StrToInt(const std::string &str)
{
std::istringstream strm(str);
int i = 0;
if (!(strm >> i)) {
throw curlpp::RuntimeError("Unable to convert string '" + str + "' to integer!");
}
return i;
}
MyCookie
MakeCookie(const std::string &str_cookie)
{
std::vector<std::string> vC = splitCookieStr(str_cookie);
MyCookie cook;
cook.domain = vC[0];
cook.tail = vC[1] == "TRUE";
cook.path = vC[2];
cook.secure = vC[3] == "TRUE";
cook.expires = StrToInt(vC[4]);
cook.name = vC[5];
cook.value = vC[6];
return cook;
}
int
main(void)
{
try
{
curlpp::Cleanup myCleanup;
curlpp::Easy exEasy;
std::vector<std::string> cookieList;
// a cookie as in HTTP header
cookieList.push_back("Set-Cookie: GMAIL_AT=EXPIRED;expires=Sun, 17-Jan-2038 19:14:07 GMT; path=/; domain=.google.com");
// a Netscape style cookie with \t
cookieList.push_back(".google.com\tTRUE\t/\tFALSE\t2147483647\tLSID\tI like you GOOGLE");
// a Netscape style cookie with tabs in string
cookieList.push_back(".yahoo.com TRUE / FALSE 0 YAHOO_COOKIE I like you yahoo, too");
exEasy.setOpt(new curlpp::options::Url("http://www.google.com"));
exEasy.setOpt(new curlpp::options::FileTime(true));
exEasy.setOpt(new curlpp::options::Verbose(true));
// loop throught the cookies and add one by one
//
for (std::vector<std::string>::iterator it = cookieList.begin();
it != cookieList.end();
++it)
{
exEasy.setOpt(curlpp::options::CookieList(*it));
}
exEasy.perform();
// see what cookies we got
//
std::cout << "\nCookies from cookie engine:" << std::endl;
std::list<std::string> cookies;
curlpp::infos::CookieList::get(exEasy, cookies);
int i = 1;
for (std::list<std::string>::const_iterator it = cookies.begin();
it != cookies.end();
++it, i++)
{
std::cout << "[" << i << "]: " << MakeCookie(*it) << std::endl;
}
exit(EXIT_SUCCESS);
}
catch(curlpp::RuntimeError &e)
{
std::cerr << e.what() << std::endl;
exit(EXIT_FAILURE);
}
catch(curlpp::LogicError &e)
{
std::cout << e.what() << std::endl;
exit(EXIT_FAILURE);
}
}
| 22.177143 | 122 | 0.608348 | [
"vector"
] |
d1a6ea43444906c9bdd4a74655946179d4aad93f | 1,537 | cpp | C++ | contrib/controller/CRBMCtrl.cpp | kzahedi/YARS | 48d9fe4178d699fba38114d3b299a228da41293d | [
"MIT"
] | 4 | 2017-08-05T03:33:21.000Z | 2021-11-08T09:15:42.000Z | contrib/controller/CRBMCtrl.cpp | kzahedi/YARS | 48d9fe4178d699fba38114d3b299a228da41293d | [
"MIT"
] | null | null | null | contrib/controller/CRBMCtrl.cpp | kzahedi/YARS | 48d9fe4178d699fba38114d3b299a228da41293d | [
"MIT"
] | 1 | 2019-03-24T08:35:25.000Z | 2019-03-24T08:35:25.000Z | #include "CRBMCtrl.h"
#include <crbm/Random.h>
#include <entropy++/Csv.h>
#include <math.h>
#include <stdio.h>
using namespace std;
void CRBMCtrl::update()
{
if(record == false)
{
for(int i = 0; i < (int)sensors.size(); i++) S[i] = sensors[i];
_crbm->update(S, A);
for(int i = 0; i < (int)motors.size(); i++) motors[i] = A[i];
// for(int i = 0; i < (int)motors.size()-1; i++) cout << motors[i] << ",";
// cout << motors[motors.size()-1] << endl;
if(t < T)
{
vector<double> tmp = Adata->row(t);
for(int i = 0; i < (int)motors.size(); i++) motors[i] = tmp[i];
}
}
else
{
if(t >= Adata->rows()) exit(0);
vector<double> tmp = Adata->row(t);
for(int i = 0; i < (int)motors.size(); i++) motors[i] = tmp[i];
}
t++;
}
void CRBMCtrl::init()
{
string crbm_filename;
string a_filename;
parameter.set("crbm", crbm_filename, "");
parameter.set("A", a_filename, "");
parameter.set("init", T, 100);
parameter.set("record", record, false);
_crbm = new libcrbm::binary::CRBMController(crbm_filename);
Adata = entropy::Csv::read(a_filename);
S = new double[sensors.size()];
A = new double[motors.size()];
libcrbm::Random::initialise();
t = 0;
}
void CRBMCtrl::reset()
{
t = 0;
}
void CRBMCtrl::close()
{ }
// the class factories
extern "C" RobotController* create()
{
CRBMCtrl* b = new CRBMCtrl();
return (RobotController*)b;
}
extern "C" void destroy(RobotController* controller)
{
//delete controller;
}
| 20.493333 | 78 | 0.574496 | [
"vector"
] |
d1aca0c308bb64da5f61f95b873af040296e32e4 | 16,143 | cpp | C++ | src/gpu/GrRenderTargetOpList.cpp | DerpRom/external_skia | 9856ce52693d8bf9e18b679420db4c795485c44e | [
"BSD-3-Clause"
] | 1 | 2019-01-16T03:59:15.000Z | 2019-01-16T03:59:15.000Z | src/gpu/GrRenderTargetOpList.cpp | DerpRom/external_skia | 9856ce52693d8bf9e18b679420db4c795485c44e | [
"BSD-3-Clause"
] | null | null | null | src/gpu/GrRenderTargetOpList.cpp | DerpRom/external_skia | 9856ce52693d8bf9e18b679420db4c795485c44e | [
"BSD-3-Clause"
] | 1 | 2019-11-05T01:02:09.000Z | 2019-11-05T01:02:09.000Z | /*
* Copyright 2010 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "GrRenderTargetOpList.h"
#include "GrAuditTrail.h"
#include "GrCaps.h"
#include "GrGpu.h"
#include "GrGpuCommandBuffer.h"
#include "GrRenderTarget.h"
#include "GrRenderTargetContext.h"
#include "GrResourceProvider.h"
#include "ops/GrClearOp.h"
#include "ops/GrClearStencilClipOp.h"
#include "ops/GrCopySurfaceOp.h"
#include "ops/GrDiscardOp.h"
#include "instanced/InstancedRendering.h"
using gr_instanced::InstancedRendering;
////////////////////////////////////////////////////////////////////////////////
// Experimentally we have found that most combining occurs within the first 10 comparisons.
static const int kDefaultMaxOpLookback = 10;
static const int kDefaultMaxOpLookahead = 10;
GrRenderTargetOpList::GrRenderTargetOpList(GrRenderTargetProxy* rtp, GrGpu* gpu,
GrResourceProvider* resourceProvider,
GrAuditTrail* auditTrail, const Options& options)
: INHERITED(rtp, auditTrail)
, fGpu(SkRef(gpu))
, fResourceProvider(resourceProvider)
, fLastClipStackGenID(SK_InvalidUniqueID)
, fClipAllocator(fClipAllocatorStorage, sizeof(fClipAllocatorStorage),
sizeof(fClipAllocatorStorage)) {
fMaxOpLookback = (options.fMaxOpCombineLookback < 0) ? kDefaultMaxOpLookback
: options.fMaxOpCombineLookback;
fMaxOpLookahead = (options.fMaxOpCombineLookahead < 0) ? kDefaultMaxOpLookahead
: options.fMaxOpCombineLookahead;
if (GrCaps::InstancedSupport::kNone != this->caps()->instancedSupport()) {
fInstancedRendering.reset(fGpu->createInstancedRendering());
}
}
GrRenderTargetOpList::~GrRenderTargetOpList() {
fGpu->unref();
}
////////////////////////////////////////////////////////////////////////////////
#ifdef SK_DEBUG
void GrRenderTargetOpList::dump() const {
INHERITED::dump();
SkDebugf("ops (%d):\n", fRecordedOps.count());
for (int i = 0; i < fRecordedOps.count(); ++i) {
SkDebugf("*******************************\n");
if (!fRecordedOps[i].fOp) {
SkDebugf("%d: <combined forward>\n", i);
} else {
SkDebugf("%d: %s\n", i, fRecordedOps[i].fOp->name());
SkString str = fRecordedOps[i].fOp->dumpInfo();
SkDebugf("%s\n", str.c_str());
const SkRect& bounds = fRecordedOps[i].fOp->bounds();
SkDebugf("ClippedBounds: [L: %.2f, T: %.2f, R: %.2f, B: %.2f]\n", bounds.fLeft,
bounds.fTop, bounds.fRight, bounds.fBottom);
}
}
}
void GrRenderTargetOpList::validateTargetsSingleRenderTarget() const {
GrRenderTarget* rt = nullptr;
for (int i = 0; i < fRecordedOps.count(); ++i) {
if (!fRecordedOps[i].fOp) {
continue; // combined forward
}
if (!rt) {
rt = fRecordedOps[i].fRenderTarget.get();
} else {
SkASSERT(fRecordedOps[i].fRenderTarget.get() == rt);
}
}
}
#endif
void GrRenderTargetOpList::prepareOps(GrOpFlushState* flushState) {
// MDB TODO: add SkASSERT(this->isClosed());
// Loop over the ops that haven't yet been prepared.
for (int i = 0; i < fRecordedOps.count(); ++i) {
if (fRecordedOps[i].fOp) {
GrOpFlushState::DrawOpArgs opArgs;
if (fRecordedOps[i].fRenderTarget) {
opArgs = {
fRecordedOps[i].fRenderTarget.get(),
fRecordedOps[i].fAppliedClip,
fRecordedOps[i].fDstTexture
};
}
flushState->setDrawOpArgs(&opArgs);
fRecordedOps[i].fOp->prepare(flushState);
flushState->setDrawOpArgs(nullptr);
}
}
if (fInstancedRendering) {
fInstancedRendering->beginFlush(flushState->resourceProvider());
}
}
// TODO: this is where GrOp::renderTarget is used (which is fine since it
// is at flush time). However, we need to store the RenderTargetProxy in the
// Ops and instantiate them here.
bool GrRenderTargetOpList::executeOps(GrOpFlushState* flushState) {
if (0 == fRecordedOps.count()) {
return false;
}
// Draw all the generated geometry.
SkRandom random;
const GrRenderTarget* currentRenderTarget = nullptr;
std::unique_ptr<GrGpuCommandBuffer> commandBuffer;
for (int i = 0; i < fRecordedOps.count(); ++i) {
if (!fRecordedOps[i].fOp) {
continue;
}
if (fRecordedOps[i].fRenderTarget.get() != currentRenderTarget) {
if (commandBuffer) {
commandBuffer->end();
commandBuffer->submit();
commandBuffer.reset();
}
currentRenderTarget = fRecordedOps[i].fRenderTarget.get();
if (currentRenderTarget) {
static const GrGpuCommandBuffer::LoadAndStoreInfo kBasicLoadStoreInfo
{ GrGpuCommandBuffer::LoadOp::kLoad,GrGpuCommandBuffer::StoreOp::kStore,
GrColor_ILLEGAL };
commandBuffer.reset(fGpu->createCommandBuffer(kBasicLoadStoreInfo, // Color
kBasicLoadStoreInfo)); // Stencil
}
flushState->setCommandBuffer(commandBuffer.get());
}
GrOpFlushState::DrawOpArgs opArgs;
if (fRecordedOps[i].fRenderTarget) {
opArgs = {
fRecordedOps[i].fRenderTarget.get(),
fRecordedOps[i].fAppliedClip,
fRecordedOps[i].fDstTexture
};
flushState->setDrawOpArgs(&opArgs);
}
fRecordedOps[i].fOp->execute(flushState);
flushState->setDrawOpArgs(nullptr);
}
if (commandBuffer) {
commandBuffer->end();
commandBuffer->submit();
flushState->setCommandBuffer(nullptr);
}
fGpu->finishOpList();
return true;
}
void GrRenderTargetOpList::reset() {
fLastFullClearOp = nullptr;
fLastFullClearRenderTargetID.makeInvalid();
fRecordedOps.reset();
if (fInstancedRendering) {
fInstancedRendering->endFlush();
}
}
void GrRenderTargetOpList::abandonGpuResources() {
if (GrCaps::InstancedSupport::kNone != this->caps()->instancedSupport()) {
InstancedRendering* ir = this->instancedRendering();
ir->resetGpuResources(InstancedRendering::ResetType::kAbandon);
}
}
void GrRenderTargetOpList::freeGpuResources() {
if (GrCaps::InstancedSupport::kNone != this->caps()->instancedSupport()) {
InstancedRendering* ir = this->instancedRendering();
ir->resetGpuResources(InstancedRendering::ResetType::kDestroy);
}
}
void GrRenderTargetOpList::fullClear(GrRenderTargetContext* renderTargetContext, GrColor color) {
GrRenderTarget* renderTarget = renderTargetContext->accessRenderTarget();
// Currently this just inserts or updates the last clear op. However, once in MDB this can
// remove all the previously recorded ops and change the load op to clear with supplied
// color.
// TODO: this needs to be updated to use GrSurfaceProxy::UniqueID
if (fLastFullClearRenderTargetID == renderTarget->uniqueID()) {
// As currently implemented, fLastFullClearOp should be the last op because we would
// have cleared it when another op was recorded.
SkASSERT(fRecordedOps.back().fOp.get() == fLastFullClearOp);
fLastFullClearOp->setColor(color);
return;
}
std::unique_ptr<GrClearOp> op(GrClearOp::Make(GrFixedClip::Disabled(), color, renderTarget));
if (GrOp* clearOp = this->recordOp(std::move(op), renderTargetContext)) {
// This is either the clear op we just created or another one that it combined with.
fLastFullClearOp = static_cast<GrClearOp*>(clearOp);
fLastFullClearRenderTargetID = renderTarget->uniqueID();
}
}
void GrRenderTargetOpList::discard(GrRenderTargetContext* renderTargetContext) {
// Currently this just inserts a discard op. However, once in MDB this can remove all the
// previously recorded ops and change the load op to discard.
if (this->caps()->discardRenderTargetSupport()) {
this->recordOp(GrDiscardOp::Make(renderTargetContext->accessRenderTarget()),
renderTargetContext);
}
}
////////////////////////////////////////////////////////////////////////////////
bool GrRenderTargetOpList::copySurface(GrSurface* dst,
GrSurface* src,
const SkIRect& srcRect,
const SkIPoint& dstPoint) {
std::unique_ptr<GrOp> op = GrCopySurfaceOp::Make(dst, src, srcRect, dstPoint);
if (!op) {
return false;
}
#ifdef ENABLE_MDB
this->addDependency(src);
#endif
// Copy surface doesn't work through a GrGpuCommandBuffer. By passing nullptr for the context we
// force this to occur between command buffers and execute directly on GrGpu. This workaround
// goes away with MDB.
this->recordOp(std::move(op), nullptr);
return true;
}
static inline bool can_reorder(const SkRect& a, const SkRect& b) {
return a.fRight <= b.fLeft || a.fBottom <= b.fTop ||
b.fRight <= a.fLeft || b.fBottom <= a.fTop;
}
bool GrRenderTargetOpList::combineIfPossible(const RecordedOp& a, GrOp* b,
const GrAppliedClip* bClip,
const DstTexture* bDstTexture) {
if (a.fAppliedClip) {
if (!bClip) {
return false;
}
if (*a.fAppliedClip != *bClip) {
return false;
}
} else if (bClip) {
return false;
}
if (bDstTexture) {
if (a.fDstTexture != *bDstTexture) {
return false;
}
} else if (a.fDstTexture.texture()) {
return false;
}
return a.fOp->combineIfPossible(b, *this->caps());
}
GrOp* GrRenderTargetOpList::recordOp(std::unique_ptr<GrOp> op,
GrRenderTargetContext* renderTargetContext,
GrAppliedClip* clip,
const DstTexture* dstTexture) {
GrRenderTarget* renderTarget =
renderTargetContext ? renderTargetContext->accessRenderTarget()
: nullptr;
// A closed GrOpList should never receive new/more ops
SkASSERT(!this->isClosed());
// Check if there is an op we can combine with by linearly searching back until we either
// 1) check every op
// 2) intersect with something
// 3) find a 'blocker'
GR_AUDIT_TRAIL_ADD_OP(fAuditTrail, op.get(), renderTarget->uniqueID());
GrOP_INFO("Recording (%s, B%u)\n"
"\tBounds LRTB (%f, %f, %f, %f)\n",
op->name(),
op->uniqueID(),
op->bounds().fLeft, op->bounds().fRight,
op->bounds().fTop, op->bounds().fBottom);
GrOP_INFO(SkTabString(op->dumpInfo(), 1).c_str());
GrOP_INFO("\tClipped Bounds: [L: %.2f, T: %.2f, R: %.2f, B: %.2f]\n", op->bounds().fLeft,
op->bounds().fTop, op->bounds().fRight, op->bounds().fBottom);
GrOP_INFO("\tOutcome:\n");
int maxCandidates = SkTMin(fMaxOpLookback, fRecordedOps.count());
// If we don't have a valid destination render target then we cannot reorder.
if (maxCandidates && renderTarget) {
int i = 0;
while (true) {
const RecordedOp& candidate = fRecordedOps.fromBack(i);
// We cannot continue to search backwards if the render target changes
if (candidate.fRenderTarget.get() != renderTarget) {
GrOP_INFO("\t\tBreaking because of (%s, B%u) Rendertarget\n", candidate.fOp->name(),
candidate.fOp->uniqueID());
break;
}
if (this->combineIfPossible(candidate, op.get(), clip, dstTexture)) {
GrOP_INFO("\t\tCombining with (%s, B%u)\n", candidate.fOp->name(),
candidate.fOp->uniqueID());
GrOP_INFO("\t\t\tCombined op info:\n");
GrOP_INFO(SkTabString(candidate.fOp->dumpInfo(), 4).c_str());
GR_AUDIT_TRAIL_OPS_RESULT_COMBINED(fAuditTrail, candidate.fOp.get(), op.get());
return candidate.fOp.get();
}
// Stop going backwards if we would cause a painter's order violation.
if (!can_reorder(fRecordedOps.fromBack(i).fOp->bounds(), op->bounds())) {
GrOP_INFO("\t\tIntersects with (%s, B%u)\n", candidate.fOp->name(),
candidate.fOp->uniqueID());
break;
}
++i;
if (i == maxCandidates) {
GrOP_INFO("\t\tReached max lookback or beginning of op array %d\n", i);
break;
}
}
} else {
GrOP_INFO("\t\tFirstOp\n");
}
GR_AUDIT_TRAIL_OP_RESULT_NEW(fAuditTrail, op);
if (clip) {
clip = fClipAllocator.make<GrAppliedClip>(std::move(*clip));
}
fRecordedOps.emplace_back(std::move(op), renderTarget, clip, dstTexture);
fRecordedOps.back().fOp->wasRecorded();
fLastFullClearOp = nullptr;
fLastFullClearRenderTargetID.makeInvalid();
return fRecordedOps.back().fOp.get();
}
void GrRenderTargetOpList::forwardCombine() {
if (fMaxOpLookahead <= 0) {
return;
}
for (int i = 0; i < fRecordedOps.count() - 1; ++i) {
GrOp* op = fRecordedOps[i].fOp.get();
GrRenderTarget* renderTarget = fRecordedOps[i].fRenderTarget.get();
// If we don't have a valid destination render target ID then we cannot reorder.
if (!renderTarget) {
continue;
}
int maxCandidateIdx = SkTMin(i + fMaxOpLookahead, fRecordedOps.count() - 1);
int j = i + 1;
while (true) {
const RecordedOp& candidate = fRecordedOps[j];
// We cannot continue to search if the render target changes
if (candidate.fRenderTarget.get() != renderTarget) {
GrOP_INFO("\t\tBreaking because of (%s, B%u) Rendertarget\n", candidate.fOp->name(),
candidate.fOp->uniqueID());
break;
}
if (this->combineIfPossible(fRecordedOps[i], candidate.fOp.get(),
candidate.fAppliedClip, &candidate.fDstTexture)) {
GrOP_INFO("\t\tCombining with (%s, B%u)\n", candidate.fOp->name(),
candidate.fOp->uniqueID());
GR_AUDIT_TRAIL_OPS_RESULT_COMBINED(fAuditTrail, op, candidate.fOp.get());
fRecordedOps[j].fOp = std::move(fRecordedOps[i].fOp);
break;
}
// Stop going traversing if we would cause a painter's order violation.
if (!can_reorder(fRecordedOps[j].fOp->bounds(), op->bounds())) {
GrOP_INFO("\t\tIntersects with (%s, B%u)\n", candidate.fOp->name(),
candidate.fOp->uniqueID());
break;
}
++j;
if (j > maxCandidateIdx) {
GrOP_INFO("\t\tReached max lookahead or end of op array %d\n", i);
break;
}
}
}
}
///////////////////////////////////////////////////////////////////////////////
void GrRenderTargetOpList::clearStencilClip(const GrFixedClip& clip,
bool insideStencilMask,
GrRenderTargetContext* renderTargetContext) {
this->recordOp(GrClearStencilClipOp::Make(clip, insideStencilMask,
renderTargetContext->accessRenderTarget()),
renderTargetContext);
}
| 40.662469 | 100 | 0.577402 | [
"geometry",
"render"
] |
d1adfc8e3ebaa67c1faeaf5ac4f857af04d1e3c5 | 728 | hpp | C++ | parse/jsd_set.hpp | 5cript/SimpleJSON | 878a6341baed91c29630447f6bd480391f563045 | [
"MIT"
] | 4 | 2015-06-25T02:06:13.000Z | 2018-07-11T13:20:24.000Z | parse/jsd_set.hpp | 5cript/SimpleJSON | 878a6341baed91c29630447f6bd480391f563045 | [
"MIT"
] | 14 | 2015-03-29T10:32:21.000Z | 2018-01-25T16:45:08.000Z | parse/jsd_set.hpp | 5cript/SimpleJSON | 878a6341baed91c29630447f6bd480391f563045 | [
"MIT"
] | 2 | 2017-07-16T09:43:22.000Z | 2020-08-30T09:33:40.000Z | #pragma once
#include "jsd_core.hpp"
#include "jsd_container.hpp"
#include <set>
namespace JSON
{
template <typename T>
void parse(std::set<T>& value, std::string const& name,
PropertyTree const& object, ParsingOptions const& options = {})
{
try
{
SJSON_GET_CHILD(name, pt, std::set<T>{});
for (auto const& i : pt)
{
T temp;
parse(temp, "", i.second, options);
value.insert(std::move(temp));
}
}
catch (boost::property_tree::ptree_bad_data& exc)
{
SJSON_DEFAULT_PROPERTY_ERROR_HANDLER(std::set<T>{}, std::set<T>{});
}
catch (boost::property_tree::ptree_bad_path& exc)
{
SJSON_DEFAULT_PATH_ERROR_HANDLER(std::set<T>{}, std::set<T>{});
}
}
}
| 21.411765 | 78 | 0.619505 | [
"object"
] |
d1b0a848361ee84a2e62a298ab67c3023fdd1286 | 6,302 | cpp | C++ | cpp/src/render/utils/vega/vega_scatter_plot/vega_weighted_pointmap.cpp | liangliu/arctern | b342f46c6b2d727d582e5f0971562447e1692043 | [
"Apache-2.0"
] | null | null | null | cpp/src/render/utils/vega/vega_scatter_plot/vega_weighted_pointmap.cpp | liangliu/arctern | b342f46c6b2d727d582e5f0971562447e1692043 | [
"Apache-2.0"
] | 1 | 2020-03-12T00:49:52.000Z | 2020-03-12T00:49:52.000Z | cpp/src/render/utils/vega/vega_scatter_plot/vega_weighted_pointmap.cpp | liangliu/arctern | b342f46c6b2d727d582e5f0971562447e1692043 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2019-2020 Zilliz. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <string>
#include <utility>
#include "render/utils/vega/vega_scatter_plot/vega_weighted_pointmap.h"
namespace arctern {
namespace render {
VegaWeightedPointmap::VegaWeightedPointmap(const std::string& json) { Parse(json); }
void VegaWeightedPointmap::Parse(const std::string& json) {
rapidjson::Document document;
document.Parse(json.c_str());
if (document.Parse(json.c_str()).HasParseError()) {
is_valid_ = false;
std::string err_msg = "json format error";
throw std::runtime_error(err_msg);
}
// 1. parse image width and height
if (!JsonLabelCheck(document, "width") || !JsonLabelCheck(document, "height") ||
!JsonNullCheck(document["width"]) || !JsonNullCheck(document["height"]) ||
!JsonTypeCheck(document["width"], rapidjson::Type::kNumberType) ||
!JsonTypeCheck(document["height"], rapidjson::Type::kNumberType)) {
return;
}
window_params_.mutable_width() = document["width"].GetInt();
window_params_.mutable_height() = document["height"].GetInt();
// 2. parse marks root
if (!JsonLabelCheck(document, "marks") ||
!JsonTypeCheck(document["marks"], rapidjson::Type::kArrayType) ||
!JsonSizeCheck(document["marks"], "marks", 1) ||
!JsonLabelCheck(document["marks"][0], "encode") ||
!JsonLabelCheck(document["marks"][0]["encode"], "enter")) {
return;
}
rapidjson::Value mark_enter;
mark_enter = document["marks"][0]["encode"]["enter"];
// 3. parse point map color
if (!JsonLabelCheck(mark_enter, "color") ||
!JsonLabelCheck(mark_enter["color"], "value") ||
!JsonTypeCheck(mark_enter["color"]["value"], rapidjson::Type::kStringType)) {
return;
}
auto color_string = std::string(mark_enter["color"]["value"].GetString());
ColorParser color_parser(color_string);
if (color_parser.is_css_hex_color()) {
is_multiple_color_ = false;
circle_params_.color = color_parser.color();
} else if (color_string == "blue_to_red") {
is_multiple_color_ = true;
color_style_ = ColorStyle::kBlueToRed;
} else if (color_string == "skyblue_to_white") {
is_multiple_color_ = true;
color_style_ = ColorStyle::kSkyBlueToWhite;
} else if (color_string == "purple_to_yellow") {
is_multiple_color_ = true;
color_style_ = ColorStyle::kPurpleToYellow;
} else if (color_string == "red_transparency") {
is_multiple_color_ = true;
color_style_ = ColorStyle::kRedTransParency;
} else if (color_string == "blue_transparency") {
is_multiple_color_ = true;
color_style_ = ColorStyle::kBlueTransParency;
} else if (color_string == "blue_green_yellow") {
is_multiple_color_ = true;
color_style_ = ColorStyle::kBlueGreenYellow;
} else if (color_string == "white_blue") {
is_multiple_color_ = true;
color_style_ = ColorStyle::kWhiteToBlue;
} else if (color_string == "blue_white_red") {
is_multiple_color_ = true;
color_style_ = ColorStyle::kBlueWhiteRed;
} else if (color_string == "green_yellow_red") {
is_multiple_color_ = true;
color_style_ = ColorStyle::kGreenYellowRed;
} else {
is_valid_ = false;
std::string err_msg = "unsupported color '" + color_string + "'.";
throw std::runtime_error(err_msg);
}
// 4. parse color_ruler
if (!JsonLabelCheck(mark_enter, "color_ruler") ||
!JsonLabelCheck(mark_enter["color_ruler"], "value") ||
!JsonTypeCheck(mark_enter["color_ruler"]["value"], rapidjson::Type::kArrayType)) {
return;
}
auto color_ruler_size = mark_enter["color_ruler"]["value"].Size();
if (color_ruler_size == 2 &&
JsonTypeCheck(mark_enter["color_ruler"]["value"][0],
rapidjson::Type::kNumberType) &&
JsonTypeCheck(mark_enter["color_ruler"]["value"][1],
rapidjson::Type::kNumberType)) {
color_ruler_ = std::make_pair(mark_enter["color_ruler"]["value"][0].GetDouble(),
mark_enter["color_ruler"]["value"][1].GetDouble());
} else {
is_valid_ = false;
std::string err_msg = "unsupported color ruler";
throw std::runtime_error(err_msg);
}
// 5. parse stroke_ruler
if (!JsonLabelCheck(mark_enter, "stroke_ruler") ||
!JsonLabelCheck(mark_enter["stroke_ruler"], "value") ||
!JsonTypeCheck(mark_enter["stroke_ruler"]["value"], rapidjson::Type::kArrayType)) {
return;
}
auto stroke_ruler_size = mark_enter["stroke_ruler"]["value"].Size();
if (stroke_ruler_size == 1 && JsonTypeCheck(mark_enter["stroke_ruler"]["value"][0],
rapidjson::Type::kNumberType)) {
is_multiple_stroke_width_ = false;
circle_params_.radius = mark_enter["stroke_ruler"]["value"][0].GetDouble();
} else if (stroke_ruler_size == 2 &&
JsonTypeCheck(mark_enter["stroke_ruler"]["value"][0],
rapidjson::Type::kNumberType) &&
JsonTypeCheck(mark_enter["stroke_ruler"]["value"][1],
rapidjson::Type::kNumberType)) {
is_multiple_stroke_width_ = true;
stroke_ruler_ = std::make_pair(mark_enter["stroke_ruler"]["value"][0].GetDouble(),
mark_enter["stroke_ruler"]["value"][1].GetDouble());
} else {
is_valid_ = false;
std::string err_msg = "unsupported stroke ruler";
throw std::runtime_error(err_msg);
}
// 6. parse opacity
if (!JsonLabelCheck(mark_enter, "opacity") ||
!JsonLabelCheck(mark_enter["opacity"], "value") ||
!JsonTypeCheck(mark_enter["opacity"]["value"], rapidjson::Type::kNumberType)) {
return;
}
circle_params_.color.a = mark_enter["opacity"]["value"].GetDouble();
}
} // namespace render
} // namespace arctern
| 40.140127 | 89 | 0.667248 | [
"render"
] |
d1ddd5aa6551ea6e3d45eb6a11d638a20df1b779 | 1,480 | cpp | C++ | cpp/leetcode/BusRoutes.cpp | danyfang/SourceCode | 8168f6058648f2a330a7354daf3a73a4d8a4e730 | [
"MIT"
] | null | null | null | cpp/leetcode/BusRoutes.cpp | danyfang/SourceCode | 8168f6058648f2a330a7354daf3a73a4d8a4e730 | [
"MIT"
] | null | null | null | cpp/leetcode/BusRoutes.cpp | danyfang/SourceCode | 8168f6058648f2a330a7354daf3a73a4d8a4e730 | [
"MIT"
] | null | null | null | //Leetcode Problem No 815 Bus Routes
//Solution written by Xuqiang Fang on 21 June, 2018
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <unordered_map>
#include <unordered_set>
#include <stack>
#include <queue>
using namespace std;
class Solution{
public:
int numBusesToDestination(vector<vector<int>>& routes, int S, int T) {
if(S == T){
return 0;
}
const int n = routes.size();
unordered_map<int, vector<int>> m;
for(int i=0; i<n; ++i){
for(const int s : routes[i]){
m[s].push_back(i);
}
}
vector<int> ride(n, 0);
queue<int> q;
q.push(S);
int buses = 0;
while(!q.empty()){
++buses;
for(int i=q.size(); i>0; --i){
int s = q.front();
q.pop();
for(const int b : m[s]){
if(ride[b]){
continue;
}
ride[b] = 1;
for(int t : routes[b]){
if(t == T){
return buses;
}
q.push(t);
}
}
}
}
return -1;
}
};
int main(){
Solution s;
vector<vector<int>> routes{{1, 2, 7}, {3, 6, 7}};
cout << s.numBusesToDestination(routes, 1, 6) << endl;
return 0;
}
| 24.666667 | 74 | 0.422973 | [
"vector"
] |
d1e64ed439531e4ae9755dc5106611a4b36cc149 | 1,793 | cc | C++ | L1Trigger/GlobalCaloTrigger/src/L1GctHfBitCountsLut.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 3 | 2018-08-24T19:10:26.000Z | 2019-02-19T11:45:32.000Z | L1Trigger/GlobalCaloTrigger/src/L1GctHfBitCountsLut.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 3 | 2018-08-23T13:40:24.000Z | 2019-12-05T21:16:03.000Z | L1Trigger/GlobalCaloTrigger/src/L1GctHfBitCountsLut.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 5 | 2018-08-21T16:37:52.000Z | 2020-01-09T13:33:17.000Z | #include "L1Trigger/GlobalCaloTrigger/interface/L1GctHfBitCountsLut.h"
//DEFINE STATICS
const int L1GctHfBitCountsLut::NAddress=5;
const int L1GctHfBitCountsLut::NData =3;
L1GctHfBitCountsLut::L1GctHfBitCountsLut(const L1GctHfEtSumsLut::hfLutType& type) :
L1GctLut<NAddress,NData>(),
m_lutType(type)
{
// No setup required
m_setupOk = true;
}
L1GctHfBitCountsLut::L1GctHfBitCountsLut() :
L1GctLut<NAddress,NData>(),
m_lutType()
{
// No setup required
m_setupOk = true;
}
L1GctHfBitCountsLut::L1GctHfBitCountsLut(const L1GctHfBitCountsLut& lut) :
L1GctLut<NAddress,NData>(),
m_lutType(lut.lutType())
{
// No setup required
m_setupOk = true;
}
L1GctHfBitCountsLut::~L1GctHfBitCountsLut()
{
}
uint16_t L1GctHfBitCountsLut::value (const uint16_t lutAddress) const
{
// Return "address=data" up to the maximum number of output codes
const int maxOutput = ((1<<NData)-1);
if (lutAddress > maxOutput) return maxOutput;
else return (lutAddress & maxOutput);
}
std::vector<unsigned> L1GctHfBitCountsLut::getThresholdsGct() const
{
std::vector<unsigned> result;
// Return "address=data" up to the maximum number of output codes
for (unsigned add=1; add<(1<<NData); add++) {
result.push_back(add);
}
return result;
}
L1GctHfBitCountsLut L1GctHfBitCountsLut::operator= (const L1GctHfBitCountsLut& lut)
{
const L1GctHfBitCountsLut& temp(lut);
return temp;
}
std::ostream& operator << (std::ostream& os, const L1GctHfBitCountsLut& lut)
{
os << "===L1GctHfBitCountsLut===" << std::endl;
os << "\n===Lookup table contents===\n" << std::endl;
const L1GctLut<L1GctHfBitCountsLut::NAddress,L1GctHfBitCountsLut::NData>* temp=&lut;
os << *temp;
return os;
}
template class L1GctLut<L1GctHfBitCountsLut::NAddress,L1GctHfBitCountsLut::NData>;
| 25.614286 | 86 | 0.734523 | [
"vector"
] |
d1e746deeb2842ebb1eb14e0a3a3ceb55644de28 | 69,467 | cpp | C++ | SRC/material/nD/TclModelBuilderNDMaterialCommand.cpp | steva44/OpenSees | 417c3be117992a108c6bbbcf5c9b63806b9362ab | [
"TCL"
] | 8 | 2019-03-05T16:25:10.000Z | 2020-04-17T14:12:03.000Z | SRC/material/nD/TclModelBuilderNDMaterialCommand.cpp | steva44/OpenSees | 417c3be117992a108c6bbbcf5c9b63806b9362ab | [
"TCL"
] | null | null | null | SRC/material/nD/TclModelBuilderNDMaterialCommand.cpp | steva44/OpenSees | 417c3be117992a108c6bbbcf5c9b63806b9362ab | [
"TCL"
] | 3 | 2019-09-21T03:11:11.000Z | 2020-01-19T07:29:37.000Z | /* ****************************************************************** **
** OpenSees - Open System for Earthquake Engineering Simulation **
** Pacific Earthquake Engineering Research Center **
** **
** **
** (C) Copyright 1999, The Regents of the University of California **
** All Rights Reserved. **
** **
** Commercial use of this program without express permission of the **
** University of California, Berkeley, is strictly prohibited. See **
** file 'COPYRIGHT' in main directory for information on usage and **
** redistribution, and for a DISCLAIMER OF ALL WARRANTIES. **
** **
** Developed by: **
** Frank McKenna (fmckenna@ce.berkeley.edu) **
** Gregory L. Fenves (fenves@ce.berkeley.edu) **
** Filip C. Filippou (filippou@ce.berkeley.edu) **
** **
** With a lot of additions by **
** Boris Jeremic (jeremic@ucdavis.edu) **
** Zaohui Yang (zhyang@ucdavis.edu) **
** Zhao Cheng (zcheng@ucdavis.edu) **
** **
** **
** **
** ****************************************************************** */
// $Revision: 1.44 $
// $Date: 2010-02-05 00:08:35 $
// $Source: /usr/local/cvs/OpenSees/SRC/material/nD/TclModelBuilderNDMaterialCommand.cpp,v $
// Description: This file contains the function invoked when the user invokes
// the nDMaterial command in the interpreter.
//
// What: "@(#) TclModelBuilderNDMaterialCommand.C, revA"
#include <TclModelBuilder.h>
#include <elementAPI.h>
#include <packages.h>
#include <PressureDependentElastic3D.h>
#include <J2Plasticity.h>
#include <MultiaxialCyclicPlasticity.h> //Gang Wang
#include <PlaneStressMaterial.h>
#include <PlaneStrainMaterial.h> // Antonios Vytiniotis:
#include <PlateFiberMaterial.h>
#include <UniaxialFiber2d.h>
#include <UniaxialFiber3d.h>
//start Yuli Huang & Xinzheng Lu
#include <PlateRebarMaterial.h>
#include <PlateFromPlaneStressMaterial.h>
#include <ConcreteS.h>
#include <PlaneStressUserMaterial.h>
//end Yuli Huang & Xinzheng Lu
#include <CapPlasticity.h> // Quan Gu & ZhiJian Qiu 2013
#include <SimplifiedJ2.h> // Quan Gu & ZhiJian Qiu 2013-6-26
#include <PlaneStressSimplifiedJ2.h>// Quan Gu & ZhiJian Qiu 2013-6-26
#include <BeamFiberMaterial.h>
#include <ConcreteMcftNonLinear5.h>
#include <ConcreteMcftNonLinear7.h>
#include <PressureIndependMultiYield.h>
#include <PressureDependMultiYield.h>
#include <PressureDependMultiYield02.h>
#include <PressureDependMultiYield03.h>
#include <FluidSolidPorousMaterial.h>
#include <J2PlasticityThermal.h> //added by L.Jiang [SIF]
#include <PlateFiberMaterialThermal.h>//L.Jiang [SIF]
#include <PlateFromPlaneStressMaterialThermal.h> //Liming Jiang [SIF]
#include <PlateRebarMaterialThermal.h> //Liming Jiang [SIF]
#include <MultiYieldSurfaceClay.h>
#include <string.h>
extern NDMaterial *
Tcl_addWrapperNDMaterial(matObj *, ClientData, Tcl_Interp *, int, TCL_Char **, TclModelBuilder *);
extern void *OPS_ReinforcedConcretePlaneStressMaterial(void);
extern void *OPS_FAReinforcedConcretePlaneStressMaterial(void);
extern void *OPS_FAFourSteelRCPlaneStressMaterial(void);
extern void *OPS_RAFourSteelRCPlaneStressMaterial(void);
extern void *OPS_PrestressedConcretePlaneStressMaterial(void);
extern void *OPS_FAPrestressedConcretePlaneStressMaterial(void);
extern void *OPS_FAFourSteelPCPlaneStressMaterial(void);
extern void *OPS_RAFourSteelPCPlaneStressMaterial(void);
extern void *OPS_MaterialCMM(void);
extern void *OPS_NewMaterialCMM(void);
extern void * OPS_NewPlasticDamageConcrete3d(void);
extern void * OPS_NewPlasticDamageConcretePlaneStress(void);
extern void *OPS_ElasticIsotropicMaterial(void);
extern void *OPS_ElasticIsotropic3D(void);
extern void *OPS_IncrementalElasticIsotropicThreeDimensional(void);
extern void *OPS_ElasticOrthotropicMaterial(void);
extern void *OPS_DruckerPragerMaterial(void);
extern void *OPS_BoundingCamClayMaterial(void);
extern void *OPS_ContactMaterial2DMaterial(void);
extern void *OPS_ContactMaterial3DMaterial(void);
extern void *OPS_InitialStateAnalysisWrapperMaterial(void);
extern void *OPS_ManzariDafaliasMaterial(void);
extern void *OPS_ManzariDafaliasMaterialRO(void);
extern void *OPS_PM4SandMaterial(void);
extern void *OPS_PM4SiltMaterial(void);
extern void *OPS_J2CyclicBoundingSurfaceMaterial(void);
extern void *OPS_CycLiqCPMaterial(void);
extern void *OPS_CycLiqCPSPMaterial(void);
extern void *OPS_InitStressNDMaterial(void);
extern void *OPS_StressDensityMaterial(void);
extern void *OPS_J2Plasticity(void);
extern void *OPS_J2BeamFiber2dMaterial(void);
extern void *OPS_J2BeamFiber3dMaterial(void);
extern void *OPS_J2PlateFibreMaterial(void);
extern void *OPS_PlaneStressLayeredMaterial(void);
extern void *OPS_PlaneStressRebarMaterial(void);
extern void *OPS_PlateFiberMaterial(void);
extern void *OPS_BeamFiberMaterial(void);
extern void *OPS_BeamFiberMaterial2d(void);
extern void *OPS_BeamFiberMaterial2dPS(void);
extern void *OPS_LinearCap(void);
extern void *OPS_AcousticMedium(void);
extern void* OPS_UVCmultiaxial(void);
extern void* OPS_UVCplanestress(void);
extern void *OPS_SAniSandMSMaterial(void);
extern void *OPS_ElasticIsotropicMaterialThermal(void); //L.Jiang [SIF]
extern void *OPS_DruckerPragerMaterialThermal(void);//L.Jiang [SIF]
//extern void *OPS_PlasticDamageConcretePlaneStressThermal(void);//L.Jiang [SIF]
#ifdef _HAVE_Faria1998
extern void *OPS_NewFaria1998Material(void);
extern void *OPS_NewConcreteMaterial(void);
#endif
extern void *OPS_FSAMMaterial(void); // K Kolozvari
#ifdef _HAVE_Damage2p
extern void *OPS_Damage2p(void);
#endif
#if defined(OPSDEF_Material_FEAP)
NDMaterial *
TclModelBuilder_addFeapMaterial(ClientData clientData, Tcl_Interp *interp,
int argc, TCL_Char **argv,
TclModelBuilder *theTclBuilder);
#endif // _OPS_Material_FEAP
extern int OPS_ResetInput(ClientData clientData,
Tcl_Interp *interp,
int cArg,
int mArg,
TCL_Char **argv,
Domain *domain,
TclModelBuilder *builder);
typedef struct ndMaterialPackageCommand {
char *funcName;
void * (*funcPtr)();
struct ndMaterialPackageCommand *next;
} NDMaterialPackageCommand;
static NDMaterialPackageCommand *theNDMaterialPackageCommands = NULL;
static void printCommand(int argc, TCL_Char **argv)
{
opserr << "Input command: ";
for (int i=0; i<argc; i++)
opserr << argv[i] << " ";
opserr << endln;
}
int
TclModelBuilderNDMaterialCommand (ClientData clientData, Tcl_Interp *interp, int argc,
TCL_Char **argv, TclModelBuilder *theTclBuilder)
{
// Make sure there is a minimum number of arguments
if (argc < 3) {
opserr << "WARNING insufficient number of ND material arguments\n";
opserr << "Want: nDMaterial type? tag? <specific material args>" << endln;
return TCL_ERROR;
}
OPS_ResetInput(clientData, interp, 2, argc, argv, 0, theTclBuilder);
// Pointer to an ND material that will be added to the model builder
NDMaterial *theMaterial = 0;
// Check argv[1] for ND material type
if ((strcmp(argv[1],"ReinforcedConcretePlaneStress") == 0) || (strcmp(argv[1],"ReinforceConcretePlaneStress") == 0)) {
void *theMat = OPS_ReinforcedConcretePlaneStressMaterial();
if (theMat != 0)
theMaterial = (NDMaterial *)theMat;
else
return TCL_ERROR;
}
else if ((strcmp(argv[1],"PlasticDamageConcrete") == 0) || (strcmp(argv[1],"PlasticDamageConcrete3d") == 0)) {
void *theMat = OPS_NewPlasticDamageConcrete3d();
if (theMat != 0) {
theMaterial = (NDMaterial *)theMat;
}
else
return TCL_ERROR;
}
else if ((strcmp(argv[1],"PlasticDamageConcretePlaneStress") == 0)) {
void *theMat = OPS_NewPlasticDamageConcretePlaneStress();
if (theMat != 0)
theMaterial = (NDMaterial *)theMat;
else
return TCL_ERROR;
}
else if ((strcmp(argv[1],"InitStressMaterial") == 0) || (strcmp(argv[1],"InitStress") == 0)) {
void *theMat = OPS_InitStressNDMaterial();
if (theMat != 0)
theMaterial = (NDMaterial *)theMat;
else
return TCL_ERROR;
}
else if (strcmp(argv[1],"PlaneStressLayeredMaterial") == 0) {
void *theMat = OPS_PlaneStressLayeredMaterial();
if (theMat != 0)
theMaterial = (NDMaterial *)theMat;
else
return TCL_ERROR;
}
else if (strcmp(argv[1],"PlaneStressRebarMaterial") == 0) {
void *theMat = OPS_PlaneStressRebarMaterial();
if (theMat != 0)
theMaterial = (NDMaterial *)theMat;
else
return TCL_ERROR;
}
else if (strcmp(argv[1],"J2BeamFiber") == 0) {
void *theMat = 0;
if (theTclBuilder->getNDM() == 2)
theMat = OPS_J2BeamFiber2dMaterial();
else
theMat = OPS_J2BeamFiber3dMaterial();
if (theMat != 0)
theMaterial = (NDMaterial *)theMat;
else
return TCL_ERROR;
}
else if (strcmp(argv[1],"J2PlateFibre") == 0) {
void *theMat = OPS_J2PlateFibreMaterial();
if (theMat != 0)
theMaterial = (NDMaterial *)theMat;
else
return TCL_ERROR;
}
#ifdef _HAVE_Faria1998
else if (strcmp(argv[1],"Faria1998") == 0) {
void *theMat = OPS_NewFaria1998Material();
if (theMat != 0)
theMaterial = (NDMaterial *)theMat;
else
return TCL_ERROR;
}
else if (strcmp(argv[1],"Concrete") == 0) {
void *theMat = OPS_NewConcreteMaterial();
if (theMat != 0)
theMaterial = (NDMaterial *)theMat;
else
return TCL_ERROR;
}
#endif
else if ((strcmp(argv[1],"FAReinforceConcretePlaneStress") == 0) || (strcmp(argv[1],"FAReinforcedConcretePlaneStress") == 0)) {
void *theMat = OPS_FAReinforcedConcretePlaneStressMaterial();
if (theMat != 0)
theMaterial = (NDMaterial *)theMat;
else
return TCL_ERROR;
}
else if ((strcmp(argv[1],"RAFourSteelRCPlaneStress") == 0)){
void *theMat = OPS_RAFourSteelRCPlaneStressMaterial();
if (theMat != 0)
theMaterial = (NDMaterial *)theMat;
else
return TCL_ERROR;
}
else if ((strcmp(argv[1],"FAFourSteelRCPlaneStress") == 0)){
void *theMat = OPS_FAFourSteelRCPlaneStressMaterial();
if (theMat != 0)
theMaterial = (NDMaterial *)theMat;
else
return TCL_ERROR;
}
#ifdef _HAVE_Damage2p
else if ((strcmp(argv[1],"Damage2p") == 0)){
void *theMat = OPS_Damage2p();
if (theMat != 0)
theMaterial = (NDMaterial *)theMat;
else
return TCL_ERROR;
}
#else
else if ((strcmp(argv[1],"Damage2p") == 0)){
opserr << "SORRY - Damage2p source code not available in this version\n";
return TCL_ERROR;
}
#endif
else if ((strcmp(argv[1],"PrestressedConcretePlaneStress") == 0)){
void *theMat = OPS_PrestressedConcretePlaneStressMaterial();
if (theMat != 0)
theMaterial = (NDMaterial *)theMat;
else
return TCL_ERROR;
}
else if ((strcmp(argv[1],"FAPrestressedConcretePlaneStress") == 0)){
void *theMat = OPS_FAPrestressedConcretePlaneStressMaterial();
if (theMat != 0)
theMaterial = (NDMaterial *)theMat;
else
return TCL_ERROR;
}
else if ((strcmp(argv[1],"RAFourSteetPCPlaneStress") == 0)){
void *theMat = OPS_RAFourSteelPCPlaneStressMaterial();
if (theMat != 0)
theMaterial = (NDMaterial *)theMat;
else
return TCL_ERROR;
}
else if ((strcmp(argv[1],"FAFourSteelPCPlaneStress") == 0)){
void *theMat = OPS_FAFourSteelPCPlaneStressMaterial();
if (theMat != 0)
theMaterial = (NDMaterial *)theMat;
else
return TCL_ERROR;
}
else if ((strcmp(argv[1],"DruckerPrager") == 0)){
void *theMat = OPS_DruckerPragerMaterial();
if (theMat != 0)
theMaterial = (NDMaterial *)theMat;
else
return TCL_ERROR;
}
else if ((strcmp(argv[1],"TruncatedDP") == 0)){
void *theMat = OPS_LinearCap();
if (theMat != 0)
theMaterial = (NDMaterial *)theMat;
else
return TCL_ERROR;
}
// K Kolozvari
else if ((strcmp(argv[1], "FSAM") == 0) ||
(strcmp(argv[1], "FSAM") == 0)) {
void *theMat = OPS_FSAMMaterial();
if (theMat != 0)
theMaterial = (NDMaterial *)theMat;
else
return TCL_ERROR;
}
else if ((strcmp(argv[1],"AcousticMedium") == 0)){
void *theMat = OPS_AcousticMedium();
if (theMat != 0)
theMaterial = (NDMaterial *)theMat;
else
return TCL_ERROR;
}
else if ((strcmp(argv[1],"UVCplanestress") == 0)){
void *theMat = OPS_UVCplanestress();
if (theMat != 0)
theMaterial = (NDMaterial *)theMat;
else
return TCL_ERROR;
}
else if ((strcmp(argv[1],"UVCmultiaxial") == 0)){
void *theMat = OPS_UVCmultiaxial();
if (theMat != 0)
theMaterial = (NDMaterial *)theMat;
else
return TCL_ERROR;
}
else if ((strcmp(argv[1],"MaterialCMM") == 0)){
void *theMat = OPS_MaterialCMM();
if (theMat != 0)
theMaterial = (NDMaterial *)theMat;
else
return TCL_ERROR;
}
else if ((strcmp(argv[1],"CycLiqCP") == 0)){
void *theMat = OPS_CycLiqCPMaterial();
if (theMat != 0)
theMaterial = (NDMaterial *)theMat;
else
return TCL_ERROR;
}
else if ((strcmp(argv[1],"CycLiqCPSP") == 0)){
void *theMat = OPS_CycLiqCPSPMaterial();
if (theMat != 0)
theMaterial = (NDMaterial *)theMat;
else
return TCL_ERROR;
}
else if ((strcmp(argv[1],"BoundingCamClay") == 0)){
void *theMat = OPS_BoundingCamClayMaterial();
if (theMat != 0)
theMaterial = (NDMaterial *)theMat;
else
return TCL_ERROR;
}
else if ((strcmp(argv[1],"ManzariDafalias") == 0)){
void *theMat = OPS_ManzariDafaliasMaterial();
if (theMat != 0)
theMaterial = (NDMaterial *)theMat;
else
return TCL_ERROR;
}
else if ((strcmp(argv[1],"ManzariDafaliasRO") == 0)){
void *theMat = OPS_ManzariDafaliasMaterialRO();
if (theMat != 0)
theMaterial = (NDMaterial *)theMat;
else
return TCL_ERROR;
}
else if ((strcmp(argv[1],"PM4Sand") == 0)){
void *theMat = OPS_PM4SandMaterial();
if (theMat != 0)
theMaterial = (NDMaterial *)theMat;
else
return TCL_ERROR;
}
else if ((strcmp(argv[1], "J2CyclicBoundingSurface") == 0)) {
void *theMat = OPS_J2CyclicBoundingSurfaceMaterial();
if (theMat != 0)
theMaterial = (NDMaterial *)theMat;
else
return TCL_ERROR;
}
else if ((strcmp(argv[1], "PM4Silt") == 0)) {
void *theMat = OPS_PM4SiltMaterial();
if (theMat != 0)
theMaterial = (NDMaterial *)theMat;
else
return TCL_ERROR;
}
else if ((strcmp(argv[1],"ContactMaterial2D") == 0)){
void *theMat = OPS_ContactMaterial2DMaterial();
if (theMat != 0)
theMaterial = (NDMaterial *)theMat;
else
return TCL_ERROR;
}
else if ((strcmp(argv[1],"ContactMaterial3D") == 0)){
void *theMat = OPS_ContactMaterial3DMaterial();
if (theMat != 0)
theMaterial = (NDMaterial *)theMat;
else
return TCL_ERROR;
}
else if ((strcmp(argv[1],"InitialStateAnalysisWrapper") == 0)){
void *theMat = OPS_InitialStateAnalysisWrapperMaterial();
if (theMat != 0)
theMaterial = (NDMaterial *)theMat;
else
return TCL_ERROR;
}
else if ((strcmp(argv[1],"stressDensity") == 0) || (strcmp(argv[1],"StressDensity") == 0)) {
void *theMat = OPS_StressDensityMaterial();
if (theMat != 0)
theMaterial = (NDMaterial *)theMat;
else
return TCL_ERROR;
}
else if ((strcmp(argv[1],"ElasticIsotropic3D") == 0)) {
void *theMat = OPS_ElasticIsotropic3D();
if (theMat != 0)
theMaterial = (NDMaterial *)theMat;
else
return TCL_ERROR;
}
else if ((strcmp(argv[1],"ElasticIsotropic") == 0)) {
void *theMat = OPS_ElasticIsotropicMaterial();
if (theMat != 0)
theMaterial = (NDMaterial *)theMat;
else
return TCL_ERROR;
}
else if ((strcmp(argv[1],"ElasticOrthotropic3D") == 0) || (strcmp(argv[1],"ElasticOrthotropic") == 0)) {
void *theMat = OPS_ElasticOrthotropicMaterial();
if (theMat != 0)
theMaterial = (NDMaterial *)theMat;
else
return TCL_ERROR;
}
else if ((strcmp(argv[1],"IncrementalElasticIsotropic3D") == 0) || (strcmp(argv[1],"incrementalElasticIsotropic3D") == 0)) {
void *theMat = OPS_IncrementalElasticIsotropicThreeDimensional();
if (theMat != 0)
theMaterial = (NDMaterial *)theMat;
else
return TCL_ERROR;
}
else if ((strcmp(argv[1],"SAniSandMS") == 0)){
void *theMat = OPS_SAniSandMSMaterial();
if (theMat != 0)
theMaterial = (NDMaterial *)theMat;
else
return TCL_ERROR;
}
else if (strcmp(argv[1],"PressureDependentElastic3D") == 0) {
if (argc < 6) {
opserr << "WARNING insufficient arguments\n";
printCommand(argc,argv);
opserr << "Want: nDMaterial PressureDependentElastic3D tag? E? v? rho?" << endln;
return TCL_ERROR;
}
int tag = 0;
double E = 0.0;
double v = 0.0;
double rho = 0.0;
double expp = 0.0;
double prp = 0.0;
double pop = 0.0;
if (Tcl_GetInt(interp, argv[2], &tag) != TCL_OK) {
opserr << "WARNING invalid PressureDependentElastic3D tag" << endln;
return TCL_ERROR;
}
if (Tcl_GetDouble(interp, argv[3], &E) != TCL_OK) {
opserr << "WARNING invalid E\n";
opserr << "nDMaterial PressureDependentElastic3D: E" << tag << endln;
return TCL_ERROR;
}
if (Tcl_GetDouble(interp, argv[4], &v) != TCL_OK) {
opserr << "WARNING invalid v\n";
opserr << "nDMaterial PressureDependentElastic3D: v" << tag << endln;
return TCL_ERROR;
}
if (Tcl_GetDouble(interp, argv[5], &rho) != TCL_OK) {
opserr << "WARNING invalid v\n";
opserr << "nDMaterial PressureDependentElastic3D: rho" << tag << endln;
return TCL_ERROR;
}
//////////////////////////////////////////////////////////////////////////////////
if( argc == 6 )
{
theMaterial = new PressureDependentElastic3D (tag, E, v, rho);
//opserr << "nDMaterial PressureDependentElastic3D: expp =" << expp << endln;
}
//////////////////////////////////////////////////////////////////////////////////
else if( argc == 7 )
{
//get the exponent of the pressure sensitive elastic material)
if (Tcl_GetDouble(interp, argv[6], &expp) != TCL_OK) {
opserr << "WARNING invalid v\n";
opserr << "nDMaterial PressureDependentElastic3D: " << tag << endln;
return TCL_ERROR;
}
theMaterial = new PressureDependentElastic3D (tag, E, v, rho, expp);
//opserr << "nDMaterial PressureDependentElastic3D: expp =" << expp << endln;
}
//////////////////////////////////////////////////////////////////////////////////
else if (argc == 8 )
{
//get the exponent pressure of the pressure sensitive elastic material)
if (Tcl_GetDouble(interp, argv[6], &expp) != TCL_OK) {
opserr << "WARNING invalid v\n";
opserr << "nDMaterial PressureDependentElastic3D: expp" << tag << endln;
return TCL_ERROR;
}
//get the reference pressure of the pressure sensitive elastic material)
if (Tcl_GetDouble(interp, argv[7], &prp) != TCL_OK) {
opserr << "WARNING invalid v\n";
opserr << "nDMaterial PressureDependentElastic3D: prp " << tag << endln;
return TCL_ERROR;
}
//opserr << "nDMaterial ElasticIsotropic3D: prp =" << prp << endln;
theMaterial = new PressureDependentElastic3D (tag, E, v, rho, expp, prp);
}
//////////////////////////////////////////////////////////////////////////////////
else if (argc >= 9 )
{
//get the exponent of the pressure sensitive elastic material)
if (Tcl_GetDouble(interp, argv[6], &expp) != TCL_OK) {
opserr << "WARNING invalid v\n";
opserr << "nDMaterial PressureDependentElastic3D: expp" << tag << endln;
return TCL_ERROR;
}
//get the reference pressure of the pressure sensitive elastic material)
if (Tcl_GetDouble(interp, argv[7], &prp) != TCL_OK) {
opserr << "WARNING invalid v\n";
opserr << "nDMaterial PressureDependentElastic3D: prp" << tag << endln;
return TCL_ERROR;
}
//get the cutoff pressure po of the pressure sensitive elastic material)
if (Tcl_GetDouble(interp, argv[8], &pop) != TCL_OK) {
opserr << "WARNING invalid v\n";
opserr << "nDMaterial PressureDependentElastic3D: pop" << tag << endln;
return TCL_ERROR;
}
//opserr << "nDMaterial PressureDependentElastic3D: pop =" << pop << endln;
theMaterial = new PressureDependentElastic3D (tag, E, v, rho, expp, prp, pop);
}
}
// Check argv[1] for J2PlaneStrain material type
else if ((strcmp(argv[1],"J2Plasticity") == 0) ||
(strcmp(argv[1],"J2") == 0)) {
void *theMat = OPS_J2Plasticity();
if (theMat != 0)
theMaterial = (NDMaterial *)theMat;
else
return TCL_ERROR;
}
/////////////////////////////////////////////////////////////////
/*
nDmaterial PlaneStressJ2 $matTag $G $K $sig0 $H_kin $H_iso
PlaneStress (int tag,
int nd,
NDMaterial &the3DMaterial);
*/
else if ((strcmp(argv[1],"PlaneStressSimplifiedJ2") == 0)) {
if (argc < 8) {
opserr << "WARNING insufficient arguments\n";
printCommand(argc,argv);
opserr << "Want: nDmaterial Simplified3DJ2 $matTag $G $K $sig0 $H_kin $H_iso" << endln;
return TCL_ERROR;
}
int tag;
double K, G, sig0, H_kin, H_iso;
if (Tcl_GetInt(interp, argv[2], &tag) != TCL_OK) {
opserr << "WARNING invalid SimplifiedJ2 tag" << endln;
return TCL_ERROR;
}
if (Tcl_GetDouble(interp, argv[3], &G) != TCL_OK) {
opserr << "WARNING invalid G\n";
opserr << "nDMaterial SimplifiedJ2: " << tag << endln;
return TCL_ERROR;
}
if (Tcl_GetDouble(interp, argv[4], &K) != TCL_OK) {
opserr << "WARNING invalid K\n";
opserr << "nDMaterial SimplifiedJ2: " << tag << endln;
return TCL_ERROR;
}
if (Tcl_GetDouble(interp, argv[5], &sig0) != TCL_OK) {
opserr << "WARNING invalid sig0\n";
opserr << "nDMaterial SimplifiedJ2: " << tag << endln;
return TCL_ERROR;
}
if (Tcl_GetDouble(interp, argv[6], &H_kin) != TCL_OK) {
opserr << "WARNING invalid H_kin\n";
opserr << "nDMaterial SimplifiedJ2: " << tag << endln;
return TCL_ERROR;
}
if (Tcl_GetDouble(interp, argv[7], &H_iso) != TCL_OK) {
opserr << "WARNING invalid H_iso\n";
opserr << "nDMaterial SimplifiedJ2: " << tag << endln;
return TCL_ERROR;
}
NDMaterial *theMaterial2 = new SimplifiedJ2 (tag,
3,
G,
K,
sig0,
H_kin,
H_iso);
theMaterial = new PlaneStressSimplifiedJ2 (tag,
2,
*theMaterial2);
// delete theMaterial2;
}
/////////////////////////////////////////////////////////////////
//
// MultiAxialCyclicPlasticity Model by Gang Wang
//
// nDMaterial MultiaxialCyclicPlasticity $tag, $rho, $K, $G,
// $Su , $Ho , $h, $m, $beta, $KCoeff
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Check argv[1] for MultiaxialCyclicPlasticity material type
else if ((strcmp(argv[1],"MultiaxialCyclicPlasticity") == 0) ||
(strcmp(argv[1],"MCP") == 0)) {
if (argc < 12) {
opserr << "WARNING insufficient arguments\n";
printCommand(argc,argv);
opserr << "Want: nDMaterial MultiaxialCyclicPlasticity tag? rho? K? G? Su? Ho? h? m? beta? KCoeff? <eta?>" << endln;
return TCL_ERROR;
}
int tag;
double K, G, rho, Su, Ho, h, m, beta, Kcoeff;
double eta = 0.0;
if (Tcl_GetInt(interp, argv[2], &tag) != TCL_OK) {
opserr << "WARNING invalid MultiaxialCyclicPlasticity tag" << endln;
return TCL_ERROR;
}
if (Tcl_GetDouble(interp, argv[3], &rho) != TCL_OK) {
opserr << "WARNING invalid rho\n";
opserr << "nDMaterial MultiaxialCyclicPlasticity: " << tag << endln;
return TCL_ERROR;
}
if (Tcl_GetDouble(interp, argv[4], &K) != TCL_OK) {
opserr << "WARNING invalid K\n";
opserr << "nDMaterial MultiaxialCyclicPlasticity: " << tag << endln;
return TCL_ERROR;
}
if (Tcl_GetDouble(interp, argv[5], &G) != TCL_OK) {
opserr << "WARNING invalid G\n";
opserr << "nDMaterial MultiaxialCyclicPlasticity: " << tag << endln;
return TCL_ERROR;
}
if (Tcl_GetDouble(interp, argv[6], &Su) != TCL_OK) {
opserr << "WARNING invalid alpha1\n";
opserr << "nDMaterial MultiaxialCyclicPlasticity: " << tag << endln;
return TCL_ERROR;
}
if (Tcl_GetDouble(interp, argv[7], &Ho) != TCL_OK) {
opserr << "WARNING invalid Ho\n";
opserr << "nDMaterial MultiaxialCyclicPlasticity: " << tag << endln;
return TCL_ERROR;
}
if (Tcl_GetDouble(interp, argv[8], &h) != TCL_OK) {
opserr << "WARNING invalid h\n";
opserr << "nDMaterial MultiaxialCyclicPlasticity: " << tag << endln;
return TCL_ERROR;
}
if (Tcl_GetDouble(interp, argv[9], &m) != TCL_OK) {
opserr << "WARNING invalid m\n";
opserr << "nDMaterial MultiaxialCyclicPlasticity: " << tag << endln;
return TCL_ERROR;
}
if (Tcl_GetDouble(interp, argv[10], &beta) != TCL_OK) {
opserr << "WARNING invalid beta\n";
opserr << "nDMaterial MultiaxialCyclicPlasticity: " << tag << endln;
return TCL_ERROR;
}
if (Tcl_GetDouble(interp, argv[11], &Kcoeff) != TCL_OK) {
opserr << "WARNING invalid Kcoeff\n";
opserr << "nDMaterial MultiaxialCyclicPlasticity: " << tag << endln;
return TCL_ERROR;
}
if (argc > 12 && Tcl_GetDouble(interp, argv[12], &eta) != TCL_OK) {
opserr << "WARNING invalid eta\n";
opserr << "nDMaterial MultiaxialCyclicPlasticity: " << tag << endln;
return TCL_ERROR;
}
theMaterial = new MultiaxialCyclicPlasticity (tag, 0, rho, K, G, Su, Ho, h,m,
beta, Kcoeff, eta);
}
// Pressure Independent Multi-yield, by ZHY
else if (strcmp(argv[1],"PressureIndependMultiYield") == 0) {
const int numParam = 6;
const int totParam = 10;
int tag; double param[totParam];
param[6] = 0.0;
param[7] = 100.;
param[8] = 0.0;
param[9] = 20;
char * arg[] = {"nd", "rho", "refShearModul", "refBulkModul",
"cohesi", "peakShearStra",
"frictionAng (=0)", "refPress (=100)", "pressDependCoe (=0.0)",
"numberOfYieldSurf (=20)"};
if (argc < (3+numParam)) {
opserr << "WARNING insufficient arguments\n";
printCommand(argc,argv);
opserr << "Want: nDMaterial PressureIndependMultiYield tag? " << arg[0];
opserr << "? "<< "\n";
opserr << arg[1] << "? "<< arg[2] << "? "<< arg[3] << "? "<< "\n";
opserr << arg[4] << "? "<< arg[5] << "? "<< arg[6] << "? "<< "\n";
opserr << arg[7] << "? "<< arg[8] << "? "<< arg[9] << "? "<<endln;
return TCL_ERROR;
}
if (Tcl_GetInt(interp, argv[2], &tag) != TCL_OK) {
opserr << "WARNING invalid PressureIndependMultiYield tag" << endln;
return TCL_ERROR;
}
for (int i=3; (i<argc && i<13); i++)
if (Tcl_GetDouble(interp, argv[i], ¶m[i-3]) != TCL_OK) {
opserr << "WARNING invalid " << arg[i-3] << "\n";
opserr << "nDMaterial PressureIndependMultiYield: " << tag << endln;
return TCL_ERROR;
}
static double * gredu = 0;
// user defined yield surfaces
if (param[9] < 0 && param[9] > -40) {
param[9] = -int(param[9]);
gredu = new double[int(2*param[9])];
for (int i=0; i<2*param[9]; i++)
if (Tcl_GetDouble(interp, argv[i+13], &gredu[i]) != TCL_OK) {
opserr << "WARNING invalid " << arg[i-3] << "\n";
opserr << "nDMaterial PressureIndependMultiYield: " << tag << endln;
return TCL_ERROR;
}
}
PressureIndependMultiYield * temp =
new PressureIndependMultiYield (tag, param[0], param[1], param[2],
param[3], param[4], param[5], param[6],
param[7], param[8], param[9], gredu);
theMaterial = temp;
if (gredu != 0) {
delete [] gredu;
gredu = 0;
}
}
// Pressure Independent Multi-yield, by Quan Gu
else if (strcmp(argv[1],"MultiYieldSurfaceClay") == 0) {
const int numParam = 6;
const int totParam = 10;
int tag; double param[totParam];
param[6] = 0.0;
param[7] = 100.;
param[8] = 0.0;
param[9] = 20;
char * arg[] = {"nd", "rho", "refShearModul", "refBulkModul",
"cohesi", "peakShearStra",
"frictionAng (=0)", "refPress (=100)", "pressDependCoe (=0.0)",
"numberOfYieldSurf (=20)"};
if (argc < (3+numParam)) {
opserr << "WARNING insufficient arguments\n";
printCommand(argc,argv);
opserr << "Want: nDMaterial MultiYieldSurfaceClay tag? " << arg[0];
opserr << "? "<< "\n";
opserr << arg[1] << "? "<< arg[2] << "? "<< arg[3] << "? "<< "\n";
opserr << arg[4] << "? "<< arg[5] << "? "<< arg[6] << "? "<< "\n";
opserr << arg[7] << "? "<< arg[8] << "? "<< arg[9] << "? "<<endln;
return TCL_ERROR;
}
if (Tcl_GetInt(interp, argv[2], &tag) != TCL_OK) {
opserr << "WARNING invalid MultiYieldSurfaceClay tag" << endln;
return TCL_ERROR;
}
for (int i=3; (i<argc && i<13); i++)
if (Tcl_GetDouble(interp, argv[i], ¶m[i-3]) != TCL_OK) {
opserr << "WARNING invalid " << arg[i-3] << "\n";
opserr << "nDMaterial MultiYieldSurfaceClay: " << tag << endln;
return TCL_ERROR;
}
static double * gredu = 0;
// user defined yield surfaces
if (param[9] < 0 && param[9] > -40) {
param[9] = -int(param[9]);
gredu = new double[int(2*param[9])];
for (int i=0; i<2*param[9]; i++)
if (Tcl_GetDouble(interp, argv[i+13], &gredu[i]) != TCL_OK) {
opserr << "WARNING invalid " << arg[i-3] << "\n";
opserr << "nDMaterial MultiYieldSurfaceClay: " << tag << endln;
return TCL_ERROR;
}
}
MultiYieldSurfaceClay * temp =
new MultiYieldSurfaceClay (tag, param[0], param[1], param[2],
param[3], param[4], param[5], param[6],
param[7], param[8], param[9], gredu);
theMaterial = temp;
if (gredu != 0) {
delete [] gredu;
gredu = 0;
}
}
// ============
// Pressure Dependent Multi-yield, by ZHY
else if (strcmp(argv[1],"PressureDependMultiYield") == 0) {
const int numParam = 15;
const int totParam = 24;
int tag;
double param[totParam];
param[15] = 20;
param[16] = 0.6;
param[17] = 0.9;
param[18] = 0.02;
param[19] = 0.7;
param[20] = 101.;
param[21] = .3;
param[22] = 0.;
param[23] = 1.;
char * arg[] = {"nd", "rho", "refShearModul",
"refBulkModul", "frictionAng",
"peakShearStra", "refPress", "pressDependCoe",
"phaseTransformAngle", "contractionParam1",
"dilationParam1", "dilationParam2",
"liquefactionParam1", "liquefactionParam2",
"liquefactionParam4", "numberOfYieldSurf (=20)",
"e (=0.6)", "volLimit1 (=0.9)", "volLimit2 (=0.02)",
"volLimit3 (=0.7)", "Atmospheric pressure (=101)", "cohesi (=.5)",
"Hv (=0)", "Pv (=1.)" };
if (argc < (3+numParam)) {
opserr << "WARNING insufficient arguments\n";
printCommand(argc,argv);
opserr << "Want: nDMaterial PressureDependMultiYield tag? "<< arg[0];
opserr << "? "<< "\n";
opserr << arg[1] << "? "<< arg[2] << "? "<< arg[3] << "? "<< "\n";
opserr << arg[4] << "? "<< arg[5] << "? "<< arg[6] << "? "<< "\n";
opserr << arg[7] << "? "<< arg[8] << "? "<< arg[9] << "? "<< "\n";
opserr << arg[10] << "? "<< arg[11] << "? "<< arg[12] << "? "<< "\n";
opserr << arg[13] << "? "<< arg[14] << "? "<< arg[15] << "? "<< "\n";
opserr << arg[16] << "? "<< arg[17] << "? "<< arg[18] << "? "<< "\n";
opserr << arg[19] << "? "<< arg[20] << "? "<< arg[21] << "? "<< endln;
return TCL_ERROR;
}
if (Tcl_GetInt(interp, argv[2], &tag) != TCL_OK) {
opserr << "WARNING invalid PressureDependMultiYield tag" << endln;
return TCL_ERROR;
}
for (int i=3; (i<argc && i<19); i++)
if (Tcl_GetDouble(interp, argv[i], ¶m[i-3]) != TCL_OK) {
opserr << "WARNING invalid " << arg[i-3] << "\n";
opserr << "nDMaterial PressureDependMultiYield: " << tag << endln;
return TCL_ERROR;
}
static double * gredu = 0;
// user defined yield surfaces
if (param[15] < 0 && param[15] > -40) {
param[15] = -int(param[15]);
gredu = new double[int(2*param[15])];
for (int i=0; i<2*param[15]; i++)
if (Tcl_GetDouble(interp, argv[i+19], &gredu[i]) != TCL_OK) {
opserr << "WARNING invalid " << arg[i-3] << "\n";
opserr << "nDMaterial PressureIndependMultiYield: " << tag << endln;
return TCL_ERROR;
}
}
if (gredu != 0) {
for (int i=19+int(2*param[15]); i<argc; i++)
if (Tcl_GetDouble(interp, argv[i], ¶m[i-3-int(2*param[15])]) != TCL_OK) {
opserr << "WARNING invalid " << arg[i-3-int(2*param[15])] << "\n";
opserr << "nDMaterial PressureDependMultiYield: " << tag << endln;
return TCL_ERROR;
}
} else {
for (int i=19; i<argc; i++)
if (Tcl_GetDouble(interp, argv[i], ¶m[i-3]) != TCL_OK) {
opserr << "WARNING invalid " << arg[i-3-int(2*param[15])] << "\n";
opserr << "nDMaterial PressureDependMultiYield: " << tag << endln;
return TCL_ERROR;
}
}
PressureDependMultiYield * temp =
new PressureDependMultiYield (tag, param[0], param[1], param[2],
param[3], param[4], param[5],
param[6], param[7], param[8],
param[9], param[10], param[11],
param[12], param[13], param[14],
param[15], gredu, param[16], param[17],
param[18], param[19], param[20], param[21], param[22], param[23]);
theMaterial = temp;
if (gredu != 0) {
delete [] gredu;
gredu = 0;
}
}
// Pressure Dependent Multi-yield, by ZHY
else if (strcmp(argv[1],"PressureDependMultiYield02") == 0) {
const int numParam = 13;
const int totParam = 26;
int tag;
double param[totParam];
param[numParam] = 20;
param[numParam+1] = 5.0;
param[numParam+2] = 3.;
param[numParam+3] = 1.;
param[numParam+4] = 0.;
param[numParam+5] = 0.6;
param[numParam+6] = 0.9;
param[numParam+7] = 0.02;
param[numParam+8] = 0.7;
param[numParam+9] = 101.;
param[numParam+10] = 0.1;
param[numParam+11] = 0.;
param[numParam+12] = 1.;
char * arg[] = {"nd", "rho", "refShearModul",
"refBulkModul", "frictionAng",
"peakShearStra", "refPress", "pressDependCoe",
"phaseTransformAngle", "contractionParam1",
"contractionParam3","dilationParam1","dilationParam3",
"numberOfYieldSurf (=20)",
"contractionParam2=5.0", "dilationParam2=3.0",
"liquefactionParam1=1.0", "liquefactionParam2=0.0",
"e (=0.6)", "volLimit1 (=0.9)", "volLimit2 (=0.02)",
"volLimit3 (=0.7)", "Atmospheric pressure (=101)", "cohesi (=.1)",
"Hv (=0)", "Pv (=1.)" };
if (argc < (3+numParam)) {
opserr << "WARNING insufficient arguments\n";
printCommand(argc,argv);
opserr << "Want: nDMaterial PressureDependMultiYield02 tag? "<< arg[0];
opserr << "? "<< "\n";
opserr << arg[1] << "? "<< arg[2] << "? "<< arg[3] << "? "<< "\n";
opserr << arg[4] << "? "<< arg[5] << "? "<< arg[6] << "? "<< "\n";
opserr << arg[7] << "? "<< arg[8] << "? "<< arg[9] << "? "<< "\n";
opserr << arg[10] << "? "<< arg[11] << "? "<< arg[12] << "? "<< "\n";
opserr << arg[13] << "? "<< arg[14] << "? "<< arg[15] << "? "<< "\n";
opserr << arg[16] << "? "<< arg[17] << "? "<< arg[18] << "? "<< "\n";
opserr << arg[19] << "? "<< arg[20] << "? "<< arg[21] << "? "<< "\n";
opserr << arg[22] << "? "<< arg[23] << "? " << endln;
return TCL_ERROR;
}
if (Tcl_GetInt(interp, argv[2], &tag) != TCL_OK) {
opserr << "WARNING invalid PressureDependMultiYield02 tag" << endln;
return TCL_ERROR;
}
int in = 17;
for (int i=3; (i<argc && i<in); i++)
if (Tcl_GetDouble(interp, argv[i], ¶m[i-3]) != TCL_OK) {
opserr << "WARNING invalid " << arg[i-3] << "\n";
opserr << "nDMaterial PressureDependMultiYield02: " << tag << endln;
return TCL_ERROR;
}
static double * gredu = 0;
// user defined yield surfaces
if (param[numParam] < 0 && param[numParam] > -100) {
param[numParam] = -int(param[numParam]);
gredu = new double[int(2*param[numParam])];
for (int i=0; i<2*param[numParam]; i++)
if (Tcl_GetDouble(interp, argv[i+in], &gredu[i]) != TCL_OK) {
opserr << "WARNING invalid " << arg[i-3] << "\n";
opserr << "nDMaterial PressureIndependMultiYield: " << tag << endln;
return TCL_ERROR;
}
}
if (gredu != 0) {
for (int i=in+int(2*param[numParam]); i<argc; i++)
if (Tcl_GetDouble(interp, argv[i], ¶m[i-3-int(2*param[numParam])]) != TCL_OK) {
opserr << "WARNING invalid " << arg[i-3-int(2*param[numParam])] << "\n";
opserr << "nDMaterial PressureDependMultiYield02: " << tag << endln;
return TCL_ERROR;
}
} else {
for (int i=in; i<argc; i++)
if (Tcl_GetDouble(interp, argv[i], ¶m[i-3]) != TCL_OK) {
opserr << "WARNING invalid " << arg[i-3-int(2*param[numParam])] << "\n";
opserr << "nDMaterial PressureDependMultiYield02: " << tag << endln;
return TCL_ERROR;
}
}
PressureDependMultiYield02 * temp =
new PressureDependMultiYield02 (tag, param[0], param[1], param[2],
param[3], param[4], param[5],
param[6], param[7], param[8],
param[9], param[10], param[11],
param[12], param[13], gredu, param[14],
param[15], param[16], param[17],
param[18], param[19], param[20], param[21],
param[22], param[23], param[24], param[25]);
theMaterial = temp;
if (gredu != 0) {
delete [] gredu;
gredu = 0;
}
}
// nDMaterial PressureDependMultiYield03 $tag $nd $rho $refShearModul $refBulkModul
// $frictionAng $peakShearStra $refPress $pressDependCoe $PTAng
// $mType $ca $cb $cc $cd $ce $da $db $dc <$noYieldSurf=20
// <$r1 $Gs1 …> $liquefac1=1. $liquefac2=0. $pa=101 <$c=1.73>>
// PressureDependMultiYield03 (based on PressureDependMultiYield02).
else if (strcmp(argv[1], "PressureDependMultiYield03") == 0) {
const int numParam = 18;
const int totParam = 23;
int tag;
double param[totParam];
param[numParam] = 20;
param[numParam + 1] = 1.;
param[numParam + 2] = 0.;
param[numParam + 3] = 101.;
param[numParam + 4] = 1.73;
char * arg[] = { "nd", "rho", "refShearModul","refBulkModul", "frictionAng",
"peakShearStra", "refPress", "pressDependCoe", "phaseTransformAngle",
"mType","ca", "cb", "cc", "cd", "ce", "da", "db", "dc",
"numberOfYieldSurf (=20)", "liquefactionParam1=1.0", "liquefactionParam2=0.0",
"Atmospheric pressure (=101)", "cohesi (=1.73)" };
if (argc < (3 + numParam)) { // 3 refers to "nDMaterial PressureDependMultiYield03 $tag"
opserr << "WARNING insufficient arguments\n";
printCommand(argc, argv);
opserr << "Want: nDMaterial PressureDependMultiYield03 tag? " << arg[0];
opserr << "? " << "\n";
opserr << arg[1] << "? " << arg[2] << "? " << arg[3] << "? " << "\n";
opserr << arg[4] << "? " << arg[5] << "? " << arg[6] << "? " << "\n";
opserr << arg[7] << "? " << arg[8] << "? " << arg[9] << "? " << "\n";
opserr << arg[10] << "? " << arg[11] << "? " << arg[12] << "? " << "\n";
opserr << arg[13] << "? " << arg[14] << "? " << arg[15] << "? " << "\n";
opserr << arg[16] << "? " << arg[17] << "? " << arg[18] << "? " << "\n";
opserr << arg[19] << "? " << arg[20] << "? " << arg[21] << "? " << arg[22] << "? " << endln;
return TCL_ERROR;
}
if (Tcl_GetInt(interp, argv[2], &tag) != TCL_OK) {
opserr << "WARNING invalid PressureDependMultiYield03 tag" << endln;
return TCL_ERROR;
}
int in = 22;
for (int i = 3; (i<argc && i<in); i++)
if (Tcl_GetDouble(interp, argv[i], ¶m[i - 3]) != TCL_OK) {
opserr << "WARNING invalid " << arg[i - 3] << "\n";
opserr << "nDMaterial PressureDependMultiYield03: " << tag << endln;
return TCL_ERROR;
}
static double * gredu = 0;
// user defined yield surfaces
if (param[numParam] < 0 && param[numParam] > -100) {
param[numParam] = -int(param[numParam]);
gredu = new double[int(2 * param[numParam])];
for (int i = 0; i<2 * param[numParam]; i++)
if (Tcl_GetDouble(interp, argv[i + in], &gredu[i]) != TCL_OK) {
opserr << "WARNING invalid " << arg[i - 3] << "\n";
opserr << "nDMaterial PressureDependMultiYield03: " << tag << endln;
return TCL_ERROR;
}
}
if (gredu != 0) {
for (int i = in + int(2 * param[numParam]); i<argc; i++)
if (Tcl_GetDouble(interp, argv[i], ¶m[i - 3 - int(2 * param[numParam])]) != TCL_OK) {
opserr << "WARNING invalid " << arg[i - 3 - int(2 * param[numParam])] << "\n";
opserr << "nDMaterial PressureDependMultiYield03: " << tag << endln;
return TCL_ERROR;
}
}
else {
for (int i = in; i<argc; i++)
if (Tcl_GetDouble(interp, argv[i], ¶m[i - 3]) != TCL_OK) {
opserr << "WARNING invalid " << arg[i - 3 - int(2 * param[numParam])] << "\n";
opserr << "nDMaterial PressureDependMultiYield03: " << tag << endln;
return TCL_ERROR;
}
}
PressureDependMultiYield03 * temp =
new PressureDependMultiYield03(tag, param[0], param[1], param[2],
param[3], param[4], param[5],
param[6], param[7], param[8],
param[9], param[10], param[11],
param[12], param[13], param[14],
param[15], param[16], param[17], param[18], gredu,
param[19], param[20], param[21], param[22]);
theMaterial = temp;
if (gredu != 0) {
delete[] gredu;
gredu = 0;
}
}
// Fluid Solid Porous, by ZHY
else if (strcmp(argv[1],"FluidSolidPorous") == 0) {
int tag; double param[4];
char * arg[] = {"nd", "soilMatTag", "combinedBulkModul", "Atmospheric pressure"};
if (argc < 6) {
opserr << "WARNING insufficient arguments\n";
printCommand(argc,argv);
opserr << "Want: nDMaterial FluidSolidPorous tag? "<< arg[0];
opserr << "? "<< "\n";
opserr << arg[1] << "? "<< arg[2] << "? "<< endln;
return TCL_ERROR;
}
if (Tcl_GetInt(interp, argv[2], &tag) != TCL_OK) {
opserr << "WARNING invalid FluidSolidPorous tag" << endln;
return TCL_ERROR;
}
for (int i=3; i<6; i++)
if (Tcl_GetDouble(interp, argv[i], ¶m[i-3] ) != TCL_OK) {
opserr << "WARNING invalid " << arg[i-3] << "\n";
opserr << "nDMaterial FluidSolidPorous: " << tag << endln;
return TCL_ERROR;
}
NDMaterial *soil = OPS_getNDMaterial(param[1]);
if (soil == 0) {
opserr << "WARNING FluidSolidPorous: couldn't get soil material ";
opserr << "tagged: " << param[1] << "\n";
return TCL_ERROR;
}
param[3] = 101.;
if (argc == 7) {
if (Tcl_GetDouble(interp, argv[6], ¶m[3] ) != TCL_OK) {
opserr << "WARNING invalid " << arg[3] << "\n";
opserr << "nDMaterial FluidSolidPorous: " << tag << endln;
return TCL_ERROR;
}
}
theMaterial = new FluidSolidPorousMaterial (tag, param[0], *soil,
param[2],param[3]);
}
else if (strcmp(argv[1],"PlaneStressMaterial") == 0 ||
strcmp(argv[1],"PlaneStress") == 0) {
if (argc < 4) {
opserr << "WARNING insufficient arguments\n";
printCommand(argc,argv);
opserr << "Want: nDMaterial PlaneStress tag? matTag?" << endln;
return TCL_ERROR;
}
int tag, matTag;
if (Tcl_GetInt(interp, argv[2], &tag) != TCL_OK) {
opserr << "WARNING invalid nDMaterial PlaneStress tag" << endln;
return TCL_ERROR;
}
if (Tcl_GetInt (interp, argv[3], &matTag) != TCL_OK) {
opserr << "WARNING invalid matTag" << endln;
opserr << "PlaneStress: " << matTag << endln;
return TCL_ERROR;
}
NDMaterial *threeDMaterial = OPS_getNDMaterial(matTag);
if (threeDMaterial == 0) {
opserr << "WARNING nD material does not exist\n";
opserr << "nD material: " << matTag;
opserr << "\nPlaneStress nDMaterial: " << tag << endln;
return TCL_ERROR;
}
theMaterial = new PlaneStressMaterial( tag, *threeDMaterial );
}
// PlaneStrainMaterial
else if (strcmp(argv[1],"PlaneStrainMaterial") == 0 ||
strcmp(argv[1],"PlaneStrain") == 0) {
if (argc < 4) {
opserr << "WARNING insufficient arguments\n";
printCommand(argc,argv);
opserr << "Want: nDMaterial PlaneStrain tag? matTag?" << endln;
return TCL_ERROR;
}
int tag, matTag;
if (Tcl_GetInt(interp, argv[2], &tag) != TCL_OK) {
opserr << "WARNING invalid nDMaterial PlaneStrain tag" << endln;
return TCL_ERROR;
}
if (Tcl_GetInt (interp, argv[3], &matTag) != TCL_OK) {
opserr << "WARNING invalid matTag" << endln;
opserr << "PlaneStrain: " << matTag << endln;
return TCL_ERROR;
}
NDMaterial *threeDMaterial = OPS_getNDMaterial(matTag);
if (threeDMaterial == 0) {
opserr << "WARNING nD material does not exist\n";
opserr << "nD material: " << matTag;
opserr << "\nPlaneStrain nDMaterial: " << tag << endln;
return TCL_ERROR;
}
theMaterial = new PlaneStrainMaterial( tag, *threeDMaterial );
}
else if (strcmp(argv[1],"PlateFiberMaterial") == 0 ||
strcmp(argv[1],"PlateFiber") == 0) {
void *theMat = OPS_PlateFiberMaterial();
if (theMat != 0)
theMaterial = (NDMaterial *)theMat;
else
return TCL_ERROR;
}
// ----- Cap plasticity model ------ // Quan Gu & ZhiJian Qiu 2013
// format nDmaterial CapPlasticity $tag $ndm $rho $G $K $X $D $W $R $lambda $theta $beta $alpha $T $tol
else if (strcmp(argv[1],"CapPlasticity") == 0) {
int tag;
int ndm =3;
double rho = 0.0;
double G = 1.0e10;
double K = 1.1e10;
double X = 1.1032e8;
double D = 4.6412e-10;
double W = 0.42;
double R = 4.43;
double lambda = 7.9979e6;
double theta = 0.11;
double beta = 6.3816e-8;
double alpha = 2.6614e7;
double T = -2.0684e6;
double tol = 1.0e-10;
if (Tcl_GetInt(interp, argv[2], &tag) != TCL_OK) {
opserr << "WARNING invalid CapPlasticity tag" << endln;
return TCL_ERROR;
}
if (Tcl_GetInt(interp, argv[3], &ndm) != TCL_OK) {
opserr << "WARNING invalid CapPlasticity nd" << endln;
return TCL_ERROR;
}
if (Tcl_GetDouble(interp, argv[4], &rho) != TCL_OK) {
opserr << "WARNING invalid CapPlasticity rho" << endln;
return TCL_ERROR;
}
if (Tcl_GetDouble(interp, argv[5], &G) != TCL_OK) {
opserr << "WARNING invalid CapPlasticity G" << endln;
return TCL_ERROR;
}
if (Tcl_GetDouble(interp, argv[6], &K) != TCL_OK) {
opserr << "WARNING invalid CapPlasticity K" << endln;
return TCL_ERROR;
}
if (argc > 7) {
if (Tcl_GetDouble(interp, argv[7], &X) != TCL_OK) {
opserr << "WARNING invalid CapPlasticity X" << endln;
return TCL_ERROR;
}
if (Tcl_GetDouble(interp, argv[8], &D) != TCL_OK) {
opserr << "WARNING invalid CapPlasticity D" << endln;
return TCL_ERROR;
}
if (Tcl_GetDouble(interp, argv[9], &W) != TCL_OK) {
opserr << "WARNING invalid CapPlasticity W" << endln;
return TCL_ERROR;
}
if (Tcl_GetDouble(interp, argv[10], &R) != TCL_OK) {
opserr << "WARNING invalid CapPlasticity R" << endln;
return TCL_ERROR;
}
if (Tcl_GetDouble(interp, argv[11], &lambda) != TCL_OK) {
opserr << "WARNING invalid CapPlasticity lambda" << endln;
return TCL_ERROR;
}
if (Tcl_GetDouble(interp, argv[12], &theta) != TCL_OK) {
opserr << "WARNING invalid CapPlasticity theta" << endln;
return TCL_ERROR;
}
if (Tcl_GetDouble(interp, argv[13], &beta) != TCL_OK) {
opserr << "WARNING invalid CapPlasticity beta" << endln;
return TCL_ERROR;
}
if (Tcl_GetDouble(interp, argv[14], &alpha) != TCL_OK) {
opserr << "WARNING invalid CapPlasticity alpha" << endln;
return TCL_ERROR;
}
if (Tcl_GetDouble(interp, argv[15], &T) != TCL_OK) {
opserr << "WARNING invalid CapPlasticity T" << endln;
return TCL_ERROR;
}
if (Tcl_GetDouble(interp, argv[16], &tol) != TCL_OK) {
opserr << "WARNING invalid CapPlasticity tol" << endln;
return TCL_ERROR;
}
} //end if
theMaterial = new CapPlasticity( tag,
G,
K,
rho,
X,
D,
W,
R,
lambda,
theta,
beta,
alpha,
T,
ndm,
tol
) ;
}
/////////////////////////////////////////////////////////////////
/*
nDmaterial Simplified3DJ2 $matTag $G $K $sig0 $H_kin $H_iso
SimplifiedJ2 (int tag,
int nd,
double G,
double K,
double sigmaY0,
double H_kin,
double H_iso);
*/
// Check argv[1] for J2PlaneStrain material type
else if ((strcmp(argv[1],"Simplified3DJ2") == 0) || (strcmp(argv[1],"3DJ2") == 0)) {
if (argc < 8) {
opserr << "WARNING insufficient arguments\n";
printCommand(argc,argv);
opserr << "Want: nDmaterial Simplified3DJ2 $matTag $G $K $sig0 $H_kin $H_iso" << endln;
return TCL_ERROR;
}
int tag;
double K, G, sig0, H_kin, H_iso;
if (Tcl_GetInt(interp, argv[2], &tag) != TCL_OK) {
opserr << "WARNING invalid SimplifiedJ2 tag" << endln;
return TCL_ERROR;
}
if (Tcl_GetDouble(interp, argv[3], &G) != TCL_OK) {
opserr << "WARNING invalid G\n";
opserr << "nDMaterial SimplifiedJ2: " << tag << endln;
return TCL_ERROR;
}
if (Tcl_GetDouble(interp, argv[4], &K) != TCL_OK) {
opserr << "WARNING invalid K\n";
opserr << "nDMaterial SimplifiedJ2: " << tag << endln;
return TCL_ERROR;
}
if (Tcl_GetDouble(interp, argv[5], &sig0) != TCL_OK) {
opserr << "WARNING invalid sig0\n";
opserr << "nDMaterial SimplifiedJ2: " << tag << endln;
return TCL_ERROR;
}
if (Tcl_GetDouble(interp, argv[6], &H_kin) != TCL_OK) {
opserr << "WARNING invalid H_kin\n";
opserr << "nDMaterial SimplifiedJ2: " << tag << endln;
return TCL_ERROR;
}
if (Tcl_GetDouble(interp, argv[7], &H_iso) != TCL_OK) {
opserr << "WARNING invalid H_iso\n";
opserr << "nDMaterial SimplifiedJ2: " << tag << endln;
return TCL_ERROR;
}
theMaterial = new SimplifiedJ2 (tag,
3,
G,
K,
sig0,
H_kin,
H_iso);
}
else if (strcmp(argv[1],"PlateRebarMaterial") == 0 ||
strcmp(argv[1],"PlateRebar") == 0) {
if (argc < 5) {
opserr << "WARNING insufficient arguments\n";
printCommand(argc,argv);
opserr << "Want: nDMaterial PlateRebar tag? matTag? angle?" << endln;
return TCL_ERROR;
}
int tag, matTag;
double angle;
if (Tcl_GetInt(interp, argv[2], &tag) != TCL_OK) {
opserr << "WARNING invalid nDMaterial PlateRebar tag" << endln;
return TCL_ERROR;
}
if (Tcl_GetInt (interp, argv[3], &matTag) != TCL_OK) {
opserr << "WARNING invalid matTag" << endln;
opserr << "PlateRebar: " << tag << endln;
return TCL_ERROR;
}
UniaxialMaterial *theMat = OPS_getUniaxialMaterial(matTag);
if (theMat == 0) {
opserr << "WARNING uniaxialmaterial does not exist\n";
opserr << "UniaxialMaterial: " << matTag;
opserr << "\nPlateRebar nDMaterial: " << tag << endln;
return TCL_ERROR;
}
if (Tcl_GetDouble (interp, argv[4], &angle) != TCL_OK) {
opserr << "WARNING invalid angle" << endln;
opserr << "PlateRebar: " << tag << endln;
return TCL_ERROR;
}
theMaterial = new PlateRebarMaterial( tag, *theMat, angle );
}
//start Yuli Huang & Xinzheng Lu PlateFromPlaneStressMaterial
else if (strcmp(argv[1],"PlateFromPlaneStressMaterial") == 0 ||
strcmp(argv[1],"PlateFromPlaneStress") == 0) {
if (argc < 5) {
opserr << "WARNING insufficient arguments\n";
printCommand(argc,argv);
opserr << "Want: nDMaterial PlateFromPlaneStress tag? matTag? gmod?" << endln;
return TCL_ERROR;
}
int tag, matTag;
double gmod;
if (Tcl_GetInt(interp, argv[2], &tag) != TCL_OK) {
opserr << "WARNING invalid nDMaterial PlateFromPlaneStress tag" << endln;
return TCL_ERROR;
}
if (Tcl_GetInt (interp, argv[3], &matTag) != TCL_OK) {
opserr << "WARNING invalid matTag" << endln;
opserr << "PlateFromPlaneStress: " << tag << endln;
return TCL_ERROR;
}
NDMaterial *theMat = OPS_getNDMaterial(matTag);
if (theMat == 0) {
opserr << "WARNING ndMaterial does not exist\n";
opserr << "ndMaterial: " << matTag;
opserr << "\nPlateFromPlaneStress nDMaterial: " << tag << endln;
return TCL_ERROR;
}
if (Tcl_GetDouble (interp, argv[4], &gmod) != TCL_OK) {
opserr << "WARNING invalid gmod" << endln;
opserr << "PlateFromPlaneStress: " << tag << endln;
return TCL_ERROR;
}
theMaterial = new PlateFromPlaneStressMaterial( tag, *theMat, gmod );
}
//start Yuli Huang & Xinzheng Lu ConcreteS
else if (strcmp(argv[1],"ConcreteS") == 0) {
if (argc < 8) {
opserr << "WARNING insufficient arguments\n";
printCommand(argc,argv);
opserr << "Want: nDMaterial ConcreteS tag? E? nu? fc? ft? Es?" << endln;
return TCL_ERROR;
}
int tag;
double E, nu, fc, ft, Es;
if (Tcl_GetInt(interp, argv[2], &tag) != TCL_OK) {
opserr << "WARNING invalid nDMaterial ConcreteS tag" << endln;
return TCL_ERROR;
}
if (Tcl_GetDouble (interp, argv[3], &E) != TCL_OK) {
opserr << "WARNING invalid E" << endln;
opserr << "ConcreteS: " << tag << endln;
return TCL_ERROR;
}
if (Tcl_GetDouble (interp, argv[4], &nu) != TCL_OK) {
opserr << "WARNING invalid nu" << endln;
opserr << "ConcreteS: " << tag << endln;
return TCL_ERROR;
}
if (Tcl_GetDouble (interp, argv[5], &fc) != TCL_OK) {
opserr << "WARNING invalid fc" << endln;
opserr << "ConcreteS: " << tag << endln;
return TCL_ERROR;
}
if (Tcl_GetDouble (interp, argv[6], &ft) != TCL_OK) {
opserr << "WARNING invalid ft" << endln;
opserr << "ConcreteS: " << tag << endln;
return TCL_ERROR;
}
if (Tcl_GetDouble (interp, argv[7], &Es) != TCL_OK) {
opserr << "WARNING invalid Es" << endln;
opserr << "ConcreteS: " << tag << endln;
return TCL_ERROR;
}
theMaterial = new ConcreteS( tag, E, nu, fc, ft, Es);
}
//end Yuli Huang & Xinzheng Lu ConcreteS
//start Yuli Huang & Xinzheng Lu PlaneStressUserMaterial
else if (strcmp(argv[1],"PlaneStressUserMaterial") == 0) {
if (argc < 6) {
opserr << "WARNING insufficient arguments\n";
printCommand(argc,argv);
opserr << "Want: nDMaterial PlaneStressUserMaterial tag? nstatevs? nprops? prop1? ... propn?" << endln;
return TCL_ERROR;
}
int tag, nstatevs, nprops;
double *props, p;
if (Tcl_GetInt(interp, argv[2], &tag) != TCL_OK) {
opserr << "WARNING invalid nDMaterial PlaneStressUserMaterial tag" << endln;
return TCL_ERROR;
}
if (Tcl_GetInt(interp, argv[3], &nstatevs) != TCL_OK) {
opserr << "WARNING invalid nDMaterial PlaneStressUserMaterial nstatevs" << endln;
return TCL_ERROR;
}
if (nstatevs < 1) nstatevs = 1;
if (Tcl_GetInt(interp, argv[4], &nprops) != TCL_OK) {
opserr << "WARNING invalid nDMaterial PlaneStressUserMaterial nprops" << endln;
return TCL_ERROR;
}
if (nprops < 1) nprops = 1;
props = new double[nprops];
for (int i = 0; i < nprops; i++) {
if (Tcl_GetDouble (interp, argv[5+i], &p) != TCL_OK) {
opserr << "WARNING invalid prop" << endln;
opserr << "PlaneStressUserMaterial: " << tag << endln;
return TCL_ERROR;
}
props[i] = p;
}
theMaterial = new PlaneStressUserMaterial( tag, nstatevs, nprops, props);
if (props != 0) delete props;
}
//end Yuli Huang & Xinzheng Lu PlaneStressUserMaterial
else if (strcmp(argv[1],"BeamFiberMaterial") == 0 ||
strcmp(argv[1],"BeamFiber") == 0) {
void *theMat = OPS_BeamFiberMaterial();
if (theMat != 0)
theMaterial = (NDMaterial *)theMat;
else
return TCL_ERROR;
}
else if (strcmp(argv[1],"BeamFiberMaterial2d") == 0 ||
strcmp(argv[1],"BeamFiber2d") == 0) {
void *theMat = OPS_BeamFiberMaterial2d();
if (theMat != 0)
theMaterial = (NDMaterial *)theMat;
else
return TCL_ERROR;
}
else if (strcmp(argv[1],"BeamFiberMaterial2dPS") == 0 ||
strcmp(argv[1],"BeamFiber2dPS") == 0) {
void *theMat = OPS_BeamFiberMaterial2dPS();
if (theMat != 0)
theMaterial = (NDMaterial *)theMat;
else
return TCL_ERROR;
}
else if (strcmp(argv[1],"ConcreteMcftNonLinear7") == 0 || strcmp(argv[1],"ConcreteMcftNonLinear5") == 0) {
if (argc < 11) {
opserr << "WARNING insufficient arguments\n";
printCommand(argc,argv);
opserr << "Want: nDMaterial ConcreteMcftNonlinear7 tag? fcu? ecu? Ec? fcr? Esv? fyv? alphaV? RoV?" << endln;
return TCL_ERROR;
}
int tag = 0;
double fcu = 0.0;
double ecu = 0.0;
double Ec = 0.0;
double fcr = 0.0;
double Esv = 0.0;
double fyv = 0.0;
double alphaV = 0.0;
double RoV = 0.0;
if (Tcl_GetInt(interp, argv[2], &tag) != TCL_OK) {
opserr << "WARNING invalid ConcreteMcftNonlinear7: tag" << endln;
return TCL_ERROR;
}
if (Tcl_GetDouble(interp, argv[3], &fcu) != TCL_OK) {
opserr << "WARNING invalid fcu\n";
opserr << "nDMaterial ConcreteMcftNonLinearNonLinear5: fcu" << tag << endln;
return TCL_ERROR;
}
if (Tcl_GetDouble(interp, argv[4], &ecu) != TCL_OK) {
opserr << "WARNING invalid ecu\n";
opserr << "nDMaterial ConcreteMcftNonLinearNonLinear5: ecu" << tag << endln;
return TCL_ERROR;
}
if (Tcl_GetDouble(interp, argv[5], &Ec) != TCL_OK) {
opserr << "WARNING invalid Ec\n";
opserr << "nDMaterial ConcreteMcftNonlinear7: Ec" << tag << endln;
return TCL_ERROR;
}
if (Tcl_GetDouble(interp, argv[6], &fcr) != TCL_OK) {
opserr << "WARNING invalid fcr\n";
opserr << "nDMaterial ConcreteMcftNonlinear7: fcr" << tag << endln;
return TCL_ERROR;
}
if (Tcl_GetDouble(interp, argv[7], &Esv) != TCL_OK) {
opserr << "WARNING invalid Esv\n";
opserr << "nDMaterial ConcreteMcftNonlinear7: Esv" << tag << endln;
return TCL_ERROR;
}
if (Tcl_GetDouble(interp, argv[8], &fyv) != TCL_OK) {
opserr << "WARNING invalid fyv\n";
opserr << "nDMaterial ConcreteMcftNonlinear7: fyv" << tag << endln;
return TCL_ERROR;
}
if (Tcl_GetDouble(interp, argv[9], &alphaV) != TCL_OK) {
opserr << "WARNING invalid alphaV\n";
opserr << "nDMaterial ConcreteMcftNonlinear7: alphaV" << tag << endln;
return TCL_ERROR;
}
if (Tcl_GetDouble(interp, argv[10], &RoV) != TCL_OK) {
opserr << "WARNING invalid RoV\n";
opserr << "nDMaterial ConcreteMcftNonlinear7: RoV" << tag << endln;
return TCL_ERROR;
}
if (strcmp(argv[1],"ConcreteMcftNonLinear7") == 0)
theMaterial = new ConcreteMcftNonLinear7 (tag, fcu, ecu, Ec, fcr, Esv, fyv, alphaV, RoV);
else
theMaterial = new ConcreteMcftNonLinear5 (tag, fcu, ecu, Ec, fcr, Esv, fyv, alphaV, RoV);
}
else if (strcmp(argv[1],"Bidirectional") == 0) {
opserr << "nDMaterial Bidirectional is now a section model, please "
<< "change to \'section Bidirectional\'" << endln;
return TCL_ERROR;
}
//-------nD materials for thermo-mechanical analysis---Added by L.Jiang[SIF]
else if ((strcmp(argv[1], "DruckerPragerThermal") == 0)) {
void *theMat = OPS_DruckerPragerMaterialThermal();
if (theMat != 0)
theMaterial = (NDMaterial *)theMat;
else
return TCL_ERROR;
}
//-------------------------------------------------------------
/*
else if ((strcmp(argv[1], "CDPPlaneStressThermal") == 0)) {
void *theMat = OPS_PlasticDamageConcretePlaneStressThermal();
if (theMat != 0)
theMaterial = (NDMaterial *)theMat;
else
return TCL_ERROR;
}
*/
//-------------------------------------------------------------
else if (strcmp(argv[1], "PlateFromPlaneStressThermal") == 0 ) {
if (argc < 5) {
opserr << "WARNING insufficient arguments\n";
printCommand(argc, argv);
opserr << "Want: nDMaterial PlateFromPlaneStress tag? matTag? gmod?" << endln;
return TCL_ERROR;
}
int tag, matTag;
double gmod;
if (Tcl_GetInt(interp, argv[2], &tag) != TCL_OK) {
opserr << "WARNING invalid nDMaterial PlateFromPlaneStress tag" << endln;
return TCL_ERROR;
}
if (Tcl_GetInt(interp, argv[3], &matTag) != TCL_OK) {
opserr << "WARNING invalid matTag" << endln;
opserr << "PlateFromPlaneStress: " << tag << endln;
return TCL_ERROR;
}
NDMaterial *theMat = OPS_getNDMaterial(matTag);
if (theMat == 0) {
opserr << "WARNING ndMaterial does not exist\n";
opserr << "ndMaterial: " << matTag;
opserr << "\nPlateFromPlaneStress nDMaterial: " << tag << endln;
return TCL_ERROR;
}
if (Tcl_GetDouble(interp, argv[4], &gmod) != TCL_OK) {
opserr << "WARNING invalid gmod" << endln;
opserr << "PlateFromPlaneStress: " << tag << endln;
return TCL_ERROR;
}
theMaterial = new PlateFromPlaneStressMaterialThermal(tag, *theMat, gmod);
}
else if (strcmp(argv[1], "PlateRebarMaterialThermal") == 0 ||
strcmp(argv[1], "PlateRebarThermal") == 0) {
if (argc < 5) {
opserr << "WARNING insufficient arguments\n";
printCommand(argc, argv);
opserr << "Want: nDMaterial PlateRebar tag? matTag? angle?" << endln;
return TCL_ERROR;
}
int tag, matTag;
double angle;
if (Tcl_GetInt(interp, argv[2], &tag) != TCL_OK) {
opserr << "WARNING invalid nDMaterial PlateRebar tag" << endln;
return TCL_ERROR;
}
if (Tcl_GetInt(interp, argv[3], &matTag) != TCL_OK) {
opserr << "WARNING invalid matTag" << endln;
opserr << "PlateRebar: " << tag << endln;
return TCL_ERROR;
}
UniaxialMaterial *theMat = OPS_getUniaxialMaterial(matTag);
if (theMat == 0) {
opserr << "WARNING uniaxialmaterial does not exist\n";
opserr << "UniaxialMaterial: " << matTag;
opserr << "\nPlateRebar nDMaterial: " << tag << endln;
return TCL_ERROR;
}
if (Tcl_GetDouble(interp, argv[4], &angle) != TCL_OK) {
opserr << "WARNING invalid angle" << endln;
opserr << "PlateRebar: " << tag << endln;
return TCL_ERROR;
}
theMaterial = new PlateRebarMaterialThermal(tag, *theMat, angle);
}
else if ((strcmp(argv[1], "J2PlasticityThermal") == 0) ||
(strcmp(argv[1], "J2Thermal") == 0)) {
if (argc < 9) {
opserr << "WARNING insufficient arguments\n";
printCommand(argc, argv);
opserr << "Want: nDMaterial J2PlasticityThermal tag? K? G? sig0? sigInf? delta? H? <eta?>" << endln;
return TCL_ERROR;
}
int tag;
double K, G, sig0, sigInf, delta, H;
double eta = 0.0;
if (Tcl_GetInt(interp, argv[2], &tag) != TCL_OK) {
opserr << "WARNING invalid J2PlasticityThermal tag" << endln;
return TCL_ERROR;
}
if (Tcl_GetDouble(interp, argv[3], &K) != TCL_OK) {
opserr << "WARNING invalid K\n";
opserr << "nDMaterial J2PlasticityThermal: " << tag << endln;
return TCL_ERROR;
}
if (Tcl_GetDouble(interp, argv[4], &G) != TCL_OK) {
opserr << "WARNING invalid G\n";
opserr << "nDMaterial J2PlasticityThermal: " << tag << endln;
return TCL_ERROR;
}
if (Tcl_GetDouble(interp, argv[5], &sig0) != TCL_OK) {
opserr << "WARNING invalid sig0\n";
opserr << "nDMaterial J2PlasticityThermal: " << tag << endln;
return TCL_ERROR;
}
if (Tcl_GetDouble(interp, argv[6], &sigInf) != TCL_OK) {
opserr << "WARNING invalid sigInf\n";
opserr << "nDMaterial J2PlasticityThermal: " << tag << endln;
return TCL_ERROR;
}
if (Tcl_GetDouble(interp, argv[7], &delta) != TCL_OK) {
opserr << "WARNING invalid delta\n";
opserr << "nDMaterial J2PlasticityThermal: " << tag << endln;
return TCL_ERROR;
}
if (Tcl_GetDouble(interp, argv[8], &H) != TCL_OK) {
opserr << "WARNING invalid H\n";
opserr << "nDMaterial J2PlasticityThermal: " << tag << endln;
return TCL_ERROR;
}
if (argc > 9 && Tcl_GetDouble(interp, argv[9], &eta) != TCL_OK) {
opserr << "WARNING invalid eta\n";
opserr << "nDMaterial J2PlasticityThermal: " << tag << endln;
return TCL_ERROR;
}
theMaterial = new J2PlasticityThermal(tag, 0, K, G, sig0, sigInf,
delta, H, eta);
}
else if (strcmp(argv[1], "PlateFiberMaterialThermal") == 0 ||
strcmp(argv[1], "PlateFiberThermal") == 0) {
if (argc < 4) {
opserr << "WARNING insufficient arguments\n";
printCommand(argc, argv);
opserr << "Want: nDMaterial PlateFiberThermal tag? matTag?" << endln;
return TCL_ERROR;
}
int tag, matTag;
if (Tcl_GetInt(interp, argv[2], &tag) != TCL_OK) {
opserr << "WARNING invalid nDMaterial PlateFiberThermal tag" << endln;
return TCL_ERROR;
}
if (Tcl_GetInt(interp, argv[3], &matTag) != TCL_OK) {
opserr << "WARNING invalid matTag" << endln;
opserr << "PlateFiberThermal: " << matTag << endln;
return TCL_ERROR;
}
NDMaterial *threeDMaterial = OPS_getNDMaterial(matTag);
if (threeDMaterial == 0) {
opserr << "WARNING nD material does not exist\n";
opserr << "nD material: " << matTag;
opserr << "\nPlateFiberThermal nDMaterial: " << tag << endln;
return TCL_ERROR;
}
theMaterial = new PlateFiberMaterialThermal(tag, *threeDMaterial);
}
//--------End of adding PlateFiberMaterialThermal
else if ( (strcmp(argv[1], "ElasticIsotropicThermal") == 0) || (strcmp(argv[1], "ElasticIsotropic3DThermal") == 0)) {
void *theMat = OPS_ElasticIsotropicMaterialThermal();
if (theMat != 0)
theMaterial = (NDMaterial *)theMat;
else
return TCL_ERROR;
}
//end of adding thermo-mechanical nd materials-L.Jiang[SIF]
#if defined(OPSDEF_Material_FEAP)
else {
theMaterial = TclModelBuilder_addFeapMaterial(clientData,
interp,
argc,
argv,
theTclBuilder);
}
#endif // _OPS_Material_FEAP
if (theMaterial == 0) {
//
// maybe element in a class package already loaded
// loop through linked list of loaded functions comparing names & if find call it
//
NDMaterialPackageCommand *matCommands = theNDMaterialPackageCommands;
bool found = false;
while (matCommands != NULL && found == false) {
if (strcmp(argv[1], matCommands->funcName) == 0) {
theMaterial = (NDMaterial *)(*(matCommands->funcPtr))();
found = true;;
} else
matCommands = matCommands->next;
}
}
//
// check to see if element is a procedure
// the proc may already have been loaded from a package or may exist in a package yet to be loaded
//
if (theMaterial == 0) {
// maybe material in a routine
//
char *matType = new char[strlen(argv[1])+1];
strcpy(matType, argv[1]);
matObj *matObject = OPS_GetMaterialType(matType, strlen(matType));
delete [] matType;
if (matObject != 0) {
theMaterial = Tcl_addWrapperNDMaterial(matObject, clientData, interp,
argc, argv, theTclBuilder);
if (theMaterial == 0)
delete matObject;
}
}
//
// maybe material class exists in a package yet to be loaded
//
if (theMaterial == 0) {
void *libHandle;
void * (*funcPtr)();
int matNameLength = strlen(argv[1]);
char *tclFuncName = new char[matNameLength+12];
strcpy(tclFuncName, "OPS_");
strcpy(&tclFuncName[4], argv[1]);
int res = getLibraryFunction(argv[1], tclFuncName, &libHandle, (void **)&funcPtr);
delete [] tclFuncName;
if (res == 0) {
//
// add loaded function to list of functions
//
char *matName = new char[matNameLength+1];
strcpy(matName, argv[1]);
NDMaterialPackageCommand *theMatCommand = new NDMaterialPackageCommand;
theMatCommand->funcPtr = funcPtr;
theMatCommand->funcName = matName;
theMatCommand->next = theNDMaterialPackageCommands;
theNDMaterialPackageCommands = theMatCommand;
theMaterial = (NDMaterial *)(*funcPtr)();
}
}
if (theMaterial == 0) {
opserr << "WARNING could not create nDMaterial: " << argv[1];
return TCL_ERROR;
}
// Now add the material to the modelBuilder
if (OPS_addNDMaterial(theMaterial) == false) {
opserr << "WARNING could not add material to the domain\n";
opserr << *theMaterial << endln;
delete theMaterial; // invoke the material objects destructor, otherwise mem leak
return TCL_ERROR;
}
return TCL_OK;
}
| 31.263276 | 131 | 0.594009 | [
"model",
"solid"
] |
d1e9d88dd0bcf287f6593c730d31fce58420764b | 2,988 | cpp | C++ | tests/src/tests_ArrayView.cpp | Mike-Bal/mart-common | 0b52654c6f756e8e86689e56d24849c97079229c | [
"MIT"
] | 1 | 2021-07-16T14:19:50.000Z | 2021-07-16T14:19:50.000Z | tests/src/tests_ArrayView.cpp | Mike-Bal/mart-common | 0b52654c6f756e8e86689e56d24849c97079229c | [
"MIT"
] | 1 | 2018-06-05T11:03:30.000Z | 2018-06-05T11:03:30.000Z | tests/src/tests_ArrayView.cpp | tum-ei-rcs/mart-common | 6f8f18ac23401eb294d96db490fbdf78bf9b316c | [
"MIT"
] | null | null | null | #include <mart-common/ArrayView.h>
#include <mart-common/algorithm.h>
#include <catch2/catch.hpp>
#include <algorithm>
#include <array>
#include <iterator>
#include <vector>
TEST_CASE( "constructed_from_container_has_same_elements", "[ArrayView]" )
{
int na1[] = {-3};
int na2[] = {-3, 1, 5, 6, 7, 8};
std::array<int, 1> a1 = {-10};
std::array<int, 10> a2 = {-15, 1, 2, 3, 4, 5, 6, 7, 8, 9};
std::vector<int> v1{};
std::vector<int> v2{-10};
std::vector<int> v3{-15, 1, 2, 3, 4, 5, 6, 7, 8, 9};
mart::ArrayView<int> view_na1( na1 );
mart::ArrayView<int> view_na2( na2 );
mart::ArrayView<int> view_a1( a1 );
mart::ArrayView<int> view_a2( a2 );
mart::ArrayView<int> view_v1( v1 );
mart::ArrayView<int> view_v2( v2 );
mart::ArrayView<int> view_v3( v3 );
CHECK( std::equal( std::begin( na1 ), std::end( na1 ), view_na1.begin(), view_na1.end() ) );
CHECK( std::equal( std::begin( na2 ), std::end( na2 ), view_na2.begin(), view_na2.end() ) );
CHECK( std::equal( a1.begin(), a1.end(), view_a1.begin(), view_a1.end() ) );
CHECK( std::equal( a2.begin(), a2.end(), view_a2.begin(), view_a2.end() ) );
CHECK( std::equal( v1.begin(), v1.end(), view_v1.begin(), view_v1.end() ) );
CHECK( std::equal( v2.begin(), v2.end(), view_v2.begin(), view_v2.end() ) );
CHECK( std::equal( v3.begin(), v3.end(), view_v3.begin(), view_v3.end() ) );
}
//TEST_CASE( "array_view_subview_throws_when_invalid_range_is_specified", "[ArrayView]" )
//{
// int na[] = {-3, 1, 5, 6, 7, 8};
//
// mart::ArrayView<int> view_na( na );
//
// bool exception_thrown = false;
//
// try {
//
// [[maybe_unused]] auto sr = view_na.subview( 0, 100 );
//
// } catch( ... ) {
// exception_thrown = true;
// }
//
// CHECK( exception_thrown );
//}
TEST_CASE( "array_view_copy_works_and_doesnt_collide_with_general_std_copy_wrapper", "[ArrayView]" )
{
const std::vector<int> src = {-3, 1, 5, 6, 7, 8};
std::vector<int> dest( src.size() + 5 );
mart::ArrayView<const int> view_src( src );
mart::ArrayView<int> view_dest( dest );
auto ret = mart::copy( view_src, view_dest );
CHECK( mart::equal( view_src, view_dest.subview( 0, view_src.size() ) ) );
CHECK( mart::equal( view_src, ret.copied ) );
CHECK( ret.free_space.size() == dest.size() - src.size() );
}
TEST_CASE( "asBytes", "[ArrayView]" )
{
int i{1};
const int ci{2};
auto crange1 = mart::view_bytes( i );
auto crange2 = mart::view_bytes_const( i );
auto crange3 = mart::view_bytes( ci );
auto range1 = mart::view_bytes_mutable( i );
static_assert( std::is_same_v<decltype( crange1 ), mart::ConstMemoryView> );
static_assert( std::is_same_v<decltype( crange2 ), mart::ConstMemoryView> );
static_assert( std::is_same_v<decltype( crange3 ), mart::ConstMemoryView> );
static_assert( std::is_same_v<decltype( range1 ), mart::MemoryView> );
CHECK( crange1.size() == sizeof( ci ) );
CHECK( crange2.size() == sizeof( ci ) );
CHECK( crange3.size() == sizeof( ci ) );
CHECK( range1.size() == sizeof( i ) );
}
| 30.181818 | 100 | 0.632865 | [
"vector"
] |
d1eaab8983480b90729cd34e9efd31425311dd29 | 1,967 | cpp | C++ | QimWatermarking/QimWatermarking/lsb.cpp | CdricGmd/Qim-Integrity-App | 4eac721c3855942cb85cd1a6473272c4cfcb8069 | [
"MIT"
] | 3 | 2015-04-21T09:23:33.000Z | 2017-12-19T06:22:00.000Z | QimWatermarking/QimWatermarking/lsb.cpp | CdricGmd/Qim-Integrity-App | 4eac721c3855942cb85cd1a6473272c4cfcb8069 | [
"MIT"
] | null | null | null | QimWatermarking/QimWatermarking/lsb.cpp | CdricGmd/Qim-Integrity-App | 4eac721c3855942cb85cd1a6473272c4cfcb8069 | [
"MIT"
] | null | null | null | #include <opencv2/opencv.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/core/mat.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include "lsb.hpp"
using namespace std;
using namespace cv;
void insert_lsb(Mat& image, vector<int> mark);
void extract_lsb(Mat& image, vector<int>& mark);
void MarkToBinayImage(vector<int> mark, Mat& bintatoo);
void insert_lsb(Mat& image, vector<int> mark) {
// get a binary mask
Mat tatoo;
resize(tatoo, tatoo, image.size());
MarkToBinayImage(mark, tatoo);
// Intensity
Mat image_HSV;
Mat imIntensity;
cvtColor(image, image_HSV, CV_RGB2HSV);
vector<Mat> hsv_channel(3);
split(image_HSV, hsv_channel);
imIntensity = hsv_channel[2].clone();
// LSB
// (8-1 =) 110 & XYZ = XY0;
Mat notlsb_mask = 254
* Mat::ones(imIntensity.rows, imIntensity.cols, CV_8U);
bitwise_and(imIntensity, notlsb_mask, imIntensity);
add(imIntensity, tatoo, imIntensity);
// Save RGB image
hsv_channel[2] = imIntensity.clone();
merge(hsv_channel, image_HSV);
// image_w = Mat(image.size().height, image.size().width, image.type());
cvtColor(image_HSV, image, CV_HSV2RGB);
}
void extract_lsb(Mat& image, vector<int>& mark) {
// get the V (Value = Intensity) channel for the image.
Mat image_HSV;
Mat imIntensity;
cvtColor(image, image_HSV, CV_RGB2HSV);
vector<Mat> hsv_channel(3);
split(image_HSV, hsv_channel);
imIntensity = hsv_channel[2];
//hsv_channel[2].convertTo(imIntensity, CV_8U);
for (size_t i = 0; i < imIntensity.rows; i++)
for (size_t j = 0; j < imIntensity.cols; j++)
mark.push_back(imIntensity.at<uchar>(j, i) & 01);
}
void MarkToBinayImage(vector<int> mark, Mat& bintatoo) {
bintatoo.convertTo(bintatoo, CV_8U);
int index = 0;
int marksize = mark.size();
for (size_t i = 0; i < bintatoo.rows; i++)
for (size_t j = 0; j < bintatoo.cols; j++) {
bintatoo.at<uchar>(j, i) = mark[index % marksize] & 01;
index++;
}
}
| 28.507246 | 74 | 0.674631 | [
"vector"
] |
d1eaed4bfec6846c3f8b016ec3d33975d493b07e | 3,638 | cpp | C++ | mx_sensitivity/child_element_NDNBJ1.cpp | mrcstan/Opt-IGFEM-2D | 834d07727cd30cfac6368d9bb67202b8a20a4d4c | [
"NCSA"
] | null | null | null | mx_sensitivity/child_element_NDNBJ1.cpp | mrcstan/Opt-IGFEM-2D | 834d07727cd30cfac6368d9bb67202b8a20a4d4c | [
"NCSA"
] | null | null | null | mx_sensitivity/child_element_NDNBJ1.cpp | mrcstan/Opt-IGFEM-2D | 834d07727cd30cfac6368d9bb67202b8a20a4d4c | [
"NCSA"
] | null | null | null | /*
Created by Marcus Tan on 8/17/2014
Modified on 12/28/2014
Copyright 2014 University of Illinois
Purpose: this function calculates shape functions, B matrix of the child
and parent elements as well as the Jacobian of the child element
mapping to the global space
INPUT:
paLocOrigNodes: parent local number of original nodes
chLocPaEnrichNodes: child local number of enrichnment nodes wrt parent
chLocEnrichNodes: child local number of enrichment nodes wrt itself
shape: TRIANGULAR or QUADRILATERAL
nNodes: total number of nodes of IGFEM element
Xel: dim x nOriginalNodes matrix of original element coordinates
Xch: dim x nChildNodes of child element coordinates
locCoord: a vector of the local coordinates
OUTPUT:
N: shape functions
B: derivative of shape functions wrt global coordinates
(note: the size of the matrix is nNodesPerElem x dim)
invJ: inverse of Jacobian
detJ: determinant of Jacobian
INPUT_OUTPUT:
DNch: nChildNodes x dim DN matrix of child element
Bch: nChildNodes of child element x dim B matrix of child element
Bel: B matrix of original element
calcBJch: flag indicating whether the B matrix of the child element should be calculated.
if true, it calculates the matrix and returns a false if child element is triangular
calcBel: flag indicating whether the B matrix of the parent element should be calculated.
if true, it calculates the matrix and returns a false
*/
#include "sensitivity.h"
#include "armadillo"
#include <cstddef>
namespace igfem
{
void child_element_NDNBJ(arma::vec& N,
arma::mat& B,
arma::mat& DNch,
arma::mat& Bch,
arma::mat& DNel,
arma::mat& Bel,
arma::mat& invJ,
double& detJ,
bool& calcBJch,
bool& calcBel,
std::size_t nNodes,
const arma::uvec& paLocOrigNodes,
const arma::uvec& chLocPaEnrichNodes,
const arma::uvec& chLocEnrichNodes,
const arma::mat& Xel,
const arma::mat& Xch,
const arma::vec& locCoord,
shapes shape)
{
N = arma::zeros<arma::vec>(nNodes);
B = arma::zeros<arma::mat>(nNodes,Xel.n_rows);
// calculate shape functions, B matrix and Jacobian of child element
arma::vec Nch; // child shape function
shape_function_2D(Nch,DNch,locCoord,shape);
if (calcBJch)
{
arma::mat Jch = Xch*DNch;
detJ = arma::det(Jch);
if (detJ > JACTOL)
{
invJ = arma::inv(Jch);
Bch = DNch*invJ;
}
else
{
invJ = arma::zeros<arma::mat>(Xel.n_rows,Xel.n_rows);
Bch = arma::zeros<arma::mat>(DNch.n_rows,DNch.n_cols);
}
if (shape == TRIANGLE)
calcBJch = false;
}
N(chLocPaEnrichNodes) = Nch(chLocEnrichNodes);
B.rows(chLocPaEnrichNodes) = Bch.rows(chLocEnrichNodes);
// calculate shape functions, B matrix of nodes belonging to parent element
arma::vec locCoordPa = local_coord_2D(Xch*Nch,Xel);
arma::vec Nel;
shape_function_2D(Nel,DNel,locCoordPa);
if (calcBel)
{
arma::mat Jel = Xel*DNel;
Bel = arma::trans(arma::solve(Jel.t(),DNel.t()));
calcBel = false;
}
N(paLocOrigNodes) = Nel;
B.rows(paLocOrigNodes) = Bel;
}
}
| 35.320388 | 98 | 0.60033 | [
"shape",
"vector"
] |
d1f76f1818d0c8d26f4aea1d38fb99b779f5f258 | 85,878 | cpp | C++ | moses/mira/Main.cpp | anshsarkar/TailBench | 25845756aee9a892229c25b681051591c94daafd | [
"MIT"
] | 3 | 2018-01-25T00:51:56.000Z | 2022-01-07T15:09:38.000Z | moses/mira/Main.cpp | anshsarkar/TailBench | 25845756aee9a892229c25b681051591c94daafd | [
"MIT"
] | 1 | 2021-11-25T18:08:22.000Z | 2021-11-25T18:08:22.000Z | moses/mira/Main.cpp | anshsarkar/TailBench | 25845756aee9a892229c25b681051591c94daafd | [
"MIT"
] | 3 | 2018-06-08T08:36:27.000Z | 2021-12-26T20:36:16.000Z | /***********************************************************************
Moses - factored phrase-based language decoder
Copyright (C) 2010 University of Edinburgh
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
***********************************************************************/
#include <algorithm>
#include <cstdlib>
#include <ctime>
#include <string>
#include <vector>
#include <map>
#include <boost/program_options.hpp>
#include <boost/algorithm/string.hpp>
#ifdef MPI_ENABLE
#include <boost/mpi.hpp>
namespace mpi = boost::mpi;
#endif
#include "Main.h"
#include "Optimiser.h"
#include "Hildreth.h"
#include "HypothesisQueue.h"
#include "moses/FeatureVector.h"
#include "moses/StaticData.h"
#include "moses/ChartTrellisPathList.h"
#include "moses/ChartTrellisPath.h"
#include "moses/ScoreComponentCollection.h"
#include "moses/ThreadPool.h"
#include "moses/DummyScoreProducers.h"
#include "moses/LexicalReordering.h"
#include "moses/WordTranslationFeature.h"
#include "moses/PhrasePairFeature.h"
#include "mert/BleuScorer.h"
using namespace Mira;
using namespace std;
using namespace Moses;
namespace po = boost::program_options;
int main(int argc, char** argv) {
size_t rank = 0;
size_t size = 1;
#ifdef MPI_ENABLE
mpi::environment env(argc,argv);
mpi::communicator world;
rank = world.rank();
size = world.size();
#endif
bool help;
int verbosity;
string mosesConfigFile;
string inputFile;
vector<string> referenceFiles;
vector<string> mosesConfigFilesFolds, inputFilesFolds, referenceFilesFolds;
// string coreWeightFile, startWeightFile;
size_t epochs;
string learner;
bool shuffle;
size_t mixingFrequency;
size_t weightDumpFrequency;
string weightDumpStem;
bool scale_margin, scale_margin_precision;
bool scale_update, scale_update_precision;
size_t n;
size_t batchSize;
bool distinctNbest;
bool accumulateWeights;
float historySmoothing;
bool scaleByInputLength, scaleByAvgInputLength;
bool scaleByInverseLength, scaleByAvgInverseLength;
float scaleByX;
float slack;
bool averageWeights;
bool weightConvergence;
float learning_rate;
float mira_learning_rate;
float perceptron_learning_rate;
string decoder_settings;
float min_weight_change;
bool normaliseWeights, normaliseMargin;
bool print_feature_values;
bool historyBleu ;
bool sentenceBleu;
bool perceptron_update;
bool hope_fear;
bool model_hope_fear;
int hope_n, fear_n;
size_t bleu_smoothing_scheme;
float min_oracle_bleu;
float minBleuRatio, maxBleuRatio;
bool boost;
bool decode_hope, decode_fear, decode_model;
string decode_filename;
bool batchEqualsShard;
bool sparseAverage, dumpMixedWeights, sparseNoAverage;
int featureCutoff;
bool pruneZeroWeights;
bool printFeatureCounts, printNbestWithFeatures;
bool avgRefLength;
bool print_weights, print_core_weights, debug_model, scale_lm, scale_wp;
float scale_lm_factor, scale_wp_factor;
bool kbest;
string moses_src;
float sigmoidParam;
float bleuWeight, bleuWeight_hope, bleuWeight_fear;
bool bleu_weight_lm, bleu_weight_lm_adjust;
float bleu_weight_lm_factor;
bool l1_regularize, l2_regularize, l1_reg_sparse, l2_reg_sparse;
float l1_lambda, l2_lambda;
bool most_violated, most_violated_reg, all_violated, max_bleu_diff, one_against_all;
bool feature_confidence, signed_counts;
float decay_core, decay_sparse, core_r0, sparse_r0;
bool selective, summed;
float bleu_weight_fear_factor;
bool hildreth;
float add2lm;
bool realBleu, disableBleuFeature;
bool rescaleSlack;
bool makePairs;
bool debug;
bool reg_on_every_mix;
size_t continue_epoch;
bool modelPlusBleu, simpleHistoryBleu;
po::options_description desc("Allowed options");
desc.add_options()
("continue-epoch", po::value<size_t>(&continue_epoch)->default_value(0), "Continue an interrupted experiment from this epoch on")
("freq-reg", po::value<bool>(®_on_every_mix)->default_value(false), "Regularize after every weight mixing")
("l1sparse", po::value<bool>(&l1_reg_sparse)->default_value(true), "L1-regularization for sparse weights only")
("l2sparse", po::value<bool>(&l2_reg_sparse)->default_value(true), "L2-regularization for sparse weights only")
("mv-reg", po::value<bool>(&most_violated_reg)->default_value(false), "Regularize most violated constraint")
("dbg", po::value<bool>(&debug)->default_value(true), "More debug output")
("make-pairs", po::value<bool>(&makePairs)->default_value(true), "Make pairs of hypotheses for 1slack")
("debug", po::value<bool>(&debug)->default_value(true), "More debug output")
("rescale-slack", po::value<bool>(&rescaleSlack)->default_value(false), "Rescale slack in 1-slack formulation")
("disable-bleu-feature", po::value<bool>(&disableBleuFeature)->default_value(false), "Disable the Bleu feature")
("real-bleu", po::value<bool>(&realBleu)->default_value(false), "Compute real sentence Bleu on complete translations")
("add2lm", po::value<float>(&add2lm)->default_value(0.0), "Add the specified amount to all LM weights")
("hildreth", po::value<bool>(&hildreth)->default_value(false), "Prefer Hildreth over analytical update")
("selective", po::value<bool>(&selective)->default_value(false), "Build constraints for every feature")
("summed", po::value<bool>(&summed)->default_value(false), "Sum up all constraints")
("model-plus-bleu", po::value<bool>(&modelPlusBleu)->default_value(false), "Use the sum of model score and +/- bleu to select hope and fear translations")
("simple-history-bleu", po::value<bool>(&simpleHistoryBleu)->default_value(false), "Simple history Bleu")
("bleu-weight", po::value<float>(&bleuWeight)->default_value(1.0), "Bleu weight used in decoder objective")
("bw-hope", po::value<float>(&bleuWeight_hope)->default_value(-1.0), "Bleu weight used in decoder objective for hope")
("bw-fear", po::value<float>(&bleuWeight_fear)->default_value(-1.0), "Bleu weight used in decoder objective for fear")
("core-r0", po::value<float>(&core_r0)->default_value(1.0), "Start learning rate for core features")
("sparse-r0", po::value<float>(&sparse_r0)->default_value(1.0), "Start learning rate for sparse features")
("tie-bw-to-lm", po::value<bool>(&bleu_weight_lm)->default_value(false), "Make bleu weight depend on lm weight")
("adjust-bw", po::value<bool>(&bleu_weight_lm_adjust)->default_value(false), "Adjust bleu weight when lm weight changes")
("bw-lm-factor", po::value<float>(&bleu_weight_lm_factor)->default_value(2.0), "Make bleu weight depend on lm weight by this factor")
("bw-factor-fear", po::value<float>(&bleu_weight_fear_factor)->default_value(1.0), "Multiply fear weight by this factor")
("accumulate-weights", po::value<bool>(&accumulateWeights)->default_value(false), "Accumulate and average weights over all epochs")
("average-weights", po::value<bool>(&averageWeights)->default_value(false), "Set decoder weights to average weights after each update")
("avg-ref-length", po::value<bool>(&avgRefLength)->default_value(false), "Use average reference length instead of shortest for BLEU score feature")
("batch-equals-shard", po::value<bool>(&batchEqualsShard)->default_value(false), "Batch size is equal to shard size (purely batch)")
("batch-size,b", po::value<size_t>(&batchSize)->default_value(1), "Size of batch that is send to optimiser for weight adjustments")
("bleu-smoothing-scheme", po::value<size_t>(&bleu_smoothing_scheme)->default_value(1), "Set a smoothing scheme for sentence-Bleu: +1 (1), +0.1 (2), papineni (3) (default:1)")
("boost", po::value<bool>(&boost)->default_value(false), "Apply boosting factor to updates on misranked candidates")
("config,f", po::value<string>(&mosesConfigFile), "Moses ini-file")
("configs-folds", po::value<vector<string> >(&mosesConfigFilesFolds), "Moses ini-files, one for each fold")
("debug-model", po::value<bool>(&debug_model)->default_value(false), "Get best model translation for debugging purposes")
("decode-hope", po::value<bool>(&decode_hope)->default_value(false), "Decode dev input set according to hope objective")
("decode-fear", po::value<bool>(&decode_fear)->default_value(false), "Decode dev input set according to fear objective")
("decode-model", po::value<bool>(&decode_model)->default_value(false), "Decode dev input set according to normal objective")
("decode-filename", po::value<string>(&decode_filename), "Filename for Bleu objective translations")
("decoder-settings", po::value<string>(&decoder_settings)->default_value(""), "Decoder settings for tuning runs")
("distinct-nbest", po::value<bool>(&distinctNbest)->default_value(true), "Use n-best list with distinct translations in inference step")
("dump-mixed-weights", po::value<bool>(&dumpMixedWeights)->default_value(false), "Dump mixed weights instead of averaged weights")
("epochs,e", po::value<size_t>(&epochs)->default_value(10), "Number of epochs")
("feature-cutoff", po::value<int>(&featureCutoff)->default_value(-1), "Feature cutoff as additional regularization for sparse features")
("fear-n", po::value<int>(&fear_n)->default_value(1), "Number of fear translations used")
("help", po::value(&help)->zero_tokens()->default_value(false), "Print this help message and exit")
("history-bleu", po::value<bool>(&historyBleu)->default_value(false), "Use 1best translations to update the history")
("history-smoothing", po::value<float>(&historySmoothing)->default_value(0.9), "Adjust the factor for history smoothing")
("hope-fear", po::value<bool>(&hope_fear)->default_value(true), "Use only hope and fear translations for optimisation (not model)")
("hope-n", po::value<int>(&hope_n)->default_value(2), "Number of hope translations used")
("input-file,i", po::value<string>(&inputFile), "Input file containing tokenised source")
("input-files-folds", po::value<vector<string> >(&inputFilesFolds), "Input files containing tokenised source, one for each fold")
("learner,l", po::value<string>(&learner)->default_value("mira"), "Learning algorithm")
("l1-lambda", po::value<float>(&l1_lambda)->default_value(0.0001), "Lambda for l1-regularization (w_i +/- lambda)")
("l2-lambda", po::value<float>(&l2_lambda)->default_value(0.01), "Lambda for l2-regularization (w_i * (1 - lambda))")
("l1-reg", po::value<bool>(&l1_regularize)->default_value(false), "L1-regularization")
("l2-reg", po::value<bool>(&l2_regularize)->default_value(false), "L2-regularization")
("min-bleu-ratio", po::value<float>(&minBleuRatio)->default_value(-1), "Set a minimum BLEU ratio between hope and fear")
("max-bleu-ratio", po::value<float>(&maxBleuRatio)->default_value(-1), "Set a maximum BLEU ratio between hope and fear")
("max-bleu-diff", po::value<bool>(&max_bleu_diff)->default_value(true), "Select hope/fear with maximum Bleu difference")
("min-oracle-bleu", po::value<float>(&min_oracle_bleu)->default_value(0), "Set a minimum oracle BLEU score")
("min-weight-change", po::value<float>(&min_weight_change)->default_value(0.0001), "Set minimum weight change for stopping criterion")
("mira-learning-rate", po::value<float>(&mira_learning_rate)->default_value(1), "Learning rate for MIRA (fixed or flexible)")
("mixing-frequency", po::value<size_t>(&mixingFrequency)->default_value(1), "How often per epoch to mix weights, when using mpi")
("model-hope-fear", po::value<bool>(&model_hope_fear)->default_value(false), "Use model, hope and fear translations for optimisation")
("moses-src", po::value<string>(&moses_src)->default_value(""), "Moses source directory")
("nbest,n", po::value<size_t>(&n)->default_value(1), "Number of translations in n-best list")
("normalise-weights", po::value<bool>(&normaliseWeights)->default_value(false), "Whether to normalise the updated weights before passing them to the decoder")
("normalise-margin", po::value<bool>(&normaliseMargin)->default_value(false), "Normalise the margin: squash between 0 and 1")
("perceptron-learning-rate", po::value<float>(&perceptron_learning_rate)->default_value(0.01), "Perceptron learning rate")
("print-feature-values", po::value<bool>(&print_feature_values)->default_value(false), "Print out feature values")
("print-feature-counts", po::value<bool>(&printFeatureCounts)->default_value(false), "Print out feature values, print feature list with hope counts after 1st epoch")
("print-nbest-with-features", po::value<bool>(&printNbestWithFeatures)->default_value(false), "Print out feature values, print feature list with hope counts after 1st epoch")
("print-weights", po::value<bool>(&print_weights)->default_value(false), "Print out current weights")
("print-core-weights", po::value<bool>(&print_core_weights)->default_value(true), "Print out current core weights")
("prune-zero-weights", po::value<bool>(&pruneZeroWeights)->default_value(false), "Prune zero-valued sparse feature weights")
("reference-files,r", po::value<vector<string> >(&referenceFiles), "Reference translation files for training")
("reference-files-folds", po::value<vector<string> >(&referenceFilesFolds), "Reference translation files for training, one for each fold")
("kbest", po::value<bool>(&kbest)->default_value(false), "Select hope/fear pairs from a list of nbest translations")
("scale-by-inverse-length", po::value<bool>(&scaleByInverseLength)->default_value(false), "Scale BLEU by (history of) inverse input length")
("scale-by-input-length", po::value<bool>(&scaleByInputLength)->default_value(false), "Scale BLEU by (history of) input length")
("scale-by-avg-input-length", po::value<bool>(&scaleByAvgInputLength)->default_value(false), "Scale BLEU by average input length")
("scale-by-avg-inverse-length", po::value<bool>(&scaleByAvgInverseLength)->default_value(false), "Scale BLEU by average inverse input length")
("scale-by-x", po::value<float>(&scaleByX)->default_value(1), "Scale the BLEU score by value x")
("scale-lm", po::value<bool>(&scale_lm)->default_value(false), "Scale the language model feature")
("scale-factor-lm", po::value<float>(&scale_lm_factor)->default_value(2), "Scale the language model feature by this factor")
("scale-wp", po::value<bool>(&scale_wp)->default_value(false), "Scale the word penalty feature")
("scale-factor-wp", po::value<float>(&scale_wp_factor)->default_value(2), "Scale the word penalty feature by this factor")
("scale-margin", po::value<bool>(&scale_margin)->default_value(0), "Scale the margin by the Bleu score of the oracle translation")
("scale-margin-precision", po::value<bool>(&scale_margin_precision)->default_value(0), "Scale margin by precision of oracle")
("scale-update", po::value<bool>(&scale_update)->default_value(0), "Scale update by Bleu score of oracle")
("scale-update-precision", po::value<bool>(&scale_update_precision)->default_value(0), "Scale update by precision of oracle")
("sentence-level-bleu", po::value<bool>(&sentenceBleu)->default_value(true), "Use a sentences level Bleu scoring function")
("shuffle", po::value<bool>(&shuffle)->default_value(false), "Shuffle input sentences before processing")
("sigmoid-param", po::value<float>(&sigmoidParam)->default_value(1), "y=sigmoidParam is the axis that this sigmoid approaches")
("slack", po::value<float>(&slack)->default_value(0.01), "Use slack in optimiser")
("sparse-average", po::value<bool>(&sparseAverage)->default_value(false), "Average weights by the number of processes")
("sparse-no-average", po::value<bool>(&sparseNoAverage)->default_value(false), "Don't average sparse weights, just sum")
("stop-weights", po::value<bool>(&weightConvergence)->default_value(true), "Stop when weights converge")
("verbosity,v", po::value<int>(&verbosity)->default_value(0), "Verbosity level")
("weight-dump-frequency", po::value<size_t>(&weightDumpFrequency)->default_value(1), "How often per epoch to dump weights (mpi)")
("weight-dump-stem", po::value<string>(&weightDumpStem)->default_value("weights"), "Stem of filename to use for dumping weights");
po::options_description cmdline_options;
cmdline_options.add(desc);
po::variables_map vm;
po::store(po::command_line_parser(argc, argv). options(cmdline_options).run(), vm);
po::notify(vm);
if (help) {
std::cout << "Usage: " + string(argv[0])
+ " -f mosesini-file -i input-file -r reference-file(s) [options]" << std::endl;
std::cout << desc << std::endl;
return 0;
}
const StaticData &staticData = StaticData::Instance();
bool trainWithMultipleFolds = false;
if (mosesConfigFilesFolds.size() > 0 || inputFilesFolds.size() > 0 || referenceFilesFolds.size() > 0) {
if (rank == 0)
cerr << "Training with " << mosesConfigFilesFolds.size() << " folds" << endl;
trainWithMultipleFolds = true;
}
if (dumpMixedWeights && (mixingFrequency != weightDumpFrequency)) {
cerr << "Set mixing frequency = weight dump frequency for dumping mixed weights!" << endl;
exit(1);
}
if ((sparseAverage || sparseNoAverage) && averageWeights) {
cerr << "Parameters --sparse-average 1/--sparse-no-average 1 and --average-weights 1 are incompatible (not implemented)" << endl;
exit(1);
}
if (trainWithMultipleFolds) {
if (!mosesConfigFilesFolds.size()) {
cerr << "Error: No moses ini files specified for training with folds" << endl;
exit(1);
}
if (!inputFilesFolds.size()) {
cerr << "Error: No input files specified for training with folds" << endl;
exit(1);
}
if (!referenceFilesFolds.size()) {
cerr << "Error: No reference files specified for training with folds" << endl;
exit(1);
}
}
else {
if (mosesConfigFile.empty()) {
cerr << "Error: No moses ini file specified" << endl;
return 1;
}
if (inputFile.empty()) {
cerr << "Error: No input file specified" << endl;
return 1;
}
if (!referenceFiles.size()) {
cerr << "Error: No reference files specified" << endl;
return 1;
}
}
// load input and references
vector<string> inputSentences;
size_t inputSize = trainWithMultipleFolds? inputFilesFolds.size(): 0;
size_t refSize = trainWithMultipleFolds? referenceFilesFolds.size(): referenceFiles.size();
vector<vector<string> > inputSentencesFolds(inputSize);
vector<vector<string> > referenceSentences(refSize);
// number of cores for each fold
size_t coresPerFold = 0, myFold = 0;
if (trainWithMultipleFolds) {
if (mosesConfigFilesFolds.size() > size) {
cerr << "Number of cores has to be a multiple of the number of folds" << endl;
exit(1);
}
coresPerFold = size/mosesConfigFilesFolds.size();
if (size % coresPerFold > 0) {
cerr << "Number of cores has to be a multiple of the number of folds" << endl;
exit(1);
}
if (rank == 0)
cerr << "Number of cores per fold: " << coresPerFold << endl;
myFold = rank/coresPerFold;
cerr << "Rank " << rank << ", my fold: " << myFold << endl;
}
// NOTE: we do not actually need the references here, because we are reading them in from StaticData
if (trainWithMultipleFolds) {
if (!loadSentences(inputFilesFolds[myFold], inputSentencesFolds[myFold])) {
cerr << "Error: Failed to load input sentences from " << inputFilesFolds[myFold] << endl;
exit(1);
}
VERBOSE(1, "Rank " << rank << " reading inputs from " << inputFilesFolds[myFold] << endl);
if (!loadSentences(referenceFilesFolds[myFold], referenceSentences[myFold])) {
cerr << "Error: Failed to load reference sentences from " << referenceFilesFolds[myFold] << endl;
exit(1);
}
if (referenceSentences[myFold].size() != inputSentencesFolds[myFold].size()) {
cerr << "Error: Input file length (" << inputSentencesFolds[myFold].size() << ") != ("
<< referenceSentences[myFold].size() << ") reference file length (rank " << rank << ")" << endl;
exit(1);
}
VERBOSE(1, "Rank " << rank << " reading references from " << referenceFilesFolds[myFold] << endl);
}
else {
if (!loadSentences(inputFile, inputSentences)) {
cerr << "Error: Failed to load input sentences from " << inputFile << endl;
return 1;
}
for (size_t i = 0; i < referenceFiles.size(); ++i) {
if (!loadSentences(referenceFiles[i], referenceSentences[i])) {
cerr << "Error: Failed to load reference sentences from "
<< referenceFiles[i] << endl;
return 1;
}
if (referenceSentences[i].size() != inputSentences.size()) {
cerr << "Error: Input file length (" << inputSentences.size() << ") != ("
<< referenceSentences[i].size() << ") length of reference file " << i
<< endl;
return 1;
}
}
}
if (scaleByAvgInputLength || scaleByInverseLength || scaleByAvgInverseLength)
scaleByInputLength = false;
if (historyBleu || simpleHistoryBleu) {
sentenceBleu = false;
cerr << "Using history Bleu. " << endl;
}
if (kbest) {
realBleu = true;
disableBleuFeature = true;
cerr << "Use kbest lists and real Bleu scores, disable Bleu feature.." << endl;
}
// initialise Moses
// add references to initialize Bleu feature
boost::trim(decoder_settings);
decoder_settings += " -mira -distinct-nbest -references";
if (trainWithMultipleFolds) {
decoder_settings += " ";
decoder_settings += referenceFilesFolds[myFold];
}
else {
for (size_t i=0; i < referenceFiles.size(); ++i) {
decoder_settings += " ";
decoder_settings += referenceFiles[i];
}
}
vector<string> decoder_params;
boost::split(decoder_params, decoder_settings, boost::is_any_of("\t "));
string configFile = trainWithMultipleFolds? mosesConfigFilesFolds[myFold] : mosesConfigFile;
VERBOSE(1, "Rank " << rank << " reading config file from " << configFile << endl);
MosesDecoder* decoder = new MosesDecoder(configFile, verbosity, decoder_params.size(), decoder_params);
decoder->setBleuParameters(disableBleuFeature, sentenceBleu, scaleByInputLength, scaleByAvgInputLength,
scaleByInverseLength, scaleByAvgInverseLength,
scaleByX, historySmoothing, bleu_smoothing_scheme, simpleHistoryBleu);
SearchAlgorithm searchAlgorithm = staticData.GetSearchAlgorithm();
bool chartDecoding = (searchAlgorithm == ChartDecoding);
// Optionally shuffle the sentences
vector<size_t> order;
if (trainWithMultipleFolds) {
for (size_t i = 0; i < inputSentencesFolds[myFold].size(); ++i) {
order.push_back(i);
}
}
else {
if (rank == 0) {
for (size_t i = 0; i < inputSentences.size(); ++i) {
order.push_back(i);
}
}
}
// initialise optimizer
Optimiser* optimiser = NULL;
if (learner == "mira") {
if (rank == 0) {
cerr << "Optimising using Mira" << endl;
cerr << "slack: " << slack << ", learning rate: " << mira_learning_rate << endl;
cerr << "selective: " << selective << endl;
if (normaliseMargin)
cerr << "sigmoid parameter: " << sigmoidParam << endl;
}
optimiser = new MiraOptimiser(slack, scale_margin, scale_margin_precision,
scale_update, scale_update_precision, boost, normaliseMargin, sigmoidParam);
learning_rate = mira_learning_rate;
perceptron_update = false;
} else if (learner == "perceptron") {
if (rank == 0) {
cerr << "Optimising using Perceptron" << endl;
}
optimiser = new Perceptron();
learning_rate = perceptron_learning_rate;
perceptron_update = true;
model_hope_fear = false; // mira only
hope_fear = false; // mira only
n = 1;
hope_n = 1;
fear_n = 1;
} else {
cerr << "Error: Unknown optimiser: " << learner << endl;
return 1;
}
// resolve parameter dependencies
if (batchSize > 1 && perceptron_update) {
batchSize = 1;
cerr << "Info: Setting batch size to 1 for perceptron update" << endl;
}
if (hope_n == -1)
hope_n = n;
if (fear_n == -1)
fear_n = n;
if (model_hope_fear || kbest)
hope_fear = false; // is true by default
if (learner == "mira" && !(hope_fear || model_hope_fear || kbest)) {
cerr << "Error: Need to select one of parameters --hope-fear/--model-hope-fear/--kbest for mira update." << endl;
return 1;
}
#ifdef MPI_ENABLE
if (!trainWithMultipleFolds)
mpi::broadcast(world, order, 0);
#endif
// Create shards according to the number of processes used
vector<size_t> shard;
if (trainWithMultipleFolds) {
size_t shardSize = order.size()/coresPerFold;
size_t shardStart = (size_t) (shardSize * (rank % coresPerFold));
size_t shardEnd = shardStart + shardSize;
if (rank % coresPerFold == coresPerFold - 1) { // last rank of each fold
shardEnd = order.size();
shardSize = shardEnd - shardStart;
}
VERBOSE(1, "Rank: " << rank << ", shard size: " << shardSize << endl);
VERBOSE(1, "Rank: " << rank << ", shard start: " << shardStart << " shard end: " << shardEnd << endl);
shard.resize(shardSize);
copy(order.begin() + shardStart, order.begin() + shardEnd, shard.begin());
batchSize = 1;
}
else {
size_t shardSize = order.size() / size;
size_t shardStart = (size_t) (shardSize * rank);
size_t shardEnd = (size_t) (shardSize * (rank + 1));
if (rank == size - 1) {
shardEnd = order.size();
shardSize = shardEnd - shardStart;
}
VERBOSE(1, "Rank: " << rank << " Shard size: " << shardSize << endl);
VERBOSE(1, "Rank: " << rank << " Shard start: " << shardStart << " Shard end: " << shardEnd << endl);
shard.resize(shardSize);
copy(order.begin() + shardStart, order.begin() + shardEnd, shard.begin());
if (batchEqualsShard)
batchSize = shardSize;
}
// get reference to feature functions
const vector<const ScoreProducer*> featureFunctions =
staticData.GetTranslationSystem(TranslationSystem::DEFAULT).GetFeatureFunctions();
ScoreComponentCollection initialWeights = decoder->getWeights();
bool tuneMetaFeature = false;
const vector<const FeatureFunction*>& sparseProducers = staticData.GetTranslationSystem(TranslationSystem::DEFAULT).GetSparseProducers();
for (unsigned i = 0; i < sparseProducers.size(); ++i) {
float spWeight = sparseProducers[i]->GetSparseProducerWeight();
if (spWeight != 1.0) {
tuneMetaFeature = true;
cerr << "Rank " << rank << ", sparse Producer " <<
sparseProducers[i]->GetScoreProducerWeightShortName()
<< " weight: " << spWeight << endl;
}
}
if (add2lm != 0) {
const LMList& lmList_new = staticData.GetLMList();
for (LMList::const_iterator i = lmList_new.begin(); i != lmList_new.end(); ++i) {
float lmWeight = initialWeights.GetScoreForProducer(*i) + add2lm;
initialWeights.Assign(*i, lmWeight);
cerr << "Rank " << rank << ", add " << add2lm << " to lm weight." << endl;
}
}
if (normaliseWeights) {
initialWeights.L1Normalise();
cerr << "Rank " << rank << ", normalised initial weights: " << initialWeights << endl;
}
decoder->setWeights(initialWeights);
// set bleu weight to twice the size of the language model weight(s)
const LMList& lmList = staticData.GetLMList();
if (bleu_weight_lm) {
float lmSum = 0;
for (LMList::const_iterator i = lmList.begin(); i != lmList.end(); ++i)
lmSum += abs(initialWeights.GetScoreForProducer(*i));
bleuWeight = lmSum * bleu_weight_lm_factor;
cerr << "Set bleu weight to lm weight * " << bleu_weight_lm_factor << endl;
}
if (bleuWeight_hope == -1) {
bleuWeight_hope = bleuWeight;
}
if (bleuWeight_fear == -1) {
bleuWeight_fear = bleuWeight;
}
bleuWeight_fear *= bleu_weight_fear_factor;
cerr << "Bleu weight: " << bleuWeight << endl;
cerr << "Bleu weight fear: " << bleuWeight_fear << endl;
if (decode_hope || decode_fear || decode_model) {
size_t decode = 1;
if (decode_fear) decode = 2;
if (decode_model) decode = 3;
decodeHopeOrFear(rank, size, decode, decode_filename, inputSentences, decoder, n, bleuWeight);
}
//Main loop:
ScoreComponentCollection cumulativeWeights; // collect weights per epoch to produce an average
ScoreComponentCollection cumulativeWeightsBinary;
size_t numberOfUpdates = 0;
size_t numberOfUpdatesThisEpoch = 0;
time_t now;
time(&now);
cerr << "Rank " << rank << ", " << ctime(&now);
float avgInputLength = 0;
float sumOfInputs = 0;
size_t numberOfInputs = 0;
ScoreComponentCollection mixedWeights;
ScoreComponentCollection mixedWeightsPrevious;
ScoreComponentCollection mixedWeightsBeforePrevious;
ScoreComponentCollection mixedAverageWeights;
ScoreComponentCollection mixedAverageWeightsPrevious;
ScoreComponentCollection mixedAverageWeightsBeforePrevious;
bool stop = false;
// int sumStillViolatedConstraints;
float epsilon = 0.0001;
// Variables for feature confidence
ScoreComponentCollection confidenceCounts, mixedConfidenceCounts, featureLearningRates;
featureLearningRates.UpdateLearningRates(decay_core, decay_sparse, confidenceCounts, core_r0, sparse_r0); //initialise core learning rates
cerr << "Initial learning rates, core: " << core_r0 << ", sparse: " << sparse_r0 << endl;
for (size_t epoch = continue_epoch; epoch < epochs && !stop; ++epoch) {
if (shuffle) {
if (trainWithMultipleFolds || rank == 0) {
cerr << "Rank " << rank << ", epoch " << epoch << ", shuffling input sentences.." << endl;
RandomIndex rindex;
random_shuffle(order.begin(), order.end(), rindex);
}
#ifdef MPI_ENABLE
if (!trainWithMultipleFolds)
mpi::broadcast(world, order, 0);
#endif
// redo shards
if (trainWithMultipleFolds) {
size_t shardSize = order.size()/coresPerFold;
size_t shardStart = (size_t) (shardSize * (rank % coresPerFold));
size_t shardEnd = shardStart + shardSize;
if (rank % coresPerFold == coresPerFold - 1) { // last rank of each fold
shardEnd = order.size();
shardSize = shardEnd - shardStart;
}
VERBOSE(1, "Rank: " << rank << ", shard size: " << shardSize << endl);
VERBOSE(1, "Rank: " << rank << ", shard start: " << shardStart << " shard end: " << shardEnd << endl);
shard.resize(shardSize);
copy(order.begin() + shardStart, order.begin() + shardEnd, shard.begin());
batchSize = 1;
}
else {
size_t shardSize = order.size()/size;
size_t shardStart = (size_t) (shardSize * rank);
size_t shardEnd = (size_t) (shardSize * (rank + 1));
if (rank == size - 1) {
shardEnd = order.size();
shardSize = shardEnd - shardStart;
}
VERBOSE(1, "Shard size: " << shardSize << endl);
VERBOSE(1, "Rank: " << rank << " Shard start: " << shardStart << " Shard end: " << shardEnd << endl);
shard.resize(shardSize);
copy(order.begin() + shardStart, order.begin() + shardEnd, shard.begin());
if (batchEqualsShard)
batchSize = shardSize;
}
}
// sum of violated constraints in an epoch
// sumStillViolatedConstraints = 0;
numberOfUpdatesThisEpoch = 0;
// Sum up weights over one epoch, final average uses weights from last epoch
if (!accumulateWeights) {
cumulativeWeights.ZeroAll();
cumulativeWeightsBinary.ZeroAll();
}
// number of weight dumps this epoch
size_t weightMixingThisEpoch = 0;
size_t weightEpochDump = 0;
size_t shardPosition = 0;
vector<size_t>::const_iterator sid = shard.begin();
while (sid != shard.end()) {
// feature values for hypotheses i,j (matrix: batchSize x 3*n x featureValues)
vector<vector<ScoreComponentCollection> > featureValues;
vector<vector<float> > bleuScores;
vector<vector<float> > modelScores;
// variables for hope-fear/perceptron setting
vector<vector<ScoreComponentCollection> > featureValuesHope;
vector<vector<ScoreComponentCollection> > featureValuesFear;
vector<vector<float> > bleuScoresHope;
vector<vector<float> > bleuScoresFear;
vector<vector<float> > modelScoresHope;
vector<vector<float> > modelScoresFear;
// get moses weights
ScoreComponentCollection mosesWeights = decoder->getWeights();
VERBOSE(1, "\nRank " << rank << ", epoch " << epoch << ", weights: " << mosesWeights << endl);
if (historyBleu || simpleHistoryBleu) {
decoder->printBleuFeatureHistory(cerr);
}
if (tuneMetaFeature) {
// initialise meta feature
MetaFeatureProducer *m = staticData.GetMetaFeatureProducer();
FeatureFunction* ff = const_cast<FeatureFunction*>(sparseProducers[0]);
if (sparseProducers[0]->GetScoreProducerWeightShortName().compare("wt") == 0) {
WordTranslationFeature* wt =
static_cast<WordTranslationFeature*>(ff);
mosesWeights.Assign(m, wt->GetSparseProducerWeight());
}
else if (sparseProducers[0]->GetScoreProducerWeightShortName().compare("pp") == 0) {
PhrasePairFeature* pp =
static_cast<PhrasePairFeature*>(ff);
mosesWeights.Assign(m, pp->GetSparseProducerWeight());
}
}
// BATCHING: produce nbest lists for all input sentences in batch
vector<float> oracleBleuScores;
vector<float> oracleModelScores;
vector<vector<const Word*> > oneBests;
vector<ScoreComponentCollection> oracleFeatureValues;
vector<size_t> inputLengths;
vector<size_t> ref_ids;
size_t actualBatchSize = 0;
vector<size_t>::const_iterator current_sid_start = sid;
size_t examples_in_batch = 0;
bool skip_example = false;
for (size_t batchPosition = 0; batchPosition < batchSize && sid
!= shard.end(); ++batchPosition) {
string input;
if (trainWithMultipleFolds)
input = inputSentencesFolds[myFold][*sid];
else
input = inputSentences[*sid];
Moses::Sentence *sentence = new Sentence();
stringstream in(input + "\n");
const vector<FactorType> inputFactorOrder = staticData.GetInputFactorOrder();
sentence->Read(in,inputFactorOrder);
cerr << "\nRank " << rank << ", epoch " << epoch << ", input sentence " << *sid << ": \"";
sentence->Print(cerr);
cerr << "\"" << " (batch pos " << batchPosition << ")" << endl;
size_t current_input_length = (*sentence).GetSize();
if (epoch == 0 && (scaleByAvgInputLength || scaleByAvgInverseLength)) {
sumOfInputs += current_input_length;
++numberOfInputs;
avgInputLength = sumOfInputs/numberOfInputs;
decoder->setAvgInputLength(avgInputLength);
cerr << "Rank " << rank << ", epoch 0, average input length: " << avgInputLength << endl;
}
vector<ScoreComponentCollection> newFeatureValues;
vector<float> newScores;
if (model_hope_fear) {
featureValues.push_back(newFeatureValues);
bleuScores.push_back(newScores);
modelScores.push_back(newScores);
}
if (hope_fear || perceptron_update) {
featureValuesHope.push_back(newFeatureValues);
featureValuesFear.push_back(newFeatureValues);
bleuScoresHope.push_back(newScores);
bleuScoresFear.push_back(newScores);
modelScoresHope.push_back(newScores);
modelScoresFear.push_back(newScores);
if (historyBleu || simpleHistoryBleu || debug_model) {
featureValues.push_back(newFeatureValues);
bleuScores.push_back(newScores);
modelScores.push_back(newScores);
}
}
if (kbest) {
// for decoding
featureValues.push_back(newFeatureValues);
bleuScores.push_back(newScores);
modelScores.push_back(newScores);
// for storing selected examples
featureValuesHope.push_back(newFeatureValues);
featureValuesFear.push_back(newFeatureValues);
bleuScoresHope.push_back(newScores);
bleuScoresFear.push_back(newScores);
modelScoresHope.push_back(newScores);
modelScoresFear.push_back(newScores);
}
size_t ref_length;
float avg_ref_length;
if (print_weights)
cerr << "Rank " << rank << ", epoch " << epoch << ", current weights: " << mosesWeights << endl;
if (print_core_weights) {
cerr << "Rank " << rank << ", epoch " << epoch << ", current weights: ";
mosesWeights.PrintCoreFeatures();
cerr << endl;
}
// check LM weight
const LMList& lmList_new = staticData.GetLMList();
for (LMList::const_iterator i = lmList_new.begin(); i != lmList_new.end(); ++i) {
float lmWeight = mosesWeights.GetScoreForProducer(*i);
cerr << "Rank " << rank << ", epoch " << epoch << ", lm weight: " << lmWeight << endl;
if (lmWeight <= 0) {
cerr << "Rank " << rank << ", epoch " << epoch << ", ERROR: language model weight should never be <= 0." << endl;
mosesWeights.Assign(*i, 0.1);
cerr << "Rank " << rank << ", epoch " << epoch << ", assign lm weights of 0.1" << endl;
}
}
// select inference scheme
cerr << "Rank " << rank << ", epoch " << epoch << ", real Bleu? " << realBleu << endl;
if (hope_fear || perceptron_update) {
// HOPE
cerr << "Rank " << rank << ", epoch " << epoch << ", " << hope_n <<
"best hope translations" << endl;
vector< vector<const Word*> > outputHope = decoder->getNBest(input, *sid, hope_n, 1.0, bleuWeight_hope,
featureValuesHope[batchPosition], bleuScoresHope[batchPosition], modelScoresHope[batchPosition],
1, realBleu, distinctNbest, avgRefLength, rank, epoch, "");
vector<const Word*> oracle = outputHope[0];
decoder->cleanup(chartDecoding);
ref_length = decoder->getClosestReferenceLength(*sid, oracle.size());
avg_ref_length = ref_length;
float hope_length_ratio = (float)oracle.size()/ref_length;
int oracleSize = (int)oracle.size();
cerr << endl;
// count sparse features occurring in hope translation
featureValuesHope[batchPosition][0].IncrementSparseHopeFeatures();
float precision = bleuScoresHope[batchPosition][0];
if (historyBleu || simpleHistoryBleu) {
precision /= decoder->getTargetLengthHistory();
}
else {
if (scaleByAvgInputLength) precision /= decoder->getAverageInputLength();
else if (scaleByAvgInverseLength) precision /= (100/decoder->getAverageInputLength());
precision /= scaleByX;
}
if (scale_margin_precision || scale_update_precision) {
if (historyBleu || simpleHistoryBleu || scaleByAvgInputLength || scaleByAvgInverseLength) {
cerr << "Rank " << rank << ", epoch " << epoch << ", set hope precision: " << precision << endl;
((MiraOptimiser*) optimiser)->setPrecision(precision);
}
}
vector<const Word*> bestModel;
if (debug_model || historyBleu || simpleHistoryBleu) {
// MODEL (for updating the history only, using dummy vectors)
cerr << "Rank " << rank << ", epoch " << epoch << ", 1best wrt model score (debug or history)" << endl;
vector< vector<const Word*> > outputModel = decoder->getNBest(input, *sid, n, 0.0, bleuWeight,
featureValues[batchPosition], bleuScores[batchPosition], modelScores[batchPosition],
1, realBleu, distinctNbest, avgRefLength, rank, epoch, "");
bestModel = outputModel[0];
decoder->cleanup(chartDecoding);
cerr << endl;
ref_length = decoder->getClosestReferenceLength(*sid, bestModel.size());
}
// FEAR
float fear_length_ratio = 0;
float bleuRatioHopeFear = 0;
int fearSize = 0;
cerr << "Rank " << rank << ", epoch " << epoch << ", " << fear_n << "best fear translations" << endl;
vector< vector<const Word*> > outputFear = decoder->getNBest(input, *sid, fear_n, -1.0, bleuWeight_fear,
featureValuesFear[batchPosition], bleuScoresFear[batchPosition], modelScoresFear[batchPosition],
1, realBleu, distinctNbest, avgRefLength, rank, epoch, "");
vector<const Word*> fear = outputFear[0];
decoder->cleanup(chartDecoding);
ref_length = decoder->getClosestReferenceLength(*sid, fear.size());
avg_ref_length += ref_length;
avg_ref_length /= 2;
fear_length_ratio = (float)fear.size()/ref_length;
fearSize = (int)fear.size();
cerr << endl;
for (size_t i = 0; i < fear.size(); ++i)
delete fear[i];
// count sparse features occurring in fear translation
featureValuesFear[batchPosition][0].IncrementSparseFearFeatures();
// Bleu-related example selection
bool skip = false;
bleuRatioHopeFear = bleuScoresHope[batchPosition][0] / bleuScoresFear[batchPosition][0];
if (minBleuRatio != -1 && bleuRatioHopeFear < minBleuRatio)
skip = true;
if(maxBleuRatio != -1 && bleuRatioHopeFear > maxBleuRatio)
skip = true;
// sanity check
if (historyBleu || simpleHistoryBleu) {
if (bleuScores[batchPosition][0] > bleuScoresHope[batchPosition][0] &&
modelScores[batchPosition][0] > modelScoresHope[batchPosition][0]) {
if (abs(bleuScores[batchPosition][0] - bleuScoresHope[batchPosition][0]) > epsilon &&
abs(modelScores[batchPosition][0] - modelScoresHope[batchPosition][0]) > epsilon) {
cerr << "Rank " << rank << ", epoch " << epoch << ", ERROR: MODEL translation better than HOPE translation." << endl;
skip = true;
}
}
if (bleuScoresFear[batchPosition][0] > bleuScores[batchPosition][0] &&
modelScoresFear[batchPosition][0] > modelScores[batchPosition][0]) {
if (abs(bleuScoresFear[batchPosition][0] - bleuScores[batchPosition][0]) > epsilon &&
abs(modelScoresFear[batchPosition][0] - modelScores[batchPosition][0]) > epsilon) {
cerr << "Rank " << rank << ", epoch " << epoch << ", ERROR: FEAR translation better than MODEL translation." << endl;
skip = true;
}
}
}
if (bleuScoresFear[batchPosition][0] > bleuScoresHope[batchPosition][0]) {
if (abs(bleuScoresFear[batchPosition][0] - bleuScoresHope[batchPosition][0]) > epsilon) {
// check if it's an error or a warning
skip = true;
if (modelScoresFear[batchPosition][0] > modelScoresHope[batchPosition][0] && abs(modelScoresFear[batchPosition][0] - modelScoresHope[batchPosition][0]) > epsilon) {
cerr << "Rank " << rank << ", epoch " << epoch << ", ERROR: FEAR translation better than HOPE translation. (abs-diff: " << abs(bleuScoresFear[batchPosition][0] - bleuScoresHope[batchPosition][0]) << ")" <<endl;
}
else {
cerr << "Rank " << rank << ", epoch " << epoch << ", WARNING: FEAR translation has better Bleu than HOPE translation. (abs-diff: " << abs(bleuScoresFear[batchPosition][0] - bleuScoresHope[batchPosition][0]) << ")" <<endl;
}
}
}
if (skip) {
cerr << "Rank " << rank << ", epoch " << epoch << ", skip example (" << hope_length_ratio << ", " << bleuRatioHopeFear << ").. " << endl;
featureValuesHope[batchPosition].clear();
featureValuesFear[batchPosition].clear();
bleuScoresHope[batchPosition].clear();
bleuScoresFear[batchPosition].clear();
if (historyBleu || simpleHistoryBleu || debug_model) {
featureValues[batchPosition].clear();
bleuScores[batchPosition].clear();
}
}
else {
examples_in_batch++;
// needed for history
if (historyBleu || simpleHistoryBleu) {
inputLengths.push_back(current_input_length);
ref_ids.push_back(*sid);
oneBests.push_back(bestModel);
}
}
}
if (model_hope_fear) {
cerr << "Rank " << rank << ", epoch " << epoch << ", " << n << "best hope translations" << endl;
size_t oraclePos = featureValues[batchPosition].size();
decoder->getNBest(input, *sid, n, 1.0, bleuWeight_hope,
featureValues[batchPosition], bleuScores[batchPosition], modelScores[batchPosition],
0, realBleu, distinctNbest, avgRefLength, rank, epoch, "");
//vector<const Word*> oracle = outputHope[0];
// needed for history
inputLengths.push_back(current_input_length);
ref_ids.push_back(*sid);
decoder->cleanup(chartDecoding);
//ref_length = decoder->getClosestReferenceLength(*sid, oracle.size());
//float hope_length_ratio = (float)oracle.size()/ref_length;
cerr << endl;
oracleFeatureValues.push_back(featureValues[batchPosition][oraclePos]);
oracleBleuScores.push_back(bleuScores[batchPosition][oraclePos]);
oracleModelScores.push_back(modelScores[batchPosition][oraclePos]);
// MODEL
cerr << "Rank " << rank << ", epoch " << epoch << ", " << n << "best wrt model score" << endl;
if (historyBleu || simpleHistoryBleu) {
vector< vector<const Word*> > outputModel = decoder->getNBest(input, *sid, n, 0.0,
bleuWeight, featureValues[batchPosition], bleuScores[batchPosition],
modelScores[batchPosition], 1, realBleu, distinctNbest, avgRefLength, rank, epoch, "");
vector<const Word*> bestModel = outputModel[0];
oneBests.push_back(bestModel);
inputLengths.push_back(current_input_length);
ref_ids.push_back(*sid);
}
else {
decoder->getNBest(input, *sid, n, 0.0, bleuWeight,
featureValues[batchPosition], bleuScores[batchPosition], modelScores[batchPosition],
0, realBleu, distinctNbest, avgRefLength, rank, epoch, "");
}
decoder->cleanup(chartDecoding);
//ref_length = decoder->getClosestReferenceLength(*sid, bestModel.size());
//float model_length_ratio = (float)bestModel.size()/ref_length;
cerr << endl;
// FEAR
cerr << "Rank " << rank << ", epoch " << epoch << ", " << n << "best fear translations" << endl;
decoder->getNBest(input, *sid, n, -1.0, bleuWeight_fear,
featureValues[batchPosition], bleuScores[batchPosition], modelScores[batchPosition],
0, realBleu, distinctNbest, avgRefLength, rank, epoch, "");
decoder->cleanup(chartDecoding);
//ref_length = decoder->getClosestReferenceLength(*sid, fear.size());
//float fear_length_ratio = (float)fear.size()/ref_length;
examples_in_batch++;
}
if (kbest) {
// MODEL
cerr << "Rank " << rank << ", epoch " << epoch << ", " << n << "best wrt model score" << endl;
if (historyBleu || simpleHistoryBleu) {
vector< vector<const Word*> > outputModel = decoder->getNBest(input, *sid, n, 0.0,
bleuWeight, featureValues[batchPosition], bleuScores[batchPosition],
modelScores[batchPosition], 1, realBleu, distinctNbest, avgRefLength, rank, epoch, "");
vector<const Word*> bestModel = outputModel[0];
oneBests.push_back(bestModel);
inputLengths.push_back(current_input_length);
ref_ids.push_back(*sid);
}
else {
decoder->getNBest(input, *sid, n, 0.0, bleuWeight,
featureValues[batchPosition], bleuScores[batchPosition],
modelScores[batchPosition], 0, realBleu, distinctNbest, avgRefLength, rank, epoch, "");
}
decoder->cleanup(chartDecoding);
//ref_length = decoder->getClosestReferenceLength(*sid, bestModel.size());
//float model_length_ratio = (float)bestModel.size()/ref_length;
cerr << endl;
examples_in_batch++;
HypothesisQueue queueHope(hope_n);
HypothesisQueue queueFear(fear_n);
cerr << endl;
if (most_violated || all_violated || one_against_all) {
float bleuHope = -1000;
float bleuFear = 1000;
size_t indexHope = -1;
size_t indexFear = -1;
vector<float> bleuHopeList;
vector<float> bleuFearList;
vector<float> indexHopeList;
vector<float> indexFearList;
if (most_violated)
cerr << "Rank " << rank << ", epoch " << epoch << ", pick pair with most violated constraint" << endl;
else if (all_violated)
cerr << "Rank " << rank << ", epoch " << epoch << ", pick all pairs with violated constraints";
else
cerr << "Rank " << rank << ", epoch " << epoch << ", pick all pairs with hope";
// find best hope, then find fear that violates our constraint most
for (size_t i=0; i<bleuScores[batchPosition].size(); ++i) {
if (abs(bleuScores[batchPosition][i] - bleuHope) < epsilon) { // equal bleu scores
if (modelScores[batchPosition][i] > modelScores[batchPosition][indexHope]) {
if (abs(modelScores[batchPosition][i] - modelScores[batchPosition][indexHope]) > epsilon) {
// better model score
bleuHope = bleuScores[batchPosition][i];
indexHope = i;
}
}
}
else if (bleuScores[batchPosition][i] > bleuHope) { // better than current best
bleuHope = bleuScores[batchPosition][i];
indexHope = i;
}
}
float currentViolation = 0;
float minimum_bleu_diff = 0.01;
for (size_t i=0; i<bleuScores[batchPosition].size(); ++i) {
float bleuDiff = bleuHope - bleuScores[batchPosition][i];
float modelDiff = modelScores[batchPosition][indexHope] - modelScores[batchPosition][i];
if (bleuDiff > epsilon) {
if (one_against_all && bleuDiff > minimum_bleu_diff) {
cerr << ".. adding pair";
bleuHopeList.push_back(bleuHope);
bleuFearList.push_back(bleuScores[batchPosition][i]);
indexHopeList.push_back(indexHope);
indexFearList.push_back(i);
}
else if (modelDiff < bleuDiff) {
float diff = bleuDiff - modelDiff;
if (diff > epsilon) {
if (all_violated) {
cerr << ".. adding pair";
bleuHopeList.push_back(bleuHope);
bleuFearList.push_back(bleuScores[batchPosition][i]);
indexHopeList.push_back(indexHope);
indexFearList.push_back(i);
}
else if (most_violated && diff > currentViolation) {
currentViolation = diff;
bleuFear = bleuScores[batchPosition][i];
indexFear = i;
cerr << "Rank " << rank << ", epoch " << epoch << ", current violation: " << currentViolation << " (" << modelDiff << " >= " << bleuDiff << ")" << endl;
}
}
}
}
}
if (most_violated) {
if (currentViolation > 0) {
cerr << "Rank " << rank << ", epoch " << epoch << ", adding pair with violation " << currentViolation << endl;
cerr << "Rank " << rank << ", epoch " << epoch << ", hope: " << bleuHope << " (" << indexHope << "), fear: " << bleuFear << " (" << indexFear << ")" << endl;
bleuScoresHope[batchPosition].push_back(bleuHope);
bleuScoresFear[batchPosition].push_back(bleuFear);
featureValuesHope[batchPosition].push_back(featureValues[batchPosition][indexHope]);
featureValuesFear[batchPosition].push_back(featureValues[batchPosition][indexFear]);
float modelScoreHope = modelScores[batchPosition][indexHope];
float modelScoreFear = modelScores[batchPosition][indexFear];
if (most_violated_reg) {
// reduce model score difference by factor ~0.5
float reg = currentViolation/4;
modelScoreHope += abs(reg);
modelScoreFear -= abs(reg);
float newViolation = (bleuHope - bleuFear) - (modelScoreHope - modelScoreFear);
cerr << "Rank " << rank << ", epoch " << epoch << ", regularized violation: " << newViolation << endl;
}
modelScoresHope[batchPosition].push_back(modelScoreHope);
modelScoresFear[batchPosition].push_back(modelScoreFear);
featureValues[batchPosition][indexHope].IncrementSparseHopeFeatures();
featureValues[batchPosition][indexFear].IncrementSparseFearFeatures();
}
else {
cerr << "Rank " << rank << ", epoch " << epoch << ", no violated constraint found." << endl;
skip_example = 1;
}
}
else cerr << endl;
}
if (max_bleu_diff) {
cerr << "Rank " << rank << ", epoch " << epoch << ", pick pair with max Bleu diff from list: " << bleuScores[batchPosition].size() << endl;
for (size_t i=0; i<bleuScores[batchPosition].size(); ++i) {
float hopeScore = bleuScores[batchPosition][i];
if (modelPlusBleu) hopeScore += modelScores[batchPosition][i];
BleuIndexPair hope(hopeScore, i);
queueHope.Push(hope);
float fearScore = -1*(bleuScores[batchPosition][i]);
if (modelPlusBleu) fearScore += modelScores[batchPosition][i];
BleuIndexPair fear(fearScore, i);
queueFear.Push(fear);
}
skip_example = 0;
}
cerr << endl;
vector<BleuIndexPair> hopeList, fearList;
for (size_t i=0; i<hope_n && !queueHope.Empty(); ++i) hopeList.push_back(queueHope.Pop());
for (size_t i=0; i<fear_n && !queueFear.Empty(); ++i) fearList.push_back(queueFear.Pop());
for (size_t i=0; i<hopeList.size(); ++i) {
//float bleuHope = hopeList[i].first;
size_t indexHope = hopeList[i].second;
float bleuHope = bleuScores[batchPosition][indexHope];
for (size_t j=0; j<fearList.size(); ++j) {
//float bleuFear = -1*(fearList[j].first);
size_t indexFear = fearList[j].second;
float bleuFear = bleuScores[batchPosition][indexFear];
cerr << "Rank " << rank << ", epoch " << epoch << ", hope: " << bleuHope << " (" << indexHope << "), fear: " << bleuFear << " (" << indexFear << ")" << endl;
bleuScoresHope[batchPosition].push_back(bleuHope);
bleuScoresFear[batchPosition].push_back(bleuFear);
featureValuesHope[batchPosition].push_back(featureValues[batchPosition][indexHope]);
featureValuesFear[batchPosition].push_back(featureValues[batchPosition][indexFear]);
float modelScoreHope = modelScores[batchPosition][indexHope];
float modelScoreFear = modelScores[batchPosition][indexFear];
modelScoresHope[batchPosition].push_back(modelScoreHope);
modelScoresFear[batchPosition].push_back(modelScoreFear);
featureValues[batchPosition][indexHope].IncrementSparseHopeFeatures();
featureValues[batchPosition][indexFear].IncrementSparseFearFeatures();
}
}
if (!makePairs)
cerr << "Rank " << rank << ", epoch " << epoch << "summing up hope and fear vectors, no pairs" << endl;
}
// next input sentence
++sid;
++actualBatchSize;
++shardPosition;
} // end of batch loop
if (examples_in_batch == 0 || (kbest && skip_example)) {
cerr << "Rank " << rank << ", epoch " << epoch << ", batch is empty." << endl;
}
else {
vector<vector<float> > losses(actualBatchSize);
if (model_hope_fear) {
// Set loss for each sentence as BLEU(oracle) - BLEU(hypothesis)
for (size_t batchPosition = 0; batchPosition < actualBatchSize; ++batchPosition) {
for (size_t j = 0; j < bleuScores[batchPosition].size(); ++j) {
losses[batchPosition].push_back(oracleBleuScores[batchPosition] - bleuScores[batchPosition][j]);
}
}
}
// set weight for bleu feature to 0 before optimizing
vector<const ScoreProducer*>::const_iterator iter;
const vector<const ScoreProducer*> featureFunctions2 = staticData.GetTranslationSystem(TranslationSystem::DEFAULT).GetFeatureFunctions();
for (iter = featureFunctions2.begin(); iter != featureFunctions2.end(); ++iter) {
if ((*iter)->GetScoreProducerWeightShortName() == "bl") {
mosesWeights.Assign(*iter, 0);
break;
}
}
// scale LM feature (to avoid rapid changes)
if (scale_lm) {
cerr << "scale lm" << endl;
const LMList& lmList_new = staticData.GetLMList();
for (LMList::const_iterator iter = lmList_new.begin(); iter != lmList_new.end(); ++iter) {
// scale down score
if (model_hope_fear) {
scaleFeatureScore(*iter, scale_lm_factor, featureValues, rank, epoch);
}
else {
scaleFeatureScore(*iter, scale_lm_factor, featureValuesHope, rank, epoch);
scaleFeatureScore(*iter, scale_lm_factor, featureValuesFear, rank, epoch);
}
}
}
// scale WP
if (scale_wp) {
// scale up weight
WordPenaltyProducer *wp = staticData.GetFirstWordPenaltyProducer();
// scale down score
if (model_hope_fear) {
scaleFeatureScore(wp, scale_wp_factor, featureValues, rank, epoch);
}
else {
scaleFeatureScore(wp, scale_wp_factor, featureValuesHope, rank, epoch);
scaleFeatureScore(wp, scale_wp_factor, featureValuesFear, rank, epoch);
}
}
// print out the feature values
if (print_feature_values) {
cerr << "\nRank " << rank << ", epoch " << epoch << ", feature values: " << endl;
if (model_hope_fear) printFeatureValues(featureValues);
else {
cerr << "hope: " << endl;
printFeatureValues(featureValuesHope);
cerr << "fear: " << endl;
printFeatureValues(featureValuesFear);
}
}
// apply learning rates to feature vectors before optimization
if (feature_confidence) {
cerr << "Rank " << rank << ", epoch " << epoch << ", apply feature learning rates with decays " << decay_core << "/" << decay_sparse << ": " << featureLearningRates << endl;
if (model_hope_fear) {
applyPerFeatureLearningRates(featureValues, featureLearningRates, sparse_r0);
}
else {
applyPerFeatureLearningRates(featureValuesHope, featureLearningRates, sparse_r0);
applyPerFeatureLearningRates(featureValuesFear, featureLearningRates, sparse_r0);
}
}
else {
// apply fixed learning rates
cerr << "Rank " << rank << ", epoch " << epoch << ", apply fixed learning rates, core: " << core_r0 << ", sparse: " << sparse_r0 << endl;
if (core_r0 != 1.0 || sparse_r0 != 1.0) {
if (model_hope_fear) {
applyLearningRates(featureValues, core_r0, sparse_r0);
}
else {
applyLearningRates(featureValuesHope, core_r0, sparse_r0);
applyLearningRates(featureValuesFear, core_r0, sparse_r0);
}
}
}
if (kbest) {
// If we are tuning a global weight for a sparse producer,
// we must collapse the sparse features first (report weighted aggregate)
if (tuneMetaFeature) {
for (unsigned i = 0; i < sparseProducers.size(); ++i) {
float spWeight = sparseProducers[i]->GetSparseProducerWeight();
if (spWeight != 1.0) {
MetaFeatureProducer *m = staticData.GetMetaFeatureProducer();
for (size_t i=0; i < featureValuesHope.size(); ++i) {
for (size_t j=0; j < featureValuesHope[i].size(); ++j) {
// multiply sparse feature values with weights
const FVector scores =
featureValuesHope[i][j].GetVectorForProducer(sparseProducers[i]);
const FVector &weights = staticData.GetAllWeights().GetScoresVector();
float aggregate = scores.inner_product(weights);
//cerr << "Rank " << rank << ", epoch " << epoch << ", sparse Producer " <<
//sparseProducers[i]->GetScoreProducerWeightShortName()
//<< " aggregate: " << aggregate << endl;
aggregate *= spWeight;
//cerr << "Rank " << rank << ", epoch " << epoch << ", sparse Producer " <<
//sparseProducers[i]->GetScoreProducerWeightShortName()
//<< " weighted aggregate: " << aggregate << endl;
// copy core features to a new collection, then assign aggregated sparse feature
ScoreComponentCollection scoresAggregate;
scoresAggregate.CoreAssign(featureValuesHope[i][j]);
scoresAggregate.Assign(m, aggregate);
featureValuesHope[i][j] = scoresAggregate;
}
}
for (size_t i=0; i < featureValuesFear.size(); ++i) {
for (size_t j=0; j < featureValuesFear[i].size(); ++j) {
// multiply sparse feature values with weights
const FVector scores =
featureValuesFear[i][j].GetVectorForProducer(sparseProducers[i]);
const FVector &weights = staticData.GetAllWeights().GetScoresVector();
float aggregate = scores.inner_product(weights);
aggregate *= spWeight;
// copy core features to a new collection, then assign aggregated sparse feature
ScoreComponentCollection scoresAggregate;
scoresAggregate.CoreAssign(featureValuesFear[i][j]);
scoresAggregate.Assign(m, aggregate);
featureValuesFear[i][j] = scoresAggregate;
}
}
cerr << "Rank " << rank << ", epoch " << epoch << ", new hope feature vector: " <<
featureValuesHope[0][0] << endl;
cerr << "Rank " << rank << ", epoch " << epoch << ", new fear feature vector: " <<
featureValuesFear[0][0] << endl;
}
}
}
}
// Run optimiser on batch:
VERBOSE(1, "\nRank " << rank << ", epoch " << epoch << ", run optimiser:" << endl);
size_t update_status = 1;
ScoreComponentCollection weightUpdate;
if (perceptron_update) {
vector<vector<float> > dummy1;
update_status = optimiser->updateWeightsHopeFear( weightUpdate, featureValuesHope,
featureValuesFear, dummy1, dummy1, dummy1, dummy1, learning_rate, rank, epoch);
}
else if (hope_fear) {
if (bleuScoresHope[0][0] >= min_oracle_bleu) {
if (hope_n == 1 && fear_n ==1 && batchSize == 1 && !hildreth) {
update_status = ((MiraOptimiser*) optimiser)->updateWeightsAnalytically(weightUpdate,
featureValuesHope[0][0], featureValuesFear[0][0], bleuScoresHope[0][0],
bleuScoresFear[0][0], modelScoresHope[0][0], modelScoresFear[0][0], learning_rate, rank, epoch);
}
else
update_status = optimiser->updateWeightsHopeFear(weightUpdate, featureValuesHope,
featureValuesFear, bleuScoresHope, bleuScoresFear, modelScoresHope,
modelScoresFear, learning_rate, rank, epoch);
}
else
update_status = 1;
}
else if (kbest) {
if (selective)
update_status = ((MiraOptimiser*)optimiser)->updateWeightsHopeFearSelective(
weightUpdate, featureValuesHope, featureValuesFear, bleuScoresHope, bleuScoresFear,
modelScoresHope, modelScoresFear, learning_rate, rank, epoch);
else if (summed)
update_status = ((MiraOptimiser*)optimiser)->updateWeightsHopeFearSummed(
weightUpdate, featureValuesHope, featureValuesFear, bleuScoresHope, bleuScoresFear,
modelScoresHope, modelScoresFear, learning_rate, rank, epoch, rescaleSlack, makePairs);
else {
if (batchSize == 1 && featureValuesHope[0].size() == 1 && !hildreth) {
cerr << "Rank " << rank << ", epoch " << epoch << ", model score hope: " << modelScoresHope[0][0] << endl;
cerr << "Rank " << rank << ", epoch " << epoch << ", model score fear: " << modelScoresFear[0][0] << endl;
update_status = ((MiraOptimiser*) optimiser)->updateWeightsAnalytically(
weightUpdate, featureValuesHope[0][0], featureValuesFear[0][0],
bleuScoresHope[0][0], bleuScoresFear[0][0], modelScoresHope[0][0],
modelScoresFear[0][0], learning_rate, rank, epoch);
}
else {
cerr << "Rank " << rank << ", epoch " << epoch << ", model score hope: " << modelScoresHope[0][0] << endl;
cerr << "Rank " << rank << ", epoch " << epoch << ", model score fear: " << modelScoresFear[0][0] << endl;
update_status = optimiser->updateWeightsHopeFear(weightUpdate, featureValuesHope,
featureValuesFear, bleuScoresHope, bleuScoresFear, modelScoresHope,
modelScoresFear, learning_rate, rank, epoch);
}
}
}
else {
// model_hope_fear
update_status = ((MiraOptimiser*) optimiser)->updateWeights(weightUpdate,
featureValues, losses, bleuScores, modelScores, oracleFeatureValues,
oracleBleuScores, oracleModelScores, learning_rate, rank, epoch);
}
// sumStillViolatedConstraints += update_status;
if (update_status == 0) { // if weights were updated
// apply weight update
if (debug)
cerr << "Rank " << rank << ", epoch " << epoch << ", update: " << weightUpdate << endl;
if (tuneMetaFeature) {
MetaFeatureProducer *m = staticData.GetMetaFeatureProducer();
// update sparse producer weight
// (NOTE: this currently doesn't work for more than one sparse producer)
float metaWeightUpdate = weightUpdate.GetScoreForProducer(m);
const vector<const FeatureFunction*> sparseProducers =
staticData.GetTranslationSystem(TranslationSystem::DEFAULT).GetSparseProducers();
FeatureFunction* ff = const_cast<FeatureFunction*>(sparseProducers[0]);
if (sparseProducers[0]->GetScoreProducerWeightShortName().compare("wt") == 0) {
WordTranslationFeature* wt =
static_cast<WordTranslationFeature*>(ff);
float newWeight = wt->GetSparseProducerWeight();
cerr << "Rank " << rank << ", epoch " << epoch << ", old meta weight: " << newWeight << endl;
newWeight += metaWeightUpdate;
wt->SetSparseProducerWeight(newWeight);
cerr << "Rank " << rank << ", epoch " << epoch << ", new meta weight: " << newWeight << endl;
}
else if (sparseProducers[0]->GetScoreProducerWeightShortName().compare("pp") == 0) {
PhrasePairFeature* pp =
static_cast<PhrasePairFeature*>(ff);
float newWeight = pp->GetSparseProducerWeight();
cerr << "Rank " << rank << ", epoch " << epoch << ", old meta weight: " << newWeight << endl;
newWeight += metaWeightUpdate;
pp->SetSparseProducerWeight(newWeight);
cerr << "Rank " << rank << ", epoch " << epoch << ", new meta weight: " << newWeight << endl;
}
}
if (feature_confidence) {
// update confidence counts based on weight update
confidenceCounts.UpdateConfidenceCounts(weightUpdate, signed_counts);
// update feature learning rates
featureLearningRates.UpdateLearningRates(decay_core, decay_sparse, confidenceCounts, core_r0, sparse_r0);
}
// apply weight update to Moses weights
mosesWeights.PlusEquals(weightUpdate);
if (normaliseWeights && !tuneMetaFeature)
mosesWeights.L1Normalise();
cumulativeWeights.PlusEquals(mosesWeights);
if (sparseAverage) {
ScoreComponentCollection binary;
binary.SetToBinaryOf(mosesWeights);
cumulativeWeightsBinary.PlusEquals(binary);
}
++numberOfUpdates;
++numberOfUpdatesThisEpoch;
if (averageWeights && !tuneMetaFeature) {
ScoreComponentCollection averageWeights(cumulativeWeights);
if (accumulateWeights) {
averageWeights.DivideEquals(numberOfUpdates);
} else {
averageWeights.DivideEquals(numberOfUpdatesThisEpoch);
}
mosesWeights = averageWeights;
}
// set new Moses weights
decoder->setWeights(mosesWeights);
//cerr << "Rank " << rank << ", epoch " << epoch << ", new weights: " << mosesWeights << endl;
}
// update history (for approximate document Bleu)
if (historyBleu || simpleHistoryBleu) {
for (size_t i = 0; i < oneBests.size(); ++i)
cerr << "Rank " << rank << ", epoch " << epoch << ", update history with 1best length: " << oneBests[i].size() << " ";
decoder->updateHistory(oneBests, inputLengths, ref_ids, rank, epoch);
deleteTranslations(oneBests);
}
} // END TRANSLATE AND UPDATE BATCH
// size of all shards except for the last one
size_t generalShardSize;
if (trainWithMultipleFolds)
generalShardSize = order.size()/coresPerFold;
else
generalShardSize = order.size()/size;
size_t mixing_base = mixingFrequency == 0 ? 0 : generalShardSize / mixingFrequency;
size_t dumping_base = weightDumpFrequency == 0 ? 0 : generalShardSize / weightDumpFrequency;
bool mix = evaluateModulo(shardPosition, mixing_base, actualBatchSize);
// mix weights?
if (mix) {
#ifdef MPI_ENABLE
cerr << "Rank " << rank << ", epoch " << epoch << ", mixing weights.. " << endl;
// collect all weights in mixedWeights and divide by number of processes
mpi::reduce(world, mosesWeights, mixedWeights, SCCPlus(), 0);
// mix confidence counts
//mpi::reduce(world, confidenceCounts, mixedConfidenceCounts, SCCPlus(), 0);
ScoreComponentCollection totalBinary;
if (sparseAverage) {
ScoreComponentCollection binary;
binary.SetToBinaryOf(mosesWeights);
mpi::reduce(world, binary, totalBinary, SCCPlus(), 0);
}
if (rank == 0) {
// divide by number of processes
if (sparseNoAverage)
mixedWeights.CoreDivideEquals(size); // average only core weights
else if (sparseAverage)
mixedWeights.DivideEquals(totalBinary);
else
mixedWeights.DivideEquals(size);
// divide confidence counts
//mixedConfidenceCounts.DivideEquals(size);
// normalise weights after averaging
if (normaliseWeights) {
mixedWeights.L1Normalise();
}
++weightMixingThisEpoch;
if (pruneZeroWeights) {
size_t pruned = mixedWeights.PruneZeroWeightFeatures();
cerr << "Rank " << rank << ", epoch " << epoch << ", "
<< pruned << " zero-weighted features pruned from mixedWeights." << endl;
pruned = cumulativeWeights.PruneZeroWeightFeatures();
cerr << "Rank " << rank << ", epoch " << epoch << ", "
<< pruned << " zero-weighted features pruned from cumulativeWeights." << endl;
}
if (featureCutoff != -1 && weightMixingThisEpoch == mixingFrequency) {
size_t pruned = mixedWeights.PruneSparseFeatures(featureCutoff);
cerr << "Rank " << rank << ", epoch " << epoch << ", "
<< pruned << " features pruned from mixedWeights." << endl;
pruned = cumulativeWeights.PruneSparseFeatures(featureCutoff);
cerr << "Rank " << rank << ", epoch " << epoch << ", "
<< pruned << " features pruned from cumulativeWeights." << endl;
}
if (weightMixingThisEpoch == mixingFrequency || reg_on_every_mix) {
if (l1_regularize) {
size_t pruned;
if (l1_reg_sparse)
pruned = mixedWeights.SparseL1Regularize(l1_lambda);
else
pruned = mixedWeights.L1Regularize(l1_lambda);
cerr << "Rank " << rank << ", epoch " << epoch << ", "
<< "l1-reg. on mixedWeights with lambda=" << l1_lambda << ", pruned: " << pruned << endl;
}
if (l2_regularize) {
if (l2_reg_sparse)
mixedWeights.SparseL2Regularize(l2_lambda);
else
mixedWeights.L2Regularize(l2_lambda);
cerr << "Rank " << rank << ", epoch " << epoch << ", "
<< "l2-reg. on mixedWeights with lambda=" << l2_lambda << endl;
}
}
}
// broadcast average weights from process 0
mpi::broadcast(world, mixedWeights, 0);
decoder->setWeights(mixedWeights);
mosesWeights = mixedWeights;
// broadcast summed confidence counts
//mpi::broadcast(world, mixedConfidenceCounts, 0);
//confidenceCounts = mixedConfidenceCounts;
#endif
#ifndef MPI_ENABLE
//cerr << "\nRank " << rank << ", no mixing, weights: " << mosesWeights << endl;
mixedWeights = mosesWeights;
#endif
} // end mixing
// Dump weights?
if (trainWithMultipleFolds || weightEpochDump == weightDumpFrequency) {
// dump mixed weights at end of every epoch to enable continuing a crashed experiment
// (for jackknife every time the weights are mixed)
ostringstream filename;
if (epoch < 10)
filename << weightDumpStem << "_mixed_0" << epoch;
else
filename << weightDumpStem << "_mixed_" << epoch;
if (weightDumpFrequency > 1)
filename << "_" << weightEpochDump;
mixedWeights.Save(filename.str());
cerr << "Dumping mixed weights during epoch " << epoch << " to " << filename.str() << endl << endl;
}
if (dumpMixedWeights) {
if (mix && rank == 0 && !weightDumpStem.empty()) {
// dump mixed weights instead of average weights
ostringstream filename;
if (epoch < 10)
filename << weightDumpStem << "_0" << epoch;
else
filename << weightDumpStem << "_" << epoch;
if (weightDumpFrequency > 1)
filename << "_" << weightEpochDump;
cerr << "Dumping mixed weights during epoch " << epoch << " to " << filename.str() << endl << endl;
mixedWeights.Save(filename.str());
++weightEpochDump;
}
}
else {
if (evaluateModulo(shardPosition, dumping_base, actualBatchSize)) {
cerr << "Rank " << rank << ", epoch " << epoch << ", dump weights.. (pos: " << shardPosition << ", base: " << dumping_base << ")" << endl;
ScoreComponentCollection tmpAverageWeights(cumulativeWeights);
bool proceed = false;
if (accumulateWeights) {
if (numberOfUpdates > 0) {
tmpAverageWeights.DivideEquals(numberOfUpdates);
proceed = true;
}
} else {
if (numberOfUpdatesThisEpoch > 0) {
if (sparseNoAverage) // average only core weights
tmpAverageWeights.CoreDivideEquals(numberOfUpdatesThisEpoch);
else if (sparseAverage)
tmpAverageWeights.DivideEquals(cumulativeWeightsBinary);
else
tmpAverageWeights.DivideEquals(numberOfUpdatesThisEpoch);
proceed = true;
}
}
if (proceed) {
#ifdef MPI_ENABLE
// average across processes
mpi::reduce(world, tmpAverageWeights, mixedAverageWeights, SCCPlus(), 0);
ScoreComponentCollection totalBinary;
if (sparseAverage) {
ScoreComponentCollection binary;
binary.SetToBinaryOf(mosesWeights);
mpi::reduce(world, binary, totalBinary, SCCPlus(), 0);
}
#endif
#ifndef MPI_ENABLE
mixedAverageWeights = tmpAverageWeights;
//FIXME: What do to for non-mpi version
ScoreComponentCollection totalBinary;
#endif
if (rank == 0 && !weightDumpStem.empty()) {
// divide by number of processes
if (sparseNoAverage)
mixedAverageWeights.CoreDivideEquals(size); // average only core weights
else if (sparseAverage)
mixedAverageWeights.DivideEquals(totalBinary);
else
mixedAverageWeights.DivideEquals(size);
// normalise weights after averaging
if (normaliseWeights) {
mixedAverageWeights.L1Normalise();
}
// dump final average weights
ostringstream filename;
if (epoch < 10) {
filename << weightDumpStem << "_0" << epoch;
} else {
filename << weightDumpStem << "_" << epoch;
}
if (weightDumpFrequency > 1) {
filename << "_" << weightEpochDump;
}
/*if (accumulateWeights) {
cerr << "\nMixed average weights (cumulative) during epoch " << epoch << ": " << mixedAverageWeights << endl;
} else {
cerr << "\nMixed average weights during epoch " << epoch << ": " << mixedAverageWeights << endl;
}*/
cerr << "Dumping mixed average weights during epoch " << epoch << " to " << filename.str() << endl << endl;
mixedAverageWeights.Save(filename.str());
++weightEpochDump;
if (weightEpochDump == weightDumpFrequency) {
if (l1_regularize) {
size_t pruned = mixedAverageWeights.SparseL1Regularize(l1_lambda);
cerr << "Rank " << rank << ", epoch " << epoch << ", "
<< "l1-reg. on mixedAverageWeights with lambda=" << l1_lambda << ", pruned: " << pruned << endl;
}
if (l2_regularize) {
mixedAverageWeights.SparseL2Regularize(l2_lambda);
cerr << "Rank " << rank << ", epoch " << epoch << ", "
<< "l2-reg. on mixedAverageWeights with lambda=" << l2_lambda << endl;
}
if (l1_regularize || l2_regularize) {
filename << "_reg";
cerr << "Dumping regularized mixed average weights during epoch " << epoch << " to " << filename.str() << endl << endl;
mixedAverageWeights.Save(filename.str());
}
}
if (weightEpochDump == weightDumpFrequency && printFeatureCounts) {
// print out all features with counts
stringstream s1, s2;
s1 << "sparse_feature_hope_counts" << "_" << epoch;
s2 << "sparse_feature_fear_counts" << "_" << epoch;
ofstream sparseFeatureCountsHope(s1.str().c_str());
ofstream sparseFeatureCountsFear(s2.str().c_str());
mixedAverageWeights.PrintSparseHopeFeatureCounts(sparseFeatureCountsHope);
mixedAverageWeights.PrintSparseFearFeatureCounts(sparseFeatureCountsFear);
sparseFeatureCountsHope.close();
sparseFeatureCountsFear.close();
}
}
}
}// end dumping
} // end if dump
} // end of shard loop, end of this epoch
cerr << "Rank " << rank << ", epoch " << epoch << ", end of epoch.." << endl;
if (historyBleu || simpleHistoryBleu) {
cerr << "Bleu feature history after epoch " << epoch << endl;
decoder->printBleuFeatureHistory(cerr);
}
// cerr << "Rank " << rank << ", epoch " << epoch << ", sum of violated constraints: " << sumStillViolatedConstraints << endl;
// Check whether there were any weight updates during this epoch
size_t sumUpdates;
size_t *sendbuf_uint, *recvbuf_uint;
sendbuf_uint = (size_t *) malloc(sizeof(size_t));
recvbuf_uint = (size_t *) malloc(sizeof(size_t));
#ifdef MPI_ENABLE
sendbuf_uint[0] = numberOfUpdatesThisEpoch;
recvbuf_uint[0] = 0;
MPI_Reduce(sendbuf_uint, recvbuf_uint, 1, MPI_UNSIGNED, MPI_SUM, 0, world);
sumUpdates = recvbuf_uint[0];
#endif
#ifndef MPI_ENABLE
sumUpdates = numberOfUpdatesThisEpoch;
#endif
if (rank == 0 && sumUpdates == 0) {
cerr << "\nNo weight updates during this epoch.. stopping." << endl;
stop = true;
#ifdef MPI_ENABLE
mpi::broadcast(world, stop, 0);
#endif
}
if (!stop) {
// Test if weights have converged
if (weightConvergence) {
bool reached = true;
if (rank == 0 && (epoch >= 2)) {
ScoreComponentCollection firstDiff, secondDiff;
if (dumpMixedWeights) {
firstDiff = mixedWeights;
firstDiff.MinusEquals(mixedWeightsPrevious);
secondDiff = mixedWeights;
secondDiff.MinusEquals(mixedWeightsBeforePrevious);
}
else {
firstDiff = mixedAverageWeights;
firstDiff.MinusEquals(mixedAverageWeightsPrevious);
secondDiff = mixedAverageWeights;
secondDiff.MinusEquals(mixedAverageWeightsBeforePrevious);
}
VERBOSE(1, "Average weight changes since previous epoch: " << firstDiff << " (max: " << firstDiff.GetLInfNorm() << ")" << endl);
VERBOSE(1, "Average weight changes since before previous epoch: " << secondDiff << " (max: " << secondDiff.GetLInfNorm() << ")" << endl << endl);
// check whether stopping criterion has been reached
// (both difference vectors must have all weight changes smaller than min_weight_change)
if (firstDiff.GetLInfNorm() >= min_weight_change)
reached = false;
if (secondDiff.GetLInfNorm() >= min_weight_change)
reached = false;
if (reached) {
// stop MIRA
stop = true;
cerr << "\nWeights have converged after epoch " << epoch << ".. stopping MIRA." << endl;
ScoreComponentCollection dummy;
ostringstream endfilename;
endfilename << "stopping";
dummy.Save(endfilename.str());
}
}
mixedWeightsBeforePrevious = mixedWeightsPrevious;
mixedWeightsPrevious = mixedWeights;
mixedAverageWeightsBeforePrevious = mixedAverageWeightsPrevious;
mixedAverageWeightsPrevious = mixedAverageWeights;
#ifdef MPI_ENABLE
mpi::broadcast(world, stop, 0);
#endif
} //end if (weightConvergence)
}
} // end of epoch loop
#ifdef MPI_ENABLE
MPI_Finalize();
#endif
time(&now);
cerr << "Rank " << rank << ", " << ctime(&now);
if (rank == 0) {
ScoreComponentCollection dummy;
ostringstream endfilename;
endfilename << "finished";
dummy.Save(endfilename.str());
}
delete decoder;
exit(0);
}
bool loadSentences(const string& filename, vector<string>& sentences) {
ifstream in(filename.c_str());
if (!in)
return false;
string line;
while (getline(in, line))
sentences.push_back(line);
return true;
}
bool evaluateModulo(size_t shard_position, size_t mix_or_dump_base, size_t actual_batch_size) {
if (mix_or_dump_base == 0) return 0;
if (actual_batch_size > 1) {
bool mix_or_dump = false;
size_t numberSubtracts = actual_batch_size;
do {
if (shard_position % mix_or_dump_base == 0) {
mix_or_dump = true;
break;
}
--shard_position;
--numberSubtracts;
} while (numberSubtracts > 0);
return mix_or_dump;
}
else {
return ((shard_position % mix_or_dump_base) == 0);
}
}
void printFeatureValues(vector<vector<ScoreComponentCollection> > &featureValues) {
for (size_t i = 0; i < featureValues.size(); ++i) {
for (size_t j = 0; j < featureValues[i].size(); ++j) {
cerr << featureValues[i][j] << endl;
}
}
cerr << endl;
}
void deleteTranslations(vector<vector<const Word*> > &translations) {
for (size_t i = 0; i < translations.size(); ++i) {
for (size_t j = 0; j < translations[i].size(); ++j) {
delete translations[i][j];
}
}
}
void decodeHopeOrFear(size_t rank, size_t size, size_t decode, string filename, vector<string> &inputSentences, MosesDecoder* decoder, size_t n, float bleuWeight) {
if (decode == 1)
cerr << "Rank " << rank << ", decoding dev input set according to hope objective.. " << endl;
else if (decode == 2)
cerr << "Rank " << rank << ", decoding dev input set according to fear objective.. " << endl;
else
cerr << "Rank " << rank << ", decoding dev input set according to normal objective.. " << endl;
// Create shards according to the number of processes used
vector<size_t> order;
for (size_t i = 0; i < inputSentences.size(); ++i)
order.push_back(i);
vector<size_t> shard;
float shardSize = (float) (order.size()) / size;
size_t shardStart = (size_t) (shardSize * rank);
size_t shardEnd = (size_t) (shardSize * (rank + 1));
if (rank == size - 1) {
shardEnd = inputSentences.size();
shardSize = shardEnd - shardStart;
}
VERBOSE(1, "Rank " << rank << ", shard start: " << shardStart << " Shard end: " << shardEnd << endl);
VERBOSE(1, "Rank " << rank << ", shard size: " << shardSize << endl);
shard.resize(shardSize);
copy(order.begin() + shardStart, order.begin() + shardEnd, shard.begin());
// open files for writing
stringstream fname;
fname << filename << ".rank" << rank;
filename = fname.str();
ostringstream filename_nbest;
filename_nbest << filename << "." << n << "best";
ofstream out(filename.c_str());
ofstream nbest_out((filename_nbest.str()).c_str());
if (!out) {
ostringstream msg;
msg << "Unable to open " << fname.str();
throw runtime_error(msg.str());
}
if (!nbest_out) {
ostringstream msg;
msg << "Unable to open " << filename_nbest;
throw runtime_error(msg.str());
}
for (size_t i = 0; i < shard.size(); ++i) {
size_t sid = shard[i];
string& input = inputSentences[sid];
vector<vector<ScoreComponentCollection> > dummyFeatureValues;
vector<vector<float> > dummyBleuScores;
vector<vector<float> > dummyModelScores;
vector<ScoreComponentCollection> newFeatureValues;
vector<float> newScores;
dummyFeatureValues.push_back(newFeatureValues);
dummyBleuScores.push_back(newScores);
dummyModelScores.push_back(newScores);
float factor = 0.0;
if (decode == 1) factor = 1.0;
if (decode == 2) factor = -1.0;
cerr << "Rank " << rank << ", translating sentence " << sid << endl;
bool realBleu = false;
vector< vector<const Word*> > nbestOutput = decoder->getNBest(input, sid, n, factor, bleuWeight, dummyFeatureValues[0],
dummyBleuScores[0], dummyModelScores[0], n, realBleu, true, false, rank, 0, "");
cerr << endl;
decoder->cleanup(StaticData::Instance().GetSearchAlgorithm() == ChartDecoding);
for (size_t i = 0; i < nbestOutput.size(); ++i) {
vector<const Word*> output = nbestOutput[i];
stringstream translation;
for (size_t k = 0; k < output.size(); ++k) {
Word* w = const_cast<Word*>(output[k]);
translation << w->GetString(0);
translation << " ";
}
if (i == 0)
out << translation.str() << endl;
nbest_out << sid << " ||| " << translation.str() << " ||| " << dummyFeatureValues[0][i] <<
" ||| " << dummyModelScores[0][i] << " ||| sBleu=" << dummyBleuScores[0][i] << endl;
}
}
out.close();
nbest_out.close();
cerr << "Closing files " << filename << " and " << filename_nbest.str() << endl;
#ifdef MPI_ENABLE
MPI_Finalize();
#endif
time_t now;
time(&now);
cerr << "Rank " << rank << ", " << ctime(&now);
delete decoder;
exit(0);
}
void applyLearningRates(vector<vector<ScoreComponentCollection> > &featureValues, float core_r0, float sparse_r0) {
for (size_t i=0; i<featureValues.size(); ++i) // each item in batch
for (size_t j=0; j<featureValues[i].size(); ++j) // each item in nbest
featureValues[i][j].MultiplyEquals(core_r0, sparse_r0);
}
void applyPerFeatureLearningRates(vector<vector<ScoreComponentCollection> > &featureValues, ScoreComponentCollection featureLearningRates, float sparse_r0) {
for (size_t i=0; i<featureValues.size(); ++i) // each item in batch
for (size_t j=0; j<featureValues[i].size(); ++j) // each item in nbest
featureValues[i][j].MultiplyEqualsBackoff(featureLearningRates, sparse_r0);
}
void scaleFeatureScore(ScoreProducer *sp, float scaling_factor, vector<vector<ScoreComponentCollection> > &featureValues, size_t rank, size_t epoch) {
string name = sp->GetScoreProducerWeightShortName();
// scale down score
float featureScore;
for (size_t i=0; i<featureValues.size(); ++i) { // each item in batch
for (size_t j=0; j<featureValues[i].size(); ++j) { // each item in nbest
featureScore = featureValues[i][j].GetScoreForProducer(sp);
featureValues[i][j].Assign(sp, featureScore*scaling_factor);
//cerr << "Rank " << rank << ", epoch " << epoch << ", " << name << " score scaled from " << featureScore << " to " << featureScore/scaling_factor << endl;
}
}
}
void scaleFeatureScores(ScoreProducer *sp, float scaling_factor, vector<vector<ScoreComponentCollection> > &featureValues, size_t rank, size_t epoch) {
string name = sp->GetScoreProducerWeightShortName();
// scale down score
for (size_t i=0; i<featureValues.size(); ++i) { // each item in batch
for (size_t j=0; j<featureValues[i].size(); ++j) { // each item in nbest
vector<float> featureScores = featureValues[i][j].GetScoresForProducer(sp);
for (size_t k=0; k<featureScores.size(); ++k)
featureScores[k] *= scaling_factor;
featureValues[i][j].Assign(sp, featureScores);
//cerr << "Rank " << rank << ", epoch " << epoch << ", " << name << " score scaled from " << featureScore << " to " << featureScore/scaling_factor << endl;
}
}
}
| 43.089814 | 223 | 0.671394 | [
"vector",
"model"
] |
d1fa833bcd7c8c6850d68e06349c9dc849295354 | 905 | cpp | C++ | stl/tests/test_11-get_just_odd.cpp | Merulo/Solutions | 28ceaef4daf28dc77bc4e44c3668f045eb277347 | [
"MIT"
] | null | null | null | stl/tests/test_11-get_just_odd.cpp | Merulo/Solutions | 28ceaef4daf28dc77bc4e44c3668f045eb277347 | [
"MIT"
] | null | null | null | stl/tests/test_11-get_just_odd.cpp | Merulo/Solutions | 28ceaef4daf28dc77bc4e44c3668f045eb277347 | [
"MIT"
] | null | null | null | #include <algorithm>
#include "gtest/gtest.h"
#include "fixture.hpp"
#include "11-get_just_odd.hpp"
TYPED_TEST(ContainerTypedTests, GetJustOddNumbers_ThereAreOddNumbers) {
const typename TestFixture::ContainerType input{5, 6, 7, 8};
const std::vector<int> expected{6, 8};
const auto result = getOddNumbers(input);
EXPECT_TRUE(std::equal(result.begin(), result.end(), expected.begin()));
}
TYPED_TEST(ContainerTypedTests, GetJustOddNumbers_NoOddNumbersAtAll) {
const typename TestFixture::ContainerType input{5, 7, 9, 11};
const auto result = getOddNumbers(input);
EXPECT_TRUE(result.empty());
}
TYPED_TEST(ContainerTypedTests, GetJustOddNumbers_JustOddNumbers) {
const typename TestFixture::ContainerType input{4, 6, 8, 10};
const std::vector<int> expected{4, 6, 8, 10};
const auto result = getOddNumbers(input);
EXPECT_TRUE(std::equal(result.begin(), result.end(), expected.begin()));
}
| 32.321429 | 73 | 0.759116 | [
"vector"
] |
0602e497c2cc5e9649dc6a3f47e32c567bbfe37c | 1,994 | cpp | C++ | tab_files/resource_tab_files/ResourceTab.cpp | mozumder/PMSPro | 4077a694747b8f889e26c39c8881cac2537a9631 | [
"Apache-2.0"
] | null | null | null | tab_files/resource_tab_files/ResourceTab.cpp | mozumder/PMSPro | 4077a694747b8f889e26c39c8881cac2537a9631 | [
"Apache-2.0"
] | null | null | null | tab_files/resource_tab_files/ResourceTab.cpp | mozumder/PMSPro | 4077a694747b8f889e26c39c8881cac2537a9631 | [
"Apache-2.0"
] | null | null | null | #include "ResourceTab.h"
ResourceTab::ResourceTab(QWidget *parent) : QWidget(parent)
{
resourceNameLabel = new QLabel(tr("Resource Name:"));
resourceDescriptionLabel = new QLabel(tr("Resource Description:"));
resourceNameField = new QLineEdit;
resourceDescriptionField = new QTextEdit;
layout = new QGridLayout;
layout->addWidget(resourceNameLabel, 0,0, Qt::AlignRight);
layout->addWidget(resourceDescriptionLabel, 1,0, Qt::AlignRight);
layout->addWidget(resourceNameField, 0,1,1,2);
layout->addWidget(resourceDescriptionField, 1,1,1,3);
setLayout(layout);
}
void ResourceTab::showResourceValues(Resource &r)
{
cout << "Showing Resource values\n";
QString name = r.getName();
QString description = r.getDescription();
QTextDocument *descriptionDocument = new QTextDocument(description);
resourceNameField->setText(name);
resourceDescriptionField->setDocument(descriptionDocument);
}
void ResourceTab::updateResource()
{
QString name = resourceNameField->text();
QString description = resourceDescriptionField->toPlainText();
/* need to implement this in Resource class
Resource *resource = new Resource(name, description, tasksInvolved, startDate, endDate);
emit updateResourceSignal(resource);
*/
}
/*
* displays data from task object passed from external signal.
* ui fields are filled in accordingly.
*/
void ResourceTab::drawResource(Resource &resource)
{
// gather data from resource data members
QString name = resource.getName();
QString creator = resource.getCreator();
QString description = resource.getDescription();
//QTextDocument *descriptionDocument = new QTextDocument(description);
//QString calendar = resource.getCalender();
/* this has all changed
* we'll see
*
// fill in ui fields
_resourceName->setText(name);
_resourceStartDate->setDateTime(creationDate);
_resourceDescription->setDocument(descriptionDocument);
_workLog->setText(workLog);
*/
}
| 28.898551 | 90 | 0.738716 | [
"object"
] |
06055d1e3b04a1683d7405ee112f53b79f688b43 | 9,817 | cpp | C++ | pxr/imaging/lib/hd/bufferArrayRegistry.cpp | unity3d-jp/USD | 0f146383613e1efe872ea7c85aa3536f170fcda2 | [
"BSD-3-Clause"
] | 7 | 2016-12-13T00:53:38.000Z | 2020-04-02T13:25:50.000Z | pxr/imaging/lib/hd/bufferArrayRegistry.cpp | unity3d-jp/USD | 0f146383613e1efe872ea7c85aa3536f170fcda2 | [
"BSD-3-Clause"
] | null | null | null | pxr/imaging/lib/hd/bufferArrayRegistry.cpp | unity3d-jp/USD | 0f146383613e1efe872ea7c85aa3536f170fcda2 | [
"BSD-3-Clause"
] | 2 | 2016-12-13T00:53:40.000Z | 2020-05-04T07:32:53.000Z | //
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#include "pxr/imaging/hd/bufferArrayRegistry.h"
#include "pxr/imaging/hd/bufferArray.h"
HdBufferArrayRegistry::HdBufferArrayRegistry()
: _entries()
{
}
HdBufferArrayRangeSharedPtr HdBufferArrayRegistry::AllocateRange(
HdAggregationStrategy *strategy,
TfToken const &role,
HdBufferSpecVector const &bufferSpecs)
{
HD_TRACE_FUNCTION();
HD_MALLOC_TAG_FUNCTION();
// early out for empty source
if (not TF_VERIFY(not bufferSpecs.empty())) {
return HdBufferArrayRangeSharedPtr();
}
if (not strategy) {
TF_CODING_ERROR("Aggregation strategy is set to null");
return HdBufferArrayRangeSharedPtr();
}
// compute an aggregation Id on current aggregation strategy
HdAggregationStrategy::AggregationId aggrId =
strategy->ComputeAggregationId(bufferSpecs);
// We use insert to do a find and insert operation
std::pair<_BufferArrayIndex::iterator, bool> result =_entries.insert(std::make_pair(aggrId, _Entry()));
_Entry &entry = (result.first)->second;
if (result.second) {
// We just created a new entry so make sure it has a buffer in it.
_InsertNewBufferArray(entry, HdBufferArraySharedPtr(), strategy, role, bufferSpecs);
} else {
// There's a protential multi-thread race condition where
// another thread has created the entry and is still in the process of adding
// the first buffer to it, therefore the list could be empty, so wait for it
_EntryIsNotEmpty pred(entry);
std::unique_lock<std::mutex> lock(entry.lock);
entry.emptyCondition.wait(lock, pred);
}
HdBufferArrayRangeSharedPtr range = strategy->CreateBufferArrayRange();
// Try to find where to insert the range.
// while no new slots can free up during allocate,
// garbage collection may create empty slots in entries.
// So we have to go through the list to find slots.
// Tough as this is Multi-thread, entries maybe added to the list.
// This doesn't invalidate the interator, but need to be careful
// on check end condition.
_HdBufferArraySharedPtrList::iterator it = entry.bufferArrays.begin();
do {
HdBufferArraySharedPtr currentArray = *it;
if (not currentArray->TryAssignRange(range)) {
_HdBufferArraySharedPtrList::iterator prev = it;
++it;
if (it == entry.bufferArrays.end()) {
// Reached end of buffer list, so try to insert new buffer
// Only one thread will win and add the buffer
// however, by the time we get back multiple buffers may have
// been added, so rewind iterator.
_InsertNewBufferArray(entry, currentArray, strategy, role, bufferSpecs);
it = prev;
++it;
}
}
} while (not range->IsAssigned());
return range;
}
void
HdBufferArrayRegistry::ReallocateAll(HdAggregationStrategy *strategy)
{
for (auto& entry : _entries) {
for (auto bufferIt = entry.second.bufferArrays.begin(),
e = entry.second.bufferArrays.end();
bufferIt != e; ++bufferIt) {
HdBufferArraySharedPtr const &bufferArray = *bufferIt;
if (not bufferArray->NeedsReallocation()) continue;
// in case of over aggregation, split the buffer
bufferArray->RemoveUnusedRanges();
size_t maxTotalElements = bufferArray->GetMaxNumElements();
size_t numTotalElements = 0;
size_t rangeCount = bufferArray->GetRangeCount();
std::vector<HdBufferArrayRangeSharedPtr> ranges;
ranges.reserve(rangeCount);
for (size_t rangeIdx = 0; rangeIdx < rangeCount; ++rangeIdx) {
HdBufferArrayRangeSharedPtr range =
bufferArray->GetRange(rangeIdx).lock();
if (not range) continue; // shouldn't exist
size_t numElements = range->GetNumElements();
// numElements in each range should not exceed maxTotalElements
if (not TF_VERIFY(numElements < maxTotalElements))
continue;
// over aggregation check of non-uniform buffer
if (numTotalElements + numElements > maxTotalElements) {
// create new BufferArray with same specification
HdBufferSpecVector bufferSpecs = bufferArray->GetBufferSpecs();
HdBufferArraySharedPtr newBufferArray =
strategy->CreateBufferArray(bufferArray->GetRole(),
bufferSpecs);
newBufferArray->Reallocate(ranges, bufferArray);
// bufferArrays is std::list
entry.second.bufferArrays.insert(bufferIt, newBufferArray);
numTotalElements = 0;
ranges.clear();
}
numTotalElements += numElements;
ranges.push_back(range);
}
bufferArray->Reallocate(ranges, bufferArray);
}
}
}
void
HdBufferArrayRegistry::GarbageCollect()
{
_BufferArrayIndex::iterator entryIt = _entries.begin();
while (entryIt != _entries.end()) {
_Entry &entry = entryIt->second;
_HdBufferArraySharedPtrList::iterator bufferIt = entry.bufferArrays.begin();
while (bufferIt != entry.bufferArrays.end()) {
if ((*bufferIt)->GarbageCollect()) {
bufferIt = entry.bufferArrays.erase(bufferIt);
} else {
++bufferIt;
}
}
if (entry.bufferArrays.empty()) {
entryIt = _entries.unsafe_erase(entryIt);
} else {
++entryIt;
}
}
}
size_t
HdBufferArrayRegistry::GetResourceAllocation(VtDictionary &result) const
{
size_t gpuMemoryUsed = 0;
std::set<GLuint> idSet;
TF_FOR_ALL (entryIt, _entries) {
TF_FOR_ALL(bufferIt, entryIt->second.bufferArrays) {
idSet.clear();
TF_FOR_ALL(resIt, (*bufferIt)->GetResources()) {
HdResourceSharedPtr const & resource = resIt->second;
// XXX avoid double counting of resources shared within a buffer
GLuint id = resource->GetId();
if (idSet.count(id) == 0) {
idSet.insert(id);
std::string const & role = resource->GetRole().GetString();
size_t size = size_t(resource->GetSize());
if (result.count(role)) {
size_t currentSize = result[role].Get<size_t>();
result[role] = VtValue(currentSize + size);
} else {
result[role] = VtValue(size);
}
gpuMemoryUsed += size;
}
}
}
}
return gpuMemoryUsed;
}
void
HdBufferArrayRegistry::_InsertNewBufferArray(_Entry &entry,
const HdBufferArraySharedPtr &expectedTail,
HdAggregationStrategy *strategy,
TfToken const &role,
HdBufferSpecVector const &bufferSpecs)
{
{
std::lock_guard<std::mutex> lock(entry.lock);
// Check state of list, still matches what is expected.
// If not another thread won and inserted a new buffer.
if (not entry.bufferArrays.empty()) {
if (entry.bufferArrays.back() != expectedTail) {
return; // Lock_guard will unlock entry
}
} else {
// This shouldn't ever happen, because where did the expected tail
// come from if it wasn't in the list???
TF_VERIFY(not expectedTail);
}
entry.bufferArrays.emplace_back(strategy->CreateBufferArray(role, bufferSpecs));
} // Lock_guard will unlock
// Notify any threads waiting on an empty list (unlock must happen first).
entry.emptyCondition.notify_all();
}
std::ostream &
operator <<(std::ostream &out, const HdBufferArrayRegistry& self)
{
out << "HdBufferArrayRegistry " << &self << " :\n";
TF_FOR_ALL (entryIt, self._entries) {
out << " _Entry aggrId = " << entryIt->first << ": \n";
size_t bufferNum = 0;
TF_FOR_ALL(bufferIt, entryIt->second.bufferArrays) {
out << "HdBufferArray " << bufferNum << "\n";
out << **bufferIt;
}
}
return out;
}
| 34.812057 | 107 | 0.59998 | [
"vector"
] |
0605b697d0ac78327b9918396b30bba438ca90dd | 2,809 | cpp | C++ | src/BVH.cpp | wonderyue/RayTracing | 4ef3562bfc3fe7192962243b7b0fae675ec4ee95 | [
"MIT"
] | null | null | null | src/BVH.cpp | wonderyue/RayTracing | 4ef3562bfc3fe7192962243b7b0fae675ec4ee95 | [
"MIT"
] | null | null | null | src/BVH.cpp | wonderyue/RayTracing | 4ef3562bfc3fe7192962243b7b0fae675ec4ee95 | [
"MIT"
] | null | null | null | #include <algorithm>
#include <cassert>
#include "BVH.h"
BVH::BVH(std::vector<Object*>& objects) {
if (objects.empty())
return;
root = build(objects, 0, objects.size());
}
BVH::~BVH() {
delete root;
root = NULL;
}
BVH::BVHNode* BVH::build(std::vector<Object*>& objects, std::vector<Object*>::size_type startIdx, std::vector<Object*>::size_type endIdx) {
BVHNode* node = new BVHNode();
if (endIdx - startIdx == 1) {
node->bounds = objects[startIdx]->getBounds();
node->object = objects[startIdx];
node->left = NULL;
node->right = NULL;
return node;
} else if (endIdx - startIdx == 2) {
node->left = build(objects, startIdx, startIdx+1);
node->right = build(objects, startIdx+1, endIdx);
node->bounds = merge(node->left->bounds, node->right->bounds);
return node;
} else {
Bounds3 centroidBounds;
for (int i = 0; i < objects.size(); ++i)
centroidBounds = merge(centroidBounds, objects[i]->getBounds().centroid);
int dim = centroidBounds.longestAxis();
switch (dim) {
case 0:
std::sort(objects.begin(), objects.end(), [](auto f1, auto f2) {
return f1->getBounds().centroid.x < f2->getBounds().centroid.x;
});
break;
case 1:
std::sort(objects.begin(), objects.end(), [](auto f1, auto f2) {
return f1->getBounds().centroid.y < f2->getBounds().centroid.y;
});
break;
case 2:
std::sort(objects.begin(), objects.end(), [](auto f1, auto f2) {
return f1->getBounds().centroid.z < f2->getBounds().centroid.z;
});
break;
}
std::vector<Object*>::size_type midIdx = (endIdx - startIdx) / 2 + startIdx;
node->left = build(objects, startIdx, midIdx);
node->right = build(objects, midIdx, endIdx);
node->bounds = merge(node->left->bounds, node->right->bounds);
}
return node;
}
Intersection BVH::rayCast(const Ray& ray) const {
Intersection res;
if (root == NULL)
return res;
res = rayCast(root, ray);
return res;
}
Intersection BVH::rayCast(BVHNode* node, const Ray& ray) const {
Intersection res;
if (node == NULL)
return res;
if (!node->bounds.rayCast(ray))
return res;
if (node->left == NULL && node->right == NULL)
return node->object->rayCast(ray);
res = rayCast(node->left, ray);
if (!res.happened)
return rayCast(node->right, ray);
Intersection right = rayCast(node->right, ray);
if (right.happened && right.distance < res.distance)
return right;
return res;
}
| 33.440476 | 139 | 0.552154 | [
"object",
"vector"
] |
0612d8561ef9ecb7caf6d8cefc52a6b553e2c028 | 6,633 | cpp | C++ | exercise/src/example/TwoLightsWithStruct/TwoLightsWithStruct.cpp | softwarekid/crayon | 72fe08eab4b4282ad729ee2719e75df2f02f1def | [
"MIT"
] | null | null | null | exercise/src/example/TwoLightsWithStruct/TwoLightsWithStruct.cpp | softwarekid/crayon | 72fe08eab4b4282ad729ee2719e75df2f02f1def | [
"MIT"
] | null | null | null | exercise/src/example/TwoLightsWithStruct/TwoLightsWithStruct.cpp | softwarekid/crayon | 72fe08eab4b4282ad729ee2719e75df2f02f1def | [
"MIT"
] | null | null | null | #include <assert.h>
#include "TwoLightsWithStruct.h"
#include <CG/cgGL.h>
#include <vector>
#include <GL/glut.h>
#include <CgLog.h>
#include <Constants.h>
using namespace std;
void TwoLightsWithStruct::_SetBrassMaterial()
{
}
void TwoLightsWithStruct::_SetRedPlasticMaterial()
{
}
void TwoLightsWithStruct::_SetEmissiveOnly(int lightIndex)
{
assert(lightIndex >= 0 && lightIndex <= 1);
}
void TwoLightsWithStruct::_InitMaterial()
{
// brass material
brassMaterial.ke = { 0.0f, 0.0f, 0.0f };
brassMaterial.ka = { 0.33f, 0.22f, 0.03f };
brassMaterial.kd = { 0.78f, 0.57f, 0.11f };
brassMaterial.ks = { 0.99f, 0.91f, 0.81f };
brassMaterial.shininess = 27.8;
// red plastic
redPlasticMaterial.ke = { 0.0f, 0.0f, 0.0f };
redPlasticMaterial.ka = { 0.0f, 0.0f, 0.0f };
redPlasticMaterial.kd = { 0.5f, 0.0f, 0.0f };
redPlasticMaterial.ks = { 0.7f, 0.6f, 0.6f };
redPlasticMaterial.shininess = 32.0f;
// only emissive
for (int i = 0; i < 2; i++)
{
emissiveMaterial[i].ke = Vector3f( _lightColors[i].x, _lightColors[i].y, _lightColors[i].z );
emissiveMaterial[i].ka = { 0.0f, 0.0f, 0.0f };
emissiveMaterial[i].kd = { 0.0f, 0.0f, 0.0f };
emissiveMaterial[i].ks = { 0.0f, 0.0f, 0.0f };
emissiveMaterial->shininess = 0.0f;
}
}
void TwoLightsWithStruct::_SetMaterial(const Material& m)
{
_vertParams->SetMaterialKe(m.ke);
_vertParams->SetMaterialKa(m.ka);
_vertParams->SetMaterialKd(m.kd);
_vertParams->SetMaterialKs(m.ks);
_vertParams->SetMaterialShininess(m.shininess);
}
void TwoLightsWithStruct::_Draw(const Vector4f& rotation, const Vector3f& translate,const Vector3f& eyePos, const vector<Vector3f>& lightPositions, const Material& m, RenderObject obj )
{
_SetMaterial(m);
_transform.SetArbitraryRotation(rotation[1], rotation[2], rotation[3], rotation[4]);
_transform.SetTranslate(translate.x, translate.y, translate.z);
Matrix4f modelMatrix;
_transform.GetModelMatrix(modelMatrix);
//TODO can I use rvalue-reference here?
Matrix4f invModelMatrix = modelMatrix.Invert();
Vector3f objSpaceEyePosition = _MatVecMulReduced(invModelMatrix, eyePos);
_vertParams->SetEyePosition(objSpaceEyePosition);
for (int i = 0; i < lightPositions.size(); i++)
{
Vector3f objSpaceLightPosition = _MatVecMulReduced(invModelMatrix, lightPositions[i]);
_vertParams->SetLightPos(i, objSpaceLightPosition);
}
Matrix4f modelViewProjMatix;
_transform.GetMVPMatrix(modelViewProjMatix);
_vertParams->SetMVPMatrix(modelViewProjMatix);
// deferred params are updated, aka, perform a draw call
_vertShader->UpdateParams();
switch (obj)
{
case RenderObject::Sphere:
glutSolidSphere(2.0, 40, 40);
break;
case RenderObject::Cone:
glutSolidCone(1.5, 3.5, 30, 30);
break;
case RenderObject::SmallSphere:
glutSolidSphere(0.2, 12, 12);
}
}
void TwoLightsWithStruct::_Idle()
{
_lightAngles[0] += 0.008; /* Add a small angle (in radians). */
if (_lightAngles[0] > 2 * Constants::Math::PI)
{
_lightAngles[0] -= 2 * Constants::Math::PI;
}
_lightAngles[1] -= 0.005; /* Add a small angle (in radians). */
if (_lightAngles[1] < 2 * Constants::Math::PI)
{
_lightAngles[1] += 2 * Constants::Math::PI;
}
glutPostRedisplay();
}
void TwoLightsWithStruct::_Display()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
const Vector3f eyePosition(0, 0, 13);
const Vector3f eyeCenter(0, 0, 0);
const Vector3f eyeUp(0, 1, 0);
const vector<Vector3f> lightPositions{Vector3f(5 * sin(_lightAngles[0]), 1.5, 5 * cos(_lightAngles[0])),
Vector3f(5 * sin(_lightAngles[1]), 0.25, 5 * cos(_lightAngles[1]))};
_vertShader->BindProgram();
_vertShader->EnableProfile();
_fragShader->BindProgram();
_fragShader->EnableProfile();
_InitLightColor();
Camera camera(eyePosition, eyeCenter, eyeUp);
_transform.SetCamera(camera);
Vector3f translation;
Vector4f rotation;
translation = Vector3f(2, 0, 0);
rotation = Vector4f(-70, 1, 1, 1);
_Draw(rotation, translation, eyePosition, lightPositions, brassMaterial, RenderObject::Sphere);
translation = Vector3f(-2.0f, -1.5f, 0);
rotation = Vector4f(-90, 1, 0, 0);
_Draw(rotation, translation, eyePosition, lightPositions, redPlasticMaterial, RenderObject::Cone);
for (int i = 0; i < 2; i++)
{
rotation = Vector4f(0, 1, 0, 0);
_Draw(rotation, lightPositions[i], eyePosition, lightPositions, emissiveMaterial[i], RenderObject::SmallSphere);
}
_vertShader->DisableProfile();
_fragShader->DisableProfile();
glutSwapBuffers();
}
void TwoLightsWithStruct::_InitVertShader()
{
auto profileVertex = cgGLGetLatestProfile(CG_GL_VERTEX);
string fileName(R"(src\example\TwoLightsWithStruct\TwoLightsWithStruct_V.cg)");
string entry("main_v");
_vertShader = new CgShader(_context, profileVertex, fileName, entry);
_vertParams = new TwoLightsWithStructVsParam(*_vertShader);
_vertParams->ExtractParams();
cgGLSetOptimalOptions(profileVertex);
}
void TwoLightsWithStruct::_InitFragShader()
{
auto profileFrag = cgGLGetLatestProfile(CG_GL_FRAGMENT);
string fileName(R"(src\example\TwoLightsWithStruct\TwoLightsWithStruct_F.cg)");
string entry("main_f");
_fragShader = new CgShader(_context, profileFrag, fileName, entry);
_fragParams = new TwoLightsWithStructFsParam(*_fragShader);
_fragParams->ExtractParams();
cgGLSetOptimalOptions(profileFrag);
}
void TwoLightsWithStruct::_InitLightColor()
{
for (int i = 0; i < 2; i++)
{
_vertParams->SetLightColor(i, _lightColors[i]);
}
_vertParams->SetGlobalAmbient(Vector3f(0.1, 0.1, 0.1));
}
TwoLightsWithStruct::TwoLightsWithStruct(const char* title, int width, int height) : GlutWrapper(title, width, height)
{
glEnable(GL_DEPTH_TEST);
_lightAngles[0] = -0.4;
_lightAngles[1] = -0.1;
_lightColors[0] = Vector3f(0.95, 0.95, 0.95);
_lightColors[1] = Vector3f(0.5, 0.5, 0.2);
_context = cgCreateContext();
CgLog::Log("create content", _context);
cgGLSetDebugMode(CG_TRUE);
cgSetParameterSettingMode(_context,CG_DEFERRED_PARAMETER_SETTING);
CgLog::Log("selecting vertex profile", _context);
_InitMaterial();
} | 34.546875 | 186 | 0.658526 | [
"vector"
] |
06144194fe0ac5c10a52e54f5406efa596647c19 | 3,064 | cpp | C++ | src/mode_calc_help.cpp | ToruNiina/Coffee-mill | 343a6b89f7bc4645d596809aac9009db1c5ec0d8 | [
"MIT"
] | 4 | 2017-12-11T07:26:34.000Z | 2021-02-01T07:33:37.000Z | src/mode_calc_help.cpp | ToruNiina/Coffee-mill | 343a6b89f7bc4645d596809aac9009db1c5ec0d8 | [
"MIT"
] | null | null | null | src/mode_calc_help.cpp | ToruNiina/Coffee-mill | 343a6b89f7bc4645d596809aac9009db1c5ec0d8 | [
"MIT"
] | null | null | null | #include <mill/math/Vector.hpp>
#include <mill/util/logger.hpp>
#include "mode_calc_help.hpp"
#include "mode_calc_rmsd.hpp"
#include "mode_calc_wham.hpp"
#include "mode_calc_dist.hpp"
#include "mode_calc_angle.hpp"
#include "mode_calc_aabb.hpp"
#include "mode_calc_obb.hpp"
#include "mode_calc_center.hpp"
#include "mode_calc_autocorrelation.hpp"
#include "mode_calc_mean.hpp"
#ifdef MILL_WITH_EIGEN
#include "mode_calc_pca.hpp"
#endif
namespace mill
{
const char* mode_calc_help_usage() noexcept
{
return "usage: mill calc [command] [parameters...]\n\n"
" avaiable commands\n"
" - rmsd\n"
" : calculate RMSD between a reference and frames in trajectory\n"
" - wham\n"
" : reconstruct free energy surface by WHAM\n"
" - dist\n"
" : calculate distance from traj file\n"
" - angle\n"
" : calculate angle from traj file\n"
" - aabb\n"
" : construct AABB\n"
" - obb\n"
" : construct OBB using covariances\n"
" - center\n"
" : calculate geometric center\n"
" - autocorrelation\n"
" : calculate autocorrelation of data\n"
" - mean\n"
" : calculate mean structure in a trajectory\n"
#ifdef MILL_WITH_EIGEN
" - pca\n"
" : performs principal component analysis\n"
#endif
" - help\n"
" : print detailed explanation of each command\n";
}
//! this function forwards the arguments to different modes.
int mode_calc_help(std::deque<std::string_view> args)
{
using namespace std::literals::string_view_literals;
if(args.empty())
{
log::info(mode_calc_help_usage());
return 0;
}
const auto command = args.front();
if(command == "rmsd")
{
return mode_calc_rmsd({"help"sv});
}
else if(command == "dist")
{
return mode_calc_dist({"help"sv});
}
else if(command == "angle")
{
return mode_calc_angle({"help"sv});
}
else if(command == "wham")
{
return mode_calc_wham({"help"sv});
}
else if(command == "obb")
{
return mode_calc_obb({"help"sv});
}
else if(command == "aabb")
{
return mode_calc_aabb({"help"sv});
}
else if(command == "center")
{
return mode_calc_center({"help"sv});
}
else if(command == "autocorrelation")
{
return mode_calc_autocorrelation({"help"sv});
}
else if(command == "mean")
{
return mode_calc_mean({"help"sv});
}
#ifdef MILL_WITH_EIGEN
else if(command == "pca")
{
return mode_calc_pca({"help"sv});
}
#endif
else if(command == "help")
{
log::info(mode_calc_help_usage());
return 0;
}
else
{
log::error("mill calc help: unknown command : ", command);
log::error(mode_calc_help_usage());
return 1;
}
}
} // mill
| 25.747899 | 82 | 0.559399 | [
"vector"
] |
16468eee644ff759a236647f2a59f3685e695779 | 4,407 | hpp | C++ | include/com.hpp | nikolaimerkel/DistributedNE | 47bc214b2f6c3641a2c6b78332be5a7bf7ff833b | [
"MIT"
] | 11 | 2019-09-06T10:30:02.000Z | 2022-02-17T20:06:56.000Z | include/com.hpp | nikolaimerkel/DistributedNE | 47bc214b2f6c3641a2c6b78332be5a7bf7ff833b | [
"MIT"
] | null | null | null | include/com.hpp | nikolaimerkel/DistributedNE | 47bc214b2f6c3641a2c6b78332be5a7bf7ff833b | [
"MIT"
] | 8 | 2019-09-09T01:21:11.000Z | 2022-03-27T04:01:13.000Z | /*
* com.hpp
*
* Copyright (c) 2019 Masatoshi Hanai
*
* This software is released under MIT License.
* See LICENSE.
*
*/
#ifndef DISTRIBUTEDNE_COM_HPP
#define DISTRIBUTEDNE_COM_HPP
#include "type.hpp"
class Communicator {
int rank_;
int rankSize_;
public:
template<class T>
void AlltoAll(std::vector<std::vector<T>>& snd,
std::vector<T>& rec);
void allGatherBool(bool requestRandom,
bool*& recRequest);
void init (int rank, int rankSize) {
rank_ = rank;
rankSize_ = rankSize;
}
Communicator(){};
private:
Communicator(const Communicator&);
void operator=(const Communicator&);
};
template<class T>
void Communicator::AlltoAll(std::vector<std::vector<T>>& snd,
std::vector<T>& rec) {
const static long MAX_BUFFER = (long) std::numeric_limits<int>::max() / rankSize_;
/* Check number of messages */
std::vector<uint64_t> sndNumMsg(rankSize_);
uint64_t maxSndNum = 0;
for (int r = 0; r < rankSize_; ++r) {
sndNumMsg[r] = snd[r].size();
maxSndNum = std::max(maxSndNum, (uint64_t) snd[r].size());
}
std::vector<uint64_t> recNumMsg(rankSize_);
MPI_Alltoall(&sndNumMsg[0],
1,
MPI_UINT64_T,
&recNumMsg[0],
1,
MPI_UINT64_T,
MPI_COMM_WORLD);
uint64_t sumMsg = 0;
for (int r = 0; r < rankSize_; ++r) {
sumMsg += recNumMsg[r];
}
uint64_t maxNum = 0;
MPI_Allreduce(&sumMsg, &maxNum, 1, MPI_UINT64_T, MPI_MAX, MPI_COMM_WORLD);
int numItr = maxNum / (MAX_BUFFER / sizeof(T)) + 1;
if (maxNum > (MAX_BUFFER / sizeof(T))) {
/* Multi AlltoAll */
rec.resize(sumMsg);
std::vector<uint64_t> sOffset(rankSize_);
uint64_t rOffset = 0;
for (int i = 0; i < numItr; ++i) {
std::vector<int> sndMsgByte(rankSize_);
for (int r = 0; r < rankSize_; ++r) {
if ((sndNumMsg[r] - sOffset[r]) * sizeof(T) > MAX_BUFFER) {
sndMsgByte[r] = (int) (MAX_BUFFER / sizeof(T)) * sizeof(T);
} else {
sndMsgByte[r] = (int) (sndNumMsg[r] - sOffset[r]) * sizeof(T);
}
}
std::vector<int> recMsgByte(rankSize_);
MPI_Alltoall(&sndMsgByte[0],
1,
MPI_INT,
&recMsgByte[0],
1,
MPI_INT,
MPI_COMM_WORLD);
int rbyte = 0;
std::vector<int> recMsgDips(rankSize_);
for (int r = 0; r < rankSize_; ++r) {
recMsgDips[r] = rbyte;
rbyte += recMsgByte[r];
}
#pragma omp parallel for
for (int r = 0; r < rankSize_; ++r) {
MPI_Gatherv(&(snd[r][sOffset[r]]),
sndMsgByte[r],
MPI_BYTE,
&rec[rOffset],
&recMsgByte[0],
&recMsgDips[0],
MPI_BYTE,
r,
MPI_COMM_WORLD);
sOffset[r] += ((long) sndMsgByte[r]) / sizeof(T);
}
rOffset += ((long) rbyte) / sizeof(T);
}
for (int r = 0; r < rankSize_; ++r) {
std::vector<T>().swap(snd[r]);
}
} else {
/* Single AlltoAll */
std::vector<int> sndMsgByte(rankSize_);
for (int r = 0; r < rankSize_; ++r) {
sndMsgByte[r] = (int) sndNumMsg[r] * sizeof(T);
}
int rbyte = 0;
std::vector<int> recMsgByte(rankSize_);
std::vector<int> recMsgDips(rankSize_);
for (int r = 0; r < rankSize_; ++r) {
recMsgDips[r] = rbyte;
recMsgByte[r] = (int) recNumMsg[r] * sizeof(T);
rbyte += recMsgByte[r];
}
rec.resize(rbyte / sizeof(T));
#pragma omp parallel for
for (int r = 0; r < rankSize_; ++r) {
MPI_Gatherv(&(snd[r][0]),
sndMsgByte[r],
MPI_BYTE,
&rec[0],
&recMsgByte[0],
&recMsgDips[0],
MPI_BYTE,
r,
MPI_COMM_WORLD);
}
for (int r = 0; r < rankSize_; ++r) {
std::vector<T>().swap(snd[r]);
}
}
};
void Communicator::allGatherBool(bool requestRandom, bool*& recRequest) {
MPI_Allgather(&requestRandom,
1,
MPI_CXX_BOOL,
recRequest,
1,
MPI_CXX_BOOL,
MPI_COMM_WORLD);
};
#endif //DISTRIBUTEDNE_COM_HPP
| 26.076923 | 84 | 0.515543 | [
"vector"
] |
164b6a49fac7a0d0de89868820a1b6d7dc92533c | 4,051 | hpp | C++ | Siv3D/include/Siv3D/Bezier2.hpp | Fuyutsubaki/OpenSiv3D | 4370f6ebe28addd39bfdd75915c5a18e3e5e9273 | [
"MIT"
] | null | null | null | Siv3D/include/Siv3D/Bezier2.hpp | Fuyutsubaki/OpenSiv3D | 4370f6ebe28addd39bfdd75915c5a18e3e5e9273 | [
"MIT"
] | null | null | null | Siv3D/include/Siv3D/Bezier2.hpp | Fuyutsubaki/OpenSiv3D | 4370f6ebe28addd39bfdd75915c5a18e3e5e9273 | [
"MIT"
] | null | null | null | //-----------------------------------------------
//
// This file is part of the Siv3D Engine.
//
// Copyright (c) 2008-2018 Ryo Suzuki
// Copyright (c) 2016-2018 OpenSiv3D Project
//
// Licensed under the MIT License.
//
//-----------------------------------------------
# pragma once
# include "Fwd.hpp"
# include "PointVector.hpp"
# include "LineString.hpp"
# include "Geometry2D.hpp"
namespace s3d
{
/// <summary>
/// 2 次ベジェ曲線
/// </summary>
struct Bezier2
{
Vec2 p0, p1, p2;
Bezier2() = default;
constexpr Bezier2(const Vec2& _p0, const Vec2& _p1, const Vec2& _p2) noexcept
: p0(_p0)
, p1(_p1)
, p2(_p2) {}
[[nodiscard]] constexpr Vec2 getPos(const double t) const noexcept
{
return (1 - t) * (1 - t)* p0 + 2 * (1 - t) * t * p1 + t * t * p2;
}
[[nodiscard]] Vec2 getTangent(const double t) const noexcept
{
return ((p1 - p0) * 2 * (1 - t) + (p2 - p1) * (2 * t)).normalized();
}
[[nodiscard]] LineString getLineString(const uint32 quality = 24) const
{
return getLineString(0.0, 1.0, quality);
}
[[nodiscard]] LineString getLineString(double start, double end, uint32 quality = 24) const;
template <class Shape2DType>
[[nodiscard]] bool intersects(const Shape2DType& shape) const
{
return Geometry2D::Intersect(*this, shape);
}
template <class Shape2DType>
[[nodiscard]] Optional<Array<Vec2>> intersectsAt(const Shape2DType& shape) const
{
return Geometry2D::IntersectAt(*this, shape);
}
// paint, overpaint
const Bezier2& draw(const ColorF& color = Palette::White) const
{
return draw(1.0, color);
}
const Bezier2& draw(double thickness, const ColorF& color = Palette::White) const;
};
struct Bezier2Path
{
private:
Vec2 m_v0, m_v1;
double m_t = 0.0;
public:
Bezier2Path() = default;
explicit constexpr Bezier2Path(const Bezier2& bezier) noexcept
: m_v0(2 * bezier.p0 - 4 * bezier.p1 + 2 * bezier.p2)
, m_v1(-2 * bezier.p0 + 2 * bezier.p1) {}
constexpr void setT(const double t) noexcept
{
m_t = t;
}
[[nodiscard]] constexpr double getT() const noexcept
{
return m_t;
}
double advance(const double distance, const int32 quality = 8) noexcept
{
for (int32 i = 0; i < quality; ++i)
{
m_t = m_t + (distance / quality) / (m_t * m_v0 + m_v1).length();
}
return m_t;
}
};
}
//////////////////////////////////////////////////
//
// Format
//
//////////////////////////////////////////////////
namespace s3d
{
void Formatter(FormatData& formatData, const Bezier2& value);
template <class CharType>
inline std::basic_ostream<CharType>& operator <<(std::basic_ostream<CharType>& output, const Bezier2& value)
{
return output << CharType('(')
<< value.p0 << CharType(',') << CharType(' ')
<< value.p1 << CharType(',') << CharType(' ')
<< value.p2 << CharType(')');
}
template <class CharType>
inline std::basic_istream<CharType>& operator >>(std::basic_istream<CharType>& input, Bezier2& value)
{
CharType unused;
return input >> unused
>> value.p0 >> unused
>> value.p1 >> unused
>> value.p2 >> unused;
}
}
//////////////////////////////////////////////////
//
// Hash
//
//////////////////////////////////////////////////
namespace std
{
template <>
struct hash<s3d::Bezier2>
{
[[nodiscard]] size_t operator ()(const s3d::Bezier2& value) const noexcept
{
return s3d::Hash::FNV1a(value);
}
};
}
//////////////////////////////////////////////////
//
// fmt
//
//////////////////////////////////////////////////
namespace fmt
{
template <>
struct formatter<s3d::Bezier2, s3d::char32>
{
s3d::String tag;
template <class ParseContext>
auto parse(ParseContext& ctx)
{
return s3d::detail::GetFmtTag(tag, ctx);
}
template <class Context>
auto format(const s3d::Bezier2& value, Context& ctx)
{
const s3d::String fmt = s3d::detail::MakeFmtArg(
U"({:", tag, U"}, {:", tag, U"}, {:", tag, U"})"
);
return format_to(ctx.begin(), wstring_view(fmt.data(), fmt.size()), value.p0, value.p1, value.p2);
}
};
}
| 21.433862 | 109 | 0.567761 | [
"shape"
] |
164d2db144b7f1662165e79f251fb6f8ac280455 | 46,862 | cpp | C++ | opengl_proxy.cpp | glampert/GLProxy | 5bafc42a6315a07aa03cceb4fa1ba4afd54a49a2 | [
"MIT"
] | 10 | 2016-09-23T22:40:48.000Z | 2022-03-23T00:11:26.000Z | opengl_proxy.cpp | glampert/GLProxy | 5bafc42a6315a07aa03cceb4fa1ba4afd54a49a2 | [
"MIT"
] | null | null | null | opengl_proxy.cpp | glampert/GLProxy | 5bafc42a6315a07aa03cceb4fa1ba4afd54a49a2 | [
"MIT"
] | 2 | 2021-03-08T00:07:35.000Z | 2021-05-05T18:29:46.000Z |
// ================================================================================================
// -*- C++ -*-
// File: opengl_proxy.cpp
// Author: Guilherme R. Lampert
// Created on: 22/11/15
// Brief: GLProxy intercepts all calls to the real OpenGL library.
//
// Source code licensed under the MIT license.
// Copyright (C) 2015 Guilherme R. Lampert
//
// This software is provided "as is" without express or implied
// warranties. You may freely copy and compile this source into
// applications you distribute provided that this copyright text
// is included in the resulting source code.
// ================================================================================================
// Trim down the WinAPI crap. We also don't want WinGDI.h
// to interfere with our WGL wrapper declarations.
#define NOGDI
#define VC_EXTRALEAN
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <algorithm>
#include <fstream>
#include <string>
#include <vector>
#include <cstdint>
#include <cstdlib>
#include <ctime>
// We are not including 'WinGDI.h' and 'gl.h', so the
// required types must be redefined in this source file.
#define GLPROXY_NEED_OGL_TYPES
#define GLPROXY_NEED_WGL_STRUCTS
// ========================================================
// Local helper macros:
// ========================================================
// To pass the silly "constant expression" warning from Visual Studio...
#define END_MACRO while (0,0)
// Local log stream output:
#define GLPROXY_LOG(message) do { GLProxy::getLogStream() << message << std::endl; } END_MACRO
// Appends a pair tokens into a single name/identifier.
// Normally used to declared internal/built-in functions and variables.
#define STRING_JOIN2_HELPER(a, b) a ## b
#define STRING_JOIN2(a, b) STRING_JOIN2_HELPER(a, b)
// Code/text to string:
#define STRINGIZE_HELPER(str) #str
#define STRINGIZE(str) STRINGIZE_HELPER(str)
//
// Calling convention used by OGL functions on Windows is stdcall.
// OpenGL is also a C API, so the 'extern C' should be the correct approach.
// However, these qualifiers alone don't seem enough to prevent the linker from
// decorating our function names, so an additional '.def' file is also required.
//
#define GLPROXY_DECL __stdcall
#define GLPROXY_EXTERN extern "C"
// ========================================================
// GLProxy utilities:
// ========================================================
namespace GLProxy
{
static std::string numToString(std::uint64_t num)
{
char tempString[128];
std::snprintf(tempString, sizeof(tempString), "%-10llu", num);
return tempString;
}
static std::string ptrToString(const void * ptr)
{
char tempString[128];
#if defined(_M_IX86)
std::snprintf(tempString, sizeof(tempString), "0x%08X",
reinterpret_cast<std::uintptr_t>(ptr));
#elif defined(_M_X64)
std::snprintf(tempString, sizeof(tempString), "0x%016llX",
reinterpret_cast<std::uintptr_t>(ptr));
#endif // x86/64
return tempString;
}
static std::string getTimeString()
{
const std::time_t rawTime = std::time(nullptr);
std::string ts;
#ifdef _MSC_VER
// Visual Studio dislikes the static buffer of std::ctime.
char tempString[256] = {'\0'};
ctime_s(tempString, sizeof(tempString), &rawTime);
ts = tempString;
#else // !_MSC_VER
ts = std::ctime(&rawTime);
#endif // _MSC_VER
ts.pop_back(); // Remove the default '\n' added by ctime.
return ts;
}
static std::ofstream & getLogStream()
{
static std::ofstream theLog("opengl_proxy.log");
return theLog;
}
static std::string lastWinErrorAsString()
{
// Adapted from this SO thread:
// http://stackoverflow.com/a/17387176/1198654
DWORD errorMessageID = GetLastError();
if (errorMessageID == 0)
{
return "Unknown error";
}
LPSTR messageBuffer = nullptr;
constexpr DWORD fmtFlags = FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS;
const auto size = FormatMessageA(fmtFlags, nullptr, errorMessageID,
MAKELANGID(LANG_NEUTRAL, SUBLANG_SYS_DEFAULT),
(LPSTR)&messageBuffer, 0, nullptr);
const std::string message{ messageBuffer, size };
LocalFree(messageBuffer);
return message + "(error " + std::to_string(errorMessageID) + ")";
}
static std::string getRealGLLibPath()
{
char defaultGLLibName[1024] = {'\0'};
GetSystemDirectoryA(defaultGLLibName, sizeof(defaultGLLibName));
std::string result;
if (defaultGLLibName[0] != '\0')
{
result += defaultGLLibName;
result += "\\opengl32.dll";
}
else // Something wrong... Try a hardcoded path...
{
result = "C:\\windows\\system32\\opengl32.dll";
}
return result;
}
static HMODULE getSelfModuleHandle()
{
//
// This is somewhat hackish, but should work.
// We try to get this module's address from the address
// of one of its functions, this very function actually.
// Worst case it fails and we return null.
//
// There's also the '__ImageBase' hack, but that seems even more precarious...
// http://stackoverflow.com/a/6924293/1198654
//
HMODULE selfHMod = nullptr;
GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS |
GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
(LPCSTR)&getSelfModuleHandle,
&selfHMod);
return selfHMod;
}
DECLSPEC_NORETURN static void fatalError(const std::string & message)
{
MessageBoxA(nullptr, message.c_str(), "GLProxy Fatal Error", MB_OK | MB_ICONERROR);
GLPROXY_LOG("Fatal error: " << message);
getLogStream().flush();
std::exit(EXIT_FAILURE);
}
// ========================================================
// class OpenGLDll:
// Simple helper class to manage loading the real OpenGL
// Dynamic Library and fetching function pointers from it.
// ========================================================
class OpenGLDll final
{
HMODULE dllHandle;
std::string dllFilePath;
public:
// Not copyable.
OpenGLDll(const OpenGLDll &) = delete;
OpenGLDll & operator = (const OpenGLDll &) = delete;
OpenGLDll()
: dllHandle{ nullptr }
{
load();
}
~OpenGLDll()
{
unload();
}
void load()
{
if (isLoaded())
{
fatalError("Real OpenGL DLL is already loaded!");
}
const auto glDllFilePath = getRealGLLibPath();
GLPROXY_LOG("Trying to load real opengl32.dll from \"" << glDllFilePath << "\"...");
dllHandle = LoadLibraryExA(glDllFilePath.c_str(), nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32);
if (dllHandle == nullptr)
{
fatalError("GLProxy unable to load the real OpenGL DLL!\n" + lastWinErrorAsString());
}
const auto selfHMod = getSelfModuleHandle();
if (dllHandle == selfHMod)
{
fatalError("GLProxy trying to load itself as the real opengl32.dll!");
}
char tempString[1024] = {'\0'};
if (GetModuleFileNameA(dllHandle, tempString, sizeof(tempString)) == 0)
{
GLPROXY_LOG("Unable to get Real OpenGL DLL file path!");
}
else
{
dllFilePath = tempString;
}
GLPROXY_LOG("\n--------------------------------------------------------");
GLPROXY_LOG(" Real OpenGL DLL is loaded!");
GLPROXY_LOG(" OpenGL = " + ptrToString(dllHandle) + ", GLProxy = " + ptrToString(selfHMod));
GLPROXY_LOG(" opengl32.dll path: \"" + dllFilePath + "\"");
GLPROXY_LOG("--------------------------------------------------------\n");
}
void unload()
{
if (isLoaded())
{
FreeLibrary(dllHandle);
dllHandle = nullptr;
dllFilePath.clear();
}
}
bool isLoaded() const
{
return dllHandle != nullptr;
}
void * getFuncPtr(const char * funcName) const
{
if (!isLoaded())
{
GLPROXY_LOG("Error! Real opengl32.dll not loaded. Can't get function " << funcName);
return nullptr;
}
auto fptr = GetProcAddress(dllHandle, funcName);
if (fptr == nullptr)
{
GLPROXY_LOG("Error! Unable to find " << funcName);
}
return reinterpret_cast<void *>(fptr);
}
// Just one instance per process.
// Also only attempt to load the DLL on the first reference.
static OpenGLDll & getInstance()
{
static OpenGLDll glDll;
return glDll;
}
};
static void * getRealGLFunc(const char * funcName)
{
auto & glDll = OpenGLDll::getInstance();
void * addr = glDll.getFuncPtr(funcName);
GLPROXY_LOG("Loading real GL func: (" << ptrToString(addr) << ") " << funcName);
return addr;
}
// ========================================================
// GL function pointers database:
// ========================================================
//
// Registry for the real functions from the GL DLL.
//
struct GLFuncBase
{
std::uint64_t callCount; // Times called during program lifetime.
const char * name; // Pointer to static string. OGL function name, like "glEnable".
const GLFuncBase * next; // Pointer to next static instance in the global list.
};
// Linked list of TGLFuncs, pointing to the actual OpenGL DLL methods.
static GLFuncBase * g_RealGLFunctions = nullptr;
//
// Each function requires a different signature...
// These are always declared as static instances.
//
template<class RetType, class... ParamTypes>
struct TGLFunc : GLFuncBase
{
typedef RetType (GLPROXY_DECL * PtrType)(ParamTypes...);
PtrType funcPtr; // Pointer to a GL function inside the actual OpenGL DLL.
TGLFunc(const char * funcName)
{
callCount = 0;
name = funcName;
funcPtr = reinterpret_cast<PtrType>(getRealGLFunc(funcName));
// Link to the global list:
this->next = g_RealGLFunctions;
g_RealGLFunctions = this;
}
};
// Shorthand macros to simplify the TGLFunc<> declarations:
#define TGLFUNC_NAME(funcName) STRING_JOIN2(_real_, funcName)
#define TGLFUNC_DECL(funcName) TGLFUNC_NAME(funcName){ STRINGIZE(funcName) }
#define TGLFUNC_CALL(funcName, ...) (TGLFUNC_NAME(funcName).callCount++, TGLFUNC_NAME(funcName).funcPtr(__VA_ARGS__))
// ========================================================
// struct AutoReport:
// Writes a report with the OpenGL function call counts.
// ========================================================
struct AutoReport
{
AutoReport()
{
GLPROXY_LOG("\n--------------------------------------------------------");
GLPROXY_LOG(" OPENGL32.DLL proxy report - " << getTimeString());
GLPROXY_LOG("--------------------------------------------------------\n");
}
~AutoReport()
{
// Gather all function pointers first so we can sort them by call count.
std::vector<const GLFuncBase *> sortedFuncs;
for (const GLFuncBase * func = g_RealGLFunctions; func; func = func->next)
{
sortedFuncs.push_back(func);
}
// Higher call counts first. If same call count then sort alphabetically by name.
std::sort(std::begin(sortedFuncs), std::end(sortedFuncs),
[](const GLFuncBase * a, const GLFuncBase * b) -> bool
{
if (a->callCount == b->callCount)
{
return std::strcmp(a->name, b->name) < 0;
}
else
{
return a->callCount > b->callCount;
}
});
GLPROXY_LOG("--------------------------------------------------------");
GLPROXY_LOG(" Function call counts:");
GLPROXY_LOG("--------------------------------------------------------\n");
for (const GLFuncBase * func : sortedFuncs)
{
GLPROXY_LOG(numToString(func->callCount) << " " << func->name);
}
GLPROXY_LOG("\n" << sortedFuncs.size() << " GL functions were called by the application.");
}
};
// This static instance will open the GLProxy log on startup and
// write the function call counts on shutdown via its destructor.
static AutoReport g_AutoReport;
} // namespace GLProxy {}
// ========================================================
// DllMain:
// Note: Threads are not supported.
// Probably a non issue, since OpenGL is single-threaded.
// ========================================================
BOOL WINAPI DllMain(HINSTANCE /* hInstDll */, DWORD reasonForDllLoad, LPVOID /* reserved */)
{
switch (reasonForDllLoad)
{
case DLL_PROCESS_ATTACH :
GLPROXY_LOG("\nDllMain: DLL_PROCESS_ATTACH\n");
break;
case DLL_PROCESS_DETACH :
GLPROXY_LOG("\nDllMain: DLL_PROCESS_DETACH\n");
break;
default :
break;
} // switch (reasonForDllLoad)
return TRUE;
}
// ================================================================================================
// These macros simplify declaring our wrapper functions:
// ================================================================================================
//
// Functions with a return value:
//
#define GLFUNC_0_WRET(retType, funcName) \
GLPROXY_EXTERN retType GLPROXY_DECL funcName(void) \
{ \
static GLProxy::TGLFunc<retType> TGLFUNC_DECL(funcName); \
return TGLFUNC_CALL(funcName); \
}
#define GLFUNC_1_WRET(retType, funcName, t0, p0) \
GLPROXY_EXTERN retType GLPROXY_DECL funcName(t0 p0) \
{ \
static GLProxy::TGLFunc<retType, t0> TGLFUNC_DECL(funcName); \
return TGLFUNC_CALL(funcName, p0); \
}
#define GLFUNC_2_WRET(retType, funcName, t0, p0, t1, p1) \
GLPROXY_EXTERN retType GLPROXY_DECL funcName(t0 p0, t1 p1) \
{ \
static GLProxy::TGLFunc<retType, t0, t1> TGLFUNC_DECL(funcName); \
return TGLFUNC_CALL(funcName, p0, p1); \
}
#define GLFUNC_3_WRET(retType, funcName, t0, p0, t1, p1, t2, p2) \
GLPROXY_EXTERN retType GLPROXY_DECL funcName(t0 p0, t1 p1, t2 p2) \
{ \
static GLProxy::TGLFunc<retType, t0, t1, t2> TGLFUNC_DECL(funcName); \
return TGLFUNC_CALL(funcName, p0, p1, p2); \
}
#define GLFUNC_4_WRET(retType, funcName, t0, p0, t1, p1, t2, p2, t3, p3) \
GLPROXY_EXTERN retType GLPROXY_DECL funcName(t0 p0, t1 p1, t2 p2, t3 p3) \
{ \
static GLProxy::TGLFunc<retType, t0, t1, t2, t3> TGLFUNC_DECL(funcName); \
return TGLFUNC_CALL(funcName, p0, p1, p2, p3); \
}
#define GLFUNC_5_WRET(retType, funcName, t0, p0, t1, p1, t2, p2, t3, p3, t4, p4) \
GLPROXY_EXTERN retType GLPROXY_DECL funcName(t0 p0, t1 p1, t2 p2, t3 p3, t4 p4) \
{ \
static GLProxy::TGLFunc<retType, t0, t1, t2, t3, t4> TGLFUNC_DECL(funcName); \
return TGLFUNC_CALL(funcName, p0, p1, p2, p3, p4); \
}
#define GLFUNC_8_WRET(retType, funcName, t0, p0, t1, p1, t2, p2, t3, p3, t4, p4, t5, p5, t6, p6, t7, p7) \
GLPROXY_EXTERN retType GLPROXY_DECL funcName(t0 p0, t1 p1, t2 p2, t3 p3, t4 p4, t5 p5, t6 p6, t7 p7) \
{ \
static GLProxy::TGLFunc<retType, t0, t1, t2, t3, t4, t5, t6, t7> TGLFUNC_DECL(funcName); \
return TGLFUNC_CALL(funcName, p0, p1, p2, p3, p4, p5, p6, p7); \
}
//
// Functions returning void/nothing:
//
#define GLFUNC_0(funcName) \
GLPROXY_EXTERN void GLPROXY_DECL funcName(void) \
{ \
static GLProxy::TGLFunc<void> TGLFUNC_DECL(funcName); \
TGLFUNC_CALL(funcName); \
}
#define GLFUNC_1(funcName, t0, p0) \
GLPROXY_EXTERN void GLPROXY_DECL funcName(t0 p0) \
{ \
static GLProxy::TGLFunc<void, t0> TGLFUNC_DECL(funcName); \
TGLFUNC_CALL(funcName, p0); \
}
#define GLFUNC_2(funcName, t0, p0, t1, p1) \
GLPROXY_EXTERN void GLPROXY_DECL funcName(t0 p0, t1 p1) \
{ \
static GLProxy::TGLFunc<void, t0, t1> TGLFUNC_DECL(funcName); \
TGLFUNC_CALL(funcName, p0, p1); \
}
#define GLFUNC_3(funcName, t0, p0, t1, p1, t2, p2) \
GLPROXY_EXTERN void GLPROXY_DECL funcName(t0 p0, t1 p1, t2 p2) \
{ \
static GLProxy::TGLFunc<void, t0, t1, t2> TGLFUNC_DECL(funcName); \
TGLFUNC_CALL(funcName, p0, p1, p2); \
}
#define GLFUNC_4(funcName, t0, p0, t1, p1, t2, p2, t3, p3) \
GLPROXY_EXTERN void GLPROXY_DECL funcName(t0 p0, t1 p1, t2 p2, t3 p3) \
{ \
static GLProxy::TGLFunc<void, t0, t1, t2, t3> TGLFUNC_DECL(funcName); \
TGLFUNC_CALL(funcName, p0, p1, p2, p3); \
}
#define GLFUNC_5(funcName, t0, p0, t1, p1, t2, p2, t3, p3, t4, p4) \
GLPROXY_EXTERN void GLPROXY_DECL funcName(t0 p0, t1 p1, t2 p2, t3 p3, t4 p4) \
{ \
static GLProxy::TGLFunc<void, t0, t1, t2, t3, t4> TGLFUNC_DECL(funcName); \
TGLFUNC_CALL(funcName, p0, p1, p2, p3, p4); \
}
#define GLFUNC_6(funcName, t0, p0, t1, p1, t2, p2, t3, p3, t4, p4, t5, p5) \
GLPROXY_EXTERN void GLPROXY_DECL funcName(t0 p0, t1 p1, t2 p2, t3 p3, t4 p4, t5 p5) \
{ \
static GLProxy::TGLFunc<void, t0, t1, t2, t3, t4, t5> TGLFUNC_DECL(funcName); \
TGLFUNC_CALL(funcName, p0, p1, p2, p3, p4, p5); \
}
#define GLFUNC_7(funcName, t0, p0, t1, p1, t2, p2, t3, p3, t4, p4, t5, p5, t6, p6) \
GLPROXY_EXTERN void GLPROXY_DECL funcName(t0 p0, t1 p1, t2 p2, t3 p3, t4 p4, t5 p5, t6 p6) \
{ \
static GLProxy::TGLFunc<void, t0, t1, t2, t3, t4, t5, t6> TGLFUNC_DECL(funcName); \
TGLFUNC_CALL(funcName, p0, p1, p2, p3, p4, p5, p6); \
}
#define GLFUNC_8(funcName, t0, p0, t1, p1, t2, p2, t3, p3, t4, p4, t5, p5, t6, p6, t7, p7) \
GLPROXY_EXTERN void GLPROXY_DECL funcName(t0 p0, t1 p1, t2 p2, t3 p3, t4 p4, t5 p5, t6 p6, t7 p7) \
{ \
static GLProxy::TGLFunc<void, t0, t1, t2, t3, t4, t5, t6, t7> TGLFUNC_DECL(funcName); \
TGLFUNC_CALL(funcName, p0, p1, p2, p3, p4, p5, p6, p7); \
}
#define GLFUNC_9(funcName, t0, p0, t1, p1, t2, p2, t3, p3, t4, p4, t5, p5, t6, p6, t7, p7, t8, p8) \
GLPROXY_EXTERN void GLPROXY_DECL funcName(t0 p0, t1 p1, t2 p2, t3 p3, t4 p4, t5 p5, t6 p6, t7 p7, t8 p8) \
{ \
static GLProxy::TGLFunc<void, t0, t1, t2, t3, t4, t5, t6, t7, t8> TGLFUNC_DECL(funcName); \
TGLFUNC_CALL(funcName, p0, p1, p2, p3, p4, p5, p6, p7, p8); \
}
#define GLFUNC_10(funcName, t0, p0, t1, p1, t2, p2, t3, p3, t4, p4, t5, p5, t6, p6, t7, p7, t8, p8, t9, p9) \
GLPROXY_EXTERN void GLPROXY_DECL funcName(t0 p0, t1 p1, t2 p2, t3 p3, t4 p4, t5 p5, t6 p6, t7 p7, t8 p8, t9 p9) \
{ \
static GLProxy::TGLFunc<void, t0, t1, t2, t3, t4, t5, t6, t7, t8, t9> TGLFUNC_DECL(funcName); \
TGLFUNC_CALL(funcName, p0, p1, p2, p3, p4, p5, p6, p7, p8, p9); \
}
// ================================================================================================
// "Classic OpenGL" and WGL wrappers:
// ================================================================================================
//
// Standard OpenGL data types.
//
// We don't include gl.h to avoid conflicting definitions, so these
// types are defined here in the same way they would be by gl.h.
//
#ifdef GLPROXY_NEED_OGL_TYPES
typedef double GLclampd;
typedef double GLdouble;
typedef float GLclampf;
typedef float GLfloat;
typedef int GLint;
typedef int GLsizei;
typedef short GLshort;
typedef signed char GLbyte;
typedef unsigned char GLboolean;
typedef unsigned char GLubyte;
typedef unsigned int GLbitfield;
typedef unsigned int GLenum;
typedef unsigned int GLuint;
typedef unsigned short GLushort;
#endif // GLPROXY_NEED_OGL_TYPES
//
// WGL structures.
//
// They are defined here because including WinGDI.h would produce
// warnings or even errors about our redefined WGL function proxies.
//
#ifdef GLPROXY_NEED_WGL_STRUCTS
struct PIXELFORMATDESCRIPTOR
{
WORD nSize;
WORD nVersion;
DWORD dwFlags;
BYTE iPixelType;
BYTE cColorBits;
BYTE cRedBits;
BYTE cRedShift;
BYTE cGreenBits;
BYTE cGreenShift;
BYTE cBlueBits;
BYTE cBlueShift;
BYTE cAlphaBits;
BYTE cAlphaShift;
BYTE cAccumBits;
BYTE cAccumRedBits;
BYTE cAccumGreenBits;
BYTE cAccumBlueBits;
BYTE cAccumAlphaBits;
BYTE cDepthBits;
BYTE cStencilBits;
BYTE cAuxBuffers;
BYTE iLayerType;
BYTE bReserved;
DWORD dwLayerMask;
DWORD dwVisibleMask;
DWORD dwDamageMask;
};
struct LAYERPLANEDESCRIPTOR
{
WORD nSize;
WORD nVersion;
DWORD dwFlags;
BYTE iPixelType;
BYTE cColorBits;
BYTE cRedBits;
BYTE cRedShift;
BYTE cGreenBits;
BYTE cGreenShift;
BYTE cBlueBits;
BYTE cBlueShift;
BYTE cAlphaBits;
BYTE cAlphaShift;
BYTE cAccumBits;
BYTE cAccumRedBits;
BYTE cAccumGreenBits;
BYTE cAccumBlueBits;
BYTE cAccumAlphaBits;
BYTE cDepthBits;
BYTE cStencilBits;
BYTE cAuxBuffers;
BYTE iLayerPlane;
BYTE bReserved;
COLORREF crTransparent;
};
struct GLYPHMETRICSFLOAT
{
float gmfBlackBoxX;
float gmfBlackBoxY;
struct
{
float x;
float y;
} gmfptGlyphOrigin;
float gmfCellIncX;
float gmfCellIncY;
};
struct WGLSWAP
{
HDC hdc;
UINT flags;
};
#endif // GLPROXY_NEED_WGL_STRUCTS
//
// WGL functions:
//
GLFUNC_0_WRET(HDC, wglGetCurrentDC);
GLFUNC_0_WRET(HGLRC, wglGetCurrentContext);
GLFUNC_1_WRET(BOOL, wglDeleteContext, HGLRC, hglrc);
GLFUNC_1_WRET(BOOL, wglSwapBuffers, HDC, hdc);
GLFUNC_1_WRET(HGLRC, wglCreateContext, HDC, hdc);
GLFUNC_1_WRET(int, wglGetPixelFormat, HDC, hdc);
GLFUNC_2_WRET(BOOL, wglMakeCurrent, HDC, hdc, HGLRC, hglrc);
GLFUNC_2_WRET(BOOL, wglShareLists, HGLRC, hglrc1, HGLRC, hglrc2);
GLFUNC_2_WRET(BOOL, wglSwapLayerBuffers, HDC, hdc, UINT, flags);
GLFUNC_2_WRET(DWORD, wglSwapMultipleBuffers, UINT, n, const WGLSWAP *, sw);
GLFUNC_2_WRET(HGLRC, wglCreateLayerContext, HDC, hdc, int, b);
GLFUNC_2_WRET(int, wglChoosePixelFormat, HDC, hdc, const PIXELFORMATDESCRIPTOR *, pfd);
GLFUNC_3_WRET(BOOL, wglCopyContext, HGLRC, hglrc1, HGLRC, hglrc2, UINT, flags);
GLFUNC_3_WRET(BOOL, wglRealizeLayerPalette, HDC, hdc, int, b, BOOL, c);
GLFUNC_3_WRET(BOOL, wglSetPixelFormat, HDC, hdc, int, b, const PIXELFORMATDESCRIPTOR *, pfd);
GLFUNC_4_WRET(BOOL, wglUseFontBitmapsA, HDC, hdc, DWORD, b, DWORD, c, DWORD, d);
GLFUNC_4_WRET(BOOL, wglUseFontBitmapsW, HDC, hdc, DWORD, b, DWORD, c, DWORD, d);
GLFUNC_4_WRET(int, wglDescribePixelFormat, HDC, hdc, int, b, UINT, c, PIXELFORMATDESCRIPTOR *, pfd);
GLFUNC_5_WRET(BOOL, wglDescribeLayerPlane, HDC, hdc, int, b, int, c, UINT, d, LAYERPLANEDESCRIPTOR *, lpd);
GLFUNC_5_WRET(int, wglGetLayerPaletteEntries, HDC, hdc, int, b, int, c, int, d, COLORREF *, e);
GLFUNC_5_WRET(int, wglSetLayerPaletteEntries, HDC, hdc, int, b, int, c, int, d, const COLORREF *, e);
GLFUNC_8_WRET(BOOL, wglUseFontOutlinesA, HDC, hdc, DWORD, b, DWORD, c, DWORD, d, float, e, float, f, int, g, GLYPHMETRICSFLOAT *, gmf);
GLFUNC_8_WRET(BOOL, wglUseFontOutlinesW, HDC, hdc, DWORD, b, DWORD, c, DWORD, d, float, e, float, f, int, g, GLYPHMETRICSFLOAT *, gmf);
//
// wglGetProcAddress is a special case. We also want to log
// which extensions got dynamically loaded by the application.
//
GLPROXY_EXTERN PROC GLPROXY_DECL wglGetProcAddress(LPCSTR funcName)
{
static GLProxy::TGLFunc<PROC, LPCSTR> TGLFUNC_DECL(wglGetProcAddress);
GLPROXY_LOG("wglGetProcAddress('" << funcName << "')");
return TGLFUNC_CALL(wglGetProcAddress, funcName);
}
// This is an undocummented function, it seems. So it is probably not called by most applications...
GLPROXY_EXTERN PROC GLPROXY_DECL wglGetDefaultProcAddress(LPCSTR funcName)
{
static GLProxy::TGLFunc<PROC, LPCSTR> TGLFUNC_DECL(wglGetDefaultProcAddress);
GLPROXY_LOG("wglGetDefaultProcAddress('" << funcName << "')");
return TGLFUNC_CALL(wglGetDefaultProcAddress, funcName);
}
//
// GL Functions with a return value:
//
GLFUNC_0_WRET(GLenum, glGetError);
GLFUNC_1_WRET(GLboolean, glIsEnabled, GLenum, cap);
GLFUNC_1_WRET(GLboolean, glIsList, GLuint, list);
GLFUNC_1_WRET(GLboolean, glIsTexture, GLuint, texture);
GLFUNC_1_WRET(GLint, glRenderMode, GLenum, mode);
GLFUNC_1_WRET(GLuint, glGenLists, GLsizei, range);
GLFUNC_1_WRET(const GLubyte *, glGetString, GLenum, name);
GLFUNC_3_WRET(GLboolean, glAreTexturesResident, GLsizei, n, const GLuint *, textures, GLboolean *, residences);
//
// GL Functions returning void:
//
GLFUNC_0(glEnd);
GLFUNC_0(glEndList);
GLFUNC_0(glFinish);
GLFUNC_0(glFlush);
GLFUNC_0(glInitNames);
GLFUNC_0(glLoadIdentity);
GLFUNC_0(glPopAttrib);
GLFUNC_0(glPopClientAttrib);
GLFUNC_0(glPopMatrix);
GLFUNC_0(glPopName);
GLFUNC_0(glPushMatrix)
GLFUNC_1(glArrayElement, GLint, i);
GLFUNC_1(glBegin, GLenum, mode);
GLFUNC_1(glCallList, GLuint, list);
GLFUNC_1(glClear, GLbitfield, mask);
GLFUNC_1(glClearDepth, GLclampd, depth);
GLFUNC_1(glClearIndex, GLfloat, c);
GLFUNC_1(glClearStencil, GLint, s);
GLFUNC_1(glColor3bv, const GLbyte *, v);
GLFUNC_1(glColor3dv, const GLdouble *, v);
GLFUNC_1(glColor3fv, const GLfloat *, v);
GLFUNC_1(glColor3iv, const GLint *, v);
GLFUNC_1(glColor3sv, const GLshort *, v);
GLFUNC_1(glColor3ubv, const GLubyte *, v);
GLFUNC_1(glColor3uiv, const GLuint *, v);
GLFUNC_1(glColor3usv, const GLushort *, v);
GLFUNC_1(glColor4bv, const GLbyte *, v);
GLFUNC_1(glColor4dv, const GLdouble *, v);
GLFUNC_1(glColor4fv, const GLfloat *, v);
GLFUNC_1(glColor4iv, const GLint *, v);
GLFUNC_1(glColor4sv, const GLshort *, v);
GLFUNC_1(glColor4ubv, const GLubyte *, v);
GLFUNC_1(glColor4uiv, const GLuint *, v);
GLFUNC_1(glColor4usv, const GLushort *, v);
GLFUNC_1(glCullFace, GLenum, mode);
GLFUNC_1(glDepthFunc, GLenum, func);
GLFUNC_1(glDepthMask, GLboolean, flag);
GLFUNC_1(glDisable, GLenum, cap);
GLFUNC_1(glDisableClientState, GLenum, array);
GLFUNC_1(glDrawBuffer, GLenum, mode);
GLFUNC_1(glEdgeFlag, GLboolean, flag);
GLFUNC_1(glEdgeFlagv, const GLboolean *, flag);
GLFUNC_1(glEnable, GLenum, cap);
GLFUNC_1(glEnableClientState, GLenum, array);
GLFUNC_1(glEvalCoord1d, GLdouble, u);
GLFUNC_1(glEvalCoord1dv, const GLdouble *, u);
GLFUNC_1(glEvalCoord1f, GLfloat, u);
GLFUNC_1(glEvalCoord1fv, const GLfloat *, u);
GLFUNC_1(glEvalCoord2dv, const GLdouble *, u);
GLFUNC_1(glEvalCoord2fv, const GLfloat *, u);
GLFUNC_1(glEvalPoint1, GLint, i);
GLFUNC_1(glFrontFace, GLenum, mode);
GLFUNC_1(glGetPolygonStipple, GLubyte *, mask);
GLFUNC_1(glIndexMask, GLuint, mask);
GLFUNC_1(glIndexd, GLdouble, c);
GLFUNC_1(glIndexdv, const GLdouble *, c);
GLFUNC_1(glIndexf, GLfloat, c);
GLFUNC_1(glIndexfv, const GLfloat *, c);
GLFUNC_1(glIndexi, GLint, c);
GLFUNC_1(glIndexiv, const GLint *, c);
GLFUNC_1(glIndexs, GLshort, c);
GLFUNC_1(glIndexsv, const GLshort *, c);
GLFUNC_1(glIndexub, GLubyte, c);
GLFUNC_1(glIndexubv, const GLubyte *, c);
GLFUNC_1(glLineWidth, GLfloat, width);
GLFUNC_1(glListBase, GLuint, base);
GLFUNC_1(glLoadMatrixd, const GLdouble *, m);
GLFUNC_1(glLoadMatrixf, const GLfloat *, m);
GLFUNC_1(glLoadName, GLuint, name);
GLFUNC_1(glLogicOp, GLenum, opcode);
GLFUNC_1(glMatrixMode, GLenum, mode);
GLFUNC_1(glMultMatrixd, const GLdouble *, m);
GLFUNC_1(glMultMatrixf, const GLfloat *, m);
GLFUNC_1(glNormal3bv, const GLbyte *, v);
GLFUNC_1(glNormal3dv, const GLdouble *, v);
GLFUNC_1(glNormal3fv, const GLfloat *, v);
GLFUNC_1(glNormal3iv, const GLint *, v);
GLFUNC_1(glNormal3sv, const GLshort *, v);
GLFUNC_1(glPassThrough, GLfloat, token);
GLFUNC_1(glPointSize, GLfloat, size);
GLFUNC_1(glPolygonStipple, const GLubyte *, mask);
GLFUNC_1(glPushAttrib, GLbitfield, mask);
GLFUNC_1(glPushClientAttrib, GLbitfield, mask);
GLFUNC_1(glPushName, GLuint, name);
GLFUNC_1(glRasterPos2dv, const GLdouble *, v);
GLFUNC_1(glRasterPos2fv, const GLfloat *, v);
GLFUNC_1(glRasterPos2iv, const GLint *, v);
GLFUNC_1(glRasterPos2sv, const GLshort *, v);
GLFUNC_1(glRasterPos3dv, const GLdouble *, v);
GLFUNC_1(glRasterPos3fv, const GLfloat *, v);
GLFUNC_1(glRasterPos3iv, const GLint *, v);
GLFUNC_1(glRasterPos3sv, const GLshort *, v);
GLFUNC_1(glRasterPos4dv, const GLdouble *, v);
GLFUNC_1(glRasterPos4fv, const GLfloat *, v);
GLFUNC_1(glRasterPos4iv, const GLint *, v);
GLFUNC_1(glRasterPos4sv, const GLshort *, v);
GLFUNC_1(glReadBuffer, GLenum, mode);
GLFUNC_1(glShadeModel, GLenum, mode);
GLFUNC_1(glStencilMask, GLuint, mask);
GLFUNC_1(glTexCoord1d, GLdouble, s);
GLFUNC_1(glTexCoord1dv, const GLdouble *, v);
GLFUNC_1(glTexCoord1f, GLfloat, s);
GLFUNC_1(glTexCoord1fv, const GLfloat *, v);
GLFUNC_1(glTexCoord1i, GLint, s);
GLFUNC_1(glTexCoord1iv, const GLint *, v);
GLFUNC_1(glTexCoord1s, GLshort, s);
GLFUNC_1(glTexCoord1sv, const GLshort *, v);
GLFUNC_1(glTexCoord2dv, const GLdouble *, v);
GLFUNC_1(glTexCoord2fv, const GLfloat *, v);
GLFUNC_1(glTexCoord2iv, const GLint *, v);
GLFUNC_1(glTexCoord2sv, const GLshort *, v);
GLFUNC_1(glTexCoord3dv, const GLdouble *, v);
GLFUNC_1(glTexCoord3fv, const GLfloat *, v);
GLFUNC_1(glTexCoord3iv, const GLint *, v);
GLFUNC_1(glTexCoord3sv, const GLshort *, v);
GLFUNC_1(glTexCoord4dv, const GLdouble *, v);
GLFUNC_1(glTexCoord4fv, const GLfloat *, v);
GLFUNC_1(glTexCoord4iv, const GLint *, v);
GLFUNC_1(glTexCoord4sv, const GLshort *, v);
GLFUNC_1(glVertex2dv, const GLdouble *, v);
GLFUNC_1(glVertex2fv, const GLfloat *, v);
GLFUNC_1(glVertex2iv, const GLint *, v);
GLFUNC_1(glVertex2sv, const GLshort *, v);
GLFUNC_1(glVertex3dv, const GLdouble *, v);
GLFUNC_1(glVertex3fv, const GLfloat *, v);
GLFUNC_1(glVertex3iv, const GLint *, v);
GLFUNC_1(glVertex3sv, const GLshort *, v);
GLFUNC_1(glVertex4dv, const GLdouble *, v);
GLFUNC_1(glVertex4fv, const GLfloat *, v);
GLFUNC_1(glVertex4iv, const GLint *, v);
GLFUNC_1(glVertex4sv, const GLshort *, v);
GLFUNC_2(glAccum, GLenum, op, GLfloat, value);
GLFUNC_2(glAlphaFunc, GLenum, func, GLclampf, ref);
GLFUNC_2(glBindTexture, GLenum, target, GLuint, texture);
GLFUNC_2(glBlendFunc, GLenum, sfactor, GLenum, dfactor);
GLFUNC_2(glClipPlane, GLenum, plane, const GLdouble *, equation);
GLFUNC_3(glColor3b, GLbyte, red, GLbyte, green, GLbyte, blue);
GLFUNC_2(glColorMaterial, GLenum, face, GLenum, mode);
GLFUNC_2(glDeleteLists, GLuint, list, GLsizei, range);
GLFUNC_2(glDeleteTextures, GLsizei, n, const GLuint *, textures);
GLFUNC_2(glDepthRange, GLclampd, zNear, GLclampd, zFar);
GLFUNC_2(glEdgeFlagPointer, GLsizei, stride, const void *, pointer);
GLFUNC_2(glEvalCoord2d, GLdouble, u, GLdouble, v);
GLFUNC_2(glEvalCoord2f, GLfloat, u, GLfloat, v);
GLFUNC_2(glEvalPoint2, GLint, i, GLint, j);
GLFUNC_2(glFogf, GLenum, pname, GLfloat, param);
GLFUNC_2(glFogfv, GLenum, pname, const GLfloat *, params);
GLFUNC_2(glFogi, GLenum, pname, GLint, param);
GLFUNC_2(glFogiv, GLenum, pname, const GLint *, params);
GLFUNC_2(glGenTextures, GLsizei, n, GLuint *, textures);
GLFUNC_2(glGetBooleanv, GLenum, pname, GLboolean *, params);
GLFUNC_2(glGetClipPlane, GLenum, plane, GLdouble *, equation);
GLFUNC_2(glGetDoublev, GLenum, pname, GLdouble *, params);
GLFUNC_2(glGetFloatv, GLenum, pname, GLfloat *, params);
GLFUNC_2(glGetIntegerv, GLenum, pname, GLint *, params);
GLFUNC_2(glGetPixelMapfv, GLenum, map, GLfloat *, values);
GLFUNC_2(glGetPixelMapuiv, GLenum, map, GLuint *, values);
GLFUNC_2(glGetPixelMapusv, GLenum, map, GLushort *, values);
GLFUNC_2(glGetPointerv, GLenum, pname, void **, params);
GLFUNC_2(glHint, GLenum, target, GLenum, mode);
GLFUNC_2(glLightModelf, GLenum, pname, GLfloat, param);
GLFUNC_2(glLightModelfv, GLenum, pname, const GLfloat *, params);
GLFUNC_2(glLightModeli, GLenum, pname, GLint, param);
GLFUNC_2(glLightModeliv, GLenum, pname, const GLint *, params);
GLFUNC_2(glLineStipple, GLint, factor, GLushort, pattern);
GLFUNC_2(glNewList, GLuint, list, GLenum, mode);
GLFUNC_2(glPixelStoref, GLenum, pname, GLfloat, param);
GLFUNC_2(glPixelStorei, GLenum, pname, GLint, param);
GLFUNC_2(glPixelTransferf, GLenum, pname, GLfloat, param);
GLFUNC_2(glPixelTransferi, GLenum, pname, GLint, param);
GLFUNC_2(glPixelZoom, GLfloat, xfactor, GLfloat, yfactor);
GLFUNC_2(glPolygonMode, GLenum, face, GLenum, mode);
GLFUNC_2(glPolygonOffset, GLfloat, factor, GLfloat, units);
GLFUNC_2(glRasterPos2d, GLdouble, x, GLdouble, y);
GLFUNC_2(glRasterPos2f, GLfloat, x, GLfloat, y);
GLFUNC_2(glRasterPos2i, GLint, x, GLint, y);
GLFUNC_2(glRasterPos2s, GLshort, x, GLshort, y);
GLFUNC_3(glRasterPos3i, GLint, x, GLint, y, GLint, z);
GLFUNC_2(glRectdv, const GLdouble *, v1, const GLdouble *, v2);
GLFUNC_2(glRectfv, const GLfloat *, v1, const GLfloat *, v2);
GLFUNC_2(glRectiv, const GLint *, v1, const GLint *, v2);
GLFUNC_2(glRectsv, const GLshort *, v1, const GLshort *, v2);
GLFUNC_2(glSelectBuffer, GLsizei, size, GLuint *, buffer);
GLFUNC_2(glTexCoord2d, GLdouble, s, GLdouble, t);
GLFUNC_2(glTexCoord2f, GLfloat, s, GLfloat, t);
GLFUNC_2(glTexCoord2i, GLint, s, GLint, t);
GLFUNC_2(glTexCoord2s, GLshort, s, GLshort, t);
GLFUNC_2(glVertex2d, GLdouble, x, GLdouble, y);
GLFUNC_2(glVertex2f, GLfloat, x, GLfloat, y);
GLFUNC_2(glVertex2i, GLint, x, GLint, y);
GLFUNC_2(glVertex2s, GLshort, x, GLshort, y);
GLFUNC_3(glCallLists, GLsizei, n, GLenum, type, const void *, lists);
GLFUNC_3(glColor3d, GLdouble, red, GLdouble, green, GLdouble, blue);
GLFUNC_3(glColor3f, GLfloat, red, GLfloat, green, GLfloat, blue);
GLFUNC_3(glColor3i, GLint, red, GLint, green, GLint, blue);
GLFUNC_3(glColor3s, GLshort, red, GLshort, green, GLshort, blue);
GLFUNC_3(glColor3ub, GLubyte, red, GLubyte, green, GLubyte, blue);
GLFUNC_3(glColor3ui, GLuint, red, GLuint, green, GLuint, blue);
GLFUNC_3(glColor3us, GLushort, red, GLushort, green, GLushort, blue);
GLFUNC_3(glDrawArrays, GLenum, mode, GLint, first, GLsizei, count);
GLFUNC_3(glEvalMesh1, GLenum, mode, GLint, i1, GLint, i2);
GLFUNC_3(glFeedbackBuffer, GLsizei, size, GLenum, type, GLfloat *, buffer);
GLFUNC_3(glGetLightfv, GLenum, light, GLenum, pname, GLfloat *, params);
GLFUNC_3(glGetLightiv, GLenum, light, GLenum, pname, GLint *, params);
GLFUNC_3(glGetMapdv, GLenum, target, GLenum, query, GLdouble *, v);
GLFUNC_3(glGetMapfv, GLenum, target, GLenum, query, GLfloat *, v);
GLFUNC_3(glGetMapiv, GLenum, target, GLenum, query, GLint *, v);
GLFUNC_3(glGetMaterialfv, GLenum, face, GLenum, pname, GLfloat *, params);
GLFUNC_3(glGetMaterialiv, GLenum, face, GLenum, pname, GLint *, params);
GLFUNC_3(glGetTexEnvfv, GLenum, target, GLenum, pname, GLfloat *, params);
GLFUNC_3(glGetTexEnviv, GLenum, target, GLenum, pname, GLint *, params);
GLFUNC_3(glGetTexGendv, GLenum, coord, GLenum, pname, GLdouble *, params);
GLFUNC_3(glGetTexGenfv, GLenum, coord, GLenum, pname, GLfloat *, params);
GLFUNC_3(glGetTexGeniv, GLenum, coord, GLenum, pname, GLint *, params);
GLFUNC_3(glGetTexParameterfv, GLenum, target, GLenum, pname, GLfloat *, params);
GLFUNC_3(glGetTexParameteriv, GLenum, target, GLenum, pname, GLint *, params);
GLFUNC_3(glIndexPointer, GLenum, type, GLsizei, stride, const void *, pointer);
GLFUNC_3(glInterleavedArrays, GLenum, format, GLsizei, stride, const void *, pointer);
GLFUNC_3(glLightf, GLenum, light, GLenum, pname, GLfloat, param);
GLFUNC_3(glLightfv, GLenum, light, GLenum, pname, const GLfloat *, params);
GLFUNC_3(glLighti, GLenum, light, GLenum, pname, GLint, param);
GLFUNC_3(glLightiv, GLenum, light, GLenum, pname, const GLint *, params);
GLFUNC_3(glMapGrid1d, GLint, un, GLdouble, u1, GLdouble, u2);
GLFUNC_3(glMapGrid1f, GLint, un, GLfloat, u1, GLfloat, u2);
GLFUNC_3(glMaterialf, GLenum, face, GLenum, pname, GLfloat, param);
GLFUNC_3(glMaterialfv, GLenum, face, GLenum, pname, const GLfloat *, params);
GLFUNC_3(glMateriali, GLenum, face, GLenum, pname, GLint, param);
GLFUNC_3(glMaterialiv, GLenum, face, GLenum, pname, const GLint *, params);
GLFUNC_3(glNormal3b, GLbyte, nx, GLbyte, ny, GLbyte, nz);
GLFUNC_3(glNormal3d, GLdouble, nx, GLdouble, ny, GLdouble, nz);
GLFUNC_3(glNormal3f, GLfloat, nx, GLfloat, ny, GLfloat, nz);
GLFUNC_3(glNormal3i, GLint, nx, GLint, ny, GLint, nz);
GLFUNC_3(glNormal3s, GLshort, nx, GLshort, ny, GLshort, nz);
GLFUNC_3(glNormalPointer, GLenum, type, GLsizei, stride, const void *, pointer);
GLFUNC_3(glPixelMapfv, GLenum, map, GLsizei, mapsize, const GLfloat *, values);
GLFUNC_3(glPixelMapuiv, GLenum, map, GLsizei, mapsize, const GLuint *, values);
GLFUNC_3(glPixelMapusv, GLenum, map, GLsizei, mapsize, const GLushort *, values);
GLFUNC_3(glPrioritizeTextures, GLsizei, n, const GLuint *, textures, const GLclampf *, priorities);
GLFUNC_3(glRasterPos3d, GLdouble, x, GLdouble, y, GLdouble, z);
GLFUNC_3(glRasterPos3f, GLfloat, x, GLfloat, y, GLfloat, z);
GLFUNC_3(glRasterPos3s, GLshort, x, GLshort, y, GLshort, z);
GLFUNC_4(glRasterPos4d, GLdouble, x, GLdouble, y, GLdouble, z, GLdouble, w);
GLFUNC_3(glScaled, GLdouble, x, GLdouble, y, GLdouble, z);
GLFUNC_3(glScalef, GLfloat, x, GLfloat, y, GLfloat, z);
GLFUNC_3(glStencilFunc, GLenum, func, GLint, ref, GLuint, mask);
GLFUNC_3(glStencilOp, GLenum, fail, GLenum, zfail, GLenum, zpass);
GLFUNC_3(glTexCoord3d, GLdouble, s, GLdouble, t, GLdouble, r);
GLFUNC_3(glTexCoord3f, GLfloat, s, GLfloat, t, GLfloat, r);
GLFUNC_3(glTexCoord3i, GLint, s, GLint, t, GLint, r);
GLFUNC_3(glTexCoord3s, GLshort, s, GLshort, t, GLshort, r);
GLFUNC_3(glTexEnvf, GLenum, target, GLenum, pname, GLfloat, param);
GLFUNC_3(glTexEnvfv, GLenum, target, GLenum, pname, const GLfloat *, params);
GLFUNC_3(glTexEnvi, GLenum, target, GLenum, pname, GLint, param);
GLFUNC_3(glTexEnviv, GLenum, target, GLenum, pname, const GLint *, params);
GLFUNC_3(glTexGend, GLenum, coord, GLenum, pname, GLdouble, param);
GLFUNC_3(glTexGendv, GLenum, coord, GLenum, pname, const GLdouble *, params);
GLFUNC_3(glTexGenf, GLenum, coord, GLenum, pname, GLfloat, param);
GLFUNC_3(glTexGenfv, GLenum, coord, GLenum, pname, const GLfloat *, params);
GLFUNC_3(glTexGeni, GLenum, coord, GLenum, pname, GLint, param);
GLFUNC_3(glTexGeniv, GLenum, coord, GLenum, pname, const GLint *, params);
GLFUNC_3(glTexParameterf, GLenum, target, GLenum, pname, GLfloat, param);
GLFUNC_3(glTexParameterfv, GLenum, target, GLenum, pname, const GLfloat *, params);
GLFUNC_3(glTexParameteri, GLenum, target, GLenum, pname, GLint, param);
GLFUNC_3(glTexParameteriv, GLenum, target, GLenum, pname, const GLint *, params);
GLFUNC_3(glTranslated, GLdouble, x, GLdouble, y, GLdouble, z);
GLFUNC_3(glTranslatef, GLfloat, x, GLfloat, y, GLfloat, z);
GLFUNC_3(glVertex3d, GLdouble, x, GLdouble, y, GLdouble, z);
GLFUNC_3(glVertex3f, GLfloat, x, GLfloat, y, GLfloat, z);
GLFUNC_3(glVertex3i, GLint, x, GLint, y, GLint, z);
GLFUNC_3(glVertex3s, GLshort, x, GLshort, y, GLshort, z);
GLFUNC_4(glClearAccum, GLfloat, red, GLfloat, green, GLfloat, blue, GLfloat, alpha);
GLFUNC_4(glClearColor, GLclampf, red, GLclampf, green, GLclampf, blue, GLclampf, alpha);
GLFUNC_4(glColor4b, GLbyte, red, GLbyte, green, GLbyte, blue, GLbyte, alpha);
GLFUNC_4(glColor4d, GLdouble, red, GLdouble, green, GLdouble, blue, GLdouble, alpha);
GLFUNC_4(glColor4f, GLfloat, red, GLfloat, green, GLfloat, blue, GLfloat, alpha);
GLFUNC_4(glColor4i, GLint, red, GLint, green, GLint, blue, GLint, alpha);
GLFUNC_4(glColor4s, GLshort, red, GLshort, green, GLshort, blue, GLshort, alpha);
GLFUNC_4(glColor4ub, GLubyte, red, GLubyte, green, GLubyte, blue, GLubyte, alpha);
GLFUNC_4(glColor4ui, GLuint, red, GLuint, green, GLuint, blue, GLuint, alpha);
GLFUNC_4(glColor4us, GLushort, red, GLushort, green, GLushort, blue, GLushort, alpha);
GLFUNC_4(glColorMask, GLboolean, red, GLboolean, green, GLboolean, blue, GLboolean, alpha);
GLFUNC_4(glColorPointer, GLint, size, GLenum, type, GLsizei, stride, const void *, pointer);
GLFUNC_4(glDrawElements, GLenum, mode, GLsizei, count, GLenum, type, const void *, indices);
GLFUNC_4(glGetTexLevelParameterfv, GLenum, target, GLint, level, GLenum, pname, GLfloat *, params);
GLFUNC_4(glGetTexLevelParameteriv, GLenum, target, GLint, level, GLenum, pname, GLint *, params);
GLFUNC_4(glRasterPos4f, GLfloat, x, GLfloat, y, GLfloat, z, GLfloat, w);
GLFUNC_4(glRasterPos4i, GLint, x, GLint, y, GLint, z, GLint, w);
GLFUNC_4(glRasterPos4s, GLshort, x, GLshort, y, GLshort, z, GLshort, w);
GLFUNC_4(glRectd, GLdouble, x1, GLdouble, y1, GLdouble, x2, GLdouble, y2);
GLFUNC_4(glRectf, GLfloat, x1, GLfloat, y1, GLfloat, x2, GLfloat, y2);
GLFUNC_4(glRecti, GLint, x1, GLint, y1, GLint, x2, GLint, y2);
GLFUNC_4(glRects, GLshort, x1, GLshort, y1, GLshort, x2, GLshort, y2);
GLFUNC_4(glRotated, GLdouble, angle, GLdouble, x, GLdouble, y, GLdouble, z);
GLFUNC_4(glRotatef, GLfloat, angle, GLfloat, x, GLfloat, y, GLfloat, z);
GLFUNC_4(glScissor, GLint, x, GLint, y, GLsizei, width, GLsizei, height);
GLFUNC_4(glTexCoord4d, GLdouble, s, GLdouble, t, GLdouble, r, GLdouble, q);
GLFUNC_4(glTexCoord4f, GLfloat, s, GLfloat, t, GLfloat, r, GLfloat, q);
GLFUNC_4(glTexCoord4i, GLint, s, GLint, t, GLint, r, GLint, q);
GLFUNC_4(glTexCoord4s, GLshort, s, GLshort, t, GLshort, r, GLshort, q);
GLFUNC_4(glTexCoordPointer, GLint, size, GLenum, type, GLsizei, stride, const void *, pointer);
GLFUNC_4(glVertex4d, GLdouble, x, GLdouble, y, GLdouble, z, GLdouble, w);
GLFUNC_4(glVertex4f, GLfloat, x, GLfloat, y, GLfloat, z, GLfloat, w);
GLFUNC_4(glVertex4i, GLint, x, GLint, y, GLint, z, GLint, w);
GLFUNC_4(glVertex4s, GLshort, x, GLshort, y, GLshort, z, GLshort, w);
GLFUNC_4(glVertexPointer, GLint, size, GLenum, type, GLsizei, stride, const void *, pointer);
GLFUNC_4(glViewport, GLint, x, GLint, y, GLsizei, width, GLsizei, height);
GLFUNC_5(glCopyPixels, GLint, x, GLint, y, GLsizei, width, GLsizei, height, GLenum, type);
GLFUNC_5(glDrawPixels, GLsizei, width, GLsizei, height, GLenum, format, GLenum, type, const void *, pixels);
GLFUNC_5(glEvalMesh2, GLenum, mode, GLint, i1, GLint, i2, GLint, j1, GLint, j2);
GLFUNC_5(glGetTexImage, GLenum, target, GLint, level, GLenum, format, GLenum, type, void *, pixels);
GLFUNC_6(glCopyTexSubImage1D, GLenum, target, GLint, level, GLint, xoffset, GLint, x, GLint, y, GLsizei, width);
GLFUNC_6(glFrustum, GLdouble, left, GLdouble, right, GLdouble, bottom, GLdouble, top, GLdouble, zNear, GLdouble, zFar);
GLFUNC_6(glMap1d, GLenum, target, GLdouble, u1, GLdouble, u2, GLint, stride, GLint, order, const GLdouble *, points);
GLFUNC_6(glMap1f, GLenum, target, GLfloat, u1, GLfloat, u2, GLint, stride, GLint, order, const GLfloat *, points);
GLFUNC_6(glMapGrid2d, GLint, un, GLdouble, u1, GLdouble, u2, GLint, vn, GLdouble, v1, GLdouble, v2);
GLFUNC_6(glMapGrid2f, GLint, un, GLfloat, u1, GLfloat, u2, GLint, vn, GLfloat, v1, GLfloat, v2);
GLFUNC_6(glOrtho, GLdouble, left, GLdouble, right, GLdouble, bottom, GLdouble, top, GLdouble, zNear, GLdouble, zFar);
GLFUNC_7(glBitmap, GLsizei, width, GLsizei, height, GLfloat, xorig, GLfloat, yorig, GLfloat, xmove, GLfloat, ymove, const GLubyte *, bitmap);
GLFUNC_7(glCopyTexImage1D, GLenum, target, GLint, level, GLenum, internalFormat, GLint, x, GLint, y, GLsizei, width, GLint, border);
GLFUNC_7(glReadPixels, GLint, x, GLint, y, GLsizei, width, GLsizei, height, GLenum, format, GLenum, type, void *, pixels);
GLFUNC_7(glTexSubImage1D, GLenum, target, GLint, level, GLint, xoffset, GLsizei, width, GLenum, format, GLenum, type, const void *, pixels);
GLFUNC_8(glCopyTexImage2D, GLenum, target, GLint, level, GLenum, internalFormat, GLint, x, GLint, y, GLsizei, width, GLsizei, height, GLint, border);
GLFUNC_8(glCopyTexSubImage2D, GLenum, target, GLint, level, GLint, xoffset, GLint, yoffset, GLint, x, GLint, y, GLsizei, width, GLsizei, height);
GLFUNC_8(glTexImage1D, GLenum, target, GLint, level, GLint, internalformat, GLsizei, width, GLint, border, GLenum, format, GLenum, type, const void *, pixels);
GLFUNC_9(glTexImage2D, GLenum, target, GLint, level, GLint, internalformat, GLsizei, width, GLsizei, height, GLint, border, GLenum, format, GLenum, type, const void *, pixels);
GLFUNC_9(glTexSubImage2D, GLenum, target, GLint, level, GLint, xoffset, GLint, yoffset, GLsizei, width, GLsizei, height, GLenum, format, GLenum, type, const void *, pixels);
GLFUNC_10(glMap2d, GLenum, target, GLdouble, u1, GLdouble, u2, GLint, ustride, GLint, uorder, GLdouble, v1, GLdouble, v2, GLint, vstride, GLint, vorder, const GLdouble *, points);
GLFUNC_10(glMap2f, GLenum, target, GLfloat, u1, GLfloat, u2, GLint, ustride, GLint, uorder, GLfloat, v1, GLfloat, v2, GLint, vstride, GLint, vorder, const GLfloat *, points);
| 43.796262 | 179 | 0.637574 | [
"vector"
] |
165a2837406f3d7e32507f62dc51be8f28a03fb0 | 3,999 | cpp | C++ | tests/test-process.cpp | jin1xiao3long2/libmozart | 78ba2e0d2cb7fbf8b721b94d05c9f2845c6b0281 | [
"Apache-2.0"
] | 2 | 2021-03-01T06:41:30.000Z | 2021-03-01T07:28:15.000Z | tests/test-process.cpp | jin1xiao3long2/libmozart | 78ba2e0d2cb7fbf8b721b94d05c9f2845c6b0281 | [
"Apache-2.0"
] | null | null | null | tests/test-process.cpp | jin1xiao3long2/libmozart | 78ba2e0d2cb7fbf8b721b94d05c9f2845c6b0281 | [
"Apache-2.0"
] | 1 | 2021-04-22T16:48:25.000Z | 2021-04-22T16:48:25.000Z | /**
* Mozart++ Template Library
* Licensed under Apache 2.0
* Copyright (C) 2020-2021 Chengdu Covariant Technologies Co., LTD.
* Website: https://covariant.cn/
* Github: https://github.com/chengdu-zhirui/
*/
#include <cstdio>
#include <cstdlib>
#include <mozart++/string>
#include <mozart++/process>
#ifdef MOZART_PLATFORM_WIN32
#define SHELL "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe"
#else
#define SHELL "/bin/bash"
#endif
using mpp::process;
using mpp::process_builder;
void test_basic() {
process p = process::exec(SHELL);
p.in() << "ls /" << std::endl;
p.in() << "exit" << std::endl;
p.wait_for();
std::string s;
while (std::getline(p.out(), s)) {
printf("process: test-basic: %s\n", s.c_str());
}
}
void test_execvpe_unix() {
#ifndef MOZART_PLATFORM_WIN32
process p = process::exec("ls");
p.wait_for();
std::string s;
while (std::getline(p.out(), s)) {
printf("process: test_execvpe_unix: %s\n", s.c_str());
}
#endif
}
void test_error_unix() {
#ifndef MOZART_PLATFORM_WIN32
try {
process p = process::exec("no-such-command");
p.wait_for();
} catch (const mpp::runtime_error &e) {
printf("%s\n", e.what());
if (!mpp::string_ref(e.what()).contains("No such file or directory")) {
printf("process: test_error_unix: failed\n");
exit(1);
}
}
#endif
}
void test_stderr() {
// PS> echo fuckms 1>&2
// + CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
// + FullyQualifiedErrorId : RedirectionNotSupported
#ifndef MOZART_PLATFORM_WIN32
// the following code is equivalent to "/bin/bash 2>&1"
process p = process_builder().command(SHELL)
.merge_outputs(true)
.start();
// write to stderr
p.in() << "echo fuckcpp 1>&2" << std::endl;
p.in() << "exit" << std::endl;
p.wait_for();
// and we can get from stdout
std::string s;
p.out() >> s;
if (s != "fuckcpp") {
printf("process: test-stderr: failed\n");
exit(1);
}
#endif
}
void test_env() {
// Thanks to the fucking powershit,
// I can't refer to my variables till now.
// God knows why MS designed an object-oriented shell,
// and it just tastes like shit.
#ifndef MOZART_PLATFORM_WIN32
process p = process_builder().command(SHELL)
.environment("VAR1", "fuck")
.environment("VAR2", "cpp")
.start();
p.in() << "echo $VAR1$VAR2" << std::endl;
p.in() << "exit" << std::endl;
p.wait_for();
std::string s;
p.out() >> s;
if (s != "fuckcpp") {
printf("process: test-env: failed\n");
exit(1);
}
#endif
}
void test_r_file() {
// VAR=fuckcpp bash <<< "echo $VAR; exit" > output-all.txt
FILE *fout = fopen("output-all.txt", "w");
process p = process_builder().command(SHELL)
#ifndef MOZART_PLATFORM_WIN32
.environment("VAR", "fuckcpp")
#endif
.redirect_stdout(fileno(fout))
.merge_outputs(true)
.start();
p.in() << "echo $VAR" << std::endl;
p.in() << "exit" << std::endl;
p.wait_for();
fclose(fout);
fout = fopen("output-all.txt", "r");
mpp::fdistream fin(fileno(fout));
std::string s;
fin >> s;
#ifndef MOZART_PLATFORM_WIN32
if (s != "fuckcpp") {
printf("process: test-redirect-file: failed\n");
exit(1);
}
#else
if (s != "Windows") {
printf("process: test-redirect-file: failed\n");
exit(1);
}
#endif
}
void test_exit_code() {
process p = process::exec(SHELL);
p.in() << "exit 120" << std::endl;
int code = p.wait_for();
if (code != 120) {
printf("process: test-exit-code: failed\n");
exit(1);
}
}
int main(int argc, const char **argv) {
test_basic();
test_execvpe_unix();
test_error_unix();
test_stderr();
test_env();
test_r_file();
test_exit_code();
return 0;
}
| 22.721591 | 88 | 0.580145 | [
"object"
] |
1668f3d8c02d145dc121fbc1b4e0cc9b04b17ac1 | 6,970 | cpp | C++ | src/console_writer.cpp | lainets/gcheck | c31471ea8c085bbdbc19ca202100c7d02e18fdc5 | [
"MIT"
] | null | null | null | src/console_writer.cpp | lainets/gcheck | c31471ea8c085bbdbc19ca202100c7d02e18fdc5 | [
"MIT"
] | null | null | null | src/console_writer.cpp | lainets/gcheck | c31471ea8c085bbdbc19ca202100c7d02e18fdc5 | [
"MIT"
] | null | null | null | #include "console_writer.h"
#include <unistd.h>
#include <iostream>
#include <algorithm>
namespace gcheck {
int ConsoleWriter::width_ = -1;
int ConsoleWriter::GetWidth() {
if(width_ != -1)
return width_;
int w = 0;
#if defined(_WIN32) || defined(WIN32)
CONSOLE_SCREEN_BUFFER_INFO csbi;
GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi);
if(csbi.dwSize.X > 0) {
terminating_newline_ = false;
w = csbi.dwSize.X;
} else if(csbi.srWindow.Right - csbi.srWindow.Left > 0) {
terminating_newline_ = false;
w = csbi.srWindow.Right - csbi.srWindow.Left + 1;
} else if(csbi.dwMaximumWindowSize.X > 0) {
terminating_newline_ = true;
w = csbi.dwMaximumWindowSize.X;
} else {
terminating_newline_ = true;
}
#else //lets hope it is unix
winsize size;
ioctl(STDOUT_FILENO,TIOCGWINSZ,&size);
w = size.ws_col;
#endif
return w < 5 ? w = 128 : w;
}
std::vector<int> ConsoleWriter::CalcWidths(const std::vector<std::string>& strs, std::vector<int> widths) {
if(widths.size() < strs.size())
widths.resize(strs.size(), 0);
auto it2 = widths.begin();
for(auto it = strs.begin(); it != strs.end(); it++, it2++) {
const std::string& str = *it;
int& max_width = *it2;
for(size_t pos = 0, pos2 = 0; pos2 != std::string::npos; pos = pos2+1) {
pos2 = str.find('\n', pos);
int width = pos2 == std::string::npos ? str.length()-pos : pos2-pos;
if(max_width < width)
max_width = width;
}
}
return widths;
}
void ConsoleWriter::WriteRow(int width, const std::vector<std::string>& cells, const std::vector<int>& widths, const std::vector<int>& cuts) {
if(width < 5) {
width = 128;
}
int totalwidth = widths.size()+1;
for(auto& e : widths)
totalwidth += e;
if(totalwidth > width)
totalwidth = width;
std::vector<std::vector<std::string>> parts;
std::vector<size_t> poss(cells.size(), 0);
unsigned int num_done = 0;
while(num_done != poss.size()) {
parts.push_back({});
std::vector<std::string>& row = parts[parts.size()-1];
for(unsigned int i = 0; i < poss.size(); i++) {
if(poss[i] != std::string::npos) {
size_t end = cells[i].find('\n', poss[i]);
if(end != std::string::npos) {
row.push_back(cells[i].substr(poss[i], end-poss[i]));
poss[i] = end+1;
} else {
row.push_back(cells[i].substr(poss[i]));
poss[i] = end;
num_done++;
}
} else {
row.push_back("");
}
}
}
int pos = 0;
for(auto it = cuts.begin(); it != cuts.end(); it++) {
if(pos == 0)
std::cout << "+";
else std::cout << " ";
int t_width = (pos == 0 ? 1 : 2);
for(int i = 0; i < *it; ++i) {
int w = std::min(widths[pos+i], totalwidth - (pos == 0 ? 2 : 3));
t_width += w + 1;
std::cout << std::string(w, '-') << '+';
}
if(terminating_newline_ || t_width != width)
std::cout << std::endl;
for(auto& row : parts) {
std::string pad = "|";
if(pos != 0)
pad = " ";
std::cout << pad;
if(row[pos].length() > totalwidth-pad.length()-1) {
size_t len = totalwidth-pad.length()-1;
SetColor(BrightBlack);
std::cout << row[pos].substr(0, len);
size_t p = len;
len = totalwidth-pad.length()-2;
for(; p < row[pos].length(); p += len) {
SetColor(Black);
std::cout << '|' << pad << " ";
SetColor(BrightBlack);
std::cout << row[pos].substr(p, len);
}
SetColor(Black);
std::cout << std::string(std::max(p-row[pos].length(), (size_t)1)-1, ' ') << '|';
} else {
t_width = (pos == 0 ? 1 : 2);
for(int i = 0; i < *it; ++i) {
SetColor(BrightBlack);
std::cout << row[pos+i];
SetColor(Black);
int w = std::min(widths[pos+i], totalwidth - (pos == 0 ? 2 : 3));;
t_width += w + 1;
std::cout << std::string(w-row[pos+i].length(), ' ') << '|';
}
if(terminating_newline_ || t_width != width)
std::cout << std::endl;
}
}
if(cuts.size() > 1 && it == cuts.end()-1)
std::cout << std::endl;
pos += *it;
}
}
void ConsoleWriter::SetColor(Color color) {
if(use_colors_) {
std::cout.flush();
#if defined(_WIN32) || defined(WIN32)
if(color == Original)
color = Black;
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hConsole, (WORD)color);
#else //lets hope it is unix
if(color == Original)
std::cout << "\033[0m";
else
std::cout << "\033[48;5;" + std::to_string((int)color) + "m";
#endif
}
}
void ConsoleWriter::WriteSeparator() {
int width = GetWidth();
std::cout << std::string(width, '*');
if(terminating_newline_)
std::cout << std::endl;
}
void ConsoleWriter::SetHeaders(const std::vector<std::string>& headers) {
headers_ = headers;
header_widths_ = CalcWidths(headers);
}
void ConsoleWriter::WriteRow(const std::vector<std::string>& cells) {
WriteRows(std::vector<std::vector<std::string>>(1, cells));
}
void ConsoleWriter::WriteRows(std::vector<std::vector<std::string>> cells) {
int width = GetWidth();
std::vector<int> widths = header_widths_;
for(auto& r : cells)
widths = CalcWidths(r, widths);
for(auto& r : cells)
if(r.size() < widths.size())
r.resize(widths.size(), "");
std::vector<int> cuts;
int cut_width = 1, counter = 0;
for(auto& e : widths) {
cut_width += e + 1;
if(cut_width > width && counter != 0) {
cut_width = e + 3;
cuts.push_back(counter);
counter = 0;
}
counter++;
}
cuts.push_back(counter);
if(headers_.size() != 0) {
if(headers_.size() != widths.size()) {
auto headers = headers_;
headers.resize(widths.size(), "");
WriteRow(width, headers, widths, cuts);
} else {
WriteRow(width, headers_, widths, cuts);
}
}
for(auto& r : cells) {
WriteRow(width, r, widths, cuts);
}
for(int i = 0; i < cuts[0]; i++) {
std::cout << '+' << std::string(widths[i], '-');
}
std::cout << '+' << std::endl;
}
} | 31.116071 | 142 | 0.494835 | [
"vector"
] |
166b9383d7ba75062f12dfbff2be40e570b84401 | 1,340 | cpp | C++ | readInput.cpp | TobbeOlsson/AoC21 | 3824f2e65137270d54c99c60d1f106da556c81f2 | [
"MIT"
] | null | null | null | readInput.cpp | TobbeOlsson/AoC21 | 3824f2e65137270d54c99c60d1f106da556c81f2 | [
"MIT"
] | null | null | null | readInput.cpp | TobbeOlsson/AoC21 | 3824f2e65137270d54c99c60d1f106da556c81f2 | [
"MIT"
] | null | null | null | #include "readInput.h"
#include <fstream>
#include <string>
#include <iostream>
#include <utility>
std::vector<int> fileLinesToIntVector(std::string file_path){
std::vector<int> input;
std::ifstream in(file_path);
if (!in){
std::cout << "Could not find input file: " << file_path << "\n";
exit(0);
}
std::string line;
while(std::getline(in, line)){
input.push_back(std::stoi(line));
}
in.close();
return input;
}
std::vector<std::string> fileLinesToStringVector(std::string file_path){
std::vector<std::string> input;
std::ifstream in(file_path);
if (!in){
std::cout << "Could not find input file: " << file_path << "\n";
exit(0);
}
std::string line;
while(std::getline(in, line)){
input.push_back(line);
}
in.close();
return input;
}
std::vector<std::pair<std::string, int> > fileLinesToPairVector(std::string file_path){
std::vector<std::pair<std::string, int> > input;
std::ifstream in(file_path);
std::string s;
int i;
if (!in){
std::cout << "Could not find input file: " << file_path << "\n";
exit(0);
}
std::string line;
while(in >> s >> i){
input.push_back(std::make_pair(s, i));
}
in.close();
return input;
} | 21.967213 | 87 | 0.565672 | [
"vector"
] |
16702eaf34630c386cf71d30e121bc88e45b20d9 | 15,450 | cc | C++ | lullaby/modules/animation_channels/transform_channels.cc | dd181818/lullaby | 71e696c3798068a350e820433c9d3185fa28c0ce | [
"Apache-2.0"
] | 1 | 2018-11-09T03:45:25.000Z | 2018-11-09T03:45:25.000Z | lullaby/modules/animation_channels/transform_channels.cc | dd181818/lullaby | 71e696c3798068a350e820433c9d3185fa28c0ce | [
"Apache-2.0"
] | null | null | null | lullaby/modules/animation_channels/transform_channels.cc | dd181818/lullaby | 71e696c3798068a350e820433c9d3185fa28c0ce | [
"Apache-2.0"
] | null | null | null | /*
Copyright 2017 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "lullaby/modules/animation_channels/transform_channels.h"
#include "lullaby/modules/dispatcher/dispatcher.h"
#include "lullaby/systems/animation/animation_system.h"
#include "lullaby/systems/transform/transform_system.h"
#include "lullaby/util/logging.h"
#include "mathfu/constants.h"
namespace lull {
const HashValue PositionChannel::kChannelName = ConstHash("transform-position");
const HashValue PositionXChannel::kChannelName =
ConstHash("transform-position-x");
const HashValue PositionYChannel::kChannelName =
ConstHash("transform-position-y");
const HashValue PositionZChannel::kChannelName =
ConstHash("transform-position-z");
const HashValue RotationChannel::kChannelName = ConstHash("transform-rotation");
const HashValue ScaleChannel::kChannelName = ConstHash("transform-scale");
const HashValue ScaleFromRigChannel::kChannelName =
ConstHash("transform-scale-rig");
const HashValue AabbMinChannel::kChannelName = ConstHash("transform-aabb-min");
const HashValue AabbMaxChannel::kChannelName = ConstHash("transform-aabb-max");
namespace {
const motive::MatrixOperationType kTranslateOps[] = {
motive::kTranslateX, motive::kTranslateY, motive::kTranslateZ};
const motive::MatrixOperationType kTranslateXOps[] = {motive::kTranslateX};
const motive::MatrixOperationType kTranslateYOps[] = {motive::kTranslateY};
const motive::MatrixOperationType kTranslateZOps[] = {motive::kTranslateZ};
const motive::MatrixOperationType kRotateOps[] = {
motive::kRotateAboutX, motive::kRotateAboutY, motive::kRotateAboutZ};
const motive::MatrixOperationType kScaleOps[] = {
motive::kScaleX, motive::kScaleY, motive::kScaleZ};
} // namespace
PositionChannel::PositionChannel(Registry* registry, size_t pool_size)
: AnimationChannel(registry, 3, pool_size),
transform_system_(registry->Get<TransformSystem>()) {}
void PositionChannel::Setup(Registry* registry, size_t pool_size) {
auto animation_system = registry->Get<AnimationSystem>();
auto transform_system = registry->Get<TransformSystem>();
if (animation_system == nullptr || transform_system == nullptr) {
LOG(DFATAL) << "Failed to setup PositionChannel.";
}
AnimationChannelPtr ptr(new PositionChannel(registry, pool_size));
animation_system->AddChannel(kChannelName, std::move(ptr));
auto* dispatcher = registry->Get<Dispatcher>();
if (animation_system && dispatcher) {
dispatcher->Connect(
animation_system, [animation_system](const AnimatePositionEvent& e) {
const auto duration = std::chrono::duration_cast<Clock::duration>(
std::chrono::duration<float, std::milli>(e.time_ms));
animation_system->SetTarget(e.entity, kChannelName, &e.position[0], 3,
duration);
});
}
}
const motive::MatrixOperationType* PositionChannel::GetOperations() const {
return kTranslateOps;
}
bool PositionChannel::Get(Entity e, float* values, size_t len) const {
const Sqt* sqt = transform_system_->GetSqt(e);
if (sqt == nullptr) {
return false;
}
values[0] = sqt->translation.x;
values[1] = sqt->translation.y;
values[2] = sqt->translation.z;
return true;
}
void PositionChannel::Set(Entity e, const float* values, size_t len) {
const Sqt* sqt = transform_system_->GetSqt(e);
if (sqt == nullptr) {
return;
}
Sqt updated_sqt = *sqt;
updated_sqt.translation.x = values[0];
updated_sqt.translation.y = values[1];
updated_sqt.translation.z = values[2];
transform_system_->SetSqt(e, updated_sqt);
}
PositionXChannel::PositionXChannel(Registry* registry, size_t pool_size)
: AnimationChannel(registry, 1 /* num_dimensions */, pool_size),
transform_system_(registry->Get<TransformSystem>()) {}
void PositionXChannel::Setup(Registry* registry, size_t pool_size) {
auto* animation_system = registry->Get<AnimationSystem>();
auto* transform_system = registry->Get<TransformSystem>();
if (animation_system == nullptr || transform_system == nullptr) {
LOG(DFATAL) << "Failed to setup PositionXChannel.";
}
AnimationChannelPtr ptr(new PositionXChannel(registry, pool_size));
animation_system->AddChannel(kChannelName, std::move(ptr));
}
const motive::MatrixOperationType* PositionXChannel::GetOperations() const {
return kTranslateXOps;
}
bool PositionXChannel::Get(Entity e, float* values, size_t len) const {
const Sqt* sqt = transform_system_->GetSqt(e);
if (sqt == nullptr) {
return false;
}
values[0] = sqt->translation.x;
return true;
}
void PositionXChannel::Set(Entity e, const float* values, size_t len) {
const Sqt* sqt = transform_system_->GetSqt(e);
if (sqt == nullptr) {
return;
}
Sqt updated_sqt = *sqt;
updated_sqt.translation.x = values[0];
transform_system_->SetSqt(e, updated_sqt);
}
PositionYChannel::PositionYChannel(Registry* registry, size_t pool_size)
: AnimationChannel(registry, 1 /* num_dimensions */, pool_size),
transform_system_(registry->Get<TransformSystem>()) {}
void PositionYChannel::Setup(Registry* registry, size_t pool_size) {
auto* animation_system = registry->Get<AnimationSystem>();
auto* transform_system = registry->Get<TransformSystem>();
if (animation_system == nullptr || transform_system == nullptr) {
LOG(DFATAL) << "Failed to setup PositionYChannel.";
}
AnimationChannelPtr ptr(new PositionYChannel(registry, pool_size));
animation_system->AddChannel(kChannelName, std::move(ptr));
}
const motive::MatrixOperationType* PositionYChannel::GetOperations() const {
return kTranslateYOps;
}
bool PositionYChannel::Get(Entity e, float* values, size_t len) const {
const Sqt* sqt = transform_system_->GetSqt(e);
if (sqt == nullptr) {
return false;
}
values[0] = sqt->translation.y;
return true;
}
void PositionYChannel::Set(Entity e, const float* values, size_t len) {
const Sqt* sqt = transform_system_->GetSqt(e);
if (sqt == nullptr) {
return;
}
Sqt updated_sqt = *sqt;
updated_sqt.translation.y = values[0];
transform_system_->SetSqt(e, updated_sqt);
}
PositionZChannel::PositionZChannel(Registry* registry, size_t pool_size)
: AnimationChannel(registry, 1 /* num_dimensions */, pool_size),
transform_system_(registry->Get<TransformSystem>()) {}
void PositionZChannel::Setup(Registry* registry, size_t pool_size) {
auto* animation_system = registry->Get<AnimationSystem>();
auto* transform_system = registry->Get<TransformSystem>();
if (animation_system == nullptr || transform_system == nullptr) {
LOG(DFATAL) << "Failed to setup PositionZChannel.";
}
AnimationChannelPtr ptr(new PositionZChannel(registry, pool_size));
animation_system->AddChannel(kChannelName, std::move(ptr));
}
const motive::MatrixOperationType* PositionZChannel::GetOperations() const {
return kTranslateZOps;
}
bool PositionZChannel::Get(Entity e, float* values, size_t len) const {
const Sqt* sqt = transform_system_->GetSqt(e);
if (sqt == nullptr) {
return false;
}
values[0] = sqt->translation.z;
return true;
}
void PositionZChannel::Set(Entity e, const float* values, size_t len) {
const Sqt* sqt = transform_system_->GetSqt(e);
if (sqt == nullptr) {
return;
}
Sqt updated_sqt = *sqt;
updated_sqt.translation.z = values[0];
transform_system_->SetSqt(e, updated_sqt);
}
RotationChannel::RotationChannel(Registry* registry, size_t pool_size)
: AnimationChannel(registry, 3, pool_size) {
transform_system_ = registry->Get<TransformSystem>();
}
void RotationChannel::Setup(Registry* registry, size_t pool_size) {
auto animation_system = registry->Get<AnimationSystem>();
auto transform_system = registry->Get<TransformSystem>();
if (animation_system && transform_system) {
AnimationChannelPtr ptr(new RotationChannel(registry, pool_size));
animation_system->AddChannel(kChannelName, std::move(ptr));
} else {
LOG(DFATAL) << "Failed to setup RotationChannel.";
}
auto* dispatcher = registry->Get<Dispatcher>();
if (animation_system && dispatcher) {
dispatcher->Connect(
animation_system, [animation_system](const AnimateRotationEvent& e) {
auto angles = e.rotation.ToEulerAngles();
const auto duration = std::chrono::duration_cast<Clock::duration>(
std::chrono::duration<float, std::milli>(e.time_ms));
animation_system->SetTarget(e.entity, kChannelName, &angles[0], 3,
duration);
});
}
}
const motive::MatrixOperationType* RotationChannel::GetOperations() const {
return kRotateOps;
}
bool RotationChannel::Get(Entity e, float* values, size_t len) const {
const Sqt* sqt = transform_system_->GetSqt(e);
if (sqt) {
const mathfu::vec3 angles = sqt->rotation.ToEulerAngles();
values[0] = angles.x;
values[1] = angles.y;
values[2] = angles.z;
return true;
}
return false;
}
void RotationChannel::Set(Entity e, const float* values, size_t len) {
const Sqt* sqt = transform_system_->GetSqt(e);
if (sqt) {
const mathfu::vec3 angles(values[0], values[1], values[2]);
Sqt updated_sqt = *sqt;
updated_sqt.rotation = mathfu::quat::FromEulerAngles(angles);
transform_system_->SetSqt(e, updated_sqt);
}
}
ScaleChannel::ScaleChannel(Registry* registry, size_t pool_size)
: AnimationChannel(registry, 3, pool_size) {
transform_system_ = registry->Get<TransformSystem>();
}
void ScaleChannel::Setup(Registry* registry, size_t pool_size) {
auto animation_system = registry->Get<AnimationSystem>();
auto transform_system = registry->Get<TransformSystem>();
if (animation_system && transform_system) {
AnimationChannelPtr ptr(new ScaleChannel(registry, pool_size));
animation_system->AddChannel(kChannelName, std::move(ptr));
} else {
LOG(DFATAL) << "Failed to setup ScaleChannel.";
}
auto* dispatcher = registry->Get<Dispatcher>();
if (animation_system && dispatcher) {
dispatcher->Connect(
animation_system, [animation_system](const AnimateScaleEvent& e) {
const auto duration = std::chrono::duration_cast<Clock::duration>(
std::chrono::duration<float, std::milli>(e.time_ms));
animation_system->SetTarget(e.entity, kChannelName, &e.scale[0], 3,
duration);
});
}
}
const motive::MatrixOperationType* ScaleChannel::GetOperations() const {
return kScaleOps;
}
bool ScaleChannel::Get(Entity e, float* values, size_t len) const {
const Sqt* sqt = transform_system_->GetSqt(e);
if (sqt) {
values[0] = sqt->scale.x;
values[1] = sqt->scale.y;
values[2] = sqt->scale.z;
return true;
}
return false;
}
void ScaleChannel::Set(Entity e, const float* values, size_t len) {
const Sqt* sqt = transform_system_->GetSqt(e);
if (sqt) {
Sqt updated_sqt = *sqt;
updated_sqt.scale.x = values[0];
updated_sqt.scale.y = values[1];
updated_sqt.scale.z = values[2];
transform_system_->SetSqt(e, updated_sqt);
}
}
ScaleFromRigChannel::ScaleFromRigChannel(Registry* registry, size_t pool_size)
: AnimationChannel(registry, 0, pool_size) {
transform_system_ = registry->Get<TransformSystem>();
}
void ScaleFromRigChannel::Setup(Registry* registry, size_t pool_size) {
auto animation_system = registry->Get<AnimationSystem>();
auto transform_system = registry->Get<TransformSystem>();
if (animation_system && transform_system) {
AnimationChannelPtr ptr(new ScaleFromRigChannel(registry, pool_size));
animation_system->AddChannel(kChannelName, std::move(ptr));
} else {
LOG(DFATAL) << "Failed to setup ScaleFromRigChannel.";
}
}
const motive::MatrixOperationType* ScaleFromRigChannel::GetOperations() const {
return kScaleOps;
}
void ScaleFromRigChannel::Set(Entity e, const float* values, size_t len) {
LOG(DFATAL) << "SetRig should be called for rig channels.";
}
void ScaleFromRigChannel::SetRig(Entity entity,
const mathfu::AffineTransform* values,
size_t len) {
if (len != 1) {
LOG(DFATAL) << "Too many transforms; can only collect scale from one.";
return;
}
const Sqt* old_sqt = transform_system_->GetSqt(entity);
if (old_sqt == nullptr) {
LOG(DFATAL) << "Entity does not have a SQT.";
return;
}
Sqt sqt = CalculateSqtFromAffineTransform(values[0]);
sqt.rotation = old_sqt->rotation;
sqt.translation = old_sqt->translation;
transform_system_->SetSqt(entity, sqt);
}
AabbMinChannel::AabbMinChannel(Registry* registry, size_t pool_size)
: AnimationChannel(registry, 3 /* num_dimensions */, pool_size),
transform_system_(registry->Get<TransformSystem>()) {}
void AabbMinChannel::Setup(Registry* registry, size_t pool_size) {
auto* animation_system = registry->Get<AnimationSystem>();
auto* transform_system = registry->Get<TransformSystem>();
if (animation_system && transform_system) {
animation_system->AddChannel(
kChannelName,
AnimationChannelPtr(new AabbMinChannel(registry, pool_size)));
} else {
LOG(DFATAL) << "Failed to setup AabbMinChannel.";
}
}
bool AabbMinChannel::Get(Entity entity, float* values, size_t len) const {
const Aabb* aabb = transform_system_->GetAabb(entity);
if (aabb) {
values[0] = aabb->min.x;
values[1] = aabb->min.y;
values[2] = aabb->min.z;
return true;
}
return false;
}
void AabbMinChannel::Set(Entity entity, const float* values, size_t len) {
const Aabb* aabb = transform_system_->GetAabb(entity);
if (aabb) {
const mathfu::vec3 min(values[0], values[1], values[2]);
transform_system_->SetAabb(entity, Aabb(min, aabb->max));
}
}
AabbMaxChannel::AabbMaxChannel(Registry* registry, size_t pool_size)
: AnimationChannel(registry, 3 /* num_dimensions */, pool_size),
transform_system_(registry->Get<TransformSystem>()) {}
void AabbMaxChannel::Setup(Registry* registry, size_t pool_size) {
auto* animation_system = registry->Get<AnimationSystem>();
auto* transform_system = registry->Get<TransformSystem>();
if (animation_system && transform_system) {
animation_system->AddChannel(
kChannelName,
AnimationChannelPtr(new AabbMaxChannel(registry, pool_size)));
} else {
LOG(DFATAL) << "Failed to setup AabbMaxChannel.";
}
}
bool AabbMaxChannel::Get(Entity entity, float* values, size_t len) const {
const Aabb* aabb = transform_system_->GetAabb(entity);
if (aabb) {
values[0] = aabb->max.x;
values[1] = aabb->max.y;
values[2] = aabb->max.z;
return true;
}
return false;
}
void AabbMaxChannel::Set(Entity entity, const float* values, size_t len) {
const Aabb* aabb = transform_system_->GetAabb(entity);
if (aabb) {
const mathfu::vec3 max(values[0], values[1], values[2]);
transform_system_->SetAabb(entity, Aabb(aabb->min, max));
}
}
} // namespace lull
| 35.193622 | 80 | 0.712104 | [
"transform"
] |
1675669331fb09e3c6e5f7c1fba717026ed9b4bd | 4,527 | cpp | C++ | UnitTests/LcpSolvers/TestContainers.cpp | jodavis42/ZeroPhysicsTestbed | e84a3f6faf16b7a4242dc049121b5338e80039f8 | [
"MIT"
] | 52 | 2018-09-11T17:18:35.000Z | 2022-03-13T15:28:21.000Z | UnitTests/LcpSolvers/TestContainers.cpp | jodavis42/ZeroPhysicsTestbed | e84a3f6faf16b7a4242dc049121b5338e80039f8 | [
"MIT"
] | 1,409 | 2018-09-19T18:03:43.000Z | 2021-06-09T08:33:33.000Z | UnitTests/LcpSolvers/TestContainers.cpp | jodavis42/ZeroPhysicsTestbed | e84a3f6faf16b7a4242dc049121b5338e80039f8 | [
"MIT"
] | 26 | 2018-09-11T17:16:32.000Z | 2021-11-22T06:21:19.000Z | ///////////////////////////////////////////////////////////////////////////////
///
/// \file TestContainers.cpp
/// Some containers used in testing LCP solvers.
///
/// Authors: Joshua Davis
/// Copyright 2012, DigiPen Institute of Technology
///
///////////////////////////////////////////////////////////////////////////////
#include "TestContainers.hpp"
void SparseVector::Set(uint index, Vec3Param value)
{
uint actualIndex = uint(-1);
for(uint i = 0; i < mCells.Size(); ++i)
{
if(mCells[i].mIndex == index)
{
actualIndex = i;
break;
}
}
if(actualIndex >= mCells.Size())
{
mCells.PushBack(SparceCell(index,value));
return;
}
mCells[actualIndex].mValue = value;
}
Vec3 SparseVector::Get(uint index) const
{
uint actualIndex = uint(-1);
for(uint i = 0; i < mCells.Size(); ++i)
{
if(mCells[i].mIndex == index)
{
actualIndex = i;
break;
}
}
if(actualIndex >= mCells.Size())
return Vec3::cZero;
return mCells[actualIndex].mValue;
}
Vec3 SparseVector::operator[](uint index) const
{
return Get(index);
}
void SparseBlockMatrix::Set(uint r, uint c, Mat3Param value)
{
uint actualRow = uint(-1);
uint actualColumn = uint(-1);
for(uint i = 0; i < mRows.Size(); ++i)
{
if(mRows[i].mIndex == r)
{
actualRow = i;
break;
}
}
if(actualRow >= mRows.Size())
{
SparseRow row(r);
row.mCells.PushBack(SparceCell(c,value));
mRows.PushBack(row);
return;
}
for(uint i = 0; i < mRows[actualRow].mCells.Size(); ++i)
{
if(mRows[actualRow].mCells[i].mIndex == c)
{
actualColumn = i;
break;
}
}
if(actualColumn >= mRows[actualRow].mCells.Size())
{
mRows[actualRow].mCells.PushBack(SparceCell(c,value));
return;
}
mRows[actualRow].mCells[actualColumn].mValue = value;
}
Mat3 SparseBlockMatrix::Get(uint r, uint c) const
{
uint actualRow = uint(-1);
uint actualColumn = uint(-1);
for(uint i = 0; i < mRows.Size(); ++i)
{
if(mRows[i].mIndex == r)
{
actualRow = i;
break;
}
}
if(actualRow >= mRows.Size())
return Mat3().ZeroOut();
for(uint i = 0; i < mRows[actualRow].mCells.Size(); ++i)
{
if(mRows[actualRow].mCells[i].mIndex == c)
{
actualColumn = i;
break;
}
}
if(actualColumn >= mRows[actualRow].mCells.Size())
return Mat3().ZeroOut();
return mRows[actualRow].mCells[actualColumn].mValue;
}
SparseVector SparseBlockMatrix::Transform(const SparseVector& rhs) const
{
SparseVector result;
for(uint row = 0; row < mRows.Size(); ++row)
{
const SparseRow& sRow = mRows[row];
uint actualRow = sRow.mIndex;
Vec3 cellVal = Vec3::cZero;
for(uint col = 0; col < sRow.mCells.Size(); ++col)
{
const SparceCell& sCell = sRow.mCells[col];
uint actualCol = sCell.mIndex;
cellVal += Math::Transform(sCell.mValue,rhs.Get(actualCol));
}
result.Set(actualRow,cellVal);
}
return result;
}
SparseVector SparceBlockCgPolicy::Add(const SparseVector& lhs, const SparseVector& rhs)
{
SparseVector result;
for(uint i = 0; i < lhs.mCells.Size(); ++i)
result.Set(lhs.mCells[i].mIndex,lhs.mCells[i].mValue);
for(uint i = 0; i < rhs.mCells.Size(); ++i)
result.Set(rhs.mCells[i].mIndex, result.Get(i) + rhs.mCells[i].mValue);
return result;
}
SparseVector SparceBlockCgPolicy::Subtract(const SparseVector& lhs, const SparseVector& rhs)
{
SparseVector result;
for(uint i = 0; i < lhs.mCells.Size(); ++i)
result.Set(lhs.mCells[i].mIndex,lhs.mCells[i].mValue);
for(uint i = 0; i < rhs.mCells.Size(); ++i)
result.Set(rhs.mCells[i].mIndex, result.Get(i) - rhs.mCells[i].mValue);
return result;
}
real SparceBlockCgPolicy::Dot(const SparseVector& lhs, const SparseVector& rhs)
{
real result = 0;
for(uint i = 0; i < lhs.mCells.Size(); ++i)
result += Math::Dot(lhs.mCells[i].mValue,rhs.Get(lhs.mCells[i].mIndex));
return result;
}
SparseVector SparceBlockCgPolicy::Scale(const SparseVector& lhs, real rhs)
{
SparseVector result;
for(uint i = 0; i < lhs.mCells.Size(); ++i)
result.Set(lhs.mCells[i].mIndex,lhs.mCells[i].mValue * rhs);
return result;
}
SparseVector SparceBlockCgPolicy::Transform(const SparseBlockMatrix& mat, const SparseVector& vec)
{
return mat.Transform(vec);
}
| 23.826316 | 99 | 0.582947 | [
"transform"
] |
1678f32812a48b3a81072365162910e8e0a0786c | 1,373 | hpp | C++ | Runtime/Character/CCharLayoutInfo.hpp | Jcw87/urde | fb9ea9092ad00facfe957ece282a86c194e9cbda | [
"MIT"
] | 267 | 2016-03-10T21:59:16.000Z | 2021-03-28T18:21:03.000Z | Runtime/Character/CCharLayoutInfo.hpp | cobalt2727/metaforce | 3bb05c0ee5dd9b1b8eaa861fc49713aef62c844a | [
"MIT"
] | 129 | 2016-03-12T10:17:32.000Z | 2021-04-05T20:45:19.000Z | Runtime/Character/CCharLayoutInfo.hpp | cobalt2727/metaforce | 3bb05c0ee5dd9b1b8eaa861fc49713aef62c844a | [
"MIT"
] | 31 | 2016-03-20T00:20:11.000Z | 2021-03-10T21:14:11.000Z | #pragma once
#include <map>
#include <memory>
#include <string>
#include <vector>
#include "Runtime/CFactoryMgr.hpp"
#include "Runtime/IOStreams.hpp"
#include "Runtime/Character/CSegId.hpp"
#include "Runtime/Character/CSegIdList.hpp"
#include "Runtime/Character/TSegIdMap.hpp"
#include <zeus/CVector3f.hpp>
namespace metaforce {
class CCharLayoutNode {
public:
struct Bone {
CSegId x0_parentId;
zeus::CVector3f x4_origin;
std::vector<CSegId> x10_children;
void read(CInputStream& in);
};
private:
TSegIdMap<Bone> x0_boneMap;
public:
explicit CCharLayoutNode(CInputStream& in);
const TSegIdMap<Bone>& GetBoneMap() const { return x0_boneMap; }
};
class CCharLayoutInfo {
std::shared_ptr<CCharLayoutNode> x0_node;
CSegIdList x8_segIdList;
std::map<std::string, CSegId, std::less<>> x18_segIdMap;
public:
explicit CCharLayoutInfo(CInputStream& in);
const std::shared_ptr<CCharLayoutNode>& GetRootNode() const { return x0_node; }
const CSegIdList& GetSegIdList() const { return x8_segIdList; }
zeus::CVector3f GetFromParentUnrotated(const CSegId& id) const;
zeus::CVector3f GetFromRootUnrotated(const CSegId& id) const;
CSegId GetSegIdFromString(std::string_view name) const;
};
CFactoryFnReturn FCharLayoutInfo(const SObjectTag&, CInputStream&, const CVParamTransfer&, CObjectReference* selfRef);
} // namespace metaforce
| 26.403846 | 118 | 0.761107 | [
"vector"
] |
167e0fe02d4f666e59c34dca37416e47a6f65aa9 | 1,599 | cc | C++ | src/ui/a11y/tests/integration/semantic_tree_parser_test.cc | OpenTrustGroup/fuchsia | 647e593ea661b8bf98dcad2096e20e8950b24a97 | [
"BSD-3-Clause"
] | 1 | 2019-04-21T18:02:26.000Z | 2019-04-21T18:02:26.000Z | src/ui/a11y/tests/integration/semantic_tree_parser_test.cc | OpenTrustGroup/fuchsia | 647e593ea661b8bf98dcad2096e20e8950b24a97 | [
"BSD-3-Clause"
] | 16 | 2020-09-04T19:01:11.000Z | 2021-05-28T03:23:09.000Z | src/ui/a11y/tests/integration/semantic_tree_parser_test.cc | OpenTrustGroup/fuchsia | 647e593ea661b8bf98dcad2096e20e8950b24a97 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/ui/a11y/tests/integration/semantic_tree_parser.h"
#include <lib/gtest/test_loop_fixture.h>
#include <src/lib/fxl/logging.h>
#include <vector>
namespace accessibility_test {
using fuchsia::accessibility::semantics::Node;
const std::string kFileNotExistPath = "/some/random/path";
const std::string kSemanticTreePath = "/pkg/data/semantic_tree_odd_nodes.json";
const std::string kFileNotParseablePath = "/pkg/data/semantic_tree_not_parseable.json";
// Unit Test for src/ui/a11y/tests/integration/semantic_tree_parser.h
class SemanticTreeParserTest : public gtest::TestLoopFixture {
public:
SemanticTreeParser semantic_tree_parser_;
};
TEST_F(SemanticTreeParserTest, FileNotExist) {
std::vector<Node> nodes;
ASSERT_FALSE(semantic_tree_parser_.ParseSemanticTree(kFileNotExistPath, &nodes));
ASSERT_TRUE(nodes.size() == 0);
}
TEST_F(SemanticTreeParserTest, SuccessfullyParseFile) {
std::vector<Node> nodes;
ASSERT_TRUE(semantic_tree_parser_.ParseSemanticTree(kSemanticTreePath, &nodes));
ASSERT_TRUE(nodes.size() == 7);
}
TEST_F(SemanticTreeParserTest, ParsingFailed) {
std::vector<Node> nodes;
FXL_LOG(INFO) << "Following error message 'Error parsing "
"file:/pkg/data/semantic_tree_not_parseable.json' is expected.";
ASSERT_FALSE(semantic_tree_parser_.ParseSemanticTree(kFileNotParseablePath, &nodes));
ASSERT_TRUE(nodes.size() == 0);
}
} // namespace accessibility_test
| 34.76087 | 87 | 0.774859 | [
"vector"
] |
167e4e7861d49df2a30583c073fdc6825f198d06 | 336 | cpp | C++ | AtCoder_cpp/ABC146/a.cpp | RyoSci/vscode-remote-cpp | 9a10b3ca840c7566887e8597e73f96560dc1d387 | [
"MIT"
] | null | null | null | AtCoder_cpp/ABC146/a.cpp | RyoSci/vscode-remote-cpp | 9a10b3ca840c7566887e8597e73f96560dc1d387 | [
"MIT"
] | null | null | null | AtCoder_cpp/ABC146/a.cpp | RyoSci/vscode-remote-cpp | 9a10b3ca840c7566887e8597e73f96560dc1d387 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
int main() {
string s = "";
cin >> s;
vector<string> weeks;
weeks = {"SUN","MON","TUE","WED","THU","FRI","SAT"};
for (int i = 0; i < weeks.size(); i++) {
if (weeks.at(i) == s) {
cout << weeks.size() - i << endl;
break;
}
}
} | 21 | 56 | 0.4375 | [
"vector"
] |
16838575cfc861e8860942b453cb5e0efe11ccb3 | 7,229 | cc | C++ | common/network/components/router/router_model.cc | NoCModellingLab/Graphite | 1b4bb98f5bfb96ca394b71e7ef3e9e500a1e3997 | [
"MIT"
] | 94 | 2015-02-21T09:44:03.000Z | 2022-03-13T03:06:19.000Z | common/network/components/router/router_model.cc | NoCModellingLab/Graphite | 1b4bb98f5bfb96ca394b71e7ef3e9e500a1e3997 | [
"MIT"
] | null | null | null | common/network/components/router/router_model.cc | NoCModellingLab/Graphite | 1b4bb98f5bfb96ca394b71e7ef3e9e500a1e3997 | [
"MIT"
] | 36 | 2015-01-09T16:48:18.000Z | 2022-03-13T03:06:21.000Z | #include "router_model.h"
#include "network_model.h"
#include "network.h"
#include "utils.h"
#include "queue_model_history_list.h"
#include "queue_model_history_tree.h"
#include "log.h"
#include "time_types.h"
RouterModel::RouterModel(NetworkModel* model, double frequency, double voltage,
SInt32 num_input_ports, SInt32 num_output_ports,
SInt32 num_flits_per_port_buffer, UInt64 delay, SInt32 flit_width,
bool contention_model_enabled, string& contention_model_type)
: _model(model)
, _frequency(frequency)
, _num_input_ports(num_input_ports)
, _num_output_ports(num_output_ports)
, _delay(delay)
, _contention_model_enabled(contention_model_enabled)
, _power_model(NULL)
{
if (_contention_model_enabled)
{
_contention_model_list.resize(_num_output_ports);
for (SInt32 i = 0; i < _num_output_ports; i++)
_contention_model_list[i] = QueueModel::create(contention_model_type, /* UInt64 */ 1);
}
initializeEventCounters();
initializeContentionCounters();
if (Config::getSingleton()->getEnablePowerModeling())
{
_power_model = new RouterPowerModel(_frequency, voltage, _num_input_ports, _num_output_ports,
num_flits_per_port_buffer, flit_width);
}
}
RouterModel::~RouterModel()
{
if (Config::getSingleton()->getEnablePowerModeling())
delete _power_model;
if (_contention_model_enabled)
{
for (SInt32 i = 0; i < _num_output_ports; i++)
delete _contention_model_list[i];
}
}
void
RouterModel::processPacket(const NetPacket& pkt, SInt32 output_port,
UInt64& zero_load_delay, UInt64& contention_delay)
{
vector<SInt32> output_port_list;
if (output_port == OUTPUT_PORT_ALL)
{
for (SInt32 i = 0; i < _num_output_ports; i++)
output_port_list.push_back(i);
}
else // only 1 output port
{
output_port_list.push_back(output_port);
}
processPacket(pkt, output_port_list, zero_load_delay, contention_delay);
}
void
RouterModel::processPacket(const NetPacket& pkt, vector<SInt32>& output_port_list,
UInt64& zero_load_delay, UInt64& contention_delay)
{
if (!_model->isModelEnabled(pkt))
return;
assert( (1 <= (SInt32) output_port_list.size()) && (_num_output_ports >= (SInt32) output_port_list.size()) );
// Supposed to increment both zero_load_delay and contention_delay
UInt32 packet_length = _model->getModeledLength(pkt); // packet_length is in bits
SInt32 num_flits = _model->computeNumFlits(packet_length);
// Add to zero_load_delay
zero_load_delay += _delay;
if (_contention_model_enabled)
{
UInt64 max_queue_delay = 0;
for (vector<SInt32>::iterator it = output_port_list.begin(); it != output_port_list.end(); it++)
{
UInt64 queue_delay = _contention_model_list[*it]->computeQueueDelay(pkt.time.toCycles(_frequency), num_flits);
max_queue_delay = max<UInt64>(max_queue_delay, queue_delay);
}
// Add to contention_delay
contention_delay += max_queue_delay;
// Update Contention Counters
updateContentionCounters(max_queue_delay, output_port_list);
}
// Update Event Counters
updateEventCounters(num_flits, output_port_list);
// Update Dynamic Energy Counters
if (Config::getSingleton()->getEnablePowerModeling())
_power_model->updateDynamicEnergy(num_flits, 1, output_port_list.size());
}
void
RouterModel::initializeEventCounters()
{
_total_buffer_writes = 0;
_total_buffer_reads = 0;
_total_switch_allocator_requests = 0;
_total_crossbar_traversals.resize(_num_output_ports, 0);
}
void
RouterModel::updateEventCounters(SInt32 num_flits, vector<SInt32>& output_port_list)
{
// Increment Event Counters
_total_buffer_writes += num_flits;
_total_buffer_reads += num_flits;
_total_switch_allocator_requests += 1;
_total_crossbar_traversals[output_port_list.size()-1] += num_flits;
}
void
RouterModel::initializeContentionCounters()
{
_total_contention_delay.resize(_num_output_ports, 0);
_total_packets.resize(_num_output_ports, 0);
}
void
RouterModel::updateContentionCounters(UInt64 contention_delay, vector<SInt32>& output_port_list)
{
for (vector<SInt32>::iterator it = output_port_list.begin(); it != output_port_list.end(); it++)
{
_total_contention_delay[*it] += contention_delay;
_total_packets[*it] ++;
}
}
float
RouterModel::getAverageContentionDelay(SInt32 output_port_start, SInt32 output_port_end)
{
if (output_port_end == INVALID_PORT)
output_port_end = output_port_start;
LOG_ASSERT_ERROR(output_port_end >= output_port_start, "output_port_end(%i) < output_port_start(%i)",
output_port_end, output_port_start);
UInt64 total_contention_delay = 0;
UInt64 total_packets = 0;
for (SInt32 i = output_port_start; i <= output_port_end; i++)
{
total_contention_delay += _total_contention_delay[i];
total_packets += _total_packets[i];
}
return (total_packets > 0) ? (((float) total_contention_delay) / total_packets) : 0.0;
}
float
RouterModel::getAverageLinkUtilization(SInt32 output_port_start, SInt32 output_port_end)
{
if (output_port_end == INVALID_PORT)
output_port_end = output_port_start;
LOG_ASSERT_ERROR(output_port_end >= output_port_start, "output_port_end(%i) < output_port_start(%i)",
output_port_end, output_port_start);
float link_utilization = 0.0;
for (SInt32 i = output_port_start; i <= output_port_end; i++)
{
link_utilization += _contention_model_list[i]->getQueueUtilization();
}
link_utilization = link_utilization / (output_port_end - output_port_start + 1);
return link_utilization;
}
float
RouterModel::getPercentAnalyticalModelsUsed(SInt32 output_port_start, SInt32 output_port_end)
{
if (output_port_end == INVALID_PORT)
output_port_end = output_port_start;
LOG_ASSERT_ERROR(output_port_end >= output_port_start, "output_port_end(%i) < output_port_start(%i)",
output_port_end, output_port_start);
UInt64 total_analytical_model_requests = 0;
UInt64 total_requests = 0;
for (SInt32 i = output_port_start; i <= output_port_end; i++)
{
assert(_total_packets[i] == _contention_model_list[i]->getTotalRequests());
total_requests += _total_packets[i];
QueueModel::Type queue_model_type = _contention_model_list[i]->getType();
if (queue_model_type == QueueModel::HISTORY_LIST)
{
QueueModelHistoryList* queue_model = (QueueModelHistoryList*) _contention_model_list[i];
total_analytical_model_requests += queue_model->getTotalRequestsUsingAnalyticalModel();
}
else if (queue_model_type == QueueModel::HISTORY_TREE)
{
QueueModelHistoryTree* queue_model = (QueueModelHistoryTree*) _contention_model_list[i];
total_analytical_model_requests += queue_model->getTotalRequestsUsingAnalyticalModel();
}
}
return (total_requests > 0) ? (((float) total_analytical_model_requests * 100) / total_requests) : 0.0;
}
| 33.467593 | 119 | 0.712547 | [
"vector",
"model"
] |
169303c7c9ea0f6e409ffb2dda27828e788806b5 | 4,970 | hpp | C++ | include/Trixy/Neuro/Serializer/PolynomialRegression.hpp | Sigma-Ryden/TrixyNet | 32822be84b53785d390caa5d9f1fa19cbca5e990 | [
"MIT"
] | null | null | null | include/Trixy/Neuro/Serializer/PolynomialRegression.hpp | Sigma-Ryden/TrixyNet | 32822be84b53785d390caa5d9f1fa19cbca5e990 | [
"MIT"
] | null | null | null | include/Trixy/Neuro/Serializer/PolynomialRegression.hpp | Sigma-Ryden/TrixyNet | 32822be84b53785d390caa5d9f1fa19cbca5e990 | [
"MIT"
] | null | null | null | #ifndef TRIXY_SERIALIZER_POLYNOMIAL_REGRESSION_HPP
#define TRIXY_SERIALIZER_POLYNOMIAL_REGRESSION_HPP
#include <cstdint> // int8_t, int16_t
#include <Trixy/Neuro/Serializer/Base.hpp>
#include <Trixy/Buffer/Core.hpp>
#include <Trixy/Neuro/Detail/TrixyNetMeta.hpp>
#include <Trixy/Detail/FunctionDetail.hpp>
#include <Trixy/Neuro/Detail/MacroScope.hpp>
namespace trixy
{
TRIXY_SERIALIZER_TPL_DECLARATION
class TRIXY_SERIALIZER_TPL(meta::is_polynomial_regression)
{
public:
using Regression = Serializable;
using Vector = typename Regression::Vector;
using precision_type = typename Regression::precision_type;
using size_type = typename Regression::size_type;
private:
using meta_data_type = std::int16_t;
using byte_type = std::int8_t;
using BaseBuffer = utility::Buffer;
using BaseId = utility::Buffer::BaseTypeId;
private:
BaseBuffer buff; ///< Specialized Buffer for casting stream data
Vector W; ///< Inner weight
size_type N; ///< Size of weight vector (same as power size + 1)
meta_data_type meta; ///< 2 bytes of meta data for hold type information
public:
Serializer() : buff(), W(), N(0), meta(0) {}
void prepare(const Regression& reg);
template <class OutStream>
void serialize(OutStream& out) const;
template <class OutStream>
void serialize(OutStream& out, const Regression& reg) const;
template <class InStream>
void deserialize(InStream& in);
const Vector& getWeight() const noexcept { return W; };
size_type getPower() const noexcept { return N; };
private:
static constexpr meta_data_type getBaseMetaData() noexcept;
template <class InStream, typename OutData>
void deserializeData(InStream& in, OutData data, size_type n, bool buffering);
};
TRIXY_SERIALIZER_TPL_DECLARATION
void TRIXY_SERIALIZER_TPL(meta::is_polynomial_regression)::prepare(const Regression& reg)
{
W = reg.getInnerWeight();
N = reg.getInnerPower();
}
TRIXY_SERIALIZER_TPL_DECLARATION
template <class OutStream>
void TRIXY_SERIALIZER_TPL(meta::is_polynomial_regression)::serialize(OutStream& out) const
{
meta_data_type xmeta = getBaseMetaData();
out.write(detail::const_byte_cast(&xmeta), 2); // writing 2 bytes of meta data
out.write(detail::const_byte_cast(&N), sizeof(size_type));
out.write(detail::const_byte_cast(W.data()), sizeof(precision_type) * W.size());
}
TRIXY_SERIALIZER_TPL_DECLARATION
template <class OutStream>
void TRIXY_SERIALIZER_TPL(meta::is_polynomial_regression)::serialize(
OutStream& out, const Regression& reg) const
{
meta_data_type xmeta = getBaseMetaData();
out.write(detail::const_byte_cast(&xmeta), 2); // writing 2 bytes of meta data
size_type n = reg.getInnerPower();
out.write(detail::const_byte_cast(&n), sizeof(size_type));
out.write(
detail::const_byte_cast(reg.getInnerWeight().data()),
sizeof(precision_type) * reg.getInnerWeight().size()
);
}
TRIXY_SERIALIZER_TPL_DECLARATION
template <class InStream>
void TRIXY_SERIALIZER_TPL(meta::is_polynomial_regression)::deserialize(InStream& in)
{
in.read(detail::byte_cast(&meta), 2); // reading 2 bytes of meta data
byte_type meta_size_type = meta >> 8;
byte_type meta_precision_type = meta & 0x00FF;
bool buffering;
buffering = (sizeof(size_type) != meta_size_type);
if (buffering) buff.set(BaseId::Unsigned, meta_size_type);
deserializeData(in, &N, 1, buffering);
W.resize(N + 1);
buffering = (sizeof(precision_type) != meta_precision_type);
if (buffering) buff.set(BaseId::Float, meta_precision_type);
deserializeData(in, W.data(), W.size(), buffering);
}
TRIXY_SERIALIZER_TPL_DECLARATION
constexpr typename TRIXY_SERIALIZER_TPL(meta::is_polynomial_regression)::meta_data_type
TRIXY_SERIALIZER_TPL(meta::is_polynomial_regression)::getBaseMetaData() noexcept
{
using M = meta_data_type;
return (static_cast<M>(sizeof(size_type)) << 8)
+ static_cast<M>(sizeof(precision_type));
}
TRIXY_SERIALIZER_TPL_DECLARATION
template <class InStream, typename OutData>
void TRIXY_SERIALIZER_TPL(meta::is_polynomial_regression)::deserializeData(
InStream& in, OutData data, size_type n, bool buffering)
{
using Data = meta::deref<OutData>; // dereferencing OutData type
if (buffering)
{
// you MUST pre-define offset for buffer before
size_type memory_size = n * buff.offset();
buff.reserve(memory_size);
in.read(buff.data(), memory_size); // write from stream to buffer
buff.read(data, memory_size); // write from buffer to data
}
else
{
size_type memory_size = n * sizeof(Data);
in.read(reinterpret_cast<char*>(data), memory_size);
}
}
} // namespace trixy
#include <Trixy/Neuro/Detail/MacroUnscope.hpp>
#endif // TRIXY_SERIALIZER_POLYNOMIAL_REGRESSION_HPP
| 30.121212 | 90 | 0.715091 | [
"vector"
] |
1698639516a8eda5dc7b1d5377ab3c11cb082f9a | 14,264 | cpp | C++ | Samples/VirtualCamera/VirtualCameraTest/VCamUtils.cpp | microsoft/Windows-Camera | 038580e7bebabc67aded3db5f80aa17159ab1c71 | [
"MIT"
] | 70 | 2019-07-05T18:01:10.000Z | 2022-03-27T02:42:32.000Z | Samples/VirtualCamera/VirtualCameraTest/VCamUtils.cpp | QPC-database/Windows-Camera | b6b0b8ee7f312671b48589c28392322d978b803c | [
"MIT"
] | 13 | 2019-05-16T02:52:02.000Z | 2021-11-02T06:58:27.000Z | Samples/VirtualCamera/VirtualCameraTest/VCamUtils.cpp | QPC-database/Windows-Camera | b6b0b8ee7f312671b48589c28392322d978b803c | [
"MIT"
] | 33 | 2019-05-23T01:05:21.000Z | 2022-03-15T00:53:57.000Z | //
// Copyright (C) Microsoft Corporation. All rights reserved.
//
#include "pch.h"
#include "VCamUtils.h"
#include "MediaCaptureUtils.h"
const winrt::hstring _DEVPKEY_DeviceInterface_FriendlyName(L"{026e516e-b814-414b-83cd-856d6fef4822} 2");
const winrt::hstring _DEVPKEY_DeviceInterface_IsVirtualCamera(L"{6EDC630D-C2E3-43B7-B2D1-20525A1AF120} 3");
const winrt::hstring _DEVPKEY_DeviceInterface_VCamCreate_SourceId(L"{6ac1fbf7-45f7-4e06-bda7-f817ebfa04d1}, 4");
const winrt::hstring _DEVPKEY_DeviceInterface_VCamCreate_FriendlyName(L"{6ac1fbf7-45f7-4e06-bda7-f817ebfa04d1}, 5");
HRESULT VCamUtils::GetDeviceInterfaceProperty(
_In_z_ LPCWSTR pwszDevSymLink,
_In_ const DEVPROPKEY& Key,
_In_ DEVPROPTYPE requiredType,
_Out_ wistd::unique_ptr<BYTE[]>& spBuffer,
_Out_ ULONG& cbData
)
{
RETURN_HR_IF_NULL(E_INVALIDARG, pwszDevSymLink);
cbData = 0;
DEVPROPTYPE propType = 0;
ULONG propSize = 0;
CONFIGRET cr = CM_Get_Device_Interface_Property(pwszDevSymLink, &Key, &propType, nullptr, &propSize, 0);
if (cr != CR_BUFFER_SMALL)
{
RETURN_IF_FAILED(HRESULT_FROM_WIN32(CM_MapCrToWin32Err(cr, ERROR_INVALID_DATA)));
}
if (propType != requiredType)
{
wprintf(L"unexpected proptype: %d (expected: %d)\n", propType, requiredType);
RETURN_IF_FAILED(HRESULT_FROM_WIN32(ERROR_INVALID_DATA));
}
if (cr == CR_BUFFER_SMALL)
{
spBuffer = wil::make_unique_nothrow<BYTE[]>(propSize);
cbData = propSize;
cr = CM_Get_Device_Interface_Property(pwszDevSymLink, &Key, &propType, (PBYTE)spBuffer.get(), &propSize, 0);
}
RETURN_IF_FAILED(HRESULT_FROM_WIN32(CM_MapCrToWin32Err(cr, ERROR_INVALID_DATA)));
return S_OK;
}
HRESULT VCamUtils::GetDeviceInterfaceRegistryEntry(
_In_ LPCWSTR pwszDevSymLink,
_In_ LPCWSTR pwszKeyName,
_Out_ wistd::unique_ptr<BYTE[]>& spBuffer,
_Out_ ULONG& cbData)
{
RETURN_HR_IF_NULL(E_INVALIDARG, pwszDevSymLink);
RETURN_HR_IF_NULL(E_INVALIDARG, pwszKeyName);
wil::unique_hkey hKey;
CONFIGRET cr = CM_Open_Device_Interface_Key(
pwszDevSymLink,
KEY_READ,
RegDisposition_OpenExisting,
&hKey,
0);
RETURN_IF_FAILED_MSG(HRESULT_FROM_WIN32(CM_MapCrToWin32Err(cr, ERROR_INVALID_DATA)), "Failed to get device interface reg key");
DWORD dwType = 0;
LONG lResult = RegQueryValueEx(hKey.get(), pwszKeyName, nullptr, &dwType, nullptr, &cbData);
RETURN_IF_FAILED_MSG(HRESULT_FROM_WIN32(lResult), "Failed to get reg key: %s", pwszKeyName);
spBuffer = wil::make_unique_nothrow<BYTE[]>(cbData);
lResult = RegQueryValueEx(hKey.get(), pwszKeyName, nullptr, &dwType, spBuffer.get(), &cbData);
RETURN_IF_FAILED_MSG(HRESULT_FROM_WIN32(lResult), "Failed to get reg key: %s", pwszKeyName);
return S_OK;
}
bool VCamUtils::IsVirtualCamera(winrt::hstring const& strDevSymLink)
{
bool isVCam = false;
winrt::Windows::Foundation::IReference<bool> val;
if (SUCCEEDED(CMediaCaptureUtils::GetDeviceProperty(strDevSymLink, _DEVPKEY_DeviceInterface_IsVirtualCamera, DeviceInformationKind::DeviceInterface, val)))
{
isVCam = val.Value();
}
return isVCam;
}
HRESULT VCamUtils::RegisterVirtualCamera(
_In_ winrt::hstring const& strMediaSource,
_In_ winrt::hstring const& strFriendlyName,
_In_ winrt::hstring const& strPhysicalCamSymLink,
_In_opt_ IMFAttributes* pAttributes,
_Outptr_ IMFVirtualCamera** ppVirtualCamera)
{
RETURN_HR_IF_NULL(E_POINTER, ppVirtualCamera);
LOG_COMMENT(L"Register virtual camera...");
LOG_COMMENT(L"device string: %s ", strMediaSource.data());
LOG_COMMENT(L"friendly name: %s ", strFriendlyName.data());
MFVirtualCameraType vcamType = MFVirtualCameraType_SoftwareCameraSource;
MFVirtualCameraLifetime vcamLifetime = MFVirtualCameraLifetime_System;
MFVirtualCameraAccess vcamAccess = MFVirtualCameraAccess_CurrentUser;
wil::com_ptr_nothrow<IMFVirtualCamera> spVirtualCamera;
RETURN_IF_FAILED(MFCreateVirtualCamera(
vcamType,
vcamLifetime,
vcamAccess,
strFriendlyName.data(),
strMediaSource.data(),
nullptr, /*Catetgorylist*/
0, /*CatetgoryCount*/
&spVirtualCamera));
RETURN_HR_IF_NULL_MSG(E_POINTER, spVirtualCamera.get(), "Fail to create virtual camera");
if(!strPhysicalCamSymLink.empty())
{
LOG_COMMENT(L"Add physical cam: %s ", strPhysicalCamSymLink.data());
RETURN_IF_FAILED(spVirtualCamera->AddDeviceSourceInfo(strPhysicalCamSymLink.data()));
}
if (pAttributes)
{
uint32_t cItems = 0;
RETURN_IF_FAILED(pAttributes->GetCount(&cItems));
LOG_COMMENT(L"Set attributes on virtual cameras: %d items ", cItems);
for (uint32_t i = 0; i < cItems; i++)
{
wil::unique_prop_variant prop;
GUID guidKey = GUID_NULL;
RETURN_IF_FAILED(pAttributes->GetItemByIndex(i, &guidKey, &prop));
LOG_COMMENT(L"%i - %s ", i, winrt::to_hstring(guidKey).data());
RETURN_IF_FAILED(spVirtualCamera->SetItem(guidKey, prop));
}
}
LOG_COMMENT(L"Succeeded (%p)! ", spVirtualCamera.get());
try
{
AppInfo appInfo = winrt::Windows::ApplicationModel::AppInfo::Current();
LOG_COMMENT(L"AppInfo: %p ", appInfo);
if (appInfo != nullptr)
{
LOG_COMMENT(L"PFN: %s ", appInfo.PackageFamilyName().data());
}
}
catch (winrt::hresult_error) { LOG_WARNING(L"not running in app package"); }
HRESULT hr = spVirtualCamera->AddProperty(
&DEVPKEY_DeviceInterface_VCamCreate_SourceId,
DEVPROP_TYPE_STRING,
(BYTE*)strMediaSource.data(),
sizeof(winrt::hstring::value_type)*(strMediaSource.size()+1));
if (hr == HRESULT_FROM_WIN32(ERROR_ACCESS_DENIED))
{
LOG_WARNING(L"Please run application in elevated mode");
return hr;
}
RETURN_IF_FAILED_MSG(hr, "Fail to addproperty - DEVPKEY_DeviceInterface_VCamCreate_SourceId ");
RETURN_IF_FAILED_MSG(spVirtualCamera->AddProperty(
&DEVPKEY_DeviceInterface_VCamCreate_FriendlyName,
DEVPROP_TYPE_STRING,
(BYTE*)strFriendlyName.data(),
sizeof(winrt::hstring::value_type) * (strFriendlyName.size() + 1)),
"Fail to addproperty - DEVPKEY_DeviceInterface_VCamCreate_FriendlyName ");
LOG_COMMENT(L"Start camera ");
RETURN_IF_FAILED(spVirtualCamera->Start(nullptr));
LOG_COMMENT(L"Succeeded!");
*ppVirtualCamera = spVirtualCamera.detach();
return S_OK;
}
HRESULT VCamUtils::UnInstallVirtualCamera(
_In_ winrt::hstring const& strDevSymLink)
{
LOG_COMMENT(L"Removing device: %s", strDevSymLink.data());
winrt::Windows::Foundation::IReference<winrt::hstring> friendlyName;
RETURN_IF_FAILED(CMediaCaptureUtils::GetDeviceProperty(strDevSymLink, _DEVPKEY_DeviceInterface_VCamCreate_FriendlyName, DeviceInformationKind::DeviceInterface, friendlyName));
RETURN_HR_IF_NULL(E_INVALIDARG, friendlyName);
LOG_COMMENT(L"friendlyname: %s", friendlyName.Value().data());
winrt::Windows::Foundation::IReference<winrt::hstring> sourceId;
RETURN_IF_FAILED(CMediaCaptureUtils::GetDeviceProperty(strDevSymLink, _DEVPKEY_DeviceInterface_VCamCreate_SourceId, DeviceInformationKind::DeviceInterface, sourceId));
RETURN_HR_IF_NULL(E_INVALIDARG, sourceId);
LOG_COMMENT(L"sourceId: %s", sourceId.Value().data());
wil::com_ptr_nothrow<IMFVirtualCamera> spVirtualCamera;
RETURN_IF_FAILED(MFCreateVirtualCamera(
MFVirtualCameraType_SoftwareCameraSource,
MFVirtualCameraLifetime_System, /*MFVirtualCameraLifetime_Session,*/
MFVirtualCameraAccess_CurrentUser, /*MFVirtualCameraAccess_System,*/ // access_denied on enabled.
friendlyName.Value().data(),
sourceId.Value().data(),
nullptr, /*Catetgorylist*/
0, /*CatetgoryCount*/
&spVirtualCamera));
RETURN_HR_IF_NULL_MSG(E_FAIL, spVirtualCamera.get(), "Fail to create virtual camera");
LOG_COMMENT(L"remove virtual camera");
RETURN_IF_FAILED(spVirtualCamera->Remove());
RETURN_IF_FAILED(spVirtualCamera->Shutdown());
LOG_COMMENT(L"succeeded!");
return S_OK;
}
HRESULT VCamUtils::UnInstallDevice(IMFVirtualCamera* pVirtualCamera)
{
wil::unique_cotaskmem_string spwszSymLink;
UINT32 cch = 0;
RETURN_IF_FAILED(pVirtualCamera->GetAllocatedString(MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_SYMBOLIC_LINK, &spwszSymLink, &cch));
RETURN_IF_FAILED(UnInstallDeviceWin32(spwszSymLink.get()));
return S_OK;
}
HRESULT VCamUtils::UnInstallDeviceWin32(const wchar_t* pwszDeviceSymLink)
{
LOG_COMMENT(L"Uninstalling device: %s ", pwszDeviceSymLink);
wistd::unique_ptr<BYTE[]> spBuffer;
ULONG cbBufferSize = 0;
RETURN_IF_FAILED_MSG(VCamUtils::GetDeviceInterfaceProperty(
pwszDeviceSymLink,
DEVPKEY_Device_InstanceId,
DEVPROP_TYPE_STRING,
spBuffer,
cbBufferSize),
"Fail to get device instanceId");
DEVINST hDevInstance;
CONFIGRET cr = CM_Locate_DevNode(&hDevInstance, (wchar_t*)spBuffer.get(), CM_LOCATE_DEVNODE_NORMAL | CM_LOCATE_DEVNODE_PHANTOM);
RETURN_IF_FAILED_MSG(HRESULT_FROM_WIN32(CM_MapCrToWin32Err(cr, ERROR_INVALID_DATA)), "Failed to locate devNode");
wchar_t vetoString[MAX_PATH] = { 0 };
PNP_VETO_TYPE vetoType = PNP_VetoTypeUnknown;
cr = CM_Query_And_Remove_SubTree(hDevInstance, &vetoType, vetoString, MAX_PATH, CM_REMOVE_NO_RESTART);
RETURN_IF_FAILED_MSG(HRESULT_FROM_WIN32(CM_MapCrToWin32Err(cr, ERROR_INVALID_DATA)), "Failed to CM_Query_And_Remove_SubTree");
cr = CM_Uninstall_DevNode(hDevInstance, 0);
RETURN_IF_FAILED_MSG(HRESULT_FROM_WIN32(CM_MapCrToWin32Err(cr, ERROR_INVALID_DATA)), "Failed to CM_Uninstall_DevNode");
LOG_COMMENT(L"succeeded");
return S_OK;
}
HRESULT VCamUtils::MSIUninstall(GUID const& clsid)
{
wil::com_ptr_nothrow<IMFAttributes> spAttributes;
wil::unique_cotaskmem_array_ptr<wil::com_ptr_nothrow<IMFActivate>> spActivates;
UINT32 numActivates = 0;
RETURN_IF_FAILED(MFCreateAttributes(&spAttributes, 1));
RETURN_IF_FAILED(spAttributes->SetGUID(MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE, MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_GUID));
RETURN_IF_FAILED(spAttributes->SetGUID(MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_CATEGORY, KSCATEGORY_VIDEO_CAMERA));
RETURN_IF_FAILED(MFEnumDeviceSources(spAttributes.get(), &spActivates, &numActivates));
for (unsigned int i = 0; i < numActivates; i++)
{
wil::com_ptr_nothrow<IMFActivate>spActivate = spActivates[i];
wil::unique_cotaskmem_string spwszSymLink;
UINT32 cch = 0;
RETURN_IF_FAILED(spActivate->GetAllocatedString(MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_SYMBOLIC_LINK, &spwszSymLink, &cch));
wistd::unique_ptr<BYTE[]> spBuffer;
ULONG cbBufferSize = 0;
if (SUCCEEDED(VCamUtils::GetDeviceInterfaceRegistryEntry(
spwszSymLink.get(),
L"CustomCaptureSourceClsid",
spBuffer,
cbBufferSize)))
{
if (_wcsicmp((LPCWSTR)spBuffer.get(), winrt::to_hstring(clsid).data()) == 0)
{
VCamUtils::UnInstallDeviceWin32(spwszSymLink.get());
}
}
}
return S_OK;
}
HRESULT VCamUtils::GetCameraActivate(const wchar_t* pwszSymLink, IMFActivate** ppActivate)
{
wil::com_ptr_nothrow<IMFAttributes> spAttributes;
IMFActivate** ppActivates;
wil::unique_cotaskmem_array_ptr<wil::com_ptr_nothrow<IMFActivate>> spActivates;
UINT32 numActivates = 0;
RETURN_HR_IF_NULL(E_POINTER, ppActivate);
RETURN_IF_FAILED(MFCreateAttributes(&spAttributes, 1));
RETURN_IF_FAILED(spAttributes->SetGUID(MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE, MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_GUID));
RETURN_IF_FAILED(spAttributes->SetGUID(MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_CATEGORY, KSCATEGORY_VIDEO_CAMERA));
RETURN_IF_FAILED(MFEnumDeviceSources(spAttributes.get(), &ppActivates, &numActivates));
spActivates.reset(ppActivates, numActivates);
for (unsigned int i = 0; i < numActivates; i++)
{
wil::com_ptr_nothrow<IMFActivate>spActivate = spActivates[i];
wil::unique_cotaskmem_string spszSymLink;
UINT32 cch = 0;
RETURN_IF_FAILED(spActivate->GetAllocatedString(MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_SYMBOLIC_LINK, &spszSymLink, &cch));
if (_wcsicmp(spszSymLink.get(), pwszSymLink) == 0)
{
RETURN_IF_FAILED(spActivate.copy_to(ppActivate));
return S_OK;
}
}
return MF_E_UNSUPPORTED_CAPTURE_DEVICE_PRESENT;
}
HRESULT VCamUtils::InitializeVirtualCamera(const wchar_t* pwszSymLink, IMFMediaSource** ppMediaSource)
{
wil::com_ptr_nothrow<IMFActivate> spActivate;
RETURN_IF_FAILED(GetCameraActivate(pwszSymLink, &spActivate));
LOG_COMMENT(L"Activate virtualcamera %s", pwszSymLink);
RETURN_IF_FAILED(spActivate->ActivateObject(IID_PPV_ARGS(ppMediaSource)));
return S_OK;
}
//
// Return list of installed VirtualCamera
//
HRESULT VCamUtils::GetVirtualCamera(std::vector<DeviceInformation>& vcamList)
{
vcamList.clear();
winrt::Windows::Devices::Enumeration::DeviceInformationCollection devList{ nullptr };
RETURN_IF_FAILED(CMediaCaptureUtils::GetDeviceList(MediaDevice::GetVideoCaptureSelector(), devList));
for (uint32_t i = 0; i < devList.Size(); i++)
{
auto dev = devList.GetAt(i);
if (IsVirtualCamera(dev.Id().data()))
{
vcamList.push_back(dev);
}
}
return S_OK;
}
HRESULT VCamUtils::GetPhysicalCameras(std::vector<DeviceInformation>& physicalCamList)
{
physicalCamList.clear();
winrt::Windows::Devices::Enumeration::DeviceInformationCollection devList{ nullptr };
RETURN_IF_FAILED(CMediaCaptureUtils::GetDeviceList(MediaDevice::GetVideoCaptureSelector(), devList));
for (uint32_t i = 0; i < devList.Size(); i++)
{
auto dev = devList.GetAt(i);
if (!IsVirtualCamera(dev.Id().data()))
{
physicalCamList.push_back(dev);
}
}
return S_OK;
}
| 38.241287 | 179 | 0.719223 | [
"vector"
] |
169be155eb6b9baf317558b3ac4e43c220de927e | 3,965 | hpp | C++ | src/common/flat_containers/flat_multimap.hpp | criminalx/Source-X | 7e656bb9edcbe78dd735feeb12a9ccff3b0f2fe3 | [
"Apache-2.0"
] | 40 | 2017-07-08T03:35:36.000Z | 2022-02-16T06:03:58.000Z | src/common/flat_containers/flat_multimap.hpp | criminalx/Source-X | 7e656bb9edcbe78dd735feeb12a9ccff3b0f2fe3 | [
"Apache-2.0"
] | 435 | 2020-01-20T12:50:15.000Z | 2022-03-29T03:31:27.000Z | src/common/flat_containers/flat_multimap.hpp | criminalx/Source-X | 7e656bb9edcbe78dd735feeb12a9ccff3b0f2fe3 | [
"Apache-2.0"
] | 47 | 2020-01-21T23:25:38.000Z | 2022-03-24T21:54:32.000Z | // Copyright Pubby 2016
// Distributed under the Boost Software License, Version 1.0.
// http://www.boost.org/LICENSE_1_0.txt
#ifndef LIB_FLAT_FLAT_MULTIMAP_HPP
#define LIB_FLAT_FLAT_MULTIMAP_HPP
#include "impl/flat_impl.hpp"
namespace fc {
namespace impl {
template<typename D, typename Key, typename Container, typename Compare,
typename = void>
class flat_multimap_base
: public flat_container_base<D, Key, Container, Compare>
{
#include "impl/container_traits.hpp"
using mapped_type = typename value_type::second_type;
using B = flat_container_base<D, Key, Container, Compare>;
D const* self() const { return static_cast<D const*>(this); }
D* self() { return static_cast<D*>(this); }
public:
using value_compare = first_compare<value_type, Compare>;
value_compare value_comp() const { return value_compare(B::key_comp()); }
using B::insert;
using B::erase;
// Modifiers
iterator insert(value_type const& value)
{
iterator it = self()->upper_bound(value.first);
return self()->container.insert(it.underlying, value);
}
iterator insert(value_type&& value)
{
iterator it = self()->upper_bound(value.first);
return self()->container.insert(it.underlying, std::move(value));
}
template<class InputIt>
void insert(InputIt first, InputIt last, delay_sort_t)
{ this->ds_insert_(first, last); }
size_type erase(key_type const& key)
{
auto it_pair = self()->equal_range(key);
std::size_t ret = std::distance(it_pair.first, it_pair.second);
self()->container.erase(it_pair.first.underlying,
it_pair.second.underlying);
return ret;
}
// Lookup
size_type count(key_type const& key) const
{
auto it_pair = self()->equal_range(key);
return std::distance(it_pair.first, it_pair.second);
}
};
template<typename D, typename Key, typename Container, typename Compare>
class flat_multimap_base<D, Key, Container, Compare,
std::void_t<typename Compare::is_transparent>>
: public flat_multimap_base<D, Key, Container, Compare, int>
{
#include "impl/container_traits.hpp"
using mapped_type = typename value_type::second_type;
using B = flat_multimap_base<D, Key, Container, Compare, int>;
D const* self() const { return static_cast<D const*>(this); }
D* self() { return static_cast<D*>(this); }
public:
using B::insert;
using B::count;
// Modifiers
template<class P>
iterator insert(P&& value)
{
iterator it = self()->upper_bound(value.first);
return self()->container.insert(it.underlying,
std::forward<P>(value));
}
// Lookup
template<typename K>
size_type count(K const& key) const
{
auto it_pair = self()->equal_range(key);
return std::distance(it_pair.first, it_pair.second);
}
};
} // namespace impl
template<typename Container, typename Compare = std::less<void>>
class flat_multimap
: public impl::flat_multimap_base<flat_multimap<Container, Compare>,
typename Container::value_type::first_type, Container, Compare>
{
#define FLATNAME flat_multimap
#define FLATKEY typename Container::value_type::first_type
#include "impl/class_def.hpp"
#undef FLATNAME
#undef FLATKEY
};
template<typename Key, typename T, typename Compare = std::less<void>>
using vector_multimap
= flat_multimap<std::vector<std::pair<Key, T>>, Compare>;
template<typename Container, typename Compare>
inline bool operator==(const flat_multimap<Container, Compare>& lhs, const flat_multimap<Container, Compare>& rhs)
{
return lhs.container == rhs.container;
}
template<typename Container, typename Compare>
inline bool operator!=(const flat_multimap<Container, Compare>& lhs, const flat_multimap<Container, Compare>& rhs)
{
return lhs.container != rhs.container;
}
} // namespace fc
#endif
| 29.589552 | 114 | 0.683985 | [
"vector"
] |
169c7ac362b13beada5a7e35da43b2ba2e919981 | 2,926 | cpp | C++ | src/daemon/ops/metadentry.cpp | jeanbez/gekko-fwd | d62be5480224ea5116b513f38a3fa3ae7754f8a8 | [
"MIT"
] | 1 | 2022-02-01T01:01:28.000Z | 2022-02-01T01:01:28.000Z | src/daemon/ops/metadentry.cpp | jeanbez/gekko-fwd | d62be5480224ea5116b513f38a3fa3ae7754f8a8 | [
"MIT"
] | null | null | null | src/daemon/ops/metadentry.cpp | jeanbez/gekko-fwd | d62be5480224ea5116b513f38a3fa3ae7754f8a8 | [
"MIT"
] | null | null | null | /*
Copyright 2018-2020, Barcelona Supercomputing Center (BSC), Spain
Copyright 2015-2020, Johannes Gutenberg Universitaet Mainz, Germany
This software was partially supported by the
EC H2020 funded project NEXTGenIO (Project ID: 671951, www.nextgenio.eu).
This software was partially supported by the
ADA-FS project under the SPPEXA project funded by the DFG.
SPDX-License-Identifier: MIT
*/
#include <daemon/ops/metadentry.hpp>
#include <daemon/backend/metadata/db.hpp>
#include <daemon/backend/data/chunk_storage.hpp>
using namespace std;
namespace gkfs {
namespace metadata {
/**
* Returns the metadata of an object at a specific path. The metadata can be of dummy values if configured
* @param path
* @param attr
* @return
*/
Metadata get(const std::string& path) {
return Metadata(get_str(path));
}
/**
* Get metadentry string only for path
* @param path
* @return
*/
std::string get_str(const std::string& path) {
return GKFS_DATA->mdb()->get(path);
}
/**
* Gets the size of a metadentry
* @param path
* @param ret_size (return val)
* @return err
*/
size_t get_size(const string& path) {
return get(path).size();
}
/**
* Returns a vector of directory entries for given directory
* @param dir
* @return
*/
std::vector<std::pair<std::string, bool>> get_dirents(const std::string& dir) {
return GKFS_DATA->mdb()->get_dirents(dir);
}
/**
* Creates metadata (if required) and dentry at the same time
* @param path
* @param mode
*/
void create(const std::string& path, Metadata& md) {
// update metadata object based on what metadata is needed
if (GKFS_DATA->atime_state() || GKFS_DATA->mtime_state() || GKFS_DATA->ctime_state()) {
std::time_t time;
std::time(&time);
auto time_s = fmt::format_int(time).str();
if (GKFS_DATA->atime_state())
md.atime(time);
if (GKFS_DATA->mtime_state())
md.mtime(time);
if (GKFS_DATA->ctime_state())
md.ctime(time);
}
GKFS_DATA->mdb()->put(path, md.serialize());
}
/**
* Update metadentry by given Metadata object and path
* @param path
* @param md
*/
void update(const string& path, Metadata& md) {
GKFS_DATA->mdb()->update(path, path, md.serialize());
}
/**
* Updates a metadentry's size atomically and returns the corresponding size after update
* @param path
* @param io_size
* @return the updated size
*/
void update_size(const string& path, size_t io_size, off64_t offset, bool append) {
GKFS_DATA->mdb()->increase_size(path, io_size + offset, append);
}
/**
* Remove metadentry if exists and try to remove all chunks for path
* @param path
* @return
*/
void remove_node(const string& path) {
GKFS_DATA->mdb()->remove(path); // remove metadentry
GKFS_DATA->storage()->destroy_chunk_space(path); // destroys all chunks for the path on this node
}
} // namespace metadata
} // namespace gkfs | 25.666667 | 106 | 0.681135 | [
"object",
"vector"
] |
16a04cd25915e90d2339deb1f4c1660a32dd4f80 | 808 | hpp | C++ | Myfunctions.hpp | wangziyinx/Stream-Clustering-with-Dynamic-Estimation-of-Emerging-Local-Densities_cpp | 818774665488a5958e8bb68e51efb0376efd8ac1 | [
"AFL-2.1"
] | 1 | 2019-10-12T17:19:35.000Z | 2019-10-12T17:19:35.000Z | Myfunctions.hpp | wangziyinx/Stream-Clustering-with-Dynamic-Estimation-of-Emerging-Local-Densities_cpp | 818774665488a5958e8bb68e51efb0376efd8ac1 | [
"AFL-2.1"
] | null | null | null | Myfunctions.hpp | wangziyinx/Stream-Clustering-with-Dynamic-Estimation-of-Emerging-Local-Densities_cpp | 818774665488a5958e8bb68e51efb0376efd8ac1 | [
"AFL-2.1"
] | 1 | 2021-10-31T09:33:21.000Z | 2021-10-31T09:33:21.000Z | //
// Myfunctions.hpp
// Clustering001
//
// Created by Wang Ziyin on 5/28/18.
// Copyright © 2018 Wang Ziyin. All rights reserved.
//
#ifndef Myfunctions_hpp
#define Myfunctions_hpp
#include <stdio.h>
#include <vector>
#include <iostream>
#include <fstream>
#include <string>
#include <math.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <ctime>
using namespace std;
double similarity_measure(double *x, double *y, string opt, int dim);
double cosine_similarity(double *a, double *b, int dim);
void histogram (vector <int > &A, vector<double> &H , int max_bin);
int vec_min(vector<double > A);
int vec_max(vector<double > A);
int read_data(string file_name, vector<double *> &Data);
vector<string> string_split(string a, string del);
#endif /* Myfunctions_hpp */
| 20.2 | 69 | 0.714109 | [
"vector"
] |
16b3ecdeb1357a4f0eb55e0ff751dc5ec25304c7 | 342 | cpp | C++ | LeetCode/problems/Rotate Array/main.cpp | object-oriented-human/competitive | 9e761020e887d8980a39a64eeaeaa39af0ecd777 | [
"MIT"
] | 1 | 2022-02-21T15:43:01.000Z | 2022-02-21T15:43:01.000Z | LeetCode/problems/Rotate Array/main.cpp | foooop/competitive | 9e761020e887d8980a39a64eeaeaa39af0ecd777 | [
"MIT"
] | null | null | null | LeetCode/problems/Rotate Array/main.cpp | foooop/competitive | 9e761020e887d8980a39a64eeaeaa39af0ecd777 | [
"MIT"
] | null | null | null | class Solution {
public:
void rotate(vector<int>& nums, int k) {
k %= nums.size();
vector<int> V;
for (int i = nums.size()-k; i < nums.size(); i++) {
V.push_back(nums[i]);
}
for (int i = 0; i < nums.size()-k; i++) {
V.push_back(nums[i]);
}
nums = V;
}
}; | 24.428571 | 59 | 0.423977 | [
"vector"
] |
16b4ca711c52f64f31a4b148b07e9ef6c942320a | 5,980 | cpp | C++ | emdconv.cpp | afiskon/cpp-opengl-models | 6e8707cf82d01bf13abf8cc5a88e286ec35087c5 | [
"MIT"
] | 8 | 2015-12-15T00:36:02.000Z | 2021-06-16T10:30:54.000Z | emdconv.cpp | afiskon/cpp-opengl-models | 6e8707cf82d01bf13abf8cc5a88e286ec35087c5 | [
"MIT"
] | null | null | null | emdconv.cpp | afiskon/cpp-opengl-models | 6e8707cf82d01bf13abf8cc5a88e286ec35087c5 | [
"MIT"
] | 3 | 2017-09-30T19:12:43.000Z | 2021-06-15T19:11:23.000Z | #include <GLXW/glxw.h>
#include <iostream>
#include <vector>
#include <defer.h>
#include "../assimp/include/assimp/Importer.hpp"
#include "../assimp/include/assimp/postprocess.h"
#include "../assimp/include/assimp/scene.h"
#include "utils/models.h"
GLfloat* importedModelCreate(const char* fname, unsigned int meshNumber, size_t* outVerticesBufferSize, unsigned int* outVerticesNumber) {
*outVerticesBufferSize = 0;
*outVerticesNumber = 0;
Assimp::Importer importer;
const aiScene* scene = importer.ReadFile(fname, aiProcess_CalcTangentSpace | aiProcess_Triangulate | aiProcess_JoinIdenticalVertices | aiProcess_SortByPType);
if(scene == nullptr) {
std::cerr << "Failed to load model " << fname << std::endl;
return nullptr;
}
if(scene->mNumMeshes <= meshNumber) {
std::cerr << "There is no mesh #" << meshNumber << " in model (" << scene->mNumMeshes << " only), fname = " << fname << std::endl;
return nullptr;
}
aiMesh* mesh = scene->mMeshes[meshNumber];
unsigned int facesNum = mesh->mNumFaces;
// unsigned int verticesNum = mesh->mNumVertices;
*outVerticesNumber = facesNum*3;
if(mesh->mTextureCoords[0] == nullptr) {
std::cerr << "mesh->mTextureCoords[0] == nullptr, fname = " << fname << std::endl;
return nullptr;
}
*outVerticesBufferSize = facesNum*sizeof(GLfloat)* 5 /* coordinates per vertex */ * 3 /* 3 vertices per face */;
GLfloat* verticesBuffer = (GLfloat*)malloc(*outVerticesBufferSize);
unsigned int verticesBufferIndex = 0;
for(unsigned int i = 0; i < facesNum; ++i) {
const aiFace& face = mesh->mFaces[i];
if(face.mNumIndices != 3) {
std::cerr << "face.numIndices = " << face.mNumIndices << " (3 expected), i = " << i << ", fname = " << fname << std::endl;
free(verticesBuffer);
return nullptr;
}
for(unsigned int j = 0; j < face.mNumIndices; ++j) {
unsigned int index = face.mIndices[j];
aiVector3D pos = mesh->mVertices[index];
aiVector3D uv = mesh->mTextureCoords[0][index];
// aiVector3D normal = mesh->mNormals[index];
verticesBuffer[verticesBufferIndex++] = pos.x;
verticesBuffer[verticesBufferIndex++] = pos.y;
verticesBuffer[verticesBufferIndex++] = pos.z;
verticesBuffer[verticesBufferIndex++] = uv.x;
verticesBuffer[verticesBufferIndex++] = 1.0f - uv.y;
}
}
return verticesBuffer;
}
bool importedModelSave(const char* fname, GLfloat* verticesBuffer, unsigned int verticesNumber) {
std::vector<GLfloat> vertices;
std::vector<unsigned int> indices;
unsigned int usedIndices = 0;
unsigned const int floatsPerVertex = 5; // 3 coordinates + UV
const GLfloat eps = 0.00001f;
for(unsigned int vtx = 0; vtx < verticesNumber; ++vtx) {
GLfloat currentX = verticesBuffer[vtx* floatsPerVertex +0];
GLfloat currentY = verticesBuffer[vtx* floatsPerVertex +1];
GLfloat currentZ = verticesBuffer[vtx* floatsPerVertex +2];
GLfloat currentU = verticesBuffer[vtx* floatsPerVertex +3];
GLfloat currentV = verticesBuffer[vtx* floatsPerVertex +4];
unsigned int foundIndex = 0;
bool indexFound = false;
for(unsigned int idx = 0; !indexFound && idx < usedIndices; ++idx) {
GLfloat idxX = vertices[idx * floatsPerVertex + 0];
GLfloat idxY = vertices[idx * floatsPerVertex + 1];
GLfloat idxZ = vertices[idx * floatsPerVertex + 2];
GLfloat idxU = vertices[idx * floatsPerVertex + 3];
GLfloat idxV = vertices[idx * floatsPerVertex + 4];
if((fabs(currentX - idxX) < eps) && (fabs(currentY - idxY) < eps) && (fabs(currentZ - idxZ) < eps) &&
(fabs(currentU - idxU) < eps) && (fabs(currentV - idxV) < eps)) {
foundIndex = idx;
indexFound = true;
}
}
if(!indexFound) {
vertices.push_back(currentX);
vertices.push_back(currentY);
vertices.push_back(currentZ);
vertices.push_back(currentU);
vertices.push_back(currentV);
foundIndex = usedIndices;
usedIndices++;
}
indices.push_back(foundIndex);
}
unsigned char indexSize = 1;
if(verticesNumber > 255) indexSize *= 2;
if(verticesNumber > 65535) indexSize *= 2;
unsigned int modelSize = (unsigned int) (verticesNumber*floatsPerVertex*sizeof(GLfloat));
unsigned int indexedModelSize = (unsigned int) (usedIndices*floatsPerVertex*sizeof(GLfloat) + verticesNumber*indexSize);
float ratio = (float)indexedModelSize*100.0f / (float)modelSize;
std::cout << "importedModelSave - fname = " << fname << ", verticesNumber = " << verticesNumber << ", usedIndices = " << usedIndices << std::endl;
std::cout << "importedModelSave - modelSize = " << modelSize << ", indexedModelSize = " << indexedModelSize << ", ratio = " << ratio << " %" << std::endl;
return modelSave(fname, vertices.data(), usedIndices* floatsPerVertex *sizeof(GLfloat), indices.data(), verticesNumber);
}
void importedModelFree(GLfloat* model) {
free(model);
}
int main(int argc, char* argv[]) {
if(argc < 2) {
std::cout << "Usage: emdconv <input file> <output file> [mesh number]" << std::endl;
return 1;
}
char* infile = argv[1];
char* outfile = argv[2];
unsigned int meshNumber = 0;
if(argc > 3) {
meshNumber = (unsigned int) atoi(argv[3]);
}
std::cout << "Infile: " << infile << std::endl;
std::cout << "Outfile: " << outfile << std::endl;
std::cout << "Mesh number: " << meshNumber << std::endl;
unsigned int modelVerticesNumber;
size_t modelVerticesBufferSize;
GLfloat * modelVerticesBuffer = importedModelCreate(infile, meshNumber, &modelVerticesBufferSize, &modelVerticesNumber);
if(modelVerticesBuffer == nullptr) {
std::cerr << "importedModelCreate returned null" << std::endl;
return 2;
}
defer(importedModelFree(modelVerticesBuffer));
if(!importedModelSave(outfile, modelVerticesBuffer, modelVerticesNumber)) {
std::cerr << "importedModelSave failed" << std::endl;
return 3;
}
std::cout << "Done!" << std::endl;
return 0;
} | 36.463415 | 160 | 0.668562 | [
"mesh",
"vector",
"model"
] |
16bea5f7dd609ced0df5baac14e86af35a2ca24e | 1,739 | cpp | C++ | HDRFusion/Tensor.cpp | Luke092/HDRFusion | 7a0fa14d0b93a55744e6a0bab64bc833e22fa859 | [
"MIT"
] | 2 | 2018-08-13T10:37:36.000Z | 2019-06-17T13:29:09.000Z | HDRFusion/Tensor.cpp | Luke092/HDRFusion | 7a0fa14d0b93a55744e6a0bab64bc833e22fa859 | [
"MIT"
] | null | null | null | HDRFusion/Tensor.cpp | Luke092/HDRFusion | 7a0fa14d0b93a55744e6a0bab64bc833e22fa859 | [
"MIT"
] | null | null | null | /*
* Tensor.cpp
*
* Created on: 25 lug 2017
* Author: gianmaria
*/
#include "Tensor.h"
template<typename T> int sgn(T val)
{
return (T(0) < val) - (val < T(0));
}
Tensor::Tensor(vector<Derivate> I, int x, int y)
{
this->x = x;
this->y = y;
this->Ix = 0;
this->Iy = 0;
for(unsigned int i = 0; i < I.size(); i++)
{
Ix += I[i].get_Ix().at<float>(y,x);
Iy += I[i].get_Iy().at<float>(y,x);
g[0][0]+= I[i].get_Ix().at<float>(y,x) * I[i].get_Ix().at<float>(y,x);
g[0][1]+= I[i].get_Ix().at<float>(y,x) * I[i].get_Iy().at<float>(y,x);
g[1][0]+= I[i].get_Iy().at<float>(y,x) * I[i].get_Ix().at<float>(y,x);
g[1][1]+= I[i].get_Iy().at<float>(y,x) * I[i].get_Iy().at<float>(y,x);
}
// cout << "g11: " << getg11() <<
// " g12: " << getg12() <<
// " g21: " << getg21() <<
// " g22: " << getg22() << endl;
calcS();
calcE();
// cout << "S: " << S <<
// " E:" << E << endl;
}
Tensor::~Tensor()
{
// TODO Auto-generated destructor stub
}
float Tensor::getg11()
{
return g[0][0];
}
float Tensor::getg12()
{
return g[0][1];
}
float Tensor::getg21()
{
return g[1][0];
}
float Tensor::getg22()
{
return g[1][1];
}
void Tensor::calcS()
{
S = sqrtf(pow(getg11() - getg22(),2) + 4 * getg12() * getg21());
}
void Tensor::calcE()
{
E = 0.5 * (getg11() + getg22() + S);
}
float Tensor::getVx()
{
float Vx = 0;
float fourg12 = 4 * pow(getg12(),2);
if(fourg12 == 0)
Vx = 0;
else
Vx = sgn<float>(Ix) * sqrt(E * fourg12 / (fourg12 + pow(getg22() - getg11() + S, 2)));
return Vx;
}
float Tensor::getVy()
{
float Vy = 0;
float g22g11S = pow(getg22() - getg11() + S,2);
if(g22g11S == 0)
Vy = 0;
else
Vy = sgn<float>(Iy) * sqrtf(E * g22g11S / (4 * pow(getg12(),2) + g22g11S));
return Vy;
}
| 17.04902 | 88 | 0.519839 | [
"vector"
] |
16c0294c5a42d76425c4fbec92f5f61803a2814e | 11,528 | cpp | C++ | beast/beast.cpp | dvorka/naaga | dce26f9803816befd3185bec3ea43ecfe3ffcaad | [
"Apache-2.0"
] | 1 | 2015-04-06T17:49:02.000Z | 2015-04-06T17:49:02.000Z | beast/beast.cpp | dvorka/naaga | dce26f9803816befd3185bec3ea43ecfe3ffcaad | [
"Apache-2.0"
] | null | null | null | beast/beast.cpp | dvorka/naaga | dce26f9803816befd3185bec3ea43ecfe3ffcaad | [
"Apache-2.0"
] | null | null | null | //----------------------------------------------------------------------------------
//
// Beasts
//
// Dvorka
// 1998
//
//----------------------------------------------------------------------------------
#include "beast.h"
#define BEASTDEBUG
extern byte keyBoard[]; // array of keys. If byte is 1, key is down
extern word DBMPw;
extern word DBMPh;
extern byte far *Original;
extern word GlobalXLevel, // upper left corner position in cells
GlobalYLevel; // 1 cell = 10 pixels
//----------------------------------------------------------------------------------
void BeastImg::square(int w, int h, byte color)
{
#define CHECKINIT(A,B) \
checkPoints[i++]=A; checkPoints[i++]=B;
int i=0;
image=(byte far *)farmalloc(w*h);
this->w=w;
this->h=h;
// checkpoints
checkLng=4;
checkPoints=(word far*)farmalloc(checkLng*sizeof(word)*2);
CHECKINIT(0,0)
CHECKINIT(w-1,0)
CHECKINIT(w-1,h-1)
CHECKINIT(0,h-1)
// create image of rectangle
for(i=0; i<w*h; i++) image[i]=color;
image[0]=image[w*h-1]=image[w-1]=image[w*h-w]= 15;
}
//----------------------------------------------------------------------------------
void BeastImg::save( int handle )
/*
- one imgRecord:
BeastImg "image"
Image array of nrOfImageBytes bytes
Checks nrOfCheckpointTuples*2 bytes
*/
{
word sbytes;
if (_dos_write(handle, this, sizeof(BeastImg), &sbytes)) { printf("\n Err: unable to write file..."); return; }
if (_dos_write(handle, image, w*h, &sbytes)) { printf("\n Err: unable to write file..."); return; }
if(checkLng)
if (_dos_write(handle, checkPoints, sizeof(word)*checkLng*2, &sbytes)) { printf("\n Err: unable to write file..."); return; }
printf("\n ImgDescr: size %d w %d h %d checkLng %d", w*h, w, h, checkLng );
}
//----------------------------------------------------------------------------------
void BeastImg::load( int handle )
/*
- one imgRecord:
BeastImg "image"
Image array of nrOfImageBytes bytes
Checks nrOfCheckpointTuples*2 bytes
*/
{
word sbytes;
if (_dos_read(handle, this, sizeof(BeastImg), &sbytes)) { printf("\n Err: unable to read file..."); return; }
// alloc space for image
image=(byte far*)farmalloc(w*h);
if (_dos_read(handle, image, w*h, &sbytes)) { printf("\n Err: unable to read file..."); return; }
// checkpoints
if(checkLng)
{
checkPoints=(word far*)farmalloc(checkLng*sizeof(word)*2);
if (_dos_read(handle, checkPoints, sizeof(word)*checkLng*2, &sbytes)) { printf("\n Err: unable to read file..."); return; }
}
printf("\n ImgDescr: size %u w %u h %u checkLng %u", w*h, w, h, checkLng );
}
//----------------------------------------------------------------------------------
void BeastImg::destruct()
{
if(image)
farfree(image);
if(checkPoints)
farfree(checkPoints);
}
//----------------------------------------------------------------------------------
Beast::Beast()
{
//printf(" -> ::Beast() constructor");
this->sizeOfImages=BEAST_IMAGES;
// allocate images
images = (BeastImg far*)farmalloc(sizeof(BeastImg)*sizeOfImages);
#ifdef BEASTDEBUG
printf(" -> ::Beast, free: %lu",farcoreleft());
#endif
this->type=SOFT_SHOT;
nrOfImages=0;
}
//----------------------------------------------------------------------------------
Beast::Beast( char *fileName )
{
word sbytes;
int handle,
i;
if (_dos_open( fileName, O_RDONLY, &handle) != 0) { printf("Err: unable to open file..."); return; }
if (_dos_read(handle, this, sizeof(Beast), &sbytes) != 0) { printf("Err: unable to read file..."); return ; }
// now alloc and load images
images = (BeastImg far*)farmalloc(sizeof(BeastImg)*sizeOfImages);
printf(" Images:");
for(i=0; i<nrOfImages; i++)
images[i].load(handle);
_dos_close(handle);
}
//----------------------------------------------------------------------------------
Beast::Beast( word sizeOfImages, int type )
{
//printf(" -> ::Beast constructor");
this->sizeOfImages=sizeOfImages;
// allocate images
images = (BeastImg far*)farmalloc(sizeof(BeastImg)*sizeOfImages);
#ifdef BEASTDEBUG
printf(" -> ::Beast, free: %lu",farcoreleft());
#endif
this->type=type;
nrOfImages=0;
}
//----------------------------------------------------------------------------------
Beast::~Beast()
{
// printf("\n -> ::Beast destructor");
// destroy active images
word i;
for( i=0; i<nrOfImages; i++ )
images[i].destruct();
// delete images vector
farfree(images);
}
//----------------------------------------------------------------------------------
bool Beast::check(byte far *screen)
// - returns TRUE if collision occured else returns FALSE
{
word j;
for( j=0; j<(images->checkLng)*2; j+=2 )
{
if( screen[x+images->checkPoints[j]+(y+images->checkPoints[j+1])*320] ) // pixel full -> collision
{
screen[0]=images->image[2];
return TRUE;
}
}
return FALSE;
}
//----------------------------------------------------------------------------------
/*
void Beast::move()
{
// save old position for unmove
int i=rand();
if( i%2 ) x++; else x--;
i=rand();
if( i%2 ) y++; else y--;
if(x<20) x=20; if(y<20) y=20;
if(x>300-images->w) x=300-images->w;
if(y>180-images->h) y=180-images->h;
}
*/
//----------------------------------------------------------------------------------
void Beast::show( byte far* screen )
{
word ww,hh;
word xx=x-GlobalXLevel*10, // normalize it to screen
yy=y-GlobalYLevel*10;
for( ww=0; ww<images[ID].w; ww++ )
for( hh=0; hh<images[ID].h; hh++ )
if( images[ID].image[ww+hh*images[ID].w] )
screen[xx+ww+(yy+hh)*320] = images[ID].image[ww+hh*images[ID].w];
}
//----------------------------------------------------------------------------------
#define JUMP_HEIGHT 10
#define MOVE_STEP 2
#define MAX_FALL_STEP 9
void Beast::move()
// - prohazovani stop obrazku pri padu je obracene
{
// jump properties
static bool jumping=FALSE,
falling=FALSE;
static byte jumpStep, // how fast move when jumping
fallStep, // how fast move when falling
moveStep=MOVE_STEP,// how fast move when walking
step=0; // each move increases by one
// -> e.g. used for image switching
static bool left; // last time moved left else moved right
// save old position
ox=x; oy=y;
if( keyBoard[KEYB_DOWN] )
{
y+=moveStep;
}
if( keyBoard[KEYB_RIGHT] )
{
left=FALSE;
x+=moveStep;
if( !(step++%7) ) ID=MoveLBeg + step%MoveLng;
}
if( keyBoard[KEYB_LEFT] )
{
left=TRUE;
x-=moveStep;
if( !(step++%7) ) ID=MoveRBeg + step%MoveLng;
}
// slow down move when falling or jumping
if( falling && (step++%3) ) return;
if( jumping && (step++%3) ) return;
if( keyBoard[KEYB_UP] )
{
word xx=x-GlobalXLevel*10, // normalize it to screen
yy=y-GlobalYLevel*10;
// jump is possible only if staying on something
if( Original[(yy+images[ID].h)*320+(xx+images[ID].w/2)] )
{
jumping=TRUE;
// change image ID by direction
if(left) ID=UpR; else ID=UpL;
}
}
// --- NO CEIL - FALL ---
if( !jumping )
{
word xx=x-GlobalXLevel*10, // normalize it to screen
yy=y-GlobalYLevel*10;
// check if avatar is staying on ground, if not - fall
// taking bottom-middle pixel
if( Original[(yy+images[ID].h)*320+(xx+images[ID].w/2)]==0 )
{
if( !falling )
{
falling=TRUE;
fallStep=1;
}
else
{
if( fallStep<MAX_FALL_STEP )fallStep++;
}
y+=fallStep;
// check position I jumped in
// if I am in some floor -> i must be *on* object, never inside ->
// move up and search for the first pixel transparent - it is ==0
if( Original[(yy+images[ID].h)*320+(xx+images[ID].w/2)]==0 )
{
do
{
y--;
yy=y-GlobalYLevel*10;
}
while( Original[(yy+images[ID].h)*320+(xx+images[ID].w/2)] );
y++; // move to floor (I was one pixel over)
}
// it's probably end of fall -> change image ID
if(left) ID=StopR; else ID=StopL;
}
else // end of fall
{
// it's end of fall
falling=FALSE;
}
}
else // I am in jump
falling=FALSE;
// JUMP
// jump bude pohyb pouze nahoru, jakmile dosahnu vrsku -> konec skoku
// a avatar bude uz sam padat
// Bude tady flag skakani.
if( jumping )
{
// it's new jump
if(!jumpStep)
jumpStep=JUMP_HEIGHT;
y-=jumpStep--; // decrease jump
if(!jumpStep)
{
jumping=FALSE;
ID = FallR;
}
}
// MOVE SCREEN
// left
if( x-GlobalXLevel*10 < 50 ) // i am too near border
{
if(GlobalXLevel) GlobalXLevel--;
}
// right
if( ((GlobalXLevel+SCREENCOLS)*10)-x < 50 )
{
if( GlobalXLevel<(LEVELWDT-SCREENCOLS) ) GlobalXLevel++;
}
// up
if( y-GlobalYLevel*10 < 80 ) // i am too near border
{
if(GlobalYLevel) GlobalYLevel--;
}
// down
if( ((GlobalYLevel+SCREENROWS)*10)-y < 80 )
{
if( GlobalYLevel<=(LEVELHGT-SCREENROWS+1) ) GlobalYLevel++;
}
}
//----------------------------------------------------------------------------------
void Beast::unmove()
// is used to return back last move
{
x=ox; y=oy;
}
//----------------------------------------------------------------------------------
bool Beast::collision( byte far* screen )
{
if( screen )
return TRUE;
else
return TRUE;
}
//----------------------------------------------------------------------------------
void Beast::addImage( char *BMPFile )
{
if( nrOfImages>=sizeOfImages )
printf("\n images vector is full: %u/%u",nrOfImages,sizeOfImages);
else
{
byte far *p=images[nrOfImages].image;
DBMPLoad( BMPFile, p, DBMPGETDATA );
images[nrOfImages].image=p;
// inside DBMPLoad are set globals DBMPw and DBMPh
images[nrOfImages].w=DBMPw;
images[nrOfImages].h=DBMPh;
images[nrOfImages].checkLng=0;
images[nrOfImages].checkPoints=NULL;
printf(" %dx%d image, ID %u/%u added...",DBMPw,DBMPh,nrOfImages,sizeOfImages);
nrOfImages++;
}
}
//----------------------------------------------------------------------------------
void Beast::save( char *fileName )
/*
- BeastFile format:
- class Beast image
- image records -> number is get from image
*/
{
word sbytes,
i;
int handle;
if (_dos_creat( fileName, _A_NORMAL, &handle)!=0) { printf(" Error: open file %s...", fileName); return; }
if (_dos_write(handle, this, sizeof(Beast), &sbytes) != 0) { printf("Err: unable to write beast image..."); return; }
printf("\n Beast core");
// save nrOfImages images
for( i=0; i<nrOfImages; i++ )
images[i].save(handle);
_dos_close(handle);
}
//----------------------------------------------------------------------------------
Avatar::Avatar(int x, int y )
{
this->x=this->ox=x;
this->y=this->oy=y;
images[0].square(10,10,WHITE);
nrOfImages=1;
}
//----------------------------------------------------------------------------------
MrZombie::MrZombie(int x, int y, byte color)
{
this->x=this->ox=x;
this->y=this->oy=y;
images[0].square(10,10,color);
nrOfImages=1;
}
//- EOF ----------------------------------------------------------------------------
| 23.966736 | 128 | 0.503383 | [
"object",
"vector"
] |
16c1edf9927e0d1f6c034d3e4d4eebbda97b87ca | 12,026 | cpp | C++ | src/solvers/gecode/models/completemodel.cpp | castor-software/unison | 9f8caf78230f956a57b50a327f8d1dca5839bf64 | [
"BSD-3-Clause"
] | 88 | 2016-09-27T15:20:07.000Z | 2022-03-24T15:23:06.000Z | src/solvers/gecode/models/completemodel.cpp | castor-software/unison | 9f8caf78230f956a57b50a327f8d1dca5839bf64 | [
"BSD-3-Clause"
] | 55 | 2017-02-14T15:21:03.000Z | 2021-09-11T11:12:25.000Z | src/solvers/gecode/models/completemodel.cpp | castor-software/unison | 9f8caf78230f956a57b50a327f8d1dca5839bf64 | [
"BSD-3-Clause"
] | 10 | 2016-11-22T15:03:46.000Z | 2020-07-13T21:34:31.000Z | /*
* Main authors:
* Roberto Castaneda Lozano <rcas@acm.org>
*
* Contributing authors:
* Mats Carlsson <mats.carlsson@ri.se>
*
* This file is part of Unison, see http://unison-code.github.io
*
* Copyright (c) 2016, RISE SICS AB
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "completemodel.hpp"
vector<temporary> & CompleteModel::T() const { return input->T; }
vector<operation> & CompleteModel::O() const { return input->O; }
vector<operand> & CompleteModel::P() const { return input->P; }
BoolVar CompleteModel::x(operand p) const {
if (input->global_optional[p]) {
return v_x[input->global_optional_index[p]];
} else {
return a(input->oper[p]);
}
}
BoolVar CompleteModel::u(operand p, temporary t) const {
unsigned int ti = input->temporary_index[p][t];
return v_u[input->fu[p] + ti];
}
IntVar CompleteModel::lat(operand p, temporary t) const {
unsigned int ti = input->temporary_index[p][t];
return v_lat[input->fu[p] + ti];
}
BoolVar CompleteModel::p(operation o1, operation o2) {
if (options->disable_precedence_variables()) {
return var(c(o1) < c(o2));
} else {
block b = input->oblock[o1];
unsigned int o1i = input->mandatory_index[o1],
o2i = input->mandatory_index[o2];
return v_p[input->accman[b] + o1i * input->mandatory[b].size() + o2i];
}
}
IntVar CompleteModel::s(operand p) const {
assert(input->global_operand[p]);
return v_s[input->global_index[p]];
}
CompleteModel::CompleteModel(Parameters * p_input, ModelOptions * p_options,
IntPropLevel p_ipl) :
Model(p_input, p_options, p_ipl)
{
v_r = int_var_array(T().size(), -1, input->RA.size() - 1);
v_i = int_var_array(O().size(), 0, input->I.size() - 1);
v_c = int_var_array(O().size(), 0, max_of(input->maxc));
if (!P().empty()) {
v_y = int_var_array(P().size(), 0, input->T.size() - 1);
}
v_x = bool_var_array(sum_of(input->n_global_optionals), 0, 1);
v_ry = int_var_array(P().size(), -1, input->RA.size() - 1);
v_a = bool_var_array(O().size(), 0, 1);
v_ls = int_var_array(T().size(), 0, max_of(input->maxc));
v_ld = int_var_array(T().size(), 0, max_of(input->maxc));
v_le = int_var_array(T().size(), 0,
max_of(input->maxc) + maybe_max_of(0, input->minlive));
v_al = bool_var_array(T().size() * input->RS.size(), 0, 1);
v_u = bool_var_array(input->nu, 0, 1);
v_us = int_var_array(T().size(), 0, O().size());
if (!P().empty()) {
v_lt = int_var_array(P().size(), input->min_lat, input->max_lat);
}
if (input->nu > 0) {
v_lat = int_var_array(input->nu, -input->max_lat, input->max_lat * 3);
}
if (!options->disable_precedence_variables()) {
v_p = bool_var_array(input->accman[input->B.size()], 0, 1);
}
if (!T().empty()) {
v_users = set_var_array(T().size(), IntSet::empty,
IntSet(min_of(input->P), max_of(input->P)));
}
if (!P().empty()) {
v_s = int_var_array(sum_of(input->n_global),
-input->max_lat, input->max_lat);
}
v_gf = int_var_array(input->N, 0, Int::Limits::max);
v_f = int_var_array(input->B.size() * input->N, 0, Int::Limits::max);
}
CompleteModel::CompleteModel(CompleteModel& cg) :
Model(cg)
{
v_gf.update(*this, cg.v_gf);
v_f.update(*this, cg.v_f);
}
CompleteModel* CompleteModel::copy(void) {
return new CompleteModel(*this);
}
IntVarArgs CompleteModel::cost() const {
return gf();
}
void CompleteModel::post_decision_variable_domain_definitions(void) {
for (block b : input->B)
Model::post_decision_variable_domain_definitions(b);
}
void CompleteModel::post_secondary_variable_definitions(void) {
for (block b : input->B)
Model::post_secondary_variable_definitions(b);
}
void CompleteModel::post_basic_model_constraints(void) {
for (block b : input->B) Model::post_basic_model_constraints(b);
post_global_operand_connection_constraints();
post_congruence_constraints();
post_activation_constraints();
post_slack_balancing_constraints();
}
void CompleteModel::post_global_operand_connection_constraints(void) {
// Global operands are connected iff any of their successors is connected:
for (auto pqs : input->succ) {
operand p = pqs.first;
BoolVarArgs xqs;
for (operand q : pqs.second) xqs << x(q);
constraint(x(p) == (sum(xqs) > 0));
}
// [MC]
for (vector<operand> adj : input->quasi_adjacent) {
operand p = adj[0], q = adj[1];
constraint(x(q) >> x(p));
}
}
void CompleteModel::post_congruence_constraints(void) {
// Connected adjacent operands are assigned to the same register:
for (vector<operand> adj : input->adjacent) {
operand p = adj[0], q = adj[1];
constraint(ry(q) == ite(x(q), ry(p), NULL_REGISTER));
}
}
void CompleteModel::post_activation_constraints(void) {
// An operation is active if any of its activator instructions is selected:
for (activation_class ac : input->AC) {
BoolVarArgs is;
for (instruction i1 : input->activation_class_instructions[ac])
for (operation o : input->O)
for (unsigned int ii = 0; ii < input->instructions[o].size(); ii++)
if (i1 == input->instructions[o][ii]) is << var(i(o) == ii);
BoolVarArgs as;
for (operation o : input->activation_class_operations[ac]) as << a(o);
rel(*this, as, IRT_EQ, ipl);
constraint((sum(is) > 0) >> a(input->activation_class_representative[ac]));
}
}
void CompleteModel::post_slack_balancing_constraints(void) {
// The slack of adjacent operands is balanced:
for (vector<operand> adj : input->adjacent) {
operand p = adj[0], q = adj[1];
constraint((s(p) + s(q)) == 0);
}
}
void CompleteModel::post_improved_model_constraints(void) {
for (block b : input->B)
Model::post_improved_model_constraints(b);
post_slack_functional_constraints();
}
void CompleteModel::post_slack_functional_constraints(void) {
int maxc = max_of(input->maxc);
int maxl = input->max_lat;
for (vector<vector<int>>& ix : input->long_latency_index) {
vector<operand> inps = ix[0];
vector<operand> outps = ix[2];
vector<int> inix = ix[1];
vector<int> outix = ix[3];
IntVarArgs inubs, outubs;
for (unsigned int ii : inix) {
vector<operand>du = input->long_latency_def_use[ii];
operand p = du[0];
operand q = du[1];
temporary t = input->single_temp[p];
inubs << var(ite(u(q, t), c(input->oper[q]) - lt(q) - slack(q) - lt(p), maxl));
}
for (unsigned int ii : outix) {
vector<operand>du = input->long_latency_def_use[ii];
operand p = du[0];
operand q = du[1];
temporary t = input->single_temp[p];
outubs << var(ite(u(q, t), ld(t) - lt(q) - slack(p) - lt(p), maxl));
}
IntVar outlb(*this, -maxc, maxc);
IntVar outub(*this, -maxc, maxc);
if(!inix.empty())
constraint(outlb == -min(inubs));
else
constraint(outlb == -maxl);
if(!outix.empty())
constraint(outub == min(outubs));
else
constraint(outub == maxl);
constraint(outlb <= outub);
constraint(s(outps[0]) == min(outub,max(outlb,0)));
for (operand p : outps)
if (p > outps[0])
constraint(s(p) == s(outps[0]));
}
}
void CompleteModel::post_presolver_constraints(void) {
for (block b : input->B)
Model::post_presolver_constraints(b);
if (!options->disable_presolver_constraints()) {
// cross-block synchronisation of spill/unspill ops
for (const vector<operation>& os : input->calleesaved_spill) {
operation spillop = os[0];
for (operation o : os) {
if (o != spillop) {
constraint(a(o) == a(spillop)); // cross-block constraint
}
}
}
// cross-block nogoods
for (UnisonConstraintExpr ng : input->gnogoods) {
constraint(!adhoc_constraint_var(ng));
}
// cross-block active tables
for (PresolverActiveTable table : input->gactive_tables) {
if (table.tuples.empty()) continue;
BoolVarArgs as;
for (operation o : table.os) as << a(o);
TupleSet ts(table.tuples[0].size());
for (vector<int> tuple : table.tuples) ts.add(IntArgs(tuple));
ts.finalize();
extensional(*this, as, ts);
}
}
}
void CompleteModel::post_global_cost_definition(void) {
// The objective is to minimize the cost of each block possibly weighted by
// the estimated execution frequency:
for (unsigned int n = 0; n < input->N; n++) {
IntVarArgs fs;
for (block b : input->B) fs << f(b, n);
if (input->optimize_dynamic[n])
linear(*this, IntArgs(input->freq), fs, IRT_EQ, gf()[n]);
else
linear(*this, fs, IRT_EQ, gf()[n]);
}
}
void CompleteModel::post_cost_definition(void) {
for (block b : input->B)
Model::post_cost_definition(b);
}
void CompleteModel::post_upper_bound(vector<int> maxcost) {
rel(*this, cost(), IRT_LQ, maxcost);
}
void CompleteModel::post_lower_bound(vector<int> mincost) {
rel(*this, cost(), IRT_GQ, mincost);
}
void CompleteModel::post_standalone_constraints(void) {
// Individual domains of problem variables
post_decision_variable_domain_definitions();
// Secondary variable definitions
post_secondary_variable_definitions();
// Basic model
post_basic_model_constraints();
// Improved model
post_improved_model_constraints();
// Presolved model
post_presolver_constraints();
// Global cost
post_global_cost_definition();
// Cost of each block
post_cost_definition();
}
void CompleteModel::print(ostream & pOs) const {
pOs << "global cost: " << gf() << endl << endl;
for (block b : input->B) Model::print(pOs, b);
pOs << endl;
}
// Returns a JSON string with the solution of the given model, assuming all
// variables are assigned.
string CompleteModel::solution_to_json() const {
std::stringstream pOs;
vector<int> rs;
for (temporary t1 : input->T)
rs.push_back(l(t1).val() ? r(t1).val() : -1);
vector<instruction> is;
for (operation o : input->O)
is.push_back(input->instructions[o][i(o).val()]);
vector<int> cs;
for (operation o : input->O)
cs.push_back(a(o).val() ? c(o).val() : -1);
vector<temporary> ys;
for (operand p : input->P)
ys.push_back(input->temps[p][y(p).val()]);
pOs << "{";
pOs << "\"registers\":" << to_json(rs) << ",";
pOs << "\"instructions\":" << to_json(is) << ",";
pOs << "\"cycles\":" << to_json(cs) << ",";
pOs << "\"temporaries\":" << to_json(ys);
pOs << "}";
return pOs.str();
}
| 31.074935 | 85 | 0.653168 | [
"vector",
"model"
] |
16c67bb613cf329d32ba944db317da8ac7e76437 | 968 | cpp | C++ | STL/iterator/reverse_iterator_1.cpp | liangjisheng/C-Cpp | 8b33ba1f43580a7bdded8bb4ce3d92983ccedb81 | [
"MIT"
] | 5 | 2019-09-17T09:12:15.000Z | 2021-05-29T10:54:39.000Z | STL/iterator/reverse_iterator_1.cpp | liangjisheng/C-Cpp | 8b33ba1f43580a7bdded8bb4ce3d92983ccedb81 | [
"MIT"
] | null | null | null | STL/iterator/reverse_iterator_1.cpp | liangjisheng/C-Cpp | 8b33ba1f43580a7bdded8bb4ce3d92983ccedb81 | [
"MIT"
] | 2 | 2021-07-26T06:36:12.000Z | 2022-01-23T15:20:30.000Z | #include <iostream>
#include <iterator>
#include <vector>
#include <algorithm>
using namespace std;
// forward_list和无序关联容器不能用reverse_iterator
// 反向遍历,rbegin()返回指向容器中最后一个元素的
// reverse_iterator, rend()返回指向容器中第一个元素之前的元素
// reverse_iterator.base()总是引用被调用reverse_iterator
// 引用的元素的最后一个元素
int main()
{
vector<int> vec;
vec.push_back(11);
vec.push_back(22);
vec.push_back(33);
vec.push_back(22);
vec.push_back(11);
int num = 11;
cout << "Enter a number to find: ";
cin >> num;
auto it1 = find(vec.begin(), vec.end(), num);
auto it2 = find(vec.rbegin(), vec.rend(), num);
if(it1 != vec.end())
{
cout << "Found " << num << " at position " << it1 - vec.begin()
<< " going forward." << endl;
cout << "Found " << num << " at position "
<< it2.base() - 1 - vec.begin() << " going backward." << endl;
}
cout << "Failed to find " << num << endl;
return 0;
}
| 24.820513 | 74 | 0.576446 | [
"vector"
] |
16cdf8a9bec7d11db00641453288fd2b789de96a | 14,630 | cpp | C++ | pio_parent/lib/EspMeshWrapper/mesh_app.cpp | ESP32Home/esp32_mesh | edb4ac481eb9e4998bec03fefa86f83040d31298 | [
"CC0-1.0"
] | 2 | 2020-11-19T19:34:14.000Z | 2021-09-17T04:53:09.000Z | pio_parent/lib/EspMeshWrapper/mesh_app.cpp | ESP32Home/esp32_mesh | edb4ac481eb9e4998bec03fefa86f83040d31298 | [
"CC0-1.0"
] | null | null | null | pio_parent/lib/EspMeshWrapper/mesh_app.cpp | ESP32Home/esp32_mesh | edb4ac481eb9e4998bec03fefa86f83040d31298 | [
"CC0-1.0"
] | null | null | null | #include "mesh_app.h"
#include "esp_wifi.h"
#include "esp_system.h"
#include "esp_event_loop.h"
#include "esp_log.h"
#include "esp_mesh.h"
#include "esp_mesh_internal.h"
#define RX_SIZE (1500)
#define TX_SIZE (1460)
#define CONFIG_MESH_ROUTE_TABLE_SIZE_MAX 50
static bool is_mesh_connected = false;
static mesh_addr_t mesh_parent_addr;
static int mesh_layer = -1;
static uint8_t tx_buf[TX_SIZE] = { 0, };
static uint8_t rx_buf[RX_SIZE] = { 0, };
static bool is_running = true;
static bool is_comm_p2p_started = false;
//reduced to singleton instance as the path such as mesh_event_handler, does not have data
MeshCallback message_callback = nullptr;
void string_to_char_len(String str,uint8_t* text,uint16_t &length){
length = str.length();
memcpy(text, str.c_str(), length);
text[length] = '\0';//clean ending for printing
}
void string_to_char_len(String str,uint8_t* text,uint8_t &length){
length = str.length();
memcpy(text, str.c_str(), length);
text[length] = '\0';//clean ending for printing
}
void string_to_char(String str,uint8_t* text){
memcpy(text, str.c_str(), str.length());
text[str.length()] = '\0';
}
void string_to_hextab(const char* str,mesh_addr_t &t){
t.addr[0] = 0x77;
t.addr[1] = 0x77;
t.addr[2] = 0x77;
t.addr[3] = 0x77;
t.addr[4] = 0x77;
t.addr[5] = 0x77;
}
String hextab_to_string(uint8_t* add){
String res;
for(int i=0;i<5;i++){
res = res + String((*add++),HEX)+":";
}
res = res + String((*add),HEX);
return res;
}
void print_mac(uint8_t* add){
for(int i=0;i<5;i++){
Serial.printf("%02X:",(*add++));
}
Serial.printf("%02X\n",(*add));
}
void print_ip(ip4_addr_t add){
uint8_t u1 = (add.addr>>3) & 0xff;
uint8_t u2 = (add.addr>>2) & 0xff;
uint8_t u3 = (add.addr>>1) & 0xff;
uint8_t u4 = add.addr & 0xff;
Serial.printf("%d.%d.%d.%d\n",u1,u2,u3,u4);
}
void esp_mesh_p2p_rx_main(void *arg)
{
esp_err_t err;
mesh_addr_t from;
mesh_data_t data;
int flag = 0;
data.data = rx_buf;
data.size = RX_SIZE;
is_running = true;
while (is_running) {
data.size = RX_SIZE;
err = esp_mesh_recv(&from, &data, portMAX_DELAY, &flag, NULL, 0);
if (err != ESP_OK || !data.size) {
Serial.printf("error> 0x%x, size:%d\n", err, data.size);
continue;
}
String result(reinterpret_cast<char*>(data.data));
String from_text = hextab_to_string(from.addr);
message_callback(result,from_text,flag);
}
vTaskDelete(NULL);
}
esp_err_t esp_mesh_comm_p2p_start(void)
{
if (!is_comm_p2p_started) {
is_comm_p2p_started = true;
xTaskCreate(esp_mesh_p2p_rx_main, "MPRX", 3072, NULL, 5, NULL);
}
return ESP_OK;
}
esp_err_t esp_mesh_comm_p2p_stop(void)
{
is_running = false;//the task will delete itself
is_comm_p2p_started = false;//so that it can be created next time
return ESP_OK;
}
void mesh_event_handler(mesh_event_t event)
{
mesh_addr_t id = {0,};
static uint8_t last_layer = 0;
switch (event.id) {
case MESH_EVENT_STARTED:
esp_mesh_get_id(&id);
Serial.printf("<MESH_EVENT_STARTED>ID:");
print_mac(id.addr);
is_mesh_connected = false;
mesh_layer = esp_mesh_get_layer();
break;
case MESH_EVENT_STOPPED:
Serial.printf("<MESH_EVENT_STOPPED>\n");
is_mesh_connected = false;
mesh_layer = esp_mesh_get_layer();
break;
case MESH_EVENT_CHILD_CONNECTED:
Serial.printf("<MESH_EVENT_CHILD_CONNECTED>aid:%d,",event.info.child_connected.aid);
print_mac(event.info.child_connected.mac);
break;
case MESH_EVENT_CHILD_DISCONNECTED:
Serial.printf("<MESH_EVENT_CHILD_DISCONNECTED>aid:%d, ",event.info.child_disconnected.aid);
print_mac(event.info.child_disconnected.mac);
break;
case MESH_EVENT_ROUTING_TABLE_ADD:
Serial.printf("<MESH_EVENT_ROUTING_TABLE_ADD>add %d, new:%d\n",
event.info.routing_table.rt_size_change,
event.info.routing_table.rt_size_new);
break;
case MESH_EVENT_ROUTING_TABLE_REMOVE:
Serial.printf("<MESH_EVENT_ROUTING_TABLE_REMOVE>remove %d, new:%d\n",
event.info.routing_table.rt_size_change,
event.info.routing_table.rt_size_new);
break;
case MESH_EVENT_NO_PARENT_FOUND:
Serial.printf("<MESH_EVENT_NO_PARENT_FOUND>scan times:%d\n",event.info.no_parent.scan_times);
/* TODO handler for the failure */
break;
case MESH_EVENT_PARENT_CONNECTED:
esp_mesh_get_id(&id);
mesh_layer = event.info.connected.self_layer;
memcpy(&mesh_parent_addr.addr, event.info.connected.connected.bssid, 6);
Serial.printf("<MESH_EVENT_PARENT_CONNECTED>layer:%d-->%d, parent:%s, ID:",
last_layer, mesh_layer,
esp_mesh_is_root() ? "<ROOT>" :
(mesh_layer == 2) ? "<layer2>" : "");
print_mac(mesh_parent_addr.addr);
print_mac(id.addr);
last_layer = mesh_layer;
is_mesh_connected = true;
if (esp_mesh_is_root()) {
tcpip_adapter_dhcpc_start(TCPIP_ADAPTER_IF_STA);
}
esp_mesh_comm_p2p_start();
break;
case MESH_EVENT_PARENT_DISCONNECTED:
Serial.printf("<MESH_EVENT_PARENT_DISCONNECTED>reason:%d\n",event.info.disconnected.reason);
is_mesh_connected = false;
mesh_layer = esp_mesh_get_layer();
//do not stop here as children might still be connected and send messages
break;
case MESH_EVENT_LAYER_CHANGE:
mesh_layer = event.info.layer_change.new_layer;
Serial.printf("<MESH_EVENT_LAYER_CHANGE>layer:%d-->%d%s",
last_layer, mesh_layer,
esp_mesh_is_root() ? "<ROOT>" :
(mesh_layer == 2) ? "<layer2>\n" : "\n");
last_layer = mesh_layer;
break;
case MESH_EVENT_ROOT_ADDRESS:
Serial.printf("<MESH_EVENT_ROOT_ADDRESS>root address:");
print_mac(event.info.root_addr.addr);
break;
case MESH_EVENT_ROOT_GOT_IP:
/* root starts to connect to server */
Serial.printf("<MESH_EVENT_ROOT_GOT_IP>sta ip:, mask: , gw: \n");
print_ip(event.info.got_ip.ip_info.ip);
print_ip(event.info.got_ip.ip_info.netmask);
print_ip(event.info.got_ip.ip_info.gw);
break;
case MESH_EVENT_ROOT_LOST_IP:
Serial.printf("<MESH_EVENT_ROOT_LOST_IP>\n");
break;
case MESH_EVENT_VOTE_STARTED:
Serial.printf("<MESH_EVENT_VOTE_STARTED>attempts:%d, reason:%d, rc_addr:",
event.info.vote_started.attempts,
event.info.vote_started.reason);
print_mac(event.info.vote_started.rc_addr.addr);
break;
case MESH_EVENT_VOTE_STOPPED:
Serial.printf("<MESH_EVENT_VOTE_STOPPED>\n");
break;
case MESH_EVENT_ROOT_SWITCH_REQ:
Serial.printf("<MESH_EVENT_ROOT_SWITCH_REQ>reason:%d, rc_addr:",
event.info.switch_req.reason);
print_mac( event.info.switch_req.rc_addr.addr);
break;
case MESH_EVENT_ROOT_SWITCH_ACK:
/* new root */
mesh_layer = esp_mesh_get_layer();
esp_mesh_get_parent_bssid(&mesh_parent_addr);
Serial.printf("<MESH_EVENT_ROOT_SWITCH_ACK>layer:%d, parent:", mesh_layer);
print_mac(mesh_parent_addr.addr);
break;
case MESH_EVENT_TODS_STATE:
Serial.printf("<MESH_EVENT_TODS_REACHABLE>state:%d\n",event.info.toDS_state);
break;
case MESH_EVENT_ROOT_FIXED:
Serial.printf("<MESH_EVENT_ROOT_FIXED>%s\n",event.info.root_fixed.is_fixed ? "fixed" : "not fixed");
break;
case MESH_EVENT_ROOT_ASKED_YIELD:
Serial.printf("<MESH_EVENT_ROOT_ASKED_YIELD>, rssi:%d, capacity:%d",
event.info.root_conflict.rssi,
event.info.root_conflict.capacity);
print_mac(event.info.root_conflict.addr);
break;
case MESH_EVENT_CHANNEL_SWITCH:
Serial.printf("<MESH_EVENT_CHANNEL_SWITCH>new channel:%d\n", event.info.channel_switch.channel);
break;
case MESH_EVENT_SCAN_DONE:
Serial.printf("<MESH_EVENT_SCAN_DONE>number:%d\n",event.info.scan_done.number);
break;
case MESH_EVENT_NETWORK_STATE:
Serial.printf("<MESH_EVENT_NETWORK_STATE>is_rootless:%d\n",event.info.network_state.is_rootless);
break;
case MESH_EVENT_STOP_RECONNECTION:
Serial.printf("<MESH_EVENT_STOP_RECONNECTION>\n");
break;
case MESH_EVENT_FIND_NETWORK:
Serial.printf("<MESH_EVENT_FIND_NETWORK>new channel:%d, router BSSID:",event.info.find_network.channel);
print_mac(event.info.find_network.router_bssid);
break;
case MESH_EVENT_ROUTER_SWITCH:
Serial.printf("<MESH_EVENT_ROUTER_SWITCH>new router:%s, channel:%d, ",
event.info.router_switch.ssid, event.info.router_switch.channel);
print_mac(event.info.router_switch.bssid);
break;
default:
Serial.printf("esp_event_handler> unknown id:%d\n", event.id);
break;
}
}
MeshApp::MeshApp(){
}
bool MeshApp::start(DynamicJsonDocument &config,DynamicJsonDocument &secret){
if(!config.containsKey("mesh")){
Serial.printf("Error> config has no key 'mesh'");
return false;
}
if(!secret.containsKey("wifi")){
Serial.printf("Error> secret has no key 'wifi'");
return false;
}
tcpip_adapter_init();
esp_err_t err;
err = tcpip_adapter_dhcps_stop(TCPIP_ADAPTER_IF_AP);
if(err != ESP_OK)Serial.printf("tcpip_adapter_dhcps_stop: 0x%X\n",err);
err = tcpip_adapter_dhcpc_stop(TCPIP_ADAPTER_IF_STA);
if(err != ESP_OK)Serial.printf("tcpip_adapter_dhcps_stop: 0x%X\n",err);
err = esp_event_loop_init(NULL, NULL);
if(err != ESP_OK)Serial.printf("esp_event_loop_init: 0x%X\n",err);
wifi_init_config_t wifi_config = WIFI_INIT_CONFIG_DEFAULT();
err = esp_wifi_init(&wifi_config);
if(err != ESP_OK)Serial.printf("esp_wifi_initt: 0x%X\n",err);
err = esp_wifi_start();
if(err != ESP_OK)Serial.printf("esp_wifi_start: 0x%X\n",err);
err = esp_mesh_init();
if(err != ESP_OK)Serial.printf("esp_mesh_init: 0x%X\n",err);
//esp_mesh_set_topology() // Not available in 3.3
//esp_mesh_set_active_duty_cycle() // Not available in 3.3
err = esp_mesh_set_announce_interval(config["mesh"]["parent"]["announce_short_ms"],config["mesh"]["parent"]["announce_long_ms"]);
err = esp_mesh_set_max_layer(config["mesh"]["max_layer"]);
if(err != ESP_OK)Serial.printf("esp_mesh_set_max_layer: 0x%X\n",err);
err = esp_mesh_set_vote_percentage(1);
if(err != ESP_OK)Serial.printf("esp_mesh_set_vote_percentage: 0x%X\n",err);
err = esp_mesh_set_ap_assoc_expire(10);
if(err != ESP_OK)Serial.printf("esp_mesh_set_ap_assoc_expire: 0x%X\n",err);
err = esp_mesh_set_ap_authmode(WIFI_AUTH_WPA_WPA2_PSK);
if(err != ESP_OK)Serial.printf("esp_mesh_set_ap_authmode: 0x%X\n",err);
mesh_cfg_t cfg;
cfg.crypto_funcs = &g_wifi_default_mesh_crypto_funcs;
cfg.event_cb = &mesh_event_handler;
string_to_hextab(config["mesh"]["id"],cfg.mesh_id);
cfg.channel = config["mesh"]["channel"];
string_to_char_len(secret["wifi"]["access_point"],cfg.router.ssid,cfg.router.ssid_len);
string_to_char(secret["wifi"]["password"],cfg.router.password);
string_to_char(secret["mesh"]["password"],cfg.mesh_ap.password);
cfg.mesh_ap.max_connection = config["mesh"]["parent"]["ap_connections"];
Serial.printf("cfg.mesh_id = ");print_mac(cfg.mesh_id.addr);
Serial.printf("cfg.channel = %d\n",cfg.channel);
Serial.printf("cfg.router.ssid = %s\n",cfg.router.ssid);
Serial.printf("cfg.router.password = %s\n",cfg.router.password);
Serial.printf("cfg.mesh_ap.password = %s\n",cfg.mesh_ap.password);
Serial.printf("cfg.mesh_ap.max_connection = %d\n",cfg.mesh_ap.max_connection);
err = esp_mesh_set_config(&cfg);
if(err != ESP_OK)Serial.printf("esp_mesh_set_config: 0x%X\n",err);
/* mesh start */
esp_err_t res = esp_mesh_start();
if(res != ESP_OK){
Serial.printf("mesh start failed, heap:%d, %s\n", esp_get_free_heap_size(),
esp_mesh_is_root_fixed() ? "root fixed" : "root not fixed");
}
return res;
}
void MeshApp::onMessage(MeshCallback cb){
message_callback = cb;
}
bool MeshApp::send_down(String message){
int i;
esp_err_t err;
mesh_addr_t route_table[CONFIG_MESH_ROUTE_TABLE_SIZE_MAX];
int route_table_size = 0;
mesh_data_t data;
data.data = tx_buf;
data.proto = MESH_PROTO_BIN;
data.tos = MESH_TOS_P2P;
if(!is_running){
return false;
}
err = esp_mesh_get_routing_table(route_table,CONFIG_MESH_ROUTE_TABLE_SIZE_MAX * sizeof(mesh_addr_t), &route_table_size);
if (err != ESP_OK) {
Serial.printf("error>on esp_mesh_get_routing_table(size=%d) [Layer:%d] [heap:%d] [err:0x%x]\n",
route_table_size,mesh_layer,esp_get_minimum_free_heap_size(),err);
return false;
}
string_to_char_len(message,data.data,data.size);
Serial.printf("route table size = %d\n",route_table_size);
for (i = 0; i < route_table_size; i++) {
Serial.printf(" Sending to ");
print_mac(route_table[i].addr);
err = esp_mesh_send(&route_table[i], &data, MESH_DATA_P2P, NULL, 0);
if (err) {
Serial.printf("error>on(%d/%d) [Layer:%d] [heap:%d] [err:0x%x, proto:%d, tos:%d] *parent *dest\n",
i,route_table_size,
mesh_layer,esp_get_minimum_free_heap_size(),err, data.proto, data.tos);
print_mac(mesh_parent_addr.addr);
print_mac(route_table[i].addr);
continue;
}
}
return true;
}
void MeshApp::print_info(){
esp_err_t err;
String info;
info = "*Layer="+String(esp_mesh_get_layer());
mesh_addr_t bssid;
err = esp_mesh_get_parent_bssid(&bssid);
if(err == ESP_OK){
info += " Parent="+hextab_to_string(bssid.addr)+" ";
}
if(!esp_mesh_is_root()){
info += " Not";
}
info += " root ";
info += "NbNodes="+String(esp_mesh_get_total_node_num());
info += " TableSize="+String(esp_mesh_get_routing_table_size());
Serial.println(info);
} | 36.30273 | 133 | 0.648462 | [
"mesh"
] |
16ce94fd97d602fbc69544e5c88fb985956e5be3 | 2,930 | cc | C++ | src/test/recordmanager.cc | zmj1316/MiniSQL | 2fc6d2b81fef7de2cc3216897e654d148a6b7d32 | [
"MIT"
] | null | null | null | src/test/recordmanager.cc | zmj1316/MiniSQL | 2fc6d2b81fef7de2cc3216897e654d148a6b7d32 | [
"MIT"
] | null | null | null | src/test/recordmanager.cc | zmj1316/MiniSQL | 2fc6d2b81fef7de2cc3216897e654d148a6b7d32 | [
"MIT"
] | null | null | null | #include "recordmanager.h"
#include "buffer.h"
#include <memory.h>
static record binary2record(table* tb, u8* bin)
{
record result;
/* Check validity */
if ((*bin) == 0xFF) // 0xFF invalid
{
result.valid = false;
return result;
}
bin++;// move ptr
result.valid = true;
for (u32 i = 0; i < tb->colNum_u64; i++)
{
column *col = &(tb->col[i]); // get current column
result.i[i].type = col->type;// get datatype
switch (col->type) // fetch data
{
case INT:
result.i[i].data.i = *reinterpret_cast<int *>(bin);
break;
case FLOAT:
result.i[i].data.f = *reinterpret_cast<float*>(bin);
break;
case CHAR:
result.i[i].data.str = new char[col->size_u8];
// reg string to str
memcpy(result.i[i].data.str,reinterpret_cast<char *>(bin), col->size_u8);/* Mem leap! */
break;
default:
break;
}
bin += col->size_u8; //move ptr
}
return result;
}
static bool record2binary(table* tb, u8* bin, record * entry)
{
*bin++ = 0;/* valid = true */
for (u32 i = 0; i < tb->colNum_u64; i++)
{
column *col = &(tb->col[i]); // get column
item * it = &(entry->i[i]); // get item
// write data
switch (it->type)
{
case INT:
*reinterpret_cast<int*>(bin) = it->data.i;
break;
case CHAR:
memcpy(bin, it->data.str, col->size_u8);
break;
case FLOAT:
*reinterpret_cast<float*>(bin) = it->data.f;
break;
default:
break;
}
bin += col->size_u8; //move ptr
}
return true;
}
std::vector<record> /* vector of record */
Recordmanager_getRecord(
table* tb /* table to visit */
)
{
std::vector<record> result;
u32 capacity = BLOCKSIZE / (tb->recordSize + 1); /* Number of records in one block (Record size is +1 for the valid flag)*/
for (u32 i = 0; i < (tb->recordNum - 1) / capacity + 1; i++) /* For all blocks */
{
move_window(&(tb->buf), i); /* move to operation block */
for (u32 i1 = 0; i1 < capacity; i1++)
{
result.push_back(binary2record(tb, tb->buf.win + i1 * tb->recordSize));
}
}
return result;
}
bool Recordmanager_insertRecord(table* tb,record* entry)
{
u32 capacity = BLOCKSIZE / (tb->recordSize + 1); /* Number of records in one block (Record size is +1 for the valid flag)*/
if (tb->recordNum % capacity == 0)
{
newBlock(&(tb->buf));
}
move_window(&(tb->buf),(++tb->recordNum - 1) / capacity);
record2binary(tb, tb->buf.win + (tb->recordSize + 1)*(tb->recordNum - 1) % capacity, entry);
tb->buf.dirty = true;
sync_window(&tb->buf);
return true;
}
| 29.897959 | 127 | 0.517065 | [
"vector"
] |
16d1746d0844ac012c86d53c742326876f841ae7 | 3,770 | hh | C++ | src/mesh/Mesh_Algorithms.hh | fmyuan/amanzi | edb7b815ae6c22956c8519acb9d87b92a9915ed4 | [
"RSA-MD"
] | 37 | 2017-04-26T16:27:07.000Z | 2022-03-01T07:38:57.000Z | src/mesh/Mesh_Algorithms.hh | fmyuan/amanzi | edb7b815ae6c22956c8519acb9d87b92a9915ed4 | [
"RSA-MD"
] | 494 | 2016-09-14T02:31:13.000Z | 2022-03-13T18:57:05.000Z | src/mesh/Mesh_Algorithms.hh | fmyuan/amanzi | edb7b815ae6c22956c8519acb9d87b92a9915ed4 | [
"RSA-MD"
] | 43 | 2016-09-26T17:58:40.000Z | 2022-03-25T02:29:59.000Z | //
// Mesh
//
// Copyright 2010-201x held jointly by LANL, ORNL, LBNL, and PNNL.
// Amanzi is released under the three-clause BSD License.
// The terms of use and "as is" disclaimer for this license are
// provided in the top-level COPYRIGHT file.
//
// Helper functions for Mesh operations and algorithms
//
#pragma once
#include "Epetra_MultiVector.h"
#include "Mesh.hh"
namespace Amanzi {
namespace AmanziMesh {
// -----------------------------------------------------------------------------
// Given a boundary face ID, get the corresponding face ID
// -----------------------------------------------------------------------------
AmanziMesh::Entity_ID
getBoundaryFaceFace(const AmanziMesh::Mesh& mesh, AmanziMesh::Entity_ID bf);
// -----------------------------------------------------------------------------
// Given a face ID, get the corresponding boundary face ID (assuming it is a bf)
// -----------------------------------------------------------------------------
AmanziMesh::Entity_ID
getFaceOnBoundaryBoundaryFace(const AmanziMesh::Mesh& mesh, AmanziMesh::Entity_ID f);
// -----------------------------------------------------------------------------
// Given a boundary face ID, get the cell internal to that face.
// -----------------------------------------------------------------------------
AmanziMesh::Entity_ID
getBoundaryFaceInternalCell(const AmanziMesh::Mesh& mesh, AmanziMesh::Entity_ID bf);
// -----------------------------------------------------------------------------
// Given a face ID, and assuming it is a boundary face, get the cell internal.
// -----------------------------------------------------------------------------
AmanziMesh::Entity_ID
getFaceOnBoundaryInternalCell(const AmanziMesh::Mesh& mesh, AmanziMesh::Entity_ID f);
// -----------------------------------------------------------------------------
// Given a vector on faces, import to vector on boundary faces
// -----------------------------------------------------------------------------
void
copyFacesToBoundaryFaces(const AmanziMesh::Mesh& mesh,
const Epetra_MultiVector& faces,
Epetra_MultiVector& boundary_faces);
// -----------------------------------------------------------------------------
// Given a vector on faces, import to vector on boundary faces
// -----------------------------------------------------------------------------
void
copyBoundaryFacesToFaces(const AmanziMesh::Mesh& mesh,
const Epetra_MultiVector& boundary_faces,
Epetra_MultiVector& faces);
// -----------------------------------------------------------------------------
// Given a vector on cells, set the boundary_face entries by their internal cell
// -----------------------------------------------------------------------------
void
copyCellsToBoundaryFaces(const AmanziMesh::Mesh& mesh,
const Epetra_MultiVector& cells,
Epetra_MultiVector& boundary_faces);
// -----------------------------------------------------------------------------
// Given a boundary face f, return the exterior normal. If f is an interior face,
// dir = 0 and normal orientation is not be reliable in parallel algorithms
// -----------------------------------------------------------------------------
AmanziGeometry::Point
getFaceNormalExterior(const AmanziMesh::Mesh& mesh, int f, int* dir);
// -----------------------------------------------------------------------------
// Given a cell c and face f, returns the neighbooring cell
// -----------------------------------------------------------------------------
int
cell_get_face_adj_cell(const AmanziMesh::Mesh& mesh, int c, int f);
} // namespace AmanziMesh
} // namespace Amanzi
| 44.880952 | 85 | 0.449072 | [
"mesh",
"vector"
] |
16db0446611d0e018b41460dc535721c0bd12876 | 1,658 | cpp | C++ | src/+cv/logPolar.cpp | 1123852253/mexopencv | 17db690133299f561924a45e9092673a4df66c5b | [
"BSD-3-Clause"
] | 571 | 2015-01-04T06:23:19.000Z | 2022-03-31T07:37:19.000Z | src/+cv/logPolar.cpp | 1123852253/mexopencv | 17db690133299f561924a45e9092673a4df66c5b | [
"BSD-3-Clause"
] | 362 | 2015-01-06T14:20:46.000Z | 2022-01-20T08:10:46.000Z | src/+cv/logPolar.cpp | 1123852253/mexopencv | 17db690133299f561924a45e9092673a4df66c5b | [
"BSD-3-Clause"
] | 300 | 2015-01-20T03:21:27.000Z | 2022-03-31T07:36:37.000Z | /**
* @file logPolar.cpp
* @brief mex interface for cv::logPolar
* @ingroup imgproc
* @author Amro
* @date 2015
*/
#include "mexopencv.hpp"
#include "opencv2/imgproc.hpp"
using namespace std;
using namespace cv;
/**
* Main entry called from Matlab
* @param nlhs number of left-hand-side arguments
* @param plhs pointers to mxArrays in the left-hand-side
* @param nrhs number of right-hand-side arguments
* @param prhs pointers to mxArrays in the right-hand-side
*/
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
// Check the number of arguments
nargchk(nrhs>=3 && (nrhs%2)==1 && nlhs<=1);
// Argument vector
vector<MxArray> rhs(prhs, prhs+nrhs);
// Option processing
int flags = cv::INTER_LINEAR;
bool fillOutliersFlag = true;
bool invMapFlag = false;
for (int i=3; i<nrhs; i+=2) {
string key(rhs[i].toString());
if (key == "Interpolation")
flags = (rhs[i+1].isChar()) ?
InterpType[rhs[i+1].toString()] : rhs[i+1].toInt();
else if (key == "FillOutliers")
fillOutliersFlag = rhs[i+1].toBool();
else if (key == "InverseMap")
invMapFlag = rhs[i+1].toBool();
else
mexErrMsgIdAndTxt("mexopencv:error",
"Unrecognized option %s", key.c_str());
}
flags |= (fillOutliersFlag ? cv::WARP_FILL_OUTLIERS : 0);
flags |= (invMapFlag ? cv::WARP_INVERSE_MAP : 0);
// Process
Mat src(rhs[0].toMat()), dst;
Point2f center(rhs[1].toPoint2f());
double M = rhs[2].toDouble();
logPolar(src, dst, center, M, flags);
plhs[0] = MxArray(dst);
}
| 30.145455 | 76 | 0.609771 | [
"vector"
] |
16e287e77468e194fb2c2bbd46734a06665044bd | 198 | hpp | C++ | waveform/wave.hpp | WatorVapor/move.wator | 406a10d259fdfd251fe0d159c95aecd16c4c23ce | [
"MIT"
] | null | null | null | waveform/wave.hpp | WatorVapor/move.wator | 406a10d259fdfd251fe0d159c95aecd16c4c23ce | [
"MIT"
] | null | null | null | waveform/wave.hpp | WatorVapor/move.wator | 406a10d259fdfd251fe0d159c95aecd16c4c23ce | [
"MIT"
] | 1 | 2020-08-17T13:02:19.000Z | 2020-08-17T13:02:19.000Z | #include <string>
#include <vector>
#include <deque>
using namespace std;
vector<vector<int16_t>> readWave(const string &path);
void writeWave(const string &path,const deque<deque<int16_t>> &data);
| 28.285714 | 69 | 0.762626 | [
"vector"
] |
16ea41b64d65f3408ba296e6fd191aefb5c5735b | 4,269 | cc | C++ | third_party/blink/renderer/core/html/html_plugin_element_test.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | third_party/blink/renderer/core/html/html_plugin_element_test.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 113 | 2015-05-04T09:58:14.000Z | 2022-01-31T19:35:03.000Z | third_party/blink/renderer/core/html/html_plugin_element_test.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/renderer/core/html/html_plugin_element.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/public/web/web_plugin_params.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/exported/web_plugin_container_impl.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/frame/settings.h"
#include "third_party/blink/renderer/core/loader/empty_clients.h"
#include "third_party/blink/renderer/core/testing/fake_web_plugin.h"
#include "third_party/blink/renderer/core/testing/page_test_base.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
namespace blink {
namespace {
class TestPluginLocalFrameClient : public EmptyLocalFrameClient {
public:
TestPluginLocalFrameClient() = default;
int plugin_created_count() const { return plugin_created_count_; }
private:
WebPluginContainerImpl* CreatePlugin(HTMLPlugInElement& element,
const KURL& url,
const Vector<String>& param_names,
const Vector<String>& param_values,
const String& mime_type,
bool load_manually) override {
++plugin_created_count_;
// Based on LocalFrameClientImpl::CreatePlugin
WebPluginParams params;
params.url = url;
params.mime_type = mime_type;
params.attribute_names = param_names;
params.attribute_values = param_values;
params.load_manually = load_manually;
WebPlugin* web_plugin = new FakeWebPlugin(params);
if (!web_plugin)
return nullptr;
// The container takes ownership of the WebPlugin.
auto* container =
MakeGarbageCollected<WebPluginContainerImpl>(element, web_plugin);
if (!web_plugin->Initialize(container))
return nullptr;
if (!element.GetLayoutObject())
return nullptr;
return container;
}
int plugin_created_count_ = 0;
};
} // namespace
class HTMLPlugInElementTest : public PageTestBase,
public testing::WithParamInterface<const char*> {
protected:
void SetUp() final {
frame_client_ = MakeGarbageCollected<TestPluginLocalFrameClient>();
PageTestBase::SetupPageWithClients(nullptr, frame_client_, nullptr);
GetFrame().GetSettings()->SetPluginsEnabled(true);
}
void TearDown() final {
PageTestBase::TearDown();
frame_client_ = nullptr;
}
LocalFrameView& GetFrameView() const {
return GetDummyPageHolder().GetFrameView();
}
int plugin_created_count() const {
return frame_client_->plugin_created_count();
}
private:
Persistent<TestPluginLocalFrameClient> frame_client_;
};
INSTANTIATE_TEST_SUITE_P(All,
HTMLPlugInElementTest,
testing::Values("embed", "object"));
TEST_P(HTMLPlugInElementTest, RemovePlugin) {
constexpr char kDivWithPlugin[] = R"HTML(
<div>
<%s id='test_plugin'
type='application/x-test-plugin'
src='test_plugin'>
</%s>
</div>
)HTML";
const char* container_type = GetParam();
GetDocument().body()->setInnerHTML(
String::Format(kDivWithPlugin, container_type, container_type));
auto* plugin =
To<HTMLPlugInElement>(GetDocument().getElementById("test_plugin"));
ASSERT_TRUE(plugin);
EXPECT_EQ(container_type, plugin->tagName().LowerASCII());
UpdateAllLifecyclePhasesForTest();
plugin->UpdatePlugin();
EXPECT_EQ(1, plugin_created_count());
auto* owned_plugin = plugin->OwnedPlugin();
ASSERT_TRUE(owned_plugin);
EXPECT_EQ(1u, GetFrameView().Plugins().size());
ASSERT_TRUE(GetFrameView().Plugins().Contains(owned_plugin));
plugin->parentNode()->removeChild(plugin);
EXPECT_FALSE(GetDocument().HasElementWithId("test_plugin"));
UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(0u, GetFrameView().Plugins().size());
EXPECT_FALSE(GetFrameView().Plugins().Contains(owned_plugin));
}
} // namespace blink
| 31.389706 | 79 | 0.698993 | [
"object",
"vector"
] |
16ed6da982b628fa864fb209babf6d0bb3566360 | 7,227 | cpp | C++ | velocity-engine/VESceneGraph.cpp | davedissian/archive | a28072a70d7dc3bb88e9a268aea99667f656c100 | [
"MIT"
] | null | null | null | velocity-engine/VESceneGraph.cpp | davedissian/archive | a28072a70d7dc3bb88e9a268aea99667f656c100 | [
"MIT"
] | null | null | null | velocity-engine/VESceneGraph.cpp | davedissian/archive | a28072a70d7dc3bb88e9a268aea99667f656c100 | [
"MIT"
] | null | null | null | /*
Velocity Engine
By SerialVelocity
*/
#include "VE.hpp"
using namespace VE;
// Scene Node
SceneNode::SceneNode( bool addToSceneGraph, int nodeType )
{
// Set all members to default values
mReady = false;
mSceneGraph = gEngine->getGraphics()->getSceneGraph();
mNodeType = nodeType;
// Trigger an event to add this to the scene graph
if( addToSceneGraph )
gEngine->postEvent( ET_NEW_SCENE_NODE, EP_IMMEDIATE, (void*)this );
}
void SceneNode::setLocalTransform( D3DXMATRIX *transform )
{
// Update the node transformation
mLocalTransform = *transform;
}
void SceneNode::computeGlobalTransform()
{
// Add transform to the stack
mSceneGraph->pushMatrix( &mLocalTransform );
// Set the global transform
mGlobalTransform = mSceneGraph->getTop();
// Iterate through each child
for( NodeList::iterator i = mChildren.begin(); i != mChildren.end(); i++ )
{
// Compute the global transform
SceneNode *node = *i;
node->computeGlobalTransform();
}
// Remove transform from the stack
mSceneGraph->popMatrix();
}
void SceneNode::addChild( SceneNode *node )
{
// Add a child
mChildren.push_back( node );
}
void SceneNode::removeChild( SceneNode *node )
{
// Remove the child specified
mChildren.remove( node );
}
void SceneNode::onPreRender()
{
// Update world matrix
gEngine->getGraphics()->setWorld( &mGlobalTransform );
}
void SceneNode::onRender()
{
// Render code here
}
void SceneNode::onRenderChildren()
{
// Iterate through each child
for( NodeList::iterator i = mChildren.begin(); i != mChildren.end(); i++ )
{
// Render the node
SceneNode *node = *i;
node->onPreRender();
node->onRender();
node->onRenderChildren();
node->onPostRender();
}
}
void SceneNode::onPostRender()
{
}
bool SceneNode::isReady()
{
// Return the flag stating whether the node is ready
return mReady;
}
SceneNode *SceneNode::getParent()
{
// Return the parent
return mParent;
}
D3DXMATRIX &SceneNode::getLocalTransform()
{
// Return the local transform matrix
return mLocalTransform;
}
D3DXMATRIX &SceneNode::getGlobalTransform()
{
// Return the local transform matrix
return mGlobalTransform;
}
int SceneNode::getType()
{
// Return the type
return mNodeType;
}
// Mesh Node
MeshNode::MeshNode( bool addToSceneGraph, int nodeType ) : SceneNode( addToSceneGraph, nodeType )
{
// Set all members to default values
mMesh = 0;
mEffect = 0;
D3DXMatrixIdentity( &mPrevWVP );
}
MeshNode::~MeshNode()
{
// Release the effect
SAFE_RELEASE( mEffect );
// Release the mesh
SAFE_RELEASE( mMesh );
}
void MeshNode::load( const char *meshFilename, const char *effectFilename )
{
// Load the mesh
std::string temp;
temp = VE_DIR_MODELS;
temp += meshFilename;
Resource *meshResource = gResCache->load( temp.c_str() );
HRESULT hr = D3DXLoadMeshFromXInMemory( meshResource->data(), meshResource->size(), D3DXMESH_SYSTEMMEM, gEngine->getGraphics()->getDevice(), 0, 0, 0, 0, &mMesh );
if( FAILED( hr ) )
{
LOGWRITE( "Failed to load " << meshFilename );
return;
}
// Load and compile the effect
ID3DXBuffer *errors;
temp = VE_DIR_SHADERS;
temp += effectFilename;
Resource *effectResource = gResCache->load( temp.c_str() );
D3DXCreateEffect( gEngine->getGraphics()->getDevice(), effectResource->data(), effectResource->size(), 0, 0, 0, 0, &mEffect, &errors );
if( errors )
{
LOGWRITE( "Shader " << effectFilename << " failed to compile." );
LOGWRITE( static_cast<char*>( errors->GetBufferPointer() ) );
SAFE_RELEASE( mMesh );
return;
}
// Find the best technique
D3DXHANDLE hTech;
mEffect->FindNextValidTechnique( 0, &hTech );
mEffect->SetTechnique( hTech );
// Ready
mReady = true;
}
void MeshNode::onRender()
{
// If the mesh isnt ready, return
if( mReady == false ) return;
// Update parameters
gEngine->getGraphics()->passSemanticValues( mEffect );
D3DXHANDLE handle = mEffect->GetParameterBySemantic( 0, "PREVWORLDVIEWPROJECTION" );
if( handle ) mEffect->SetMatrix( handle, &mPrevWVP );
// Render each pass
UINT numPasses;
mEffect->Begin( &numPasses, 0 );
for( unsigned int i = 0; i < numPasses; i++ )
{
mEffect->BeginPass( i );
mMesh->DrawSubset( 0 );
mEffect->EndPass();
}
mEffect->End();
// Update Prev WVP
mPrevWVP = gEngine->getGraphics()->getWorld() * gEngine->getGraphics()->getView() * gEngine->getGraphics()->getProjection();
}
ID3DXMesh *MeshNode::getMesh()
{
// Return the mesh
return mMesh;
}
ID3DXEffect *MeshNode::getEffect()
{
// Return the effect
return mEffect;
}
// Sprite Node
// Camera Node
Camera::Camera() : SceneNode( false, SNT_SOLID )
{
// Set all members to default values
mSceneGraph = gEngine->getGraphics()->getSceneGraph();
mFOV = 60.0f;
mAspect = 1.0f;
mZNear = 1.0f;
mZFar = 1000.0f;
}
Camera::~Camera()
{
}
void Camera::setup( float FOV, float aspect, float zNear, float zFar )
{
// Setup camera properties
mFOV = FOV;
mAspect = aspect;
mZNear = zNear;
mZFar = zFar;
}
void Camera::onRender()
{
}
void Camera::updateView()
{
// Generate view matrix
D3DXMATRIX view;
D3DXMatrixInverse( &view, 0, &mLocalTransform );
gEngine->getGraphics()->setView( &view );
}
void Camera::updateProjection()
{
// Generate projection matrix
D3DXMATRIX projection;
D3DXMatrixPerspectiveFovLH( &projection, D3DXToRadian( mFOV ), mAspect, mZNear, mZFar );
gEngine->getGraphics()->setProjection( &projection );
}
// Scene Graph Base
SceneGraph::SceneGraph()
{
// Create the matrix stack
D3DXCreateMatrixStack( 0, &mMatStack );
mMatStack->LoadIdentity();
// Set all members to default values
mMainCamera = mDebugCamera = 0;
}
SceneGraph::~SceneGraph()
{
// Release the matrix stack
SAFE_RELEASE( mMatStack );
}
void SceneGraph::addSceneNode( SceneNode *node )
{
// Add the node
mNodes.push_back( node );
}
void SceneGraph::removeSceneNode( SceneNode *node )
{
// Remove the node to the scene graph
mNodes.remove( node );
}
void SceneGraph::setCameras( Camera *mainCamera, Camera *debugCamera )
{
// Update the cameras
mainCamera->updateProjection();
debugCamera->updateProjection();
mMainCamera = mainCamera;
mDebugCamera = debugCamera;
}
void SceneGraph::toggleDebugCamera()
{
}
Camera *SceneGraph::getCamera()
{
// Return the current main camera
return mMainCamera;
}
void SceneGraph::pushMatrix( D3DXMATRIX *matrix )
{
// Push a new matrix on the stack and multiply by the argument
mMatStack->Push();
mMatStack->MultMatrixLocal( matrix );
}
void SceneGraph::popMatrix()
{
// Pop the top matrix from the stack
mMatStack->Pop();
}
D3DXMATRIX SceneGraph::getTop()
{
// Return the current top matrix
return *( mMatStack->GetTop() );
}
void SceneGraph::computeGlobalTransforms()
{
// Iterate through each child
for( NodeList::iterator i = mNodes.begin(); i != mNodes.end(); i++ )
{
// Compute the global transform
SceneNode *node = *i;
node->computeGlobalTransform();
}
}
void SceneGraph::renderScene()
{
// If the node list is empty then return
if( mNodes.empty() )
return;
// Iterate and render each node
for( NodeList::iterator i = mNodes.begin(); i != mNodes.end(); i++ )
{
// Render the node
SceneNode *node = *i;
node->onPreRender();
node->onRender();
node->onRenderChildren();
node->onPostRender();
}
} | 20.648571 | 163 | 0.700706 | [
"mesh",
"render",
"transform"
] |
a84b1d4efa53a0d24a8d1f2a7ba01b98f8f0abe9 | 8,243 | cc | C++ | apps/mnist-conv.cc | avdmitry/graphmodels | 1b4f4e50033350b5a7492752cab8879aeff8f722 | [
"MIT"
] | 1 | 2018-09-22T04:02:28.000Z | 2018-09-22T04:02:28.000Z | apps/mnist-conv.cc | avdmitry/graphmodels | 1b4f4e50033350b5a7492752cab8879aeff8f722 | [
"MIT"
] | null | null | null | apps/mnist-conv.cc | avdmitry/graphmodels | 1b4f4e50033350b5a7492752cab8879aeff8f722 | [
"MIT"
] | null | null | null | #include "utils.h"
#include "layers.h"
#include "learn.h"
#include "datasets/mnist.h"
using std::string;
using std::vector;
using std::shared_ptr;
// bs_1: 3.333 epoch| cost: 0.022| test acc: 0.990
// bs_10: 4.667 epoch| cost: 0.004| test acc: 0.990
class CnnNet : public Model
{
public:
CnnNet(int num_input_x, int num_input_y, int num_output, int batch_size)
{
static const int filter1_x = 3;
static const int filter1_y = 3;
static const int num_filters1 = 8;
static const int filter2_x = 3;
static const int filter2_y = 3;
static const int num_filters2 = 16;
graph_ = shared_ptr<Graph>(new Graph);
input_ = shared_ptr<Mat>(new Mat(num_input_x, num_input_y, 1, batch_size));
math->MemoryAlloc(input_);
math->MemoryAlloc(input_->dw_);
shared_ptr<Mat> conv1, rel1, mp1;
graph_->Process(shared_ptr<Operation>(
new ConvLayer("conv1", input_, &conv1, num_filters1, filter1_x,
filter1_y, 1, 1, 1, 1)));
graph_->Process(shared_ptr<Operation>(new ReluOp(conv1, &rel1)));
graph_->Process(shared_ptr<Operation>(
new PoolLayer(rel1, &mp1, 3, 3, 1, 1, 2, 2, MAX)));
shared_ptr<Mat> conv2, rel2, mp2;
graph_->Process(shared_ptr<Operation>(new ConvLayer(
"conv2", mp1, &conv2, num_filters2, filter2_x, filter2_y, 1, 1, 1, 1)));
graph_->Process(shared_ptr<Operation>(new ReluOp(conv2, &rel2)));
graph_->Process(shared_ptr<Operation>(
new PoolLayer(rel2, &mp2, 3, 3, 1, 1, 2, 2, MAX)));
graph_->Process(
shared_ptr<Operation>(new FCLayer("fc1", mp2, &output_, num_output)));
graph_->GetParams(params_);
for (size_t i = 0; i < params_.size(); ++i)
{
shared_ptr<Mat> &mat = params_[i];
params_prev_.emplace_back(new Mat(mat->size_, false));
math->CopyToDevice(params_prev_.back());
}
}
// Virtual functions stubs.
void Create(int idx)
{
}
void ClearPrevState()
{
}
};
void Validate(shared_ptr<Model> &net,
vector<shared_ptr<datasets::MnistObj>> &test)
{
int batch_size = net->output_->size_[3];
float acc = 0;
int test_idx = 0;
shared_ptr<Mat> labels(new Mat(1, 1, 1, batch_size, false));
while (test_idx < test.size())
{
int curr_size = batch_size;
for (int batch = 0; batch < batch_size; ++batch)
{
shared_ptr<datasets::MnistObj> &curr = test[test_idx];
for (int idx = 0; idx < 784; ++idx)
{
net->input_->data_[batch * 784 + idx] = curr->image[idx];
}
labels->data_[batch] = curr->label;
test_idx++;
if (test_idx % 1000 == 0)
{
// printf("%u ", test_idx);
}
if (test_idx == test.size())
{
curr_size = batch + 1;
break;
}
}
math->CopyToDevice(net->input_);
net->Forward(false);
math->CopyToHost(net->output_);
for (int batch = 0; batch < curr_size; ++batch)
{
float *data = &net->output_->data_[batch * 10];
int pred_idx = 0;
for (int prob_idx = 0; prob_idx < 10; ++prob_idx)
{
if (data[pred_idx] < data[prob_idx])
{
pred_idx = prob_idx;
}
}
if (labels->data_[batch] == pred_idx)
{
acc += 1;
}
}
}
acc /= test.size();
printf("| test acc: %.3f", acc);
}
int main(int argc, char *argv[])
{
if (argc < 2)
{
printf("usage: mnist_data_path [model]\n");
return -1;
}
string data_path(argv[1]);
string model_name;
if (argc > 2)
{
model_name = argv[2];
}
// srand(time(NULL));
srand(0);
math = shared_ptr<Math>(new MathCpu);
// math = shared_ptr<Math>(new MathCudnn(0));
math->Init();
datasets::Mnist mnist(data_path);
vector<shared_ptr<datasets::MnistObj>> &train = mnist.train_;
vector<shared_ptr<datasets::MnistObj>> &test = mnist.test_;
printf("train: %lu\n", train.size());
printf("test: %lu\n", test.size());
// Hyperparameters.
float learning_rate = 0.001;
float decay_rate = 0.001;
int batch_size = 10;
int output_each = 1000;
int time_each = 1000;
int validate_each = 10000;
int save_each = 10000;
int lr_drop_each = 60000;
int steps_num = 1000000;
int start_step = 0;
int output_each_curr = 0;
int time_each_curr = 0;
int save_each_curr = 0;
int lr_drop_each_curr = 0;
printf("epoch size in batches: %.1f\n", 1.0 * train.size() / batch_size);
shared_ptr<Model> net(new CnnNet(28, 28, 10, batch_size));
if (model_name.length() > 0)
{
printf("loading %s\n", model_name.c_str());
FILE *file = fopen(model_name.c_str(), "rb");
net->graph_->Load(file);
int res = fread((void *)&start_step, sizeof(int), 1, file);
printf("start_step: %u\n", start_step);
res = fread((void *)&learning_rate, sizeof(float), 1, file);
printf("learning_rate: %f\n", learning_rate);
res = fread((void *)&output_each_curr, sizeof(int), 1, file);
printf("output_each_curr: %u\n", output_each_curr);
res = fread((void *)&time_each_curr, sizeof(int), 1, file);
printf("time_each_curr: %u\n", time_each_curr);
res = fread((void *)&save_each_curr, sizeof(int), 1, file);
printf("save_each_curr: %u\n", save_each_curr);
res = fread((void *)&lr_drop_each_curr, sizeof(int), 1, file);
printf("lr_drop_each_curr: %u\n", lr_drop_each_curr);
fclose(file);
Validate(net, test);
exit(0);
}
int num_examples = 0;
int epoch_num = 0;
float cost = 0.0;
int train_idx = 0;
clock_t begin_time = clock();
for (int step = start_step + 1; step <= steps_num; ++step)
{
shared_ptr<Mat> labels(new Mat(1, 1, 1, batch_size, false));
for (int batch = 0; batch < batch_size; ++batch)
{
for (int x = 0; x < 28; ++x)
{
for (int y = 0; y < 28; ++y)
{
int idx = x + y * 28;
net->input_->data_[idx + batch * 28 * 28] =
train[train_idx]->image[idx];
}
}
labels->data_[batch] = train[train_idx]->label;
train_idx++;
if (train_idx == train.size())
{
train_idx = 0;
}
}
math->CopyToDevice(net->input_);
math->CopyToDevice(labels);
net->Forward(true);
shared_ptr<Mat> out;
cost += math->Softmax(net->output_, out, labels);
net->Backward();
LearnRmsprop(net, learning_rate, batch_size);
// LearnSGD(net, learning_rate, batch_size, decay_rate);
bool new_line = false;
num_examples = step * batch_size;
int epoch_num_curr = num_examples / train.size();
if (epoch_num != epoch_num_curr)
{
epoch_num = epoch_num_curr;
}
lr_drop_each_curr += batch_size;
if (lr_drop_each_curr >= lr_drop_each)
{
lr_drop_each_curr = 0;
learning_rate *= 0.33;
printf("learning rate: %.6f\n", learning_rate);
}
save_each_curr += batch_size;
if (save_each_curr >= save_each)
{
save_each_curr = 0;
string file_name("mnist_conv_" + std::to_string(step) + ".model");
printf("saving %s\n", file_name.c_str());
FILE *file = fopen(file_name.c_str(), "wb");
net->graph_->Save(file);
fwrite((void *)&step, sizeof(int), 1, file);
fwrite((void *)&learning_rate, sizeof(float), 1, file);
fwrite((void *)&output_each_curr, sizeof(int), 1, file);
fwrite((void *)&time_each_curr, sizeof(int), 1, file);
fwrite((void *)&save_each_curr, sizeof(int), 1, file);
fwrite((void *)&lr_drop_each_curr, sizeof(int), 1, file);
fclose(file);
}
output_each_curr += batch_size;
if (output_each_curr >= output_each)
{
output_each_curr = 0;
printf("%.3f epoch| cost: %.6f", 1.0f * num_examples / train.size(),
cost / (output_each /* * batch_size*/));
cost = 0.0;
new_line = true;
}
if (num_examples % validate_each == 0 && step != 0)
{
Validate(net, test);
new_line = true;
}
time_each_curr += batch_size;
if (time_each_curr >= time_each)
{
time_each_curr = 0;
float time_curr = float(clock() - begin_time) / CLOCKS_PER_SEC;
printf("| time: %.3f s", time_curr);
begin_time = clock();
new_line = true;
}
if (new_line)
{
printf("\n");
}
}
return 0;
}
| 27.294702 | 80 | 0.596991 | [
"vector",
"model"
] |
a85ac65089a6c5857df10632f515d5520d6aa5cd | 180 | cc | C++ | ccap/addon/hcaptha.cc | 1353619565/online-q-a-system | 598fe885ec18d6b7d7eae27bd3f60f49afc5803b | [
"MIT"
] | 459 | 2015-01-04T13:14:19.000Z | 2021-12-18T14:47:10.000Z | ccap/addon/hcaptha.cc | 1353619565/online-q-a-system | 598fe885ec18d6b7d7eae27bd3f60f49afc5803b | [
"MIT"
] | 71 | 2015-01-14T07:48:09.000Z | 2019-07-26T01:34:01.000Z | ccap/addon/hcaptha.cc | 1353619565/online-q-a-system | 598fe885ec18d6b7d7eae27bd3f60f49afc5803b | [
"MIT"
] | 91 | 2015-01-02T08:01:26.000Z | 2022-02-12T03:58:23.000Z | #include <node.h>
#include "cap.h"
using namespace v8;
void Init(Local<Object> target) {
//hcap
NODE_SET_METHOD(target, "create", cap::create);
}
NODE_MODULE(hcaptha, Init) | 12.857143 | 49 | 0.7 | [
"object"
] |
a85b813bc9d4fd6b23160f2e35f10665abf96fc7 | 181,216 | cpp | C++ | mlir_graphblas/src/lib/GraphBLAS/GraphBLASLowerPass.cpp | vishalbelsare/mlir-graphblas | ae9e5bd97ad63f0182230dbcde2a205b4086e607 | [
"Apache-2.0",
"MIT"
] | null | null | null | mlir_graphblas/src/lib/GraphBLAS/GraphBLASLowerPass.cpp | vishalbelsare/mlir-graphblas | ae9e5bd97ad63f0182230dbcde2a205b4086e607 | [
"Apache-2.0",
"MIT"
] | null | null | null | mlir_graphblas/src/lib/GraphBLAS/GraphBLASLowerPass.cpp | vishalbelsare/mlir-graphblas | ae9e5bd97ad63f0182230dbcde2a205b4086e607 | [
"Apache-2.0",
"MIT"
] | null | null | null | //===- GraphBLASPasses.cpp - GraphBLAS dialect passes ---------*- C++ -*-===//
//
// TODO add documentation
//
//===--------------------------------------------------------------------===//
#include "mlir/Dialect/Bufferization/IR/Bufferization.h"
#include "mlir/Dialect/LLVMIR/LLVMDialect.h"
#include "mlir/Dialect/Linalg/Transforms/Transforms.h"
#include "mlir/Dialect/SparseTensor/IR/SparseTensor.h"
#include "mlir/IR/Region.h"
#include "mlir/Pass/Pass.h"
#include "mlir/Transforms/GreedyPatternRewriteDriver.h"
#include "llvm/ADT/None.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/TypeSwitch.h"
#include "llvm/Support/raw_ostream.h"
#include "GraphBLAS/GraphBLASArrayUtils.h"
#include "GraphBLAS/GraphBLASDialect.h"
#include "GraphBLAS/GraphBLASPasses.h"
#include "GraphBLAS/GraphBLASUtils.h"
using namespace ::mlir;
using namespace std::placeholders;
namespace {
//===----------------------------------------------------------------------===//
// Passes declaration.
//===----------------------------------------------------------------------===//
#define GEN_PASS_CLASSES
#include "GraphBLAS/GraphBLASPasses.h.inc"
//===----------------------------------------------------------------------===//
// Passes implementation.
//===----------------------------------------------------------------------===//
class LowerSizeRewrite : public OpRewritePattern<graphblas::SizeOp> {
public:
using OpRewritePattern<graphblas::SizeOp>::OpRewritePattern;
LogicalResult matchAndRewrite(graphblas::SizeOp op,
PatternRewriter &rewriter) const override {
Location loc = op->getLoc();
Value c0 = rewriter.create<arith::ConstantIndexOp>(loc, 0);
Value inputTensor = op.input();
Value size = rewriter.create<tensor::DimOp>(loc, inputTensor, c0);
rewriter.replaceOp(op, size);
return success();
};
};
class LowerNumRowsRewrite : public OpRewritePattern<graphblas::NumRowsOp> {
public:
using OpRewritePattern<graphblas::NumRowsOp>::OpRewritePattern;
LogicalResult matchAndRewrite(graphblas::NumRowsOp op,
PatternRewriter &rewriter) const override {
Location loc = op->getLoc();
Value c0 = rewriter.create<arith::ConstantIndexOp>(loc, 0);
Value inputTensor = op.input();
Value nrows = rewriter.create<tensor::DimOp>(loc, inputTensor, c0);
rewriter.replaceOp(op, nrows);
return success();
};
};
class LowerNumColsRewrite : public OpRewritePattern<graphblas::NumColsOp> {
public:
using OpRewritePattern<graphblas::NumColsOp>::OpRewritePattern;
LogicalResult matchAndRewrite(graphblas::NumColsOp op,
PatternRewriter &rewriter) const override {
Location loc = op->getLoc();
Value c1 = rewriter.create<arith::ConstantIndexOp>(loc, 1);
Value inputTensor = op.input();
Value ncols = rewriter.create<tensor::DimOp>(loc, inputTensor, c1);
rewriter.replaceOp(op, ncols);
return success();
};
};
class LowerNumValsRewrite : public OpRewritePattern<graphblas::NumValsOp> {
public:
using OpRewritePattern<graphblas::NumValsOp>::OpRewritePattern;
LogicalResult matchAndRewrite(graphblas::NumValsOp op,
PatternRewriter &rewriter) const override {
Location loc = op->getLoc();
Value inputTensor = op.input();
Type inputType = inputTensor.getType();
sparse_tensor::SparseTensorEncodingAttr sparseEncoding =
sparse_tensor::getSparseTensorEncoding(inputType);
unsigned pointerBitWidth = sparseEncoding.getPointerBitWidth();
Type pointerType = rewriter.getIntegerType(pointerBitWidth);
Type indexType = rewriter.getIndexType();
// Access the pointers
Type memref1DPointerType = MemRefType::get({-1}, pointerType);
unsigned rank = inputType.dyn_cast<RankedTensorType>().getRank();
Value c_rank_minus_1 =
rewriter.create<arith::ConstantIndexOp>(loc, rank - 1);
Value ptrs = rewriter.create<sparse_tensor::ToPointersOp>(
loc, memref1DPointerType, inputTensor, c_rank_minus_1);
// Find length of pointer array
Value npointers;
if (rank == 1) {
npointers = rewriter.create<arith::ConstantIndexOp>(loc, 1);
} else {
Value dimForPointers;
if (hasRowOrdering(inputType)) {
dimForPointers = rewriter.create<arith::ConstantIndexOp>(loc, 0);
} else {
dimForPointers = rewriter.create<arith::ConstantIndexOp>(loc, 1);
}
npointers =
rewriter.create<tensor::DimOp>(loc, inputTensor, dimForPointers);
}
// The last value from the pointers is the number of nonzero values
Value nnz_ptype = rewriter.create<memref::LoadOp>(loc, ptrs, npointers);
Value nnz = rewriter.create<arith::IndexCastOp>(loc, nnz_ptype, indexType);
rewriter.replaceOp(op, nnz);
return success();
};
};
class LowerDupRewrite : public OpRewritePattern<graphblas::DupOp> {
public:
using OpRewritePattern<graphblas::DupOp>::OpRewritePattern;
LogicalResult matchAndRewrite(graphblas::DupOp op,
PatternRewriter &rewriter) const override {
ModuleOp module = op->getParentOfType<ModuleOp>();
Location loc = op->getLoc();
Value inputTensor = op.input();
Value duplicate = callDupTensor(rewriter, module, loc, inputTensor);
rewriter.replaceOp(op, duplicate);
return success();
};
};
class LowerConvertLayoutRewrite
: public OpRewritePattern<graphblas::ConvertLayoutOp> {
public:
using OpRewritePattern<graphblas::ConvertLayoutOp>::OpRewritePattern;
LogicalResult matchAndRewrite(graphblas::ConvertLayoutOp op,
PatternRewriter &rewriter) const override {
MLIRContext *context = op.getContext();
ModuleOp module = op->getParentOfType<ModuleOp>();
Location loc = op->getLoc();
Value inputTensor = op.input();
Type inputType = inputTensor.getType();
Type outputType = op->getResultTypes().front();
// Shortcut operation if no change
if (inputType == outputType) {
rewriter.replaceOp(op, inputTensor);
return success();
}
// otherwise, the rest of this function changes the data layout
RankedTensorType inputTensorType = inputType.dyn_cast<RankedTensorType>();
sparse_tensor::SparseTensorEncodingAttr sparseEncoding =
sparse_tensor::getSparseTensorEncoding(inputTensorType);
unsigned ptrBitWidth = sparseEncoding.getPointerBitWidth();
unsigned idxBitWidth = sparseEncoding.getIndexBitWidth();
Type valueType = inputTensorType.getElementType();
Type int64Type = rewriter.getIntegerType(64);
Type indexType = rewriter.getIndexType();
// Initial constants
Value c0 = rewriter.create<arith::ConstantIndexOp>(loc, 0);
Value c1 = rewriter.create<arith::ConstantIndexOp>(loc, 1);
Value c0_64 = rewriter.create<arith::ConstantIntOp>(loc, 0, int64Type);
Value c1_64 = rewriter.create<arith::ConstantIntOp>(loc, 1, int64Type);
// Get sparse tensor info
Type memref1DI64Type = MemRefType::get({-1}, int64Type);
Type memref1DValueType = MemRefType::get({-1}, valueType);
Value inputPtrs = rewriter.create<sparse_tensor::ToPointersOp>(
loc, memref1DI64Type, inputTensor, c1);
Value inputIndices = rewriter.create<sparse_tensor::ToIndicesOp>(
loc, memref1DI64Type, inputTensor, c1);
Value inputValues = rewriter.create<sparse_tensor::ToValuesOp>(
loc, memref1DValueType, inputTensor);
Value nrow = rewriter.create<graphblas::NumRowsOp>(loc, inputTensor);
Value ncol = rewriter.create<graphblas::NumColsOp>(loc, inputTensor);
Value nnz = rewriter.create<graphblas::NumValsOp>(loc, inputTensor);
Value duplicate = callEmptyLike(rewriter, module, loc, inputTensor);
// Beyond this point, the algorithm assumes csr->csc,
// so swap nrow/ncol for csc->csr
bool outputIsCSC = hasColumnOrdering(outputType);
// update the reverse index map and dimensions for CSR or CSC
if (outputIsCSC) {
callAssignRev(rewriter, module, loc, duplicate, c0, c1);
callAssignRev(rewriter, module, loc, duplicate, c1, c0);
callResizeDim(rewriter, module, loc, duplicate, c0, ncol);
callResizeDim(rewriter, module, loc, duplicate, c1, nrow);
} else {
callAssignRev(rewriter, module, loc, duplicate, c0, c0);
callAssignRev(rewriter, module, loc, duplicate, c1, c1);
callResizeDim(rewriter, module, loc, duplicate, c0, nrow);
callResizeDim(rewriter, module, loc, duplicate, c1, ncol);
Value tmp = nrow;
nrow = ncol;
ncol = tmp;
}
Value ncols_plus_one = rewriter.create<arith::AddIOp>(loc, ncol, c1);
callResizePointers(rewriter, module, loc, duplicate, c1, ncols_plus_one);
callResizeIndex(rewriter, module, loc, duplicate, c1, nnz);
callResizeValues(rewriter, module, loc, duplicate, nnz);
// the verify function will ensure that this is CSR->CSC or CSC->CSR
Value output = castToPtr8(rewriter, module, loc, duplicate);
RankedTensorType flippedType = getSingleCompressedMatrixType(
context, inputTensorType.getShape(), outputIsCSC, valueType,
ptrBitWidth, idxBitWidth);
output = castToTensor(rewriter, module, loc, output, flippedType);
Value outputPtrs = rewriter.create<sparse_tensor::ToPointersOp>(
loc, memref1DI64Type, output, c1);
Value outputIndices = rewriter.create<sparse_tensor::ToIndicesOp>(
loc, memref1DI64Type, output, c1);
Value outputValues = rewriter.create<sparse_tensor::ToValuesOp>(
loc, memref1DValueType, output);
// compute number of non-zero entries per column of A
// init B.pointers to zero
scf::ForOp initLoop = rewriter.create<scf::ForOp>(loc, c0, ncol, c1);
Value initLoopIdx = initLoop.getInductionVar();
rewriter.setInsertionPointToStart(initLoop.getBody());
rewriter.create<memref::StoreOp>(loc, c0_64, outputPtrs, initLoopIdx);
rewriter.setInsertionPointAfter(initLoop);
// store pointers
scf::ForOp ptrLoop = rewriter.create<scf::ForOp>(loc, c0, nnz, c1);
Value ptrLoopIdx = ptrLoop.getInductionVar();
rewriter.setInsertionPointToStart(ptrLoop.getBody());
Value colA64 =
rewriter.create<memref::LoadOp>(loc, inputIndices, ptrLoopIdx);
Value colA = rewriter.create<arith::IndexCastOp>(loc, colA64, indexType);
Value colB = rewriter.create<memref::LoadOp>(loc, outputPtrs, colA);
Value colB1 = rewriter.create<arith::AddIOp>(loc, colB, c1_64);
rewriter.create<memref::StoreOp>(loc, colB1, outputPtrs, colA);
rewriter.setInsertionPointAfter(ptrLoop);
// cumsum the nnz per column to get Bp
rewriter.create<memref::StoreOp>(loc, c0_64, outputPtrs, ncol);
scf::ForOp colAccLoop = rewriter.create<scf::ForOp>(loc, c0, ncol, c1);
Value colAccLoopIdx = colAccLoop.getInductionVar();
rewriter.setInsertionPointToStart(colAccLoop.getBody());
Value temp =
rewriter.create<memref::LoadOp>(loc, outputPtrs, colAccLoopIdx);
Value cumsum = rewriter.create<memref::LoadOp>(loc, outputPtrs, ncol);
rewriter.create<memref::StoreOp>(loc, cumsum, outputPtrs, colAccLoopIdx);
Value cumsum2 = rewriter.create<arith::AddIOp>(loc, cumsum, temp);
rewriter.create<memref::StoreOp>(loc, cumsum2, outputPtrs, ncol);
rewriter.setInsertionPointAfter(colAccLoop);
// copy values
scf::ForOp outerLoop = rewriter.create<scf::ForOp>(loc, c0, nrow, c1);
Value rowIdx = outerLoop.getInductionVar();
rewriter.setInsertionPointToStart(outerLoop.getBody());
Value row_64 = rewriter.create<arith::IndexCastOp>(loc, rowIdx, int64Type);
Value j_start_64 = rewriter.create<memref::LoadOp>(loc, inputPtrs, rowIdx);
Value j_start =
rewriter.create<arith::IndexCastOp>(loc, j_start_64, indexType);
Value row_plus1 = rewriter.create<arith::AddIOp>(loc, rowIdx, c1);
Value j_end_64 = rewriter.create<memref::LoadOp>(loc, inputPtrs, row_plus1);
Value j_end = rewriter.create<arith::IndexCastOp>(loc, j_end_64, indexType);
scf::ForOp innerLoop = rewriter.create<scf::ForOp>(loc, j_start, j_end, c1);
Value jj = innerLoop.getInductionVar();
rewriter.setInsertionPointToStart(innerLoop.getBody());
Value col_64 = rewriter.create<memref::LoadOp>(loc, inputIndices, jj);
Value col = rewriter.create<arith::IndexCastOp>(loc, col_64, indexType);
Value dest_64 = rewriter.create<memref::LoadOp>(loc, outputPtrs, col);
Value dest = rewriter.create<arith::IndexCastOp>(loc, dest_64, indexType);
rewriter.create<memref::StoreOp>(loc, row_64, outputIndices, dest);
Value axjj = rewriter.create<memref::LoadOp>(loc, inputValues, jj);
rewriter.create<memref::StoreOp>(loc, axjj, outputValues, dest);
// Bp[col]++
Value bp_inc = rewriter.create<memref::LoadOp>(loc, outputPtrs, col);
Value bp_inc1 = rewriter.create<arith::AddIOp>(loc, bp_inc, c1_64);
rewriter.create<memref::StoreOp>(loc, bp_inc1, outputPtrs, col);
rewriter.setInsertionPointAfter(outerLoop);
Value last_last = rewriter.create<memref::LoadOp>(loc, outputPtrs, ncol);
rewriter.create<memref::StoreOp>(loc, c0_64, outputPtrs, ncol);
scf::ForOp finalLoop = rewriter.create<scf::ForOp>(loc, c0, ncol, c1);
Value iCol = finalLoop.getInductionVar();
rewriter.setInsertionPointToStart(finalLoop.getBody());
Value swapTemp = rewriter.create<memref::LoadOp>(loc, outputPtrs, iCol);
Value last = rewriter.create<memref::LoadOp>(loc, outputPtrs, ncol);
rewriter.create<memref::StoreOp>(loc, last, outputPtrs, iCol);
rewriter.create<memref::StoreOp>(loc, swapTemp, outputPtrs, ncol);
rewriter.setInsertionPointAfter(finalLoop);
rewriter.create<memref::StoreOp>(loc, last_last, outputPtrs, ncol);
rewriter.replaceOp(op, output);
cleanupIntermediateTensor(rewriter, module, loc, output);
return success();
};
};
class LowerCastRewrite : public OpRewritePattern<graphblas::CastOp> {
public:
using OpRewritePattern<graphblas::CastOp>::OpRewritePattern;
LogicalResult matchAndRewrite(graphblas::CastOp op,
PatternRewriter &rewriter) const override {
// MLIRContext *context = op.getContext();
ModuleOp module = op->getParentOfType<ModuleOp>();
Location loc = op->getLoc();
Value input = op.input();
Type inputType = input.getType();
Type outputType = op->getResultTypes().front();
// Shortcut operation if no change
if (inputType == outputType) {
rewriter.replaceOp(op, input);
return success();
}
RankedTensorType inputTensorType = inputType.cast<RankedTensorType>();
// sparse_tensor::SparseTensorEncodingAttr inputSparseEncoding =
// sparse_tensor::getSparseTensorEncoding(inputTensorType);
// unsigned inputPtrBitWidth = inputSparseEncoding.getPointerBitWidth();
// unsigned inputIdxBitWidth = inputSparseEncoding.getIndexBitWidth();
Type inputValueType = inputTensorType.getElementType();
RankedTensorType outputTensorType = outputType.cast<RankedTensorType>();
// sparse_tensor::SparseTensorEncodingAttr outputSparseEncoding =
// sparse_tensor::getSparseTensorEncoding(outputTensorType);
// unsigned outputPtrBitWidth = outputSparseEncoding.getPointerBitWidth();
// unsigned outputIdxBitWidth = outputSparseEncoding.getIndexBitWidth();
Type outputValueType = outputTensorType.getElementType();
unsigned rank = inputTensorType.getRank();
Type memref1DIValueType = MemRefType::get({-1}, inputValueType);
Type memref1DOValueType = MemRefType::get({-1}, outputValueType);
// Initial constants
Value c0 = rewriter.create<arith::ConstantIndexOp>(loc, 0);
Value c1 = rewriter.create<arith::ConstantIndexOp>(loc, 1);
// Get the shape as a ValueRange
ValueRange shape;
if (rank == 1) {
Value size = rewriter.create<graphblas::SizeOp>(loc, input);
shape = ValueRange{size};
} else {
Value nrows = rewriter.create<graphblas::NumRowsOp>(loc, input);
Value ncols = rewriter.create<graphblas::NumColsOp>(loc, input);
shape = ValueRange{nrows, ncols};
}
// Create a new tensor with the correct output value type
Value output =
rewriter.create<sparse_tensor::InitOp>(loc, outputType, shape);
// Make a copy of the input so we can swap the pointers and indices
Value duplicate = callDupTensor(rewriter, module, loc, input);
callSwapPointers(rewriter, module, loc, duplicate, output);
callSwapIndices(rewriter, module, loc, duplicate, output);
rewriter.create<sparse_tensor::ReleaseOp>(loc, duplicate);
// Cast values to new dtype
Value nnz = rewriter.create<graphblas::NumValsOp>(loc, input);
callResizeValues(rewriter, module, loc, output, nnz);
Value inputValues = rewriter.create<sparse_tensor::ToValuesOp>(
loc, memref1DIValueType, input);
Value outputValues = rewriter.create<sparse_tensor::ToValuesOp>(
loc, memref1DOValueType, output);
scf::ParallelOp loop = rewriter.create<scf::ParallelOp>(loc, c0, nnz, c1);
Value loopIdx = loop.getInductionVars().front();
{
rewriter.setInsertionPointToStart(loop.getBody());
Value val = rewriter.create<memref::LoadOp>(loc, inputValues, loopIdx);
Value newVal;
if (auto itype = inputValueType.dyn_cast<IntegerType>()) {
newVal = llvm::TypeSwitch<Type, Value>(outputValueType)
.Case<IntegerType>([&](IntegerType otype) {
// int -> int
unsigned iBitWidth = itype.getWidth();
unsigned oBitWidth = otype.getWidth();
if (iBitWidth < oBitWidth)
return rewriter
.create<arith::ExtSIOp>(loc, outputValueType, val)
.getResult();
else if (iBitWidth > oBitWidth)
return rewriter
.create<arith::TruncIOp>(loc, outputValueType, val)
.getResult();
else
return val;
})
.Case<FloatType>([&](FloatType otype) {
// int -> float
return rewriter.create<arith::SIToFPOp>(
loc, outputValueType, val);
});
} else {
newVal = llvm::TypeSwitch<Type, Value>(outputValueType)
.Case<IntegerType>([&](IntegerType otype) {
// float -> int
return rewriter.create<arith::FPToSIOp>(
loc, outputValueType, val);
})
.Case<FloatType>([&](FloatType otype) {
// float -> float
unsigned iBitWidth =
inputValueType.dyn_cast<FloatType>().getWidth();
unsigned oBitWidth = otype.getWidth();
if (iBitWidth < oBitWidth)
return rewriter
.create<arith::ExtFOp>(loc, outputValueType, val)
.getResult();
else if (iBitWidth > oBitWidth)
return rewriter
.create<arith::TruncFOp>(loc, outputValueType, val)
.getResult();
else
return val;
});
}
rewriter.create<memref::StoreOp>(loc, newVal, outputValues, loopIdx);
rewriter.setInsertionPointAfter(loop);
}
rewriter.replaceOp(op, output);
cleanupIntermediateTensor(rewriter, module, loc, output);
return success();
};
};
class TransposeDWIMRewrite : public OpRewritePattern<graphblas::TransposeOp> {
public:
using OpRewritePattern<graphblas::TransposeOp>::OpRewritePattern;
static bool needsDWIM(graphblas::TransposeOp op) {
Value inputTensor = op.input();
RankedTensorType inputType =
inputTensor.getType().dyn_cast<RankedTensorType>();
RankedTensorType outputType =
op->getResultTypes().front().dyn_cast<RankedTensorType>();
bool inputTypeIsCSR = hasRowOrdering(inputType);
bool outputTypeIsCSR = hasRowOrdering(outputType);
return (inputTypeIsCSR == outputTypeIsCSR);
};
LogicalResult match(graphblas::TransposeOp op) const override {
if (needsDWIM(op))
return success();
else
return failure();
};
void rewrite(graphblas::TransposeOp op,
PatternRewriter &rewriter) const override {
MLIRContext *context = op.getContext();
Location loc = op->getLoc();
Value inputTensor = op.input();
RankedTensorType outputType =
op->getResultTypes().front().dyn_cast<RankedTensorType>();
RankedTensorType flippedInputType =
getFlippedLayoutType(context, inputTensor.getType());
Value flippedInput = rewriter.create<graphblas::ConvertLayoutOp>(
loc, flippedInputType, inputTensor);
Value transposed =
rewriter.create<graphblas::TransposeOp>(loc, outputType, flippedInput);
rewriter.replaceOp(op, transposed);
};
};
class LowerTransposeRewrite : public OpRewritePattern<graphblas::TransposeOp> {
public:
using OpRewritePattern<graphblas::TransposeOp>::OpRewritePattern;
LogicalResult match(graphblas::TransposeOp op) const override {
if (TransposeDWIMRewrite::needsDWIM(op))
return failure();
else
return success();
};
void rewrite(graphblas::TransposeOp op,
PatternRewriter &rewriter) const override {
ModuleOp module = op->getParentOfType<ModuleOp>();
Location loc = op->getLoc();
Value inputTensor = op.input();
RankedTensorType inputType =
inputTensor.getType().dyn_cast<RankedTensorType>();
bool inputTypeIsCSR = hasRowOrdering(inputType);
RankedTensorType flippedInputType =
op.getResult().getType().cast<RankedTensorType>();
// Cast types
Value output = callDupTensor(rewriter, module, loc, inputTensor);
Value c0 = rewriter.create<arith::ConstantIndexOp>(loc, 0);
Value c1 = rewriter.create<arith::ConstantIndexOp>(loc, 1);
if (inputTypeIsCSR) {
callAssignRev(rewriter, module, loc, output, c0, c1);
callAssignRev(rewriter, module, loc, output, c1, c0);
} else {
callAssignRev(rewriter, module, loc, output, c0, c0);
callAssignRev(rewriter, module, loc, output, c1, c1);
}
output = castToPtr8(rewriter, module, loc, output);
output = castToTensor(rewriter, module, loc, output, flippedInputType);
// TODO we get an error when we have hard-coded/known sizes at compile time.
rewriter.replaceOp(op, output);
cleanupIntermediateTensor(rewriter, module, loc, output);
};
};
class LowerSelectRewrite : public OpRewritePattern<graphblas::SelectOp> {
public:
using OpRewritePattern<graphblas::SelectOp>::OpRewritePattern;
LogicalResult matchAndRewrite(graphblas::SelectOp op,
PatternRewriter &rewriter) const override {
std::string selector = op.selector().str();
OperandRange thunks = op.thunks();
if (selector == "probability") {
Value thunk = thunks[0];
Value rngContext = thunks[1];
auto probBlock = std::bind(probabilityBlock, _1, _2, _3, _4, _5, _6, _7,
thunk, rngContext);
return buildAlgorithm<graphblas::SelectOp>(op, rewriter, probBlock);
} else {
Location loc = op->getLoc();
Value input = op.input();
RankedTensorType inputType = input.getType().cast<RankedTensorType>();
Type valueType = inputType.getElementType();
// Replace with SelectGenericOp
graphblas::SelectGenericOp newSelectOp =
rewriter.create<graphblas::SelectGenericOp>(loc, op->getResultTypes(),
input, 1);
// Populate based on operator kind
LogicalResult popResult = failure();
if (unary1.contains(selector) || unary3.contains(selector)) {
popResult = populateUnary(rewriter, loc, selector, valueType,
newSelectOp.getRegions().slice(0, 1),
graphblas::YieldKind::SELECT_OUT,
/* boolAsI8 */ false);
} else {
popResult = populateBinary(rewriter, loc, selector, valueType,
newSelectOp.getRegions().slice(0, 1),
graphblas::YieldKind::SELECT_OUT,
/* boolAsI8 */ false);
}
if (failed(popResult))
return failure();
// Remove thunk from populated block
if (binary2.contains(selector) || binary4.contains(selector)) {
Value thunk = thunks[0];
Block &block = newSelectOp.getRegion(0).front();
Value thunkArg = block.getArgument(1);
thunkArg.replaceAllUsesWith(thunk);
block.eraseArgument(1);
}
rewriter.setInsertionPointAfter(newSelectOp);
rewriter.replaceOp(op, newSelectOp.getResult());
}
return success();
};
template <class T>
static LogicalResult
buildAlgorithm(T op, PatternRewriter &rewriter,
std::function<LogicalResult(T, PatternRewriter &, Location,
Value &, Value, Value, Value)>
func) {
ModuleOp module = op->template getParentOfType<ModuleOp>();
Location loc = op->getLoc();
Value input = op.input();
RankedTensorType inputType = input.getType().cast<RankedTensorType>();
Type valueType = inputType.getElementType();
Type int64Type = rewriter.getIntegerType(64);
Type indexType = rewriter.getIndexType();
Type memref1DI64Type = MemRefType::get({-1}, int64Type);
Type memref1DValueType = MemRefType::get({-1}, valueType);
// Initial constants
Value c0 = rewriter.create<arith::ConstantIndexOp>(loc, 0);
Value c1 = rewriter.create<arith::ConstantIndexOp>(loc, 1);
Value c1_64 = rewriter.create<arith::ConstantIntOp>(loc, 1, int64Type);
// Get sparse tensor info
unsigned rank = inputType.getRank();
Value nrow;
if (rank == 2)
nrow = rewriter.create<graphblas::NumRowsOp>(loc, input);
else
// Vectors are stored as a 1xn matrix
// so the code works correctly if we assume a single row
nrow = c1;
Value indexPos = (rank == 2 ? c1 : c0);
Value Ap = rewriter.create<sparse_tensor::ToPointersOp>(
loc, memref1DI64Type, input, indexPos);
Value Aj = rewriter.create<sparse_tensor::ToIndicesOp>(loc, memref1DI64Type,
input, indexPos);
Value Ax = rewriter.create<sparse_tensor::ToValuesOp>(
loc, memref1DValueType, input);
// Create output
Value output = rewriter.create<graphblas::DupOp>(loc, input);
bool colWise = false;
if (rank == 2)
colWise = hasColumnOrdering(inputType);
Value Bp = rewriter.create<sparse_tensor::ToPointersOp>(
loc, memref1DI64Type, output, indexPos);
Value Bj = rewriter.create<sparse_tensor::ToIndicesOp>(loc, memref1DI64Type,
output, indexPos);
Value Bx = rewriter.create<sparse_tensor::ToValuesOp>(
loc, memref1DValueType, output);
// Loop
scf::ForOp outerLoop = rewriter.create<scf::ForOp>(loc, c0, nrow, c1);
Value row = outerLoop.getInductionVar();
{
rewriter.setInsertionPointToStart(outerLoop.getBody());
Value row_plus1 = rewriter.create<arith::AddIOp>(loc, row, c1);
Value bp_curr_count = rewriter.create<memref::LoadOp>(loc, Bp, row);
rewriter.create<memref::StoreOp>(loc, bp_curr_count, Bp, row_plus1);
Value j_start_64 = rewriter.create<memref::LoadOp>(loc, Ap, row);
Value j_end_64 = rewriter.create<memref::LoadOp>(loc, Ap, row_plus1);
Value j_start =
rewriter.create<arith::IndexCastOp>(loc, j_start_64, indexType);
Value j_end =
rewriter.create<arith::IndexCastOp>(loc, j_end_64, indexType);
scf::ForOp innerLoop =
rewriter.create<scf::ForOp>(loc, j_start, j_end, c1);
Value jj = innerLoop.getInductionVar();
{
rewriter.setInsertionPointToStart(innerLoop.getBody());
Value col_64 = rewriter.create<memref::LoadOp>(loc, Aj, jj);
Value col = rewriter.create<arith::IndexCastOp>(loc, col_64, indexType);
Value val = rewriter.create<memref::LoadOp>(loc, Ax, jj);
// Inject code from func
Value keep = nullptr;
LogicalResult funcResult = failure();
if (rank == 1)
funcResult = func(op, rewriter, loc, keep, val, col, col);
else if (colWise)
funcResult = func(op, rewriter, loc, keep, val, col, row);
else
funcResult = func(op, rewriter, loc, keep, val, row, col);
if (funcResult.failed()) {
return funcResult;
}
scf::IfOp ifKeep =
rewriter.create<scf::IfOp>(loc, keep, false /* no else region */);
{
rewriter.setInsertionPointToStart(ifKeep.thenBlock());
Value bj_pos_64 = rewriter.create<memref::LoadOp>(loc, Bp, row_plus1);
Value bj_pos =
rewriter.create<arith::IndexCastOp>(loc, bj_pos_64, indexType);
rewriter.create<memref::StoreOp>(loc, col_64, Bj, bj_pos);
rewriter.create<memref::StoreOp>(loc, val, Bx, bj_pos);
Value bj_pos_plus1 =
rewriter.create<arith::AddIOp>(loc, bj_pos_64, c1_64);
rewriter.create<memref::StoreOp>(loc, bj_pos_plus1, Bp, row_plus1);
rewriter.setInsertionPointAfter(ifKeep);
}
// rewriter.setInsertionPointAfter(innerLoop);
}
rewriter.setInsertionPointAfter(outerLoop);
}
// trim excess values
Value nnz = rewriter.create<graphblas::NumValsOp>(loc, output);
callResizeIndex(rewriter, module, loc, output, indexPos, nnz);
callResizeValues(rewriter, module, loc, output, nnz);
rewriter.replaceOp(op, output);
cleanupIntermediateTensor(rewriter, module, loc, output);
return success();
};
private:
static LogicalResult
probabilityBlock(graphblas::SelectOp op, PatternRewriter &rewriter,
Location loc, Value &keep, Value val, Value row, Value col,
// These are not part of the standard signature
// and will be passed using `bind`
Value thunk, Value rngContext) {
Type f64Type = rewriter.getF64Type();
SymbolRefAttr random_double =
SymbolRefAttr::get(rewriter.getContext(), "random_double");
// Get a random double between [0, 1)
CallOp randCall = rewriter.create<mlir::CallOp>(
loc, random_double, TypeRange{f64Type}, ArrayRef<Value>({rngContext}));
Value rand = randCall.getResult(0);
keep = rewriter.create<arith::CmpFOp>(loc, arith::CmpFPredicate::OLT, rand,
thunk);
return success();
};
};
class LowerSelectGenericRewrite
: public OpRewritePattern<graphblas::SelectGenericOp> {
public:
using OpRewritePattern<graphblas::SelectGenericOp>::OpRewritePattern;
LogicalResult matchAndRewrite(graphblas::SelectGenericOp op,
PatternRewriter &rewriter) const override {
LogicalResult callResult =
LowerSelectRewrite::buildAlgorithm<graphblas::SelectGenericOp>(
op, rewriter, genericBlock);
if (callResult.failed()) {
return callResult;
}
return success();
};
private:
static LogicalResult genericBlock(graphblas::SelectGenericOp op,
PatternRewriter &rewriter, Location loc,
Value &keep, Value val, Value row,
Value col) {
// Required blocks
RegionRange extensions = op.extensions();
ExtensionBlocks extBlocks;
std::set<graphblas::YieldKind> required = {
graphblas::YieldKind::SELECT_OUT};
LogicalResult extractResult =
extBlocks.extractBlocks(op, extensions, required, {});
if (extractResult.failed()) {
return extractResult;
}
int numArguments = extBlocks.selectOut->getArguments().size();
// scf::ForOp automatically gets an empty scf.yield at the end which
// we need to insert before
Operation *scfYield = rewriter.getBlock()->getTerminator();
// insert selectOut block
graphblas::YieldOp selectOutYield =
llvm::dyn_cast_or_null<graphblas::YieldOp>(
extBlocks.selectOut->getTerminator());
ValueRange subVals = ValueRange{val, row, col}.slice(0, numArguments);
rewriter.mergeBlockBefore(extBlocks.selectOut, scfYield, subVals);
keep = selectOutYield.values().front();
rewriter.eraseOp(selectOutYield);
return success();
};
};
class ReduceToVectorDWIMRewrite
: public OpRewritePattern<graphblas::ReduceToVectorOp> {
public:
using OpRewritePattern<graphblas::ReduceToVectorOp>::OpRewritePattern;
static bool needsDWIM(graphblas::ReduceToVectorOp op) {
int axis = op.axis();
bool isCSR = hasRowOrdering(op.input().getType());
return ((axis == 0 && isCSR) || (axis == 1 && !isCSR));
};
LogicalResult matchAndRewrite(graphblas::ReduceToVectorOp op,
PatternRewriter &rewriter) const override {
if (!needsDWIM(op))
return failure();
MLIRContext *context = op.getContext();
Location loc = op->getLoc();
Value input = op.input();
RankedTensorType flippedInputType =
getFlippedLayoutType(context, input.getType());
rewriter.setInsertionPoint(op);
Value flippedInput = rewriter.create<graphblas::ConvertLayoutOp>(
loc, flippedInputType, input);
op.inputMutable().assign(flippedInput);
return success();
};
};
class LowerReduceToVectorRewrite
: public OpRewritePattern<graphblas::ReduceToVectorOp> {
public:
using OpRewritePattern<graphblas::ReduceToVectorOp>::OpRewritePattern;
LogicalResult matchAndRewrite(graphblas::ReduceToVectorOp op,
PatternRewriter &rewriter) const override {
if (ReduceToVectorDWIMRewrite::needsDWIM(op))
return failure();
Value input = op.input();
StringRef aggregator = op.aggregator();
RankedTensorType inputType = input.getType().dyn_cast<RankedTensorType>();
Type elementType = inputType.getElementType();
Type i64Type = rewriter.getI64Type();
if (aggregator == "count") {
return buildAlgorithm<graphblas::ReduceToVectorOp>(op, rewriter, i64Type,
countBlock);
} else if (aggregator == "argmin" or aggregator == "argmax") {
return buildAlgorithm<graphblas::ReduceToVectorOp>(op, rewriter, i64Type,
argminmaxBlock);
} else if (aggregator == "first" or aggregator == "last") {
return buildAlgorithm<graphblas::ReduceToVectorOp>(
op, rewriter, elementType, firstLastBlock);
} else {
Location loc = op->getLoc();
NamedAttrList attributes = {};
attributes.append(StringRef("axis"),
rewriter.getIntegerAttr(i64Type, op.axis()));
attributes.append(StringRef("mask_complement"),
rewriter.getBoolAttr(op.mask_complement()));
graphblas::ReduceToVectorGenericOp newReduceOp =
rewriter.create<graphblas::ReduceToVectorGenericOp>(
loc, op->getResultTypes(), input, attributes.getAttrs(), 2);
if (failed(populateMonoid(rewriter, loc, op.aggregator(), elementType,
newReduceOp.getRegions().slice(0, 2),
graphblas::YieldKind::AGG_IDENTITY,
graphblas::YieldKind::AGG)))
return failure();
rewriter.setInsertionPointAfter(newReduceOp);
rewriter.replaceOp(op, newReduceOp.getResult());
}
return success();
};
template <class T>
static LogicalResult buildAlgorithm(
T op, PatternRewriter &rewriter, Type outputType,
std::function<LogicalResult(T, PatternRewriter &, Location, Value &,
Value, Value, Value, Value)>
func) {
MLIRContext *context = op.getContext();
ModuleOp module = op->template getParentOfType<ModuleOp>();
Location loc = op->getLoc();
// Inputs
Value input = op.input();
Value mask = op.mask();
int axis = op.axis();
bool maskComplement = op.mask_complement();
// Types
Type indexType = rewriter.getIndexType();
Type i64Type = rewriter.getIntegerType(64);
RankedTensorType inputType = input.getType().dyn_cast<RankedTensorType>();
Type memrefPointerType = getMemrefPointerType(inputType);
Type memrefIndexType = getMemrefIndexType(inputType);
Type memrefIValueType = getMemrefValueType(inputType);
Type memrefOValueType = MemRefType::get({-1}, outputType);
// Constants
Value c0 = rewriter.create<arith::ConstantIndexOp>(loc, 0);
Value c1 = rewriter.create<arith::ConstantIndexOp>(loc, 1);
// Sparse pointers
Value Ip = rewriter.create<sparse_tensor::ToPointersOp>(
loc, memrefPointerType, input, c1);
Value Ii = rewriter.create<sparse_tensor::ToIndicesOp>(loc, memrefIndexType,
input, c1);
Value Ix = rewriter.create<sparse_tensor::ToValuesOp>(loc, memrefIValueType,
input);
// Compute output sizes
Value size;
if (axis == 1)
size = rewriter.create<graphblas::NumRowsOp>(loc, input);
else
size = rewriter.create<graphblas::NumColsOp>(loc, input);
// Compute sparse array of valid output indices
ValueRange sdpRet = sparsifyDensePointers(rewriter, loc, size, Ip);
Value sparsePointers = sdpRet[0];
Value nnz = sdpRet[1];
if (mask) {
Value Mi = rewriter.create<sparse_tensor::ToIndicesOp>(
loc, memrefIndexType, mask, c0);
Value mNnz = rewriter.create<graphblas::NumValsOp>(loc, mask);
if (maskComplement) {
ValueRange bmcRet =
buildMaskComplement(rewriter, loc, size, Mi, c0, mNnz);
Mi = bmcRet[0];
mNnz = bmcRet[1];
}
Value prevSparsePointers = sparsePointers;
ValueRange bioRet =
buildIndexOverlap(rewriter, loc, nnz, prevSparsePointers, mNnz, Mi);
sparsePointers = bioRet[0];
nnz = bioRet[1];
if (maskComplement)
rewriter.create<memref::DeallocOp>(loc, Mi);
rewriter.create<memref::DeallocOp>(loc, prevSparsePointers);
}
Value nnz64 = rewriter.create<arith::IndexCastOp>(loc, nnz, i64Type);
// Build output vector
Value output = callNewTensor(rewriter, module, loc, ValueRange{size},
getCompressedVectorType(context, outputType));
callResizeIndex(rewriter, module, loc, output, c0, nnz);
callResizeValues(rewriter, module, loc, output, nnz);
Value Op = rewriter.create<sparse_tensor::ToPointersOp>(
loc, memrefPointerType, output, c0);
Value Oi = rewriter.create<sparse_tensor::ToIndicesOp>(loc, memrefIndexType,
output, c0);
Value Ox = rewriter.create<sparse_tensor::ToValuesOp>(loc, memrefOValueType,
output);
// Populate output
rewriter.create<memref::StoreOp>(loc, nnz64, Op, c1);
// Loop over sparse array of valid output indices
scf::ForOp reduceLoop = rewriter.create<scf::ForOp>(loc, c0, nnz, c1);
{
rewriter.setInsertionPointToStart(reduceLoop.getBody());
Value outputPos = reduceLoop.getInductionVar();
Value rowIndex64 =
rewriter.create<memref::LoadOp>(loc, sparsePointers, outputPos);
Value rowIndex =
rewriter.create<arith::IndexCastOp>(loc, rowIndex64, indexType);
Value nextRowIndex =
rewriter.create<arith::AddIOp>(loc, rowIndex, c1).getResult();
Value ptr64 = rewriter.create<memref::LoadOp>(loc, Ip, rowIndex);
Value nextPtr64 = rewriter.create<memref::LoadOp>(loc, Ip, nextRowIndex);
// At this point, we know the row is not empty, so nextPtr64 > ptr64
Value ptr = rewriter.create<arith::IndexCastOp>(loc, ptr64, indexType);
Value nextPtr =
rewriter.create<arith::IndexCastOp>(loc, nextPtr64, indexType);
// Inject code from func
Value aggVal = nullptr;
LogicalResult funcResult =
func(op, rewriter, loc, aggVal, ptr, nextPtr, Ii, Ix);
if (funcResult.failed()) {
return funcResult;
}
rewriter.create<memref::StoreOp>(loc, aggVal, Ox, outputPos);
rewriter.create<memref::StoreOp>(loc, rowIndex64, Oi, outputPos);
}
rewriter.setInsertionPointAfter(reduceLoop);
rewriter.create<memref::DeallocOp>(loc, sparsePointers);
rewriter.replaceOp(op, output);
cleanupIntermediateTensor(rewriter, module, loc, output);
return success();
};
private:
static LogicalResult countBlock(graphblas::ReduceToVectorOp op,
PatternRewriter &rewriter, Location loc,
Value &aggVal, Value ptr, Value nextPtr,
Value Ii, Value Ix) {
Type i64Type = rewriter.getI64Type();
Value diff = rewriter.create<arith::SubIOp>(loc, nextPtr, ptr);
aggVal = rewriter.create<arith::IndexCastOp>(loc, diff, i64Type);
return success();
}
static LogicalResult argminmaxBlock(graphblas::ReduceToVectorOp op,
PatternRewriter &rewriter, Location loc,
Value &aggVal, Value ptr, Value nextPtr,
Value Ii, Value Ix) {
StringRef aggregator = op.aggregator();
Value c1 = rewriter.create<arith::ConstantIndexOp>(loc, 1);
RankedTensorType inputType =
op.input().getType().dyn_cast<RankedTensorType>();
Type elementType = inputType.getElementType();
Type i64Type = rewriter.getI64Type();
Value initVal = rewriter.create<memref::LoadOp>(loc, Ix, ptr);
Value initIdx = rewriter.create<memref::LoadOp>(loc, Ii, ptr);
Value ptrPlusOne = rewriter.create<arith::AddIOp>(loc, ptr, c1);
scf::ForOp loop = rewriter.create<scf::ForOp>(loc, ptrPlusOne, nextPtr, c1,
ValueRange{initVal, initIdx});
{
rewriter.setInsertionPointToStart(loop.getBody());
Value curVal = loop.getLoopBody().getArgument(1);
Value curIdx = loop.getLoopBody().getArgument(2);
Value curPtr = loop.getInductionVar();
Value rowValue = rewriter.create<memref::LoadOp>(loc, Ix, curPtr);
bool useMinimum = aggregator == "argmin";
Value mustUpdate = llvm::TypeSwitch<Type, Value>(elementType)
.Case<IntegerType>([&](IntegerType type) {
return rewriter.create<arith::CmpIOp>(
loc,
useMinimum ? arith::CmpIPredicate::slt
: arith::CmpIPredicate::sgt,
rowValue, curVal);
})
.Case<FloatType>([&](FloatType type) {
return rewriter.create<arith::CmpFOp>(
loc,
useMinimum ? arith::CmpFPredicate::OLT
: arith::CmpFPredicate::OGT,
rowValue, curVal);
});
scf::IfOp ifMustUpdateBlock = rewriter.create<scf::IfOp>(
loc, TypeRange{elementType, i64Type}, mustUpdate, true);
{
rewriter.setInsertionPointToStart(ifMustUpdateBlock.thenBlock());
Value newIdx = rewriter.create<memref::LoadOp>(loc, Ii, curPtr);
rewriter.create<scf::YieldOp>(loc, ValueRange{rowValue, newIdx});
}
{
rewriter.setInsertionPointToStart(ifMustUpdateBlock.elseBlock());
rewriter.create<scf::YieldOp>(loc, ValueRange{curVal, curIdx});
rewriter.setInsertionPointAfter(ifMustUpdateBlock);
}
rewriter.create<scf::YieldOp>(loc, ifMustUpdateBlock.getResults());
rewriter.setInsertionPointAfter(loop);
}
aggVal = loop.getResult(1);
return success();
}
static LogicalResult firstLastBlock(graphblas::ReduceToVectorOp op,
PatternRewriter &rewriter, Location loc,
Value &aggVal, Value ptr, Value nextPtr,
Value Ii, Value Ix) {
StringRef aggregator = op.aggregator();
Value c1 = rewriter.create<arith::ConstantIndexOp>(loc, 1);
if (aggregator == "first") {
aggVal = rewriter.create<memref::LoadOp>(loc, Ix, ptr);
} else {
Value lastPtr = rewriter.create<arith::SubIOp>(loc, nextPtr, c1);
aggVal = rewriter.create<memref::LoadOp>(loc, Ix, lastPtr);
}
return success();
}
};
class LowerReduceToVectorGenericRewrite
: public OpRewritePattern<graphblas::ReduceToVectorGenericOp> {
public:
using OpRewritePattern<graphblas::ReduceToVectorGenericOp>::OpRewritePattern;
LogicalResult matchAndRewrite(graphblas::ReduceToVectorGenericOp op,
PatternRewriter &rewriter) const override {
Type elementType =
op.input().getType().cast<RankedTensorType>().getElementType();
LogicalResult callResult = LowerReduceToVectorRewrite::buildAlgorithm<
graphblas::ReduceToVectorGenericOp>(op, rewriter, elementType,
genericBlock);
if (callResult.failed()) {
return callResult;
}
return success();
};
private:
static LogicalResult genericBlock(graphblas::ReduceToVectorGenericOp op,
PatternRewriter &rewriter, Location loc,
Value &aggVal, Value ptr, Value nextPtr,
Value Ii, Value Ix) {
// Required blocks
RegionRange extensions = op.extensions();
ExtensionBlocks extBlocks;
std::set<graphblas::YieldKind> required = {
graphblas::YieldKind::AGG_IDENTITY, graphblas::YieldKind::AGG};
LogicalResult extractResult =
extBlocks.extractBlocks(op, extensions, required, {});
if (extractResult.failed()) {
return extractResult;
}
// Build inner block
Value c1 = rewriter.create<arith::ConstantIndexOp>(loc, 1);
// insert agg identity
rewriter.mergeBlocks(extBlocks.aggIdentity, rewriter.getBlock(), {});
graphblas::YieldOp aggIdentityYield =
llvm::dyn_cast_or_null<graphblas::YieldOp>(
rewriter.getBlock()->getTerminator());
Value c0Accumulator = aggIdentityYield.values().front();
rewriter.eraseOp(aggIdentityYield);
// reduce in a loop
scf::ParallelOp aggLoop =
rewriter.create<scf::ParallelOp>(loc, ptr, nextPtr, c1, c0Accumulator);
ValueRange aggIdx = aggLoop.getInductionVars();
rewriter.setInsertionPointToStart(aggLoop.getBody());
Value x = rewriter.create<memref::LoadOp>(loc, Ix, aggIdx);
scf::ReduceOp reducer = rewriter.create<scf::ReduceOp>(loc, x);
BlockArgument lhs = reducer.getRegion().getArgument(0);
BlockArgument rhs = reducer.getRegion().getArgument(1);
rewriter.setInsertionPointToStart(&reducer.getRegion().front());
rewriter.mergeBlocks(extBlocks.agg, rewriter.getBlock(), {lhs, rhs});
graphblas::YieldOp aggYield = llvm::dyn_cast_or_null<graphblas::YieldOp>(
rewriter.getBlock()->getTerminator());
Value result = aggYield.values().front();
rewriter.eraseOp(aggYield);
rewriter.create<scf::ReduceReturnOp>(loc, result);
rewriter.setInsertionPointAfter(aggLoop);
aggVal = aggLoop.getResult(0);
return success();
};
};
class LowerReduceToScalarRewrite
: public OpRewritePattern<graphblas::ReduceToScalarOp> {
public:
using OpRewritePattern<graphblas::ReduceToScalarOp>::OpRewritePattern;
LogicalResult matchAndRewrite(graphblas::ReduceToScalarOp op,
PatternRewriter &rewriter) const override {
StringRef aggregator = op.aggregator();
if (aggregator == "count") {
return rewriteCount(op, rewriter);
} else if (aggregator == "argmin" or aggregator == "argmax") {
return rewriteArgMinMax(op, rewriter);
} else {
return rewriteStandard(op, rewriter);
}
};
private:
LogicalResult rewriteCount(graphblas::ReduceToScalarOp op,
PatternRewriter &rewriter) const {
Value input = op.input();
Location loc = op->getLoc();
Type int64Type = rewriter.getIntegerType(64);
Value countOp = rewriter.create<graphblas::NumValsOp>(loc, input);
Value countOp_64 =
rewriter.create<arith::IndexCastOp>(loc, countOp, int64Type);
rewriter.replaceOp(op, countOp_64);
return success();
}
LogicalResult rewriteArgMinMax(graphblas::ReduceToScalarOp op,
PatternRewriter &rewriter) const {
// TODO we get seg faults if given a size 0 vector or a sparse vector with
// no non-zero values. Probably should return a -1 for these cases.
Location loc = op->getLoc();
StringRef aggregator = op.aggregator();
Value input = op.input();
RankedTensorType inputType = input.getType().cast<RankedTensorType>();
Value c0 = rewriter.create<arith::ConstantIndexOp>(loc, 0);
Value c1 = rewriter.create<arith::ConstantIndexOp>(loc, 1);
Type indexType = rewriter.getIndexType();
Type int64Type = rewriter.getIntegerType(64);
Type memref1DI64Type = MemRefType::get({-1}, int64Type);
Value pointers = rewriter.create<sparse_tensor::ToPointersOp>(
loc, memref1DI64Type, input, c0);
Value endPosition64 = rewriter.create<memref::LoadOp>(loc, pointers, c1);
Value endPosition =
rewriter.create<arith::IndexCastOp>(loc, endPosition64, indexType);
Type inputElementType = inputType.getElementType();
Type memref1DValueType = MemRefType::get({-1}, inputElementType);
Value values = rewriter.create<sparse_tensor::ToValuesOp>(
loc, memref1DValueType, input);
Value initialExtremum = rewriter.create<memref::LoadOp>(loc, values, c0);
scf::ForOp loop = rewriter.create<scf::ForOp>(
loc, c1, endPosition, c1, ValueRange{initialExtremum, c0});
Value currentValuePosition = loop.getInductionVar();
Value currentExtremum = loop.getLoopBody().getArgument(1);
Value currentExtremumPosition = loop.getLoopBody().getArgument(2);
rewriter.setInsertionPointToStart(loop.getBody());
Value currentValue =
rewriter.create<memref::LoadOp>(loc, values, currentValuePosition);
bool useMinimum = aggregator == "argmin";
Value replace = llvm::TypeSwitch<Type, Value>(inputElementType)
.Case<IntegerType>([&](IntegerType type) {
return rewriter.create<arith::CmpIOp>(
loc,
useMinimum ? arith::CmpIPredicate::slt
: arith::CmpIPredicate::sgt,
currentValue, currentExtremum);
})
.Case<FloatType>([&](FloatType type) {
return rewriter.create<arith::CmpFOp>(
loc,
useMinimum ? arith::CmpFPredicate::OLT
: arith::CmpFPredicate::OGT,
currentValue, currentExtremum);
});
scf::IfOp ifBlock = rewriter.create<scf::IfOp>(
loc, TypeRange{inputElementType, indexType}, replace, true);
rewriter.setInsertionPointToStart(ifBlock.thenBlock());
rewriter.create<scf::YieldOp>(
loc, ValueRange{currentValue, currentValuePosition});
rewriter.setInsertionPointToStart(ifBlock.elseBlock());
rewriter.create<scf::YieldOp>(
loc, ValueRange{currentExtremum, currentExtremumPosition});
rewriter.setInsertionPointAfter(ifBlock);
rewriter.create<scf::YieldOp>(loc, ifBlock.getResults());
rewriter.setInsertionPointAfter(loop);
Value finalExtremumPosition = loop.getResult(1);
Value indices = rewriter.create<sparse_tensor::ToIndicesOp>(
loc, memref1DI64Type, input, c0);
Value argExtremum =
rewriter.create<memref::LoadOp>(loc, indices, finalExtremumPosition);
rewriter.replaceOp(op, argExtremum);
return success();
}
LogicalResult rewriteStandard(graphblas::ReduceToScalarOp op,
PatternRewriter &rewriter) const {
Value input = op.input();
Location loc = op->getLoc();
Type valueType = input.getType().cast<RankedTensorType>().getElementType();
graphblas::ReduceToScalarGenericOp newReduceOp =
rewriter.create<graphblas::ReduceToScalarGenericOp>(
loc, op->getResultTypes(), input, 2);
if (failed(populateMonoid(rewriter, loc, op.aggregator(), valueType,
newReduceOp.getRegions().slice(0, 2),
graphblas::YieldKind::AGG_IDENTITY,
graphblas::YieldKind::AGG)))
return failure();
rewriter.setInsertionPointAfter(newReduceOp);
rewriter.replaceOp(op, newReduceOp.getResult());
return success();
}
};
class LowerReduceToScalarGenericRewrite
: public OpRewritePattern<graphblas::ReduceToScalarGenericOp> {
public:
using OpRewritePattern<graphblas::ReduceToScalarGenericOp>::OpRewritePattern;
LogicalResult matchAndRewrite(graphblas::ReduceToScalarGenericOp op,
PatternRewriter &rewriter) const override {
Value input = op.input();
Location loc = op->getLoc();
RankedTensorType operandType =
op.input().getType().dyn_cast<RankedTensorType>();
Type valueType = operandType.getElementType();
// Required blocks
RegionRange extensions = op.extensions();
ExtensionBlocks extBlocks;
std::set<graphblas::YieldKind> required = {
graphblas::YieldKind::AGG_IDENTITY, graphblas::YieldKind::AGG};
LogicalResult extractResult =
extBlocks.extractBlocks(op, extensions, required, {});
if (extractResult.failed()) {
return extractResult;
}
// insert agg identity
rewriter.mergeBlocks(extBlocks.aggIdentity, rewriter.getBlock(), {});
graphblas::YieldOp aggIdentityYield =
llvm::dyn_cast_or_null<graphblas::YieldOp>(
rewriter.getBlock()->getTerminator());
Value c0Accumulator = aggIdentityYield.values().front();
rewriter.eraseOp(aggIdentityYield);
// initial constants
Value c0 = rewriter.create<arith::ConstantIndexOp>(loc, 0);
Value c1 = rewriter.create<arith::ConstantIndexOp>(loc, 1);
// Get sparse tensor info
MemRefType memref1DValueType = MemRefType::get({-1}, valueType);
sparse_tensor::ToValuesOp inputValues =
rewriter.create<sparse_tensor::ToValuesOp>(loc, memref1DValueType,
input);
Value nnz = rewriter.create<graphblas::NumValsOp>(loc, input);
// begin loop
scf::ParallelOp valueLoop =
rewriter.create<scf::ParallelOp>(loc, c0, nnz, c1, c0Accumulator);
ValueRange valueLoopIdx = valueLoop.getInductionVars();
rewriter.setInsertionPointToStart(valueLoop.getBody());
memref::LoadOp y =
rewriter.create<memref::LoadOp>(loc, inputValues, valueLoopIdx);
scf::ReduceOp reducer = rewriter.create<scf::ReduceOp>(loc, y);
BlockArgument lhs = reducer.getRegion().getArgument(0);
BlockArgument rhs = reducer.getRegion().getArgument(1);
rewriter.setInsertionPointToStart(&reducer.getRegion().front());
rewriter.mergeBlocks(extBlocks.agg, rewriter.getBlock(), {lhs, rhs});
graphblas::YieldOp aggYield = llvm::dyn_cast_or_null<graphblas::YieldOp>(
rewriter.getBlock()->getTerminator());
Value result = aggYield.values().front();
rewriter.eraseOp(aggYield);
rewriter.create<scf::ReduceReturnOp>(loc, result);
rewriter.setInsertionPointAfter(reducer);
rewriter.replaceOp(op, valueLoop.getResult(0));
return success();
};
};
class LowerApplyRewrite : public OpRewritePattern<graphblas::ApplyOp> {
public:
using OpRewritePattern<graphblas::ApplyOp>::OpRewritePattern;
LogicalResult matchAndRewrite(graphblas::ApplyOp op,
PatternRewriter &rewriter) const override {
Value input, thunk;
LogicalResult extractArgResult = extractApplyOpArgs(op, input, thunk);
assert(!extractArgResult.failed() &&
"Assumption that extractApplyOpArgs succeeded (due to verify "
"method) has been violated.");
StringRef apply_operator = op.apply_operator();
if (apply_operator == "identity") {
// This doesn't produce a copy like we do for all the other operators
rewriter.replaceOp(op, input);
return success();
}
ModuleOp module = op->getParentOfType<ModuleOp>(); /* ignore unused variable
for debugging */
(void)module;
Location loc = op->getLoc();
Type valueType =
input.getType().dyn_cast<RankedTensorType>().getElementType();
// New op
graphblas::ApplyGenericOp newApplyOp =
rewriter.create<graphblas::ApplyGenericOp>(loc, op->getResultTypes(),
input, 1);
// Populate based on operator kind
LogicalResult popResult = failure();
if (unary1.contains(apply_operator) || unary3.contains(apply_operator))
popResult = populateUnary(rewriter, loc, apply_operator, valueType,
newApplyOp.getRegions().slice(0, 1),
graphblas::YieldKind::TRANSFORM_OUT);
else
popResult = populateBinary(rewriter, loc, apply_operator, valueType,
newApplyOp.getRegions().slice(0, 1),
graphblas::YieldKind::TRANSFORM_OUT);
if (failed(popResult))
return failure();
// Remove thunk from populated block
if (binary2.contains(apply_operator) || binary4.contains(apply_operator)) {
Block &block = newApplyOp.getRegion(0).front();
int thunkPos = thunk == op.left() ? 0 : 1;
Value thunkArg = block.getArgument(thunkPos);
thunkArg.replaceAllUsesWith(thunk);
block.eraseArgument(thunkPos);
}
rewriter.replaceOp(op, newApplyOp.getResult());
return success();
};
};
class LowerApplyGenericRewrite
: public OpRewritePattern<graphblas::ApplyGenericOp> {
public:
using OpRewritePattern<graphblas::ApplyGenericOp>::OpRewritePattern;
LogicalResult matchAndRewrite(graphblas::ApplyGenericOp op,
PatternRewriter &rewriter) const override {
ModuleOp module = op->getParentOfType<ModuleOp>();
Location loc = op->getLoc();
Value inputTensor = op.input();
RankedTensorType inputTensorType =
inputTensor.getType().cast<RankedTensorType>();
RankedTensorType outputTensorType =
op.getResult().getType().cast<RankedTensorType>();
unsigned rank = inputTensorType.getRank();
Type indexType = rewriter.getIndexType();
Type memrefPointerType = getMemrefPointerType(inputTensorType);
Type memrefIndexType = getMemrefIndexType(inputTensorType);
Type memrefIValueType = getMemrefValueType(inputTensorType);
Type memrefOValueType = getMemrefValueType(outputTensorType);
// Required blocks
RegionRange extensions = op.extensions();
ExtensionBlocks extBlocks;
std::set<graphblas::YieldKind> required = {
graphblas::YieldKind::TRANSFORM_OUT};
LogicalResult extractResult =
extBlocks.extractBlocks(op, extensions, required, {});
if (extractResult.failed()) {
return extractResult;
}
// Initial constants
Value c0 = rewriter.create<arith::ConstantIndexOp>(loc, 0);
Value c1 = rewriter.create<arith::ConstantIndexOp>(loc, 1);
// Build output with same shape as input, but possibly different output type
Value output = rewriter.create<graphblas::DupOp>(loc, inputTensor);
if (inputTensorType != outputTensorType)
output =
rewriter.create<graphblas::CastOp>(loc, outputTensorType, output);
// Get sparse tensor info
Value inputValues = rewriter.create<sparse_tensor::ToValuesOp>(
loc, memrefIValueType, inputTensor);
Value outputValues = rewriter.create<sparse_tensor::ToValuesOp>(
loc, memrefOValueType, output);
Value nnz = rewriter.create<graphblas::NumValsOp>(loc, inputTensor);
int numArguments = extBlocks.transformOut->getArguments().size();
if (numArguments == 3) {
// Loop over pointers, indices, values
// This works for
// - vector -> passes in (val, index, index)
// - CSR or CSC -> passes in (val, row, col)
Value inputPointers = rewriter.create<sparse_tensor::ToPointersOp>(
loc, memrefPointerType, inputTensor);
Value inputIndices = rewriter.create<sparse_tensor::ToIndicesOp>(
loc, memrefIndexType, inputTensor);
bool byCols = false;
Value npointers;
if (rank == 1) {
npointers = c1;
} else if (hasRowOrdering(inputTensorType)) {
npointers = rewriter.create<graphblas::NumRowsOp>(loc, inputTensor);
} else {
npointers = rewriter.create<graphblas::NumColsOp>(loc, inputTensor);
byCols = true;
}
scf::ParallelOp pointerLoop =
rewriter.create<scf::ParallelOp>(loc, c0, npointers, c1);
Value pointerIdx = pointerLoop.getInductionVars().front();
rewriter.setInsertionPointToStart(pointerLoop.getBody());
Value pointerIdx_plus1 =
rewriter.create<arith::AddIOp>(loc, pointerIdx, c1);
Value indexStart_64 =
rewriter.create<memref::LoadOp>(loc, inputPointers, pointerIdx);
Value indexEnd_64 =
rewriter.create<memref::LoadOp>(loc, inputPointers, pointerIdx_plus1);
Value indexStart =
rewriter.create<arith::IndexCastOp>(loc, indexStart_64, indexType);
Value indexEnd =
rewriter.create<arith::IndexCastOp>(loc, indexEnd_64, indexType);
scf::ForOp innerLoop =
rewriter.create<scf::ForOp>(loc, indexStart, indexEnd, c1);
Value jj = innerLoop.getInductionVar();
{
rewriter.setInsertionPointToStart(innerLoop.getBody());
Value col_64 = rewriter.create<memref::LoadOp>(loc, inputIndices, jj);
Value col = rewriter.create<arith::IndexCastOp>(loc, col_64, indexType);
Value val = rewriter.create<memref::LoadOp>(loc, inputValues, jj);
// insert transformOut block
graphblas::YieldOp transformOutYield =
llvm::dyn_cast_or_null<graphblas::YieldOp>(
extBlocks.transformOut->getTerminator());
ValueRange subVals;
if (rank == 1)
subVals = ValueRange{val, col, col};
else if (byCols)
subVals = ValueRange{val, col, pointerIdx};
else
subVals = ValueRange{val, pointerIdx, col};
rewriter.mergeBlocks(extBlocks.transformOut, rewriter.getBlock(),
subVals);
Value result = transformOutYield.values().front();
rewriter.eraseOp(transformOutYield);
rewriter.create<memref::StoreOp>(loc, result, outputValues, jj);
// rewriter.setInsertionPointAfter(innerLoop);
}
// end row loop
rewriter.setInsertionPointAfter(pointerLoop);
} else if (numArguments == 1) {
// Fast path: only loop over values because we don't need indices
scf::ParallelOp valueLoop =
rewriter.create<scf::ParallelOp>(loc, c0, nnz, c1);
ValueRange valueLoopIdx = valueLoop.getInductionVars();
rewriter.setInsertionPointToStart(valueLoop.getBody());
Value val =
rewriter.create<memref::LoadOp>(loc, inputValues, valueLoopIdx);
// scf::ParallelOp automatically gets an empty scf.yield at the end which
// we need to insert before
Operation *scfYield = valueLoop.getBody()->getTerminator();
// insert transformOut block
graphblas::YieldOp transformOutYield =
llvm::dyn_cast_or_null<graphblas::YieldOp>(
extBlocks.transformOut->getTerminator());
rewriter.mergeBlockBefore(extBlocks.transformOut, scfYield, {val});
Value result = transformOutYield.values().front();
rewriter.eraseOp(transformOutYield);
rewriter.create<memref::StoreOp>(loc, result, outputValues, valueLoopIdx);
// end value loop
rewriter.setInsertionPointAfter(valueLoop);
} else
assert(0);
// Add return op
rewriter.replaceOp(op, output);
cleanupIntermediateTensor(rewriter, module, loc, output);
return success();
};
};
class LowerMatrixMultiplyRewrite
: public OpRewritePattern<graphblas::MatrixMultiplyOp> {
public:
using OpRewritePattern<graphblas::MatrixMultiplyOp>::OpRewritePattern;
LogicalResult matchAndRewrite(graphblas::MatrixMultiplyOp op,
PatternRewriter &rewriter) const override {
ModuleOp module = op->getParentOfType<ModuleOp>(); /* ignore unused variable
for debugging */
(void)module;
Location loc = op->getLoc();
// Inputs
ValueRange operands = op.getOperands();
StringRef semiring = op.semiring();
bool maskComplement = op.mask_complement();
// Types
// Can't use result here because it might be a scalar (vector-vector)
Type valueType =
op.a().getType().dyn_cast<RankedTensorType>().getElementType();
// New op
NamedAttrList attributes = {};
attributes.append(StringRef("mask_complement"),
rewriter.getBoolAttr(maskComplement));
graphblas::MatrixMultiplyGenericOp newMultOp =
rewriter.create<graphblas::MatrixMultiplyGenericOp>(
loc, op->getResultTypes(), operands, attributes.getAttrs(), 3);
if (failed(populateSemiring(rewriter, loc, semiring, valueType,
newMultOp.getRegions().slice(0, 3))))
return failure();
rewriter.setInsertionPointAfter(newMultOp);
rewriter.replaceOp(op, newMultOp.getResult());
return success();
};
};
class MatrixMultiplyGenericDWIMFirstArgRewrite
: public OpRewritePattern<graphblas::MatrixMultiplyGenericOp> {
public:
using OpRewritePattern<graphblas::MatrixMultiplyGenericOp>::OpRewritePattern;
template <class T>
static bool needsDWIM(T op) {
return hasColumnOrdering(op.a().getType());
};
LogicalResult matchAndRewrite(graphblas::MatrixMultiplyGenericOp op,
PatternRewriter &rewriter) const override {
if (!needsDWIM(op))
return failure();
MLIRContext *context = op.getContext();
Location loc = op->getLoc();
Value A = op.a();
RankedTensorType aType = A.getType().cast<RankedTensorType>();
RankedTensorType flippedMatrixType = getFlippedLayoutType(context, aType);
rewriter.setInsertionPoint(op);
Value flippedA =
rewriter.create<graphblas::ConvertLayoutOp>(loc, flippedMatrixType, A);
op.aMutable().assign(flippedA);
return success();
};
};
class MatrixMultiplyGenericDWIMSecondArgRewrite
: public OpRewritePattern<graphblas::MatrixMultiplyGenericOp> {
public:
using OpRewritePattern<graphblas::MatrixMultiplyGenericOp>::OpRewritePattern;
template <class T>
static bool needsDWIM(T op) {
return hasRowOrdering(op.b().getType());
};
LogicalResult matchAndRewrite(graphblas::MatrixMultiplyGenericOp op,
PatternRewriter &rewriter) const override {
if (!needsDWIM(op))
return failure();
MLIRContext *context = op.getContext();
Location loc = op->getLoc();
Value B = op.b();
RankedTensorType bType = B.getType().cast<RankedTensorType>();
RankedTensorType flippedMatrixType = getFlippedLayoutType(context, bType);
rewriter.setInsertionPoint(op);
Value flippedB =
rewriter.create<graphblas::ConvertLayoutOp>(loc, flippedMatrixType, B);
op.bMutable().assign(flippedB);
return success();
};
};
class MatrixMultiplyGenericDWIMMaskRewrite
: public OpRewritePattern<graphblas::MatrixMultiplyGenericOp> {
public:
using OpRewritePattern<graphblas::MatrixMultiplyGenericOp>::OpRewritePattern;
template <class T>
static bool needsDWIM(T op) {
Value mask = op.mask();
if (!mask)
return false;
return hasColumnOrdering(mask.getType());
};
LogicalResult matchAndRewrite(graphblas::MatrixMultiplyGenericOp op,
PatternRewriter &rewriter) const override {
if (!needsDWIM(op))
return failure();
MLIRContext *context = op.getContext();
Location loc = op->getLoc();
Value mask = op.mask();
RankedTensorType maskType = mask.getType().cast<RankedTensorType>();
RankedTensorType flippedMatrixType =
getFlippedLayoutType(context, maskType);
rewriter.setInsertionPoint(op);
Value flippedMask = rewriter.create<graphblas::ConvertLayoutOp>(
loc, flippedMatrixType, mask);
op.maskMutable().assign(flippedMask);
return success();
};
};
class LowerMatrixMultiplyGenericRewrite
: public OpRewritePattern<graphblas::MatrixMultiplyGenericOp> {
public:
using OpRewritePattern<graphblas::MatrixMultiplyGenericOp>::OpRewritePattern;
LogicalResult matchAndRewrite(graphblas::MatrixMultiplyGenericOp op,
PatternRewriter &rewriter) const override {
if (MatrixMultiplyGenericDWIMFirstArgRewrite::needsDWIM(op) ||
MatrixMultiplyGenericDWIMSecondArgRewrite::needsDWIM(op) ||
MatrixMultiplyGenericDWIMMaskRewrite::needsDWIM(op))
return failure();
// Required blocks
RegionRange extensions = op.extensions();
ExtensionBlocks extBlocks;
std::set<graphblas::YieldKind> required = {
graphblas::YieldKind::ADD_IDENTITY, graphblas::YieldKind::ADD,
graphblas::YieldKind::MULT};
std::set<graphblas::YieldKind> optional = {
graphblas::YieldKind::TRANSFORM_OUT};
LogicalResult extractResult =
extBlocks.extractBlocks(op, extensions, required, optional);
if (extractResult.failed()) {
return extractResult;
}
// Inputs
Value A = op.a();
Value B = op.b();
unsigned aRank = A.getType().dyn_cast<RankedTensorType>().getRank();
unsigned bRank = B.getType().dyn_cast<RankedTensorType>().getRank();
if (aRank == 2 && bRank == 2)
return rewriteMatrixMatrixMultiplication(op, rewriter, extBlocks);
else if (aRank == 2 && bRank == 1)
return rewriteMatrixVectorMultiplication(op, rewriter, extBlocks);
else if (aRank == 1 && bRank == 2)
return rewriteVectorMatrixMultiplication(op, rewriter, extBlocks);
else
return rewriteVectorVectorMultiplication(op, rewriter, extBlocks);
};
private:
LogicalResult
rewriteMatrixMatrixMultiplication(graphblas::MatrixMultiplyGenericOp op,
PatternRewriter &rewriter,
ExtensionBlocks extBlocks) const {
ModuleOp module = op->getParentOfType<ModuleOp>();
Location loc = op->getLoc();
// Inputs
Value A = op.a();
Value B = op.b();
Value mask = op.mask();
bool isMaskComplement = op.mask_complement();
// Types
Type indexType = rewriter.getIndexType();
Type int64Type = rewriter.getIntegerType(64);
Type valueType =
op.getResult().getType().dyn_cast<RankedTensorType>().getElementType();
MemRefType memref1DI64Type = MemRefType::get({-1}, int64Type);
MemRefType memref1DValueType = MemRefType::get({-1}, valueType);
// Initial constants
Value c0 = rewriter.create<arith::ConstantIndexOp>(loc, 0);
Value c1 = rewriter.create<arith::ConstantIndexOp>(loc, 1);
Value ci0 = rewriter.create<arith::ConstantIntOp>(loc, 0, int64Type);
Value nrow = rewriter.create<graphblas::NumRowsOp>(loc, A);
Value ncol = rewriter.create<graphblas::NumColsOp>(loc, B);
Value nk = rewriter.create<graphblas::NumColsOp>(
loc, A); // guaranteed equal to B.rows
Value nrow_plus_one = rewriter.create<arith::AddIOp>(loc, nrow, c1);
Value C = callEmptyLike(rewriter, module, loc, A);
callResizeDim(rewriter, module, loc, C, c0, nrow);
callResizeDim(rewriter, module, loc, C, c1, ncol);
callResizePointers(rewriter, module, loc, C, c1, nrow_plus_one);
Value Ap = rewriter.create<sparse_tensor::ToPointersOp>(
loc, memref1DI64Type, A, c1);
Value Aj = rewriter.create<sparse_tensor::ToIndicesOp>(loc, memref1DI64Type,
A, c1);
Value Ax =
rewriter.create<sparse_tensor::ToValuesOp>(loc, memref1DValueType, A);
Value Bp = rewriter.create<sparse_tensor::ToPointersOp>(
loc, memref1DI64Type, B, c1);
Value Bi = rewriter.create<sparse_tensor::ToIndicesOp>(loc, memref1DI64Type,
B, c1);
Value Bx =
rewriter.create<sparse_tensor::ToValuesOp>(loc, memref1DValueType, B);
Value Cp = rewriter.create<sparse_tensor::ToPointersOp>(
loc, memref1DI64Type, C, c1);
Value Mp, Mj;
if (mask) {
Mp = rewriter.create<sparse_tensor::ToPointersOp>(loc, memref1DI64Type,
mask, c1);
Mj = rewriter.create<sparse_tensor::ToIndicesOp>(loc, memref1DI64Type,
mask, c1);
}
// 1st pass
// Compute the number of nonzero entries per row.
// Store results in Cp
// The rows in A are the fixed elements, while the columns of B are the
// iteration element
scf::ParallelOp rowLoop1 =
rewriter.create<scf::ParallelOp>(loc, c0, nrow, c1);
Value row = rowLoop1.getInductionVars().front();
rewriter.setInsertionPointToStart(rowLoop1.getBody());
Value colStart64 = rewriter.create<memref::LoadOp>(loc, Ap, row);
Value rowPlus1 = rewriter.create<arith::AddIOp>(loc, row, c1);
Value colEnd64 = rewriter.create<memref::LoadOp>(loc, Ap, rowPlus1);
Value cmpColSame = rewriter.create<arith::CmpIOp>(
loc, arith::CmpIPredicate::eq, colStart64, colEnd64);
scf::IfOp ifBlock_rowTotal =
rewriter.create<scf::IfOp>(loc, int64Type, cmpColSame, true);
// if cmpColSame
rewriter.setInsertionPointToStart(ifBlock_rowTotal.thenBlock());
rewriter.create<scf::YieldOp>(loc, ci0);
// else
rewriter.setInsertionPointToStart(ifBlock_rowTotal.elseBlock());
Value colStart =
rewriter.create<arith::IndexCastOp>(loc, colStart64, indexType);
Value colEnd =
rewriter.create<arith::IndexCastOp>(loc, colEnd64, indexType);
Value total;
if (mask) {
Value mcolStart64 = rewriter.create<memref::LoadOp>(loc, Mp, row);
Value mcolEnd64 = rewriter.create<memref::LoadOp>(loc, Mp, rowPlus1);
Value mcolStart =
rewriter.create<arith::IndexCastOp>(loc, mcolStart64, indexType);
Value mcolEnd =
rewriter.create<arith::IndexCastOp>(loc, mcolEnd64, indexType);
if (isMaskComplement) {
ValueRange mcResult =
buildMaskComplement(rewriter, loc, ncol, Mj, mcolStart, mcolEnd);
Value maskComplement = mcResult[0];
Value mcSize = mcResult[1];
total = computeNumOverlaps(rewriter, loc, nk, Aj, colStart, colEnd, Bp,
Bi, maskComplement, c0, mcSize, valueType);
rewriter.create<memref::DeallocOp>(loc, maskComplement);
} else {
total = computeNumOverlaps(rewriter, loc, nk, Aj, colStart, colEnd, Bp,
Bi, Mj, mcolStart, mcolEnd, valueType);
}
} else {
total = computeNumOverlaps(rewriter, loc, nk, Aj, colStart, colEnd, Bp,
Bi, nullptr, c0, ncol, valueType);
}
rewriter.create<scf::YieldOp>(loc, total);
// end if cmpColSame
rewriter.setInsertionPointAfter(ifBlock_rowTotal);
Value rowTotal = ifBlock_rowTotal.getResult(0);
rewriter.create<memref::StoreOp>(loc, rowTotal, Cp, row);
// end row loop
rewriter.setInsertionPointAfter(rowLoop1);
// 2nd pass
// Compute the cumsum of values in Cp to build the final Cp
// Then resize C's indices and values
scf::ForOp rowLoop2 = rewriter.create<scf::ForOp>(loc, c0, nrow, c1);
Value cs_i = rowLoop2.getInductionVar();
rewriter.setInsertionPointToStart(rowLoop2.getBody());
Value csTemp = rewriter.create<memref::LoadOp>(loc, Cp, cs_i);
Value cumsum = rewriter.create<memref::LoadOp>(loc, Cp, nrow);
rewriter.create<memref::StoreOp>(loc, cumsum, Cp, cs_i);
Value cumsum2 = rewriter.create<arith::AddIOp>(loc, cumsum, csTemp);
rewriter.create<memref::StoreOp>(loc, cumsum2, Cp, nrow);
// end row loop
rewriter.setInsertionPointAfter(rowLoop2);
Value nnz = rewriter.create<graphblas::NumValsOp>(loc, C);
callResizeIndex(rewriter, module, loc, C, c1, nnz);
callResizeValues(rewriter, module, loc, C, nnz);
Value Cj = rewriter.create<sparse_tensor::ToIndicesOp>(loc, memref1DI64Type,
C, c1);
Value Cx =
rewriter.create<sparse_tensor::ToValuesOp>(loc, memref1DValueType, C);
// 3rd pass
// In parallel over the rows,
// compute the nonzero columns and associated values.
// Store in Cj and Cx
// The rows in A are the fixed elements, while the columns of B are the
// iteration element
scf::ParallelOp rowLoop3 =
rewriter.create<scf::ParallelOp>(loc, c0, nrow, c1);
row = rowLoop3.getInductionVars().front();
rewriter.setInsertionPointToStart(rowLoop3.getBody());
rowPlus1 = rewriter.create<arith::AddIOp>(loc, row, c1);
Value cpStart64 = rewriter.create<memref::LoadOp>(loc, Cp, row);
Value cpEnd64 = rewriter.create<memref::LoadOp>(loc, Cp, rowPlus1);
Value cmp_cpDifferent = rewriter.create<arith::CmpIOp>(
loc, arith::CmpIPredicate::ne, cpStart64, cpEnd64);
scf::IfOp ifBlock_cmpDiff =
rewriter.create<scf::IfOp>(loc, cmp_cpDifferent);
rewriter.setInsertionPointToStart(ifBlock_cmpDiff.thenBlock());
Value baseIndex64 = rewriter.create<memref::LoadOp>(loc, Cp, row);
Value baseIndex =
rewriter.create<arith::IndexCastOp>(loc, baseIndex64, indexType);
colStart64 = rewriter.create<memref::LoadOp>(loc, Ap, row);
colEnd64 = rewriter.create<memref::LoadOp>(loc, Ap, rowPlus1);
colStart = rewriter.create<arith::IndexCastOp>(loc, colStart64, indexType);
colEnd = rewriter.create<arith::IndexCastOp>(loc, colEnd64, indexType);
if (mask) {
Value mcolStart64 = rewriter.create<memref::LoadOp>(loc, Mp, row);
Value mcolEnd64 = rewriter.create<memref::LoadOp>(loc, Mp, rowPlus1);
Value mcolStart =
rewriter.create<arith::IndexCastOp>(loc, mcolStart64, indexType);
Value mcolEnd =
rewriter.create<arith::IndexCastOp>(loc, mcolEnd64, indexType);
if (isMaskComplement) {
ValueRange mcResult =
buildMaskComplement(rewriter, loc, ncol, Mj, mcolStart, mcolEnd);
Value maskComplement = mcResult[0];
Value mcSize = mcResult[1];
computeInnerProduct(rewriter, loc, nk, row, Aj, Ax, colStart, colEnd,
Bp, Bi, Bx, maskComplement, c0, mcSize, valueType,
extBlocks, Cj, Cx, baseIndex, false);
rewriter.create<memref::DeallocOp>(loc, maskComplement);
} else {
computeInnerProduct(rewriter, loc, nk, row, Aj, Ax, colStart, colEnd,
Bp, Bi, Bx, Mj, mcolStart, mcolEnd, valueType,
extBlocks, Cj, Cx, baseIndex, false);
}
} else {
computeInnerProduct(rewriter, loc, nk, row, Aj, Ax, colStart, colEnd, Bp,
Bi, Bx, nullptr, c0, ncol, valueType, extBlocks, Cj,
Cx, baseIndex, false);
}
// end if cmpDiff
rewriter.setInsertionPointAfter(ifBlock_cmpDiff);
// end row loop
rewriter.setInsertionPointAfter(rowLoop3);
rewriter.replaceOp(op, C);
cleanupIntermediateTensor(rewriter, module, loc, C);
return success();
}
LogicalResult
rewriteMatrixVectorMultiplication(graphblas::MatrixMultiplyGenericOp op,
PatternRewriter &rewriter,
ExtensionBlocks extBlocks) const {
ModuleOp module = op->getParentOfType<ModuleOp>();
Location loc = op->getLoc();
// Inputs
Value A = op.a();
Value B = op.b();
Value mask = op.mask();
bool isMaskComplement = op.mask_complement();
// Types
Type indexType = rewriter.getIndexType();
Type int64Type = rewriter.getIntegerType(64);
Type valueType =
op.getResult().getType().dyn_cast<RankedTensorType>().getElementType();
MemRefType memref1DI64Type = MemRefType::get({-1}, int64Type);
MemRefType memref1DValueType = MemRefType::get({-1}, valueType);
// Initial constants
Value c0 = rewriter.create<arith::ConstantIndexOp>(loc, 0);
Value c1 = rewriter.create<arith::ConstantIndexOp>(loc, 1);
Value c2 = rewriter.create<arith::ConstantIndexOp>(loc, 2);
Value ci0 = rewriter.create<arith::ConstantIntOp>(loc, 0, int64Type);
Value size = rewriter.create<graphblas::NumRowsOp>(loc, A);
Value nk = rewriter.create<graphblas::SizeOp>(loc, B);
// TODO: how do I check nk == nk_check and raise an exception if they don't
// match? Value nk_check = rewriter.create<graphblas::NumColsOp>(loc, A);
Value C = callEmptyLike(rewriter, module, loc, B);
callResizeDim(rewriter, module, loc, C, c0, size);
callResizePointers(rewriter, module, loc, C, c0, c2);
Value Ap = rewriter.create<sparse_tensor::ToPointersOp>(
loc, memref1DI64Type, A, c1);
Value Aj = rewriter.create<sparse_tensor::ToIndicesOp>(loc, memref1DI64Type,
A, c1);
Value Ax =
rewriter.create<sparse_tensor::ToValuesOp>(loc, memref1DValueType, A);
Value Bp = rewriter.create<sparse_tensor::ToPointersOp>(
loc, memref1DI64Type, B, c0);
Value Bi = rewriter.create<sparse_tensor::ToIndicesOp>(loc, memref1DI64Type,
B, c0);
Value Bx =
rewriter.create<sparse_tensor::ToValuesOp>(loc, memref1DValueType, B);
Value Cp = rewriter.create<sparse_tensor::ToPointersOp>(
loc, memref1DI64Type, C, c0);
Value Mp, Mi, maskStart, maskEnd;
if (mask) {
Mp = rewriter.create<sparse_tensor::ToPointersOp>(loc, memref1DI64Type,
mask, c0);
Mi = rewriter.create<sparse_tensor::ToIndicesOp>(loc, memref1DI64Type,
mask, c0);
Value maskStart64 = rewriter.create<memref::LoadOp>(loc, Mp, c0);
Value maskEnd64 = rewriter.create<memref::LoadOp>(loc, Mp, c1);
maskStart =
rewriter.create<arith::IndexCastOp>(loc, maskStart64, indexType);
maskEnd = rewriter.create<arith::IndexCastOp>(loc, maskEnd64, indexType);
}
// 1st pass
// Compute the number of nonzero entries in the result
// Store results in Cp
// The vector B is the fixed element, while the rows of A are the
// iteration element
Value fixedIndexEnd64 = rewriter.create<memref::LoadOp>(loc, Bp, c1);
Value fixedIndexEnd =
rewriter.create<arith::IndexCastOp>(loc, fixedIndexEnd64, indexType);
Value cmpColSame = rewriter.create<arith::CmpIOp>(
loc, arith::CmpIPredicate::eq, c0, fixedIndexEnd);
scf::IfOp ifBlock_rowTotal =
rewriter.create<scf::IfOp>(loc, int64Type, cmpColSame, true);
// if cmpColSame
rewriter.setInsertionPointToStart(ifBlock_rowTotal.thenBlock());
rewriter.create<scf::YieldOp>(loc, ci0);
// else
rewriter.setInsertionPointToStart(ifBlock_rowTotal.elseBlock());
Value total;
if (mask) {
if (isMaskComplement) {
ValueRange mcResult =
buildMaskComplement(rewriter, loc, size, Mi, maskStart, maskEnd);
Value maskComplement = mcResult[0];
Value mcSize = mcResult[1];
total = computeNumOverlaps(rewriter, loc, nk, Bi, c0, fixedIndexEnd, Ap,
Aj, maskComplement, c0, mcSize, valueType);
rewriter.create<memref::DeallocOp>(loc, maskComplement);
} else {
total = computeNumOverlaps(rewriter, loc, nk, Bi, c0, fixedIndexEnd, Ap,
Aj, Mi, maskStart, maskEnd, valueType);
}
} else {
total = computeNumOverlaps(rewriter, loc, nk, Bi, c0, fixedIndexEnd, Ap,
Aj, nullptr, c0, size, valueType);
}
rewriter.create<scf::YieldOp>(loc, total);
// end if cmpColSame
rewriter.setInsertionPointAfter(ifBlock_rowTotal);
Value nnzTotal = ifBlock_rowTotal.getResult(0);
Value nnz = rewriter.create<arith::IndexCastOp>(loc, nnzTotal, indexType);
rewriter.create<memref::StoreOp>(loc, nnzTotal, Cp, c1);
callResizeIndex(rewriter, module, loc, C, c0, nnz);
callResizeValues(rewriter, module, loc, C, nnz);
Value Ci = rewriter.create<sparse_tensor::ToIndicesOp>(loc, memref1DI64Type,
C, c0);
Value Cx =
rewriter.create<sparse_tensor::ToValuesOp>(loc, memref1DValueType, C);
// 2nd pass
// Compute the nonzero values.
// Store in Ci and Cx
// The vector B is the fixed element, while the rows of A are the
// iteration element
Value cmp_cpDifferent =
rewriter.create<arith::CmpIOp>(loc, arith::CmpIPredicate::ne, c0, nnz);
scf::IfOp ifBlock_cmpDiff =
rewriter.create<scf::IfOp>(loc, cmp_cpDifferent);
rewriter.setInsertionPointToStart(ifBlock_cmpDiff.thenBlock());
if (mask) {
if (isMaskComplement) {
ValueRange mcResult =
buildMaskComplement(rewriter, loc, size, Mi, maskStart, maskEnd);
Value maskComplement = mcResult[0];
Value mcSize = mcResult[1];
computeInnerProduct(rewriter, loc, nk, c0, Bi, Bx, c0, fixedIndexEnd,
Ap, Aj, Ax, maskComplement, c0, mcSize, valueType,
extBlocks, Ci, Cx, c0, true);
rewriter.create<memref::DeallocOp>(loc, maskComplement);
} else {
computeInnerProduct(rewriter, loc, nk, c0, Bi, Bx, c0, fixedIndexEnd,
Ap, Aj, Ax, Mi, maskStart, maskEnd, valueType,
extBlocks, Ci, Cx, c0, true);
}
} else {
computeInnerProduct(rewriter, loc, nk, c0, Bi, Bx, c0, fixedIndexEnd, Ap,
Aj, Ax, nullptr, c0, size, valueType, extBlocks, Ci,
Cx, c0, true);
}
// end if cmpDiff
rewriter.setInsertionPointAfter(ifBlock_cmpDiff);
rewriter.replaceOp(op, C);
cleanupIntermediateTensor(rewriter, module, loc, C);
return success();
}
LogicalResult
rewriteVectorMatrixMultiplication(graphblas::MatrixMultiplyGenericOp op,
PatternRewriter &rewriter,
ExtensionBlocks extBlocks) const {
ModuleOp module = op->getParentOfType<ModuleOp>();
Location loc = op->getLoc();
// Inputs
Value A = op.a();
Value B = op.b();
Value mask = op.mask();
bool isMaskComplement = op.mask_complement();
// Types
Type indexType = rewriter.getIndexType();
Type int64Type = rewriter.getIntegerType(64);
Type valueType =
op.getResult().getType().dyn_cast<RankedTensorType>().getElementType();
MemRefType memref1DI64Type = MemRefType::get({-1}, int64Type);
MemRefType memref1DValueType = MemRefType::get({-1}, valueType);
// Initial constants
Value c0 = rewriter.create<arith::ConstantIndexOp>(loc, 0);
Value c1 = rewriter.create<arith::ConstantIndexOp>(loc, 1);
Value c2 = rewriter.create<arith::ConstantIndexOp>(loc, 2);
Value ci0 = rewriter.create<arith::ConstantIntOp>(loc, 0, int64Type);
Value size = rewriter.create<graphblas::NumColsOp>(loc, B);
Value nk = rewriter.create<graphblas::SizeOp>(
loc, A); // guaranteed equal to B.rows
Value C = callEmptyLike(rewriter, module, loc, A);
callResizeDim(rewriter, module, loc, C, c0, size);
callResizePointers(rewriter, module, loc, C, c0, c2);
Value Ap = rewriter.create<sparse_tensor::ToPointersOp>(
loc, memref1DI64Type, A, c0);
Value Ai = rewriter.create<sparse_tensor::ToIndicesOp>(loc, memref1DI64Type,
A, c0);
Value Ax =
rewriter.create<sparse_tensor::ToValuesOp>(loc, memref1DValueType, A);
Value Bp = rewriter.create<sparse_tensor::ToPointersOp>(
loc, memref1DI64Type, B, c1);
Value Bi = rewriter.create<sparse_tensor::ToIndicesOp>(loc, memref1DI64Type,
B, c1);
Value Bx =
rewriter.create<sparse_tensor::ToValuesOp>(loc, memref1DValueType, B);
Value Cp = rewriter.create<sparse_tensor::ToPointersOp>(
loc, memref1DI64Type, C, c0);
Value Mp, Mi, maskStart, maskEnd;
if (mask) {
Mp = rewriter.create<sparse_tensor::ToPointersOp>(loc, memref1DI64Type,
mask, c0);
Mi = rewriter.create<sparse_tensor::ToIndicesOp>(loc, memref1DI64Type,
mask, c0);
Value maskStart64 = rewriter.create<memref::LoadOp>(loc, Mp, c0);
Value maskEnd64 = rewriter.create<memref::LoadOp>(loc, Mp, c1);
maskStart =
rewriter.create<arith::IndexCastOp>(loc, maskStart64, indexType);
maskEnd = rewriter.create<arith::IndexCastOp>(loc, maskEnd64, indexType);
}
// 1st pass
// Compute the number of nonzero entries in the result
// Store results in Cp
// The vector A is the fixed element, while the columns of B are the
// iteration element
Value fixedIndexEnd64 = rewriter.create<memref::LoadOp>(loc, Ap, c1);
Value fixedIndexEnd =
rewriter.create<arith::IndexCastOp>(loc, fixedIndexEnd64, indexType);
Value cmpColSame = rewriter.create<arith::CmpIOp>(
loc, arith::CmpIPredicate::eq, c0, fixedIndexEnd);
scf::IfOp ifBlock_rowTotal =
rewriter.create<scf::IfOp>(loc, int64Type, cmpColSame, true);
// if cmpColSame
rewriter.setInsertionPointToStart(ifBlock_rowTotal.thenBlock());
rewriter.create<scf::YieldOp>(loc, ci0);
// else
rewriter.setInsertionPointToStart(ifBlock_rowTotal.elseBlock());
Value total;
if (mask) {
if (isMaskComplement) {
ValueRange mcResult =
buildMaskComplement(rewriter, loc, size, Mi, maskStart, maskEnd);
Value maskComplement = mcResult[0];
Value mcSize = mcResult[1];
total = computeNumOverlaps(rewriter, loc, nk, Ai, c0, fixedIndexEnd, Bp,
Bi, maskComplement, c0, mcSize, valueType);
rewriter.create<memref::DeallocOp>(loc, maskComplement);
} else {
total = computeNumOverlaps(rewriter, loc, nk, Ai, c0, fixedIndexEnd, Bp,
Bi, Mi, maskStart, maskEnd, valueType);
}
} else {
total = computeNumOverlaps(rewriter, loc, nk, Ai, c0, fixedIndexEnd, Bp,
Bi, nullptr, c0, size, valueType);
}
rewriter.create<scf::YieldOp>(loc, total);
// end if cmpColSame
rewriter.setInsertionPointAfter(ifBlock_rowTotal);
Value nnzTotal = ifBlock_rowTotal.getResult(0);
Value nnz = rewriter.create<arith::IndexCastOp>(loc, nnzTotal, indexType);
rewriter.create<memref::StoreOp>(loc, nnzTotal, Cp, c1);
callResizeIndex(rewriter, module, loc, C, c0, nnz);
callResizeValues(rewriter, module, loc, C, nnz);
Value Ci = rewriter.create<sparse_tensor::ToIndicesOp>(loc, memref1DI64Type,
C, c0);
Value Cx =
rewriter.create<sparse_tensor::ToValuesOp>(loc, memref1DValueType, C);
// 2nd pass
// Compute the nonzero values.
// Store in Ci and Cx
// The vector A is the fixed element, while the columns of B are the
// iteration element
Value cmp_cpDifferent =
rewriter.create<arith::CmpIOp>(loc, arith::CmpIPredicate::ne, c0, nnz);
scf::IfOp ifBlock_cmpDiff =
rewriter.create<scf::IfOp>(loc, cmp_cpDifferent);
rewriter.setInsertionPointToStart(ifBlock_cmpDiff.thenBlock());
if (mask) {
if (isMaskComplement) {
ValueRange mcResult =
buildMaskComplement(rewriter, loc, size, Mi, maskStart, maskEnd);
Value maskComplement = mcResult[0];
Value mcSize = mcResult[1];
computeInnerProduct(rewriter, loc, nk, c0, Ai, Ax, c0, fixedIndexEnd,
Bp, Bi, Bx, maskComplement, c0, mcSize, valueType,
extBlocks, Ci, Cx, c0, false);
rewriter.create<memref::DeallocOp>(loc, maskComplement);
} else {
computeInnerProduct(rewriter, loc, nk, c0, Ai, Ax, c0, fixedIndexEnd,
Bp, Bi, Bx, Mi, maskStart, maskEnd, valueType,
extBlocks, Ci, Cx, c0, false);
}
} else {
computeInnerProduct(rewriter, loc, nk, c0, Ai, Ax, c0, fixedIndexEnd, Bp,
Bi, Bx, nullptr, c0, size, valueType, extBlocks, Ci,
Cx, c0, false);
}
// end if cmpDiff
rewriter.setInsertionPointAfter(ifBlock_cmpDiff);
rewriter.replaceOp(op, C);
cleanupIntermediateTensor(rewriter, module, loc, C);
return success();
}
LogicalResult
rewriteVectorVectorMultiplication(graphblas::MatrixMultiplyGenericOp op,
PatternRewriter &rewriter,
ExtensionBlocks extBlocks) const {
ModuleOp module = op->getParentOfType<ModuleOp>();
Location loc = op->getLoc();
// Inputs
Value A = op.a();
Value B = op.b();
// Types
Type indexType = rewriter.getIndexType();
Type int64Type = rewriter.getIntegerType(64);
Type valueType = A.getType().dyn_cast<RankedTensorType>().getElementType();
MemRefType memref1DI64Type = MemRefType::get({-1}, int64Type);
MemRefType memref1DValueType = MemRefType::get({-1}, valueType);
// Initial constants
Value c0 = rewriter.create<arith::ConstantIndexOp>(loc, 0);
Value c1 = rewriter.create<arith::ConstantIndexOp>(loc, 1);
Value c2 = rewriter.create<arith::ConstantIndexOp>(loc, 2);
Value size = rewriter.create<graphblas::SizeOp>(loc, A);
Value C = callEmptyLike(rewriter, module, loc, A);
callResizeDim(
rewriter, module, loc, C, c0,
c1); // exactly one entry because this is a vector representing a scalar
callResizePointers(rewriter, module, loc, C, c0, c2);
callResizeIndex(rewriter, module, loc, C, c0, c1);
callResizeValues(rewriter, module, loc, C, c1);
Value Ap = rewriter.create<sparse_tensor::ToPointersOp>(
loc, memref1DI64Type, A, c0);
Value Ai = rewriter.create<sparse_tensor::ToIndicesOp>(loc, memref1DI64Type,
A, c0);
Value Ax =
rewriter.create<sparse_tensor::ToValuesOp>(loc, memref1DValueType, A);
Value Bp = rewriter.create<sparse_tensor::ToPointersOp>(
loc, memref1DI64Type, B, c0);
Value Bi = rewriter.create<sparse_tensor::ToIndicesOp>(loc, memref1DI64Type,
B, c0);
Value Bx =
rewriter.create<sparse_tensor::ToValuesOp>(loc, memref1DValueType, B);
Value Ci = rewriter.create<sparse_tensor::ToIndicesOp>(loc, memref1DI64Type,
C, c0);
Value Cx =
rewriter.create<sparse_tensor::ToValuesOp>(loc, memref1DValueType, C);
// Single pass
// Compute the nonzero values.
// Store in Ci and Cx (single-element vector representing a scalar)
// The vector A is the fixed element, while the vector B is treated as the
// iteration element
Value fixedIndexEnd64 = rewriter.create<memref::LoadOp>(loc, Ap, c1);
Value fixedIndexEnd =
rewriter.create<arith::IndexCastOp>(loc, fixedIndexEnd64, indexType);
computeInnerProduct(rewriter, loc, size, c0, Ai, Ax, c0, fixedIndexEnd, Bp,
Bi, Bx, nullptr, c0, c1, valueType, extBlocks, Ci, Cx,
c0, false);
// extract scalar from C
Value cScalar = rewriter.create<memref::LoadOp>(loc, Cx, c0);
rewriter.replaceOp(op, cScalar);
cleanupIntermediateTensor(rewriter, module, loc, C);
return success();
}
};
class MatrixMultiplyReduceToScalarGenericDWIMFirstArgRewrite
: public OpRewritePattern<
graphblas::MatrixMultiplyReduceToScalarGenericOp> {
public:
using OpRewritePattern<
graphblas::MatrixMultiplyReduceToScalarGenericOp>::OpRewritePattern;
LogicalResult
matchAndRewrite(graphblas::MatrixMultiplyReduceToScalarGenericOp op,
PatternRewriter &rewriter) const override {
if (!MatrixMultiplyGenericDWIMFirstArgRewrite::needsDWIM(op))
return failure();
MLIRContext *context = op.getContext();
Location loc = op->getLoc();
Value A = op.a();
RankedTensorType aType = A.getType().cast<RankedTensorType>();
RankedTensorType flippedMatrixType = getFlippedLayoutType(context, aType);
rewriter.setInsertionPoint(op);
Value flippedA =
rewriter.create<graphblas::ConvertLayoutOp>(loc, flippedMatrixType, A);
op.aMutable().assign(flippedA);
return success();
};
};
class MatrixMultiplyReduceToScalarGenericDWIMSecondArgRewrite
: public OpRewritePattern<
graphblas::MatrixMultiplyReduceToScalarGenericOp> {
public:
using OpRewritePattern<
graphblas::MatrixMultiplyReduceToScalarGenericOp>::OpRewritePattern;
LogicalResult
matchAndRewrite(graphblas::MatrixMultiplyReduceToScalarGenericOp op,
PatternRewriter &rewriter) const override {
if (!MatrixMultiplyGenericDWIMSecondArgRewrite::needsDWIM(op))
return failure();
MLIRContext *context = op.getContext();
Location loc = op->getLoc();
Value B = op.b();
RankedTensorType bType = B.getType().cast<RankedTensorType>();
RankedTensorType flippedMatrixType = getFlippedLayoutType(context, bType);
rewriter.setInsertionPoint(op);
Value flippedB =
rewriter.create<graphblas::ConvertLayoutOp>(loc, flippedMatrixType, B);
op.bMutable().assign(flippedB);
return success();
};
};
class MatrixMultiplyReduceToScalarGenericDWIMMaskRewrite
: public OpRewritePattern<
graphblas::MatrixMultiplyReduceToScalarGenericOp> {
public:
using OpRewritePattern<
graphblas::MatrixMultiplyReduceToScalarGenericOp>::OpRewritePattern;
LogicalResult
matchAndRewrite(graphblas::MatrixMultiplyReduceToScalarGenericOp op,
PatternRewriter &rewriter) const override {
if (!MatrixMultiplyGenericDWIMMaskRewrite::needsDWIM(op))
return failure();
MLIRContext *context = op.getContext();
Location loc = op->getLoc();
Value mask = op.mask();
RankedTensorType maskType = mask.getType().cast<RankedTensorType>();
RankedTensorType flippedMatrixType =
getFlippedLayoutType(context, maskType);
rewriter.setInsertionPoint(op);
Value flippedMask = rewriter.create<graphblas::ConvertLayoutOp>(
loc, flippedMatrixType, mask);
op.maskMutable().assign(flippedMask);
return success();
};
};
class LowerMatrixMultiplyReduceToScalarGenericRewrite
: public OpRewritePattern<
graphblas::MatrixMultiplyReduceToScalarGenericOp> {
public:
using OpRewritePattern<
graphblas::MatrixMultiplyReduceToScalarGenericOp>::OpRewritePattern;
LogicalResult
matchAndRewrite(graphblas::MatrixMultiplyReduceToScalarGenericOp op,
PatternRewriter &rewriter) const override {
if (MatrixMultiplyGenericDWIMFirstArgRewrite::needsDWIM(op) ||
MatrixMultiplyGenericDWIMSecondArgRewrite::needsDWIM(op) ||
MatrixMultiplyGenericDWIMMaskRewrite::needsDWIM(op))
return failure();
ModuleOp module = op->getParentOfType<ModuleOp>(); /* ignore unused variable
for debugging */
(void)module;
Location loc = op->getLoc();
// Inputs
Value A = op.a();
Value B = op.b();
Value mask = op.mask();
// Required blocks
RegionRange extensions = op.extensions();
ExtensionBlocks extBlocks;
std::set<graphblas::YieldKind> required = {
graphblas::YieldKind::ADD_IDENTITY, graphblas::YieldKind::ADD,
graphblas::YieldKind::MULT, graphblas::YieldKind::AGG_IDENTITY,
graphblas::YieldKind::AGG};
std::set<graphblas::YieldKind> optional = {};
LogicalResult extractResult =
extBlocks.extractBlocks(op, extensions, required, optional);
if (extractResult.failed()) {
return extractResult;
}
// Types
Type indexType = rewriter.getIndexType();
Type int64Type = rewriter.getIntegerType(64);
Type boolType = rewriter.getI1Type();
Type valueType = A.getType().dyn_cast<RankedTensorType>().getElementType();
MemRefType memref1DI64Type = MemRefType::get({-1}, int64Type);
MemRefType memref1DBoolType = MemRefType::get({-1}, boolType);
MemRefType memref1DValueType = MemRefType::get({-1}, valueType);
// Initial constants
Value c0 = rewriter.create<arith::ConstantIndexOp>(loc, 0);
Value c1 = rewriter.create<arith::ConstantIndexOp>(loc, 1);
// TODO: make cf0 value dependent on the aggregator
Value cf0 = llvm::TypeSwitch<Type, Value>(valueType)
.Case<IntegerType>([&](IntegerType type) {
return rewriter.create<arith::ConstantIntOp>(
loc, 0, type.getWidth());
})
.Case<FloatType>([&](FloatType type) {
return rewriter.create<arith::ConstantFloatOp>(
loc, APFloat(0.0), type);
});
Value ctrue = rewriter.create<arith::ConstantIntOp>(loc, 1, boolType);
Value cfalse = rewriter.create<arith::ConstantIntOp>(loc, 0, boolType);
// Get sparse tensor info
Value Ap = rewriter.create<sparse_tensor::ToPointersOp>(
loc, memref1DI64Type, A, c1);
Value Aj = rewriter.create<sparse_tensor::ToIndicesOp>(loc, memref1DI64Type,
A, c1);
Value Ax =
rewriter.create<sparse_tensor::ToValuesOp>(loc, memref1DValueType, A);
Value Bp = rewriter.create<sparse_tensor::ToPointersOp>(
loc, memref1DI64Type, B, c1);
Value Bi = rewriter.create<sparse_tensor::ToIndicesOp>(loc, memref1DI64Type,
B, c1);
Value Bx =
rewriter.create<sparse_tensor::ToValuesOp>(loc, memref1DValueType, B);
Value nrow = rewriter.create<graphblas::NumRowsOp>(loc, A);
Value ncol = rewriter.create<graphblas::NumColsOp>(loc, B);
Value nk = rewriter.create<graphblas::NumColsOp>(
loc, A); // guaranteed equal to B.rows
Value Mp, Mj;
if (mask) {
Mp = rewriter.create<sparse_tensor::ToPointersOp>(loc, memref1DI64Type,
mask, c1);
Mj = rewriter.create<sparse_tensor::ToIndicesOp>(loc, memref1DI64Type,
mask, c1);
}
// In parallel over the rows and columns,
// compute the nonzero values and accumulate
scf::ParallelOp rowLoop =
rewriter.create<scf::ParallelOp>(loc, c0, nrow, c1, cf0);
Value row = rowLoop.getInductionVars().front();
rewriter.setInsertionPointToStart(rowLoop.getBody());
Value rowPlus1 = rewriter.create<arith::AddIOp>(loc, row, c1);
Value apStart64 = rewriter.create<memref::LoadOp>(loc, Ap, row);
Value apEnd64 = rewriter.create<memref::LoadOp>(loc, Ap, rowPlus1);
Value cmp_cpSame = rewriter.create<arith::CmpIOp>(
loc, arith::CmpIPredicate::eq, apStart64, apEnd64);
scf::IfOp ifBlock_cmpSame =
rewriter.create<scf::IfOp>(loc, valueType, cmp_cpSame, true);
// if cmpSame
rewriter.setInsertionPointToStart(ifBlock_cmpSame.thenBlock());
rewriter.create<scf::YieldOp>(loc, cf0);
// else
rewriter.setInsertionPointToStart(ifBlock_cmpSame.elseBlock());
// Construct a dense array of row values
Value colStart =
rewriter.create<arith::IndexCastOp>(loc, apStart64, indexType);
Value colEnd = rewriter.create<arith::IndexCastOp>(loc, apEnd64, indexType);
Value kvec = rewriter.create<memref::AllocOp>(loc, memref1DValueType, nk);
Value kvec_i1 = rewriter.create<memref::AllocOp>(loc, memref1DBoolType, nk);
rewriter.create<linalg::FillOp>(loc, cfalse, kvec_i1);
scf::ParallelOp colLoop1 =
rewriter.create<scf::ParallelOp>(loc, colStart, colEnd, c1);
Value jj = colLoop1.getInductionVars().front();
rewriter.setInsertionPointToStart(colLoop1.getBody());
Value col64 = rewriter.create<memref::LoadOp>(loc, Aj, jj);
Value col = rewriter.create<arith::IndexCastOp>(loc, col64, indexType);
rewriter.create<memref::StoreOp>(loc, ctrue, kvec_i1, col);
Value val = rewriter.create<memref::LoadOp>(loc, Ax, jj);
rewriter.create<memref::StoreOp>(loc, val, kvec, col);
// end col loop 1
rewriter.setInsertionPointAfter(colLoop1);
// Loop thru all columns of B; accumulate values
scf::ParallelOp colLoop2;
if (mask) {
Value mcolStart64 = rewriter.create<memref::LoadOp>(loc, Mp, row);
Value mcolEnd64 = rewriter.create<memref::LoadOp>(loc, Mp, rowPlus1);
Value mcolStart =
rewriter.create<arith::IndexCastOp>(loc, mcolStart64, indexType);
Value mcolEnd =
rewriter.create<arith::IndexCastOp>(loc, mcolEnd64, indexType);
colLoop2 =
rewriter.create<scf::ParallelOp>(loc, mcolStart, mcolEnd, c1, cf0);
Value mm = colLoop2.getInductionVars().front();
rewriter.setInsertionPointToStart(colLoop2.getBody());
col64 = rewriter.create<memref::LoadOp>(loc, Mj, mm);
col = rewriter.create<arith::IndexCastOp>(loc, col64, indexType);
} else {
colLoop2 = rewriter.create<scf::ParallelOp>(loc, c0, ncol, c1, cf0);
col = colLoop2.getInductionVars().front();
rewriter.setInsertionPointToStart(colLoop2.getBody());
col64 = rewriter.create<arith::IndexCastOp>(loc, col, int64Type);
}
Value colPlus1 = rewriter.create<arith::AddIOp>(loc, col, c1);
Value iStart64 = rewriter.create<memref::LoadOp>(loc, Bp, col);
Value iEnd64 = rewriter.create<memref::LoadOp>(loc, Bp, colPlus1);
Value iStart =
rewriter.create<arith::IndexCastOp>(loc, iStart64, indexType);
Value iEnd = rewriter.create<arith::IndexCastOp>(loc, iEnd64, indexType);
// insert add identity block
rewriter.mergeBlocks(extBlocks.addIdentity, rewriter.getBlock(), {});
graphblas::YieldOp addIdentityYield =
llvm::dyn_cast_or_null<graphblas::YieldOp>(
rewriter.getBlock()->getTerminator());
Value addIdentity = addIdentityYield.values().front();
rewriter.eraseOp(addIdentityYield);
scf::ForOp kLoop =
rewriter.create<scf::ForOp>(loc, iStart, iEnd, c1, addIdentity);
Value ii = kLoop.getInductionVar();
Value curr = kLoop.getLoopBody().getArgument(1);
rewriter.setInsertionPointToStart(kLoop.getBody());
Value kk64 = rewriter.create<memref::LoadOp>(loc, Bi, ii);
Value kk = rewriter.create<arith::IndexCastOp>(loc, kk64, indexType);
Value cmpPair = rewriter.create<memref::LoadOp>(loc, kvec_i1, kk);
scf::IfOp ifBlock_cmpPair =
rewriter.create<scf::IfOp>(loc, valueType, cmpPair, true);
// if cmpPair
rewriter.setInsertionPointToStart(ifBlock_cmpPair.thenBlock());
Value aVal = rewriter.create<memref::LoadOp>(loc, kvec, kk);
Value bVal = rewriter.create<memref::LoadOp>(loc, Bx, ii);
// insert multiply operation block
ValueRange injectVals = ValueRange{aVal, bVal, row, col, kk};
rewriter.mergeBlocks(
extBlocks.mult, rewriter.getBlock(),
injectVals.slice(0, extBlocks.mult->getArguments().size()));
graphblas::YieldOp multYield = llvm::dyn_cast_or_null<graphblas::YieldOp>(
rewriter.getBlock()->getTerminator());
Value multResult = multYield.values().front();
rewriter.eraseOp(multYield);
// insert add operation block
rewriter.mergeBlocks(extBlocks.add, rewriter.getBlock(),
{curr, multResult});
graphblas::YieldOp addYield = llvm::dyn_cast_or_null<graphblas::YieldOp>(
rewriter.getBlock()->getTerminator());
Value addResult = addYield.values().front();
rewriter.eraseOp(addYield);
rewriter.create<scf::YieldOp>(loc, addResult);
// else
rewriter.setInsertionPointToStart(ifBlock_cmpPair.elseBlock());
rewriter.create<scf::YieldOp>(loc, curr);
// end if cmpPair
rewriter.setInsertionPointAfter(ifBlock_cmpPair);
Value newCurr = ifBlock_cmpPair.getResult(0);
rewriter.create<scf::YieldOp>(loc, newCurr);
// end k loop
rewriter.setInsertionPointAfter(kLoop);
Value colVal = kLoop.getResult(0);
// FIXME: this is where transform_out goes
scf::ReduceOp colReducer = rewriter.create<scf::ReduceOp>(loc, colVal);
BlockArgument lhs = colReducer.getRegion().getArgument(0);
BlockArgument rhs = colReducer.getRegion().getArgument(1);
rewriter.setInsertionPointToStart(&colReducer.getRegion().front());
Region *aggRegion = extBlocks.agg->getParent();
BlockAndValueMapping mapper;
// Clone blocks into front of region to displace existing entry block, which
// will be removed by canonicalization later
aggRegion->cloneInto(&colReducer.getRegion(),
colReducer.getRegion().begin(), mapper);
graphblas::YieldOp colYield = llvm::dyn_cast_or_null<graphblas::YieldOp>(
colReducer.getRegion().front().getTerminator());
Value colAggResult = colYield.values().front();
rewriter.setInsertionPointAfter(colYield);
rewriter.create<scf::ReduceReturnOp>(loc, colAggResult);
rewriter.eraseOp(colYield);
rewriter.setInsertionPointAfter(colReducer);
// end col loop 2
rewriter.setInsertionPointAfter(colLoop2);
Value subtotal = colLoop2.getResult(0);
rewriter.create<memref::DeallocOp>(loc, kvec);
rewriter.create<memref::DeallocOp>(loc, kvec_i1);
rewriter.create<scf::YieldOp>(loc, subtotal);
// end if cmpSame
rewriter.setInsertionPointAfter(ifBlock_cmpSame);
Value rowTotal = ifBlock_cmpSame.getResult(0);
scf::ReduceOp rowReducer = rewriter.create<scf::ReduceOp>(loc, rowTotal);
lhs = rowReducer.getRegion().getArgument(0);
rhs = rowReducer.getRegion().getArgument(1);
rewriter.setInsertionPointToStart(&rowReducer.getRegion().front());
graphblas::YieldOp yield = llvm::dyn_cast_or_null<graphblas::YieldOp>(
extBlocks.agg->getTerminator());
Value aggResult = yield.values().front();
// we can safely merge this agg block now, since the previous agg instance
// was cloned above
rewriter.mergeBlocks(extBlocks.agg, rewriter.getBlock(), {lhs, rhs});
rewriter.create<scf::ReduceReturnOp>(loc, aggResult);
rewriter.eraseOp(yield);
// end row loop
rewriter.setInsertionPointAfter(rowLoop);
Value total = rowLoop.getResult(0);
rewriter.replaceOp(op, total);
return success();
};
};
class LowerUnionRewrite : public OpRewritePattern<graphblas::UnionOp> {
public:
using OpRewritePattern<graphblas::UnionOp>::OpRewritePattern;
LogicalResult matchAndRewrite(graphblas::UnionOp op,
PatternRewriter &rewriter) const override {
Location loc = op->getLoc();
Value a = op.a();
Value b = op.b();
Value mask = op.mask();
Type valueType = a.getType().cast<RankedTensorType>().getElementType();
if (mask) {
NamedAttrList attributes = {};
attributes.append(StringRef("mask_complement"),
rewriter.getBoolAttr(op.mask_complement()));
a = rewriter.create<graphblas::SelectMaskOp>(
loc, a.getType(), ValueRange{a, mask}, attributes.getAttrs());
b = rewriter.create<graphblas::SelectMaskOp>(
loc, b.getType(), ValueRange{b, mask}, attributes.getAttrs());
}
// New op
NamedAttrList attributes = {};
graphblas::UnionGenericOp newUnionOp =
rewriter.create<graphblas::UnionGenericOp>(loc, op->getResultTypes(),
ValueRange{a, b},
attributes.getAttrs(), 1);
if (failed(populateBinary(rewriter, loc, op.union_operator(), valueType,
newUnionOp.getRegions().slice(0, 1),
graphblas::YieldKind::MULT)))
return failure();
rewriter.setInsertionPointAfter(newUnionOp);
rewriter.replaceOp(op, newUnionOp.getResult());
return success();
};
};
class LowerUnionGenericRewrite
: public OpRewritePattern<graphblas::UnionGenericOp> {
public:
using OpRewritePattern<graphblas::UnionGenericOp>::OpRewritePattern;
LogicalResult matchAndRewrite(graphblas::UnionGenericOp op,
PatternRewriter &rewriter) const override {
ModuleOp module = op->getParentOfType<ModuleOp>();
Location loc = op->getLoc();
// Inputs
Value a = op.a();
Value b = op.b();
// Required block
RegionRange extensions = op.extensions();
ExtensionBlocks extBlocks;
std::set<graphblas::YieldKind> required = {graphblas::YieldKind::MULT};
LogicalResult extractResult =
extBlocks.extractBlocks(op, extensions, required, {});
if (extractResult.failed()) {
return extractResult;
}
// Types
RankedTensorType aType = a.getType().dyn_cast<RankedTensorType>();
unsigned rank = aType.getRank(); // ranks guaranteed to be equal
Type outputType =
op.getResult().getType().dyn_cast<RankedTensorType>().getElementType();
Value output = callEmptyLike(rewriter, module, loc, a, outputType);
if (rank == 2) {
computeMatrixElementWise(rewriter, loc, module, a, b, output,
extBlocks.mult, UNION);
} else {
computeVectorElementWise(rewriter, loc, module, a, b, output,
extBlocks.mult, UNION);
}
rewriter.replaceOp(op, output);
cleanupIntermediateTensor(rewriter, module, loc, output);
return success();
};
};
class LowerIntersectRewrite : public OpRewritePattern<graphblas::IntersectOp> {
public:
using OpRewritePattern<graphblas::IntersectOp>::OpRewritePattern;
LogicalResult matchAndRewrite(graphblas::IntersectOp op,
PatternRewriter &rewriter) const override {
Location loc = op->getLoc();
Value a = op.a();
Value b = op.b();
Value mask = op.mask();
Type valueType = a.getType().cast<RankedTensorType>().getElementType();
StringRef opstr = op.intersect_operator();
if (mask) {
NamedAttrList attributes = {};
attributes.append(StringRef("mask_complement"),
rewriter.getBoolAttr(op.mask_complement()));
a = rewriter.create<graphblas::SelectMaskOp>(
loc, a.getType(), ValueRange{a, mask}, attributes.getAttrs());
b = rewriter.create<graphblas::SelectMaskOp>(
loc, b.getType(), ValueRange{b, mask}, attributes.getAttrs());
}
// Special handling for "first" and "second"
if (opstr == "first") {
graphblas::SelectMaskOp newIntersectOp =
rewriter.create<graphblas::SelectMaskOp>(loc, op->getResultTypes(),
ValueRange{a, b});
rewriter.replaceOp(op, newIntersectOp.getResult());
} else if (opstr == "second") {
graphblas::SelectMaskOp newIntersectOp =
rewriter.create<graphblas::SelectMaskOp>(loc, op->getResultTypes(),
ValueRange{b, a});
rewriter.replaceOp(op, newIntersectOp.getResult());
} else {
// New op
NamedAttrList attributes = {};
graphblas::IntersectGenericOp newIntersectOp =
rewriter.create<graphblas::IntersectGenericOp>(
loc, op->getResultTypes(), ValueRange{a, b},
attributes.getAttrs(), 1);
if (failed(populateBinary(rewriter, loc, op.intersect_operator(),
valueType,
newIntersectOp.getRegions().slice(0, 1),
graphblas::YieldKind::MULT)))
return failure();
rewriter.setInsertionPointAfter(newIntersectOp);
rewriter.replaceOp(op, newIntersectOp.getResult());
}
return success();
};
};
class LowerIntersectGenericRewrite
: public OpRewritePattern<graphblas::IntersectGenericOp> {
public:
using OpRewritePattern<graphblas::IntersectGenericOp>::OpRewritePattern;
LogicalResult matchAndRewrite(graphblas::IntersectGenericOp op,
PatternRewriter &rewriter) const override {
ModuleOp module = op->getParentOfType<ModuleOp>();
Location loc = op->getLoc();
// Inputs
Value a = op.a();
Value b = op.b();
// Required block
RegionRange extensions = op.extensions();
ExtensionBlocks extBlocks;
std::set<graphblas::YieldKind> required = {graphblas::YieldKind::MULT};
LogicalResult extractResult =
extBlocks.extractBlocks(op, extensions, required, {});
if (extractResult.failed()) {
return extractResult;
}
// Types
RankedTensorType aType = a.getType().dyn_cast<RankedTensorType>();
unsigned rank = aType.getRank(); // ranks guaranteed to be equal
Type outputType =
op.getResult().getType().dyn_cast<RankedTensorType>().getElementType();
Value output = callEmptyLike(rewriter, module, loc, a, outputType);
if (rank == 2) {
computeMatrixElementWise(rewriter, loc, module, a, b, output,
extBlocks.mult, INTERSECT);
} else {
computeVectorElementWise(rewriter, loc, module, a, b, output,
extBlocks.mult, INTERSECT);
}
rewriter.replaceOp(op, output);
cleanupIntermediateTensor(rewriter, module, loc, output);
return success();
};
};
class LowerUpdateRewrite : public OpRewritePattern<graphblas::UpdateOp> {
public:
using OpRewritePattern<graphblas::UpdateOp>::OpRewritePattern;
LogicalResult matchAndRewrite(graphblas::UpdateOp op,
PatternRewriter &rewriter) const override {
ModuleOp module = op->getParentOfType<ModuleOp>();
Location loc = op->getLoc();
Type valueType =
op.input().getType().cast<RankedTensorType>().getElementType();
bool maskComplement = op.mask_complement();
bool replace = op.replace();
llvm::Optional<llvm::StringRef> accumulateOperator =
op.accumulate_operator();
// Use generic for accumulator
if (accumulateOperator) {
// New op
NamedAttrList attributes = {};
attributes.append(StringRef("mask_complement"),
rewriter.getBoolAttr(maskComplement));
attributes.append(StringRef("replace"), rewriter.getBoolAttr(replace));
graphblas::UpdateGenericOp newUpdateOp =
rewriter.create<graphblas::UpdateGenericOp>(loc, op->getResultTypes(),
op.getOperands(),
attributes.getAttrs(), 1);
if (failed(populateBinary(rewriter, loc, accumulateOperator->str(),
valueType, newUpdateOp.getRegions().slice(0, 1),
graphblas::YieldKind::ACCUMULATE)))
return failure();
rewriter.setInsertionPointAfter(newUpdateOp);
rewriter.eraseOp(op);
return success();
}
// No accumulator; lower without generic op
Value input = op.input();
Value output = op.output();
Value mask = op.mask();
// Types
RankedTensorType outputType = output.getType().dyn_cast<RankedTensorType>();
unsigned rank = outputType.getRank(); // ranks guaranteed to be equal
auto computeEwise =
rank == 2 ? computeMatrixElementWise : computeVectorElementWise;
if (mask) {
EwiseBehavior maskBehavior = (maskComplement ? MASK_COMPLEMENT : MASK);
if (replace) {
// input -> output(mask) { replace }
computeEwise(rewriter, loc, module, input, mask, output, nullptr,
maskBehavior);
} else {
// input -> output(mask)
// Step 1: apply the mask inverse to the output
EwiseBehavior maskInverseBehavior =
(maskComplement ? MASK : MASK_COMPLEMENT);
Value maskedOutput = callEmptyLike(rewriter, module, loc, output);
computeEwise(rewriter, loc, module, output, mask, maskedOutput, nullptr,
maskInverseBehavior);
// Step 2: apply the mask to the input
Value maskedInput = callEmptyLike(rewriter, module, loc, input);
computeEwise(rewriter, loc, module, input, mask, maskedInput, nullptr,
maskBehavior);
// Step 3: union the two masked results
// Note that there should be zero overlaps, so we do not provide
// an accumulation block
computeEwise(rewriter, loc, module, maskedInput, maskedOutput, output,
nullptr, UNION);
rewriter.create<sparse_tensor::ReleaseOp>(loc, maskedOutput);
rewriter.create<sparse_tensor::ReleaseOp>(loc, maskedInput);
}
} else {
// input -> output { replace? }
Value inputCopy = callDupTensor(rewriter, module, loc, input);
callSwapPointers(rewriter, module, loc, inputCopy, output);
callSwapIndices(rewriter, module, loc, inputCopy, output);
callSwapValues(rewriter, module, loc, inputCopy, output);
rewriter.create<sparse_tensor::ReleaseOp>(loc, inputCopy);
}
rewriter.eraseOp(op);
return success();
};
};
class LowerUpdateGenericRewrite
: public OpRewritePattern<graphblas::UpdateGenericOp> {
public:
using OpRewritePattern<graphblas::UpdateGenericOp>::OpRewritePattern;
LogicalResult matchAndRewrite(graphblas::UpdateGenericOp op,
PatternRewriter &rewriter) const override {
ModuleOp module = op->getParentOfType<ModuleOp>();
Location loc = op->getLoc();
// Inputs
Value input = op.input();
Value output = op.output();
Value mask = op.mask();
bool maskComplement = op.mask_complement();
bool replace = op.replace();
// Extension blocks
RegionRange extensions = op.extensions();
ExtensionBlocks extBlocks;
std::set<graphblas::YieldKind> optional = {
graphblas::YieldKind::ACCUMULATE};
LogicalResult extractResult =
extBlocks.extractBlocks(op, extensions, {}, optional);
if (extractResult.failed()) {
return extractResult;
}
// Types
RankedTensorType outputType = output.getType().dyn_cast<RankedTensorType>();
unsigned rank = outputType.getRank(); // ranks guaranteed to be equal
auto computeEwise =
rank == 2 ? computeMatrixElementWise : computeVectorElementWise;
if (mask) {
EwiseBehavior maskBehavior = (maskComplement ? MASK_COMPLEMENT : MASK);
if (replace) {
// input -> output(mask) { accumulate, replace }
// Must think of this as `output(mask) << input` so ordering is correct
// Step 1: apply the mask to the output
Value maskedOutput = callEmptyLike(rewriter, module, loc, output);
computeEwise(rewriter, loc, module, output, mask, maskedOutput, nullptr,
maskBehavior);
// Step 2: apply the mask to the input
Value maskedInput = callEmptyLike(rewriter, module, loc, input);
computeEwise(rewriter, loc, module, input, mask, maskedInput, nullptr,
maskBehavior);
// Step 3: union the two masked results
computeEwise(rewriter, loc, module, maskedOutput, maskedInput, output,
extBlocks.accumulate, UNION);
rewriter.create<sparse_tensor::ReleaseOp>(loc, maskedOutput);
rewriter.create<sparse_tensor::ReleaseOp>(loc, maskedInput);
} else {
// input -> output(mask) { accumulate }
// Must think of this as `output(mask) << input` so ordering is correct
// Step 1: apply the mask to the input
Value maskedInput = callEmptyLike(rewriter, module, loc, input);
computeEwise(rewriter, loc, module, input, mask, maskedInput, nullptr,
maskBehavior);
// Step 2: union the two masked results
Value outputCopy = callDupTensor(rewriter, module, loc, output);
computeEwise(rewriter, loc, module, outputCopy, maskedInput, output,
extBlocks.accumulate, UNION);
rewriter.create<sparse_tensor::ReleaseOp>(loc, outputCopy);
rewriter.create<sparse_tensor::ReleaseOp>(loc, maskedInput);
}
} else {
// input -> output { accumulate, replace? }
// Must think of this as `output << input` so ordering is correct
Value outputCopy = callDupTensor(rewriter, module, loc, output);
computeEwise(rewriter, loc, module, outputCopy, input, output,
extBlocks.accumulate, UNION);
rewriter.create<sparse_tensor::ReleaseOp>(loc, outputCopy);
}
rewriter.eraseOp(op);
return success();
};
};
class LowerEqualRewrite : public OpRewritePattern<graphblas::EqualOp> {
public:
using OpRewritePattern<graphblas::EqualOp>::OpRewritePattern;
LogicalResult matchAndRewrite(graphblas::EqualOp op,
PatternRewriter &rewriter) const override {
Location loc = op->getLoc();
// Inputs
Value A = op.a();
Value B = op.b();
RankedTensorType aType = A.getType().dyn_cast<RankedTensorType>();
// Types
Type boolType = rewriter.getI1Type();
// Need to use a standard word size in AND-reduction for OpenMP
// This could be i8, i32, or i64, but we pick i32
Type intReduceType = rewriter.getIntegerType(32);
Type int64Type = rewriter.getIntegerType(64);
Type valueType = aType.getElementType();
MemRefType memref1DI64Type = MemRefType::get({-1}, int64Type);
MemRefType memref1DValueType = MemRefType::get({-1}, valueType);
// Initial constants
Value c0 = rewriter.create<arith::ConstantIndexOp>(loc, 0);
Value c1 = rewriter.create<arith::ConstantIndexOp>(loc, 1);
Value cfalse = rewriter.create<arith::ConstantIntOp>(loc, 0, boolType);
Value c1_reduce =
rewriter.create<arith::ConstantIntOp>(loc, 1, intReduceType);
unsigned rank = aType.getRank(); // ranks guaranteed to be equal
Value dimIndex;
Value cmpShape;
if (rank == 2) {
// Matrix check
dimIndex = c1;
Value aNrows = rewriter.create<graphblas::NumRowsOp>(loc, A);
Value bNrows = rewriter.create<graphblas::NumRowsOp>(loc, B);
Value aNcols = rewriter.create<graphblas::NumColsOp>(loc, A);
Value bNcols = rewriter.create<graphblas::NumColsOp>(loc, B);
Value cmpNrows = rewriter.create<arith::CmpIOp>(
loc, arith::CmpIPredicate::eq, aNrows, bNrows);
Value cmpNcols = rewriter.create<arith::CmpIOp>(
loc, arith::CmpIPredicate::eq, aNcols, bNcols);
cmpShape = rewriter.create<arith::AndIOp>(loc, cmpNrows, cmpNcols);
} else {
// Vector check
dimIndex = c0;
// Check size
Value aSize = rewriter.create<graphblas::SizeOp>(loc, A);
Value bSize = rewriter.create<graphblas::SizeOp>(loc, B);
cmpShape = rewriter.create<arith::CmpIOp>(loc, arith::CmpIPredicate::eq,
aSize, bSize);
}
scf::IfOp ifOuter =
rewriter.create<scf::IfOp>(loc, boolType, cmpShape, true);
// if cmpSize
rewriter.setInsertionPointToStart(ifOuter.thenBlock());
// Check number of non-zeros
Value aNnz = rewriter.create<graphblas::NumValsOp>(loc, A);
Value bNnz = rewriter.create<graphblas::NumValsOp>(loc, B);
Value cmpNnz = rewriter.create<arith::CmpIOp>(loc, arith::CmpIPredicate::eq,
aNnz, bNnz);
scf::IfOp ifNnz = rewriter.create<scf::IfOp>(loc, boolType, cmpNnz, true);
// if cmpNnz
rewriter.setInsertionPointToStart(ifNnz.thenBlock());
// Check index positions and values
Value Ai = rewriter.create<sparse_tensor::ToIndicesOp>(loc, memref1DI64Type,
A, dimIndex);
Value Bi = rewriter.create<sparse_tensor::ToIndicesOp>(loc, memref1DI64Type,
B, dimIndex);
Value Ax =
rewriter.create<sparse_tensor::ToValuesOp>(loc, memref1DValueType, A);
Value Bx =
rewriter.create<sparse_tensor::ToValuesOp>(loc, memref1DValueType, B);
scf::ParallelOp indexLoop =
rewriter.create<scf::ParallelOp>(loc, c0, aNnz, c1, c1_reduce);
Value loopIdx = indexLoop.getInductionVars().front();
rewriter.setInsertionPointToStart(indexLoop.getBody());
Value aIndex = rewriter.create<memref::LoadOp>(loc, Ai, loopIdx);
Value bIndex = rewriter.create<memref::LoadOp>(loc, Bi, loopIdx);
Value aValue = rewriter.create<memref::LoadOp>(loc, Ax, loopIdx);
Value bValue = rewriter.create<memref::LoadOp>(loc, Bx, loopIdx);
Value cmpIndex = rewriter.create<arith::CmpIOp>(
loc, arith::CmpIPredicate::eq, aIndex, bIndex);
Value cmpValue = llvm::TypeSwitch<Type, Value>(valueType)
.Case<IntegerType>([&](IntegerType type) {
return rewriter.create<arith::CmpIOp>(
loc, arith::CmpIPredicate::eq, aValue, bValue);
})
.Case<FloatType>([&](FloatType type) {
return rewriter.create<arith::CmpFOp>(
loc, arith::CmpFPredicate::OEQ, aValue, bValue);
});
Value cmpCombined = rewriter.create<arith::AndIOp>(loc, cmpIndex, cmpValue);
// Need to do reduction with a standard word size (rather than i1) for
// OpenMP
Value cmpCombined_ext =
rewriter.create<arith::ExtSIOp>(loc, cmpCombined, intReduceType);
scf::ReduceOp reducer =
rewriter.create<scf::ReduceOp>(loc, cmpCombined_ext);
BlockArgument lhs = reducer.getRegion().getArgument(0);
BlockArgument rhs = reducer.getRegion().getArgument(1);
rewriter.setInsertionPointToStart(&reducer.getRegion().front());
Value cmpFinal = rewriter.create<arith::AndIOp>(loc, lhs, rhs);
rewriter.create<scf::ReduceReturnOp>(loc, cmpFinal);
rewriter.setInsertionPointAfter(indexLoop);
Value boolResult =
rewriter.create<arith::TruncIOp>(loc, indexLoop.getResult(0), boolType);
rewriter.create<scf::YieldOp>(loc, boolResult);
// else cmpNnz
rewriter.setInsertionPointToStart(ifNnz.elseBlock());
rewriter.create<scf::YieldOp>(loc, cfalse);
// end cmpNnz
rewriter.setInsertionPointAfter(ifNnz);
Value nnzReturn = ifNnz.getResult(0);
rewriter.create<scf::YieldOp>(loc, nnzReturn);
// else cmpSize
rewriter.setInsertionPointToStart(ifOuter.elseBlock());
rewriter.create<scf::YieldOp>(loc, cfalse);
// end cmpSize
rewriter.setInsertionPointAfter(ifOuter);
Value isEqual = ifOuter.getResult(0);
rewriter.replaceOp(op, isEqual);
return success();
};
};
class LowerSelectMaskRewrite
: public OpRewritePattern<graphblas::SelectMaskOp> {
public:
using OpRewritePattern<graphblas::SelectMaskOp>::OpRewritePattern;
LogicalResult matchAndRewrite(graphblas::SelectMaskOp op,
PatternRewriter &rewriter) const override {
ModuleOp module = op->getParentOfType<ModuleOp>();
Location loc = op->getLoc();
// Inputs
Value input = op.input();
Value mask = op.mask();
bool maskComplement = op.mask_complement();
RankedTensorType inputTensorType =
input.getType().dyn_cast<RankedTensorType>();
Value output = callEmptyLike(rewriter, module, loc, input);
EwiseBehavior maskBehavior = (maskComplement ? MASK_COMPLEMENT : MASK);
unsigned rank = inputTensorType.getRank();
if (rank == 2) {
computeMatrixElementWise(rewriter, loc, module, input, mask, output,
nullptr, maskBehavior);
} else {
computeVectorElementWise(rewriter, loc, module, input, mask, output,
nullptr, maskBehavior);
}
rewriter.replaceOp(op, output);
cleanupIntermediateTensor(rewriter, module, loc, output);
return success();
};
};
class LowerUniformComplementRewrite
: public OpRewritePattern<graphblas::UniformComplementOp> {
public:
using OpRewritePattern<graphblas::UniformComplementOp>::OpRewritePattern;
LogicalResult matchAndRewrite(graphblas::UniformComplementOp op,
PatternRewriter &rewriter) const override {
ModuleOp module = op->getParentOfType<ModuleOp>();
Location loc = op->getLoc();
// Inputs
Value input = op.input();
Value value = op.value();
RankedTensorType inputTensorType =
input.getType().dyn_cast<RankedTensorType>();
RankedTensorType outputTensorType =
op.getResult().getType().dyn_cast<RankedTensorType>();
Type outputElementType = outputTensorType.getElementType();
Type indexType = rewriter.getIndexType();
Type i64Type = rewriter.getI64Type();
Type memrefPointerType = getMemrefPointerType(inputTensorType);
Type memrefIndexType = getMemrefIndexType(inputTensorType);
Type memrefOValueType = getMemrefValueType(outputTensorType);
unsigned rank = inputTensorType.getRank();
// Initial constants
Value c0 = rewriter.create<arith::ConstantIndexOp>(loc, 0);
Value c1 = rewriter.create<arith::ConstantIndexOp>(loc, 1);
Value output =
callEmptyLike(rewriter, module, loc, input, outputElementType);
// Resize output (max size - nnz)
Value size, npointers, compSize, dimIndex;
if (rank == 1) {
npointers = c1;
size = rewriter.create<graphblas::SizeOp>(loc, input);
compSize = size;
dimIndex = c0;
} else {
Value nrows = rewriter.create<graphblas::NumRowsOp>(loc, input);
Value ncols = rewriter.create<graphblas::NumColsOp>(loc, input);
size = rewriter.create<arith::MulIOp>(loc, nrows, ncols);
dimIndex = c1;
if (hasRowOrdering(inputTensorType)) {
npointers = nrows;
compSize = ncols;
} else {
npointers = ncols;
compSize = nrows;
}
}
Value nnz = rewriter.create<graphblas::NumValsOp>(loc, input);
Value newSize = rewriter.create<arith::SubIOp>(loc, size, nnz);
callResizeIndex(rewriter, module, loc, output, dimIndex, newSize);
callResizeValues(rewriter, module, loc, output, newSize);
// Get sparse tensor info
Value Ip = rewriter.create<sparse_tensor::ToPointersOp>(
loc, memrefPointerType, input, dimIndex);
Value Ii = rewriter.create<sparse_tensor::ToIndicesOp>(loc, memrefIndexType,
input, dimIndex);
Value Op = rewriter.create<sparse_tensor::ToPointersOp>(
loc, memrefPointerType, output, dimIndex);
Value Oi = rewriter.create<sparse_tensor::ToIndicesOp>(loc, memrefIndexType,
output, dimIndex);
Value Ox = rewriter.create<sparse_tensor::ToValuesOp>(loc, memrefOValueType,
output);
scf::ForOp loop =
rewriter.create<scf::ForOp>(loc, c0, npointers, c1, ValueRange{c0});
{
rewriter.setInsertionPointToStart(loop.getBody());
Value rowCount = loop.getLoopBody().getArgument(1);
Value rowIndex = loop.getInductionVar();
Value row_plus1 = rewriter.create<arith::AddIOp>(loc, rowIndex, c1);
Value idxStart_64 = rewriter.create<memref::LoadOp>(loc, Ip, rowIndex);
Value idxEnd_64 = rewriter.create<memref::LoadOp>(loc, Ip, row_plus1);
Value idxStart =
rewriter.create<arith::IndexCastOp>(loc, idxStart_64, indexType);
Value idxEnd =
rewriter.create<arith::IndexCastOp>(loc, idxEnd_64, indexType);
ValueRange mcResults =
buildMaskComplement(rewriter, loc, compSize, Ii, idxStart, idxEnd);
Value maskComplement = mcResults[0];
Value maskComplementSize = mcResults[1];
Value newCount =
rewriter.create<arith::AddIOp>(loc, rowCount, maskComplementSize);
Value newCount_64 =
rewriter.create<arith::IndexCastOp>(loc, newCount, i64Type);
rewriter.create<memref::StoreOp>(loc, newCount_64, Op, row_plus1);
scf::ForOp innerLoop =
rewriter.create<scf::ForOp>(loc, c0, maskComplementSize, c1);
{
rewriter.setInsertionPointToStart(innerLoop.getBody());
Value mcIndex = innerLoop.getInductionVar();
Value colIndex = rewriter.create<arith::AddIOp>(loc, mcIndex, rowCount);
Value innerIdx =
rewriter.create<memref::LoadOp>(loc, maskComplement, mcIndex);
rewriter.create<memref::StoreOp>(loc, innerIdx, Oi, colIndex);
rewriter.create<memref::StoreOp>(loc, value, Ox, colIndex);
rewriter.setInsertionPointAfter(innerLoop);
}
rewriter.create<scf::YieldOp>(loc, ValueRange{newCount});
rewriter.setInsertionPointAfter(loop);
}
rewriter.replaceOp(op, output);
return success();
};
};
class LowerDiagOpRewrite : public OpRewritePattern<graphblas::DiagOp> {
public:
using OpRewritePattern<graphblas::DiagOp>::OpRewritePattern;
LogicalResult matchAndRewrite(graphblas::DiagOp op,
PatternRewriter &rewriter) const override {
RankedTensorType resultTensorType =
op.getResult().getType().dyn_cast<RankedTensorType>();
if (resultTensorType.getRank() == 1) {
return lowerMatrixToVecDiagOp(op, rewriter, resultTensorType);
} else if (resultTensorType.getRank() == 2) {
return lowerVecToMatrixDiagOp(op, rewriter, resultTensorType);
}
return failure();
};
private:
LogicalResult
lowerVecToMatrixDiagOp(graphblas::DiagOp op, PatternRewriter &rewriter,
RankedTensorType &resultTensorType) const {
ModuleOp module = op->getParentOfType<ModuleOp>();
Location loc = op->getLoc();
Value vector = op.input();
Type valueType = resultTensorType.getElementType();
Type indexType = rewriter.getIndexType();
Type int64Type = rewriter.getIntegerType(64);
Type memref1DI64Type = MemRefType::get({-1}, int64Type);
Type memref1DValueType = MemRefType::get({-1}, valueType);
Value c0_i64 =
rewriter.create<ConstantOp>(loc, rewriter.getIntegerAttr(int64Type, 0));
Value c1_i64 =
rewriter.create<ConstantOp>(loc, rewriter.getIntegerAttr(int64Type, 1));
Value c0 = rewriter.create<arith::ConstantIndexOp>(loc, 0);
Value c1 = rewriter.create<arith::ConstantIndexOp>(loc, 1);
Value vectorLength = rewriter.create<graphblas::SizeOp>(loc, vector);
Value vectorIndices = rewriter.create<sparse_tensor::ToIndicesOp>(
loc, memref1DI64Type, vector, c0);
Value vectorValues = rewriter.create<sparse_tensor::ToValuesOp>(
loc, memref1DValueType, vector);
Value output = callNewTensor(
rewriter, module, loc, {vectorLength, vectorLength}, resultTensorType);
Value outputNNZ = rewriter.create<graphblas::NumValsOp>(loc, vector);
Value hasValues = rewriter.create<arith::CmpIOp>(
loc, arith::CmpIPredicate::ugt, outputNNZ, c0);
scf::IfOp ifHasValues = rewriter.create<scf::IfOp>(loc, hasValues, false);
{
rewriter.setInsertionPointToStart(ifHasValues.thenBlock());
callResizeIndex(rewriter, module, loc, output, c1, outputNNZ);
callResizeValues(rewriter, module, loc, output, outputNNZ);
Value outputIndices = rewriter.create<sparse_tensor::ToIndicesOp>(
loc, memref1DI64Type, output, c1);
Value outputValues = rewriter.create<sparse_tensor::ToValuesOp>(
loc, memref1DValueType, output);
scf::ForOp copyValuesAndIndicesLoop =
rewriter.create<scf::ForOp>(loc, c0, outputNNZ, c1);
{
rewriter.setInsertionPointToStart(copyValuesAndIndicesLoop.getBody());
Value outputPosition = copyValuesAndIndicesLoop.getInductionVar();
Value vectorIndex =
rewriter.create<memref::LoadOp>(loc, vectorIndices, outputPosition);
rewriter.create<memref::StoreOp>(loc, vectorIndex, outputIndices,
outputPosition);
Value vectorValue =
rewriter.create<memref::LoadOp>(loc, vectorValues, outputPosition);
rewriter.create<memref::StoreOp>(loc, vectorValue, outputValues,
outputPosition);
rewriter.setInsertionPointAfter(copyValuesAndIndicesLoop);
}
Value outputPointers = rewriter.create<sparse_tensor::ToPointersOp>(
loc, memref1DI64Type, output, c1);
Value initialVectorIndicesValue =
rewriter.create<memref::LoadOp>(loc, vectorIndices, c0);
Value vectorLengthMinusOne =
rewriter.create<arith::SubIOp>(loc, vectorLength, c1);
scf::ForOp pointersUpdateLoop = rewriter.create<scf::ForOp>(
loc, c0, vectorLength, c1,
ValueRange{c0_i64, c0, initialVectorIndicesValue});
{
rewriter.setInsertionPointToStart(pointersUpdateLoop.getBody());
Value pointersPosition = pointersUpdateLoop.getInductionVar();
Value ptr_i64 = pointersUpdateLoop.getLoopBody().getArgument(1);
Value vectorIndicesPosition =
pointersUpdateLoop.getLoopBody().getArgument(2);
Value vectorIndicesValue =
pointersUpdateLoop.getLoopBody().getArgument(3);
rewriter.create<memref::StoreOp>(loc, ptr_i64, outputPointers,
pointersPosition);
Value pointersPosition_i64 = rewriter.create<arith::IndexCastOp>(
loc, pointersPosition, int64Type);
Value rowHasValue = rewriter.create<arith::CmpIOp>(
op.getLoc(), arith::CmpIPredicate::eq, vectorIndicesValue,
pointersPosition_i64);
Value notAtLastIteration = rewriter.create<arith::CmpIOp>(
op.getLoc(), arith::CmpIPredicate::ne, pointersPosition,
vectorLengthMinusOne);
Value mustUpdate = rewriter.create<arith::AndIOp>(
loc, notAtLastIteration, rowHasValue);
scf::IfOp ifMustUpdateBlock = rewriter.create<scf::IfOp>(
loc, TypeRange{int64Type, indexType, int64Type}, mustUpdate, true);
{
rewriter.setInsertionPointToStart(ifMustUpdateBlock.thenBlock());
Value nextPtr_i64 =
rewriter.create<arith::AddIOp>(loc, ptr_i64, c1_i64);
Value nextVectorIndicesPosition =
rewriter.create<arith::AddIOp>(loc, vectorIndicesPosition, c1);
Value nextUpdatedVectorIndicesValue = rewriter.create<memref::LoadOp>(
loc, vectorIndices, nextVectorIndicesPosition);
rewriter.create<scf::YieldOp>(
loc, ValueRange{nextPtr_i64, nextVectorIndicesPosition,
nextUpdatedVectorIndicesValue});
}
{
rewriter.setInsertionPointToStart(ifMustUpdateBlock.elseBlock());
rewriter.create<scf::YieldOp>(
loc,
ValueRange{ptr_i64, vectorIndicesPosition, vectorIndicesValue});
}
rewriter.setInsertionPointAfter(ifMustUpdateBlock);
Value updatedPtr_i64 = ifMustUpdateBlock.getResult(0);
Value updatedVectorIndicesPosition = ifMustUpdateBlock.getResult(1);
Value updatedVectorIndicesValue = ifMustUpdateBlock.getResult(2);
rewriter.create<scf::YieldOp>(
loc, ValueRange{updatedPtr_i64, updatedVectorIndicesPosition,
updatedVectorIndicesValue});
rewriter.setInsertionPointAfter(pointersUpdateLoop);
}
Value outputNNZ_i64 =
rewriter.create<arith::IndexCastOp>(loc, outputNNZ, int64Type);
rewriter.create<memref::StoreOp>(loc, outputNNZ_i64, outputPointers,
vectorLength);
rewriter.setInsertionPointAfter(ifHasValues);
}
rewriter.replaceOp(op, output);
cleanupIntermediateTensor(rewriter, module, loc, output);
return success();
}
LogicalResult
lowerMatrixToVecDiagOp(graphblas::DiagOp op, PatternRewriter &rewriter,
RankedTensorType &resultTensorType) const {
// This implementation reads as assuming the input matrix is CSR,
// but it will work for CSC as well.
ModuleOp module = op->getParentOfType<ModuleOp>();
Location loc = op->getLoc();
Value matrix = op.input();
Type valueType = resultTensorType.getElementType();
Type indexType = rewriter.getIndexType();
Type int64Type = rewriter.getIntegerType(64);
Type int1Type = rewriter.getIntegerType(1);
Type memref1DI64Type = MemRefType::get({-1}, int64Type);
Type memref1DValueType = MemRefType::get({-1}, valueType);
Value c1_i1 =
rewriter.create<ConstantOp>(loc, rewriter.getIntegerAttr(int1Type, 1));
Value c0_valueType = llvm::TypeSwitch<Type, Value>(valueType)
.Case<IntegerType>([&](IntegerType type) {
return rewriter.create<ConstantOp>(
loc, rewriter.getIntegerAttr(valueType, 1));
})
.Case<FloatType>([&](FloatType type) {
return rewriter.create<ConstantOp>(
loc, rewriter.getFloatAttr(valueType, 1.0));
});
Value c0 = rewriter.create<arith::ConstantIndexOp>(loc, 0);
Value c1 = rewriter.create<arith::ConstantIndexOp>(loc, 1);
Value nrows = rewriter.create<graphblas::NumRowsOp>(loc, matrix);
Value matrixPointers = rewriter.create<sparse_tensor::ToPointersOp>(
loc, memref1DI64Type, matrix, c1);
Value matrixIndices = rewriter.create<sparse_tensor::ToIndicesOp>(
loc, memref1DI64Type, matrix, c1);
Value matrixValues = rewriter.create<sparse_tensor::ToValuesOp>(
loc, memref1DValueType, matrix);
Value output = callNewTensor(rewriter, module, loc, ValueRange{nrows},
resultTensorType);
// We do two loops, one to find the output vector's nnz
// and one to fill up the output's indices and values.
// We have to get the nnz first to allocate space in the
// output vector correctly.
// TODO We could do one loop where we do both.
// 1) assume that the output nnz is some arbitrary size
// 2) resize accordingly
// 3) on each iteration,
// - store the values and indices
// - track the correct nnz
// - if we reach the limit of whatever size the
// output vector is, resize (double it or
// something like that)
// 4) resize the output vector to the correct nnz
// It's unclear which approach is more performant since
// it depends on how accurate our arbitrary guesses are
// for initial size and how much we should resize.
scf::ForOp outputNNZLoop =
rewriter.create<scf::ForOp>(loc, c0, nrows, c1, ValueRange{c0});
{
Value numDiagonalContainingRows =
outputNNZLoop.getLoopBody().getArgument(1);
rewriter.setInsertionPointToStart(outputNNZLoop.getBody());
Value matrixRowIndex = outputNNZLoop.getInductionVar();
Value nextMatrixRowIndex =
rewriter.create<arith::AddIOp>(loc, matrixRowIndex, c1);
Value firstPtr_i64 =
rewriter.create<memref::LoadOp>(loc, matrixPointers, matrixRowIndex);
Value secondPtr_i64 = rewriter.create<memref::LoadOp>(loc, matrixPointers,
nextMatrixRowIndex);
Value firstPtr =
rewriter.create<arith::IndexCastOp>(loc, firstPtr_i64, indexType);
Value secondPtr =
rewriter.create<arith::IndexCastOp>(loc, secondPtr_i64, indexType);
Value matrixRowIndex_i64 =
rewriter.create<arith::IndexCastOp>(loc, matrixRowIndex, int64Type);
scf::WhileOp findDiagonalWhileLoop = rewriter.create<scf::WhileOp>(
loc, TypeRange{indexType, int1Type}, ValueRange{firstPtr, c1_i1});
Block *findDiagonalWhileLoopBefore =
rewriter.createBlock(&findDiagonalWhileLoop.getBefore(), {},
TypeRange{indexType, int1Type});
Block *findDiagonalWhileLoopAfter =
rewriter.createBlock(&findDiagonalWhileLoop.getAfter(), {},
TypeRange{indexType, int1Type});
Value diagonalNotFound = findDiagonalWhileLoop.getResult(1);
{
rewriter.setInsertionPointToStart(
&findDiagonalWhileLoop.getBefore().front());
Value ptr = findDiagonalWhileLoopBefore->getArgument(0);
Value diagonalPositionNotFound =
findDiagonalWhileLoopBefore->getArgument(1);
Value morePtrs = rewriter.create<arith::CmpIOp>(
op.getLoc(), arith::CmpIPredicate::ult, ptr, secondPtr);
Value continueCondition = rewriter.create<arith::AndIOp>(
loc, diagonalPositionNotFound, morePtrs);
rewriter.create<scf::ConditionOp>(
loc, continueCondition, ValueRange{ptr, diagonalPositionNotFound});
}
{
rewriter.setInsertionPointToStart(
&findDiagonalWhileLoop.getAfter().front());
Value currentPtr = findDiagonalWhileLoopAfter->getArgument(0);
Value elementColumnIndex_i64 =
rewriter.create<memref::LoadOp>(loc, matrixIndices, currentPtr);
Value isNotDiagonalPosition = rewriter.create<arith::CmpIOp>(
op.getLoc(), arith::CmpIPredicate::ne, elementColumnIndex_i64,
matrixRowIndex_i64);
Value nextPtr = rewriter.create<arith::AddIOp>(loc, currentPtr, c1);
rewriter.create<scf::YieldOp>(
loc, ValueRange{nextPtr, isNotDiagonalPosition});
rewriter.setInsertionPointAfter(findDiagonalWhileLoop);
}
scf::IfOp ifDiagonalNotFoundBlock = rewriter.create<scf::IfOp>(
loc, TypeRange{indexType}, diagonalNotFound, true);
{
rewriter.setInsertionPointToStart(ifDiagonalNotFoundBlock.thenBlock());
rewriter.create<scf::YieldOp>(loc,
ValueRange{numDiagonalContainingRows});
}
{
rewriter.setInsertionPointToStart(ifDiagonalNotFoundBlock.elseBlock());
Value nextNumDiagonalContainingRows =
rewriter.create<arith::AddIOp>(loc, numDiagonalContainingRows, c1);
rewriter.create<scf::YieldOp>(
loc, ValueRange{nextNumDiagonalContainingRows});
}
rewriter.setInsertionPointAfter(ifDiagonalNotFoundBlock);
Value updatedNumDiagonalContainingRows =
ifDiagonalNotFoundBlock.getResult(0);
rewriter.create<scf::YieldOp>(
loc, ValueRange{updatedNumDiagonalContainingRows});
rewriter.setInsertionPointAfter(outputNNZLoop);
}
Value outputNNZ = outputNNZLoop.getResult(0);
callResizeIndex(rewriter, module, loc, output, c0, outputNNZ);
callResizeValues(rewriter, module, loc, output, outputNNZ);
Value outputPointers = rewriter.create<sparse_tensor::ToPointersOp>(
loc, memref1DI64Type, output, c0);
Value outputNNZ_i64 =
rewriter.create<arith::IndexCastOp>(loc, outputNNZ, int64Type);
rewriter.create<memref::StoreOp>(loc, outputNNZ_i64, outputPointers, c1);
Value outputIndices = rewriter.create<sparse_tensor::ToIndicesOp>(
loc, memref1DI64Type, output, c0);
Value outputValues = rewriter.create<sparse_tensor::ToValuesOp>(
loc, memref1DValueType, output);
scf::ForOp outputValueAndIndicesFillingLoop =
rewriter.create<scf::ForOp>(loc, c0, nrows, c1, ValueRange{c0});
{
Value outputValuesPosition =
outputValueAndIndicesFillingLoop.getLoopBody().getArgument(1);
Value rowIndex = outputValueAndIndicesFillingLoop.getInductionVar();
rewriter.setInsertionPointToStart(
outputValueAndIndicesFillingLoop.getBody());
Value nextRowIndex = rewriter.create<arith::AddIOp>(loc, rowIndex, c1);
Value firstPtr_i64 =
rewriter.create<memref::LoadOp>(loc, matrixPointers, rowIndex);
Value secondPtr_i64 =
rewriter.create<memref::LoadOp>(loc, matrixPointers, nextRowIndex);
Value firstPtr =
rewriter.create<arith::IndexCastOp>(loc, firstPtr_i64, indexType);
Value secondPtr =
rewriter.create<arith::IndexCastOp>(loc, secondPtr_i64, indexType);
Value rowIndex_i64 =
rewriter.create<arith::IndexCastOp>(loc, rowIndex, int64Type);
// instead of having a var for whether or not a diagonal value was found
// and the value itself, we could just track whether or not the diagonal
// value (see the C++ variable diagonalValue) is zero (or whatever the
// missing value represents).
// This will cause bugs with malformed sparse tensors that have the
// missing value in the values array.
// c0_valueType is just used as a dummmy initial value here ; any garbage
// value would work
scf::WhileOp findDiagonalWhileLoop = rewriter.create<scf::WhileOp>(
loc, TypeRange{indexType, int1Type, valueType},
ValueRange{firstPtr, c1_i1, c0_valueType});
Block *findDiagonalWhileLoopBefore =
rewriter.createBlock(&findDiagonalWhileLoop.getBefore(), {},
TypeRange{indexType, int1Type, valueType});
Block *findDiagonalWhileLoopAfter =
rewriter.createBlock(&findDiagonalWhileLoop.getAfter(), {},
TypeRange{indexType, int1Type, valueType});
Value diagonalNotFound = findDiagonalWhileLoop.getResult(1);
Value diagonalValue = findDiagonalWhileLoop.getResult(2);
{
Value ptr = findDiagonalWhileLoopBefore->getArgument(0);
Value diagonalPositionNotFound =
findDiagonalWhileLoopBefore->getArgument(1);
Value currentDiagonalValue =
findDiagonalWhileLoopBefore->getArgument(2);
rewriter.setInsertionPointToStart(
&findDiagonalWhileLoop.getBefore().front());
Value morePtrs = rewriter.create<arith::CmpIOp>(
op.getLoc(), arith::CmpIPredicate::ult, ptr, secondPtr);
Value continueCondition = rewriter.create<arith::AndIOp>(
loc, diagonalPositionNotFound, morePtrs);
rewriter.create<scf::ConditionOp>(
loc, continueCondition,
ValueRange{ptr, diagonalPositionNotFound, currentDiagonalValue});
}
{
rewriter.setInsertionPointToStart(
&findDiagonalWhileLoop.getAfter().front());
Value currentPtr = findDiagonalWhileLoopAfter->getArgument(0);
Value previousDiagonalValue =
findDiagonalWhileLoopAfter->getArgument(2);
Value elementColumnIndex_i64 =
rewriter.create<memref::LoadOp>(loc, matrixIndices, currentPtr);
Value isNotDiagonalPosition = rewriter.create<arith::CmpIOp>(
op.getLoc(), arith::CmpIPredicate::ne, elementColumnIndex_i64,
rowIndex_i64);
scf::IfOp ifDiagonalNotFoundBlock = rewriter.create<scf::IfOp>(
loc, TypeRange{valueType}, isNotDiagonalPosition, true);
{
rewriter.setInsertionPointToStart(
ifDiagonalNotFoundBlock.thenBlock());
// TODO yielding a dummy value (e.g. c0_valueType) works as well ;
// unsure which creates more optimal code
rewriter.create<scf::YieldOp>(loc, ValueRange{previousDiagonalValue});
}
{
rewriter.setInsertionPointToStart(
ifDiagonalNotFoundBlock.elseBlock());
Value actualDiagonalValue =
rewriter.create<memref::LoadOp>(loc, matrixValues, currentPtr);
rewriter.create<scf::YieldOp>(loc, ValueRange{actualDiagonalValue});
}
rewriter.setInsertionPointAfter(ifDiagonalNotFoundBlock);
Value updatedDiagonalValue = ifDiagonalNotFoundBlock.getResult(0);
Value nextPtr = rewriter.create<arith::AddIOp>(loc, currentPtr, c1);
rewriter.create<scf::YieldOp>(
loc,
ValueRange{nextPtr, isNotDiagonalPosition, updatedDiagonalValue});
rewriter.setInsertionPointAfter(findDiagonalWhileLoop);
}
scf::IfOp ifDiagonalNotFoundBlock = rewriter.create<scf::IfOp>(
loc, TypeRange{indexType}, diagonalNotFound, true);
{
rewriter.setInsertionPointToStart(ifDiagonalNotFoundBlock.thenBlock());
rewriter.create<scf::YieldOp>(loc, ValueRange{outputValuesPosition});
}
{
rewriter.setInsertionPointToStart(ifDiagonalNotFoundBlock.elseBlock());
rewriter.create<memref::StoreOp>(loc, diagonalValue, outputValues,
outputValuesPosition);
rewriter.create<memref::StoreOp>(loc, rowIndex_i64, outputIndices,
outputValuesPosition);
Value nextOutputValuesPosition =
rewriter.create<arith::AddIOp>(loc, outputValuesPosition, c1);
rewriter.create<scf::YieldOp>(loc,
ValueRange{nextOutputValuesPosition});
}
rewriter.setInsertionPointAfter(ifDiagonalNotFoundBlock);
Value nextOutputValuesPosition = ifDiagonalNotFoundBlock.getResult(0);
rewriter.create<scf::YieldOp>(loc, ValueRange{nextOutputValuesPosition});
rewriter.setInsertionPointAfter(outputValueAndIndicesFillingLoop);
}
rewriter.replaceOp(op, output);
return success();
}
};
class LowerCommentRewrite : public OpRewritePattern<graphblas::CommentOp> {
public:
using OpRewritePattern<graphblas::CommentOp>::OpRewritePattern;
LogicalResult matchAndRewrite(graphblas::CommentOp op,
PatternRewriter &rewriter) const override {
rewriter.eraseOp(op);
return success();
};
};
class LowerPrintRewrite : public OpRewritePattern<graphblas::PrintOp> {
public:
using OpRewritePattern<graphblas::PrintOp>::OpRewritePattern;
LogicalResult matchAndRewrite(graphblas::PrintOp op,
PatternRewriter &rewriter) const override {
ModuleOp module = op->getParentOfType<ModuleOp>();
Location loc = op->getLoc();
for (auto enumerated_pair :
llvm::enumerate(llvm::zip_longest(op.strings(), op.values()))) {
auto pair = enumerated_pair.value();
Optional<Attribute> stringAttribute = std::get<0>(pair);
Optional<Value> val = std::get<1>(pair);
if (stringAttribute) {
StringRef currentString =
stringAttribute.getValue().dyn_cast<StringAttr>().getValue();
callPrintString(rewriter, module, loc, currentString);
} else if (enumerated_pair.index() != 0)
callPrintString(rewriter, module, loc, " ");
if (!val)
callPrintString(rewriter, module, loc, " ");
else if (val.getValue().getType().dyn_cast_or_null<RankedTensorType>())
callPrintTensor(rewriter, module, loc, val.getValue());
else
callPrintValue(rewriter, module, loc, val.getValue());
}
callPrintString(rewriter, module, loc, "\n");
rewriter.eraseOp(op);
return success();
};
};
class LowerPrintTensorRewrite
: public OpRewritePattern<graphblas::PrintTensorOp> {
public:
using OpRewritePattern<graphblas::PrintTensorOp>::OpRewritePattern;
LogicalResult matchAndRewrite(graphblas::PrintTensorOp op,
PatternRewriter &rewriter) const override {
ModuleOp module = op->getParentOfType<ModuleOp>();
Location loc = op->getLoc();
Value input = op.input();
int64_t level = op.level();
callPrintTensorComponents(rewriter, module, loc, input, level);
rewriter.eraseOp(op);
return success();
};
};
class LowerMatrixSelectRandomRewrite
: public OpRewritePattern<graphblas::MatrixSelectRandomOp> {
public:
using OpRewritePattern<graphblas::MatrixSelectRandomOp>::OpRewritePattern;
LogicalResult matchAndRewrite(graphblas::MatrixSelectRandomOp op,
PatternRewriter &rewriter) const override {
Location loc = op->getLoc();
ModuleOp module = op->getParentOfType<ModuleOp>();
Value input = op.input();
Value n = op.n();
Value rngContext = op.rng_context();
SymbolRefAttr chooseNSymbol = op.choose_n();
Type valueType = input.getType().dyn_cast<TensorType>().getElementType();
Type int64Type = rewriter.getIntegerType(64);
Type indexType = rewriter.getIndexType();
Type memref1DI64Type = MemRefType::get({-1}, int64Type);
Type memref1DValueType = MemRefType::get({-1}, valueType);
// Initial constants
Value c0 = rewriter.create<arith::ConstantIndexOp>(loc, 0);
Value c0_64 = rewriter.create<arith::ConstantIntOp>(loc, 0, int64Type);
Value c1 = rewriter.create<arith::ConstantIndexOp>(loc, 1);
// Get sparse tensor info
Value nrow = rewriter.create<graphblas::NumRowsOp>(loc, input);
Value Ap = rewriter.create<sparse_tensor::ToPointersOp>(
loc, memref1DI64Type, input, c1);
Value Aj = rewriter.create<sparse_tensor::ToIndicesOp>(loc, memref1DI64Type,
input, c1);
Value Ax = rewriter.create<sparse_tensor::ToValuesOp>(
loc, memref1DValueType, input);
// Create output tensor
Value output = rewriter.create<graphblas::DupOp>(loc, input);
Value Bp = rewriter.create<sparse_tensor::ToPointersOp>(
loc, memref1DI64Type, output, c1);
Value Bj = rewriter.create<sparse_tensor::ToIndicesOp>(loc, memref1DI64Type,
output, c1);
Value Bx = rewriter.create<sparse_tensor::ToValuesOp>(
loc, memref1DValueType, output);
rewriter.create<memref::StoreOp>(loc, c0_64, Bp, c0);
// Pass 1: Scan input tensor to compute offsets
scf::ForOp scanLoop = rewriter.create<scf::ForOp>(loc, c0, nrow, c1);
Value row = scanLoop.getInductionVar();
rewriter.setInsertionPointToStart(scanLoop.getBody());
Value row_plus1 = rewriter.create<arith::AddIOp>(loc, row, c1);
Value Aj_start_64 = rewriter.create<memref::LoadOp>(loc, Ap, row);
Value Aj_end_64 = rewriter.create<memref::LoadOp>(loc, Ap, row_plus1);
// Limit number of row values in output to n
Value Aj_size_64 =
rewriter.create<arith::SubIOp>(loc, Aj_end_64, Aj_start_64);
Value isRowSmall = rewriter.create<arith::CmpIOp>(
loc, arith::CmpIPredicate::ule, Aj_size_64, n);
Value Bj_size_64 =
rewriter.create<SelectOp>(loc, isRowSmall, Aj_size_64, n);
Value Bj_start_64 = rewriter.create<memref::LoadOp>(loc, Bp, row);
Value Bj_end_64 =
rewriter.create<arith::AddIOp>(loc, Bj_start_64, Bj_size_64);
rewriter.create<memref::StoreOp>(loc, Bj_end_64, Bp, row_plus1);
rewriter.setInsertionPointAfter(scanLoop);
// Pass 2: Parallel select and compute output
scf::ParallelOp rowLoop =
rewriter.create<scf::ParallelOp>(loc, c0, nrow, c1);
row = rowLoop.getInductionVars()[0];
rewriter.setInsertionPointToStart(rowLoop.getBody());
row_plus1 = rewriter.create<arith::AddIOp>(loc, row, c1);
Aj_start_64 = rewriter.create<memref::LoadOp>(loc, Ap, row);
Value Aj_start =
rewriter.create<arith::IndexCastOp>(loc, Aj_start_64, indexType);
Aj_end_64 = rewriter.create<memref::LoadOp>(loc, Ap, row_plus1);
Value Aj_end =
rewriter.create<arith::IndexCastOp>(loc, Aj_end_64, indexType);
Bj_start_64 = rewriter.create<memref::LoadOp>(loc, Bp, row);
Value Bj_start =
rewriter.create<arith::IndexCastOp>(loc, Bj_start_64, indexType);
Bj_end_64 = rewriter.create<memref::LoadOp>(loc, Bp, row_plus1);
Value Bj_end =
rewriter.create<arith::IndexCastOp>(loc, Bj_end_64, indexType);
Value Aj_size = rewriter.create<arith::SubIOp>(loc, Aj_end, Aj_start);
Aj_size_64 = rewriter.create<arith::IndexCastOp>(loc, Aj_size, int64Type);
Value Bj_size = rewriter.create<arith::SubIOp>(loc, Bj_end, Bj_start);
Bj_size_64 = rewriter.create<arith::IndexCastOp>(loc, Bj_size, int64Type);
Value copyRow = rewriter.create<arith::CmpIOp>(
loc, arith::CmpIPredicate::eq, Aj_size, Bj_size);
// Create output subviews
Value Bj_view =
rewriter.create<memref::SubViewOp>(loc, Bj, Bj_start, Bj_size, c1);
Value Bx_view =
rewriter.create<memref::SubViewOp>(loc, Bx, Bj_start, Bj_size, c1);
Value Aj_view =
rewriter.create<memref::SubViewOp>(loc, Aj, Aj_start, Aj_size, c1);
Value Ax_view =
rewriter.create<memref::SubViewOp>(loc, Ax, Aj_start, Aj_size, c1);
// If number of row values less than or equal to n, copy row directly
scf::IfOp ifCopy = rewriter.create<scf::IfOp>(loc, copyRow, true);
rewriter.setInsertionPointToStart(ifCopy.thenBlock());
// copy contents
rewriter.create<memref::CopyOp>(loc, Aj_view, Bj_view);
rewriter.create<memref::CopyOp>(loc, Ax_view, Bx_view);
// Else, fill output row with random selection from input row
rewriter.setInsertionPointToStart(ifCopy.elseBlock());
// These are unused. Should they be removed?
// MLIRContext *context = module.getContext();
// FuncOp chooseFunc = module.lookupSymbol<FuncOp>(chooseNSymbol);
// TODO: Verify signature of this function is what we expect
// Call function using output Bj row as temporary storage
rewriter.create<mlir::CallOp>(
loc, chooseNSymbol, TypeRange(),
ArrayRef<Value>(
{rngContext, Bj_size_64, Aj_size_64, Bj_view, Ax_view}));
// Loop over randomly selected offsets
scf::ParallelOp colLoop =
rewriter.create<scf::ParallelOp>(loc, c0, Bj_size, c1);
Value offset = colLoop.getInductionVars()[0];
rewriter.setInsertionPointToStart(colLoop.getBody());
Value sourceOffset_64 =
rewriter.create<memref::LoadOp>(loc, Bj_view, offset);
Value sourceOffset =
rewriter.create<arith::IndexCastOp>(loc, sourceOffset_64, indexType);
Value colIndex =
rewriter.create<memref::LoadOp>(loc, Aj_view, sourceOffset);
Value colValue =
rewriter.create<memref::LoadOp>(loc, Ax_view, sourceOffset);
// overwrite the randomly selected offset with the actual column index
rewriter.create<memref::StoreOp>(loc, colIndex, Bj_view, offset);
// write the corresponding value from source matrix
rewriter.create<memref::StoreOp>(loc, colValue, Bx_view, offset);
// end loop over columns
// end loop over rows
// Output array is populated
rewriter.setInsertionPointAfter(rowLoop);
// Resize output index and values to match total number of elements
Value outputNNZ_64 = rewriter.create<memref::LoadOp>(loc, Bp, nrow);
Value outputNNZ =
rewriter.create<arith::IndexCastOp>(loc, outputNNZ_64, indexType);
callResizeIndex(rewriter, module, loc, output, c1, outputNNZ);
callResizeValues(rewriter, module, loc, output, outputNNZ);
rewriter.replaceOp(op, output);
return success();
};
};
class LowerFromCoordinatesRewrite
: public OpRewritePattern<graphblas::FromCoordinatesOp> {
public:
using OpRewritePattern<graphblas::FromCoordinatesOp>::OpRewritePattern;
LogicalResult matchAndRewrite(graphblas::FromCoordinatesOp op,
PatternRewriter &rewriter) const override {
ModuleOp module = op->getParentOfType<ModuleOp>();
Location loc = op->getLoc();
Value indices = op.indices();
Value values = op.values();
ValueRange sizes = op.sizes();
// Types
RankedTensorType resultType =
op.getResult().getType().cast<RankedTensorType>();
Type int64Type = rewriter.getIntegerType(64);
MemRefType memrefI64Type = MemRefType::get({-1}, int64Type);
MemRefType memrefValueType =
MemRefType::get({-1}, resultType.getElementType());
unsigned rank = resultType.getRank();
// Initial constants
Value c0 = rewriter.create<arith::ConstantIndexOp>(loc, 0);
Value c1 = rewriter.create<arith::ConstantIndexOp>(loc, 1);
Value ci0 = rewriter.create<arith::ConstantIntOp>(loc, 0, int64Type);
Value ci1 = rewriter.create<arith::ConstantIntOp>(loc, 1, int64Type);
Value output =
rewriter.create<sparse_tensor::InitOp>(loc, resultType, sizes);
// Sparse Tensor info
Value npointers, dimIndex;
if (rank == 1) {
npointers = c1;
dimIndex = c0;
} else {
npointers = sizes[0];
dimIndex = c1;
}
// Size sparse arrays
Value nnz = rewriter.create<tensor::DimOp>(loc, indices, c0);
Value npointers_plus1 = rewriter.create<arith::AddIOp>(loc, npointers, c1);
callResizePointers(rewriter, module, loc, output, dimIndex,
npointers_plus1);
callResizeIndex(rewriter, module, loc, output, dimIndex, nnz);
callResizeValues(rewriter, module, loc, output, nnz);
Value Op = rewriter.create<sparse_tensor::ToPointersOp>(loc, memrefI64Type,
output, dimIndex);
Value Oi = rewriter.create<sparse_tensor::ToIndicesOp>(loc, memrefI64Type,
output, dimIndex);
Value Ox = rewriter.create<sparse_tensor::ToValuesOp>(loc, memrefValueType,
output);
// Populate from indices and values
// We assume everything is in the correct order
// Increment the pointer count and fill in the index and value
scf::ForOp loop = rewriter.create<scf::ForOp>(loc, c0, nnz, c1);
{
rewriter.setInsertionPointToStart(loop.getBody());
Value pos = loop.getInductionVar();
if (rank == 2) {
Value row = rewriter.create<tensor::ExtractOp>(loc, indices,
ValueRange{pos, c0});
Value currRowCount = rewriter.create<memref::LoadOp>(loc, Op, row);
Value rowCount_plus1 =
rewriter.create<arith::AddIOp>(loc, currRowCount, ci1);
rewriter.create<memref::StoreOp>(loc, rowCount_plus1, Op, row);
}
Value idx = rewriter.create<tensor::ExtractOp>(loc, indices,
ValueRange{pos, dimIndex});
Value idx64 = rewriter.create<arith::IndexCastOp>(loc, idx, int64Type);
Value val = rewriter.create<tensor::ExtractOp>(loc, values, pos);
rewriter.create<memref::StoreOp>(loc, idx64, Oi, pos);
rewriter.create<memref::StoreOp>(loc, val, Ox, pos);
rewriter.setInsertionPointAfter(loop);
}
if (rank == 2) {
// Update pointers using cumsum
scf::ForOp cumSumLoop =
rewriter.create<scf::ForOp>(loc, c0, npointers, c1, ValueRange{ci0});
{
rewriter.setInsertionPointToStart(cumSumLoop.getBody());
Value pos = cumSumLoop.getInductionVar();
Value base = cumSumLoop.getLoopBody().getArgument(1);
Value numEntries = rewriter.create<memref::LoadOp>(loc, Op, pos);
rewriter.create<memref::StoreOp>(loc, base, Op, pos);
Value nextBase = rewriter.create<arith::AddIOp>(loc, base, numEntries);
rewriter.create<scf::YieldOp>(loc, nextBase);
rewriter.setInsertionPointAfter(cumSumLoop);
}
}
// Update last pointer with nnz
Value nnz64 = rewriter.create<arith::IndexCastOp>(loc, nnz, int64Type);
rewriter.create<memref::StoreOp>(loc, nnz64, Op, npointers);
rewriter.replaceOp(op, output);
return success();
};
};
class LowerToCoordinatesRewrite
: public OpRewritePattern<graphblas::ToCoordinatesOp> {
public:
using OpRewritePattern<graphblas::ToCoordinatesOp>::OpRewritePattern;
LogicalResult matchAndRewrite(graphblas::ToCoordinatesOp op,
PatternRewriter &rewriter) const override {
Location loc = op->getLoc();
Value input = op.input();
RankedTensorType inputType = input.getType().cast<RankedTensorType>();
RankedTensorType valuesType =
op.getResult(1).getType().cast<RankedTensorType>();
unsigned rank = inputType.getRank();
Value nvals = rewriter.create<graphblas::NumValsOp>(loc, input);
Value nrank = rewriter.create<arith::ConstantIndexOp>(loc, rank);
Type indexType = rewriter.getIndexType();
Type int64Type = rewriter.getIntegerType(64);
MemRefType memrefI64Type = MemRefType::get({-1}, int64Type);
MemRefType memrefIndicesType = MemRefType::get({-1, -1}, indexType);
MemRefType memrefValueType =
MemRefType::get({-1}, valuesType.getElementType());
Value indices = rewriter.create<memref::AllocOp>(loc, memrefIndicesType,
ValueRange{nvals, nrank});
Value values =
rewriter.create<memref::AllocOp>(loc, memrefValueType, nvals);
// Initial constants
Value c0 = rewriter.create<arith::ConstantIndexOp>(loc, 0);
Value c1 = rewriter.create<arith::ConstantIndexOp>(loc, 1);
// Get sparse tensor info
Value npointers, dimIndex;
if (rank == 1) {
npointers = c1;
dimIndex = c0;
} else {
npointers = rewriter.create<graphblas::NumRowsOp>(loc, input);
dimIndex = c1;
}
Value Ip = rewriter.create<sparse_tensor::ToPointersOp>(loc, memrefI64Type,
input, dimIndex);
Value Ii = rewriter.create<sparse_tensor::ToIndicesOp>(loc, memrefI64Type,
input, dimIndex);
Value Ix =
rewriter.create<sparse_tensor::ToValuesOp>(loc, memrefValueType, input);
// Iterate through input, populating indices and values
scf::ForOp rowLoop = rewriter.create<scf::ForOp>(loc, c0, npointers, c1);
{
rewriter.setInsertionPointToStart(rowLoop.getBody());
Value row = rowLoop.getInductionVar();
Value row_plus1 = rewriter.create<arith::AddIOp>(loc, row, c1);
Value j_start_64 = rewriter.create<memref::LoadOp>(loc, Ip, row);
Value j_end_64 = rewriter.create<memref::LoadOp>(loc, Ip, row_plus1);
Value j_start =
rewriter.create<arith::IndexCastOp>(loc, j_start_64, indexType);
Value j_end =
rewriter.create<arith::IndexCastOp>(loc, j_end_64, indexType);
scf::ForOp colLoop = rewriter.create<scf::ForOp>(loc, j_start, j_end, c1);
{
rewriter.setInsertionPointToStart(colLoop.getBody());
Value jj = colLoop.getInductionVar();
Value col_64 = rewriter.create<memref::LoadOp>(loc, Ii, jj);
Value col = rewriter.create<arith::IndexCastOp>(loc, col_64, indexType);
Value val = rewriter.create<memref::LoadOp>(loc, Ix, jj);
if (rank == 2)
rewriter.create<memref::StoreOp>(loc, row, indices,
ValueRange{jj, c0});
rewriter.create<memref::StoreOp>(loc, col, indices,
ValueRange{jj, dimIndex});
rewriter.create<memref::StoreOp>(loc, val, values, jj);
rewriter.setInsertionPointAfter(colLoop);
}
rewriter.setInsertionPointAfter(rowLoop);
}
// Convert memrefs to tensors
Value indicesTensor =
rewriter.create<bufferization::ToTensorOp>(loc, indices);
Value valuesTensor =
rewriter.create<bufferization::ToTensorOp>(loc, values);
rewriter.replaceOp(op, ValueRange{indicesTensor, valuesTensor});
return success();
};
};
void populateGraphBLASLoweringPatterns(RewritePatternSet &patterns) {
patterns
.add<LowerMatrixSelectRandomRewrite, LowerSelectRewrite,
LowerSelectGenericRewrite, LowerReduceToVectorRewrite,
LowerReduceToVectorGenericRewrite, LowerReduceToScalarRewrite,
LowerReduceToScalarGenericRewrite, LowerConvertLayoutRewrite,
LowerCastRewrite, LowerTransposeRewrite, LowerApplyRewrite,
LowerApplyGenericRewrite, LowerUniformComplementRewrite,
LowerMatrixMultiplyReduceToScalarGenericRewrite,
LowerMatrixMultiplyRewrite, LowerMatrixMultiplyGenericRewrite,
LowerUnionRewrite, LowerUnionGenericRewrite, LowerIntersectRewrite,
LowerIntersectGenericRewrite, LowerUpdateRewrite,
LowerUpdateGenericRewrite, LowerEqualRewrite, LowerDiagOpRewrite,
LowerSelectMaskRewrite, LowerCommentRewrite, LowerPrintRewrite,
LowerPrintTensorRewrite, LowerSizeRewrite, LowerNumRowsRewrite,
LowerNumColsRewrite, LowerNumValsRewrite, LowerDupRewrite,
LowerFromCoordinatesRewrite, LowerToCoordinatesRewrite>(
patterns.getContext());
}
struct GraphBLASLoweringPass
: public GraphBLASLoweringBase<GraphBLASLoweringPass> {
void runOnOperation() override {
MLIRContext *ctx = &getContext();
RewritePatternSet patterns(ctx);
ConversionTarget target(*ctx);
populateGraphBLASLoweringPatterns(patterns);
(void)applyPatternsAndFoldGreedily(getOperation(), std::move(patterns));
target.addIllegalDialect<graphblas::GraphBLASDialect>();
}
};
void populateGraphBLASStructuralizePatterns(RewritePatternSet &patterns) {
patterns
.add<TransposeDWIMRewrite, ReduceToVectorDWIMRewrite,
MatrixMultiplyGenericDWIMFirstArgRewrite,
MatrixMultiplyGenericDWIMSecondArgRewrite,
MatrixMultiplyGenericDWIMMaskRewrite,
MatrixMultiplyReduceToScalarGenericDWIMFirstArgRewrite,
MatrixMultiplyReduceToScalarGenericDWIMSecondArgRewrite,
MatrixMultiplyReduceToScalarGenericDWIMMaskRewrite,
LowerMatrixMultiplyRewrite, LowerApplyRewrite, LowerSelectRewrite,
LowerUnionRewrite, LowerIntersectRewrite, LowerUpdateRewrite,
LowerReduceToVectorRewrite, LowerReduceToScalarRewrite>(
patterns.getContext());
}
struct GraphBLASStructuralizePass
: public GraphBLASStructuralizeBase<GraphBLASStructuralizePass> {
void runOnOperation() override {
MLIRContext *ctx = &getContext();
RewritePatternSet patterns(ctx);
ConversionTarget target(*ctx);
populateGraphBLASStructuralizePatterns(patterns);
(void)applyPatternsAndFoldGreedily(getOperation(), std::move(patterns));
}
};
} // end anonymous namespace
std::unique_ptr<OperationPass<ModuleOp>> mlir::createGraphBLASLoweringPass() {
return std::make_unique<GraphBLASLoweringPass>();
}
std::unique_ptr<OperationPass<ModuleOp>>
mlir::createGraphBLASStructuralizePass() {
return std::make_unique<GraphBLASStructuralizePass>();
}
| 40.989821 | 80 | 0.652056 | [
"shape",
"vector"
] |
a85d031b38645dbe39cd30e96514963109a94a49 | 11,515 | cpp | C++ | src/ClientData/CallstackData.cpp | dimitry-/orbit | fdbcde3783a6b65deabaebfb5c164e58a1513831 | [
"BSD-2-Clause"
] | null | null | null | src/ClientData/CallstackData.cpp | dimitry-/orbit | fdbcde3783a6b65deabaebfb5c164e58a1513831 | [
"BSD-2-Clause"
] | null | null | null | src/ClientData/CallstackData.cpp | dimitry-/orbit | fdbcde3783a6b65deabaebfb5c164e58a1513831 | [
"BSD-2-Clause"
] | null | null | null | // Copyright (c) 2020 The Orbit Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ClientData/CallstackData.h"
#include <absl/container/flat_hash_map.h>
#include <absl/container/flat_hash_set.h>
#include <cstdint>
#include <utility>
#include "ClientData/CallstackTypes.h"
#include "OrbitBase/Logging.h"
#include "capture_data.pb.h"
using orbit_client_protos::CallstackEvent;
using orbit_client_protos::CallstackInfo;
namespace orbit_client_data {
void CallstackData::AddCallstackEvent(CallstackEvent callstack_event) {
std::lock_guard lock(mutex_);
CHECK(unique_callstacks_.contains(callstack_event.callstack_id()));
RegisterTime(callstack_event.time());
callstack_events_by_tid_[callstack_event.thread_id()][callstack_event.time()] =
std::move(callstack_event);
}
void CallstackData::RegisterTime(uint64_t time) {
if (time > max_time_) max_time_ = time;
if (time > 0 && time < min_time_) min_time_ = time;
}
void CallstackData::AddUniqueCallstack(uint64_t callstack_id,
orbit_client_protos::CallstackInfo callstack) {
std::lock_guard lock(mutex_);
unique_callstacks_[callstack_id] =
std::make_shared<orbit_client_protos::CallstackInfo>(std::move(callstack));
}
uint32_t CallstackData::GetCallstackEventsCount() const {
std::lock_guard lock(mutex_);
uint32_t count = 0;
for (const auto& tid_and_events : callstack_events_by_tid_) {
count += tid_and_events.second.size();
}
return count;
}
std::vector<orbit_client_protos::CallstackEvent> CallstackData::GetCallstackEventsInTimeRange(
uint64_t time_begin, uint64_t time_end) const {
std::lock_guard lock(mutex_);
std::vector<CallstackEvent> callstack_events;
for (const auto& tid_and_events : callstack_events_by_tid_) {
const std::map<uint64_t, CallstackEvent>& events = tid_and_events.second;
for (auto event_it = events.lower_bound(time_begin); event_it != events.end(); ++event_it) {
uint64_t time = event_it->first;
if (time < time_end) {
callstack_events.push_back(event_it->second);
} else {
break;
}
}
}
return callstack_events;
}
absl::flat_hash_map<int32_t, uint32_t> CallstackData::GetCallstackEventsCountsPerTid() const {
std::lock_guard lock(mutex_);
absl::flat_hash_map<int32_t, uint32_t> counts;
for (const auto& tid_and_events : callstack_events_by_tid_) {
counts.emplace(tid_and_events.first, tid_and_events.second.size());
}
return counts;
}
uint32_t CallstackData::GetCallstackEventsOfTidCount(int32_t thread_id) const {
std::lock_guard lock(mutex_);
const auto& tid_and_events_it = callstack_events_by_tid_.find(thread_id);
if (tid_and_events_it == callstack_events_by_tid_.end()) {
return 0;
}
return tid_and_events_it->second.size();
}
std::vector<CallstackEvent> CallstackData::GetCallstackEventsOfTidInTimeRange(
int32_t tid, uint64_t time_begin, uint64_t time_end) const {
std::lock_guard lock(mutex_);
std::vector<CallstackEvent> callstack_events;
auto tid_and_events_it = callstack_events_by_tid_.find(tid);
if (tid_and_events_it == callstack_events_by_tid_.end()) {
return callstack_events;
}
const std::map<uint64_t, CallstackEvent>& events = tid_and_events_it->second;
for (auto event_it = events.lower_bound(time_begin); event_it != events.end(); ++event_it) {
uint64_t time = event_it->first;
if (time < time_end) {
callstack_events.push_back(event_it->second);
} else {
break;
}
}
return callstack_events;
}
void CallstackData::ForEachCallstackEvent(
const std::function<void(const orbit_client_protos::CallstackEvent&)>& action) const {
std::lock_guard lock(mutex_);
for (const auto& [unused_tid, events] : callstack_events_by_tid_) {
for (const auto& [unused_timestamp, event] : events) {
action(event);
}
}
}
void CallstackData::ForEachCallstackEventInTimeRange(
uint64_t min_timestamp, uint64_t max_timestamp,
const std::function<void(const orbit_client_protos::CallstackEvent&)>& action) const {
std::lock_guard lock(mutex_);
CHECK(min_timestamp <= max_timestamp);
for (const auto& [unused_tid, events] : callstack_events_by_tid_) {
for (auto event_it = events.lower_bound(min_timestamp);
event_it != events.upper_bound(max_timestamp); ++event_it) {
action(event_it->second);
}
}
}
void CallstackData::ForEachCallstackEventOfTidInTimeRange(
int32_t tid, uint64_t min_timestamp, uint64_t max_timestamp,
const std::function<void(const orbit_client_protos::CallstackEvent&)>& action) const {
std::lock_guard lock(mutex_);
CHECK(min_timestamp <= max_timestamp);
const auto& tid_and_events_it = callstack_events_by_tid_.find(tid);
if (tid_and_events_it == callstack_events_by_tid_.end()) {
return;
}
const auto& events = tid_and_events_it->second;
for (auto event_it = events.lower_bound(min_timestamp);
event_it != events.upper_bound(max_timestamp); ++event_it) {
action(event_it->second);
}
}
void CallstackData::AddCallstackFromKnownCallstackData(const CallstackEvent& event,
const CallstackData* known_callstack_data) {
std::lock_guard lock(mutex_);
uint64_t callstack_id = event.callstack_id();
std::shared_ptr<orbit_client_protos::CallstackInfo> unique_callstack =
known_callstack_data->GetCallstackPtr(callstack_id);
if (unique_callstack == nullptr) {
return;
}
// The insertion only happens if the hash isn't already present.
unique_callstacks_.emplace(callstack_id, std::move(unique_callstack));
callstack_events_by_tid_[event.thread_id()][event.time()] = CallstackEvent(event);
}
const orbit_client_protos::CallstackInfo* CallstackData::GetCallstack(uint64_t callstack_id) const {
std::lock_guard lock(mutex_);
auto it = unique_callstacks_.find(callstack_id);
if (it != unique_callstacks_.end()) {
return it->second.get();
}
return nullptr;
}
bool CallstackData::HasCallstack(uint64_t callstack_id) const {
std::lock_guard lock(mutex_);
return unique_callstacks_.contains(callstack_id);
}
void CallstackData::ForEachUniqueCallstack(
const std::function<void(uint64_t callstack_id,
const orbit_client_protos::CallstackInfo& callstack)>& action) const {
std::lock_guard lock(mutex_);
for (const auto& [callstack_id, callstack_ptr] : unique_callstacks_) {
action(callstack_id, *callstack_ptr);
}
}
void CallstackData::ForEachFrameInCallstack(uint64_t callstack_id,
const std::function<void(uint64_t)>& action) const {
std::lock_guard lock(mutex_);
for (uint64_t frame : unique_callstacks_.at(callstack_id)->frames()) {
action(frame);
}
}
absl::flat_hash_map<uint64_t, std::shared_ptr<orbit_client_protos::CallstackInfo>>
CallstackData::GetUniqueCallstacksCopy() const {
std::lock_guard lock(mutex_);
return unique_callstacks_;
}
std::shared_ptr<orbit_client_protos::CallstackInfo> CallstackData::GetCallstackPtr(
uint64_t callstack_id) const {
auto it = unique_callstacks_.find(callstack_id);
if (it != unique_callstacks_.end()) {
return unique_callstacks_.at(callstack_id);
}
return nullptr;
}
void CallstackData::UpdateCallstackTypeBasedOnMajorityStart() {
std::lock_guard lock(mutex_);
absl::flat_hash_set<uint64_t> callstack_ids_to_filter;
for (auto& [tid, timestamps_and_callstack_events] : callstack_events_by_tid_) {
uint64_t count_for_this_thread = 0;
// Count the number of occurrences of each outer frame for this thread.
absl::flat_hash_map<uint64_t, uint64_t> count_by_outer_frame;
for (const auto& [unused_timestamp_ns, event] : timestamps_and_callstack_events) {
const CallstackInfo& callstack = *unique_callstacks_.at(event.callstack_id());
CHECK(callstack.type() != CallstackInfo::kFilteredByMajorityOutermostFrame);
if (callstack.type() != CallstackInfo::kComplete) {
continue;
}
++count_for_this_thread;
const auto& frames = callstack.frames();
CHECK(!frames.empty());
uint64_t outer_frame = *frames.rbegin();
++count_by_outer_frame[outer_frame];
}
// Find the outer frame with the most occurrences.
if (count_by_outer_frame.empty()) {
continue;
}
uint64_t majority_outer_frame = 0;
uint64_t majority_outer_frame_count = 0;
for (const auto& outer_frame_and_count : count_by_outer_frame) {
CHECK(outer_frame_and_count.second > 0);
if (outer_frame_and_count.second > majority_outer_frame_count) {
majority_outer_frame = outer_frame_and_count.first;
majority_outer_frame_count = outer_frame_and_count.second;
}
}
// The value is somewhat arbitrary. We want at least three quarters of the thread's callstacks
// to agree on the "correct" outermost frame.
static constexpr double kFilterSupermajorityThreshold = 0.75;
if (majority_outer_frame_count < count_for_this_thread * kFilterSupermajorityThreshold) {
LOG("Skipping filtering CallstackEvents for tid %d: majority outer frame has only %lu "
"occurrences out of %lu",
tid, majority_outer_frame_count, count_for_this_thread);
continue;
}
// Record the ids of the CallstackInfos references by the CallstackEvents whose outer frame
// doesn't match the (super)majority outer frame.
// Note that if a CallstackEvent from another thread references a filtered CallstackInfo, that
// CallstackEvent will also be affected.
for (const auto& [unused_timestamp_ns, event] : timestamps_and_callstack_events) {
const CallstackInfo& callstack = *unique_callstacks_.at(event.callstack_id());
CHECK(callstack.type() != CallstackInfo::kFilteredByMajorityOutermostFrame);
if (callstack.type() != CallstackInfo::kComplete) {
continue;
}
const auto& frames = unique_callstacks_.at(event.callstack_id())->frames();
CHECK(!frames.empty());
if (*frames.rbegin() != majority_outer_frame) {
callstack_ids_to_filter.insert(event.callstack_id());
}
}
}
// Change the type of the recorded CallstackInfos.
for (uint64_t callstack_id_to_filter : callstack_ids_to_filter) {
CallstackInfo* callstack = unique_callstacks_.at(callstack_id_to_filter).get();
CHECK(callstack->type() == CallstackInfo::kComplete);
callstack->set_type(CallstackInfo::kFilteredByMajorityOutermostFrame);
}
// Count how many CallstackEvents had their CallstackInfo affected by the type change.
uint64_t affected_event_count = 0;
for (auto& [tid, timestamps_and_callstack_events] : callstack_events_by_tid_) {
for (const auto& [unused_timestamp_ns, event] : timestamps_and_callstack_events) {
if (unique_callstacks_.at(event.callstack_id())->type() ==
CallstackInfo::kFilteredByMajorityOutermostFrame) {
++affected_event_count;
}
}
}
uint32_t callstack_event_count = GetCallstackEventsCount();
LOG("Filtered %u CallstackInfos of %u (%.2f%%), affecting %u CallstackEvents of %u (%.2f%%)",
callstack_ids_to_filter.size(), unique_callstacks_.size(),
100.0f * callstack_ids_to_filter.size() / unique_callstacks_.size(), affected_event_count,
callstack_event_count, 100.0f * affected_event_count / callstack_event_count);
}
} // namespace orbit_client_data
| 38.129139 | 100 | 0.731307 | [
"vector"
] |
a85e4f4cd23e3a9977e24ef6012c154f7cb927a0 | 536 | cpp | C++ | custom_opengl_wrapper/custom_opengl_wrapper/FBOManager.cpp | mallocc/custom_opengl_wrapper | 2384615c624b32947ae198af0cb5fb5f4371ffe2 | [
"MIT"
] | null | null | null | custom_opengl_wrapper/custom_opengl_wrapper/FBOManager.cpp | mallocc/custom_opengl_wrapper | 2384615c624b32947ae198af0cb5fb5f4371ffe2 | [
"MIT"
] | null | null | null | custom_opengl_wrapper/custom_opengl_wrapper/FBOManager.cpp | mallocc/custom_opengl_wrapper | 2384615c624b32947ae198af0cb5fb5f4371ffe2 | [
"MIT"
] | null | null | null | #include "FBOManager.h"
#include "Mesh.h"
using gfx::engine::FBOManager;
// constructor
FBOManager::FBOManager() {}
// Add an FBO to the list and returns its FBOID
gfx::engine::FBOID FBOManager::addFBO(glm::vec2 size, gfx::engine::Mesh * render_mesh)
{
gfx::engine::FBO fbo = gfx::engine::FBO(size);
fbo.set_render_mesh(render_mesh);
m_fbos.insert({ fbo.get_fboid(), fbo });
return fbo.get_fboid();
}
// Get the pointer to an FBO in the list
gfx::engine::FBO * FBOManager::get_fbo(gfx::engine::FBOID id)
{
return &m_fbos[id];
} | 24.363636 | 86 | 0.705224 | [
"mesh"
] |
a869fac1deaa3f86f4a4050bee558a7d04d0e09f | 7,574 | cpp | C++ | src/BvhTriangleMeshShape.cpp | yoshinoToylogic/bulletsharp | 79558f9e78b68f1d218d64234645848661a54e01 | [
"MIT"
] | null | null | null | src/BvhTriangleMeshShape.cpp | yoshinoToylogic/bulletsharp | 79558f9e78b68f1d218d64234645848661a54e01 | [
"MIT"
] | null | null | null | src/BvhTriangleMeshShape.cpp | yoshinoToylogic/bulletsharp | 79558f9e78b68f1d218d64234645848661a54e01 | [
"MIT"
] | null | null | null | #include "StdAfx.h"
#include "BvhTriangleMeshShape.h"
#include "StridingMeshInterface.h"
#include "TriangleCallback.h"
#include "TriangleInfoMap.h"
#ifndef DISABLE_BVH
#include "OptimizedBvh.h"
#endif
#ifndef DISABLE_SERIALIZE
#include "Serializer.h"
#endif
#define Native static_cast<btBvhTriangleMeshShape*>(_native)
BvhTriangleMeshShape::BvhTriangleMeshShape(btBvhTriangleMeshShape* native)
: TriangleMeshShape(native)
{
}
BvhTriangleMeshShape::BvhTriangleMeshShape(StridingMeshInterface^ meshInterface, bool useQuantizedAabbCompression,
bool buildBvh)
: TriangleMeshShape(new btBvhTriangleMeshShape(meshInterface->_native, useQuantizedAabbCompression,
buildBvh))
{
_meshInterface = meshInterface;
}
BvhTriangleMeshShape::BvhTriangleMeshShape(StridingMeshInterface^ meshInterface, bool useQuantizedAabbCompression)
: TriangleMeshShape(new btBvhTriangleMeshShape(meshInterface->_native, useQuantizedAabbCompression))
{
_meshInterface = meshInterface;
}
BvhTriangleMeshShape::BvhTriangleMeshShape(StridingMeshInterface^ meshInterface, bool useQuantizedAabbCompression,
Vector3% bvhAabbMin, Vector3% bvhAabbMax, bool buildBvh)
: TriangleMeshShape(0)
{
VECTOR3_CONV(bvhAabbMin);
VECTOR3_CONV(bvhAabbMax);
UnmanagedPointer = new btBvhTriangleMeshShape(meshInterface->_native, useQuantizedAabbCompression,
VECTOR3_USE(bvhAabbMin), VECTOR3_USE(bvhAabbMax), buildBvh);
VECTOR3_DEL(bvhAabbMin);
VECTOR3_DEL(bvhAabbMax);
_meshInterface = meshInterface;
}
BvhTriangleMeshShape::BvhTriangleMeshShape(StridingMeshInterface^ meshInterface, bool useQuantizedAabbCompression,
Vector3 bvhAabbMin, Vector3 bvhAabbMax, bool buildBvh)
: TriangleMeshShape(0)
{
VECTOR3_CONV(bvhAabbMin);
VECTOR3_CONV(bvhAabbMax);
UnmanagedPointer = new btBvhTriangleMeshShape(meshInterface->_native, useQuantizedAabbCompression,
VECTOR3_USE(bvhAabbMin), VECTOR3_USE(bvhAabbMax), buildBvh);
VECTOR3_DEL(bvhAabbMin);
VECTOR3_DEL(bvhAabbMax);
_meshInterface = meshInterface;
}
BvhTriangleMeshShape::BvhTriangleMeshShape(StridingMeshInterface^ meshInterface, bool useQuantizedAabbCompression,
Vector3% bvhAabbMin, Vector3% bvhAabbMax)
: TriangleMeshShape(0)
{
VECTOR3_CONV(bvhAabbMin);
VECTOR3_CONV(bvhAabbMax);
UnmanagedPointer = new btBvhTriangleMeshShape(meshInterface->_native, useQuantizedAabbCompression,
VECTOR3_USE(bvhAabbMin), VECTOR3_USE(bvhAabbMax));
VECTOR3_DEL(bvhAabbMin);
VECTOR3_DEL(bvhAabbMax);
_meshInterface = meshInterface;
}
BvhTriangleMeshShape::BvhTriangleMeshShape(StridingMeshInterface^ meshInterface, bool useQuantizedAabbCompression,
Vector3 bvhAabbMin, Vector3 bvhAabbMax)
: TriangleMeshShape(0)
{
VECTOR3_CONV(bvhAabbMin);
VECTOR3_CONV(bvhAabbMax);
UnmanagedPointer = new btBvhTriangleMeshShape(meshInterface->_native, useQuantizedAabbCompression,
VECTOR3_USE(bvhAabbMin), VECTOR3_USE(bvhAabbMax));
VECTOR3_DEL(bvhAabbMin);
VECTOR3_DEL(bvhAabbMax);
_meshInterface = meshInterface;
}
void BvhTriangleMeshShape::BuildOptimizedBvh()
{
Native->buildOptimizedBvh();
}
void BvhTriangleMeshShape::PartialRefitTree(Vector3% aabbMin, Vector3% aabbMax)
{
VECTOR3_CONV(aabbMin);
VECTOR3_CONV(aabbMax);
Native->partialRefitTree(VECTOR3_USE(aabbMin), VECTOR3_USE(aabbMax));
VECTOR3_DEL(aabbMin);
VECTOR3_DEL(aabbMax);
}
void BvhTriangleMeshShape::PartialRefitTree(Vector3 aabbMin, Vector3 aabbMax)
{
VECTOR3_CONV(aabbMin);
VECTOR3_CONV(aabbMax);
Native->partialRefitTree(VECTOR3_USE(aabbMin), VECTOR3_USE(aabbMax));
VECTOR3_DEL(aabbMin);
VECTOR3_DEL(aabbMax);
}
void BvhTriangleMeshShape::PerformConvexcast(TriangleCallback^ callback, Vector3% boxSource,
Vector3% boxTarget, Vector3% boxMin, Vector3% boxMax)
{
VECTOR3_CONV(boxSource);
VECTOR3_CONV(boxTarget);
VECTOR3_CONV(boxMin);
VECTOR3_CONV(boxMax);
Native->performConvexcast(callback->_native, VECTOR3_USE(boxSource), VECTOR3_USE(boxTarget),
VECTOR3_USE(boxMin), VECTOR3_USE(boxMax));
VECTOR3_DEL(boxSource);
VECTOR3_DEL(boxTarget);
VECTOR3_DEL(boxMin);
VECTOR3_DEL(boxMax);
}
void BvhTriangleMeshShape::PerformConvexcast(TriangleCallback^ callback, Vector3 boxSource,
Vector3 boxTarget, Vector3 boxMin, Vector3 boxMax)
{
VECTOR3_CONV(boxSource);
VECTOR3_CONV(boxTarget);
VECTOR3_CONV(boxMin);
VECTOR3_CONV(boxMax);
Native->performConvexcast(callback->_native, VECTOR3_USE(boxSource), VECTOR3_USE(boxTarget),
VECTOR3_USE(boxMin), VECTOR3_USE(boxMax));
VECTOR3_DEL(boxSource);
VECTOR3_DEL(boxTarget);
VECTOR3_DEL(boxMin);
VECTOR3_DEL(boxMax);
}
void BvhTriangleMeshShape::PerformRaycast(TriangleCallback^ callback, Vector3% raySource,
Vector3% rayTarget)
{
VECTOR3_CONV(raySource);
VECTOR3_CONV(rayTarget);
Native->performRaycast(callback->_native, VECTOR3_USE(raySource), VECTOR3_USE(rayTarget));
VECTOR3_DEL(raySource);
VECTOR3_DEL(rayTarget);
}
void BvhTriangleMeshShape::PerformRaycast(TriangleCallback^ callback, Vector3 raySource,
Vector3 rayTarget)
{
VECTOR3_CONV(raySource);
VECTOR3_CONV(rayTarget);
Native->performRaycast(callback->_native, VECTOR3_USE(raySource), VECTOR3_USE(rayTarget));
VECTOR3_DEL(raySource);
VECTOR3_DEL(rayTarget);
}
void BvhTriangleMeshShape::RefitTree(Vector3% aabbMin, Vector3% aabbMax)
{
VECTOR3_CONV(aabbMin);
VECTOR3_CONV(aabbMax);
Native->refitTree(VECTOR3_USE(aabbMin), VECTOR3_USE(aabbMax));
VECTOR3_DEL(aabbMin);
VECTOR3_DEL(aabbMax);
}
void BvhTriangleMeshShape::RefitTree(Vector3 aabbMin, Vector3 aabbMax)
{
VECTOR3_CONV(aabbMin);
VECTOR3_CONV(aabbMax);
Native->refitTree(VECTOR3_USE(aabbMin), VECTOR3_USE(aabbMax));
VECTOR3_DEL(aabbMin);
VECTOR3_DEL(aabbMax);
}
#ifndef DISABLE_SERIALIZE
void BvhTriangleMeshShape::SerializeSingleBvh(BulletSharp::Serializer^ serializer)
{
Native->serializeSingleBvh(serializer->_native);
}
void BvhTriangleMeshShape::SerializeSingleTriangleInfoMap(BulletSharp::Serializer^ serializer)
{
Native->serializeSingleTriangleInfoMap(serializer->_native);
}
#endif
#ifndef DISABLE_BVH
void BvhTriangleMeshShape::SetOptimizedBvh(BulletSharp::OptimizedBvh^ bvh, Vector3 localScaling)
{
VECTOR3_CONV(localScaling);
Native->setOptimizedBvh((btOptimizedBvh*)bvh->_native, VECTOR3_USE(localScaling));
VECTOR3_DEL(localScaling);
}
#pragma managed(push, off)
void BvhTriangleMeshShape_SetOptimizedBvh(btBvhTriangleMeshShape* shape, btOptimizedBvh* bvh)
{
shape->setOptimizedBvh(bvh);
}
#pragma managed(pop)
OptimizedBvh^ BvhTriangleMeshShape::OptimizedBvh::get()
{
btOptimizedBvh* optimizedBvh = Native->getOptimizedBvh();
ReturnCachedObjectCast(BulletSharp::OptimizedBvh, _optimizedBvh, optimizedBvh)
}
void BvhTriangleMeshShape::OptimizedBvh::set(BulletSharp::OptimizedBvh^ value)
{
BvhTriangleMeshShape_SetOptimizedBvh(Native, (btOptimizedBvh*)value->_native);
}
#endif
bool BvhTriangleMeshShape::OwnsBvh::get()
{
return Native->getOwnsBvh();
}
BulletSharp::TriangleInfoMap^ BvhTriangleMeshShape::TriangleInfoMap::get()
{
if (_triangleInfoMap == nullptr)
{
_triangleInfoMap = gcnew BulletSharp::TriangleInfoMap(Native->getTriangleInfoMap(), true);
}
return _triangleInfoMap;
}
void BvhTriangleMeshShape::TriangleInfoMap::set(BulletSharp::TriangleInfoMap^ triangleInfoMap)
{
_triangleInfoMap = triangleInfoMap;
Native->setTriangleInfoMap(triangleInfoMap->_native);
}
bool BvhTriangleMeshShape::UsesQuantizedAabbCompression::get()
{
return Native->usesQuantizedAabbCompression();
}
| 31.168724 | 115 | 0.79258 | [
"shape"
] |
a86f7d74b127a0beb43eb3614e6e299b56708796 | 577 | cpp | C++ | Private/TPHUD.cpp | deg3x/ThirdPersonCombatSystem | fa8a242ce45d45e800c960b233db24585548cb0f | [
"MIT"
] | 1 | 2021-11-08T11:47:28.000Z | 2021-11-08T11:47:28.000Z | Private/TPHUD.cpp | deg3x/ThirdPersonCombatSystem | fa8a242ce45d45e800c960b233db24585548cb0f | [
"MIT"
] | null | null | null | Private/TPHUD.cpp | deg3x/ThirdPersonCombatSystem | fa8a242ce45d45e800c960b233db24585548cb0f | [
"MIT"
] | null | null | null | // Fill out your copyright notice in the Description page of Project Settings.
#include "TPHUD.h"
#include "UObject/ConstructorHelpers.h"
#include "Blueprint/UserWidget.h"
ATPHUD::ATPHUD()
{
/*static ConstructorHelpers::FObjectFinder<UUserWidget> PrimaryUI(TEXT("/Game/UI/WB_PlayerHealth.WB_PlayerHealth"));
PlayerPrimaryUI = PrimaryUI.Object;*/
}
void ATPHUD::BeginPlay()
{
/*if (PlayerPrimaryUI == nullptr)
{
UE_LOG(LogTemp, Warning, TEXT("[!] Primary UI blueprint not found"));
return;
}
PlayerPrimaryUI->*/
}
void ATPHUD::DrawHUD()
{
Super::DrawHUD();
}
| 18.612903 | 117 | 0.724437 | [
"object"
] |
a872e1c3987b0b0872905fd012f8a2ecc91eb55d | 2,411 | cpp | C++ | game/LevelChunk.cpp | kolyden/engine | cab1881a8493b591a136a5ce3d502e704fdea7bf | [
"Unlicense"
] | null | null | null | game/LevelChunk.cpp | kolyden/engine | cab1881a8493b591a136a5ce3d502e704fdea7bf | [
"Unlicense"
] | null | null | null | game/LevelChunk.cpp | kolyden/engine | cab1881a8493b591a136a5ce3d502e704fdea7bf | [
"Unlicense"
] | null | null | null | #include "LevelChunk.h"
#include "Level.h"
#include "video/uutModel.h"
namespace uut
{
LevelChunk::LevelChunk(Context* context)
: Object(context)
, _index(0, 0)
, _cells(0)
, _position(0,0,0)
{
}
LevelChunk::~LevelChunk()
{
delete[] _cells;
}
void LevelChunk::Init(Level* level, const Vector2i& index)
{
_level = level;
_index = index;
_cells = new LevelCell[MAX_COUNT];
_position = Vector3f(
SIDE * LevelCell::SIZE * index.x,
0,
SIDE * LevelCell::SIZE * index.y);
}
void LevelChunk::Draw() const
{
Matrix4f mat = Matrix4f::IDENTITY;
for (int y = 0; y < SIDE; y++)
{
for (int x = 0; x < SIDE; x++)
{
const auto& cell = GetCell(Vector2i(x, y));
if (cell._floor < 0)
continue;
const Vector3f offset = _position + Vector3f(x, 0, y) * LevelCell::SIZE;
mat = Matrix4f::createTranslate(offset.x, offset.y, offset.z);
_level->GetPrefabs()[cell._floor]->Draw(mat);
for (int i = 0; i < 4; i++)
{
if (cell._wall[i] < 0)
continue;
const Matrix4f mat2 = LevelCell::WALL_OFFSET[i] * mat;
_level->GetPrefabs()[cell._wall[i]]->Draw(mat2);
}
// if (cell._wall[DIR_WEST] >= 0)
// {
// glPushMatrix();
// glTranslatef(-0.5f * LevelCell::SIZE, 0, 0);
// _level->GetPrefabs()[cell._wall[DIR_WEST]]->Draw();
// glPopMatrix();
// }
//
// if (cell._wall[DIR_EAST] >= 0)
// {
// glPushMatrix();
// glTranslatef(+0.5f * LevelCell::SIZE, 0, 0);
// _level->GetPrefabs()[cell._wall[DIR_EAST]]->Draw();
// glPopMatrix();
// }
//
// if (cell._wall[DIR_NORTH] >= 0)
// {
// glPushMatrix();
// glRotatef(90, 0, 1, 0);
// glTranslatef(+0.5f * LevelCell::SIZE, 0, 0);
// _level->GetPrefabs()[cell._wall[DIR_NORTH]]->Draw();
// glPopMatrix();
// }
//
// if (cell._wall[DIR_SOUTH] >= 0)
// {
// glPushMatrix();
// glRotatef(90, 0, 1, 0);
// glTranslatef(-0.5f * LevelCell::SIZE, 0, 0);
// _level->GetPrefabs()[cell._wall[DIR_SOUTH]]->Draw();
// glPopMatrix();
// }
}
}
}
LevelCell& LevelChunk::GetCell(const Vector2i& pos)
{
return _cells[pos.x + pos.y * SIDE];
}
const LevelCell& LevelChunk::GetCell(const Vector2i& pos) const
{
return _cells[pos.x + pos.y * SIDE];
}
} | 23.637255 | 77 | 0.543758 | [
"object"
] |
a87b9d0afb596e7f2d63d087ba6126fda1500d1a | 1,385 | cpp | C++ | mains/ch1.cpp | andleb/derivatives | f9449b278a60b7d209ca9914b67751ff034aaf78 | [
"MIT"
] | 6 | 2020-03-22T16:24:49.000Z | 2021-09-14T13:40:12.000Z | mains/ch1.cpp | andleb/derivatives | f9449b278a60b7d209ca9914b67751ff034aaf78 | [
"MIT"
] | null | null | null | mains/ch1.cpp | andleb/derivatives | f9449b278a60b7d209ca9914b67751ff034aaf78 | [
"MIT"
] | 2 | 2021-05-02T17:06:38.000Z | 2021-10-14T14:57:41.000Z | /** \file ch1.cpp
* \author Andrej Leban
* \date 11/2018
*
* Chapter 1. A simple Monte Carlo model
*/
#include <cmath>
#include <iostream>
#include <sstream>
#include "../src/derivatives.h"
double payoff(double p_spot, double p_strike) { return std::max<double>((p_spot - p_strike), 0); }
double simSpot(double p_S0, double p_t, double p_sigma, double p_r)
{
return p_S0 * std::exp((p_r - 0.5 * p_sigma * p_sigma) * p_t + p_sigma * std::sqrt(p_t) * der::normalDist<double>());
}
int main()
{
double S0, K, T, sigma, r;
int nScen;
#ifndef NDEBUG
S0 = 100;
K = 90;
T = 30;
sigma = 0.5;
r = 0.02;
nScen = 10000000;
#else
std::cout << "enter spot, strike, time to expiry, vol, r and number of scenarios:\n";
std::string inputParams;
std::getline(std::cin, inputParams);
std::istringstream iss{inputParams};
iss >> S0 >> K >> T >> sigma >> r >> nScen;
std::cin >> S0 >> K >> T >> sigma >> r >> nScen;
#endif
std::cout << S0 << " " << K << " " << T << " " << sigma << " " << r << " " << nScen << "\n";
double sum = 0.0;
for (int i = 0; i < nScen; ++i)
{
sum += payoff(simSpot(S0, T, sigma, r), K);
}
// NOTE: this is wildly inaccurate due to the numerical inaccuracy of the simSpot call
std::cout << "the price is: " << std::exp(-r * T) * (sum / nScen) << "\n";
return 0;
}
| 24.298246 | 121 | 0.560289 | [
"model"
] |
a886b89818683e28af4f5383ed34097883cab28d | 5,228 | cpp | C++ | engine/test/gtest/test_one_hot_op.cpp | alexsu52/neural-compressor | 7607ee46a015ee83a5e79dace8535a439d49cc8c | [
"Apache-2.0"
] | null | null | null | engine/test/gtest/test_one_hot_op.cpp | alexsu52/neural-compressor | 7607ee46a015ee83a5e79dace8535a439d49cc8c | [
"Apache-2.0"
] | null | null | null | engine/test/gtest/test_one_hot_op.cpp | alexsu52/neural-compressor | 7607ee46a015ee83a5e79dace8535a439d49cc8c | [
"Apache-2.0"
] | null | null | null | // Copyright (c) 2021 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <map>
#include <string>
#include "gtest/gtest.h"
#include "../../include/conf.hpp"
#include "../../include/common.hpp"
#include "../../include/operators/one_hot.hpp"
using executor::Tensor;
using executor::OperatorConfig;
using executor::TensorConfig;
using executor::AttrConfig;
using executor::MemoryAllocator;
struct OpArgs {
std::vector<Tensor*> input;
std::vector<Tensor*> output;
OperatorConfig conf;
};
struct TestParams {
std::pair<OpArgs, OpArgs> args;
bool expect_to_fail;
};
bool CheckResult(const TestParams& t) {
const auto& p = t.args.first;
const auto& q = t.args.second;
executor::OnehotOperator onehot_op(p.conf);
onehot_op.Reshape(p.input, p.output);
onehot_op.Forward(p.input, p.output);
// Should compare buffer with different addresses
EXPECT_NE(p.output[0]->data(), q.output[0]->data());
return executor::CompareData<float>(p.output[0]->data(), p.output[0]->size(),
q.output[0]->data(), q.output[0]->size());
}
class OnehotOpTest : public testing::TestWithParam<TestParams> {
protected:
OnehotOpTest() {}
~OnehotOpTest() {}
void SetUp() override {}
void TearDown() override {}
};
TEST_P(OnehotOpTest, TestPostfix) {
TestParams t = testing::TestWithParam<TestParams>::GetParam();
EXPECT_TRUE(CheckResult(t));
}
std::pair<OpArgs, OpArgs> GenerateFp32Case(const std::vector<std::vector<int64_t> >& input_shape,
std::string append_op = "") {
// Step 1: Construct Tensor config ptr
const auto& src_shape = input_shape[0];
TensorConfig* src_config = new TensorConfig("indices_tensor", src_shape, "int32");
std::vector<TensorConfig*> input_config_vec = {src_config};
int64_t depth = 2;
int64_t on_value = 1;
int64_t off_value = 0;
std::vector<int64_t> dst_shape = {src_shape[0], depth}; // axis = -1, depth = 2
TensorConfig* dst_config = new TensorConfig("dst", dst_shape);
std::vector<TensorConfig*> output_config_vec = {dst_config};
// Step 1.1: Construct Operator config obj
std::map<std::string, std::string> attr_map;
attr_map["axis"] = "-1";
attr_map["depth"] = std::to_string(depth);
attr_map["on_value"] = std::to_string(on_value);
attr_map["off_value"] = std::to_string(off_value);
AttrConfig* op_attr = new AttrConfig(attr_map);
OperatorConfig op_config = OperatorConfig("one_hot", "fp32", input_config_vec,
output_config_vec, op_attr);
// Step 2: Construct Tensor ptr
auto make_tensor_obj = [&](const TensorConfig* a_tensor_config, int life_num = 1) {
// step1: set shape
Tensor* a_tensor = new Tensor(*a_tensor_config);
// step2: set tensor life
a_tensor->add_tensor_life(life_num);
// step3: library buffer can only be obtained afterwards
auto tensor_data = static_cast<int32_t*>(a_tensor->mutable_data());
uint32_t seed = 123;
for (int i = 0; i < a_tensor->size(); ++i) {
tensor_data[i] = (int32_t)(rand_r(&seed) % 3);
}
Tensor* a_tensor_copy = new Tensor(*a_tensor_config);
a_tensor_copy->add_tensor_life(life_num);
auto tensor_data_copy = a_tensor_copy->mutable_data();
memcpy(tensor_data_copy, tensor_data, a_tensor_copy->size() * sizeof(float));
return std::pair<Tensor*, Tensor*>{a_tensor, a_tensor_copy};
};
auto src_tensors = make_tensor_obj(src_config);
Tensor* dst_tensor = new Tensor(*dst_config);
dst_tensor->add_tensor_life(1);
Tensor* dst_tensor_copy = new Tensor(*dst_config);
dst_tensor_copy->add_tensor_life(1);
auto dst_data_copy = static_cast<float*>(dst_tensor_copy->mutable_data());
auto src_data_copy = (const int32_t*)src_tensors.second->data();
for (int i = 0; i < dst_shape[0]; ++i) {
for (int j = 0; j < depth; ++j) {
dst_data_copy[i * depth + j] = (j == src_data_copy[i]) ? on_value : off_value;
}
}
OpArgs op_args = {{src_tensors.first}, {dst_tensor}, op_config};
OpArgs op_args_copy = {{src_tensors.second}, {dst_tensor_copy}, op_config};
return {op_args, op_args_copy};
}
static auto CasesFp32 = []() {
std::string memory_strategy = getenv("DIRECT_BUFFER") == NULL ? "cycle_buffer" : "direct_buffer";
MemoryAllocator::SetStrategy(memory_strategy);
std::vector<TestParams> cases;
// Config
std::vector<int64_t> src_shape;
// case: simple
src_shape = {64};
cases.push_back({GenerateFp32Case({src_shape}), false});
// case: simple
src_shape = {8192};
cases.push_back({GenerateFp32Case({src_shape}), false});
return ::testing::ValuesIn(cases);
};
INSTANTIATE_TEST_SUITE_P(Prefix, OnehotOpTest, CasesFp32());
| 35.564626 | 99 | 0.688791 | [
"shape",
"vector"
] |
a88758393642747cfe418e5b452a2b3855493596 | 3,059 | cpp | C++ | numbers/sieve_of_eratosthenes.cpp | rressi/exercises | b3d19f73361c3b1286d39d9f05d24cd1ebb3f034 | [
"MIT"
] | null | null | null | numbers/sieve_of_eratosthenes.cpp | rressi/exercises | b3d19f73361c3b1286d39d9f05d24cd1ebb3f034 | [
"MIT"
] | 1 | 2022-01-02T14:58:03.000Z | 2022-01-02T14:58:03.000Z | numbers/sieve_of_eratosthenes.cpp | rressi/exercises | b3d19f73361c3b1286d39d9f05d24cd1ebb3f034 | [
"MIT"
] | null | null | null |
#include "sieve_of_eratosthenes.h"
#include <cassert>
#include <cmath>
#include <future>
#include <thread>
#include <valarray>
namespace numbers {
namespace {
auto getNumberOfCpus() -> unsigned {
return std::thread::hardware_concurrency();
}
auto findPrimeNumbersSequentially(Number maxNumber) -> std::vector<Number> {
auto foundPrimeNumbers = std::vector<Number>();
std::vector<bool> sieve;
sieve.resize(maxNumber);
for (auto x = 2; x < maxNumber; x++) {
if (!sieve[x]) {
foundPrimeNumbers.emplace_back(x);
for (auto multiplierOfX = 2 * x; multiplierOfX < maxNumber;
multiplierOfX += x) {
sieve[multiplierOfX] = true;
}
}
}
return foundPrimeNumbers;
}
auto findFirstDividend(Number primeNumber, Number minNumber) {
auto firstDividend = minNumber - (minNumber % primeNumber);
if (firstDividend < minNumber) {
firstDividend += primeNumber;
}
firstDividend = std::max(firstDividend, primeNumber * primeNumber);
assert(firstDividend >= minNumber);
return firstDividend;
}
auto findPrimeNumbersInRange(const std::vector<Number> &basePrimes,
Number minNumber, Number maxNumber)
-> std::vector<Number> {
assert(!basePrimes.empty());
assert(minNumber < maxNumber);
auto foundPrimeNumbers = std::vector<Number>();
std::vector<bool> sieve;
sieve.resize(maxNumber - minNumber);
for (auto basePrime : basePrimes) {
for (auto x = findFirstDividend(basePrime, minNumber); x < maxNumber;
x += basePrime) {
sieve[x - minNumber] = true;
}
}
for (auto x = 0; x < sieve.size(); x++) {
if (!sieve[x]) {
foundPrimeNumbers.emplace_back(x + minNumber);
}
}
return foundPrimeNumbers;
}
} // namespace
auto findPrimeNumbers(Number maxNumber, Opt<unsigned> maxThreads)
-> std::vector<Number> {
auto numThreads = maxThreads ? maxThreads.value() : getNumberOfCpus();
auto sequentialMaxNumbers =
numThreads == 1 ? maxNumber : std::min(maxNumber, Number(10'000));
if (sequentialMaxNumbers == maxNumber) {
return findPrimeNumbersSequentially(sequentialMaxNumbers);
}
auto firstPrimeNumbersMax = Number(std::lround(std::sqrt(maxNumber)));
auto firstPrimeNumbers = findPrimeNumbersSequentially(firstPrimeNumbersMax);
auto tasks = std::vector<std::future<std::vector<Number>>>();
tasks.resize(numThreads);
auto partStart = firstPrimeNumbersMax;
auto partSize = (maxNumber - partStart) / numThreads;
for (auto &task : tasks) {
bool isLastPart = (&task == &tasks.back());
auto partEnd = isLastPart ? maxNumber : partStart + partSize;
task = std::async(std::launch::async, findPrimeNumbersInRange,
firstPrimeNumbers, partStart, partEnd);
partStart += partSize;
}
auto primeNumbers = firstPrimeNumbers;
for (auto &task : tasks) {
auto partResult = task.get();
primeNumbers.insert(primeNumbers.end(), partResult.begin(),
partResult.end());
}
return primeNumbers;
}
} // namespace numbers | 26.833333 | 78 | 0.673096 | [
"vector"
] |
a887fca9a173f65aed82932fbe9fea9b89c1f2cb | 1,857 | hxx | C++ | opencascade/Adaptor3d_HVertex.hxx | mgreminger/OCP | 92eacb99497cd52b419c8a4a8ab0abab2330ed42 | [
"Apache-2.0"
] | null | null | null | opencascade/Adaptor3d_HVertex.hxx | mgreminger/OCP | 92eacb99497cd52b419c8a4a8ab0abab2330ed42 | [
"Apache-2.0"
] | null | null | null | opencascade/Adaptor3d_HVertex.hxx | mgreminger/OCP | 92eacb99497cd52b419c8a4a8ab0abab2330ed42 | [
"Apache-2.0"
] | null | null | null | // Created on: 1994-03-25
// Created by: model
// Copyright (c) 1994-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _Adaptor3d_HVertex_HeaderFile
#define _Adaptor3d_HVertex_HeaderFile
#include <Adaptor2d_Curve2d.hxx>
#include <gp_Pnt2d.hxx>
#include <TopAbs_Orientation.hxx>
class Adaptor3d_HVertex;
DEFINE_STANDARD_HANDLE(Adaptor3d_HVertex, Standard_Transient)
class Adaptor3d_HVertex : public Standard_Transient
{
public:
Standard_EXPORT Adaptor3d_HVertex();
Standard_EXPORT Adaptor3d_HVertex(const gp_Pnt2d& P, const TopAbs_Orientation Ori, const Standard_Real Resolution);
Standard_EXPORT virtual gp_Pnt2d Value();
Standard_EXPORT virtual Standard_Real Parameter (const Handle(Adaptor2d_Curve2d)& C);
//! Parametric resolution (2d).
Standard_EXPORT virtual Standard_Real Resolution (const Handle(Adaptor2d_Curve2d)& C);
Standard_EXPORT virtual TopAbs_Orientation Orientation();
Standard_EXPORT virtual Standard_Boolean IsSame (const Handle(Adaptor3d_HVertex)& Other);
DEFINE_STANDARD_RTTIEXT(Adaptor3d_HVertex,Standard_Transient)
protected:
private:
gp_Pnt2d myPnt;
Standard_Real myTol;
TopAbs_Orientation myOri;
};
#endif // _Adaptor3d_HVertex_HeaderFile
| 24.116883 | 117 | 0.788368 | [
"model"
] |
a8893b89ba1847cd6f6e93a4610f35660ffff719 | 25,911 | cc | C++ | paragraph/translation/allgather/mesh_2d_allgather_translator_test.cc | paragraph-sim/paragraph-core | 0d0f9e76c474f5ed08ec5c1f7acc672444270727 | [
"Apache-2.0"
] | null | null | null | paragraph/translation/allgather/mesh_2d_allgather_translator_test.cc | paragraph-sim/paragraph-core | 0d0f9e76c474f5ed08ec5c1f7acc672444270727 | [
"Apache-2.0"
] | 1 | 2021-11-23T17:17:57.000Z | 2021-11-23T17:17:57.000Z | paragraph/translation/allgather/mesh_2d_allgather_translator_test.cc | paragraph-sim/paragraph-core | 0d0f9e76c474f5ed08ec5c1f7acc672444270727 | [
"Apache-2.0"
] | null | null | null | /* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.
*/
#include "paragraph/translation/allgather/mesh_2d_allgather_translator.h"
#include <memory>
#include <string>
#include <utility>
#include "google/protobuf/text_format.h"
#include "google/protobuf/util/message_differencer.h"
#include "gtest/gtest.h"
#include "paragraph/shim/test_macros.h"
#include "paragraph/translation/translation_map.h"
paragraph::InstructionProto Mesh2dAllGather_no_barrier_test_proto() {
paragraph::InstructionProto proto;
std::string test_str =
R"proto(
name: "all-gather"
opcode: "all-gather"
instruction_id: 2
bytes_out: 160
communication_groups {
group_ids: 0
group_ids: 1
group_ids: 2
group_ids: 3
group_ids: 4
group_ids: 5
group_ids: 6
group_ids: 7
}
inner_subroutines {
name: "all-gather_mesh-2d"
subroutine_root_id: 24
execution_probability: 1
execution_count: 1
instructions {
name: "all-gather_stream-0_stage-0"
opcode: "all-gather"
instruction_id: 4
bytes_out: 20
communication_groups {
group_ids: 1
group_ids: 3
}
inner_subroutines {
name: "all-gather_stream-0_stage-0_mesh-1d"
subroutine_root_id: 5
execution_probability: 1
execution_count: 1
instructions {
name: "all-gather_stream-0_stage-0_mesh-1d_cw_sendrecv_0"
opcode: "sendrecv"
instruction_id: 5
bytes_in: 10
bytes_out: 10
communication_groups {
group_ids: 3
group_ids: 3
}
}
}
}
instructions {
name: "all-gather_stream-0_stage-1"
opcode: "all-gather"
instruction_id: 6
bytes_out: 80
communication_groups {
group_ids: 0
group_ids: 1
group_ids: 4
group_ids: 5
}
operand_ids: 4
inner_subroutines {
name: "all-gather_stream-0_stage-1_mesh-1d"
subroutine_root_id: 13
execution_probability: 1
execution_count: 1
instructions {
name: "all-gather_stream-0_stage-1_mesh-1d_ccw_sendrecv_0"
opcode: "sendrecv"
instruction_id: 7
bytes_in: 20
bytes_out: 20
communication_groups {
group_ids: 0
group_ids: 0
}
}
instructions {
name: "all-gather_stream-0_stage-1_mesh-1d_cw_sendrecv_0"
opcode: "sendrecv"
instruction_id: 8
bytes_in: 20
bytes_out: 20
communication_groups {
group_ids: 4
group_ids: 4
}
}
instructions {
name: "all-gather_stream-0_stage-1_mesh-1d_root_0"
opcode: "null"
instruction_id: 9
operand_ids: 8
operand_ids: 7
}
instructions {
name: "all-gather_stream-0_stage-1_mesh-1d_ccw_send_1"
opcode: "send"
instruction_id: 10
bytes_out: 20
communication_groups {
group_ids: 0
}
operand_ids: 9
}
instructions {
name: "all-gather_stream-0_stage-1_mesh-1d_cw_sendrecv_1"
opcode: "sendrecv"
instruction_id: 11
bytes_in: 20
bytes_out: 20
communication_groups {
group_ids: 4
group_ids: 4
}
operand_ids: 9
}
instructions {
name: "all-gather_stream-0_stage-1_mesh-1d_root_1"
opcode: "null"
instruction_id: 12
operand_ids: 11
operand_ids: 10
}
instructions {
name: "all-gather_stream-0_stage-1_mesh-1d_ccw_send_2"
opcode: "send"
instruction_id: 13
bytes_out: 20
communication_groups {
group_ids: 0
}
operand_ids: 12
}
}
}
instructions {
name: "all-gather_stream-1_stage-0"
opcode: "all-gather"
instruction_id: 14
bytes_out: 20
communication_groups {
group_ids: 1
group_ids: 5
}
inner_subroutines {
name: "all-gather_stream-1_stage-0_mesh-1d"
subroutine_root_id: 15
execution_probability: 1
execution_count: 1
instructions {
name: "all-gather_stream-1_stage-0_mesh-1d_cw_sendrecv_0"
opcode: "sendrecv"
instruction_id: 15
bytes_in: 10
bytes_out: 10
communication_groups {
group_ids: 5
group_ids: 5
}
}
}
}
instructions {
name: "all-gather_stream-1_stage-1"
opcode: "all-gather"
instruction_id: 16
bytes_out: 80
communication_groups {
group_ids: 0
group_ids: 1
group_ids: 2
group_ids: 3
}
operand_ids: 14
inner_subroutines {
name: "all-gather_stream-1_stage-1_mesh-1d"
subroutine_root_id: 23
execution_probability: 1
execution_count: 1
instructions {
name: "all-gather_stream-1_stage-1_mesh-1d_ccw_sendrecv_0"
opcode: "sendrecv"
instruction_id: 17
bytes_in: 20
bytes_out: 20
communication_groups {
group_ids: 0
group_ids: 0
}
}
instructions {
name: "all-gather_stream-1_stage-1_mesh-1d_cw_sendrecv_0"
opcode: "sendrecv"
instruction_id: 18
bytes_in: 20
bytes_out: 20
communication_groups {
group_ids: 2
group_ids: 2
}
}
instructions {
name: "all-gather_stream-1_stage-1_mesh-1d_root_0"
opcode: "null"
instruction_id: 19
operand_ids: 18
operand_ids: 17
}
instructions {
name: "all-gather_stream-1_stage-1_mesh-1d_ccw_send_1"
opcode: "send"
instruction_id: 20
bytes_out: 20
communication_groups {
group_ids: 0
}
operand_ids: 19
}
instructions {
name: "all-gather_stream-1_stage-1_mesh-1d_cw_sendrecv_1"
opcode: "sendrecv"
instruction_id: 21
bytes_in: 20
bytes_out: 20
communication_groups {
group_ids: 2
group_ids: 2
}
operand_ids: 19
}
instructions {
name: "all-gather_stream-1_stage-1_mesh-1d_root_1"
opcode: "null"
instruction_id: 22
operand_ids: 21
operand_ids: 20
}
instructions {
name: "all-gather_stream-1_stage-1_mesh-1d_ccw_send_2"
opcode: "send"
instruction_id: 23
bytes_out: 20
communication_groups {
group_ids: 0
}
operand_ids: 22
}
}
}
instructions {
name: "all-gather_root"
opcode: "null"
instruction_id: 24
operand_ids: 6
operand_ids: 16
}
}
)proto";
google::protobuf::TextFormat::ParseFromString(test_str,
&proto);
return proto;
} // NOLINT
// Tests expanding 2D-Mesh all-gather
TEST(Mesh2dAllGather, NoBarrier) {
auto graph = absl::make_unique<paragraph::Graph>("test_graph", 1);
auto sub = absl::make_unique<paragraph::Subroutine>(
"test_subroutine", graph.get());
auto sub_ptr = sub.get();
graph->SetEntrySubroutine(std::move(sub));
ASSERT_OK_AND_ASSIGN(auto instr_1, paragraph::Instruction::Create(
paragraph::Opcode::kDelay, "first_instruction", sub_ptr));
instr_1->SetOps(4);
ASSERT_OK_AND_ASSIGN(auto allgather,
paragraph::Instruction::Create(
paragraph::Opcode::kAllGather, "all-gather", sub_ptr));
allgather->SetBytesOut(160);
paragraph::CommunicationGroup allgather_group = {0, 1, 2, 3, 4, 5, 6, 7};
allgather->AppendCommunicationGroup(allgather_group);
ASSERT_OK_AND_ASSIGN(auto instr_3, paragraph::Instruction::Create(
paragraph::Opcode::kDelay, "last_instruction", sub_ptr, true));
instr_3->SetOps(4);
nlohmann::json config = R"(
{
"all-gather": {
"algorithm": "mesh-2d",
"concentration": 2,
"dimension_widths": [2, 2],
"integrated_local_exchange": true
}
}
)"_json;
ASSERT_OK_AND_ASSIGN(auto translators, paragraph::CreateTranslators(
paragraph::TranslatorType::kCollective, config));
EXPECT_OK(translators["all-gather"]->Translate(allgather));
paragraph::InstructionProto allgather_proto =
Mesh2dAllGather_no_barrier_test_proto();
EXPECT_TRUE(google::protobuf::util::MessageDifferencer::Equals(
allgather->ToProto().value(), allgather_proto));
}
paragraph::InstructionProto Mesh2dAllGather_with_barrier_test_proto() {
paragraph::InstructionProto proto;
std::string test_str =
R"proto(
name: "all-gather"
opcode: "all-gather"
instruction_id: 2
bytes_out: 160
communication_groups {
group_ids: 0
group_ids: 1
group_ids: 2
group_ids: 3
group_ids: 4
group_ids: 5
group_ids: 6
group_ids: 7
}
inner_subroutines {
name: "all-gather_mesh-2d"
subroutine_root_id: 26
execution_probability: 1
execution_count: 1
instructions {
name: "all-gather_stream-0_stage-0"
opcode: "all-gather"
instruction_id: 4
bytes_out: 20
communication_groups {
group_ids: 0
group_ids: 2
}
inner_subroutines {
name: "all-gather_stream-0_stage-0_mesh-1d"
subroutine_root_id: 8
execution_probability: 1
execution_count: 1
instructions {
name: "all-gather_stream-0_stage-0_mesh-1d_barrier"
opcode: "barrier"
instruction_id: 5
communication_groups {
group_ids: 0
group_ids: 2
}
inner_subroutines {
name: "all-gather_stream-0_stage-0_mesh-1d_barrier_centralized"
subroutine_root_id: 7
execution_probability: 1
execution_count: 1
instructions {
name: "all-gather_stream-0_stage-0_mesh-1d_barrier_centralized_send_to_0"
opcode: "send"
instruction_id: 6
communication_groups {
group_ids: 0
}
}
instructions {
name: "all-gather_stream-0_stage-0_mesh-1d_barrier_centralized_recv_from_0"
opcode: "recv"
instruction_id: 7
communication_groups {
group_ids: 0
}
operand_ids: 6
}
}
}
instructions {
name: "all-gather_stream-0_stage-0_mesh-1d_ccw_sendrecv_0"
opcode: "sendrecv"
instruction_id: 8
bytes_in: 10
bytes_out: 10
communication_groups {
group_ids: 0
group_ids: 0
}
operand_ids: 5
}
}
}
instructions {
name: "all-gather_stream-0_stage-1"
opcode: "all-gather"
instruction_id: 9
bytes_out: 40
communication_groups {
group_ids: 2
group_ids: 6
}
operand_ids: 4
inner_subroutines {
name: "all-gather_stream-0_stage-1_mesh-1d"
subroutine_root_id: 14
execution_probability: 1
execution_count: 1
instructions {
name: "all-gather_stream-0_stage-1_mesh-1d_barrier"
opcode: "barrier"
instruction_id: 10
communication_groups {
group_ids: 2
group_ids: 6
}
inner_subroutines {
name: "all-gather_stream-0_stage-1_mesh-1d_barrier_centralized"
subroutine_root_id: 13
execution_probability: 1
execution_count: 1
instructions {
name: "all-gather_stream-0_stage-1_mesh-1d_barrier_centralized_coordinator_recv_from_6"
opcode: "recv"
instruction_id: 11
communication_groups {
group_ids: 6
}
}
instructions {
name: "all-gather_stream-0_stage-1_mesh-1d_barrier_centralized_coordinator_send_to_6"
opcode: "send"
instruction_id: 12
communication_groups {
group_ids: 6
}
operand_ids: 11
}
instructions {
name: "all-gather_stream-0_stage-1_mesh-1d_barrier_centralized_root_2"
opcode: "null"
instruction_id: 13
operand_ids: 12
}
}
}
instructions {
name: "all-gather_stream-0_stage-1_mesh-1d_cw_sendrecv_0"
opcode: "sendrecv"
instruction_id: 14
bytes_in: 20
bytes_out: 20
communication_groups {
group_ids: 6
group_ids: 6
}
operand_ids: 10
}
}
}
instructions {
name: "all-gather_stream-1_stage-0"
opcode: "all-gather"
instruction_id: 15
bytes_out: 20
communication_groups {
group_ids: 2
group_ids: 6
}
inner_subroutines {
name: "all-gather_stream-1_stage-0_mesh-1d"
subroutine_root_id: 20
execution_probability: 1
execution_count: 1
instructions {
name: "all-gather_stream-1_stage-0_mesh-1d_barrier"
opcode: "barrier"
instruction_id: 16
communication_groups {
group_ids: 2
group_ids: 6
}
inner_subroutines {
name: "all-gather_stream-1_stage-0_mesh-1d_barrier_centralized"
subroutine_root_id: 19
execution_probability: 1
execution_count: 1
instructions {
name: "all-gather_stream-1_stage-0_mesh-1d_barrier_centralized_coordinator_recv_from_6"
opcode: "recv"
instruction_id: 17
communication_groups {
group_ids: 6
}
}
instructions {
name: "all-gather_stream-1_stage-0_mesh-1d_barrier_centralized_coordinator_send_to_6"
opcode: "send"
instruction_id: 18
communication_groups {
group_ids: 6
}
operand_ids: 17
}
instructions {
name: "all-gather_stream-1_stage-0_mesh-1d_barrier_centralized_root_2"
opcode: "null"
instruction_id: 19
operand_ids: 18
}
}
}
instructions {
name: "all-gather_stream-1_stage-0_mesh-1d_cw_sendrecv_0"
opcode: "sendrecv"
instruction_id: 20
bytes_in: 10
bytes_out: 10
communication_groups {
group_ids: 6
group_ids: 6
}
operand_ids: 16
}
}
}
instructions {
name: "all-gather_stream-1_stage-1"
opcode: "all-gather"
instruction_id: 21
bytes_out: 40
communication_groups {
group_ids: 0
group_ids: 2
}
operand_ids: 15
inner_subroutines {
name: "all-gather_stream-1_stage-1_mesh-1d"
subroutine_root_id: 25
execution_probability: 1
execution_count: 1
instructions {
name: "all-gather_stream-1_stage-1_mesh-1d_barrier"
opcode: "barrier"
instruction_id: 22
communication_groups {
group_ids: 0
group_ids: 2
}
inner_subroutines {
name: "all-gather_stream-1_stage-1_mesh-1d_barrier_centralized"
subroutine_root_id: 24
execution_probability: 1
execution_count: 1
instructions {
name: "all-gather_stream-1_stage-1_mesh-1d_barrier_centralized_send_to_0"
opcode: "send"
instruction_id: 23
communication_groups {
group_ids: 0
}
}
instructions {
name: "all-gather_stream-1_stage-1_mesh-1d_barrier_centralized_recv_from_0"
opcode: "recv"
instruction_id: 24
communication_groups {
group_ids: 0
}
operand_ids: 23
}
}
}
instructions {
name: "all-gather_stream-1_stage-1_mesh-1d_ccw_sendrecv_0"
opcode: "sendrecv"
instruction_id: 25
bytes_in: 20
bytes_out: 20
communication_groups {
group_ids: 0
group_ids: 0
}
operand_ids: 22
}
}
}
instructions {
name: "all-gather_conc"
opcode: "all-gather"
instruction_id: 26
bytes_out: 160
communication_groups {
group_ids: 2
group_ids: 3
}
operand_ids: 9
operand_ids: 21
inner_subroutines {
name: "all-gather_conc_mesh-1d"
subroutine_root_id: 31
execution_probability: 1
execution_count: 1
instructions {
name: "all-gather_conc_mesh-1d_barrier"
opcode: "barrier"
instruction_id: 27
communication_groups {
group_ids: 2
group_ids: 3
}
inner_subroutines {
name: "all-gather_conc_mesh-1d_barrier_centralized"
subroutine_root_id: 30
execution_probability: 1
execution_count: 1
instructions {
name: "all-gather_conc_mesh-1d_barrier_centralized_coordinator_recv_from_3"
opcode: "recv"
instruction_id: 28
communication_groups {
group_ids: 3
}
}
instructions {
name: "all-gather_conc_mesh-1d_barrier_centralized_coordinator_send_to_3"
opcode: "send"
instruction_id: 29
communication_groups {
group_ids: 3
}
operand_ids: 28
}
instructions {
name: "all-gather_conc_mesh-1d_barrier_centralized_root_2"
opcode: "null"
instruction_id: 30
operand_ids: 29
}
}
}
instructions {
name: "all-gather_conc_mesh-1d_cw_sendrecv_0"
opcode: "sendrecv"
instruction_id: 31
bytes_in: 80
bytes_out: 80
communication_groups {
group_ids: 3
group_ids: 3
}
operand_ids: 27
}
}
}
}
)proto";
google::protobuf::TextFormat::ParseFromString(test_str,
&proto);
return proto;
} // NOLINT
// Tests expanding 1D-Mesh all-gather with barrier
TEST(Mesh2dAllGather, WithBarrier) {
auto graph = absl::make_unique<paragraph::Graph>("test_graph", 2);
auto sub = absl::make_unique<paragraph::Subroutine>(
"test_subroutine", graph.get());
auto sub_ptr = sub.get();
sub_ptr->SetId(3);
graph->SetEntrySubroutine(std::move(sub));
ASSERT_OK_AND_ASSIGN(auto instr_1, paragraph::Instruction::Create(
paragraph::Opcode::kDelay, "first_instruction", sub_ptr));
instr_1->SetOps(4);
ASSERT_OK_AND_ASSIGN(auto allgather,
paragraph::Instruction::Create(
paragraph::Opcode::kAllGather, "all-gather", sub_ptr));
allgather->SetBytesOut(160);
paragraph::CommunicationGroup allgather_group = {0, 1, 2, 3, 4, 5, 6, 7};
allgather->AppendCommunicationGroup(allgather_group);
ASSERT_OK_AND_ASSIGN(auto instr_3, paragraph::Instruction::Create(
paragraph::Opcode::kDelay, "last_instruction", sub_ptr, true));
instr_3->SetOps(4);
nlohmann::json config = R"(
{
"all-gather": {
"algorithm": "mesh-2d",
"concentration": 2,
"dimension_widths": [2, 2],
"barrier": {
"algorithm": "centralized"
}
}
}
)"_json;
ASSERT_OK_AND_ASSIGN(auto translators, paragraph::CreateTranslators(
paragraph::TranslatorType::kCollective, config));
EXPECT_OK(translators["all-gather"]->Translate(allgather));
paragraph::InstructionProto allgather_proto =
Mesh2dAllGather_with_barrier_test_proto();
EXPECT_TRUE(google::protobuf::util::MessageDifferencer::Equals(
allgather->ToProto().value(), allgather_proto));
}
paragraph::InstructionProto
Mesh2dAllGather_inconsecutive_proc_test_proto() {
paragraph::InstructionProto proto;
std::string test_str =
R"proto(
name: "all-gather"
opcode: "all-gather"
instruction_id: 2
bytes_out: 48
communication_groups {
group_ids: 0
group_ids: 2
group_ids: 4
}
inner_subroutines {
name: "all-gather_mesh-2d"
subroutine_root_id: 18
execution_probability: 1
execution_count: 1
instructions {
name: "all-gather_stream-0_stage-1"
opcode: "all-gather"
instruction_id: 4
bytes_out: 24
communication_groups {
group_ids: 0
group_ids: 2
group_ids: 4
}
inner_subroutines {
name: "all-gather_stream-0_stage-1_mesh-1d"
subroutine_root_id: 10
execution_probability: 1
execution_count: 1
instructions {
name: "all-gather_stream-0_stage-1_mesh-1d_ccw_sendrecv_0"
opcode: "sendrecv"
instruction_id: 5
bytes_in: 8
bytes_out: 8
communication_groups {
group_ids: 0
group_ids: 0
}
}
instructions {
name: "all-gather_stream-0_stage-1_mesh-1d_cw_sendrecv_0"
opcode: "sendrecv"
instruction_id: 6
bytes_in: 8
bytes_out: 8
communication_groups {
group_ids: 4
group_ids: 4
}
}
instructions {
name: "all-gather_stream-0_stage-1_mesh-1d_root_0"
opcode: "null"
instruction_id: 7
operand_ids: 6
operand_ids: 5
}
instructions {
name: "all-gather_stream-0_stage-1_mesh-1d_ccw_send_1"
opcode: "send"
instruction_id: 8
bytes_out: 8
communication_groups {
group_ids: 0
}
operand_ids: 7
}
instructions {
name: "all-gather_stream-0_stage-1_mesh-1d_cw_send_1"
opcode: "send"
instruction_id: 9
bytes_out: 8
communication_groups {
group_ids: 4
}
operand_ids: 7
}
instructions {
name: "all-gather_stream-0_stage-1_mesh-1d_root_1"
opcode: "null"
instruction_id: 10
operand_ids: 9
operand_ids: 8
}
}
}
instructions {
name: "all-gather_stream-1_stage-0"
opcode: "all-gather"
instruction_id: 11
bytes_out: 24
communication_groups {
group_ids: 0
group_ids: 2
group_ids: 4
}
inner_subroutines {
name: "all-gather_stream-1_stage-0_mesh-1d"
subroutine_root_id: 17
execution_probability: 1
execution_count: 1
instructions {
name: "all-gather_stream-1_stage-0_mesh-1d_ccw_sendrecv_0"
opcode: "sendrecv"
instruction_id: 12
bytes_in: 8
bytes_out: 8
communication_groups {
group_ids: 0
group_ids: 0
}
}
instructions {
name: "all-gather_stream-1_stage-0_mesh-1d_cw_sendrecv_0"
opcode: "sendrecv"
instruction_id: 13
bytes_in: 8
bytes_out: 8
communication_groups {
group_ids: 4
group_ids: 4
}
}
instructions {
name: "all-gather_stream-1_stage-0_mesh-1d_root_0"
opcode: "null"
instruction_id: 14
operand_ids: 13
operand_ids: 12
}
instructions {
name: "all-gather_stream-1_stage-0_mesh-1d_ccw_send_1"
opcode: "send"
instruction_id: 15
bytes_out: 8
communication_groups {
group_ids: 0
}
operand_ids: 14
}
instructions {
name: "all-gather_stream-1_stage-0_mesh-1d_cw_send_1"
opcode: "send"
instruction_id: 16
bytes_out: 8
communication_groups {
group_ids: 4
}
operand_ids: 14
}
instructions {
name: "all-gather_stream-1_stage-0_mesh-1d_root_1"
opcode: "null"
instruction_id: 17
operand_ids: 16
operand_ids: 15
}
}
}
instructions {
name: "all-gather_root"
opcode: "null"
instruction_id: 18
operand_ids: 4
operand_ids: 11
}
}
)proto";
google::protobuf::TextFormat::ParseFromString(test_str,
&proto);
return proto;
} // NOLINT
// Tests expanding 1D-Mesh all-gather
TEST(Mesh2dAllGather, InconsecutiveProcessors) {
auto graph = absl::make_unique<paragraph::Graph>("test_graph", 2);
auto sub = absl::make_unique<paragraph::Subroutine>(
"test_subroutine", graph.get());
auto sub_ptr = sub.get();
graph->SetEntrySubroutine(std::move(sub));
ASSERT_OK_AND_ASSIGN(auto instr_1, paragraph::Instruction::Create(
paragraph::Opcode::kDelay, "first_instruction", sub_ptr));
instr_1->SetOps(4);
ASSERT_OK_AND_ASSIGN(auto allgather,
paragraph::Instruction::Create(
paragraph::Opcode::kAllGather, "all-gather", sub_ptr));
allgather->SetBytesOut(48);
paragraph::CommunicationGroup allgather_group = {0, 2, 4};
allgather->AppendCommunicationGroup(allgather_group);
ASSERT_OK_AND_ASSIGN(auto instr_3, paragraph::Instruction::Create(
paragraph::Opcode::kDelay, "last_instruction", sub_ptr, true));
instr_3->SetOps(4);
nlohmann::json config = R"(
{
"all-gather": {
"algorithm": "mesh-2d",
"dimension_widths": [2, 3]
}
}
)"_json;
ASSERT_OK_AND_ASSIGN(auto translators, paragraph::CreateTranslators(
paragraph::TranslatorType::kCollective, config));
EXPECT_OK(translators["all-gather"]->Translate(allgather));
paragraph::InstructionProto allgather_proto =
Mesh2dAllGather_inconsecutive_proc_test_proto();
EXPECT_TRUE(google::protobuf::util::MessageDifferencer::Equals(
allgather->ToProto().value(), allgather_proto));
}
| 27.131937 | 99 | 0.607039 | [
"mesh"
] |
a893d3b7ca5f9dbdf97b510dd9efe34fe8026757 | 2,253 | cpp | C++ | codeforces/F - Two Pizzas/Accepted.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | 1 | 2022-02-11T16:55:36.000Z | 2022-02-11T16:55:36.000Z | codeforces/F - Two Pizzas/Accepted.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | null | null | null | codeforces/F - Two Pizzas/Accepted.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | null | null | null | /****************************************************************************************
* @author: kzvd4729 created: Jul/15/2020 21:20
* solution_verdict: Accepted language: GNU C++17
* run_time: 280 ms memory_used: 6300 KB
* problem: https://codeforces.com/contest/1185/problem/F
****************************************************************************************/
#include<iostream>
#include<vector>
#include<cstring>
#include<map>
#include<bitset>
#include<assert.h>
#include<algorithm>
#include<iomanip>
#include<cmath>
#include<set>
#include<queue>
#include<unordered_map>
#include<random>
#include<chrono>
#include<stack>
#include<deque>
#define endl '\n'
#define long long long
using namespace std;
const int N=(1<<10)+2;
int msk[100000+2],sub[N+2];
vector<pair<int,int> >v[N+2];
int main()
{
ios_base::sync_with_stdio(0);cin.tie(0);
int n,m;cin>>n>>m;
for(int i=1;i<=n;i++)
{
int f;cin>>f;int now=0;
while(f--)
{
int x;cin>>x;
now|=(1<<(x-1));
}
msk[i]=now;
}
for(int i=0;i<(1<<9);i++)
{
for(int j=1;j<=n;j++)
if((i&msk[j])==msk[j])sub[i]++;
}
for(int i=1;i<=m;i++)
{
int p,f;cin>>p>>f;int now=0;
while(f--)
{
int x;cin>>x;
now|=(1<<(x-1));
}
v[now].push_back({p,i});
}
for(int i=0;i<(1<<9);i++)
sort(v[i].begin(),v[i].end());
int mx=-1,a=1,b=2,p=0;
for(int i=0;i<(1<<9);i++)
{
if(v[i].size()>=2)
{
if(sub[i]>mx)mx=sub[i],p=v[i][0].first+v[i][1].first,a=v[i][0].second,b=v[i][1].second;
else if(sub[i]==mx&&v[i][0].first+v[i][1].first<p)
p=v[i][0].first+v[i][1].first,a=v[i][0].second,b=v[i][1].second;
}
if(v[i].size()==0)continue;
for(int j=i+1;j<(1<<9);j++)
{
if(v[j].size()==0)continue;
if(sub[(i|j)]>mx)mx=sub[(i|j)],p=v[i][0].first+v[j][0].first,a=v[i][0].second,b=v[j][0].second;
else if(sub[(i|j)]==mx&&v[i][0].first+v[j][0].first<p)
p=v[i][0].first+v[j][0].first,a=v[i][0].second,b=v[j][0].second;
}
}
cout<<a<<" "<<b<<endl;
return 0;
} | 28.1625 | 111 | 0.452286 | [
"vector"
] |
a893d768341ca7c2e826c35ef2476ebbfc165782 | 1,014 | cc | C++ | leetcode/162_find_peak_element.cc | norlanliu/algorithm | 1684db2631f259b4de567164b3ee866351e5b1b6 | [
"MIT"
] | null | null | null | leetcode/162_find_peak_element.cc | norlanliu/algorithm | 1684db2631f259b4de567164b3ee866351e5b1b6 | [
"MIT"
] | null | null | null | leetcode/162_find_peak_element.cc | norlanliu/algorithm | 1684db2631f259b4de567164b3ee866351e5b1b6 | [
"MIT"
] | null | null | null | /*
* =====================================================================================
*
* Filename: 162_find_peak_element.cc
*
* Description:
*
* Version: 1.0
* Created: 07/19/2015 09:39:01 PM
* Revision: none
* Compiler: gcc
*
* Author: (Qi Liu), liuqi.edward@gmail.com
* Organization: antq.com
*
* Copyright (c) 2015, Qi Liu.
* All rights reserved.
* =====================================================================================
*/
#include <vector>
#include <iostream>
using namespace std;
class Solution {
public:
int findPeakElement(vector<int>& nums) {
int head = 0, middle, next, tail=nums.size()-1;
while(head < tail) {
middle = (head + tail) / 2;
next = middle + 1;
if( nums[middle] >= nums[next] )
tail = middle;
else
head = next;
}
return head;
}
};
int main() {
Solution sln;
vector<int> nums = {1,2,3,2,1,5,6,7,8,9};
cout<<sln.findPeakElement(nums)<<endl;
return 0;
}
| 21.574468 | 88 | 0.470414 | [
"vector"
] |
a8a0256d9c8a21d41230bdf38906c2dbda89a516 | 5,238 | cpp | C++ | src/unity/toolkits/text/perplexity.cpp | shreyasvj25/turicreate | 32e84ca16aef8d04aff3d49ae9984bd49326bffd | [
"BSD-3-Clause"
] | 1 | 2018-12-15T20:03:51.000Z | 2018-12-15T20:03:51.000Z | src/unity/toolkits/text/perplexity.cpp | shreyasvj25/turicreate | 32e84ca16aef8d04aff3d49ae9984bd49326bffd | [
"BSD-3-Clause"
] | 1 | 2018-12-11T10:37:10.000Z | 2018-12-11T10:37:10.000Z | src/unity/toolkits/text/perplexity.cpp | shreyasvj25/turicreate | 32e84ca16aef8d04aff3d49ae9984bd49326bffd | [
"BSD-3-Clause"
] | 1 | 2019-01-12T01:07:34.000Z | 2019-01-12T01:07:34.000Z | /* Copyright © 2017 Apple Inc. All rights reserved.
*
* Use of this source code is governed by a BSD-3-clause license that can
* be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause
*/
#include <fstream>
#include <algorithm>
#include <iostream>
#include <cmath>
#include <parallel/pthread_tools.hpp>
#include <unity/lib/unity_sarray.hpp>
#include <unity/lib/flex_dict_view.hpp>
#include <unity/toolkits/text/topic_model.hpp>
#include <logger/assertions.hpp>
#include <unity/toolkits/util/indexed_sframe_tools.hpp>
#include <ml_data/ml_data.hpp>
#include <numerics/armadillo.hpp>
namespace turi {
namespace text {
/**
* Compute the perplexity of the provided documents given the provided
* topic model estimates. This implementation allows one to compute
* perplexity in the absence of any model object. One drawback is ome
* code duplication; the benefit is that it is standalone, not depending on the
* current implementation of the topic_model class.
*/
double perplexity(std::shared_ptr<sarray<flexible_type>> dataset,
const std::shared_ptr<sarray<flexible_type>> doc_topic_prob,
const std::shared_ptr<sarray<flexible_type>> word_topic_prob,
const std::shared_ptr<sarray<flexible_type>> vocabulary) {
DASSERT_EQ(dataset->size(), doc_topic_prob->size());
// Convert the SArray of vocabulary into std::vector
std::map<flexible_type, size_t> vocab;
auto vocab_reader = vocabulary->get_reader();
for (size_t seg = 0; seg < vocabulary->num_segments(); ++seg) {
auto iter = vocab_reader->begin(seg);
auto enditer = vocab_reader->end(seg);
while (iter != enditer) {
DASSERT_EQ(flex_type_enum_to_name((*iter).get_type()),
flex_type_enum_to_name(flex_type_enum::STRING));
size_t idx = vocab.size();
vocab[(*iter)] = idx;
++iter;
}
}
// Load the topics SArray into a vector of vectors
std::vector<std::vector<double>> phi(word_topic_prob->size());
auto phi_reader = word_topic_prob->get_reader();
size_t word_id = 0;
size_t num_topics = 0;
for (size_t seg = 0; seg < word_topic_prob->num_segments(); ++seg) {
auto iter = phi_reader->begin(seg);
auto enditer = phi_reader->end(seg);
while (iter != enditer) {
DASSERT_EQ(flex_type_enum_to_name((*iter).get_type()),
flex_type_enum_to_name(flex_type_enum::VECTOR));
phi[word_id] = (*iter).get<flex_vec>();
// Assume the number of topics is the length of the first vector.
if (word_id == 0)
num_topics = phi[word_id].size();
// Throw an error of the length of some vector doesn't match num_topics.
if (phi[word_id].size() != num_topics)
log_and_throw("Provided topic probability vectors do not have the same length.");
++word_id;
++iter;
}
}
// Prepare to iterate through documents
size_t num_segments = thread::cpu_count();
std::vector<double> llk_per_thread(num_segments);
std::vector<size_t> num_words_per_thread(num_segments);
auto theta_reader = doc_topic_prob->get_reader(num_segments);
auto doc_reader = dataset->get_reader(num_segments);
// Start iterating through documents
in_parallel([&](size_t thread_idx, size_t num_threads) {
// Prepare to iterate through document topics
auto theta_iter = theta_reader->begin(thread_idx);
auto theta_enditer = theta_reader->end(thread_idx);
auto doc_iter = doc_reader->begin(thread_idx);
auto doc_enditer = doc_reader->end(thread_idx);
// Start iterating through documents
while(doc_iter != doc_enditer && theta_iter != theta_enditer) {
if ((*theta_iter).get_type() == flex_type_enum::VECTOR &&
(*doc_iter).get_type() == flex_type_enum::DICT) {
// Get topic proportions
const flex_vec& theta_doc = *theta_iter;
const flex_dict& doc_dict = *doc_iter;
DASSERT_EQ(theta_doc.size(), num_topics);
for (size_t j = 0; j < doc_dict.size(); ++j) {
// Get word index and frequency
flexible_type word = doc_dict[j].first;
double freq = doc_dict[j].second.to<double>();
auto word_find_iter = vocab.find(word);
if (word_find_iter != vocab.end()) {
size_t word_id = word_find_iter->second;
// Compute Pr(word | theta, phi)
double prob = 0;
for (size_t k = 0; k < num_topics; ++k) {
DASSERT_LT(0.0, theta_doc[k]);
DASSERT_LT(0.0, phi[word_id][k]);
prob += theta_doc[k] * phi[word_id][k];
}
// Increment numerator and denominator of perplexity estimate
llk_per_thread[thread_idx] += freq * log(prob);
num_words_per_thread[thread_idx] += freq;
}
}
}
++theta_iter;
++doc_iter;
}
});
double llk = std::accumulate(llk_per_thread.begin(),
llk_per_thread.end(), 0.0);
size_t num_words = std::accumulate(num_words_per_thread.begin(),
num_words_per_thread.end(), 0.0);
return std::exp(- llk / num_words);
}
} // text
} // turicreate
| 36.124138 | 89 | 0.649294 | [
"object",
"vector",
"model"
] |
a8acb5e2f967af533c3cbb3437d22b02593a0123 | 1,121 | cpp | C++ | Node.cpp | hit-joseph/BattRAE | 04124138a5fdfd0f159b5480321648f8e63e5d73 | [
"BSD-3-Clause"
] | 9 | 2018-02-06T20:57:07.000Z | 2022-02-04T16:22:32.000Z | Node.cpp | hit-joseph/BattRAE | 04124138a5fdfd0f159b5480321648f8e63e5d73 | [
"BSD-3-Clause"
] | 2 | 2018-12-16T13:36:28.000Z | 2020-06-26T14:14:45.000Z | Node.cpp | hit-joseph/BattRAE | 04124138a5fdfd0f159b5480321648f8e63e5d73 | [
"BSD-3-Clause"
] | 3 | 2017-06-15T01:01:34.000Z | 2018-12-10T02:32:27.000Z | #include "Node.h"
Node::Node(lbfgsfloatval_t* vector, int dim, bool isLeaf){
this -> isLeaf = isLeaf;
this -> dim = dim;
this -> id = OOV;
this -> lChild = NULL;
this -> rChild = NULL;
this -> is_root = false;
this -> span.first = 0, this -> span.second = 0; // initial [0,0]
//{ allocate memory
__LBFGSALLOC__(v_vector, dim);
__LBFGSALLOC__(v_cerror, dim);
__LBFGSALLOC__(v_deriva, dim * dim);
__LBFGSALLOC__(v_oerror, 2 * dim);
__LBFGSALLOC__(v_perror, 2 * dim);
//}
//{ deal with leaves
if(isLeaf){// for leaves, the gradient set to be I
Map<VectorLBFGS>(v_vector, dim) =
Map<VectorLBFGS>(vector, dim);
Map<MatrixLBFGS>(v_deriva, dim, dim).setIdentity();
}else{
Map<VectorLBFGS>(v_vector, dim)
= Map<VectorLBFGS>(vector, dim);
Map<MatrixLBFGS>(v_deriva, dim, dim).setZero();
}
//}
}
Node::~Node(){
// recusive deleting
if(this -> lChild != NULL) delete this -> lChild;
if(this -> rChild != NULL) delete this -> rChild;
//{ free memory
__LBFGSFREE__(v_vector);
__LBFGSFREE__(v_cerror);
__LBFGSFREE__(v_deriva);
__LBFGSFREE__(v_oerror);
__LBFGSFREE__(v_perror);
//}
}
| 23.851064 | 66 | 0.664585 | [
"vector"
] |
a8b1fc2a8909efb87fd54734c31a0409ccec60d2 | 3,564 | cpp | C++ | source/platform/sdl/input_sdl.cpp | ZopharsDomain/GAMEBOYC-3DS-GameYob | 48723b5f7c8300ff6eb6bff441cc0527c7c65671 | [
"MIT"
] | 2 | 2022-01-19T09:57:43.000Z | 2022-01-19T09:57:53.000Z | source/platform/sdl/input_sdl.cpp | ZopharsDomain/GAMEBOYC-3DS-GameYob | 48723b5f7c8300ff6eb6bff441cc0527c7c65671 | [
"MIT"
] | null | null | null | source/platform/sdl/input_sdl.cpp | ZopharsDomain/GAMEBOYC-3DS-GameYob | 48723b5f7c8300ff6eb6bff441cc0527c7c65671 | [
"MIT"
] | null | null | null | #ifdef BACKEND_SDL
#include <string.h>
#include <vector>
#include "platform/common/config.h"
#include "platform/input.h"
#include <SDL2/SDL_events.h>
static KeyConfig defaultKeyConfig = {
"Main",
{FUNC_KEY_NONE}
};
static std::vector<int> bindings[NUM_FUNC_KEYS];
static bool pressed[NUM_FUNC_KEYS] = {false};
static bool held[NUM_FUNC_KEYS] = {false};
static bool forceReleased[NUM_FUNC_KEYS] = {false};
static const Uint8* keyState = NULL;
static int keyCount = 0;
void inputInit() {
keyState = SDL_GetKeyboardState(&keyCount);
defaultKeyConfig.funcKeys[SDL_SCANCODE_Z] = FUNC_KEY_A;
defaultKeyConfig.funcKeys[SDL_SCANCODE_X] = FUNC_KEY_B;
defaultKeyConfig.funcKeys[SDL_SCANCODE_LEFT] = FUNC_KEY_LEFT;
defaultKeyConfig.funcKeys[SDL_SCANCODE_RIGHT] = FUNC_KEY_RIGHT;
defaultKeyConfig.funcKeys[SDL_SCANCODE_UP] = FUNC_KEY_UP;
defaultKeyConfig.funcKeys[SDL_SCANCODE_DOWN] = FUNC_KEY_DOWN;
defaultKeyConfig.funcKeys[SDL_SCANCODE_RETURN] = FUNC_KEY_START;
defaultKeyConfig.funcKeys[SDL_SCANCODE_RSHIFT] = FUNC_KEY_SELECT;
defaultKeyConfig.funcKeys[SDL_SCANCODE_M] = FUNC_KEY_MENU;
defaultKeyConfig.funcKeys[SDL_SCANCODE_P] = FUNC_KEY_MENU_PAUSE;
defaultKeyConfig.funcKeys[SDL_SCANCODE_S] = FUNC_KEY_SAVE;
defaultKeyConfig.funcKeys[SDL_SCANCODE_Q] = FUNC_KEY_AUTO_A;
defaultKeyConfig.funcKeys[SDL_SCANCODE_W] = FUNC_KEY_AUTO_B;
defaultKeyConfig.funcKeys[SDL_SCANCODE_LCTRL] = FUNC_KEY_FAST_FORWARD;
defaultKeyConfig.funcKeys[SDL_SCANCODE_LALT] = FUNC_KEY_FAST_FORWARD_TOGGLE;
defaultKeyConfig.funcKeys[SDL_SCANCODE_RCTRL] = FUNC_KEY_SCALE;
defaultKeyConfig.funcKeys[SDL_SCANCODE_RALT] = FUNC_KEY_RESET;
defaultKeyConfig.funcKeys[SDL_SCANCODE_BACKSPACE] = FUNC_KEY_SCREENSHOT;
}
void inputCleanup() {
}
void inputUpdate() {
for(int funcKey = 0; funcKey < NUM_FUNC_KEYS; funcKey++) {
bool currPressed = false;
for(int realKey : bindings[funcKey]) {
if(keyState[realKey] == 1) {
currPressed = true;
break;
}
}
if(currPressed) {
pressed[funcKey] = !held[funcKey];
held[funcKey] = true;
} else {
pressed[funcKey] = false;
held[funcKey] = currPressed;
forceReleased[funcKey] = false;
}
}
}
bool inputKeyHeld(int key) {
return key >= 0 && key < NUM_FUNC_KEYS && !forceReleased[key] && held[key];
}
bool inputKeyPressed(int key) {
return key >= 0 && key < NUM_FUNC_KEYS && !forceReleased[key] && pressed[key];
}
void inputKeyRelease(int key) {
if(key >= 0 && key < NUM_FUNC_KEYS) {
forceReleased[key] = true;
}
}
void inputReleaseAll() {
for(int i = 0; i < NUM_FUNC_KEYS; i++) {
inputKeyRelease(i);
}
}
u16 inputGetMotionSensorX() {
return 0x7FF;
}
u16 inputGetMotionSensorY() {
return 0x7FF;
}
int inputGetKeyCount() {
return keyCount;
}
bool inputIsValidKey(int keyIndex) {
return keyIndex >= 0 && keyIndex < keyCount && keyIndex != SDL_SCANCODE_RETURN2 && strlen(SDL_GetScancodeName((SDL_Scancode) keyIndex)) > 0;
}
const char* inputGetKeyName(int keyIndex) {
return SDL_GetScancodeName((SDL_Scancode) keyIndex);
}
KeyConfig inputGetDefaultKeyConfig() {
return defaultKeyConfig;
}
void inputLoadKeyConfig(KeyConfig* keyConfig) {
for(int i = 0; i < NUM_FUNC_KEYS; i++) {
bindings[i].clear();
}
for(int i = 0; i < keyCount; i++) {
bindings[keyConfig->funcKeys[i]].push_back(i);
}
}
#endif
| 27.84375 | 144 | 0.691639 | [
"vector"
] |
a8b5da3f5934b3d1dc2dd298c58d1cadbaa56a23 | 237,144 | cc | C++ | src/parser/pregenerated/ugrammar.cc | jcbaillie/urbi | fb17359b2838cdf8d3c0858abb141e167a9d4bdb | [
"BSD-3-Clause"
] | 16 | 2016-05-10T05:50:58.000Z | 2021-10-05T22:16:13.000Z | src/parser/pregenerated/ugrammar.cc | jcbaillie/urbi | fb17359b2838cdf8d3c0858abb141e167a9d4bdb | [
"BSD-3-Clause"
] | 7 | 2016-09-05T10:08:33.000Z | 2019-02-13T10:51:07.000Z | src/parser/pregenerated/ugrammar.cc | jcbaillie/urbi | fb17359b2838cdf8d3c0858abb141e167a9d4bdb | [
"BSD-3-Clause"
] | 4 | 2017-03-30T14:13:58.000Z | 2022-01-22T13:13:07.000Z | // A Bison parser, made by GNU Bison 3.1.
// Skeleton implementation for Bison LALR(1) parsers in C++
// Copyright (C) 2002-2015, 2018 Free Software Foundation, Inc.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
// As a special exception, you may create a larger work that contains
// part or all of the Bison parser skeleton and distribute that work
// under terms of your choice, so long as that work isn't itself a
// parser generator using the skeleton or a modified version thereof
// as a parser skeleton. Alternatively, if you modify or redistribute
// the parser skeleton itself, you may (at your option) remove this
// special exception, which will cause the skeleton and the resulting
// Bison output files to be licensed under the GNU General Public
// License without this special exception.
// This special exception was added by the Free Software Foundation in
// version 2.2 of Bison.
// First part of user declarations.
#line 37 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:407
# ifndef YY_NULLPTR
# if defined __cplusplus && 201103L <= __cplusplus
# define YY_NULLPTR nullptr
# else
# define YY_NULLPTR 0
# endif
# endif
#include "ugrammar.hh"
// User implementation prologue.
#line 51 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:415
// Unqualified %code blocks.
#line 62 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:416
#include <string>
#include <iostream>
#include <boost/bind.hpp>
#include <boost/lexical_cast.hpp>
#include <libport/cassert>
#include <libport/finally.hh>
#include <libport/format.hh>
#include <libport/separate.hh>
#include <ast/all.hh>
#include <ast/new-clone.hh>
#include <ast/parametric-ast.hh>
#include <ast/print.hh>
#include <parser/parse.hh>
#include <parser/parser-impl.hh>
#include <parser/utoken.hh>
#if defined __GNUC__ && __GNUC__ == 4 && __GNUC_MINOR__ == 4
# pragma GCC diagnostic ignored "-Wuninitialized"
#endif
#define MAKE(Kind, ...) \
up.factory().make_ ## Kind(__VA_ARGS__)
namespace
{
static void
modifiers_add(parser::ParserImpl& up, const ast::loc& loc,
ast::modifiers_type& mods,
const ::ast::Factory::modifier_type& mod)
{
if (libport::has(mods, mod.first))
up.warn(loc,
libport::format("modifier redefined: %s", mod.first));
mods[mod.first] = mod.second;
}
static void
assocs_add(parser::ParserImpl& /*up*/, const ast::loc& /*loc*/,
ast::dictionary_elts_type& mods,
const ast::dictionary_elt_type& mod)
{
// FIXME: check for duplicate literal keys?
// if (libport::has(mods, mod.first))
// up.warn(loc,
// libport::format("key redefined: %s", mod.first));
mods.push_back(mod);
}
/// Use the scanner in the right parser::ParserImpl.
static
inline
yy::parser::symbol_type
yylex(parser::ParserImpl& up)
{
boost::optional< ::yy::parser::token_type>&
initial_token(up.initial_token_get());
if (initial_token)
{
::yy::parser::token_type res = initial_token.get();
initial_token = boost::optional< ::yy::parser::token_type>();
return yy::parser::symbol_type(res, yy::location());
}
return up.scanner_.yylex();
}
} // anon namespace
# define REQUIRE_IDENTIFIER(Loc, Effective, Expected) \
do { \
if (Effective != libport::Symbol(Expected)) \
up.error(Loc, \
libport::format("unexpected `%s', expecting `%s'", \
Effective, Expected)); \
} while (false)
#line 136 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:416
#ifndef YY_
# if defined YYENABLE_NLS && YYENABLE_NLS
# if ENABLE_NLS
# include <libintl.h> // FIXME: INFRINGES ON USER NAME SPACE.
# define YY_(msgid) dgettext ("bison-runtime", msgid)
# endif
# endif
# ifndef YY_
# define YY_(msgid) msgid
# endif
#endif
// Whether we are compiled with exception support.
#ifndef YY_EXCEPTIONS
# if defined __GNUC__ && !defined __EXCEPTIONS
# define YY_EXCEPTIONS 0
# else
# define YY_EXCEPTIONS 1
# endif
#endif
#define YYRHSLOC(Rhs, K) ((Rhs)[K].location)
/* YYLLOC_DEFAULT -- Set CURRENT to span from RHS[1] to RHS[N].
If N is 0, then set CURRENT to the empty location which ends
the previous symbol: RHS[0] (always defined). */
# ifndef YYLLOC_DEFAULT
# define YYLLOC_DEFAULT(Current, Rhs, N) \
do \
if (N) \
{ \
(Current).begin = YYRHSLOC (Rhs, 1).begin; \
(Current).end = YYRHSLOC (Rhs, N).end; \
} \
else \
{ \
(Current).begin = (Current).end = YYRHSLOC (Rhs, 0).end; \
} \
while (/*CONSTCOND*/ false)
# endif
// Suppress unused-variable warnings by "using" E.
#define YYUSE(E) ((void) (E))
// Enable debugging if requested.
#if YYDEBUG
// A pseudo ostream that takes yydebug_ into account.
# define YYCDEBUG if (yydebug_) (*yycdebug_)
# define YY_SYMBOL_PRINT(Title, Symbol) \
do { \
if (yydebug_) \
{ \
*yycdebug_ << Title << ' '; \
yy_print_ (*yycdebug_, Symbol); \
*yycdebug_ << '\n'; \
} \
} while (false)
# define YY_REDUCE_PRINT(Rule) \
do { \
if (yydebug_) \
yy_reduce_print_ (Rule); \
} while (false)
# define YY_STACK_PRINT() \
do { \
if (yydebug_) \
yystack_print_ (); \
} while (false)
#else // !YYDEBUG
# define YYCDEBUG if (false) std::cerr
# define YY_SYMBOL_PRINT(Title, Symbol) YYUSE (Symbol)
# define YY_REDUCE_PRINT(Rule) static_cast<void> (0)
# define YY_STACK_PRINT() static_cast<void> (0)
#endif // !YYDEBUG
#define yyerrok (yyerrstatus_ = 0)
#define yyclearin (yyla.clear ())
#define YYACCEPT goto yyacceptlab
#define YYABORT goto yyabortlab
#define YYERROR goto yyerrorlab
#define YYRECOVERING() (!!yyerrstatus_)
namespace yy {
#line 231 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:491
/* Return YYSTR after stripping away unnecessary quotes and
backslashes, so that it's suitable for yyerror. The heuristic is
that double-quoting is unnecessary unless the string contains an
apostrophe, a comma, or backslash (other than backslash-backslash).
YYSTR is taken from yytname. */
std::string
parser::yytnamerr_ (const char *yystr)
{
if (*yystr == '"')
{
std::string yyr = "";
char const *yyp = yystr;
for (;;)
switch (*++yyp)
{
case '\'':
case ',':
goto do_not_strip_quotes;
case '\\':
if (*++yyp != '\\')
goto do_not_strip_quotes;
// Fall through.
default:
yyr += *yyp;
break;
case '"':
return yyr;
}
do_not_strip_quotes: ;
}
return yystr;
}
/// Build a parser object.
parser::parser (::parser::ParserImpl& up_yyarg)
:
#if YYDEBUG
yydebug_ (false),
yycdebug_ (&std::cerr),
#endif
up (up_yyarg)
{}
parser::~parser ()
{}
/*---------------.
| Symbol types. |
`---------------*/
// by_state.
parser::by_state::by_state ()
: state (empty_state)
{}
parser::by_state::by_state (const by_state& other)
: state (other.state)
{}
void
parser::by_state::clear ()
{
state = empty_state;
}
void
parser::by_state::move (by_state& that)
{
state = that.state;
that.clear ();
}
parser::by_state::by_state (state_type s)
: state (s)
{}
parser::symbol_number_type
parser::by_state::type_get () const
{
if (state == empty_state)
return empty_symbol;
else
return yystos_[state];
}
parser::stack_symbol_type::stack_symbol_type ()
{}
parser::stack_symbol_type::stack_symbol_type (const stack_symbol_type& that)
: super_type (that.state, that.location)
{
switch (that.type_get ())
{
case 168: // event_match
value.copy< ast::EventMatch > (that.value);
break;
case 143: // case
value.copy< ast::Factory::case_type > (that.value);
break;
case 142: // cases
value.copy< ast::Factory::cases_type > (that.value);
break;
case 136: // modifier
value.copy< ast::Factory::modifier_type > (that.value);
break;
case 174: // rel-ops
value.copy< ast::Factory::relations_type > (that.value);
break;
case 187: // formal
value.copy< ast::Formal > (that.value);
break;
case 188: // formals.1
case 189: // formals.0
case 190: // formals
value.copy< ast::Formals* > (that.value);
break;
case 144: // catches.1
value.copy< ast::catches_type > (that.value);
break;
case 158: // assoc
value.copy< ast::dictionary_elt_type > (that.value);
break;
case 159: // assocs.1
case 160: // assocs
value.copy< ast::dictionary_elts_type > (that.value);
break;
case 127: // protos.1
case 128: // protos
case 162: // tuple.exps
case 163: // tuple
case 164: // bitor-exps
case 165: // bitor-exps.1
case 177: // claims
case 178: // claims.1
case 179: // exps
case 180: // exps.1
case 181: // exps.2
case 182: // args
case 183: // args.opt
value.copy< ast::exps_type* > (that.value);
break;
case 41: // ","
case 42: // ";"
case 43: // "&"
case 44: // "|"
case 45: // "every"
case 46: // "for"
case 47: // "loop"
case 48: // "while"
case 49: // "at"
value.copy< ast::flavor_type > (that.value);
break;
case 137: // modifiers
value.copy< ast::modifiers_type > (that.value);
break;
case 135: // k1_id
value.copy< ast::rCall > (that.value);
break;
case 147: // catch
value.copy< ast::rCatch > (that.value);
break;
case 161: // dictionary
value.copy< ast::rDictionary > (that.value);
break;
case 116: // root
case 117: // root_exp
case 118: // root_exps
case 120: // cstmt.opt
case 121: // cstmt
case 122: // stmt.opt
case 123: // stmt
case 124: // block
case 126: // proto
case 129: // exp
case 138: // primary-exp
case 140: // else.opt
case 141: // onleave.opt
case 148: // catch.opt
case 149: // finally.opt
case 154: // bitor-exp
case 155: // new
case 156: // float-exp
case 166: // literal-exp
case 169: // guard.opt
case 170: // tilda.opt
case 171: // unary-exp
case 173: // rel-exp
case 175: // exp.opt
case 185: // typespec
case 186: // typespec.opt
value.copy< ast::rExp > (that.value);
break;
case 152: // lvalue
value.copy< ast::rLValue > (that.value);
break;
case 145: // match
case 146: // match.opt
value.copy< ast::rMatch > (that.value);
break;
case 119: // stmts
case 139: // default.opt
value.copy< ast::rNary > (that.value);
break;
case 130: // id.0
case 131: // id.1
case 184: // identifiers
value.copy< ast::symbols_type > (that.value);
break;
case 134: // routine
case 151: // detach
value.copy< bool > (that.value);
break;
case 50: // "identifier"
case 62: // "^="
case 63: // "-="
case 64: // "%="
case 65: // "+="
case 66: // "/="
case 67: // "*="
case 75: // "new"
case 84: // "!"
case 85: // "bitand"
case 86: // "bitor"
case 87: // "^"
case 88: // "compl"
case 89: // ">>"
case 90: // "<<"
case 91: // "-"
case 92: // "%"
case 93: // "+"
case 94: // "/"
case 95: // "*"
case 96: // "**"
case 97: // "=~="
case 98: // "=="
case 99: // "==="
case 100: // ">="
case 101: // ">"
case 102: // "<="
case 103: // "<"
case 104: // "!="
case 105: // "!=="
case 106: // "~="
case 107: // "&&"
case 108: // "||"
case 133: // event_or_function
case 153: // id
case 172: // rel-op
value.copy< libport::Symbol > (that.value);
break;
case 76: // "angle"
case 77: // "duration"
case 78: // "float"
case 157: // duration
value.copy< libport::ufloat > (that.value);
break;
case 80: // "string"
case 167: // string
value.copy< std::string > (that.value);
break;
case 176: // unsigned
value.copy< unsigned > (that.value);
break;
default:
break;
}
}
parser::stack_symbol_type::stack_symbol_type (state_type s, symbol_type& that)
: super_type (s, that.location)
{
switch (that.type_get ())
{
case 168: // event_match
value.move< ast::EventMatch > (that.value);
break;
case 143: // case
value.move< ast::Factory::case_type > (that.value);
break;
case 142: // cases
value.move< ast::Factory::cases_type > (that.value);
break;
case 136: // modifier
value.move< ast::Factory::modifier_type > (that.value);
break;
case 174: // rel-ops
value.move< ast::Factory::relations_type > (that.value);
break;
case 187: // formal
value.move< ast::Formal > (that.value);
break;
case 188: // formals.1
case 189: // formals.0
case 190: // formals
value.move< ast::Formals* > (that.value);
break;
case 144: // catches.1
value.move< ast::catches_type > (that.value);
break;
case 158: // assoc
value.move< ast::dictionary_elt_type > (that.value);
break;
case 159: // assocs.1
case 160: // assocs
value.move< ast::dictionary_elts_type > (that.value);
break;
case 127: // protos.1
case 128: // protos
case 162: // tuple.exps
case 163: // tuple
case 164: // bitor-exps
case 165: // bitor-exps.1
case 177: // claims
case 178: // claims.1
case 179: // exps
case 180: // exps.1
case 181: // exps.2
case 182: // args
case 183: // args.opt
value.move< ast::exps_type* > (that.value);
break;
case 41: // ","
case 42: // ";"
case 43: // "&"
case 44: // "|"
case 45: // "every"
case 46: // "for"
case 47: // "loop"
case 48: // "while"
case 49: // "at"
value.move< ast::flavor_type > (that.value);
break;
case 137: // modifiers
value.move< ast::modifiers_type > (that.value);
break;
case 135: // k1_id
value.move< ast::rCall > (that.value);
break;
case 147: // catch
value.move< ast::rCatch > (that.value);
break;
case 161: // dictionary
value.move< ast::rDictionary > (that.value);
break;
case 116: // root
case 117: // root_exp
case 118: // root_exps
case 120: // cstmt.opt
case 121: // cstmt
case 122: // stmt.opt
case 123: // stmt
case 124: // block
case 126: // proto
case 129: // exp
case 138: // primary-exp
case 140: // else.opt
case 141: // onleave.opt
case 148: // catch.opt
case 149: // finally.opt
case 154: // bitor-exp
case 155: // new
case 156: // float-exp
case 166: // literal-exp
case 169: // guard.opt
case 170: // tilda.opt
case 171: // unary-exp
case 173: // rel-exp
case 175: // exp.opt
case 185: // typespec
case 186: // typespec.opt
value.move< ast::rExp > (that.value);
break;
case 152: // lvalue
value.move< ast::rLValue > (that.value);
break;
case 145: // match
case 146: // match.opt
value.move< ast::rMatch > (that.value);
break;
case 119: // stmts
case 139: // default.opt
value.move< ast::rNary > (that.value);
break;
case 130: // id.0
case 131: // id.1
case 184: // identifiers
value.move< ast::symbols_type > (that.value);
break;
case 134: // routine
case 151: // detach
value.move< bool > (that.value);
break;
case 50: // "identifier"
case 62: // "^="
case 63: // "-="
case 64: // "%="
case 65: // "+="
case 66: // "/="
case 67: // "*="
case 75: // "new"
case 84: // "!"
case 85: // "bitand"
case 86: // "bitor"
case 87: // "^"
case 88: // "compl"
case 89: // ">>"
case 90: // "<<"
case 91: // "-"
case 92: // "%"
case 93: // "+"
case 94: // "/"
case 95: // "*"
case 96: // "**"
case 97: // "=~="
case 98: // "=="
case 99: // "==="
case 100: // ">="
case 101: // ">"
case 102: // "<="
case 103: // "<"
case 104: // "!="
case 105: // "!=="
case 106: // "~="
case 107: // "&&"
case 108: // "||"
case 133: // event_or_function
case 153: // id
case 172: // rel-op
value.move< libport::Symbol > (that.value);
break;
case 76: // "angle"
case 77: // "duration"
case 78: // "float"
case 157: // duration
value.move< libport::ufloat > (that.value);
break;
case 80: // "string"
case 167: // string
value.move< std::string > (that.value);
break;
case 176: // unsigned
value.move< unsigned > (that.value);
break;
default:
break;
}
// that is emptied.
that.type = empty_symbol;
}
parser::stack_symbol_type&
parser::stack_symbol_type::operator= (const stack_symbol_type& that)
{
state = that.state;
switch (that.type_get ())
{
case 168: // event_match
value.copy< ast::EventMatch > (that.value);
break;
case 143: // case
value.copy< ast::Factory::case_type > (that.value);
break;
case 142: // cases
value.copy< ast::Factory::cases_type > (that.value);
break;
case 136: // modifier
value.copy< ast::Factory::modifier_type > (that.value);
break;
case 174: // rel-ops
value.copy< ast::Factory::relations_type > (that.value);
break;
case 187: // formal
value.copy< ast::Formal > (that.value);
break;
case 188: // formals.1
case 189: // formals.0
case 190: // formals
value.copy< ast::Formals* > (that.value);
break;
case 144: // catches.1
value.copy< ast::catches_type > (that.value);
break;
case 158: // assoc
value.copy< ast::dictionary_elt_type > (that.value);
break;
case 159: // assocs.1
case 160: // assocs
value.copy< ast::dictionary_elts_type > (that.value);
break;
case 127: // protos.1
case 128: // protos
case 162: // tuple.exps
case 163: // tuple
case 164: // bitor-exps
case 165: // bitor-exps.1
case 177: // claims
case 178: // claims.1
case 179: // exps
case 180: // exps.1
case 181: // exps.2
case 182: // args
case 183: // args.opt
value.copy< ast::exps_type* > (that.value);
break;
case 41: // ","
case 42: // ";"
case 43: // "&"
case 44: // "|"
case 45: // "every"
case 46: // "for"
case 47: // "loop"
case 48: // "while"
case 49: // "at"
value.copy< ast::flavor_type > (that.value);
break;
case 137: // modifiers
value.copy< ast::modifiers_type > (that.value);
break;
case 135: // k1_id
value.copy< ast::rCall > (that.value);
break;
case 147: // catch
value.copy< ast::rCatch > (that.value);
break;
case 161: // dictionary
value.copy< ast::rDictionary > (that.value);
break;
case 116: // root
case 117: // root_exp
case 118: // root_exps
case 120: // cstmt.opt
case 121: // cstmt
case 122: // stmt.opt
case 123: // stmt
case 124: // block
case 126: // proto
case 129: // exp
case 138: // primary-exp
case 140: // else.opt
case 141: // onleave.opt
case 148: // catch.opt
case 149: // finally.opt
case 154: // bitor-exp
case 155: // new
case 156: // float-exp
case 166: // literal-exp
case 169: // guard.opt
case 170: // tilda.opt
case 171: // unary-exp
case 173: // rel-exp
case 175: // exp.opt
case 185: // typespec
case 186: // typespec.opt
value.copy< ast::rExp > (that.value);
break;
case 152: // lvalue
value.copy< ast::rLValue > (that.value);
break;
case 145: // match
case 146: // match.opt
value.copy< ast::rMatch > (that.value);
break;
case 119: // stmts
case 139: // default.opt
value.copy< ast::rNary > (that.value);
break;
case 130: // id.0
case 131: // id.1
case 184: // identifiers
value.copy< ast::symbols_type > (that.value);
break;
case 134: // routine
case 151: // detach
value.copy< bool > (that.value);
break;
case 50: // "identifier"
case 62: // "^="
case 63: // "-="
case 64: // "%="
case 65: // "+="
case 66: // "/="
case 67: // "*="
case 75: // "new"
case 84: // "!"
case 85: // "bitand"
case 86: // "bitor"
case 87: // "^"
case 88: // "compl"
case 89: // ">>"
case 90: // "<<"
case 91: // "-"
case 92: // "%"
case 93: // "+"
case 94: // "/"
case 95: // "*"
case 96: // "**"
case 97: // "=~="
case 98: // "=="
case 99: // "==="
case 100: // ">="
case 101: // ">"
case 102: // "<="
case 103: // "<"
case 104: // "!="
case 105: // "!=="
case 106: // "~="
case 107: // "&&"
case 108: // "||"
case 133: // event_or_function
case 153: // id
case 172: // rel-op
value.copy< libport::Symbol > (that.value);
break;
case 76: // "angle"
case 77: // "duration"
case 78: // "float"
case 157: // duration
value.copy< libport::ufloat > (that.value);
break;
case 80: // "string"
case 167: // string
value.copy< std::string > (that.value);
break;
case 176: // unsigned
value.copy< unsigned > (that.value);
break;
default:
break;
}
location = that.location;
return *this;
}
template <typename Base>
void
parser::yy_destroy_ (const char* yymsg, basic_symbol<Base>& yysym) const
{
if (yymsg)
YY_SYMBOL_PRINT (yymsg, yysym);
}
#if YYDEBUG
template <typename Base>
void
parser::yy_print_ (std::ostream& yyo,
const basic_symbol<Base>& yysym) const
{
std::ostream& yyoutput = yyo;
YYUSE (yyoutput);
symbol_number_type yytype = yysym.type_get ();
// Avoid a (spurious) G++ 4.8 warning about "array subscript is
// below array bounds".
if (yysym.empty ())
std::abort ();
yyo << (yytype < yyntokens_ ? "token" : "nterm")
<< ' ' << yytname_[yytype] << " ("
<< yysym.location << ": ";
switch (yytype)
{
case 41: // ","
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< ast::flavor_type > (); }
#line 986 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 42: // ";"
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< ast::flavor_type > (); }
#line 993 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 43: // "&"
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< ast::flavor_type > (); }
#line 1000 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 44: // "|"
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< ast::flavor_type > (); }
#line 1007 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 45: // "every"
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< ast::flavor_type > (); }
#line 1014 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 46: // "for"
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< ast::flavor_type > (); }
#line 1021 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 47: // "loop"
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< ast::flavor_type > (); }
#line 1028 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 48: // "while"
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< ast::flavor_type > (); }
#line 1035 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 49: // "at"
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< ast::flavor_type > (); }
#line 1042 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 50: // "identifier"
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< libport::Symbol > (); }
#line 1049 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 62: // "^="
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< libport::Symbol > (); }
#line 1056 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 63: // "-="
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< libport::Symbol > (); }
#line 1063 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 64: // "%="
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< libport::Symbol > (); }
#line 1070 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 65: // "+="
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< libport::Symbol > (); }
#line 1077 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 66: // "/="
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< libport::Symbol > (); }
#line 1084 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 67: // "*="
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< libport::Symbol > (); }
#line 1091 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 75: // "new"
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< libport::Symbol > (); }
#line 1098 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 76: // "angle"
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< libport::ufloat > (); }
#line 1105 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 77: // "duration"
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< libport::ufloat > (); }
#line 1112 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 78: // "float"
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< libport::ufloat > (); }
#line 1119 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 80: // "string"
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< std::string > (); }
#line 1126 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 84: // "!"
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< libport::Symbol > (); }
#line 1133 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 85: // "bitand"
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< libport::Symbol > (); }
#line 1140 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 86: // "bitor"
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< libport::Symbol > (); }
#line 1147 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 87: // "^"
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< libport::Symbol > (); }
#line 1154 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 88: // "compl"
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< libport::Symbol > (); }
#line 1161 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 89: // ">>"
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< libport::Symbol > (); }
#line 1168 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 90: // "<<"
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< libport::Symbol > (); }
#line 1175 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 91: // "-"
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< libport::Symbol > (); }
#line 1182 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 92: // "%"
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< libport::Symbol > (); }
#line 1189 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 93: // "+"
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< libport::Symbol > (); }
#line 1196 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 94: // "/"
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< libport::Symbol > (); }
#line 1203 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 95: // "*"
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< libport::Symbol > (); }
#line 1210 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 96: // "**"
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< libport::Symbol > (); }
#line 1217 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 97: // "=~="
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< libport::Symbol > (); }
#line 1224 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 98: // "=="
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< libport::Symbol > (); }
#line 1231 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 99: // "==="
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< libport::Symbol > (); }
#line 1238 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 100: // ">="
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< libport::Symbol > (); }
#line 1245 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 101: // ">"
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< libport::Symbol > (); }
#line 1252 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 102: // "<="
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< libport::Symbol > (); }
#line 1259 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 103: // "<"
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< libport::Symbol > (); }
#line 1266 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 104: // "!="
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< libport::Symbol > (); }
#line 1273 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 105: // "!=="
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< libport::Symbol > (); }
#line 1280 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 106: // "~="
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< libport::Symbol > (); }
#line 1287 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 107: // "&&"
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< libport::Symbol > (); }
#line 1294 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 108: // "||"
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< libport::Symbol > (); }
#line 1301 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 116: // root
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< ast::rExp > (); }
#line 1308 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 117: // root_exp
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< ast::rExp > (); }
#line 1315 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 118: // root_exps
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< ast::rExp > (); }
#line 1322 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 119: // stmts
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< ast::rNary > (); }
#line 1329 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 120: // cstmt.opt
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< ast::rExp > (); }
#line 1336 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 121: // cstmt
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< ast::rExp > (); }
#line 1343 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 122: // stmt.opt
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< ast::rExp > (); }
#line 1350 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 123: // stmt
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< ast::rExp > (); }
#line 1357 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 124: // block
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< ast::rExp > (); }
#line 1364 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 126: // proto
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< ast::rExp > (); }
#line 1371 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 127: // protos.1
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< ast::exps_type* > (); }
#line 1378 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 128: // protos
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< ast::exps_type* > (); }
#line 1385 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 129: // exp
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< ast::rExp > (); }
#line 1392 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 130: // id.0
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< ast::symbols_type > (); }
#line 1399 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 131: // id.1
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< ast::symbols_type > (); }
#line 1406 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 133: // event_or_function
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< libport::Symbol > (); }
#line 1413 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 134: // routine
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< bool > (); }
#line 1420 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 135: // k1_id
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< ast::rCall > (); }
#line 1427 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 136: // modifier
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< ast::Factory::modifier_type > (); }
#line 1434 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 137: // modifiers
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< ast::modifiers_type > (); }
#line 1441 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 138: // primary-exp
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< ast::rExp > (); }
#line 1448 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 139: // default.opt
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< ast::rNary > (); }
#line 1455 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 140: // else.opt
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< ast::rExp > (); }
#line 1462 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 141: // onleave.opt
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< ast::rExp > (); }
#line 1469 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 142: // cases
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< ast::Factory::cases_type > (); }
#line 1476 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 143: // case
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< ast::Factory::case_type > (); }
#line 1483 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 144: // catches.1
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< ast::catches_type > (); }
#line 1490 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 145: // match
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< ast::rMatch > (); }
#line 1497 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 146: // match.opt
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< ast::rMatch > (); }
#line 1504 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 147: // catch
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< ast::rCatch > (); }
#line 1511 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 148: // catch.opt
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< ast::rExp > (); }
#line 1518 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 149: // finally.opt
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< ast::rExp > (); }
#line 1525 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 151: // detach
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< bool > (); }
#line 1532 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 152: // lvalue
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< ast::rLValue > (); }
#line 1539 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 153: // id
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< libport::Symbol > (); }
#line 1546 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 154: // bitor-exp
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< ast::rExp > (); }
#line 1553 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 155: // new
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< ast::rExp > (); }
#line 1560 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 156: // float-exp
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< ast::rExp > (); }
#line 1567 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 157: // duration
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< libport::ufloat > (); }
#line 1574 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 158: // assoc
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< ast::dictionary_elt_type > (); }
#line 1581 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 159: // assocs.1
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< ast::dictionary_elts_type > (); }
#line 1588 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 160: // assocs
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< ast::dictionary_elts_type > (); }
#line 1595 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 161: // dictionary
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< ast::rDictionary > (); }
#line 1602 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 162: // tuple.exps
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< ast::exps_type* > (); }
#line 1609 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 163: // tuple
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< ast::exps_type* > (); }
#line 1616 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 164: // bitor-exps
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< ast::exps_type* > (); }
#line 1623 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 165: // bitor-exps.1
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< ast::exps_type* > (); }
#line 1630 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 166: // literal-exp
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< ast::rExp > (); }
#line 1637 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 167: // string
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< std::string > (); }
#line 1644 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 168: // event_match
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< ast::EventMatch > (); }
#line 1651 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 169: // guard.opt
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< ast::rExp > (); }
#line 1658 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 170: // tilda.opt
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< ast::rExp > (); }
#line 1665 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 171: // unary-exp
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< ast::rExp > (); }
#line 1672 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 172: // rel-op
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< libport::Symbol > (); }
#line 1679 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 173: // rel-exp
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< ast::rExp > (); }
#line 1686 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 174: // rel-ops
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< ast::Factory::relations_type > (); }
#line 1693 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 175: // exp.opt
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< ast::rExp > (); }
#line 1700 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 176: // unsigned
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< unsigned > (); }
#line 1707 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 177: // claims
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< ast::exps_type* > (); }
#line 1714 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 178: // claims.1
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< ast::exps_type* > (); }
#line 1721 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 179: // exps
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< ast::exps_type* > (); }
#line 1728 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 180: // exps.1
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< ast::exps_type* > (); }
#line 1735 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 181: // exps.2
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< ast::exps_type* > (); }
#line 1742 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 182: // args
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< ast::exps_type* > (); }
#line 1749 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 183: // args.opt
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< ast::exps_type* > (); }
#line 1756 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 184: // identifiers
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< ast::symbols_type > (); }
#line 1763 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 185: // typespec
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< ast::rExp > (); }
#line 1770 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 186: // typespec.opt
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< ast::rExp > (); }
#line 1777 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 187: // formal
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< ast::Formal > (); }
#line 1784 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 188: // formals.1
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< ast::Formals* > (); }
#line 1791 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 189: // formals.0
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< ast::Formals* > (); }
#line 1798 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
case 190: // formals
#line 205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:644
{ debug_stream() << libport::deref << yysym.value.template as< ast::Formals* > (); }
#line 1805 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:644
break;
default:
break;
}
yyo << ')';
}
#endif
void
parser::yypush_ (const char* m, state_type s, symbol_type& sym)
{
stack_symbol_type t (s, sym);
yypush_ (m, t);
}
void
parser::yypush_ (const char* m, stack_symbol_type& s)
{
if (m)
YY_SYMBOL_PRINT (m, s);
yystack_.push (s);
}
void
parser::yypop_ (unsigned n)
{
yystack_.pop (n);
}
#if YYDEBUG
std::ostream&
parser::debug_stream () const
{
return *yycdebug_;
}
void
parser::set_debug_stream (std::ostream& o)
{
yycdebug_ = &o;
}
parser::debug_level_type
parser::debug_level () const
{
return yydebug_;
}
void
parser::set_debug_level (debug_level_type l)
{
yydebug_ = l;
}
#endif // YYDEBUG
parser::state_type
parser::yy_lr_goto_state_ (state_type yystate, int yysym)
{
int yyr = yypgoto_[yysym - yyntokens_] + yystate;
if (0 <= yyr && yyr <= yylast_ && yycheck_[yyr] == yystate)
return yytable_[yyr];
else
return yydefgoto_[yysym - yyntokens_];
}
bool
parser::yy_pact_value_is_default_ (int yyvalue)
{
return yyvalue == yypact_ninf_;
}
bool
parser::yy_table_value_is_error_ (int yyvalue)
{
return yyvalue == yytable_ninf_;
}
int
parser::parse ()
{
// State.
int yyn;
/// Length of the RHS of the rule being reduced.
int yylen = 0;
// Error handling.
int yynerrs_ = 0;
int yyerrstatus_ = 0;
/// The lookahead symbol.
symbol_type yyla;
/// The locations where the error started and ended.
stack_symbol_type yyerror_range[3];
/// The return value of parse ().
int yyresult;
#if YY_EXCEPTIONS
try
#endif // YY_EXCEPTIONS
{
YYCDEBUG << "Starting parse\n";
// User initialization code.
#line 55 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:746
{
// Saved when exiting the start symbol.
up.scanner_.loc = up.loc_;
}
#line 1921 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:746
/* Initialize the stack. The initial state will be set in
yynewstate, since the latter expects the semantical and the
location values to have been already stored, initialize these
stacks with a primary value. */
yystack_.clear ();
yypush_ (YY_NULLPTR, 0, yyla);
// A new symbol was pushed on the stack.
yynewstate:
YYCDEBUG << "Entering state " << yystack_[0].state << '\n';
// Accept?
if (yystack_[0].state == yyfinal_)
goto yyacceptlab;
goto yybackup;
// Backup.
yybackup:
// Try to take a decision without lookahead.
yyn = yypact_[yystack_[0].state];
if (yy_pact_value_is_default_ (yyn))
goto yydefault;
// Read a lookahead token.
if (yyla.empty ())
{
YYCDEBUG << "Reading a token: ";
#if YY_EXCEPTIONS
try
#endif // YY_EXCEPTIONS
{
symbol_type yylookahead (yylex (up));
yyla.move (yylookahead);
}
#if YY_EXCEPTIONS
catch (const syntax_error& yyexc)
{
error (yyexc);
goto yyerrlab1;
}
#endif // YY_EXCEPTIONS
}
YY_SYMBOL_PRINT ("Next token is", yyla);
/* If the proper action on seeing token YYLA.TYPE is to reduce or
to detect an error, take that action. */
yyn += yyla.type_get ();
if (yyn < 0 || yylast_ < yyn || yycheck_[yyn] != yyla.type_get ())
goto yydefault;
// Reduce or error.
yyn = yytable_[yyn];
if (yyn <= 0)
{
if (yy_table_value_is_error_ (yyn))
goto yyerrlab;
yyn = -yyn;
goto yyreduce;
}
// Count tokens shifted since error; after three, turn off error status.
if (yyerrstatus_)
--yyerrstatus_;
// Shift the lookahead token.
yypush_ ("Shifting", yyn, yyla);
goto yynewstate;
/*-----------------------------------------------------------.
| yydefault -- do the default action for the current state. |
`-----------------------------------------------------------*/
yydefault:
yyn = yydefact_[yystack_[0].state];
if (yyn == 0)
goto yyerrlab;
goto yyreduce;
/*-----------------------------.
| yyreduce -- Do a reduction. |
`-----------------------------*/
yyreduce:
yylen = yyr2_[yyn];
{
stack_symbol_type yylhs;
yylhs.state = yy_lr_goto_state_ (yystack_[yylen].state, yyr1_[yyn]);
/* Variants are always initialized to an empty instance of the
correct type. The default '$$ = $1' action is NOT applied
when using variants. */
switch (yyr1_[yyn])
{
case 168: // event_match
yylhs.value.build< ast::EventMatch > ();
break;
case 143: // case
yylhs.value.build< ast::Factory::case_type > ();
break;
case 142: // cases
yylhs.value.build< ast::Factory::cases_type > ();
break;
case 136: // modifier
yylhs.value.build< ast::Factory::modifier_type > ();
break;
case 174: // rel-ops
yylhs.value.build< ast::Factory::relations_type > ();
break;
case 187: // formal
yylhs.value.build< ast::Formal > ();
break;
case 188: // formals.1
case 189: // formals.0
case 190: // formals
yylhs.value.build< ast::Formals* > ();
break;
case 144: // catches.1
yylhs.value.build< ast::catches_type > ();
break;
case 158: // assoc
yylhs.value.build< ast::dictionary_elt_type > ();
break;
case 159: // assocs.1
case 160: // assocs
yylhs.value.build< ast::dictionary_elts_type > ();
break;
case 127: // protos.1
case 128: // protos
case 162: // tuple.exps
case 163: // tuple
case 164: // bitor-exps
case 165: // bitor-exps.1
case 177: // claims
case 178: // claims.1
case 179: // exps
case 180: // exps.1
case 181: // exps.2
case 182: // args
case 183: // args.opt
yylhs.value.build< ast::exps_type* > ();
break;
case 41: // ","
case 42: // ";"
case 43: // "&"
case 44: // "|"
case 45: // "every"
case 46: // "for"
case 47: // "loop"
case 48: // "while"
case 49: // "at"
yylhs.value.build< ast::flavor_type > ();
break;
case 137: // modifiers
yylhs.value.build< ast::modifiers_type > ();
break;
case 135: // k1_id
yylhs.value.build< ast::rCall > ();
break;
case 147: // catch
yylhs.value.build< ast::rCatch > ();
break;
case 161: // dictionary
yylhs.value.build< ast::rDictionary > ();
break;
case 116: // root
case 117: // root_exp
case 118: // root_exps
case 120: // cstmt.opt
case 121: // cstmt
case 122: // stmt.opt
case 123: // stmt
case 124: // block
case 126: // proto
case 129: // exp
case 138: // primary-exp
case 140: // else.opt
case 141: // onleave.opt
case 148: // catch.opt
case 149: // finally.opt
case 154: // bitor-exp
case 155: // new
case 156: // float-exp
case 166: // literal-exp
case 169: // guard.opt
case 170: // tilda.opt
case 171: // unary-exp
case 173: // rel-exp
case 175: // exp.opt
case 185: // typespec
case 186: // typespec.opt
yylhs.value.build< ast::rExp > ();
break;
case 152: // lvalue
yylhs.value.build< ast::rLValue > ();
break;
case 145: // match
case 146: // match.opt
yylhs.value.build< ast::rMatch > ();
break;
case 119: // stmts
case 139: // default.opt
yylhs.value.build< ast::rNary > ();
break;
case 130: // id.0
case 131: // id.1
case 184: // identifiers
yylhs.value.build< ast::symbols_type > ();
break;
case 134: // routine
case 151: // detach
yylhs.value.build< bool > ();
break;
case 50: // "identifier"
case 62: // "^="
case 63: // "-="
case 64: // "%="
case 65: // "+="
case 66: // "/="
case 67: // "*="
case 75: // "new"
case 84: // "!"
case 85: // "bitand"
case 86: // "bitor"
case 87: // "^"
case 88: // "compl"
case 89: // ">>"
case 90: // "<<"
case 91: // "-"
case 92: // "%"
case 93: // "+"
case 94: // "/"
case 95: // "*"
case 96: // "**"
case 97: // "=~="
case 98: // "=="
case 99: // "==="
case 100: // ">="
case 101: // ">"
case 102: // "<="
case 103: // "<"
case 104: // "!="
case 105: // "!=="
case 106: // "~="
case 107: // "&&"
case 108: // "||"
case 133: // event_or_function
case 153: // id
case 172: // rel-op
yylhs.value.build< libport::Symbol > ();
break;
case 76: // "angle"
case 77: // "duration"
case 78: // "float"
case 157: // duration
yylhs.value.build< libport::ufloat > ();
break;
case 80: // "string"
case 167: // string
yylhs.value.build< std::string > ();
break;
case 176: // unsigned
yylhs.value.build< unsigned > ();
break;
default:
break;
}
// Default location.
{
slice<stack_symbol_type, stack_type> slice (yystack_, yylen);
YYLLOC_DEFAULT (yylhs.location, slice, yylen);
yyerror_range[1].location = yylhs.location;
}
// Perform the reduction.
YY_REDUCE_PRINT (yyn);
#if YY_EXCEPTIONS
try
#endif // YY_EXCEPTIONS
{
switch (yyn)
{
case 2:
#line 314 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{
// Remove the reference from yystack by swaping with a 0 intrusive
// pointer.
aver(up.result_.get() == 0);
std::swap(up.result_, yystack_[0].value.as< ast::rExp > ());
up.loc_ = yylhs.location;
YYACCEPT;
}
#line 2240 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 3:
#line 328 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rExp > () = 0; }
#line 2246 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 4:
#line 329 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ std::swap(yylhs.value.as< ast::rExp > (), yystack_[0].value.as< ast::rExp > ()); }
#line 2252 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 5:
#line 330 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ std::swap(yylhs.value.as< ast::rExp > (), yystack_[0].value.as< ast::rExp > ()); }
#line 2258 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 6:
#line 336 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rExp > () = new ast::Stmt(yylhs.location, yystack_[0].value.as< ast::flavor_type > (), yystack_[1].value.as< ast::rExp > ()); }
#line 2264 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 7:
#line 337 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rExp > () = new ast::Stmt(yylhs.location, yystack_[0].value.as< ast::flavor_type > (), yystack_[1].value.as< ast::rExp > ()); }
#line 2270 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 8:
#line 338 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rExp > () = new ast::Stmt(yylhs.location, ast::flavor_none, yystack_[1].value.as< ast::rExp > ()); }
#line 2276 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 9:
#line 339 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rExp > () = 0; }
#line 2282 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 10:
#line 340 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rExp > () = 0; }
#line 2288 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 11:
#line 341 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rExp > () = 0; }
#line 2294 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 12:
#line 346 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rExp > () = yystack_[0].value.as< ast::rNary > (); }
#line 2300 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 13:
#line 358 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rNary > () = MAKE(nary, yylhs.location, yystack_[0].value.as< ast::rExp > ()); }
#line 2306 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 14:
#line 359 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rNary > () = MAKE(nary, yylhs.location, yystack_[2].value.as< ast::rNary > (), yystack_[1].location, yystack_[1].value.as< ast::flavor_type > (), yystack_[0].value.as< ast::rExp > ()); }
#line 2312 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 15:
#line 360 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rNary > () = MAKE(nary, yylhs.location, yystack_[2].value.as< ast::rNary > (), yystack_[1].location, yystack_[1].value.as< ast::flavor_type > (), yystack_[0].value.as< ast::rExp > ()); }
#line 2318 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 16:
#line 368 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rExp > () = MAKE(noop, yylhs.location); }
#line 2324 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 17:
#line 369 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ std::swap(yylhs.value.as< ast::rExp > (), yystack_[0].value.as< ast::rExp > ()); }
#line 2330 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 18:
#line 370 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rExp > () = MAKE(bin, yylhs.location, yystack_[0].value.as< ast::flavor_type > (), yystack_[1].value.as< ast::rExp > (), MAKE(noop, yystack_[0].location)); }
#line 2336 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 19:
#line 375 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ assert(yystack_[0].value.as< ast::rExp > ()); std::swap(yylhs.value.as< ast::rExp > (), yystack_[0].value.as< ast::rExp > ()); }
#line 2342 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 20:
#line 376 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rExp > () = MAKE(bin, yylhs.location, yystack_[1].value.as< ast::flavor_type > (), yystack_[2].value.as< ast::rExp > (), yystack_[0].value.as< ast::rExp > ()); }
#line 2348 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 21:
#line 377 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rExp > () = MAKE(bin, yylhs.location, yystack_[1].value.as< ast::flavor_type > (), yystack_[2].value.as< ast::rExp > (), yystack_[0].value.as< ast::rExp > ()); }
#line 2354 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 22:
#line 387 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rExp > () = MAKE(noop, yylhs.location); }
#line 2360 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 23:
#line 388 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ std::swap(yylhs.value.as< ast::rExp > (), yystack_[0].value.as< ast::rExp > ()); }
#line 2366 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 24:
#line 394 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{
yylhs.value.as< ast::rExp > () = new ast::TaggedStmt(yylhs.location, yystack_[2].value.as< ast::rExp > (), MAKE(scope, yylhs.location, yystack_[0].value.as< ast::rExp > ()));
}
#line 2374 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 25:
#line 404 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ std::swap(yylhs.value.as< ast::rExp > (), yystack_[0].value.as< ast::rExp > ()); }
#line 2380 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 26:
#line 408 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rExp > () = MAKE(strip, yystack_[1].value.as< ast::rNary > ()); }
#line 2386 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 27:
#line 409 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rExp > () = MAKE(noop, yylhs.location); }
#line 2392 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 28:
#line 413 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rExp > () = MAKE(noop, yylhs.location); }
#line 2398 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 33:
#line 435 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ std::swap(yylhs.value.as< ast::rExp > (), yystack_[0].value.as< ast::rExp > ()); }
#line 2404 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 34:
#line 441 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::exps_type* > () = new ast::exps_type(1, yystack_[0].value.as< ast::rExp > ()); }
#line 2410 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 35:
#line 442 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ std::swap(yylhs.value.as< ast::exps_type* > (), yystack_[2].value.as< ast::exps_type* > ()); *yylhs.value.as< ast::exps_type* > () << yystack_[0].value.as< ast::rExp > (); }
#line 2416 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 36:
#line 447 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::exps_type* > () = 0; }
#line 2422 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 37:
#line 448 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ std::swap(yylhs.value.as< ast::exps_type* > (), yystack_[0].value.as< ast::exps_type* > ()); }
#line 2428 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 38:
#line 454 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{
yylhs.value.as< ast::rExp > () = MAKE(class, yylhs.location, yystack_[2].value.as< ast::rLValue > (), yystack_[1].value.as< ast::exps_type* > (), yystack_[0].value.as< ast::rExp > (), false);
}
#line 2436 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 39:
#line 463 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{
ast::rClass c = MAKE(class, yylhs.location, yystack_[2].value.as< ast::rLValue > (), yystack_[1].value.as< ast::exps_type* > (), yystack_[0].value.as< ast::rExp > (), true).unsafe_cast<ast::Class>();
c->is_package_set(true);
yylhs.value.as< ast::rExp > () = c;
}
#line 2446 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 40:
#line 478 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{}
#line 2452 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 41:
#line 479 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ std::swap(yylhs.value.as< ast::symbols_type > (), yystack_[1].value.as< ast::symbols_type > ()); }
#line 2458 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 42:
#line 483 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::symbols_type > () << yystack_[0].value.as< libport::Symbol > (); }
#line 2464 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 43:
#line 484 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ std::swap(yylhs.value.as< ast::symbols_type > (), yystack_[2].value.as< ast::symbols_type > ()); yylhs.value.as< ast::symbols_type > () << yystack_[0].value.as< libport::Symbol > (); }
#line 2470 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 44:
#line 490 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{
yylhs.value.as< ast::rExp > () = MAKE(enum, yylhs.location, yystack_[3].value.as< libport::Symbol > (), yystack_[1].value.as< ast::symbols_type > ());
}
#line 2478 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 45:
#line 501 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{
REQUIRE_IDENTIFIER(yystack_[0].location, yystack_[0].value.as< libport::Symbol > (), "from");
}
#line 2486 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 46:
#line 510 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{
yylhs.value.as< libport::Symbol > () = SYMBOL(function);
}
#line 2494 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 47:
#line 514 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{
REQUIRE_IDENTIFIER(yystack_[0].location, yystack_[0].value.as< libport::Symbol > (), "event");
yylhs.value.as< libport::Symbol > () = SYMBOL(event);
}
#line 2503 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 48:
#line 524 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{
REQUIRE_IDENTIFIER(yystack_[1].location, yystack_[1].value.as< libport::Symbol > (), "object");
yylhs.value.as< ast::rExp > () = MAKE(external_object, yylhs.location, yystack_[0].value.as< libport::Symbol > ());
}
#line 2512 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 49:
#line 530 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{
yylhs.value.as< ast::rExp > () = MAKE(external_var, yylhs.location, yystack_[4].value.as< libport::Symbol > (), yystack_[2].value.as< libport::Symbol > (), yystack_[0].value.as< libport::Symbol > ());
}
#line 2520 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 50:
#line 536 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{
yylhs.value.as< ast::rExp > () = MAKE(external_event_or_function,
yylhs.location, yystack_[8].value.as< libport::Symbol > (), yystack_[6].value.as< unsigned > (), yystack_[4].value.as< libport::Symbol > (), yystack_[2].value.as< libport::Symbol > (), yystack_[0].value.as< libport::Symbol > ());
}
#line 2529 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 51:
#line 547 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{
ast::rExp e = yystack_[0].value.as< ast::rLValue > ();
ast::rCall c = yystack_[0].value.as< ast::rLValue > ().unsafe_cast<ast::Call>();
libport::Symbol s = c->name_get();
bool isStar = (s==SYMBOL(STAR));
if (isStar)
{
e = c->target_get();
// s is irrelevant in that case
}
else
{ // We must replace last call with a getslot
ast::rExp tgt = c->target_get();
if (c->target_implicit())
e = MAKE(call, yylhs.location, c->target_get(), SYMBOL(findSlot),
MAKE(string, yylhs.location, s));
else
e = MAKE(get_slot, yylhs.location, tgt, s);
}
ast::LocalDeclaration* ae
= new ast::LocalDeclaration(yylhs.location, s, e);
ae->is_star_set(isStar);
ae->is_import_set(true);
yylhs.value.as< ast::rExp > () = ae;
}
#line 2559 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 52:
#line 588 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{
yylhs.value.as< ast::rExp > () = new ast::Emit(yylhs.location, yystack_[3].value.as< ast::rExp > (), yystack_[1].value.as< ast::exps_type* > (), yystack_[0].value.as< ast::rExp > ());
}
#line 2567 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 53:
#line 600 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< bool > () = true; }
#line 2573 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 54:
#line 601 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< bool > () = false; }
#line 2579 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 55:
#line 608 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{
// Compiled as "var name = function args stmt".
yylhs.value.as< ast::rExp > () = new ast::Declaration(yylhs.location, yystack_[2].value.as< ast::rCall > (),
MAKE(routine, yylhs.location, yystack_[3].value.as< bool > (), yystack_[1].location, yystack_[1].value.as< ast::Formals* > (), yystack_[0].value.as< ast::rExp > ()));
}
#line 2589 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 56:
#line 614 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{
if (yystack_[3].value.as< libport::Symbol > () == SYMBOL(get) || yystack_[3].value.as< libport::Symbol > () == SYMBOL(set))
{
yylhs.value.as< ast::rExp > () = MAKE(define_setter_getter, yylhs.location,
libport::Symbol("o" + std::string(yystack_[3].value.as< libport::Symbol > ())), yystack_[2].value.as< libport::Symbol > (),
MAKE(routine, yylhs.location, false, yystack_[1].location, yystack_[1].value.as< ast::Formals* > (), yystack_[0].value.as< ast::rExp > ()));
}
else
{
REQUIRE_IDENTIFIER(yylhs.location, yystack_[3].value.as< libport::Symbol > (), "get or set");
yylhs.value.as< ast::rExp > () = MAKE(nil);
}
}
#line 2607 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 57:
#line 660 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rCall > () = MAKE(call, yylhs.location, yystack_[0].value.as< libport::Symbol > ()); }
#line 2613 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 58:
#line 661 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rCall > () = MAKE(call, yylhs.location, new ast::This(yystack_[2].location), yystack_[0].value.as< libport::Symbol > ()); }
#line 2619 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 59:
#line 662 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rCall > () = MAKE(call, yylhs.location, ast::rExp(yystack_[2].value.as< ast::rCall > ()), yystack_[0].value.as< libport::Symbol > ()); }
#line 2625 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 60:
#line 674 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{
yylhs.value.as< ast::Factory::modifier_type > ().first = yystack_[2].value.as< libport::Symbol > ();
yylhs.value.as< ast::Factory::modifier_type > ().second = yystack_[0].value.as< ast::rExp > ();
}
#line 2634 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 61:
#line 683 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{
modifiers_add(up, yystack_[0].location, yylhs.value.as< ast::modifiers_type > (), yystack_[0].value.as< ast::Factory::modifier_type > ());
}
#line 2642 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 62:
#line 687 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{
std::swap(yylhs.value.as< ast::modifiers_type > (), yystack_[1].value.as< ast::modifiers_type > ());
modifiers_add(up, yystack_[0].location, yylhs.value.as< ast::modifiers_type > (), yystack_[0].value.as< ast::Factory::modifier_type > ());
}
#line 2651 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 63:
#line 704 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{
yylhs.value.as< ast::rExp > () = MAKE(assign, yylhs.location, yystack_[2].value.as< ast::rExp > (), yystack_[0].value.as< ast::rExp > ());
}
#line 2659 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 64:
#line 708 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{
yylhs.value.as< ast::rExp > () = MAKE(assign, yylhs.location, yystack_[3].value.as< ast::rExp > (), yystack_[1].value.as< ast::rExp > (), yystack_[0].value.as< ast::modifiers_type > ());
}
#line 2667 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 65:
#line 723 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rExp > () = new ast::OpAssignment(yystack_[1].location, yystack_[2].value.as< ast::rLValue > (), yystack_[0].value.as< ast::rExp > (), yystack_[1].value.as< libport::Symbol > ()); }
#line 2673 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 66:
#line 724 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rExp > () = new ast::OpAssignment(yystack_[1].location, yystack_[2].value.as< ast::rLValue > (), yystack_[0].value.as< ast::rExp > (), yystack_[1].value.as< libport::Symbol > ()); }
#line 2679 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 67:
#line 725 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rExp > () = new ast::OpAssignment(yystack_[1].location, yystack_[2].value.as< ast::rLValue > (), yystack_[0].value.as< ast::rExp > (), yystack_[1].value.as< libport::Symbol > ()); }
#line 2685 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 68:
#line 726 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rExp > () = new ast::OpAssignment(yystack_[1].location, yystack_[2].value.as< ast::rLValue > (), yystack_[0].value.as< ast::rExp > (), yystack_[1].value.as< libport::Symbol > ()); }
#line 2691 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 69:
#line 727 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rExp > () = new ast::OpAssignment(yystack_[1].location, yystack_[2].value.as< ast::rLValue > (), yystack_[0].value.as< ast::rExp > (), yystack_[1].value.as< libport::Symbol > ()); }
#line 2697 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 70:
#line 728 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rExp > () = new ast::OpAssignment(yystack_[1].location, yystack_[2].value.as< ast::rLValue > (), yystack_[0].value.as< ast::rExp > (), yystack_[1].value.as< libport::Symbol > ()); }
#line 2703 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 71:
#line 736 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rExp > () = new ast::Decrementation(yylhs.location, yystack_[1].value.as< ast::rLValue > (), true); }
#line 2709 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 72:
#line 737 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rExp > () = new ast::Incrementation(yylhs.location, yystack_[1].value.as< ast::rLValue > (), true); }
#line 2715 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 73:
#line 749 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{
yylhs.value.as< ast::rExp > () = new ast::Property(yylhs.location, yystack_[2].value.as< ast::rLValue > ()->call(), yystack_[0].value.as< libport::Symbol > ());
}
#line 2723 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 74:
#line 760 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{
yylhs.value.as< ast::rExp > () = MAKE(at, yylhs.location, yystack_[7].location, yystack_[7].value.as< ast::flavor_type > (), yystack_[6].value.as< ast::symbols_type > (), yystack_[4].value.as< ast::rExp > (), yystack_[1].value.as< ast::rExp > (), yystack_[0].value.as< ast::rExp > (), yystack_[3].value.as< ast::rExp > ());
}
#line 2731 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 75:
#line 764 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{
yylhs.value.as< ast::rExp > () = MAKE(at_event, yylhs.location, yystack_[6].location, yystack_[6].value.as< ast::flavor_type > (), yystack_[5].value.as< ast::symbols_type > (), yystack_[3].value.as< ast::EventMatch > (), yystack_[1].value.as< ast::rExp > (), yystack_[0].value.as< ast::rExp > ());
}
#line 2739 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 76:
#line 768 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{
yylhs.value.as< ast::rExp > () = MAKE(every, yylhs.location, yystack_[4].location, yystack_[4].value.as< ast::flavor_type > (), yystack_[2].value.as< ast::rExp > (), yystack_[0].value.as< ast::rExp > ());
}
#line 2747 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 77:
#line 772 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{
yylhs.value.as< ast::rExp > () = MAKE(if, yylhs.location, yystack_[3].value.as< ast::rNary > (), yystack_[1].value.as< ast::rExp > (), yystack_[0].value.as< ast::rExp > ());
}
#line 2755 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 78:
#line 776 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{
yylhs.value.as< ast::rExp > () = MAKE(freezeif, yylhs.location, yystack_[3].value.as< ast::rExp > (), yystack_[0].value.as< ast::rExp > (), yystack_[2].value.as< ast::rExp > ());
}
#line 2763 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 79:
#line 780 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{
yylhs.value.as< ast::rExp > () = MAKE(freezeif_event, yylhs.location, yystack_[2].value.as< ast::EventMatch > (), yystack_[0].value.as< ast::rExp > ());
}
#line 2771 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 80:
#line 784 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{
yylhs.value.as< ast::rExp > () = MAKE(stopif, yylhs.location, yystack_[3].value.as< ast::rExp > (), yystack_[0].value.as< ast::rExp > (), yystack_[2].value.as< ast::rExp > ());
}
#line 2779 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 81:
#line 788 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{
yylhs.value.as< ast::rExp > () = MAKE(stopif_event, yylhs.location, yystack_[2].value.as< ast::EventMatch > (), yystack_[0].value.as< ast::rExp > ());
}
#line 2787 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 82:
#line 792 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{
yylhs.value.as< ast::rExp > () = MAKE(switch, yystack_[5].location, yystack_[5].value.as< ast::rExp > (), yystack_[2].value.as< ast::Factory::cases_type > (), yystack_[1].value.as< ast::rNary > ());
}
#line 2795 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 83:
#line 796 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{
yylhs.value.as< ast::rExp > () = MAKE(timeout, yylhs.location,
yystack_[5].value.as< ast::rExp > (), yystack_[3].value.as< ast::rExp > (), yystack_[2].value.as< ast::rExp > (), yystack_[1].value.as< ast::rExp > (), yystack_[0].value.as< ast::rExp > ());
}
#line 2804 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 84:
#line 801 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{
yylhs.value.as< ast::rExp > () = new ast::Return(yylhs.location, yystack_[0].value.as< ast::rExp > ());
}
#line 2812 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 85:
#line 805 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{
yylhs.value.as< ast::rExp > () = new ast::Break(yylhs.location);
}
#line 2820 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 86:
#line 809 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{
yylhs.value.as< ast::rExp > () = new ast::Continue(yylhs.location);
}
#line 2828 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 87:
#line 813 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{
yylhs.value.as< ast::rExp > () = MAKE(waituntil, yylhs.location, yystack_[2].value.as< ast::rExp > (), yystack_[1].value.as< ast::rExp > ());
}
#line 2836 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 88:
#line 817 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{
yylhs.value.as< ast::rExp > () = MAKE(waituntil_event, yylhs.location, yystack_[1].value.as< ast::EventMatch > ());
}
#line 2844 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 89:
#line 821 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{
yylhs.value.as< ast::rExp > () = MAKE(whenever, yylhs.location, yystack_[4].value.as< ast::rExp > (), yystack_[1].value.as< ast::rExp > (), yystack_[0].value.as< ast::rExp > (), yystack_[3].value.as< ast::rExp > ());
}
#line 2852 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 90:
#line 825 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{
yylhs.value.as< ast::rExp > () = MAKE(whenever_event, yylhs.location, yystack_[3].value.as< ast::EventMatch > (), yystack_[1].value.as< ast::rExp > (), yystack_[0].value.as< ast::rExp > ());
}
#line 2860 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 91:
#line 841 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rNary > () = 0; }
#line 2866 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 92:
#line 842 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ std::swap(yylhs.value.as< ast::rNary > (), yystack_[0].value.as< ast::rNary > ()); }
#line 2872 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 93:
#line 847 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rExp > () = 0; }
#line 2878 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 94:
#line 848 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ std::swap(yylhs.value.as< ast::rExp > (), yystack_[0].value.as< ast::rExp > ()); }
#line 2884 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 95:
#line 854 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rExp > () = 0; }
#line 2890 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 96:
#line 855 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ std::swap(yylhs.value.as< ast::rExp > (), yystack_[0].value.as< ast::rExp > ()); }
#line 2896 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 97:
#line 865 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{}
#line 2902 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 98:
#line 866 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ std::swap(yylhs.value.as< ast::Factory::cases_type > (), yystack_[1].value.as< ast::Factory::cases_type > ()); yylhs.value.as< ast::Factory::cases_type > () << yystack_[0].value.as< ast::Factory::case_type > (); }
#line 2908 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 99:
#line 872 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::Factory::case_type > () = ::ast::Factory::case_type(yystack_[2].value.as< ast::rMatch > (), yystack_[0].value.as< ast::rNary > ()); }
#line 2914 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 100:
#line 881 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::catches_type > () = ast::catches_type(); yylhs.value.as< ast::catches_type > () << yystack_[0].value.as< ast::rCatch > (); }
#line 2920 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 101:
#line 882 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ std::swap(yylhs.value.as< ast::catches_type > (), yystack_[1].value.as< ast::catches_type > ()); yylhs.value.as< ast::catches_type > () << yystack_[0].value.as< ast::rCatch > (); }
#line 2926 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 102:
#line 887 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rMatch > () = new ast::Match(yylhs.location, yystack_[0].value.as< ast::rExp > (), 0); }
#line 2932 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 103:
#line 888 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rMatch > () = new ast::Match(yylhs.location, yystack_[2].value.as< ast::rExp > (), yystack_[0].value.as< ast::rExp > ()); }
#line 2938 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 104:
#line 891 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rMatch > () = 0; }
#line 2944 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 105:
#line 892 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ std::swap(yylhs.value.as< ast::rMatch > (), yystack_[1].value.as< ast::rMatch > ()); }
#line 2950 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 106:
#line 896 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rCatch > () = MAKE(catch, yylhs.location, yystack_[1].value.as< ast::rMatch > (), yystack_[0].value.as< ast::rExp > ()); }
#line 2956 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 107:
#line 903 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rExp > () = 0; }
#line 2962 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 108:
#line 904 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rExp > () = yystack_[0].value.as< ast::rExp > (); }
#line 2968 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 109:
#line 910 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rExp > () = 0; }
#line 2974 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 110:
#line 911 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rExp > () = yystack_[0].value.as< ast::rExp > (); }
#line 2980 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 111:
#line 916 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{
yylhs.value.as< ast::rExp > () = MAKE(try, yylhs.location, yystack_[3].value.as< ast::rExp > (), yystack_[2].value.as< ast::catches_type > (), yystack_[1].value.as< ast::rExp > (), yystack_[0].value.as< ast::rExp > ());
}
#line 2988 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 112:
#line 920 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{
yylhs.value.as< ast::rExp > () = MAKE(finally, yylhs.location, yystack_[2].value.as< ast::rExp > (), yystack_[0].value.as< ast::rExp > ());
}
#line 2996 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 113:
#line 924 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{
yylhs.value.as< ast::rExp > () = MAKE(throw, yylhs.location, yystack_[0].value.as< ast::rExp > ());
}
#line 3004 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 114:
#line 953 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{
yylhs.value.as< ast::rExp > () = MAKE(loop, yylhs.location, yystack_[1].location, yystack_[1].value.as< ast::flavor_type > (), yystack_[0].value.as< ast::rExp > ());
}
#line 3012 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 115:
#line 957 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{
yylhs.value.as< ast::rExp > () = MAKE(for, yylhs.location, yystack_[4].location, yystack_[4].value.as< ast::flavor_type > (), yystack_[2].value.as< ast::rExp > (), yystack_[0].value.as< ast::rExp > ());
}
#line 3020 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 116:
#line 961 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{
yylhs.value.as< ast::rExp > () = MAKE(for, yylhs.location, yystack_[8].location, yystack_[8].value.as< ast::flavor_type > (), yystack_[6].value.as< ast::rExp > (), yystack_[4].value.as< ast::rExp > (), yystack_[2].value.as< ast::rExp > (), yystack_[0].value.as< ast::rExp > ());
}
#line 3028 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 117:
#line 965 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{
yylhs.value.as< ast::rExp > () = MAKE(for, yylhs.location, yystack_[7].location, yystack_[7].value.as< ast::flavor_type > (), yystack_[4].location, yystack_[4].value.as< libport::Symbol > (), yystack_[2].value.as< ast::rExp > (), yystack_[0].value.as< ast::rExp > ());
}
#line 3036 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 118:
#line 969 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{
yylhs.value.as< ast::rExp > () = MAKE(while, yylhs.location, yystack_[4].location, yystack_[4].value.as< ast::flavor_type > (), yystack_[2].value.as< ast::rExp > (), yystack_[0].value.as< ast::rExp > ());
}
#line 3044 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 121:
#line 984 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rExp > () = MAKE(scope, yylhs.location, 0, yystack_[0].value.as< ast::rExp > ()); }
#line 3050 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 122:
#line 985 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rExp > () = MAKE(scope, yylhs.location, yystack_[2].value.as< ast::rExp > (), yystack_[0].value.as< ast::rExp > ()); }
#line 3056 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 123:
#line 997 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< bool > () = true; }
#line 3062 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 124:
#line 998 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< bool > () = false; }
#line 3068 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 125:
#line 1002 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rExp > () = MAKE(assert, yylhs.location, yystack_[1].value.as< ast::rExp > ()); }
#line 3074 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 126:
#line 1003 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rExp > () = MAKE(assert, yylhs.location, yystack_[1].value.as< ast::exps_type* > ()); }
#line 3080 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 127:
#line 1004 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rExp > () = MAKE(detach, yylhs.location, yystack_[3].value.as< bool > (), yystack_[1].value.as< ast::rExp > ()); }
#line 3086 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 128:
#line 1005 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rExp > () = MAKE(detach, yylhs.location, yystack_[1].value.as< bool > (), yystack_[0].value.as< ast::rExp > ()); }
#line 3092 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 129:
#line 1006 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rExp > () = MAKE(isdef, yylhs.location, yystack_[1].value.as< ast::rCall > ()); }
#line 3098 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 130:
#line 1007 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rExp > () = MAKE(watch, yylhs.location, yystack_[1].value.as< ast::rExp > ()); }
#line 3104 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 131:
#line 1017 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rLValue > () = MAKE(call, yylhs.location, yystack_[0].value.as< libport::Symbol > ()); }
#line 3110 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 132:
#line 1018 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rLValue > () = MAKE(call, yylhs.location, yystack_[2].value.as< ast::rExp > (), yystack_[0].value.as< libport::Symbol > ()); }
#line 3116 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 133:
#line 1019 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rLValue > () = MAKE(call, yylhs.location, yystack_[2].value.as< ast::rExp > (), yystack_[0].value.as< libport::Symbol > ()); }
#line 3122 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 134:
#line 1023 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rExp > () = MAKE(get_slot, yylhs.location, yystack_[0].value.as< libport::Symbol > ()); }
#line 3128 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 135:
#line 1024 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rExp > () = MAKE(get_slot, yylhs.location, yystack_[3].value.as< ast::rExp > (), yystack_[0].value.as< libport::Symbol > ()); }
#line 3134 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 136:
#line 1028 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ std::swap(yylhs.value.as< libport::Symbol > (), yystack_[0].value.as< libport::Symbol > ()); }
#line 3140 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 137:
#line 1033 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{
yylhs.value.as< ast::rExp > () = MAKE(binding, yylhs.location, false, yystack_[0].location, yystack_[0].value.as< ast::rExp > ());
}
#line 3148 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 138:
#line 1037 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{
yylhs.value.as< ast::rExp > () = MAKE(binding, yylhs.location, true, yystack_[0].location, yystack_[0].value.as< ast::rExp > ());
}
#line 3156 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 139:
#line 1044 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{
yylhs.value.as< ast::rExp > () = yystack_[0].value.as< ast::rLValue > ();
}
#line 3164 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 140:
#line 1048 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{
yylhs.value.as< ast::rExp > () = yystack_[1].value.as< ast::rLValue > ();
yylhs.value.as< ast::rExp > ().unchecked_cast<ast::LValueArgs>()->arguments_set(yystack_[0].value.as< ast::exps_type* > ());
yylhs.value.as< ast::rExp > ()->location_set(yylhs.location);
}
#line 3174 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 141:
#line 1061 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{
// Compiled as "id . new (args)".
ast::exps_type* args = yystack_[0].value.as< ast::exps_type* > ();
if (!args)
args = new ast::exps_type();
yylhs.value.as< ast::rExp > () = MAKE(call, yylhs.location, MAKE(call, yylhs.location, yystack_[1].value.as< libport::Symbol > ()), SYMBOL(new), args);
up.deprecated(yylhs.location, "new Obj(x)", "Obj.new(x)");
}
#line 3187 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 142:
#line 1072 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ std::swap(yylhs.value.as< ast::rExp > (), yystack_[0].value.as< ast::rExp > ()); }
#line 3193 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 143:
#line 1077 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ std::swap(yylhs.value.as< libport::Symbol > (), yystack_[0].value.as< libport::Symbol > ()); }
#line 3199 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 144:
#line 1088 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{
yylhs.value.as< ast::rExp > () = MAKE(routine, yylhs.location, yystack_[2].value.as< bool > (), yystack_[1].location, yystack_[1].value.as< ast::Formals* > (), yystack_[0].value.as< ast::rExp > ());
}
#line 3207 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 145:
#line 1104 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rExp > () = MAKE(float, yylhs.location, yystack_[0].value.as< libport::ufloat > ()); }
#line 3213 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 146:
#line 1114 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< libport::ufloat > () = yystack_[0].value.as< libport::ufloat > (); }
#line 3219 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 147:
#line 1115 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< libport::ufloat > () = yystack_[1].value.as< libport::ufloat > () + yystack_[0].value.as< libport::ufloat > (); }
#line 3225 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 148:
#line 1129 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{
yylhs.value.as< ast::dictionary_elt_type > ().first = yystack_[2].value.as< ast::rExp > ();
yylhs.value.as< ast::dictionary_elt_type > ().second = yystack_[0].value.as< ast::rExp > ();
}
#line 3234 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 149:
#line 1137 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{
assocs_add(up, yystack_[0].location, yylhs.value.as< ast::dictionary_elts_type > (), yystack_[0].value.as< ast::dictionary_elt_type > ());
}
#line 3242 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 150:
#line 1141 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{
std::swap(yylhs.value.as< ast::dictionary_elts_type > (), yystack_[2].value.as< ast::dictionary_elts_type > ());
assocs_add(up, yystack_[0].location, yylhs.value.as< ast::dictionary_elts_type > (), yystack_[0].value.as< ast::dictionary_elt_type > ());
}
#line 3251 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 151:
#line 1148 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ /* nothing */ }
#line 3257 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 152:
#line 1149 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ std::swap(yylhs.value.as< ast::dictionary_elts_type > (), yystack_[1].value.as< ast::dictionary_elts_type > ()); }
#line 3263 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 153:
#line 1154 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rDictionary > () = new ast::Dictionary(yylhs.location, yystack_[1].value.as< ast::dictionary_elts_type > ()); }
#line 3269 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 154:
#line 1165 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::exps_type* > () = new ast::exps_type; }
#line 3275 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 155:
#line 1166 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ std::swap(yylhs.value.as< ast::exps_type* > (), yystack_[1].value.as< ast::exps_type* > ()); }
#line 3281 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 156:
#line 1167 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ std::swap(yylhs.value.as< ast::exps_type* > (), yystack_[0].value.as< ast::exps_type* > ()); }
#line 3287 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 157:
#line 1171 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::exps_type* > () = yystack_[1].value.as< ast::exps_type* > (); }
#line 3293 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 158:
#line 1185 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::exps_type* > () = new ast::exps_type; }
#line 3299 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 159:
#line 1186 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ std::swap(yylhs.value.as< ast::exps_type* > (), yystack_[1].value.as< ast::exps_type* > ()); }
#line 3305 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 160:
#line 1190 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::exps_type* > () = new ast::exps_type(1, yystack_[0].value.as< ast::rExp > ()); }
#line 3311 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 161:
#line 1191 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ std::swap(yylhs.value.as< ast::exps_type* > (), yystack_[2].value.as< ast::exps_type* > ()); *yylhs.value.as< ast::exps_type* > () << yystack_[0].value.as< ast::rExp > ();}
#line 3317 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 162:
#line 1199 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ std::swap(yylhs.value.as< ast::rExp > (), yystack_[0].value.as< ast::rExp > ()); }
#line 3323 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 163:
#line 1200 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rExp > () = MAKE(float, yylhs.location, yystack_[0].value.as< libport::ufloat > ()); }
#line 3329 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 164:
#line 1201 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rExp > () = MAKE(float, yylhs.location, yystack_[0].value.as< libport::ufloat > ()); }
#line 3335 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 165:
#line 1202 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rExp > () = MAKE(string, yylhs.location, yystack_[0].value.as< std::string > ()); }
#line 3341 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 166:
#line 1203 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rExp > () = MAKE(list, yylhs.location, yystack_[1].value.as< ast::exps_type* > ()); }
#line 3347 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 167:
#line 1204 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rExp > () = MAKE(vector, yylhs.location, yystack_[1].value.as< ast::exps_type* > ()); }
#line 3353 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 168:
#line 1205 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rExp > () = yystack_[0].value.as< ast::rDictionary > (); }
#line 3359 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 169:
#line 1206 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rExp > () = MAKE(tuple, yylhs.location, yystack_[0].value.as< ast::exps_type* > ()); }
#line 3365 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 170:
#line 1212 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ std::swap(yylhs.value.as< std::string > (), yystack_[0].value.as< std::string > ()); }
#line 3371 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 171:
#line 1213 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ std::swap(yylhs.value.as< std::string > (), yystack_[1].value.as< std::string > ()); yylhs.value.as< std::string > () += yystack_[0].value.as< std::string > (); }
#line 3377 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 172:
#line 1221 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rExp > () = MAKE(position, yylhs.location); }
#line 3383 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 173:
#line 1232 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{
yylhs.value.as< ast::EventMatch > () = MAKE(event_match, yylhs.location, yystack_[4].value.as< ast::rExp > (), yystack_[2].value.as< ast::exps_type* > (), yystack_[1].value.as< ast::rExp > (), yystack_[0].value.as< ast::rExp > ());
}
#line 3391 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 174:
#line 1239 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rExp > () = 0; }
#line 3397 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 175:
#line 1240 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ std::swap(yylhs.value.as< ast::rExp > (), yystack_[0].value.as< ast::rExp > ()); }
#line 3403 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 176:
#line 1245 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rExp > () = 0; }
#line 3409 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 177:
#line 1246 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ std::swap(yylhs.value.as< ast::rExp > (), yystack_[0].value.as< ast::rExp > ()); }
#line 3415 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 178:
#line 1256 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{
yylhs.value.as< ast::rLValue > () = new ast::Subscript(yylhs.location, yystack_[1].value.as< ast::exps_type* > (), yystack_[3].value.as< ast::rExp > ());
}
#line 3423 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 179:
#line 1271 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rExp > () = new ast::This(yylhs.location); }
#line 3429 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 180:
#line 1272 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rExp > () = new ast::CallMsg(yylhs.location); }
#line 3435 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 181:
#line 1276 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ std::swap(yylhs.value.as< ast::rExp > (), yystack_[0].value.as< ast::rExp > ()); }
#line 3441 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 182:
#line 1277 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ std::swap(yylhs.value.as< ast::rExp > (), yystack_[1].value.as< ast::rExp > ()); }
#line 3447 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 183:
#line 1278 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rExp > () = MAKE(noop, yylhs.location); }
#line 3453 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 184:
#line 1279 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rExp > () = MAKE(call, yylhs.location, yystack_[2].value.as< ast::rExp > (), yystack_[1].value.as< libport::Symbol > (), yystack_[0].value.as< ast::rExp > ()); }
#line 3459 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 185:
#line 1284 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ std::swap(yylhs.value.as< ast::rExp > (), yystack_[0].value.as< ast::rExp > ()); }
#line 3465 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 186:
#line 1285 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rExp > () = new ast::Decrementation(yylhs.location, yystack_[0].value.as< ast::rLValue > (), false); }
#line 3471 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 187:
#line 1286 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rExp > () = new ast::Incrementation(yylhs.location, yystack_[0].value.as< ast::rLValue > (), false); }
#line 3477 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 188:
#line 1287 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rExp > () = MAKE(call, yylhs.location, yystack_[0].value.as< ast::rExp > (), yystack_[1].value.as< libport::Symbol > (), new ast::exps_type()); }
#line 3483 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 189:
#line 1288 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rExp > () = MAKE(call, yylhs.location, yystack_[0].value.as< ast::rExp > (), yystack_[1].value.as< libport::Symbol > (), new ast::exps_type()); }
#line 3489 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 190:
#line 1289 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rExp > () = MAKE(call, yylhs.location, yystack_[0].value.as< ast::rExp > (), yystack_[1].value.as< libport::Symbol > (), new ast::exps_type()); }
#line 3495 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 191:
#line 1290 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rExp > () = MAKE(call, yylhs.location, yystack_[0].value.as< ast::rExp > (), yystack_[1].value.as< libport::Symbol > (), new ast::exps_type()); }
#line 3501 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 192:
#line 1315 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ std::swap(yylhs.value.as< ast::rExp > (), yystack_[0].value.as< ast::rExp > ()); }
#line 3507 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 193:
#line 1316 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rExp > () = MAKE(call, yylhs.location, yystack_[2].value.as< ast::rExp > (), yystack_[1].value.as< libport::Symbol > (), yystack_[0].value.as< ast::rExp > ()); }
#line 3513 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 194:
#line 1317 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rExp > () = MAKE(call, yylhs.location, yystack_[2].value.as< ast::rExp > (), yystack_[1].value.as< libport::Symbol > (), yystack_[0].value.as< ast::rExp > ()); }
#line 3519 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 195:
#line 1318 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rExp > () = MAKE(call, yylhs.location, yystack_[2].value.as< ast::rExp > (), yystack_[1].value.as< libport::Symbol > (), yystack_[0].value.as< ast::rExp > ()); }
#line 3525 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 196:
#line 1319 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rExp > () = MAKE(call, yylhs.location, yystack_[2].value.as< ast::rExp > (), yystack_[1].value.as< libport::Symbol > (), yystack_[0].value.as< ast::rExp > ()); }
#line 3531 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 197:
#line 1320 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rExp > () = MAKE(call, yylhs.location, yystack_[2].value.as< ast::rExp > (), yystack_[1].value.as< libport::Symbol > (), yystack_[0].value.as< ast::rExp > ()); }
#line 3537 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 198:
#line 1321 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rExp > () = MAKE(call, yylhs.location, yystack_[2].value.as< ast::rExp > (), yystack_[1].value.as< libport::Symbol > (), yystack_[0].value.as< ast::rExp > ()); }
#line 3543 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 199:
#line 1322 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rExp > () = MAKE(call, yylhs.location, yystack_[2].value.as< ast::rExp > (), yystack_[1].value.as< libport::Symbol > (), yystack_[0].value.as< ast::rExp > ()); }
#line 3549 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 200:
#line 1323 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rExp > () = MAKE(call, yylhs.location, yystack_[2].value.as< ast::rExp > (), yystack_[1].value.as< libport::Symbol > (), yystack_[0].value.as< ast::rExp > ()); }
#line 3555 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 201:
#line 1324 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rExp > () = MAKE(call, yylhs.location, yystack_[2].value.as< ast::rExp > (), yystack_[1].value.as< libport::Symbol > (), yystack_[0].value.as< ast::rExp > ()); }
#line 3561 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 202:
#line 1325 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rExp > () = MAKE(call, yylhs.location, yystack_[2].value.as< ast::rExp > (), yystack_[1].value.as< libport::Symbol > (), yystack_[0].value.as< ast::rExp > ()); }
#line 3567 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 203:
#line 1351 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ std::swap(yylhs.value.as< libport::Symbol > (), yystack_[0].value.as< libport::Symbol > ()); }
#line 3573 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 204:
#line 1352 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ std::swap(yylhs.value.as< libport::Symbol > (), yystack_[0].value.as< libport::Symbol > ()); }
#line 3579 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 205:
#line 1353 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ std::swap(yylhs.value.as< libport::Symbol > (), yystack_[0].value.as< libport::Symbol > ()); }
#line 3585 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 206:
#line 1354 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ std::swap(yylhs.value.as< libport::Symbol > (), yystack_[0].value.as< libport::Symbol > ()); }
#line 3591 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 207:
#line 1355 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ std::swap(yylhs.value.as< libport::Symbol > (), yystack_[0].value.as< libport::Symbol > ()); }
#line 3597 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 208:
#line 1356 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ std::swap(yylhs.value.as< libport::Symbol > (), yystack_[0].value.as< libport::Symbol > ()); }
#line 3603 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 209:
#line 1357 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ std::swap(yylhs.value.as< libport::Symbol > (), yystack_[0].value.as< libport::Symbol > ()); }
#line 3609 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 210:
#line 1358 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ std::swap(yylhs.value.as< libport::Symbol > (), yystack_[0].value.as< libport::Symbol > ()); }
#line 3615 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 211:
#line 1359 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ std::swap(yylhs.value.as< libport::Symbol > (), yystack_[0].value.as< libport::Symbol > ()); }
#line 3621 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 212:
#line 1360 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ std::swap(yylhs.value.as< libport::Symbol > (), yystack_[0].value.as< libport::Symbol > ()); }
#line 3627 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 213:
#line 1364 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rExp > () = MAKE(relation, yylhs.location, yystack_[1].value.as< ast::rExp > (), yystack_[0].value.as< ast::Factory::relations_type > ()); }
#line 3633 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 214:
#line 1369 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ /* empty */ }
#line 3639 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 215:
#line 1370 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ std::swap(yylhs.value.as< ast::Factory::relations_type > (), MAKE(relation, yystack_[2].value.as< ast::Factory::relations_type > (), yystack_[1].value.as< libport::Symbol > (), yystack_[0].value.as< ast::rExp > ())); }
#line 3645 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 216:
#line 1384 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ std::swap(yylhs.value.as< ast::rExp > (), yystack_[0].value.as< ast::rExp > ()); }
#line 3651 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 217:
#line 1385 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rExp > () = MAKE(and, yylhs.location, yystack_[2].value.as< ast::rExp > (), yystack_[0].value.as< ast::rExp > ()); }
#line 3657 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 218:
#line 1386 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rExp > () = MAKE(or, yylhs.location, yystack_[2].value.as< ast::rExp > (), yystack_[0].value.as< ast::rExp > ()); }
#line 3663 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 219:
#line 1391 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rExp > () = MAKE(call, yylhs.location, yystack_[0].value.as< ast::rExp > (), SYMBOL(has), yystack_[2].value.as< ast::rExp > ()); }
#line 3669 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 220:
#line 1392 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rExp > () = MAKE(call, yylhs.location, yystack_[0].value.as< ast::rExp > (), SYMBOL(hasNot), yystack_[3].value.as< ast::rExp > ()); }
#line 3675 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 221:
#line 1396 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rExp > () = 0; }
#line 3681 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 222:
#line 1397 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ std::swap(yylhs.value.as< ast::rExp > (), yystack_[0].value.as< ast::rExp > ()); }
#line 3687 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 223:
#line 1408 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< unsigned > () = static_cast<unsigned int>(yystack_[0].value.as< libport::ufloat > ()); }
#line 3693 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 224:
#line 1417 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{
yylhs.value.as< ast::rExp > () = new ast::Unscope(yylhs.location, yystack_[0].value.as< unsigned > ());
}
#line 3701 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 225:
#line 1429 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{
yylhs.value.as< ast::rExp > () = new ast::MetaExp(yylhs.location, yystack_[0].value.as< unsigned > ());
}
#line 3709 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 226:
#line 1437 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{
yylhs.value.as< ast::rLValue > () = new ast::MetaLValue(yylhs.location, new ast::exps_type(), yystack_[0].value.as< unsigned > ());
}
#line 3717 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 227:
#line 1445 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{
yylhs.value.as< ast::rLValue > () = new ast::MetaId(yylhs.location, 0, yystack_[0].value.as< unsigned > ());
}
#line 3725 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 228:
#line 1449 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{
yylhs.value.as< ast::rLValue > () = new ast::MetaCall(yylhs.location, 0, yystack_[3].value.as< ast::rExp > (), yystack_[0].value.as< unsigned > ());
}
#line 3733 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 229:
#line 1457 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{
assert(yystack_[4].value.as< ast::rLValue > ().unsafe_cast<ast::LValueArgs>());
assert(!yystack_[4].value.as< ast::rLValue > ().unsafe_cast<ast::LValueArgs>()->arguments_get());
yylhs.value.as< ast::rExp > () = new ast::MetaArgs(yylhs.location, yystack_[4].value.as< ast::rLValue > (), yystack_[1].value.as< unsigned > ());
}
#line 3743 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 230:
#line 1473 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::exps_type* > () = new ast::exps_type; }
#line 3749 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 231:
#line 1474 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ std::swap(yylhs.value.as< ast::exps_type* > (), yystack_[1].value.as< ast::exps_type* > ()); }
#line 3755 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 232:
#line 1478 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::exps_type* > () = new ast::exps_type(1, yystack_[0].value.as< ast::rExp > ()); }
#line 3761 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 233:
#line 1479 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ std::swap(yylhs.value.as< ast::exps_type* > (), yystack_[2].value.as< ast::exps_type* > ()); *yylhs.value.as< ast::exps_type* > () << yystack_[0].value.as< ast::rExp > (); }
#line 3767 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 234:
#line 1485 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::exps_type* > () = new ast::exps_type; }
#line 3773 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 235:
#line 1486 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ std::swap(yylhs.value.as< ast::exps_type* > (), yystack_[1].value.as< ast::exps_type* > ()); }
#line 3779 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 236:
#line 1490 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::exps_type* > () = new ast::exps_type(1, yystack_[0].value.as< ast::rExp > ()); }
#line 3785 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 237:
#line 1491 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ std::swap(yylhs.value.as< ast::exps_type* > (), yystack_[2].value.as< ast::exps_type* > ()); *yylhs.value.as< ast::exps_type* > () << yystack_[0].value.as< ast::rExp > (); }
#line 3791 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 238:
#line 1495 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ std::swap(yylhs.value.as< ast::exps_type* > (), yystack_[2].value.as< ast::exps_type* > ()); *yylhs.value.as< ast::exps_type* > () << yystack_[0].value.as< ast::rExp > (); }
#line 3797 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 239:
#line 1500 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ std::swap(yylhs.value.as< ast::exps_type* > (), yystack_[1].value.as< ast::exps_type* > ()); }
#line 3803 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 240:
#line 1504 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::exps_type* > () = 0; }
#line 3809 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 241:
#line 1505 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ std::swap(yylhs.value.as< ast::exps_type* > (), yystack_[0].value.as< ast::exps_type* > ()); }
#line 3815 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 242:
#line 1515 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ /* empty */ }
#line 3821 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 243:
#line 1516 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ std::swap(yylhs.value.as< ast::symbols_type > (), yystack_[1].value.as< ast::symbols_type > ()); yylhs.value.as< ast::symbols_type > ().push_back(yystack_[0].value.as< libport::Symbol > ()); }
#line 3827 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 244:
#line 1521 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rExp > () = yystack_[0].value.as< ast::rExp > ();}
#line 3833 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 245:
#line 1526 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::rExp > ()=0;}
#line 3839 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 246:
#line 1527 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ std::swap(yylhs.value.as< ast::rExp > (), yystack_[0].value.as< ast::rExp > ());}
#line 3845 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 247:
#line 1532 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::Formal > () = ast::Formal(yystack_[1].value.as< libport::Symbol > (), 0, yystack_[0].value.as< ast::rExp > ()); }
#line 3851 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 248:
#line 1533 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::Formal > () = ast::Formal(yystack_[3].value.as< libport::Symbol > (), yystack_[1].value.as< ast::rExp > (), yystack_[0].value.as< ast::rExp > ()); }
#line 3857 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 249:
#line 1534 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::Formal > () = ast::Formal(yystack_[2].value.as< libport::Symbol > (), true); }
#line 3863 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 250:
#line 1540 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::Formals* > () = new ast::Formals(1, yystack_[0].value.as< ast::Formal > ()); }
#line 3869 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 251:
#line 1541 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ std::swap(yylhs.value.as< ast::Formals* > (), yystack_[2].value.as< ast::Formals* > ()); *yylhs.value.as< ast::Formals* > () << yystack_[0].value.as< ast::Formal > (); }
#line 3875 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 252:
#line 1546 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::Formals* > () = new ast::Formals; }
#line 3881 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 253:
#line 1547 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ std::swap(yylhs.value.as< ast::Formals* > (), yystack_[1].value.as< ast::Formals* > ()); }
#line 3887 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 254:
#line 1552 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ yylhs.value.as< ast::Formals* > () = 0; }
#line 3893 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
case 255:
#line 1553 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:870
{ std::swap(yylhs.value.as< ast::Formals* > (), yystack_[1].value.as< ast::Formals* > ()); }
#line 3899 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
break;
#line 3903 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:870
default:
break;
}
}
#if YY_EXCEPTIONS
catch (const syntax_error& yyexc)
{
error (yyexc);
YYERROR;
}
#endif // YY_EXCEPTIONS
YY_SYMBOL_PRINT ("-> $$ =", yylhs);
yypop_ (yylen);
yylen = 0;
YY_STACK_PRINT ();
// Shift the result of the reduction.
yypush_ (YY_NULLPTR, yylhs);
}
goto yynewstate;
/*--------------------------------------.
| yyerrlab -- here on detecting error. |
`--------------------------------------*/
yyerrlab:
// If not already recovering from an error, report this error.
if (!yyerrstatus_)
{
++yynerrs_;
error (yyla.location, yysyntax_error_ (yystack_[0].state, yyla));
}
yyerror_range[1].location = yyla.location;
if (yyerrstatus_ == 3)
{
/* If just tried and failed to reuse lookahead token after an
error, discard it. */
// Return failure if at end of input.
if (yyla.type_get () == yyeof_)
YYABORT;
else if (!yyla.empty ())
{
yy_destroy_ ("Error: discarding", yyla);
yyla.clear ();
}
}
// Else will try to reuse lookahead token after shifting the error token.
goto yyerrlab1;
/*---------------------------------------------------.
| yyerrorlab -- error raised explicitly by YYERROR. |
`---------------------------------------------------*/
yyerrorlab:
/* Pacify compilers like GCC when the user code never invokes
YYERROR and the label yyerrorlab therefore never appears in user
code. */
if (false)
goto yyerrorlab;
/* Do not reclaim the symbols of the rule whose action triggered
this YYERROR. */
yypop_ (yylen);
yylen = 0;
goto yyerrlab1;
/*-------------------------------------------------------------.
| yyerrlab1 -- common code for both syntax error and YYERROR. |
`-------------------------------------------------------------*/
yyerrlab1:
yyerrstatus_ = 3; // Each real token shifted decrements this.
{
stack_symbol_type error_token;
for (;;)
{
yyn = yypact_[yystack_[0].state];
if (!yy_pact_value_is_default_ (yyn))
{
yyn += yyterror_;
if (0 <= yyn && yyn <= yylast_ && yycheck_[yyn] == yyterror_)
{
yyn = yytable_[yyn];
if (0 < yyn)
break;
}
}
// Pop the current state because it cannot handle the error token.
if (yystack_.size () == 1)
YYABORT;
yyerror_range[1].location = yystack_[0].location;
yy_destroy_ ("Error: popping", yystack_[0]);
yypop_ ();
YY_STACK_PRINT ();
}
yyerror_range[2].location = yyla.location;
YYLLOC_DEFAULT (error_token.location, yyerror_range, 2);
// Shift the error token.
error_token.state = yyn;
yypush_ ("Shifting", error_token);
}
goto yynewstate;
// Accept.
yyacceptlab:
yyresult = 0;
goto yyreturn;
// Abort.
yyabortlab:
yyresult = 1;
goto yyreturn;
yyreturn:
if (!yyla.empty ())
yy_destroy_ ("Cleanup: discarding lookahead", yyla);
/* Do not reclaim the symbols of the rule whose action triggered
this YYABORT or YYACCEPT. */
yypop_ (yylen);
while (1 < yystack_.size ())
{
yy_destroy_ ("Cleanup: popping", yystack_[0]);
yypop_ ();
}
return yyresult;
}
#if YY_EXCEPTIONS
catch (...)
{
YYCDEBUG << "Exception caught: cleaning lookahead and stack\n";
// Do not try to display the values of the reclaimed symbols,
// as their printers might throw an exception.
if (!yyla.empty ())
yy_destroy_ (YY_NULLPTR, yyla);
while (1 < yystack_.size ())
{
yy_destroy_ (YY_NULLPTR, yystack_[0]);
yypop_ ();
}
throw;
}
#endif // YY_EXCEPTIONS
}
void
parser::error (const syntax_error& yyexc)
{
error (yyexc.location, yyexc.what ());
}
// Generate an error message.
std::string
parser::yysyntax_error_ (state_type yystate, const symbol_type& yyla) const
{
// Number of reported tokens (one for the "unexpected", one per
// "expected").
size_t yycount = 0;
// Its maximum.
enum { YYERROR_VERBOSE_ARGS_MAXIMUM = 5 };
// Arguments of yyformat.
char const *yyarg[YYERROR_VERBOSE_ARGS_MAXIMUM];
/* There are many possibilities here to consider:
- If this state is a consistent state with a default action, then
the only way this function was invoked is if the default action
is an error action. In that case, don't check for expected
tokens because there are none.
- The only way there can be no lookahead present (in yyla) is
if this state is a consistent state with a default action.
Thus, detecting the absence of a lookahead is sufficient to
determine that there is no unexpected or expected token to
report. In that case, just report a simple "syntax error".
- Don't assume there isn't a lookahead just because this state is
a consistent state with a default action. There might have
been a previous inconsistent state, consistent state with a
non-default action, or user semantic action that manipulated
yyla. (However, yyla is currently not documented for users.)
- Of course, the expected token list depends on states to have
correct lookahead information, and it depends on the parser not
to perform extra reductions after fetching a lookahead from the
scanner and before detecting a syntax error. Thus, state
merging (from LALR or IELR) and default reductions corrupt the
expected token list. However, the list is correct for
canonical LR with one exception: it will still contain any
token that will not be accepted due to an error action in a
later state.
*/
if (!yyla.empty ())
{
int yytoken = yyla.type_get ();
yyarg[yycount++] = yytname_[yytoken];
int yyn = yypact_[yystate];
if (!yy_pact_value_is_default_ (yyn))
{
/* Start YYX at -YYN if negative to avoid negative indexes in
YYCHECK. In other words, skip the first -YYN actions for
this state because they are default actions. */
int yyxbegin = yyn < 0 ? -yyn : 0;
// Stay within bounds of both yycheck and yytname.
int yychecklim = yylast_ - yyn + 1;
int yyxend = yychecklim < yyntokens_ ? yychecklim : yyntokens_;
for (int yyx = yyxbegin; yyx < yyxend; ++yyx)
if (yycheck_[yyx + yyn] == yyx && yyx != yyterror_
&& !yy_table_value_is_error_ (yytable_[yyx + yyn]))
{
if (yycount == YYERROR_VERBOSE_ARGS_MAXIMUM)
{
yycount = 1;
break;
}
else
yyarg[yycount++] = yytname_[yyx];
}
}
}
char const* yyformat = YY_NULLPTR;
switch (yycount)
{
#define YYCASE_(N, S) \
case N: \
yyformat = S; \
break
default: // Avoid compiler warnings.
YYCASE_ (0, YY_("syntax error"));
YYCASE_ (1, YY_("syntax error, unexpected %s"));
YYCASE_ (2, YY_("syntax error, unexpected %s, expecting %s"));
YYCASE_ (3, YY_("syntax error, unexpected %s, expecting %s or %s"));
YYCASE_ (4, YY_("syntax error, unexpected %s, expecting %s or %s or %s"));
YYCASE_ (5, YY_("syntax error, unexpected %s, expecting %s or %s or %s or %s"));
#undef YYCASE_
}
std::string yyres;
// Argument number.
size_t yyi = 0;
for (char const* yyp = yyformat; *yyp; ++yyp)
if (yyp[0] == '%' && yyp[1] == 's' && yyi < yycount)
{
yyres += yytnamerr_ (yyarg[yyi++]);
++yyp;
}
else
yyres += *yyp;
return yyres;
}
const short parser::yypact_ninf_ = -267;
const short parser::yytable_ninf_ = -261;
const short
parser::yypact_[] =
{
336, -267, 690, 1162, 51, -267, 32, -267, -267, -267,
30, -267, 46, -267, 54, 72, 893, 1346, 977, 1498,
82, 89, 1498, 108, 113, 766, 141, 146, 157, -10,
165, 176, 1162, 182, -267, -267, 1692, 1692, -10, 94,
1692, 1692, 1692, 203, -11, -267, -267, 180, -267, -267,
-267, -267, -267, -267, 1650, 1650, 1650, 1650, 766, 170,
170, 170, 170, -267, 79, 132, -267, -267, 342, 22,
18, 196, 538, -10, 558, -267, -267, 160, -267, -267,
-267, 164, -267, -267, -267, 173, -267, -267, -267, -267,
-267, 766, 1422, 1162, -38, 213, 101, 59, -267, 15,
227, 11, -267, -267, 225, 224, 239, 236, 238, 55,
248, 250, -267, 357, -267, 1422, 1422, -267, 1422, 68,
212, 558, 1422, 1422, 1422, -267, -267, 1422, 1270, -267,
1422, -8, 11, 521, 521, 270, -267, 257, 261, 276,
462, 462, 462, 1422, 1422, 1422, 285, -267, -267, -267,
-267, 558, 193, 282, -267, -267, -267, -267, -267, -267,
-267, -267, 1162, 1162, 1422, 1422, 162, 1422, 1422, 103,
-267, 298, 219, 113, 1162, 1422, 13, 1692, 1422, -267,
1053, 1422, 1422, 1422, 1422, 1422, 1422, -267, -267, -10,
-267, 227, 766, 766, 766, 766, 766, 766, 766, 766,
766, 766, 1441, -267, -267, 1162, 1162, 558, 49, 299,
117, 166, -267, -267, -10, 1422, 311, 1422, -267, -267,
-267, 1422, -267, -267, -267, -267, 1422, 49, 305, 70,
121, 320, 113, 140, -267, 49, 326, 163, 49, 329,
189, 1574, 318, -267, 191, 244, 1422, -267, 249, 113,
113, -10, 349, -267, 170, 263, 357, 351, 337, 300,
1422, -267, -267, -267, 766, -267, -267, 346, 226, 3,
1422, 360, 8, -3, -267, -267, 344, 367, 340, 350,
353, 113, -267, -267, 357, 371, -10, -267, 170, -267,
11, 302, 170, 374, 357, 357, 357, 357, 357, 357,
-267, 113, 565, 594, 728, 222, 222, 301, -267, 301,
-267, -267, -267, -267, -267, -267, -267, -267, -267, -267,
-267, -267, 766, -267, -267, 1422, 285, 375, 1162, 1162,
-267, 379, 357, 15, -267, 357, 395, 381, 1162, 394,
1162, 1422, 113, -267, 1162, 402, -267, 390, -267, -267,
392, 1162, 1162, 69, 1422, 1162, 1162, 49, 398, -267,
-267, -267, 1422, -267, 383, -267, -267, 403, 388, -267,
384, 401, 113, -267, 1422, -267, -267, 558, 422, -267,
387, 3, -267, 103, -267, -267, 37, -267, -267, -267,
-267, -267, -267, -267, 408, -267, -267, 558, 357, 360,
1162, -267, 424, -267, 1162, -267, -267, 435, 118, 415,
-267, -267, 113, -267, -267, 1162, 424, -267, -267, -267,
1422, 259, -267, -267, 416, 1162, 357, 249, -267, -10,
-267, 404, 407, -267, 357, 1422, -267, -267, 1422, 1422,
420, -267, -267, -267, 434, -267, -267, -267, 159, 113,
424, 1422, -267, -267, 424, -267, 413, 1162, 1162, 433,
-267, -267, -267, 409, 436, 357, 211, 357, -267, 1422,
-267, 1422, 447, 439, -267, -267, 402, 357, -267, 1162,
440, 433, 1162, -267, -267, 421, -267, 357, 460, 1162,
-267, -267, -267, 1162, -267, -267, 404, 1162, 173, -267,
428, 173, -267
};
const unsigned short
parser::yydefact_[] =
{
0, 3, 0, 16, 0, 2, 0, 172, 85, 53,
0, 86, 0, 54, 0, 0, 0, 234, 0, 221,
0, 0, 221, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 242, 136, 0, 0, 0, 0,
0, 0, 0, 0, 0, 123, 124, 143, 163, 146,
145, 170, 180, 179, 0, 0, 0, 0, 158, 0,
0, 0, 0, 4, 0, 17, 19, 121, 25, 254,
185, 0, 139, 131, 214, 142, 162, 164, 168, 169,
181, 165, 192, 216, 5, 12, 13, 1, 11, 10,
9, 0, 0, 16, 0, 0, 0, 131, 151, 236,
254, 185, 131, 149, 256, 0, 0, 256, 0, 236,
0, 0, 156, 222, 84, 0, 0, 113, 0, 0,
139, 137, 0, 0, 0, 143, 134, 0, 22, 114,
0, 0, 0, 139, 139, 0, 46, 0, 47, 0,
51, 186, 187, 0, 230, 0, 240, 190, 191, 189,
188, 160, 0, 256, 223, 224, 225, 226, 227, 8,
7, 6, 0, 18, 0, 0, 240, 0, 0, 252,
57, 0, 254, 0, 0, 234, 0, 0, 0, 128,
234, 0, 0, 0, 0, 0, 0, 71, 72, 0,
140, 254, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 213, 147, 171, 16, 16, 138, 176, 0,
0, 0, 27, 26, 0, 0, 0, 257, 152, 153,
166, 257, 235, 183, 182, 157, 155, 176, 0, 0,
0, 104, 0, 93, 100, 176, 0, 0, 176, 0,
0, 0, 0, 23, 25, 0, 0, 243, 29, 0,
0, 40, 0, 48, 0, 0, 232, 0, 258, 0,
234, 241, 141, 167, 257, 159, 21, 20, 63, 219,
0, 176, 217, 218, 261, 250, 256, 0, 0, 0,
0, 0, 144, 24, 236, 0, 0, 133, 0, 132,
184, 0, 0, 0, 69, 66, 70, 65, 68, 67,
73, 0, 200, 201, 198, 202, 199, 194, 197, 193,
196, 195, 209, 207, 208, 211, 210, 206, 205, 203,
204, 212, 0, 15, 14, 0, 240, 0, 0, 0,
129, 0, 148, 0, 150, 237, 237, 0, 0, 0,
0, 0, 0, 112, 0, 109, 101, 0, 88, 130,
0, 0, 0, 136, 0, 0, 0, 176, 0, 30,
31, 32, 0, 34, 37, 38, 39, 0, 256, 42,
0, 0, 0, 126, 259, 231, 125, 161, 0, 61,
64, 220, 52, 257, 253, 255, 245, 58, 59, 55,
178, 135, 228, 127, 0, 239, 56, 215, 177, 176,
0, 79, 93, 28, 0, 81, 97, 107, 102, 0,
106, 94, 0, 111, 87, 0, 93, 76, 120, 119,
0, 0, 115, 118, 0, 0, 33, 29, 44, 257,
41, 0, 0, 122, 233, 0, 62, 251, 0, 0,
0, 246, 247, 229, 174, 78, 77, 80, 91, 0,
93, 0, 105, 110, 93, 90, 0, 22, 0, 95,
35, 43, 45, 0, 0, 60, 245, 244, 249, 0,
173, 0, 0, 0, 98, 108, 109, 103, 89, 0,
0, 95, 0, 75, 49, 0, 248, 175, 0, 16,
82, 83, 117, 0, 74, 96, 0, 16, 92, 116,
0, 99, 50
};
const short
parser::yypgoto_[] =
{
-267, -267, -267, -267, -267, -13, 2, 71, 6, 184,
40, -267, 56, -267, 347, 450, -267, -267, -14, -267,
36, 396, 112, -267, 17, -267, -266, 19, -267, -267,
-267, 27, -267, 268, -267, 28, -267, -267, 61, -2,
356, -267, -267, -267, 288, -267, -267, -267, -267, -267,
-267, -267, -267, -267, -100, -267, -209, 231, -267, -267,
-267, 485, -53, -267, -267, -7, 490, -267, -141, -160,
-267, -267, 43, 128, -267, -267, -125, -105, -267, -267
};
const short
parser::yydefgoto_[] =
{
-1, 4, 5, 63, 84, 85, 86, 65, 242, 66,
67, 362, 363, 364, 249, 68, 367, 368, 463, 139,
100, 172, 379, 380, 101, 473, 345, 483, 448, 474,
233, 409, 342, 234, 450, 413, 420, 71, 72, 102,
74, 75, 76, 77, 103, 104, 105, 78, 110, 79,
152, 153, 80, 81, 209, 470, 327, 82, 322, 83,
202, 114, 155, 257, 258, 293, 107, 112, 190, 262,
131, 441, 442, 275, 276, 277, 173, 218, 375, 278
};
const short
parser::yytable_[] =
{
73, 73, 222, 96, 64, 261, 271, 156, 157, 158,
106, 144, 170, 145, 97, 228, 246, 165, 337, 70,
70, 164, 236, -261, 239, 261, 347, 126, 165, 350,
73, 174, 88, 70, 175, 165, 135, 176, 69, 69,
35, 175, 247, 438, 176, 171, 169, 281, 265, 70,
439, 87, 69, 132, 132, 164, 286, 132, 132, 132,
440, 164, 382, 35, 119, 125, 301, 91, 69, 165,
92, 191, 170, 89, 90, 165, 164, 231, 93, 159,
210, 216, 418, 325, 232, 224, 120, 216, 125, 419,
165, 73, 216, 214, 215, 191, 94, 133, 134, 216,
339, 140, 141, 142, 167, 171, 115, 177, 287, 35,
70, 179, 136, 116, 177, 120, 120, 120, 120, 120,
160, 161, 167, 168, 164, 288, 73, 164, 213, 69,
326, 137, 118, 216, 125, 16, 446, 451, 165, 216,
274, 165, 205, 206, 138, 70, 358, 329, 424, 231,
455, 340, 120, -260, 216, 344, 167, 168, 205, 206,
73, 73, 167, 168, 69, 122, 399, 471, 285, 164,
123, 384, 73, 472, 289, 162, 163, 167, 168, 70,
70, 124, 270, 165, 476, 261, 260, 300, 478, 127,
444, 70, 280, 349, 290, 164, 330, 164, 69, 69,
128, 371, 216, 73, 73, 216, 130, 323, 324, 165,
69, 165, 331, 282, 205, 206, 129, 164, 16, 352,
178, 355, 70, 70, 439, 167, 168, 143, 167, 168,
146, 165, 164, 266, 267, 392, 180, 203, 120, 394,
212, 69, 69, 169, 204, 280, 165, 216, 154, 369,
164, 169, 219, 120, 120, 120, 120, 120, 120, 120,
120, 120, 120, 430, 165, 164, 217, 220, 223, 164,
167, 168, 343, 216, 356, 166, 378, 221, 225, 165,
187, 188, 189, 165, 391, 147, 148, 149, 150, 365,
366, 226, 251, 372, 263, 216, 167, 168, 167, 168,
254, 457, 120, 359, 360, 361, 164, 252, 164, 260,
216, 253, 243, 197, 198, 199, 200, 201, 167, 168,
165, 389, 165, 264, 279, 120, 73, 73, 216, 328,
376, 270, 393, 167, 168, 338, 73, 1, 73, 2,
3, 396, 73, 216, 341, 70, 70, 216, 164, 73,
73, 167, 168, 73, 73, 70, 348, 70, 283, 351,
354, 70, 165, 164, 69, 69, 167, 168, 70, 70,
167, 168, 70, 70, 69, 370, 69, 165, 373, 374,
69, 121, 410, 120, 216, 383, 216, 69, 69, 162,
386, 69, 69, 198, 325, 200, 201, 385, 73, 390,
387, 164, 73, 388, 395, 400, 403, 167, 168, 167,
168, 404, 433, 73, 151, 165, 406, 70, 412, 164,
414, 70, 415, 73, 427, -238, 166, 461, 425, 429,
428, 432, 70, 165, 431, 435, 69, 378, 443, 344,
69, 216, 70, 479, 449, 452, 458, 207, 468, 167,
168, 69, 453, 469, 462, 73, 73, 464, 482, 484,
489, 69, 485, 480, 167, 168, 490, 99, 109, 113,
493, 496, 113, 497, 70, 70, 498, 73, 502, 216,
73, 250, 500, 460, 501, -139, 180, 73, -139, 475,
211, 73, 436, 69, 69, 73, 70, 216, 488, 70,
494, 346, 167, 168, 491, 334, 70, 117, 111, 486,
70, 437, 401, 402, 70, 69, 0, 0, 69, 0,
167, 168, 405, 0, 407, 69, 0, 0, 411, 69,
187, 188, 189, 69, 248, 416, 417, 0, 0, 422,
423, 0, 208, -36, 0, 180, 0, 0, 302, 303,
304, 305, 306, 307, 308, 309, 310, 311, -139, 0,
0, 0, 180, 0, 0, 227, 229, 0, 230, 0,
0, 0, 235, 237, 238, 0, 0, 240, 244, 0,
245, 0, 0, 0, 445, 0, 0, 0, 447, 187,
188, 189, 0, 255, 256, 259, 0, 121, 0, 454,
181, 182, 183, 184, 185, 186, 187, 188, 189, 459,
0, 0, 0, 0, 268, 269, 0, 272, 273, 0,
377, 0, 0, 0, 0, 284, 0, 0, 291, 0,
284, 294, 295, 296, 297, 298, 299, 0, 0, 0,
0, 243, 481, 192, 193, 194, 0, 195, 196, 197,
198, 199, 200, 201, 195, 196, 197, 198, 199, 200,
201, 0, 0, 492, 0, 332, 495, 333, 0, 0,
0, 335, 0, 0, 0, 0, 336, 499, 397, 192,
0, 194, 0, 195, 196, 197, 198, 199, 200, 201,
-16, 6, 0, 0, 0, 7, 357, 8, 0, 0,
9, 10, 11, 0, 0, 0, 0, 12, 13, 14,
284, 15, 16, 17, 18, 0, 0, 0, 0, 19,
381, 20, 21, 22, 0, 23, 24, 25, 26, 27,
28, -16, -16, 29, 0, 30, 31, 32, 33, 34,
35, 0, 0, 0, 0, 0, 0, 36, 37, 38,
39, 40, 0, 0, 0, 0, 0, 0, 41, 42,
0, 43, 44, 45, 46, 47, 48, 49, 50, 0,
51, 7, 52, 53, 54, 398, 9, 10, 55, 0,
0, 56, 0, 57, 13, 0, 0, 15, 16, 17,
18, 408, 0, 58, 0, 0, 0, 0, 0, 59,
60, 61, 62, 25, 421, 27, 0, 0, 0, 29,
0, 0, 426, 192, 0, 0, 35, 195, 196, 197,
198, 199, 200, 201, 434, 0, 0, 0, 0, 0,
0, 0, 0, 0, 41, 42, 0, 43, 44, 45,
46, 47, 48, 49, 50, 0, 51, 0, 52, 53,
54, 0, 0, 0, 55, 0, 0, 56, 0, 57,
0, 0, 0, 0, 0, 0, 0, 0, 0, 58,
456, 0, 0, 0, 0, 0, 60, 61, 62, 0,
0, 0, 0, 0, 0, 465, 0, 0, 466, 467,
0, 0, 0, 0, 95, 0, 0, 0, 7, 0,
8, 477, 0, 9, 10, 11, 0, 0, 0, 0,
12, 13, 14, 0, 15, 16, 17, 18, 0, 487,
-16, 408, 19, 0, 20, 21, 22, 0, 23, 24,
25, 26, 27, 28, -16, -16, 29, 0, 30, 31,
32, 33, 34, 35, 0, 0, 0, 0, 0, 0,
36, 37, 38, 39, 40, 0, 0, 0, 0, 0,
0, 41, 42, 0, 43, 44, 45, 46, 47, 48,
49, 50, 0, 51, 0, 52, 53, 54, 108, 0,
0, 55, 7, 0, 56, 0, 57, 9, 10, 0,
0, 0, 0, 0, 0, 13, 58, 0, 15, 16,
17, 18, 59, 60, 61, 62, 0, -154, 0, 0,
0, 0, 0, 0, 25, 0, 27, 0, 0, 0,
29, 0, 0, 0, 0, 0, 0, 35, 0, 0,
0, 0, 0, 0, 36, 37, 0, 0, 0, 0,
0, 0, 0, 0, 0, 41, 42, 0, 43, 44,
45, 46, 47, 48, 49, 50, 0, 51, 7, 52,
53, 54, 0, 9, 10, 55, 0, 0, 56, 0,
57, 13, 0, 0, 15, 16, 17, 18, 0, 0,
58, 0, 0, 0, 0, 0, 59, 60, 61, 62,
25, 0, 27, 0, 0, 0, 29, 0, 0, 0,
0, 0, 0, 35, 0, 0, 0, 0, 0, 0,
36, 37, 0, 0, 0, 0, 0, 0, 0, 0,
0, 41, 42, 0, 43, 44, 45, 46, 47, 48,
49, 50, 0, 51, 0, 52, 53, 54, 0, 0,
0, 55, 0, 0, 56, 0, 57, 0, 0, 0,
0, 0, 0, 0, 0, 0, 58, 0, 0, 0,
0, 0, 59, 60, 61, 62, 292, 7, 0, 8,
0, 0, 9, 10, 11, 0, 0, 0, 0, 12,
13, 14, 0, 15, 16, 17, 18, 0, 0, 0,
0, 19, 0, 20, 21, 22, 0, 23, 24, 25,
26, 27, 28, 0, 0, 29, 0, 30, 31, 32,
33, 34, 35, 0, 0, 0, 0, 0, 0, 36,
37, 38, 39, 40, 0, 0, 0, 0, 0, 0,
41, 42, 0, 43, 44, 45, 46, 47, 48, 49,
50, 0, 51, 0, 52, 53, 54, 0, 0, 0,
55, 0, 0, 56, 0, 57, 0, 0, 0, 0,
0, 0, 0, 0, 0, 58, 0, 0, 0, 0,
0, 59, 60, 61, 62, 7, 0, 8, 0, 0,
9, 10, 11, 0, 0, 0, 0, 12, 13, 14,
0, 15, 16, 17, 18, 0, 0, 0, 0, 19,
0, 20, 21, 22, 0, 23, 24, 241, 26, 27,
28, 0, 0, 29, 0, 30, 31, 32, 33, 34,
35, 0, 0, 0, 0, 0, 0, 36, 37, 38,
39, 40, 0, 0, 0, 0, 0, 0, 41, 42,
0, 43, 44, 45, 46, 47, 48, 49, 50, 0,
51, 7, 52, 53, 54, 0, 9, 10, 55, 0,
0, 56, 0, 57, 13, 0, 0, 15, 16, 17,
18, 0, 0, 58, 0, 0, 0, 0, 0, 59,
60, 61, 62, 25, 0, 27, 0, 0, 0, 29,
0, 0, 0, 0, 0, 0, 35, 0, 0, 0,
0, 0, 0, 36, 37, 0, 0, 0, 0, 0,
0, 0, 0, 0, 41, 42, 0, 43, 44, 45,
46, 47, 48, 49, 50, 98, 51, 7, 52, 53,
54, 0, 9, 10, 55, 0, 0, 56, 0, 57,
13, 0, 0, 15, 16, 17, 18, 0, 0, 58,
0, 0, 0, 0, 0, 59, 60, 61, 62, 25,
0, 27, 0, 0, 0, 29, 0, 0, 0, 0,
0, 0, 35, 0, 0, 0, 0, 0, 0, 36,
37, 0, 0, 0, 0, 0, 0, 0, 0, 0,
41, 42, 0, 43, 44, 45, 46, 47, 48, 49,
50, 0, 51, 7, 52, 53, 54, 0, 9, 10,
55, 0, 0, 56, 0, 57, 13, 0, 0, 15,
16, 17, 18, 0, 0, 58, 0, 0, 0, 0,
0, 59, 60, 61, 62, 25, 0, 27, 312, 313,
314, 315, 316, 317, 318, 319, 320, 321, 35, 0,
0, 0, 0, 0, 0, 36, 37, 0, 0, 0,
0, 0, 0, 0, 0, 0, 41, 42, 0, 43,
44, 45, 46, 47, 48, 49, 50, 0, 51, 7,
52, 53, 54, 0, 9, 10, 55, 0, 0, 56,
0, 57, 13, 0, 0, 15, 16, 17, 18, 0,
0, 58, 0, 0, 0, 0, 0, 59, 60, 61,
62, 25, 0, 27, 0, 0, 0, 29, 0, 0,
0, 0, 0, 0, 353, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 41, 42, 0, 43, 44, 45, 46, 47,
48, 49, 50, 0, 51, 7, 52, 53, 54, 0,
9, 0, 55, 0, 0, 56, 0, 57, 13, 0,
0, 15, 16, 17, 18, 0, 0, 58, 0, 0,
0, 0, 0, 0, 60, 61, 62, 0, 0, 27,
0, 0, 0, 29, 0, 0, 0, 7, 0, 0,
35, 0, 9, 0, 0, 0, 0, 0, 0, 0,
13, 0, 0, 15, 16, 17, 18, 0, 41, 42,
0, 43, 44, 45, 46, 125, 48, 49, 50, 0,
51, 27, 52, 53, 54, 29, 0, 0, 55, 0,
0, 56, 35, 57, 0, 0, 0, 0, 0, 0,
0, 0, 0, 58, 0, 0, 0, 0, 0, 0,
60, 61, 62, 43, 44, 45, 46, 125, 48, 49,
50, 0, 51, 0, 52, 53, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 58, 0, 0, 0, 0,
0, 0, 60, 61, 62
};
const short
parser::yycheck_[] =
{
2, 3, 107, 16, 2, 146, 166, 60, 61, 62,
17, 22, 50, 24, 16, 115, 24, 20, 227, 2,
3, 6, 122, 20, 124, 166, 235, 29, 20, 238,
32, 13, 0, 16, 23, 20, 38, 26, 2, 3,
50, 23, 50, 6, 26, 83, 24, 172, 153, 32,
13, 0, 16, 36, 37, 6, 43, 40, 41, 42,
23, 6, 271, 50, 24, 75, 191, 37, 32, 20,
24, 73, 50, 41, 42, 20, 6, 9, 24, 0,
93, 84, 13, 34, 16, 30, 25, 84, 75, 20,
20, 93, 84, 34, 79, 97, 24, 36, 37, 84,
30, 40, 41, 42, 107, 83, 24, 96, 95, 50,
93, 71, 18, 24, 96, 54, 55, 56, 57, 58,
41, 42, 107, 108, 6, 112, 128, 6, 27, 93,
81, 37, 24, 84, 75, 22, 402, 19, 20, 84,
37, 20, 41, 42, 50, 128, 246, 30, 357, 9,
416, 30, 91, 50, 84, 15, 107, 108, 41, 42,
162, 163, 107, 108, 128, 24, 326, 8, 175, 6,
24, 276, 174, 14, 176, 43, 44, 107, 108, 162,
163, 24, 20, 20, 450, 326, 24, 189, 454, 24,
399, 174, 26, 30, 177, 6, 30, 6, 162, 163,
24, 254, 84, 205, 206, 84, 24, 205, 206, 20,
174, 20, 214, 173, 41, 42, 32, 6, 22, 30,
24, 30, 205, 206, 13, 107, 108, 24, 107, 108,
50, 20, 6, 162, 163, 288, 24, 77, 177, 292,
27, 205, 206, 24, 80, 26, 20, 84, 78, 251,
6, 24, 28, 192, 193, 194, 195, 196, 197, 198,
199, 200, 201, 368, 20, 6, 41, 28, 30, 6,
107, 108, 232, 84, 30, 84, 50, 41, 30, 20,
68, 69, 70, 20, 286, 54, 55, 56, 57, 249,
250, 41, 22, 30, 101, 84, 107, 108, 107, 108,
24, 42, 241, 54, 55, 56, 6, 50, 6, 24,
84, 50, 128, 91, 92, 93, 94, 95, 107, 108,
20, 281, 20, 41, 26, 264, 328, 329, 84, 30,
30, 20, 30, 107, 108, 30, 338, 1, 340, 3,
4, 301, 344, 84, 24, 328, 329, 84, 6, 351,
352, 107, 108, 355, 356, 338, 30, 340, 174, 30,
42, 344, 20, 6, 328, 329, 107, 108, 351, 352,
107, 108, 355, 356, 338, 26, 340, 20, 27, 42,
344, 25, 342, 322, 84, 41, 84, 351, 352, 43,
50, 355, 356, 92, 34, 94, 95, 30, 400, 28,
50, 6, 404, 50, 30, 30, 27, 107, 108, 107,
108, 30, 372, 415, 58, 20, 22, 400, 16, 6,
30, 404, 30, 425, 41, 30, 84, 429, 30, 41,
27, 30, 415, 20, 50, 13, 400, 50, 30, 15,
404, 84, 425, 30, 9, 30, 30, 91, 28, 107,
108, 415, 412, 19, 50, 457, 458, 50, 25, 50,
13, 425, 26, 457, 107, 108, 27, 17, 18, 19,
30, 50, 22, 13, 457, 458, 489, 479, 50, 84,
482, 134, 496, 427, 497, 23, 24, 489, 26, 449,
94, 493, 380, 457, 458, 497, 479, 84, 471, 482,
481, 233, 107, 108, 476, 217, 489, 22, 18, 466,
493, 383, 328, 329, 497, 479, -1, -1, 482, -1,
107, 108, 338, -1, 340, 489, -1, -1, 344, 493,
68, 69, 70, 497, 13, 351, 352, -1, -1, 355,
356, -1, 92, 22, -1, 24, -1, -1, 192, 193,
194, 195, 196, 197, 198, 199, 200, 201, 96, -1,
-1, -1, 24, -1, -1, 115, 116, -1, 118, -1,
-1, -1, 122, 123, 124, -1, -1, 127, 128, -1,
130, -1, -1, -1, 400, -1, -1, -1, 404, 68,
69, 70, -1, 143, 144, 145, -1, 241, -1, 415,
62, 63, 64, 65, 66, 67, 68, 69, 70, 425,
-1, -1, -1, -1, 164, 165, -1, 167, 168, -1,
264, -1, -1, -1, -1, 175, -1, -1, 178, -1,
180, 181, 182, 183, 184, 185, 186, -1, -1, -1,
-1, 457, 458, 85, 86, 87, -1, 89, 90, 91,
92, 93, 94, 95, 89, 90, 91, 92, 93, 94,
95, -1, -1, 479, -1, 215, 482, 217, -1, -1,
-1, 221, -1, -1, -1, -1, 226, 493, 322, 85,
-1, 87, -1, 89, 90, 91, 92, 93, 94, 95,
0, 1, -1, -1, -1, 5, 246, 7, -1, -1,
10, 11, 12, -1, -1, -1, -1, 17, 18, 19,
260, 21, 22, 23, 24, -1, -1, -1, -1, 29,
270, 31, 32, 33, -1, 35, 36, 37, 38, 39,
40, 41, 42, 43, -1, 45, 46, 47, 48, 49,
50, -1, -1, -1, -1, -1, -1, 57, 58, 59,
60, 61, -1, -1, -1, -1, -1, -1, 68, 69,
-1, 71, 72, 73, 74, 75, 76, 77, 78, -1,
80, 5, 82, 83, 84, 325, 10, 11, 88, -1,
-1, 91, -1, 93, 18, -1, -1, 21, 22, 23,
24, 341, -1, 103, -1, -1, -1, -1, -1, 109,
110, 111, 112, 37, 354, 39, -1, -1, -1, 43,
-1, -1, 362, 85, -1, -1, 50, 89, 90, 91,
92, 93, 94, 95, 374, -1, -1, -1, -1, -1,
-1, -1, -1, -1, 68, 69, -1, 71, 72, 73,
74, 75, 76, 77, 78, -1, 80, -1, 82, 83,
84, -1, -1, -1, 88, -1, -1, 91, -1, 93,
-1, -1, -1, -1, -1, -1, -1, -1, -1, 103,
420, -1, -1, -1, -1, -1, 110, 111, 112, -1,
-1, -1, -1, -1, -1, 435, -1, -1, 438, 439,
-1, -1, -1, -1, 1, -1, -1, -1, 5, -1,
7, 451, -1, 10, 11, 12, -1, -1, -1, -1,
17, 18, 19, -1, 21, 22, 23, 24, -1, 469,
27, 471, 29, -1, 31, 32, 33, -1, 35, 36,
37, 38, 39, 40, 41, 42, 43, -1, 45, 46,
47, 48, 49, 50, -1, -1, -1, -1, -1, -1,
57, 58, 59, 60, 61, -1, -1, -1, -1, -1,
-1, 68, 69, -1, 71, 72, 73, 74, 75, 76,
77, 78, -1, 80, -1, 82, 83, 84, 1, -1,
-1, 88, 5, -1, 91, -1, 93, 10, 11, -1,
-1, -1, -1, -1, -1, 18, 103, -1, 21, 22,
23, 24, 109, 110, 111, 112, -1, 30, -1, -1,
-1, -1, -1, -1, 37, -1, 39, -1, -1, -1,
43, -1, -1, -1, -1, -1, -1, 50, -1, -1,
-1, -1, -1, -1, 57, 58, -1, -1, -1, -1,
-1, -1, -1, -1, -1, 68, 69, -1, 71, 72,
73, 74, 75, 76, 77, 78, -1, 80, 5, 82,
83, 84, -1, 10, 11, 88, -1, -1, 91, -1,
93, 18, -1, -1, 21, 22, 23, 24, -1, -1,
103, -1, -1, -1, -1, -1, 109, 110, 111, 112,
37, -1, 39, -1, -1, -1, 43, -1, -1, -1,
-1, -1, -1, 50, -1, -1, -1, -1, -1, -1,
57, 58, -1, -1, -1, -1, -1, -1, -1, -1,
-1, 68, 69, -1, 71, 72, 73, 74, 75, 76,
77, 78, -1, 80, -1, 82, 83, 84, -1, -1,
-1, 88, -1, -1, 91, -1, 93, -1, -1, -1,
-1, -1, -1, -1, -1, -1, 103, -1, -1, -1,
-1, -1, 109, 110, 111, 112, 113, 5, -1, 7,
-1, -1, 10, 11, 12, -1, -1, -1, -1, 17,
18, 19, -1, 21, 22, 23, 24, -1, -1, -1,
-1, 29, -1, 31, 32, 33, -1, 35, 36, 37,
38, 39, 40, -1, -1, 43, -1, 45, 46, 47,
48, 49, 50, -1, -1, -1, -1, -1, -1, 57,
58, 59, 60, 61, -1, -1, -1, -1, -1, -1,
68, 69, -1, 71, 72, 73, 74, 75, 76, 77,
78, -1, 80, -1, 82, 83, 84, -1, -1, -1,
88, -1, -1, 91, -1, 93, -1, -1, -1, -1,
-1, -1, -1, -1, -1, 103, -1, -1, -1, -1,
-1, 109, 110, 111, 112, 5, -1, 7, -1, -1,
10, 11, 12, -1, -1, -1, -1, 17, 18, 19,
-1, 21, 22, 23, 24, -1, -1, -1, -1, 29,
-1, 31, 32, 33, -1, 35, 36, 37, 38, 39,
40, -1, -1, 43, -1, 45, 46, 47, 48, 49,
50, -1, -1, -1, -1, -1, -1, 57, 58, 59,
60, 61, -1, -1, -1, -1, -1, -1, 68, 69,
-1, 71, 72, 73, 74, 75, 76, 77, 78, -1,
80, 5, 82, 83, 84, -1, 10, 11, 88, -1,
-1, 91, -1, 93, 18, -1, -1, 21, 22, 23,
24, -1, -1, 103, -1, -1, -1, -1, -1, 109,
110, 111, 112, 37, -1, 39, -1, -1, -1, 43,
-1, -1, -1, -1, -1, -1, 50, -1, -1, -1,
-1, -1, -1, 57, 58, -1, -1, -1, -1, -1,
-1, -1, -1, -1, 68, 69, -1, 71, 72, 73,
74, 75, 76, 77, 78, 79, 80, 5, 82, 83,
84, -1, 10, 11, 88, -1, -1, 91, -1, 93,
18, -1, -1, 21, 22, 23, 24, -1, -1, 103,
-1, -1, -1, -1, -1, 109, 110, 111, 112, 37,
-1, 39, -1, -1, -1, 43, -1, -1, -1, -1,
-1, -1, 50, -1, -1, -1, -1, -1, -1, 57,
58, -1, -1, -1, -1, -1, -1, -1, -1, -1,
68, 69, -1, 71, 72, 73, 74, 75, 76, 77,
78, -1, 80, 5, 82, 83, 84, -1, 10, 11,
88, -1, -1, 91, -1, 93, 18, -1, -1, 21,
22, 23, 24, -1, -1, 103, -1, -1, -1, -1,
-1, 109, 110, 111, 112, 37, -1, 39, 97, 98,
99, 100, 101, 102, 103, 104, 105, 106, 50, -1,
-1, -1, -1, -1, -1, 57, 58, -1, -1, -1,
-1, -1, -1, -1, -1, -1, 68, 69, -1, 71,
72, 73, 74, 75, 76, 77, 78, -1, 80, 5,
82, 83, 84, -1, 10, 11, 88, -1, -1, 91,
-1, 93, 18, -1, -1, 21, 22, 23, 24, -1,
-1, 103, -1, -1, -1, -1, -1, 109, 110, 111,
112, 37, -1, 39, -1, -1, -1, 43, -1, -1,
-1, -1, -1, -1, 50, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, 68, 69, -1, 71, 72, 73, 74, 75,
76, 77, 78, -1, 80, 5, 82, 83, 84, -1,
10, -1, 88, -1, -1, 91, -1, 93, 18, -1,
-1, 21, 22, 23, 24, -1, -1, 103, -1, -1,
-1, -1, -1, -1, 110, 111, 112, -1, -1, 39,
-1, -1, -1, 43, -1, -1, -1, 5, -1, -1,
50, -1, 10, -1, -1, -1, -1, -1, -1, -1,
18, -1, -1, 21, 22, 23, 24, -1, 68, 69,
-1, 71, 72, 73, 74, 75, 76, 77, 78, -1,
80, 39, 82, 83, 84, 43, -1, -1, 88, -1,
-1, 91, 50, 93, -1, -1, -1, -1, -1, -1,
-1, -1, -1, 103, -1, -1, -1, -1, -1, -1,
110, 111, 112, 71, 72, 73, 74, 75, 76, 77,
78, -1, 80, -1, 82, 83, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, 103, -1, -1, -1, -1,
-1, -1, 110, 111, 112
};
const unsigned char
parser::yystos_[] =
{
0, 1, 3, 4, 115, 116, 1, 5, 7, 10,
11, 12, 17, 18, 19, 21, 22, 23, 24, 29,
31, 32, 33, 35, 36, 37, 38, 39, 40, 43,
45, 46, 47, 48, 49, 50, 57, 58, 59, 60,
61, 68, 69, 71, 72, 73, 74, 75, 76, 77,
78, 80, 82, 83, 84, 88, 91, 93, 103, 109,
110, 111, 112, 117, 120, 121, 123, 124, 129, 134,
138, 151, 152, 153, 154, 155, 156, 157, 161, 163,
166, 167, 171, 173, 118, 119, 120, 0, 0, 41,
42, 37, 24, 24, 24, 1, 119, 153, 79, 129,
134, 138, 153, 158, 159, 160, 179, 180, 1, 129,
162, 180, 181, 129, 175, 24, 24, 175, 24, 124,
152, 154, 24, 24, 24, 75, 153, 24, 24, 123,
24, 184, 138, 152, 152, 153, 18, 37, 50, 133,
152, 152, 152, 24, 22, 24, 50, 171, 171, 171,
171, 154, 164, 165, 78, 176, 176, 176, 176, 0,
41, 42, 43, 44, 6, 20, 84, 107, 108, 24,
50, 83, 135, 190, 13, 23, 26, 96, 24, 124,
24, 62, 63, 64, 65, 66, 67, 68, 69, 70,
182, 153, 85, 86, 87, 89, 90, 91, 92, 93,
94, 95, 174, 77, 80, 41, 42, 154, 129, 168,
119, 135, 27, 27, 34, 79, 84, 41, 191, 28,
28, 41, 191, 30, 30, 30, 41, 129, 168, 129,
129, 9, 16, 144, 147, 129, 168, 129, 129, 168,
129, 37, 122, 123, 129, 129, 24, 50, 13, 128,
128, 22, 50, 50, 24, 129, 129, 177, 178, 129,
24, 182, 183, 101, 41, 191, 121, 121, 129, 129,
20, 183, 129, 129, 37, 187, 188, 189, 193, 26,
26, 190, 124, 123, 129, 179, 43, 95, 112, 153,
138, 129, 113, 179, 129, 129, 129, 129, 129, 129,
153, 190, 154, 154, 154, 154, 154, 154, 154, 154,
154, 154, 97, 98, 99, 100, 101, 102, 103, 104,
105, 106, 172, 120, 120, 34, 81, 170, 30, 30,
30, 153, 129, 129, 158, 129, 129, 170, 30, 30,
30, 24, 146, 124, 15, 140, 147, 170, 30, 30,
170, 30, 30, 50, 42, 30, 30, 129, 168, 54,
55, 56, 125, 126, 127, 124, 124, 130, 131, 153,
26, 176, 30, 27, 42, 192, 30, 154, 50, 136,
137, 129, 170, 41, 191, 30, 50, 50, 50, 124,
28, 153, 176, 30, 176, 30, 124, 154, 129, 183,
30, 123, 123, 27, 30, 123, 22, 123, 129, 145,
124, 123, 16, 149, 30, 30, 123, 123, 13, 20,
150, 129, 123, 123, 170, 30, 129, 41, 27, 41,
191, 50, 30, 124, 129, 13, 136, 187, 6, 13,
23, 185, 186, 30, 170, 123, 140, 123, 142, 9,
148, 19, 30, 124, 123, 140, 129, 42, 30, 123,
126, 153, 50, 132, 50, 129, 129, 129, 28, 19,
169, 8, 14, 139, 143, 124, 140, 129, 140, 30,
122, 123, 25, 141, 50, 26, 186, 129, 145, 13,
27, 149, 123, 30, 141, 123, 50, 13, 119, 123,
132, 119, 50
};
const unsigned char
parser::yyr1_[] =
{
0, 114, 115, 116, 116, 116, 117, 117, 117, 117,
117, 117, 118, 119, 119, 119, 120, 120, 120, 121,
121, 121, 122, 122, 123, 123, 124, 124, 124, 125,
125, 125, 125, 126, 127, 127, 128, 128, 129, 129,
130, 130, 131, 131, 123, 132, 133, 133, 123, 123,
123, 123, 123, 134, 134, 123, 123, 135, 135, 135,
136, 137, 137, 129, 129, 129, 129, 129, 129, 129,
129, 138, 138, 138, 123, 123, 123, 123, 123, 123,
123, 123, 123, 123, 123, 123, 123, 123, 123, 123,
123, 139, 139, 140, 140, 141, 141, 142, 142, 143,
144, 144, 145, 145, 146, 146, 147, 148, 148, 149,
149, 123, 123, 123, 123, 123, 123, 123, 123, 150,
150, 138, 138, 151, 151, 138, 138, 138, 138, 138,
138, 152, 152, 152, 138, 138, 153, 154, 154, 138,
138, 155, 154, 153, 138, 156, 157, 157, 158, 159,
159, 160, 160, 161, 162, 162, 162, 163, 164, 164,
165, 165, 166, 166, 166, 166, 166, 166, 166, 166,
167, 167, 166, 168, 169, 169, 170, 170, 152, 166,
166, 138, 138, 138, 138, 171, 171, 171, 171, 171,
171, 171, 154, 154, 154, 154, 154, 154, 154, 154,
154, 154, 154, 172, 172, 172, 172, 172, 172, 172,
172, 172, 172, 173, 174, 174, 129, 129, 129, 129,
129, 175, 175, 176, 129, 138, 152, 152, 152, 138,
177, 177, 178, 178, 179, 179, 180, 180, 181, 182,
183, 183, 184, 184, 185, 186, 186, 187, 187, 187,
188, 188, 189, 189, 190, 190, 191, 191, 192, 192,
193, 193
};
const unsigned char
parser::yyr2_[] =
{
0, 2, 1, 1, 2, 2, 2, 2, 2, 2,
2, 2, 1, 1, 3, 3, 0, 1, 2, 1,
3, 3, 0, 1, 3, 1, 3, 3, 5, 0,
1, 1, 1, 2, 1, 3, 0, 2, 4, 4,
0, 2, 1, 3, 5, 1, 1, 1, 3, 7,
10, 2, 4, 1, 1, 4, 4, 1, 3, 3,
3, 1, 2, 3, 4, 3, 3, 3, 3, 3,
3, 2, 2, 3, 8, 7, 5, 6, 6, 5,
6, 5, 8, 8, 2, 1, 1, 5, 4, 7,
6, 0, 3, 0, 2, 0, 2, 0, 2, 4,
1, 2, 1, 3, 0, 3, 3, 0, 2, 0,
2, 5, 4, 2, 2, 5, 9, 8, 5, 1,
1, 1, 5, 1, 1, 4, 4, 4, 2, 4,
4, 1, 3, 3, 2, 4, 1, 2, 3, 1,
2, 3, 1, 1, 3, 1, 1, 2, 3, 1,
3, 1, 2, 3, 0, 2, 1, 3, 0, 2,
1, 3, 1, 1, 1, 1, 3, 3, 1, 1,
1, 2, 1, 5, 0, 2, 0, 2, 4, 1,
1, 1, 3, 3, 3, 1, 2, 2, 2, 2,
2, 2, 1, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 2, 0, 3, 1, 3, 3, 3,
4, 0, 1, 1, 2, 2, 2, 2, 4, 5,
0, 2, 1, 3, 0, 2, 1, 3, 3, 3,
0, 1, 0, 2, 2, 0, 1, 3, 5, 4,
1, 3, 0, 2, 0, 3, 0, 1, 0, 1,
0, 1
};
// YYTNAME[SYMBOL-NUM] -- String name of the symbol SYMBOL-NUM.
// First, the terminals, then, starting at \a yyntokens_, nonterminals.
const char*
const parser::yytname_[] =
{
"\"end of command\"", "error", "$undefined", "MODE_EXP", "MODE_EXPS",
"\"__HERE__\"", "\"=\"", "\"break\"", "\"case\"", "\"catch\"",
"\"closure\"", "\"const\"", "\"continue\"", "\":\"", "\"default\"",
"\"else\"", "\"finally\"", "\"freezeif\"", "\"function\"", "\"if\"",
"\"in\"", "\"isdef\"", "\"{\"", "\"[\"", "\"(\"", "\"onleave\"", "\".\"",
"\"}\"", "\"]\"", "\"return\"", "\")\"", "\"stopif\"", "\"switch\"",
"\"throw\"", "\"~\"", "\"timeout\"", "\"try\"", "\"var\"",
"\"waituntil\"", "\"watch\"", "\"whenever\"", "\",\"", "\";\"", "\"&\"",
"\"|\"", "\"every\"", "\"for\"", "\"loop\"", "\"while\"", "\"at\"",
"\"identifier\"", "ASSIGN", "EMPTY", "UNARY", "\"private\"",
"\"protected\"", "\"public\"", "\"class\"", "\"package\"", "\"enum\"",
"\"external\"", "\"import\"", "\"^=\"", "\"-=\"", "\"%=\"", "\"+=\"",
"\"/=\"", "\"*=\"", "\"--\"", "\"++\"", "\"->\"", "\"do\"", "\"assert\"",
"\"detach\"", "\"disown\"", "\"new\"", "\"angle\"", "\"duration\"",
"\"float\"", "\"=>\"", "\"string\"", "\"?\"", "\"call\"", "\"this\"",
"\"!\"", "\"bitand\"", "\"bitor\"", "\"^\"", "\"compl\"", "\">>\"",
"\"<<\"", "\"-\"", "\"%\"", "\"+\"", "\"/\"", "\"*\"", "\"**\"",
"\"=~=\"", "\"==\"", "\"===\"", "\">=\"", "\">\"", "\"<=\"", "\"<\"",
"\"!=\"", "\"!==\"", "\"~=\"", "\"&&\"", "\"||\"", "\"%unscope:\"",
"\"%exp:\"", "\"%lvalue:\"", "\"%id:\"", "\"%exps:\"", "$accept",
"start", "root", "root_exp", "root_exps", "stmts", "cstmt.opt", "cstmt",
"stmt.opt", "stmt", "block", "visibility", "proto", "protos.1", "protos",
"exp", "id.0", "id.1", "from", "event_or_function", "routine", "k1_id",
"modifier", "modifiers", "primary-exp", "default.opt", "else.opt",
"onleave.opt", "cases", "case", "catches.1", "match", "match.opt",
"catch", "catch.opt", "finally.opt", "in_or_colon", "detach", "lvalue",
"id", "bitor-exp", "new", "float-exp", "duration", "assoc", "assocs.1",
"assocs", "dictionary", "tuple.exps", "tuple", "bitor-exps",
"bitor-exps.1", "literal-exp", "string", "event_match", "guard.opt",
"tilda.opt", "unary-exp", "rel-op", "rel-exp", "rel-ops", "exp.opt",
"unsigned", "claims", "claims.1", "exps", "exps.1", "exps.2", "args",
"args.opt", "identifiers", "typespec", "typespec.opt", "formal",
"formals.1", "formals.0", "formals", "comma.opt", "semi.opt", "var.opt", YY_NULLPTR
};
#if YYDEBUG
const unsigned short
parser::yyrline_[] =
{
0, 313, 313, 328, 329, 330, 336, 337, 338, 339,
340, 341, 346, 358, 359, 360, 368, 369, 370, 375,
376, 377, 387, 388, 393, 404, 408, 409, 413, 426,
428, 429, 430, 435, 441, 442, 447, 448, 453, 462,
478, 479, 483, 484, 489, 500, 509, 513, 523, 528,
533, 546, 587, 600, 601, 607, 613, 660, 661, 662,
673, 682, 686, 703, 707, 723, 724, 725, 726, 727,
728, 736, 737, 748, 759, 763, 767, 771, 775, 779,
783, 787, 791, 795, 800, 804, 808, 812, 816, 820,
824, 841, 842, 847, 848, 854, 855, 865, 866, 872,
881, 882, 887, 888, 891, 892, 896, 903, 904, 910,
911, 915, 919, 923, 952, 956, 960, 964, 968, 974,
974, 984, 985, 997, 998, 1002, 1003, 1004, 1005, 1006,
1007, 1017, 1018, 1019, 1023, 1024, 1028, 1032, 1036, 1043,
1047, 1060, 1072, 1077, 1087, 1104, 1114, 1115, 1128, 1136,
1140, 1148, 1149, 1154, 1165, 1166, 1167, 1171, 1185, 1186,
1190, 1191, 1199, 1200, 1201, 1202, 1203, 1204, 1205, 1206,
1212, 1213, 1221, 1231, 1239, 1240, 1245, 1246, 1255, 1271,
1272, 1276, 1277, 1278, 1279, 1284, 1285, 1286, 1287, 1288,
1289, 1290, 1315, 1316, 1317, 1318, 1319, 1320, 1321, 1322,
1323, 1324, 1325, 1351, 1352, 1353, 1354, 1355, 1356, 1357,
1358, 1359, 1360, 1364, 1369, 1370, 1384, 1385, 1386, 1391,
1392, 1396, 1397, 1408, 1416, 1428, 1436, 1444, 1448, 1456,
1473, 1474, 1478, 1479, 1485, 1486, 1490, 1491, 1495, 1500,
1504, 1505, 1515, 1516, 1521, 1526, 1527, 1532, 1533, 1534,
1540, 1541, 1546, 1547, 1552, 1553, 1556, 1556, 1557, 1557,
1558, 1558
};
// Print the state stack on the debug stream.
void
parser::yystack_print_ ()
{
*yycdebug_ << "Stack now";
for (stack_type::const_iterator
i = yystack_.begin (),
i_end = yystack_.end ();
i != i_end; ++i)
*yycdebug_ << ' ' << i->state;
*yycdebug_ << '\n';
}
// Report on the debug stream that the rule \a yyrule is going to be reduced.
void
parser::yy_reduce_print_ (int yyrule)
{
unsigned yylno = yyrline_[yyrule];
int yynrhs = yyr2_[yyrule];
// Print the symbols being reduced, and their result.
*yycdebug_ << "Reducing stack by rule " << yyrule - 1
<< " (line " << yylno << "):\n";
// The symbols being reduced.
for (int yyi = 0; yyi < yynrhs; yyi++)
YY_SYMBOL_PRINT (" $" << yyi + 1 << " =",
yystack_[(yynrhs) - (yyi + 1)]);
}
#endif // YYDEBUG
} // yy
#line 4902 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/build-sys-linux-x86_64/src/parser/ugrammar.cc" // lalr1.cc:1181
#line 1560 "/alpha/home/bearclaw/projects/urbirebord/urbiforge/urbi/src/parser/ugrammar.y" // lalr1.cc:1182
// The error function that 'bison' calls.
void
yy::parser::error(const location_type& l, const std::string& m)
{
GD_CATEGORY(Urbi.Error);
GD_FINFO_TRACE("%s: %s", l, m);
up.error(l, m);
}
// Local Variables:
// mode: c++
// End:
| 48.229408 | 329 | 0.587613 | [
"object",
"vector"
] |
a8b5e5cf3da563aa16fc190968e32c89cfd0a52a | 1,292 | cpp | C++ | applications/src/TestJSM.cpp | Sebanisu/VIIIcppTest | 59565ae2d32ea302401402544a70d3b37fab7351 | [
"MIT"
] | 2 | 2020-04-30T22:12:06.000Z | 2020-05-01T07:06:26.000Z | applications/src/TestJSM.cpp | Sebanisu/VIIIcppTest | 59565ae2d32ea302401402544a70d3b37fab7351 | [
"MIT"
] | 9 | 2020-04-26T01:52:21.000Z | 2020-05-20T21:10:28.000Z | applications/src/TestJSM.cpp | Sebanisu/VIIIcppTest | 59565ae2d32ea302401402544a70d3b37fab7351 | [
"MIT"
] | null | null | null | //
// Created by pcvii on 1/18/2021.
//
#include "TestJSM.hpp"
#include "open_viii/archive/Archives.hpp"
#include "open_viii/field/scripts/Jsm.hpp"
#include "open_viii/paths/Paths.hpp"
int
main()
{
const auto start = std::chrono::steady_clock::now();
open_viii::Paths::for_each_path([](const std::filesystem::path &path) {
std::cout << path << std::endl;
static constexpr auto coo = open_viii::LangT::en;
const auto archives = open_viii::archive::Archives(
path, open_viii::LangCommon::to_string<coo>());
if (!static_cast<bool>(archives)) {
std::cerr << "Failed to load path: " << path.string() << '\n';
return;
}
const open_viii::archive::FIFLFS<true> &field =
archives.get<open_viii::archive::ArchiveTypeT::field>();
field.execute_with_nested(
{},
[]([[maybe_unused]] const std::vector<char> &buffer,
const std::string & in_path) {
std::cout << in_path << std::endl;
[[maybe_unused]] auto jsm = open_viii::field::scripts::Jsm(buffer);
},
{ "jsm" });
});
const auto end = std::chrono::steady_clock::now();
const auto diff = end - start;
std::cout << std::chrono::duration<double, std::milli>(diff).count() << " ms"
<< '\n';
} | 35.888889 | 79 | 0.598297 | [
"vector"
] |
a8b9e6be84a34528c44fb1c98f94ee8cdd57e8d3 | 3,885 | hpp | C++ | source/util/AllocatorPointer.hpp | Xett/gba-modern | 8b74fcf78d49c156dc4ffa6c4adba8fd812004dd | [
"MIT"
] | 70 | 2019-08-10T05:44:02.000Z | 2022-02-19T10:19:14.000Z | source/util/AllocatorPointer.hpp | Xett/gba-modern | 8b74fcf78d49c156dc4ffa6c4adba8fd812004dd | [
"MIT"
] | 2 | 2020-11-26T06:25:21.000Z | 2020-12-03T13:34:46.000Z | source/util/AllocatorPointer.hpp | Xett/gba-modern | 8b74fcf78d49c156dc4ffa6c4adba8fd812004dd | [
"MIT"
] | 4 | 2020-04-12T04:08:40.000Z | 2020-11-17T19:32:03.000Z | //--------------------------------------------------------------------------------
// AllocatorPointer.hpp
//--------------------------------------------------------------------------------
// RAII wrapper over any object that implements a simple allocator pattern
//--------------------------------------------------------------------------------
#pragma once
#include <type_traits>
#include "bit-pointers.hpp"
// An allocator class that uses CRTP to access its derived type
template <typename T>
class Allocator
{
u16 refs;
protected:
// Increases the reference counter
void retain()
{
if (refs == 0) static_cast<T*>(this)->alloc();
refs++;
}
// Decreases the reference counter
void release()
{
refs--;
if (refs == 0) static_cast<T*>(this)->clear();
}
public:
Allocator() : refs(0) {}
~Allocator() { static_cast<T*>(this)->clear(); }
template <typename U>
friend class AllocatorPointer;
};
template <typename T>
class AllocatorPointer
{
static_assert(std::is_base_of_v<Allocator<T>, T>, "The allocator type must be derived from Allocator!");
// Since the address space of the GBA has only 28 bits, this is safe to do
constexpr static std::uintptr_t InactiveBit = 1 << 31;
protected:
T *allocator;
public:
AllocatorPointer() : allocator(nullptr) {}
AllocatorPointer(T& allocator, bool active = true) : allocator(&allocator)
{
if (active) allocator.retain();
else setBits(this->allocator, InactiveBit);
}
AllocatorPointer(const AllocatorPointer& o) : allocator(o.allocator)
{
if (o.active()) allocator->retain();
}
AllocatorPointer& operator=(const AllocatorPointer& o)
{
if (active()) allocator->release();
allocator = o.allocator;
if (active()) allocator->retain();
return *this;
}
AllocatorPointer(AllocatorPointer&& o) : allocator(o.allocator)
{
o.allocator = nullptr;
}
AllocatorPointer& operator=(AllocatorPointer&& o)
{
std::swap(allocator, o.allocator);
return *this;
}
~AllocatorPointer()
{
if (active()) allocator->release();
}
void setActive(bool act)
{
// Two cases
if (active() && !act)
{
allocator->release();
setBits(allocator, InactiveBit);
}
else if (!active() && act)
{
resetBits(allocator, InactiveBit);
allocator->retain();
}
}
explicit operator bool() const { return active(); }
bool active() const { return allocator && !hasOneOf(allocator, InactiveBit); }
};
#define INHERIT_ALLOCATOR_CTORS(Derived, ...) \
Derived() : AllocatorPointer<__VA_ARGS__>() {} \
Derived(__VA_ARGS__ &allocator, bool active = true) \
: AllocatorPointer<__VA_ARGS__>(allocator, active) {} \
Derived(const Derived &o) : AllocatorPointer<__VA_ARGS__>(o) {} \
Derived &operator=(const Derived &o) \
{ \
if (this->active()) this->allocator->release(); \
this->allocator = o.allocator; \
if (this->active()) this->allocator->retain(); \
return *this; \
} \
Derived(Derived &&o) : AllocatorPointer<__VA_ARGS__>(o) {} \
Derived &operator=(Derived &&o) \
{ \
std::swap(this->allocator, o.allocator); \
return *this; \
}
| 30.833333 | 108 | 0.490347 | [
"object"
] |
a8bf3323b760aca83809587629d79f98e8f185e4 | 225 | cpp | C++ | src/fluid4node.cpp | jabza/fluid4node | 831f3db39eb10e8c65bc6db7c40799c2dd16cd82 | [
"MIT"
] | 1 | 2022-03-30T21:36:07.000Z | 2022-03-30T21:36:07.000Z | src/fluid4node.cpp | jabza/fluid4node | 831f3db39eb10e8c65bc6db7c40799c2dd16cd82 | [
"MIT"
] | 3 | 2018-05-27T03:59:15.000Z | 2021-04-25T05:19:35.000Z | src/fluid4node.cpp | jabza/fluid4node | 831f3db39eb10e8c65bc6db7c40799c2dd16cd82 | [
"MIT"
] | 3 | 2020-08-29T22:46:03.000Z | 2021-04-05T02:45:26.000Z | //#define BUILDING_NODE_EXTENSION
#include <node.h>
#include "synth.h"
using namespace v8;
void Init(Handle<Object> exports, Local<Object> module) {
FluidSynth::Init(exports, module);
}
NODE_MODULE(fluid4node, Init)
| 17.307692 | 59 | 0.737778 | [
"object"
] |
a8c063f2fcc312af2c3a520fc62b6765ae98793d | 15,421 | cpp | C++ | src/AddingPluginView.cpp | kolayuk/TweakS | a5eb2e03454c29746f150df8e83d59f4b12cfc8f | [
"Apache-2.0"
] | null | null | null | src/AddingPluginView.cpp | kolayuk/TweakS | a5eb2e03454c29746f150df8e83d59f4b12cfc8f | [
"Apache-2.0"
] | null | null | null | src/AddingPluginView.cpp | kolayuk/TweakS | a5eb2e03454c29746f150df8e83d59f4b12cfc8f | [
"Apache-2.0"
] | 2 | 2016-10-27T21:13:31.000Z | 2021-09-26T13:17:02.000Z | /*
========================================================================
Name : AddingPluginView.cpp
Author : Usanov-Kornilov Nikolay (aka Kolay)
Copyright :
Contacts:
kolayuk@mail.ru
http://kolaysoft.ru
(c) KolaySoft, 2010
Description :
========================================================================
*/
// [[[ begin generated region: do not modify [Generated System Includes]
#include <aknviewappui.h>
#include <eikmenub.h>
#include <avkon.hrh>
#include <barsread.h>
#include <stringloader.h>
#include <aknlists.h>
#include <eikenv.h>
#include <akniconarray.h>
#include <eikclbd.h>
#include <akncontext.h>
#include <akntitle.h>
#include <eikbtgpc.h>
#include <TweakS.rsg>
// ]]] end generated region [Generated System Includes]
// [[[ begin generated region: do not modify [Generated User Includes]
#include "TweakS.hrh"
#include "AddingPluginView.h"
#include "PluginsList.hrh"
#include "ListOfSettings.hrh"
#include "PluginsManager.hrh"
#include "SettingList.hrh"
#include "AddingPlugin.hrh"
#include "AddingPlugin.h"
// ]]] end generated region [Generated User Includes]
// [[[ begin generated region: do not modify [Generated Constants]
// ]]] end generated region [Generated Constants]
#include <apgcli.h>
#include <TweakSAppUi.h>
#include <ListOfSettingsView.h>
#include <logger.h>
#include <aknpopup.h>
/**
* First phase of Symbian two-phase construction. Should not contain any
* code that could leave.
*/
CAddingPluginView::CAddingPluginView()
{
// [[[ begin generated region: do not modify [Generated Contents]
iAddingPlugin = NULL;
// ]]] end generated region [Generated Contents]
}
/**
* The view's destructor removes the container from the control
* stack and destroys it.
*/
CAddingPluginView::~CAddingPluginView()
{
// [[[ begin generated region: do not modify [Generated Contents]
delete iAddingPlugin;
iAddingPlugin = NULL;
// ]]] end generated region [Generated Contents]
}
/**
* Symbian two-phase constructor.
* This creates an instance then calls the second-phase constructor
* without leaving the instance on the cleanup stack.
* @return new instance of CAddingPluginView
*/
CAddingPluginView* CAddingPluginView::NewL()
{
CAddingPluginView* self = CAddingPluginView::NewLC();
CleanupStack::Pop( self );
return self;
}
/**
* Symbian two-phase constructor.
* This creates an instance, pushes it on the cleanup stack,
* then calls the second-phase constructor.
* @return new instance of CAddingPluginView
*/
CAddingPluginView* CAddingPluginView::NewLC()
{
CAddingPluginView* self = new ( ELeave ) CAddingPluginView();
CleanupStack::PushL( self );
self->ConstructL();
return self;
}
/**
* Second-phase constructor for view.
* Initialize contents from resource.
*/
void CAddingPluginView::ConstructL()
{
// [[[ begin generated region: do not modify [Generated Code]
BaseConstructL( R_ADDING_PLUGIN_ADDING_PLUGIN_VIEW );
// ]]] end generated region [Generated Code]
// add your own initialization code here
}
/**
* @return The UID for this view
*/
TUid CAddingPluginView::Id() const
{
return TUid::Uid( EAddingPluginViewId );
}
/**
* Handle a command for this view (override)
* @param aCommand command id to be handled
*/
void CAddingPluginView::HandleCommandL( TInt aCommand )
{
// [[[ begin generated region: do not modify [Generated Code]
TBool commandHandled = EFalse;
switch ( aCommand )
{ // code to dispatch to the AknView's menu and CBA commands is generated here
case EAddingPluginViewControlPaneRightId:
commandHandled = Back( aCommand );
break;
case EAddingPluginView_MenuItemCommand:
commandHandled = Add( aCommand );
break;
case EAddingPluginView_MenuItem1Command:
commandHandled = Edit( aCommand );
break;
case EAddingPluginView_C_MenuItemCommand:
commandHandled = Remove( aCommand );
break;
case EAddingPluginView_MenuItem4Command:
commandHandled = Reset( aCommand );
break;
case EAddingPluginView_MenuItem2Command:
commandHandled = Info( aCommand );
break;
case EAddingPluginView_MenuItem3Command:
commandHandled = Back( aCommand );
break;
default:
break;
}
if ( !commandHandled )
{
if ( aCommand == EAddingPluginViewControlPaneRightId )
{
AppUi()->HandleCommandL( EEikCmdExit );
}
}
// ]]] end generated region [Generated Code]
}
/**
* Handles user actions during activation of the view,
* such as initializing the content.
*/
void CAddingPluginView::Active(TSettingData aData)
{
iData=aData;
}
void CAddingPluginView::DoActivateL(
const TVwsViewId& /*aPrevViewId*/,
TUid /*aCustomMessageId*/,
const TDesC8& /*aCustomMessage*/ )
{
// [[[ begin generated region: do not modify [Generated Contents]
SetupStatusPaneL();
if ( iAddingPlugin == NULL )
{
iAddingPlugin = CreateContainerL();
iAddingPlugin->SetMopParent( this );
AppUi()->AddToStackL( *this, iAddingPlugin );
}
// ]]] end generated region [Generated Contents]
TBuf<255> text;
TInt res=R_ADDPLUGIN_EMPTY;
TRAPD(err,
{
CRepository* CR=CRepository::NewL(TUid::Uid(iData.iUid));
};);
if (err!=KErrNone){res=R_ADDPLUGIN_NOT_SUPPORTED;}
CEikonEnv::Static()->ReadResource(text,res);
iAddingPlugin->ListBox()->View()->SetListEmptyTextL(text);
if (err!=KErrNone)
{
TBuf<255> txt;
CEikonEnv::Static()->ReadResource(txt,R_ADDPLUGIN_NOT_SUPPORTED);
((CTweakSAppUi*)CEikonEnv::Static()->AppUi())->GlobalMsgQuery(txt,txt);
return;
}
iCR=CRepository::NewL(TUid::Uid(iData.iUid));
CListOfSettingsView::SetTitle(iData.iName);
Update();
}
/**
*/
void CAddingPluginView::DoDeactivate()
{
// [[[ begin generated region: do not modify [Generated Contents]
CleanupStatusPane();
if ( iAddingPlugin != NULL )
{
AppUi()->RemoveFromViewStack( *this, iAddingPlugin );
delete iAddingPlugin;
iAddingPlugin = NULL;
}
// ]]] end generated region [Generated Contents]
if (iCR){delete iCR;}
}
/**
* Handle status pane size change for this view (override)
*/
void CAddingPluginView::HandleStatusPaneSizeChange()
{
CAknView::HandleStatusPaneSizeChange();
// this may fail, but we're not able to propagate exceptions here
TVwsViewId view;
AppUi()->GetActiveViewId( view );
if ( view.iViewUid == Id() )
{
TInt result;
TRAP( result, SetupStatusPaneL() );
}
// [[[ begin generated region: do not modify [Generated Code]
// ]]] end generated region [Generated Code]
}
// [[[ begin generated function: do not modify
void CAddingPluginView::SetupStatusPaneL()
{
// reset the context pane
TUid contextPaneUid = TUid::Uid( EEikStatusPaneUidContext );
CEikStatusPaneBase::TPaneCapabilities subPaneContext =
StatusPane()->PaneCapabilities( contextPaneUid );
if ( subPaneContext.IsPresent() && subPaneContext.IsAppOwned() )
{
CAknContextPane* context = static_cast< CAknContextPane* > (
StatusPane()->ControlL( contextPaneUid ) );
context->SetPictureToDefaultL();
}
// setup the title pane
TUid titlePaneUid = TUid::Uid( EEikStatusPaneUidTitle );
CEikStatusPaneBase::TPaneCapabilities subPaneTitle =
StatusPane()->PaneCapabilities( titlePaneUid );
if ( subPaneTitle.IsPresent() && subPaneTitle.IsAppOwned() )
{
CAknTitlePane* title = static_cast< CAknTitlePane* >(
StatusPane()->ControlL( titlePaneUid ) );
TResourceReader reader;
iEikonEnv->CreateResourceReaderLC( reader, R_ADDING_PLUGIN_TITLE_RESOURCE );
title->SetFromResourceL( reader );
CleanupStack::PopAndDestroy(); // reader internal state
}
}
// ]]] end generated function
// [[[ begin generated function: do not modify
void CAddingPluginView::CleanupStatusPane()
{
}
// ]]] end generated function
/**
* Creates the top-level container for the view. You may modify this method's
* contents and the CAddingPlugin::NewL() signature as needed to initialize the
* container, but the signature for this method is fixed.
* @return new initialized instance of CAddingPlugin
*/
CAddingPlugin* CAddingPluginView::CreateContainerL()
{
return CAddingPlugin::NewL( ClientRect(), NULL, this );
}
/**
* Handle the rightSoftKeyPressed event.
* @return ETrue if the command was handled, EFalse if not
*/
TBool CAddingPluginView::Back( TInt aCommand )
{
AppUi()->ActivateLocalViewL(TUid::Uid(EPluginsListViewId));
return ETrue;
}
/**
* Handle the selected event.
* @param aCommand the command id invoked
* @return ETrue if the command was handled, EFalse if not
*/
TBool CAddingPluginView::Add( TInt aCommand )
{
TUint32 key;
_LOGDATA(_L("View: %d"),iData.iViewType);
if (iData.iViewType==EViewAddUidCombo)
{
TInt val;
key=CListOfSettingsView::UIDNumSelect(iData,-1);
if (key==-1) {return ETrue;}
TInt curr=CListOfSettingsView::PopupMenu(iData);
if (curr==-1){return ETrue;}
val=iData.iComboElements->At(curr).iIntValue;
_LOGDATA2(_L("Creating: %d, %d"),key,val);
iCR->Create(key,val);
}
else if (iData.iViewType==EViewAddUid)
{
TInt val;
RArray<TUint32> keys;
iCR->FindL(0,0,keys);
TInt i=1;
while (keys.Find((TUint32)i)!=-1){i++;}
key=i;
val=CListOfSettingsView::UIDNumSelect(iData,-1);
if (val==-1){return ETrue;}
_LOGDATA2(_L("Creating: %d, %d"),key,val);
iCR->Create(key,val);
}
else if (iData.iViewType==EViewAddFolder)
{
TInt i;
TBuf<512> val;
CDesCArray* arr=CEikonEnv::Static()->ReadDesC16ArrayResourceL(R_ACTIONS);
TInt type=PopupMenu(iData.iName,arr);
if (type==-1){return ETrue;}
if (type==0){i=0x10001;}
else {i=0x20001;}
RArray<TUint32> keys;
iCR->FindL(0,0,keys);
while (keys.Find((TUint32)i)!=-1){i++;}
key=i;
CListOfSettingsView::FileSelectDialog(iData,val);
_LOG(_L("In Add again"));
if (val.Compare(_L(""))==0){return ETrue;}
val.Copy(val.Right(val.Length()-2));
_LOGDATA2(_L("Creating: %d, %S"),key,&val);
iCR->Create(key,val);
}
Update();
return ETrue;
}
void CAddingPluginView::HandleLBSelect()
{
Edit(0);
}
/**
* Handle the selected event.
* @param aCommand the command id invoked
* @return ETrue if the command was handled, EFalse if not
*/
TBool CAddingPluginView::Edit( TInt aCommand )
{
TUint32 key;
if (iAddingPlugin->ListBox()->Model()->NumberOfItems()==0){return ETrue;}
RArray<TUint32> keys;
iCR->FindL(0,0,keys);
TInt i=iAddingPlugin->ListBox()->CurrentItemIndex();
if (iData.iViewType==EViewAddUidCombo)
{
TInt val;
key=keys[i];
TInt curr=CListOfSettingsView::PopupMenu(iData);
if (curr==-1){return ETrue;}
val=iData.iComboElements->At(curr).iIntValue;
_LOGDATA2(_L("Editing: %d, %d"),key,val);
iCR->Set(key,val);
}
else if (iData.iViewType==EViewAddUid)
{
TInt val;
key=keys[i];
val=CListOfSettingsView::UIDNumSelect(iData,-1);
if (val==-1){return ETrue;}
_LOGDATA2(_L("Editing: %d, %d"),key,val);
iCR->Set(key,val);
}
else if (iData.iViewType==EViewAddFolder)
{
TBuf<512> val;
key=keys[i];
CListOfSettingsView::FileSelectDialog(iData,val);
_LOG(_L("In edit again"));
if (val.Compare(_L(""))==0){return ETrue;}
val.Copy(val.Right(val.Length()-2));
_LOGDATA2(_L("Editing: %d, %S"),key,&val);
iCR->Set(key,val);
}
Update();
return ETrue;
}
/**
* Handle the selected event.
* @param aCommand the command id invoked
* @return ETrue if the command was handled, EFalse if not
*/
TBool CAddingPluginView::Remove( TInt aCommand )
{
if (iAddingPlugin->ListBox()->Model()->NumberOfItems()==0){return ETrue;}
RArray<TUint32> keys;
iCR->FindL(0,0,keys);
TInt i=iAddingPlugin->ListBox()->CurrentItemIndex();
iCR->Delete(keys[i]);
Update();
return ETrue;
}
/**
* Handle the selected event.
* @param aCommand the command id invoked
* @return ETrue if the command was handled, EFalse if not
*/
TBool CAddingPluginView::Info( TInt aCommand )
{
((CTweakSAppUi*)AppUi())->GlobalMsgQuery(iData.iDescription,iData.iName);
return ETrue;
}
void CAddingPluginView::Update()
{
CDesCArray* items=((CDesCArray*)iAddingPlugin->ListBox()->Model()->ItemTextArray());
if (items->Count()>0){items->Reset();}
RArray<TUint32> arr;
iCR->FindL(0,0,arr);
RApaLsSession ls;
ls.Connect();
TApaAppInfo info;
TBuf<512> title,subtitle;
TBuf<1024> LBBuffer;
for (TInt i=0;i<arr.Count();i++)
{
if (iData.iViewType==EViewAddUidCombo)
{
TBuf<10> uid;
TInt val;
iCR->Get(arr[i],val);
ls.GetAppInfo(info,TUid::Uid(arr[i]));
if (iData.iNumOfCombo!=0) // combo
{
TInt j=0;
subtitle.Num(val);
for (j=0;j<iData.iNumOfCombo;j++)
{
if (val==iData.iComboElements->At(j).iIntValue){subtitle.Copy(iData.iComboElements->At(j).iDescription);}
}
}
uid.Num((TUint)info.iUid.iUid,EHex);
uid.UpperCase();
title.Copy(info.iCaption);
title.Append(_L(" ["));
title.Append(uid);
title.Append(_L("]"));
}
else if (iData.iViewType==EViewAddUid)
{
TBuf<10> uid;
TInt val;
iCR->Get(arr[i],val);
_LOGDATA(_L("Val in update (EViewAddUid): %d"),val);
ls.GetAppInfo(info,TUid::Uid(val));
uid.Num((TUint)info.iUid.iUid,EHex);
uid.UpperCase();
title.Copy(info.iCaption);
subtitle.Copy(uid);
}
else if (iData.iViewType==EViewAddFolder)
{
TInt temp=arr[i]/0x10000;
TBuf<255> txt;
if (!(temp==1||temp==2)){continue;}
iCR->Get(arr[i],title);
CDesC16Array* arr=CEikonEnv::Static()->ReadDesC16ArrayResourceL(R_ACTIONS);
subtitle.Copy(arr->MdcaPoint(temp-1));
delete arr;
}
iAddingPlugin->CreateListBoxItemL(LBBuffer,title,subtitle);
iAddingPlugin->AddListBoxItemL(iAddingPlugin->ListBox(),LBBuffer);
}
ls.Close();
iAddingPlugin->ListBox()->SetCurrentItemIndex(0);
iAddingPlugin->ListBox()->DrawNow();
}
TInt CAddingPluginView::PopupMenu(TDes& aTxt,CDesCArray* itemList)
{
_LIT(KListItemFormat, "%S");
CAknSinglePopupMenuStyleListBox* list = new(ELeave) CAknSinglePopupMenuStyleListBox;
CleanupStack::PushL(list);
CAknPopupList* popupList = CAknPopupList::NewL(list, R_AVKON_SOFTKEYS_OK_BACK, AknPopupLayouts::EMenuWindow);
CleanupStack::PushL(popupList);
list->ConstructL(popupList, CEikListBox::ELeftDownInViewRect);
list->CreateScrollBarFrameL(ETrue);
list->ScrollBarFrame()->SetScrollBarVisibilityL(CEikScrollBarFrame::EOff, CEikScrollBarFrame::EAuto);
list->Model()->SetItemTextArray(itemList);
list->Model()->SetOwnershipType(ELbmOwnsItemArray);
list->ItemDrawer()->FormattedCellData()->EnableMarqueeL( ETrue );
popupList->SetTitleL(aTxt);
CleanupStack::Pop(); // popuplist
CleanupStack::Pop(); //list
TBool popupOk = popupList->ExecuteLD();
if (!popupOk)
{
return -1;
}
else
{
TInt current=list->CurrentItemIndex();
return current;
}
}
/**
* Handle the selected event.
* @param aCommand the command id invoked
* @return ETrue if the command was handled, EFalse if not
*/
TBool CAddingPluginView::Reset( TInt aCommand )
{
iCR->Reset();
return ETrue;
}
| 27.586762 | 112 | 0.668245 | [
"model"
] |
a8c18e1fbb7603b8622a336da6869e79e257cc2d | 4,471 | cpp | C++ | src/nell/components/meshlet_triangle_mesh.cpp | nicoell/Culling-with-Mesh-Shaders | 7b5b835b5001f81d4021d24948e6c59a50f7c8a1 | [
"MIT"
] | 7 | 2020-05-17T20:09:18.000Z | 2021-11-21T02:59:19.000Z | src/nell/components/meshlet_triangle_mesh.cpp | nicoell/Culling-with-Mesh-Shaders | 7b5b835b5001f81d4021d24948e6c59a50f7c8a1 | [
"MIT"
] | null | null | null | src/nell/components/meshlet_triangle_mesh.cpp | nicoell/Culling-with-Mesh-Shaders | 7b5b835b5001f81d4021d24948e6c59a50f7c8a1 | [
"MIT"
] | null | null | null | #include <spdlog/spdlog.h>
#include <glm/gtc/constants.hpp>
#include <map>
#include <nell/components/meshlet_triangle_mesh.hpp>
namespace nell::gpu
{
BoundingCone BoundingCone::GetApproximateReflexBoundingCone(
std::vector<glm::vec4 *> &normals)
{
glm::vec3 mean_normal{};
for (auto normal : normals)
{
mean_normal += glm::vec3(*normal);
}
mean_normal = glm::normalize(mean_normal);
float angular_span = 0.0f;
for (auto normal : normals)
{
angular_span =
glm::max(angular_span,
glm::acos(glm::dot(mean_normal, glm::vec3(*normal))));
}
BoundingCone cone{.normal = mean_normal, .angle = angular_span};
return cone;
}
} // namespace nell::gpu
namespace nell::comp
{
AxisAlignedBoundingBox::AxisAlignedBoundingBox(
std::vector<glm::vec4 *> &vertices)
{
_min = *vertices[0];
_max = _min;
for (auto vertex : vertices)
{
_min = glm::min(_min, glm::vec3(*vertex));
_max = glm::max(_max, glm::vec3(*vertex));
}
_extents = (_max - _min) / 2.f;
_center = _min + _extents;
}
MeshletTriangleMesh::MeshletTriangleMesh(aiMesh *ai_mesh)
{
const auto vertex_count = ai_mesh->mNumVertices;
vertices.reserve(vertex_count);
normals.reserve(vertex_count);
for (unsigned i_vert = 0; i_vert < vertex_count; i_vert++)
{
aiVector3D ai_pos = ai_mesh->mVertices[i_vert];
aiVector3D ai_normal = ai_mesh->mNormals[i_vert];
vertices.emplace_back(ai_pos.x, ai_pos.y, ai_pos.z, 1);
normals.emplace_back(ai_normal.x, ai_normal.y, ai_normal.z, 0);
}
// Iterate Meshlets
const auto max_indices_count = ai_mesh->mNumFaces * 3;
indices.reserve(max_indices_count);
const auto meshlet_count =
ai_mesh->mNumFaces / _meshlet_primitive_count +
(ai_mesh->mNumFaces % _meshlet_primitive_count != 0);
meshlet_descriptors.reserve(meshlet_count); // Round up integer division
auto i_face_from = 0u;
const auto face_count = ai_mesh->mNumFaces;
std::map<unsigned, bool> unique_index_map;
std::vector<glm::vec4 *> meshlet_vertices;
std::vector<glm::vec4 *> meshlet_normals;
for (unsigned i_meshlet = 0; i_meshlet < meshlet_count; ++i_meshlet)
{
const auto i_face_to =
glm::min(i_face_from + _meshlet_primitive_count, face_count);
GLushort primitive_count = i_face_to - i_face_from;
unique_index_map.clear();
meshlet_vertices.clear();
meshlet_vertices.reserve(max_indices_count);
meshlet_normals.clear();
meshlet_normals.reserve(max_indices_count);
// Iterate primitives of this meshlet
for (unsigned i_face = i_face_from; i_face < i_face_to; ++i_face)
{
const aiFace ai_face = ai_mesh->mFaces[i_face];
for (unsigned i_indx = 0; i_indx < ai_face.mNumIndices; ++i_indx)
{
unsigned index = ai_face.mIndices[i_indx];
indices.push_back(index);
// Add to map to test if index already present
if (unique_index_map
.insert(std::make_pair(index, true))
.second)
{
auto *vertex = &vertices.at(index);
auto *normal = &normals.at(index);
meshlet_vertices.push_back(vertex);
meshlet_normals.push_back(normal);
}
}
}
auto aabb = AxisAlignedBoundingBox(meshlet_vertices);
gpu::BoundingSphere bounding_sphere{
.center = aabb.getCenter(), .radius = [&]() -> float {
float radius = 0.f;
for (auto vertex : meshlet_vertices)
{
radius =
glm::max(radius, glm::distance(bounding_sphere.center,
glm::vec3(*vertex)));
}
return radius;
}()};
gpu::BoundingCone bounding_cone =
gpu::BoundingCone::GetApproximateReflexBoundingCone(
meshlet_normals);
meshlet_descriptors.push_back(
gpu::MeshletDescriptor{.sphere = bounding_sphere,
.cone = bounding_cone,
.primitive_count = primitive_count});
i_face_from += _meshlet_primitive_count;
}
}
void MeshletTriangleMesh::drawImGui()
{
if (ImGui::TreeNode("Meshlet Triangle Mesh"))
{
ImGui::Text("%s: %d", "meshlet_descriptors", meshlet_descriptors.size());
ImGui::Text("%s: %d", "vertices", vertices.size());
ImGui::Text("%s: %d", "normals", normals.size());
ImGui::Text("%s: %d", "Indices", indices.size());
ImGui::TreePop();
}
}
} // namespace nell::comp
| 29.222222 | 77 | 0.642586 | [
"mesh",
"vector"
] |
a8c2eaa327f86a00935b0a936892226e06cec4ca | 5,906 | cc | C++ | performance_test/LIN/Flame_gbench_getrf.cc | greck2908/libflame | 51d901f5fa1729c018c19110d100d117b91a0e65 | [
"BSD-3-Clause"
] | 27 | 2017-10-01T08:26:08.000Z | 2022-01-03T20:26:42.000Z | performance_test/LIN/Flame_gbench_getrf.cc | greck2908/libflame | 51d901f5fa1729c018c19110d100d117b91a0e65 | [
"BSD-3-Clause"
] | null | null | null | performance_test/LIN/Flame_gbench_getrf.cc | greck2908/libflame | 51d901f5fa1729c018c19110d100d117b91a0e65 | [
"BSD-3-Clause"
] | 11 | 2017-07-30T19:15:00.000Z | 2020-02-21T13:18:13.000Z | // Gbench headers
#include "benchmark/benchmark.h"
#include "gtest/gtest.h"
// Test suite headers
#include "../Flame_gbench_main.h"
#include "../Flame_gbench_aux.h"
using namespace std;
/* Macros */
#define getrf_parameters_free() \
if (A!=NULL){ \
free(A); \
}\
if (ipiv!=NULL){ \
free(ipiv); \
}
/* Begin getrf_parameters class definition */
template <class T>
class getrf_parameters{
public:
int m, n, lda, info;
int forced_loop_count;
/* Local arrays */
T *A;
int *ipiv, *ipivref;
T norm;
public:
~getrf_parameters ();
getrf_parameters ( int nrow, int ncol, int lda_ )
{
m = nrow;
n = ncol; // set test matrix size
lda = lda_;
forced_loop_count = 1;
if ( (m > FLAME_BIG_MATRIX_SIZE) || (n > FLAME_BIG_MATRIX_SIZE )){
forced_loop_count = FLAME_GBENCH_FORCED_ITERATION_COUNT;
}
/* Memory allocation of the buffers */
A = (T *)malloc(m*n*sizeof(T)) ;
ipiv = (int *)malloc(m*sizeof(int));
if ((ipiv==NULL) || (A==NULL) ){
printf("error of memory allocation. Exiting ...\n");
getrf_parameters_free();
exit(0);
}
/* Initialization of input Buffers */
Flame_gbench_init_buffer_rand( A, m*n );
} /* end of Constructor */
}; /* end of getrf_parameters class definition */
/* Destructor definition 'getrf_parameters' class */
template <class T>
getrf_parameters<T>:: ~getrf_parameters ()
{
#if FLAME_TEST_VERBOSE
printf(" getrf_parameters object: destructor invoked. \n");
#endif
getrf_parameters_free ();
}
/* Fixture definition */
template <class T>
class getrf_test : public ::benchmark::Fixture {
public:
int m,n, lda, ldb;
std::unique_ptr<getrf_parameters<T>> data;
void SetUp(const ::benchmark::State& state) BENCHMARK_OVERRIDE {
m = static_cast<size_t>(state.range(0));
n = static_cast<size_t>(state.range(1));
assert(data.get() == nullptr);
data.reset(new getrf_parameters<T>(m,n,m));
}
void TearDown(const ::benchmark::State& state) BENCHMARK_OVERRIDE {
assert(data.get() != nullptr);
data.reset();
}
~getrf_test() { assert(data == nullptr); }
};
// Customized argument generator for getrf API
static void CustomArguments(benchmark::internal::Benchmark* b) {
if (lin_solver_paramslist[0].mode == MODE_RANGE) {
for (int i = 0; i < lin_solver_paramslist[0].num_tests ; i++){
b->ArgsProduct({
{benchmark::CreateDenseRange( lin_solver_paramslist[i].m_range_start,
lin_solver_paramslist[i].m_range_end,
lin_solver_paramslist[i].m_range_step_size)} ,
{benchmark::CreateDenseRange( lin_solver_paramslist[i].n_range_start,
lin_solver_paramslist[i].n_range_end,
lin_solver_paramslist[i].n_range_step_size)}
});
}
}
if (lin_solver_paramslist[0].mode == MODE_DISCRETE) {
for (int i = 0; i < lin_solver_paramslist[0].num_tests ; i++)
{
b->Args({lin_solver_paramslist[i].m, lin_solver_paramslist[i].n});
}
}
if (lin_solver_paramslist[0].mode == MODE_COMBINATIONAL) {
for (int i = 0; i < lin_solver_paramslist[0].num_tests ; i++)
{
for (int j = 0; j < lin_solver_paramslist[0].num_tests ; j++){
b->Args({lin_solver_paramslist[i].m, lin_solver_paramslist[j].n});
}
}
}
}
/* Template Fixture for dgetrf API */
BENCHMARK_TEMPLATE_DEFINE_F(getrf_test, dgetrf, double)(benchmark::State &state) {
assert(data.get() != nullptr);
for (auto _ : state) {
for (int i=0; i<data->forced_loop_count; i++) {
/* Invoke the getrf API for benchmarking */
dgetrf_(&data->m, &data->n, data->A, &data->lda, data->ipiv, &data->info);
if( data->info < 0 ) {
printf( "\n warning: The %d th argument dgetrf is wrong\n", data->info );
}
}
}
}
BENCHMARK_REGISTER_F(getrf_test, dgetrf)->Apply(CustomArguments);
/* Template Fixture for sgettrf API */
BENCHMARK_TEMPLATE_DEFINE_F(getrf_test, sgetrf, float)(benchmark::State &state) {
assert(data.get() != nullptr);
for (auto _ : state) {
for (int i=0; i<data->forced_loop_count; i++) {
/* Invoke the getrf API for benchmarking */
sgetrf_(&data->m, &data->n, data->A, &data->lda, data->ipiv, &data->info);
if( data->info < 0 ) {
printf( "\n warning: The %d th argument sgetrf is wrong\n", data->info );
}
}
}
}
BENCHMARK_REGISTER_F(getrf_test, sgetrf)->Apply(CustomArguments);
/* Template Fixture for cgetrf API */
BENCHMARK_TEMPLATE_DEFINE_F(getrf_test, cgetrf, float _Complex)(benchmark::State &state) {
assert(data.get() != nullptr);
for (auto _ : state) {
for (int i=0; i<data->forced_loop_count; i++) {
/* Invoke the getrf API for benchmarking */
cgetrf_(&data->m, &data->n, data->A, &data->lda, data->ipiv, &data->info);
if( data->info < 0 ) {
printf( "\n warning: The %d th argument cgetrf is wrong\n", data->info );
}
}
}
}
BENCHMARK_REGISTER_F(getrf_test, cgetrf)->Apply(CustomArguments);
/* Template Fixture for zgetrf API */
BENCHMARK_TEMPLATE_DEFINE_F(getrf_test, zgetrf, double _Complex)(benchmark::State &state) {
assert(data.get() != nullptr);
for (auto _ : state) {
for (int i=0; i<data->forced_loop_count; i++) {
/* Invoke the getrf API for benchmarking */
zgetrf_(&data->m, &data->n, data->A, &data->lda, data->ipiv, &data->info);
if( data->info < 0 ) {
printf( "\n warning: The %d th argument zgetrf is wrong\n", data->info );
}
}
}
}
BENCHMARK_REGISTER_F(getrf_test, zgetrf)->Apply(CustomArguments);
| 29.53 | 91 | 0.603454 | [
"object"
] |
a8c83f427dc8ec21124b186e4d018448b285a32a | 3,295 | hpp | C++ | header.hpp | STEllAR-GROUP/cxx-demangler | aa73517c3b6ea45662df8709c9f69c8ad305a725 | [
"BSL-1.0"
] | 6 | 2016-04-18T03:58:55.000Z | 2020-01-12T14:07:46.000Z | header.hpp | STEllAR-GROUP/cxx-demangler | aa73517c3b6ea45662df8709c9f69c8ad305a725 | [
"BSL-1.0"
] | null | null | null | header.hpp | STEllAR-GROUP/cxx-demangler | aa73517c3b6ea45662df8709c9f69c8ad305a725 | [
"BSL-1.0"
] | null | null | null | /* Copyright (c) 2012 Michael LeSane
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
namespace cxx_demangler
{
std::vector<std::string> global_backref;
int DO_DEBUG = 0;
int GCC_MANGLE = 0;
int NESTED = 0;
std::vector<std::string> getGlobalBackRef(){
return global_backref;
}
/*
* functions headers
*/
std::vector<std::string> getGlobalBackRef();
int is_alphanumeric(char c);
int is_valid_first_character(char c);
char consume1(std::string &s);
int consume(std::string &s,std::string ss);
std::string implode(std::string,std::vector<std::string>);
std::string parseQualification(std::string &str);
void debug(std::string a, std::string &b);
std::string syscall(std::string);
/*
* datatypes headers
*/
std::string getNextDataType(std::string &s, std::vector<std::string> &backref);
std::string getNextOpCode(std::string &s);
std::string getNextContainer(std::string &s);
std::string getRealType(std::string &s);
std::string getNextCallingConvention(std::string &s);
std::string checkExceptions(std::string s, std::string &str, std::vector<std::string> &backref);
std::string getNextStorageClass(std::string &s);
std::string checkPrefix(std::string &str);
/*
* main headers
*/
std::string demangle(std::string s);
std::string parseFunctionTypeCode(std::string &s);
std::string parseReturnValueTypeCode(std::string &s);
std::string parseArgumentList(std::string &s);
std::string parseBasicName(std::string &s);
std::string parseMangledName(std::string &s);
/*
* Struct prototypes
*/
struct basicName{
int hasOperator;
int hasTemplate;
int templateName;
std::string operatorCode;
std::string nameFragment;
std::string templateStr;
std::string gcc_template;
basicName();
void parse(std::string &str, std::vector<std::string> &backref);
std::vector<std::string> local_backref;
std::string toString();
std::string toGCC();
void build(std::string add);
};
struct argumentList{
std::vector<std::string> args;
std::vector<std::string> local_backref;
int forTemplate;
argumentList();
void parse(std::string &str, std::vector<std::string> &backref);
std::string toString();
std::string toGCC();
};
struct templateArg{
std::string name;
std::string arguments;
std::string gcc_arguments;
std::string qualificn;
std::vector<std::string> local_backref;
argumentList aL;
basicName bN;
templateArg();
void parse(std::string &str);
std::string toString();
std::string toGCC();
};
struct functionTypeCode{
std::string
cConvention,
returnValueTypeCode,
argList,
aL_gcc;
functionTypeCode();
void parse(std::string &str);
std::string toString(std::string name, std::string suffix);
std::string toGCC();
};
struct qualification{
std::vector<std::string> contents;
std::vector<basicName> bN_contents;
std::vector<std::string> local_backref;
int initial;
qualification();
void parse(std::string &str,std::vector<std::string> &backref);
std::string toString(std::vector<std::string> backref);
std::string toGCC(std::vector<std::string> backref);
std::string check(std::string, std::vector<std::string>);
};
int main();
}
| 25.742188 | 97 | 0.701973 | [
"vector"
] |
a8c9f635d69ca88aaa0f5e0394cca1f73e0289c4 | 175,043 | cpp | C++ | com/mobile/syncmgr/exe/hndlrq.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | com/mobile/syncmgr/exe/hndlrq.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | com/mobile/syncmgr/exe/hndlrq.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | //+-------------------------------------------------------------------------
//
// Microsoft Windows
// Copyright (C) Microsoft Corporation, 1997.
//
// File: Hndlrq.cpp
//
// Contents: Implements class for keeping track of handlers
// and the UI associated with them
//
// Classes: CHndlrQueue
//
// Notes:
//
// History: 05-Nov-97 rogerg Created.
//
//--------------------------------------------------------------------------
#include "precomp.h"
#define HNDRLQUEUE_DEFAULT_PROGRESS_MAXVALUE 10
// called to set up the JobInfo on a choice queue.
STDMETHODIMP CHndlrQueue::AddQueueJobInfo(DWORD dwSyncFlags,DWORD cbNumConnectionNames,
TCHAR **ppConnectionNames,
TCHAR *pszScheduleName,BOOL fCanMakeConnection
,JOBINFO **pJobInfo)
{
HRESULT hr = E_UNEXPECTED;
TCHAR *pszConnectionName;
TCHAR **pszConnectionNameArray;
CLock clockqueue(this);
*pJobInfo = NULL;
Assert(m_QueueType == QUEUETYPE_CHOICE);
if (m_QueueType != QUEUETYPE_CHOICE)
{
return E_UNEXPECTED;
}
clockqueue.Enter();
Assert(NULL == m_pFirstJobInfo);
// fix up connections so have at least one connection/job.
// this currently happens on an UpdateItems.
if (NULL == ppConnectionNames || 0 == cbNumConnectionNames )
{
cbNumConnectionNames = 1;
pszConnectionName = TEXT("");
pszConnectionNameArray = &pszConnectionName;
}
else
{
pszConnectionName = *ppConnectionNames;
pszConnectionNameArray = ppConnectionNames;
}
// create a job requesting size for the number of connections passed in.
hr = CreateJobInfo(&m_pFirstJobInfo,cbNumConnectionNames);
if (S_OK == hr)
{
DWORD dwConnectionIndex;
Assert(cbNumConnectionNames >= 1); // Review assert for debugging to test when have multiple connections for first time.
m_pFirstJobInfo->cbNumConnectionObjs = 0;
// add a connectionObject for each connection
for (dwConnectionIndex = 0; dwConnectionIndex < cbNumConnectionNames; ++dwConnectionIndex)
{
hr = ConnectObj_FindConnectionObj(pszConnectionNameArray[dwConnectionIndex],
TRUE,&(m_pFirstJobInfo->pConnectionObj[dwConnectionIndex]));
if (S_OK != hr)
{
break;
}
else
{
++m_pFirstJobInfo->cbNumConnectionObjs;
}
}
if (S_OK == hr)
{
m_pFirstJobInfo->dwSyncFlags = dwSyncFlags;
if ((SYNCMGRFLAG_SCHEDULED == (dwSyncFlags & SYNCMGRFLAG_EVENTMASK)))
{
StringCchCopy(m_pFirstJobInfo->szScheduleName, ARRAYSIZE(m_pFirstJobInfo->szScheduleName), pszScheduleName);
m_pFirstJobInfo->fCanMakeConnection = fCanMakeConnection;
m_pFirstJobInfo->fTriedConnection = FALSE;
}
}
else
{
// couldn't create the connectionObj so release our jobID
m_pFirstJobInfo = NULL;
}
}
*pJobInfo = m_pFirstJobInfo;
clockqueue.Leave();
return hr;
}
//+---------------------------------------------------------------------------
//
// Member: CHndlrQueue::CHndlrQueue, public
//
// Synopsis: Constructor used to create a progress queue
//
// Arguments: [QueueType] - Type of Queue that should be created.
// [hwndDlg] - Hwnd who owns this queue.
//
// Returns:
//
// Modifies:
//
// History: 17-Nov-97 rogerg Created.
//
//----------------------------------------------------------------------------
CHndlrQueue::CHndlrQueue(QUEUETYPE QueueType,CBaseDlg *pDlg)
{
Assert( (QueueType == QUEUETYPE_PROGRESS) || (QueueType == QUEUETYPE_CHOICE) );
m_pFirstHandler = NULL;
m_wHandlerCount = 0;
m_dwShowErrororOutCallCount = 0;
m_cRefs = 1;
m_QueueType = QueueType;
m_fItemsMissing = FALSE;
m_dwQueueThreadId = GetCurrentThreadId();
m_iNormalizedMax = 0;
m_fNumItemsCompleteNeedsARecalc = TRUE;
m_pDlg = pDlg;
if (m_pDlg)
{
m_hwndDlg = m_pDlg->GetHwnd();
Assert(m_hwndDlg);
}
m_fInCancelCall = FALSE;
m_pFirstJobInfo = NULL;
}
//+---------------------------------------------------------------------------
//
// Member: CHndlrQueue::~CHndlrQueue, public
//
// Synopsis: Destructor
//
// Arguments:
//
// Returns:
//
// Modifies:
//
// History: 17-Nov-97 rogerg Created.
//
//----------------------------------------------------------------------------
CHndlrQueue::~CHndlrQueue()
{
CLock clockqueue(this);
// for a progress queue all the jobInfos should be released
// for the choice queue there should be one JobInfo that has to
// be released that was addref'd in the constructor.
Assert(0 == m_cRefs);
Assert(NULL == m_pFirstJobInfo); // review - this should never fire anymore.
Assert(NULL == m_pFirstJobInfo
|| m_QueueType == QUEUETYPE_CHOICE); // there shouldn't be any unreleased JobInfo
Assert(m_pFirstHandler == NULL); // All Handlers should have been released by now.
}
//+---------------------------------------------------------------------------
//
// Member: CHndlrQueue::AddRef, public
//
// Synopsis:
//
// Arguments:
//
// Returns:
//
// Modifies:
//
// History: 01-June-98 rogerg Created.
//
//----------------------------------------------------------------------------
STDMETHODIMP_(ULONG) CHndlrQueue::AddRef()
{
DWORD cRefs;
Assert(m_cRefs >= 1); // should never zero bounce.
cRefs = InterlockedIncrement((LONG *)& m_cRefs);
return cRefs;
}
//+---------------------------------------------------------------------------
//
// Member: CHndlrQueue::Release, public
//
// Synopsis:
//
// Arguments:
//
// Returns:
//
// Modifies:
//
// History: 01-June-98 rogerg Created.
//
//----------------------------------------------------------------------------
STDMETHODIMP_(ULONG) CHndlrQueue::Release()
{
DWORD cRefs;
cRefs = InterlockedDecrement( (LONG *) &m_cRefs);
Assert( ((LONG) cRefs) >= 0); // should never go negative.
if (0 == cRefs)
{
delete this;
}
return cRefs;
}
//+---------------------------------------------------------------------------
//
// Member: CHndlrQueue::AddHandler, public
//
// Synopsis: Adds a new empty handler to the queue and returns it ID
//
// Arguments: [pwHandlerID] - on success contains the assigned Handler ID
// [pJobInfo] - Job this item is associated with
// [dwRegistrationFlags] - Flags the Handler has registered for.
//
// Returns: Appropriate return codes
//
// Modifies:
//
// History: 17-Nov-97 rogerg Created.
//
//----------------------------------------------------------------------------
STDMETHODIMP CHndlrQueue::AddHandler(HANDLERINFO **ppHandlerId,JOBINFO *pJobInfo,DWORD dwRegistrationFlags)
{
HRESULT hr = E_OUTOFMEMORY;
LPHANDLERINFO pnewHandlerInfo;
CLock clockqueue(this);
*ppHandlerId = 0;
pnewHandlerInfo = (LPHANDLERINFO) ALLOC(sizeof(HANDLERINFO));
if (pnewHandlerInfo)
{
clockqueue.Enter();
m_fNumItemsCompleteNeedsARecalc = TRUE; // need to recalc next GetProgress.
// initialize the new Handler Entry
memset(pnewHandlerInfo, 0, sizeof(HANDLERINFO));
pnewHandlerInfo->HandlerState = HANDLERSTATE_CREATE;
pnewHandlerInfo->pHandlerId = pnewHandlerInfo;
pnewHandlerInfo->dwRegistrationFlags = dwRegistrationFlags;
// queue should be a choice queue and
// there should already be a jobinfo.
Assert(m_QueueType == QUEUETYPE_CHOICE);
Assert(m_pFirstJobInfo);
Assert(pJobInfo == m_pFirstJobInfo); // for now job info should always be the first one.
if (m_QueueType == QUEUETYPE_CHOICE && pJobInfo)
{
AddRefJobInfo(pJobInfo);
pnewHandlerInfo->pJobInfo = pJobInfo;
}
// add to end of list and set pHandlerId. End of list since in choice dialog want
// first writer wins so don't have to continue searches when setting item state.
if (NULL == m_pFirstHandler)
{
m_pFirstHandler = pnewHandlerInfo;
}
else
{
LPHANDLERINFO pCurHandlerInfo;
pCurHandlerInfo = m_pFirstHandler;
while (pCurHandlerInfo->pNextHandler)
{
pCurHandlerInfo = pCurHandlerInfo->pNextHandler;
}
pCurHandlerInfo->pNextHandler = pnewHandlerInfo;
}
*ppHandlerId = pnewHandlerInfo->pHandlerId;
clockqueue.Leave();
hr = S_OK;
}
return hr;
}
//+---------------------------------------------------------------------------
//
// Member: CHndlrQueue::ForceKillHandlers, public
//
// Synopsis: Kills unresponsive handlers after timeout
//
// Returns: Appropriate return codes
//
// History: 20-Nov-98 rogerg Created.
//
//----------------------------------------------------------------------------
STDMETHODIMP CHndlrQueue::ForceCompleteOutCalls(LPHANDLERINFO pCurHandler)
{
// need to have lock for argument to be valid.
ASSERT_LOCKHELD(this);
//prepare for sync out call
if (pCurHandler->dwOutCallMessages & ThreadMsg_PrepareForSync)
{
CallCompletionRoutine(pCurHandler,ThreadMsg_PrepareForSync,
HRESULT_FROM_WIN32(ERROR_CANCELLED),0,NULL);
}
//Synchronize out call
if (pCurHandler->dwOutCallMessages & ThreadMsg_Synchronize)
{
CallCompletionRoutine(pCurHandler,ThreadMsg_Synchronize,
HRESULT_FROM_WIN32(ERROR_CANCELLED),0,NULL);
}
//ShowProperties out call
if (pCurHandler->dwOutCallMessages & ThreadMsg_ShowProperties)
{
CallCompletionRoutine(pCurHandler,ThreadMsg_ShowProperties,
HRESULT_FROM_WIN32(ERROR_CANCELLED),0,NULL);
}
//Show Errors out call
if (pCurHandler->dwOutCallMessages & ThreadMsg_ShowError)
{
CallCompletionRoutine(pCurHandler,ThreadMsg_ShowError,
HRESULT_FROM_WIN32(ERROR_CANCELLED),0,NULL);
}
// force handler state to release.
pCurHandler->HandlerState = HANDLERSTATE_RELEASE;
return S_OK;
}
//+---------------------------------------------------------------------------
//
// Member: CHndlrQueue::ForceKillHandlers, public
//
// Synopsis: Kills unresponsive handlers after timeout
//
// Returns: Appropriate return codes
//
// History: 30-Oct-98 susia Created.
// 19-Nov-98 rogerg Change to only kill first unresponsive handler
//
//----------------------------------------------------------------------------
#define BAD_HANDLERSTATE(pHandlerId) \
( (HANDLERSTATE_INSYNCHRONIZE >= pHandlerId->HandlerState) \
|| (pHandlerId->dwOutCallMessages & ThreadMsg_SetItemStatus) \
)
STDMETHODIMP CHndlrQueue::ForceKillHandlers(BOOL *pfItemToKill)
{
HRESULT hr = S_OK;
LPHANDLERINFO pCurHandler;
CLock clockqueue(this);
*pfItemToKill = TRUE; // if something strange happens make sure timer gets reset.
clockqueue.Enter();
pCurHandler = m_pFirstHandler;
while (pCurHandler)
{
// if handler is cancelled but still in a noncancelled state or
// is cancelled but stuck in the outcall then terminate.
// need to check both because some handlers may call the callback
// to set the state done but still be stuck in an out call.
if ( pCurHandler->fCancelled && BAD_HANDLERSTATE(pCurHandler) )
{
TCHAR pszHandlerName[MAX_SYNCMGRHANDLERNAME + 1];
ConvertString(pszHandlerName,
(pCurHandler->SyncMgrHandlerInfo).wszHandlerName,
MAX_SYNCMGRHANDLERNAME);
// yield because of message box in Terminate Handler call.
Assert(!pCurHandler->fInTerminateCall);
pCurHandler->fInTerminateCall = TRUE;
clockqueue.Leave();
hr = pCurHandler->pThreadProxy->TerminateHandlerThread(pszHandlerName,TRUE);
clockqueue.Enter();
pCurHandler->fInTerminateCall = FALSE;
if (hr == S_OK)
{
LPHANDLERINFO pKilledHandler = pCurHandler;
ForceCompleteOutCalls(pCurHandler);
// now need to loop through remaining instances handlers off the same clsid
// we just killed
// CODE REVIEW: NOTENOTE:
// pCurHandler is being assigned, not compared - its a '=', not a '=='
while(pCurHandler = pCurHandler->pNextHandler)
{
if (pCurHandler->clsidHandler == pKilledHandler->clsidHandler)
{
// must meet original kil criteria
if ( pCurHandler->fCancelled && BAD_HANDLERSTATE(pCurHandler) )
{
HRESULT hrProxyTerminate;
pCurHandler->fInTerminateCall = TRUE;
clockqueue.Leave();
hrProxyTerminate = pCurHandler->pThreadProxy->TerminateHandlerThread(pszHandlerName,FALSE);
clockqueue.Enter();
Assert(S_OK == hrProxyTerminate);// this should never fail.
ForceCompleteOutCalls(pCurHandler);
pCurHandler->fInTerminateCall = FALSE;
}
}
}
}
// if handled one , break out and reqiure to be called again.
break;
}
pCurHandler = pCurHandler->pNextHandler;
}
// finally loop through the queue and see if there are any more items to kill
*pfItemToKill = FALSE;
pCurHandler = m_pFirstHandler;
while (pCurHandler)
{
// if handler is cancelled but still in a noncancelled state or
// is cancelled but stuck in the outcall then terminate.
// need to check both because some handlers may call the callback
// to set the state done but still be stuck in an out call.
if ( pCurHandler->fCancelled && BAD_HANDLERSTATE(pCurHandler) )
{
*pfItemToKill = TRUE;
break;
}
pCurHandler = pCurHandler->pNextHandler;
}
clockqueue.Leave();
return hr;
}
//+---------------------------------------------------------------------------
//
// Member: CHndlrQueue::Cancel, public
//
// Synopsis: Set the current Handler Items in the queue
// into cancel mode.
//
// The Different States Are.
// If the item is waiting for <= PrepareForSync place in Release
// If InPrepareForSync Skip Items and then Synchrnoize
// will check the complete value before calling through
// and if set will just release the Handler.
// If Waiting to Synchronize Skip Items then let Synchronize
// Check for complete value and just set release
// If Item is currently In the Synchronize Skip all items
// and then just let synchronize return
//
// Algorithm. If <= PrepareForSync then place in Release, Else if <= InSynchronize
// then SkipTheItems
//
// Note: Relies on Synchronize setting handler state before calling
// through to Handlers Synchronize Method. PrepareForSync should
// also check this in case new PrepareforSync request comes
// in during an out call in this routine.
//
// Arguments:
//
// Returns: Appropriate return codes
//
// Modifies:
//
// History: 17-Nov-97 rogerg Created.
//
//----------------------------------------------------------------------------
STDMETHODIMP CHndlrQueue::Cancel(void)
{
HRESULT hr = E_UNEXPECTED;
LPHANDLERINFO pCurHandler;
CLock clockqueue(this);
clockqueue.Enter();
// don't do anything is still processing the last cancel request
if (!m_fInCancelCall)
{
m_fInCancelCall = TRUE;
// first thing set cancel to true on all handler items
// so if sync,PrepareForSyncRequest comes in during SetItemStatus
// out call it will be cancelled immediately.
pCurHandler = m_pFirstHandler;
while (pCurHandler)
{
pCurHandler->fCancelled = TRUE;
pCurHandler = pCurHandler->pNextHandler;
}
// now loop through looking for any items that need to have
// their item status set.
// !!!remember new requests can come in so only make out call
// if fCancelled is set.
// !!! items can be removed from queue in between our cancel call
// and when we return.
pCurHandler = m_pFirstHandler;
while (pCurHandler)
{
CThreadMsgProxy *pThreadProxy = pCurHandler->pThreadProxy;
if (pCurHandler->fCancelled && pThreadProxy
&& (pCurHandler->HandlerState >= HANDLERSTATE_INPREPAREFORSYNC)
&& (pCurHandler->HandlerState <= HANDLERSTATE_INSYNCHRONIZE) )
{
// could be in a setitemstatus call, if so then don't do another.
// review - dup of SkipCode. should have a general purpose function
// to call after setting what items should be cancelled.
if (!(pCurHandler->dwOutCallMessages & ThreadMsg_SetItemStatus))
{
pCurHandler->dwOutCallMessages |= ThreadMsg_SetItemStatus;
clockqueue.Leave();
// send a reset to the hwnd we belong to if there is one
if (m_hwndDlg)
{
SendMessage(m_hwndDlg,WM_PROGRESS_RESETKILLHANDLERSTIMER,0,0);
}
hr = pThreadProxy->SetItemStatus(GUID_NULL, SYNCMGRSTATUS_STOPPED);
clockqueue.Enter();
pCurHandler->dwOutCallMessages &= ~ThreadMsg_SetItemStatus;
}
}
else if (pCurHandler->HandlerState < HANDLERSTATE_INPREPAREFORSYNC)
{
LPITEMLIST pCurItem;
pCurHandler->HandlerState = HANDLERSTATE_RELEASE;
// need to setup HwndCallback so progres gets updated.
// review, after ship why can't setup HwndCallback on transferqueueu
pCurHandler->hWndCallback = m_hwndDlg;
// if handler hansn't been kicked off yet, just reset the items ourselves
pCurItem = pCurHandler->pFirstItem;
while (pCurItem)
{
if (pCurItem->fIncludeInProgressBar)
{
SYNCMGRPROGRESSITEM SyncProgressItem;
SyncProgressItem.cbSize = sizeof(SYNCMGRPROGRESSITEM);
SyncProgressItem.mask = SYNCMGRPROGRESSITEM_PROGVALUE | SYNCMGRPROGRESSITEM_MAXVALUE | SYNCMGRPROGRESSITEM_STATUSTYPE;
SyncProgressItem.iProgValue = HNDRLQUEUE_DEFAULT_PROGRESS_MAXVALUE;
SyncProgressItem.iMaxValue = HNDRLQUEUE_DEFAULT_PROGRESS_MAXVALUE;
SyncProgressItem.dwStatusType = SYNCMGRSTATUS_STOPPED;
// set progress faking we are in an out call so any releasecompleted
// handler that comes through doesn't release us.
// if already in outCall then progress just won't get updated
// until next time.
if (!(pCurHandler->dwOutCallMessages & ThreadMsg_SetItemStatus))
{
pCurHandler->dwOutCallMessages |= ThreadMsg_SetItemStatus;
clockqueue.Leave();
Progress(pCurHandler->pHandlerId, pCurItem->offlineItem.ItemID,&SyncProgressItem);
clockqueue.Enter();
pCurHandler->dwOutCallMessages &= ~ThreadMsg_SetItemStatus;
}
}
pCurItem = pCurItem->pnextItem;
}
}
pCurHandler = pCurHandler->pNextHandler;
}
m_fInCancelCall = FALSE;
}
clockqueue.Leave();
return hr;
}
//+---------------------------------------------------------------------------
//
// Member: CHndlrQueue::MoveHandler, public
//
// Synopsis: Moves the Handler from a queue into this queue.
//
// Arguments: [pQueueMoveFrom] - Queue the handler is being moved from.
// [pHandlerInfoMoveFrom] - Handler that is being moved
// [ppHandlerId] - On Success contains the new HandlerID
//
// Returns: Appropriate return codes
//
// Modifies:
//
// History: 17-Nov-97 rogerg Created.
//
//----------------------------------------------------------------------------
STDMETHODIMP CHndlrQueue::MoveHandler(CHndlrQueue *pQueueMoveFrom,
LPHANDLERINFO pHandlerInfoMoveFrom,
HANDLERINFO **ppHandlerId,
CLock *pclockQueue)
{
LPITEMLIST pCurItem = NULL;
JOBINFO *pJobInfo = NULL;
BOOL fHasItemsToSync = FALSE;
ASSERT_LOCKHELD(this); // items should already be locked when this function is called.
ASSERT_LOCKHELD(pQueueMoveFrom);
if ( (QUEUETYPE_PROGRESS != m_QueueType) && (QUEUETYPE_CHOICE != m_QueueType) )
{
Assert(QUEUETYPE_CHOICE == m_QueueType);
Assert(QUEUETYPE_PROGRESS == m_QueueType);
return E_UNEXPECTED; // review error code.
}
*ppHandlerId = 0;
++m_wHandlerCount;
// pHandlerInfoMoveFrom->pHandlerId = m_wHandlerCount;
pHandlerInfoMoveFrom->pNextHandler = NULL;
*ppHandlerId = pHandlerInfoMoveFrom->pHandlerId;
// now fix up the items duplicate flag information.
pCurItem = pHandlerInfoMoveFrom->pFirstItem;
while (pCurItem)
{
LPHANDLERINFO pHandlerMatched;
LPITEMLIST pItemListMatch;
// setup the information for the UI depending on if this item is check and
// the state it is in.
// if item is now within a valid range then uncheck it.
if (SYNCMGRITEMSTATE_CHECKED == pCurItem->offlineItem.dwItemState
&& ( (pHandlerInfoMoveFrom->HandlerState < HANDLERSTATE_PREPAREFORSYNC)
|| (pHandlerInfoMoveFrom->HandlerState >= HANDLERSTATE_RELEASE) ) )
{
Assert(pHandlerInfoMoveFrom->HandlerState >= HANDLERSTATE_PREPAREFORSYNC); // this should never happen.
pCurItem->offlineItem.dwItemState = SYNCMGRITEMSTATE_UNCHECKED;
}
// setup the UI information based on if the item is checked.
// or if its a hidden item.
if ( (SYNCMGRITEMSTATE_UNCHECKED == pCurItem->offlineItem.dwItemState) || pCurItem->fHiddenItem)
{
SetItemProgressValues(pCurItem,HNDRLQUEUE_DEFAULT_PROGRESS_MAXVALUE,HNDRLQUEUE_DEFAULT_PROGRESS_MAXVALUE);
pCurItem->fIncludeInProgressBar = FALSE;
}
else
{
fHasItemsToSync = TRUE;
SetItemProgressValues(pCurItem,0,HNDRLQUEUE_DEFAULT_PROGRESS_MAXVALUE);
pCurItem->fIncludeInProgressBar = TRUE;
}
if (IsItemAlreadyInList(pHandlerInfoMoveFrom->clsidHandler,
(pCurItem->offlineItem.ItemID),
pHandlerInfoMoveFrom->pHandlerId,
&pHandlerMatched,&pItemListMatch) )
{
pCurItem->fDuplicateItem = TRUE;
}
else
{
Assert(FALSE == pCurItem->fDuplicateItem); // catch case of duplicate getting lost
pCurItem->fDuplicateItem = FALSE;
}
pCurItem = pCurItem->pnextItem;
}
// if the item we are moving has a Proxy then update the proxy to the new queue.
// We update this when the item is not attached to either queue.
if (pHandlerInfoMoveFrom->pThreadProxy)
{
HANDLERINFO *pHandlerInfoArg = pHandlerInfoMoveFrom->pHandlerId;
// set the proxy to point to the new information
pHandlerInfoMoveFrom->pThreadProxy->SetProxyParams(m_hwndDlg
,m_dwQueueThreadId
,this
,pHandlerInfoArg);
}
// Add the handler to this list.
if (NULL == m_pFirstHandler)
{
m_pFirstHandler = pHandlerInfoMoveFrom;
// Assert(1 == m_wHandlerCount); // Review = HandlerCount doesn't have to be 1 if ReleaseCompltedHandlers has been called.
}
else
{
LPHANDLERINFO pCurHandlerInfo;
pCurHandlerInfo = m_pFirstHandler;
while (pCurHandlerInfo->pNextHandler)
{
pCurHandlerInfo = pCurHandlerInfo->pNextHandler;
}
pCurHandlerInfo->pNextHandler = pHandlerInfoMoveFrom;
}
// if this is a progress queue and there are not items to sync for the
// handler or the HandlerState isn't in PrepareForSync then set
// the state to TransferRelease since it can be freed.
if ((QUEUETYPE_PROGRESS == m_QueueType && !fHasItemsToSync )
|| (pHandlerInfoMoveFrom->HandlerState != HANDLERSTATE_PREPAREFORSYNC))
{
pHandlerInfoMoveFrom->HandlerState = HANDLERSTATE_TRANSFERRELEASE;
}
return S_OK;
}
//+---------------------------------------------------------------------------
//
// Member: CHndlrQueue::TransferQueueData, public
//
// Synopsis: Moves the Items from one queue to another. Currently we only
// support transferrring items from a choice queueu to a choice or
// progress queue. Only handlers in the PREPAREFORSYNC state are moved
// when transferring to a Progress queue. When transferring to a choice
// queue only items in the ADDHANDLERITEMS state are moved.
//
// !!Warning - Cannot release lock during this process
//
// Arguments: [pQueueMoveFrom] - Queue to move items from.
// [dwSyncFlags] - flags that started the sync
// [pszConnectionName] - Connection the sync should be performed on, can be NULL
// [szSchedulName] - Name of Schedule that started this Job. Can be NULL.
// [hRasPendingEvent] - Event to signal when job is complete. Can be NULL.
//
// Returns: Appropriate return codes
//
// Modifies:
//
// History: 17-Nov-97 rogerg Created.
//
//----------------------------------------------------------------------------
STDMETHODIMP CHndlrQueue::TransferQueueData(CHndlrQueue *pQueueMoveFrom
/* ,DWORD dwSyncFlags,TCHAR *pzConnectionName,TCHAR *szScheduleName */)
{
HRESULT hr = E_UNEXPECTED;
HANDLERINFO HandlerInfoMoveFrom;
LPHANDLERINFO pHandlerInfoMoveFrom = &HandlerInfoMoveFrom;
CLock clockqueue(this);
CLock clockqueueMoveFrom(pQueueMoveFrom);
clockqueue.Enter();
clockqueueMoveFrom.Enter();
m_fNumItemsCompleteNeedsARecalc = TRUE; // need to recalc NumItems next time
if ((QUEUETYPE_PROGRESS != m_QueueType
&& QUEUETYPE_CHOICE != m_QueueType) || QUEUETYPE_CHOICE != pQueueMoveFrom->m_QueueType)
{
Assert(QUEUETYPE_PROGRESS == m_QueueType || QUEUETYPE_CHOICE == m_QueueType);
Assert(QUEUETYPE_CHOICE == pQueueMoveFrom->m_QueueType);
}
else if (NULL == pQueueMoveFrom->m_pFirstHandler)
{
// if no job info then there aren't any items to move.
}
else
{
JOBINFO *pMoveFromJobInfo = NULL;
// transfer everything over and then release after done call freecompletedhandlers
// to clean anything up.
// transfer over all jobs
Assert(pQueueMoveFrom->m_pFirstJobInfo);
Assert(pQueueMoveFrom->m_pFirstJobInfo->pConnectionObj);
pMoveFromJobInfo = pQueueMoveFrom->m_pFirstJobInfo;
pQueueMoveFrom->m_pFirstJobInfo = NULL;
if (NULL == m_pFirstJobInfo)
{
m_pFirstJobInfo = pMoveFromJobInfo;
}
else
{
JOBINFO *pCurLastJob = NULL;
pCurLastJob = m_pFirstJobInfo;
while (pCurLastJob->pNextJobInfo)
{
pCurLastJob = pCurLastJob->pNextJobInfo;
}
pCurLastJob->pNextJobInfo = pMoveFromJobInfo;
}
// loop through moving items, have to reassign the Handler ID and
// !!Warning - This function does nothing with ListViewData it is up to the
// caller to make sure this is set up properly
// review - should just loop through fixing up necessary items and then
// add entire list onto end. inneficient to do one at a time.
pHandlerInfoMoveFrom->pNextHandler = pQueueMoveFrom->m_pFirstHandler;
while (pHandlerInfoMoveFrom->pNextHandler)
{
LPHANDLERINFO pHandlerToMove;
HANDLERINFO *pNewHandlerId;
// Asserts for making sure the UI has been cleared from the queue
Assert(FALSE == pHandlerInfoMoveFrom->pNextHandler->fHasErrorJumps);
Assert(pHandlerInfoMoveFrom->pNextHandler->pJobInfo);
// !!! Warning get next handler before transfer or next ptr will be invalid.
pHandlerToMove = pHandlerInfoMoveFrom->pNextHandler;
pHandlerInfoMoveFrom->pNextHandler = pHandlerToMove->pNextHandler;
MoveHandler(pQueueMoveFrom,pHandlerToMove,&pNewHandlerId,&clockqueue);
// now set the original queues head
pQueueMoveFrom->m_pFirstHandler = HandlerInfoMoveFrom.pNextHandler;
hr = S_OK;
}
}
clockqueue.Leave();
clockqueueMoveFrom.Leave();
// now free any handlers that came into the queue that we
// don't want to do anything with .
ReleaseHandlers(HANDLERSTATE_TRANSFERRELEASE);
return hr;
}
//+---------------------------------------------------------------------------
//
// Member: CHndlrQueue::SetQueueHwnd, public
//
// Synopsis: informs the queue os the new dialog owner if any
// queue must also loop through existing proxies
// and reset their hwnd.
//
// Arguments:
//
// Returns: Appropriate return codes
//
// Modifies:
//
// History: 17-Nov-97 rogerg Created.
//
//----------------------------------------------------------------------------
STDMETHODIMP CHndlrQueue::SetQueueHwnd(CBaseDlg *pDlg)
{
LPHANDLERINFO pCurHandlerInfo;
CLock clockqueue(this);
clockqueue.Enter();
m_pDlg = pDlg;
if (m_pDlg)
{
m_hwndDlg = m_pDlg->GetHwnd();
}
else
{
m_hwndDlg = NULL;
}
m_dwQueueThreadId = GetCurrentThreadId(); // make sure queu threadId is updated.
pCurHandlerInfo = m_pFirstHandler;
while (pCurHandlerInfo)
{
if (pCurHandlerInfo->pThreadProxy)
{
pCurHandlerInfo->pThreadProxy->SetProxyParams(m_hwndDlg
,m_dwQueueThreadId
,this
,pCurHandlerInfo->pHandlerId);
}
pCurHandlerInfo = pCurHandlerInfo->pNextHandler;
}
clockqueue.Leave();
return S_OK;
}
//+---------------------------------------------------------------------------
//
// Member: CHndlrQueue::ReleaseCompletedHandlers, public
//
// Synopsis: Releases any Handlers that are in the Release or free
// dead state from the queue.
//
// Arguments:
//
// Returns: Appropriate return codes
//
// Modifies:
//
// History: 17-Nov-97 rogerg Created.
//
//----------------------------------------------------------------------------
STDMETHODIMP CHndlrQueue::ReleaseCompletedHandlers()
{
return ReleaseHandlers(HANDLERSTATE_RELEASE);
}
//+---------------------------------------------------------------------------
//
// Member: CHndlrQueue::FreeAllHandlers, public
//
// Synopsis: Releases all handlers from the queue.
//
// Arguments:
//
// Returns: Appropriate return codes
//
// Modifies:
//
// History: 17-Nov-97 rogerg Created.
//
//----------------------------------------------------------------------------
STDMETHODIMP CHndlrQueue::FreeAllHandlers(void)
{
return ReleaseHandlers(HANDLERSTATE_NEW); // release handlers in all states.
}
//+---------------------------------------------------------------------------
//
// Member: CHndlrQueue::ReleaseHandlers, public
//
// Synopsis: Releases any Handlers are in a state >= the requested state
//
// Arguments: HandlerState - Frees all handlers that have a state >= the requested state.
//
// !!Warning: This should be the only place the proxy if freed and
// the handler is removed from the list.
//
// Returns: Appropriate return codes
//
// Modifies:
//
// History: 17-Nov-97 rogerg Created.
//
//----------------------------------------------------------------------------
STDMETHODIMP CHndlrQueue::ReleaseHandlers(HANDLERSTATE HandlerState)
{
HANDLERINFO HandlerInfoStart;
LPHANDLERINFO pPrevHandlerInfo = &HandlerInfoStart;
LPHANDLERINFO pCurHandlerInfo = NULL;
LPHANDLERINFO pHandlerFreeList = NULL;
LPITEMLIST pCurItem = NULL;
LPITEMLIST pNextItem = NULL;
CLock clockqueue(this);
ASSERT_LOCKNOTHELD(this); // shouldn't be any out calls in progress when this is called.
clockqueue.Enter();
m_fNumItemsCompleteNeedsARecalc = TRUE; // need to recalc next GetProgress.
// loop through the handlers finding the one that match the criteria
// removing them from list and adding them to the free list
// we do this so don't have to worry about someone else accessing
// handlers we are freeing during an out call.
if (HANDLERSTATE_NEW == HandlerState)
{
// Release should only be called on this state if caller is sure no out
// calls are in progress or else handler may not exist when
// they come back
pHandlerFreeList = m_pFirstHandler;
m_pFirstHandler = NULL;
}
else
{
Assert(HandlerState >= HANDLERSTATE_RELEASE); // if in release no out calls are in progress.
pPrevHandlerInfo->pNextHandler = m_pFirstHandler;
while (pPrevHandlerInfo->pNextHandler)
{
pCurHandlerInfo = pPrevHandlerInfo->pNextHandler;
// if meet handler state criteria and not in any out calls then can
// remove from list.
// if request for HANDLERSTATE_NEW then assert than there shouldn't be
// any out calls in progress or terminating.
Assert(!(HandlerState == HANDLERSTATE_NEW) ||
(0 == pCurHandlerInfo->dwOutCallMessages && !pCurHandlerInfo->fInTerminateCall));
if ( (HandlerState <= pCurHandlerInfo->HandlerState)
&& (0 == pCurHandlerInfo->dwOutCallMessages)
&& !(pCurHandlerInfo->fInTerminateCall))
{
Assert (HANDLERSTATE_RELEASE == pCurHandlerInfo->HandlerState ||
HANDLERSTATE_TRANSFERRELEASE == pCurHandlerInfo->HandlerState ||
HANDLERSTATE_HASERRORJUMPS == pCurHandlerInfo->HandlerState ||
HANDLERSTATE_DEAD == pCurHandlerInfo->HandlerState);
// remove from queue list and add to free.
pPrevHandlerInfo->pNextHandler = pCurHandlerInfo->pNextHandler;
pCurHandlerInfo->pNextHandler = pHandlerFreeList;
pHandlerFreeList = pCurHandlerInfo;
}
else
{
// if no match then just continue.
pPrevHandlerInfo = pCurHandlerInfo;
}
}
// update the queue head.
m_pFirstHandler = HandlerInfoStart.pNextHandler;
}
// now loop through the free list freeing the items.
while (pHandlerFreeList)
{
pCurHandlerInfo = pHandlerFreeList;
pHandlerFreeList = pHandlerFreeList->pNextHandler;
// if the item has a job info release the reference on it.
if (pCurHandlerInfo->pJobInfo)
{
ReleaseJobInfo(pCurHandlerInfo->pJobInfo);
pCurHandlerInfo->pJobInfo = NULL;
}
if (pCurHandlerInfo->pThreadProxy)
{
CThreadMsgProxy *pThreadProxy = pCurHandlerInfo->pThreadProxy;
HWND hwndCallback;
Assert(HANDLERSTATE_DEAD != pCurHandlerInfo->HandlerState);
pCurHandlerInfo->HandlerState = HANDLERSTATE_DEAD;
pThreadProxy = pCurHandlerInfo->pThreadProxy;
pCurHandlerInfo->pThreadProxy = NULL;
hwndCallback = pCurHandlerInfo->hWndCallback;
pCurHandlerInfo->hWndCallback = NULL;
clockqueue.Leave(); // release lock when making the OutCall.
pThreadProxy->Release(); // review, don't release proxy to try to catch race condition.
clockqueue.Enter();
}
pCurItem = pCurHandlerInfo->pFirstItem;
while (pCurItem)
{
pNextItem = pCurItem->pnextItem;
FREE(pCurItem);
pCurItem = pNextItem;
}
FREE(pCurHandlerInfo);
}
clockqueue.Leave();
return S_OK;
}
//+---------------------------------------------------------------------------
//
// Member: CHndlrQueue::GetHandlerInfo, public
//
// Synopsis: Gets Data associated with the HandlerID and ItemID
//
// Arguments: [clsidHandler] - ClsiId Of Handler the Item belongs too
//
// Returns: Appropriate return codes
//
// Modifies:
//
// History: 17-Nov-97 rogerg Created.
//
//----------------------------------------------------------------------------
STDMETHODIMP CHndlrQueue::GetHandlerInfo(REFCLSID clsidHandler, LPSYNCMGRHANDLERINFO pSyncMgrHandlerInfo)
{
HRESULT hr = S_FALSE;
LPHANDLERINFO pCurHandlerInfo = NULL;
CLock clockqueue(this);
clockqueue.Enter();
// find first handler that matches the request CLSID
pCurHandlerInfo = m_pFirstHandler;
while (pCurHandlerInfo )
{
if (clsidHandler == pCurHandlerInfo->clsidHandler)
{
*pSyncMgrHandlerInfo = pCurHandlerInfo->SyncMgrHandlerInfo;
hr = S_OK;
break;
}
pCurHandlerInfo = pCurHandlerInfo->pNextHandler;
}
clockqueue.Leave();
return hr;
}
//+---------------------------------------------------------------------------
//
// Member: CHndlrQueue::GetHandlerInfo, public
//
// Synopsis: Gets Data associated with the HandlerID and ItemID
//
// Arguments: [wHandlerId] - Id Of Handler the Item belongs too
//
// Returns: Appropriate return codes
//
// Modifies:
//
// History: 17-Nov-97 rogerg Created.
//
//----------------------------------------------------------------------------
STDMETHODIMP CHndlrQueue::GetHandlerInfo(HANDLERINFO *pHandlerId, LPSYNCMGRHANDLERINFO pSyncMgrHandlerInfo)
{
HRESULT hr = S_FALSE;
LPHANDLERINFO pHandlerInfo = NULL;
CLock clockqueue(this);
clockqueue.Enter();
if (S_OK == LookupHandlerFromId(pHandlerId,&pHandlerInfo))
{
*pSyncMgrHandlerInfo = pHandlerInfo->SyncMgrHandlerInfo;
hr = S_OK;
}
clockqueue.Leave();
return hr;
}
//+---------------------------------------------------------------------------
//
// Member: CHndlrQueue::GetItemDataAtIndex, public
//
// Synopsis: Gets Data associated with the HandlerID and ItemID
//
// Arguments: [wHandlerId] - Id Of Handler the Item belongs too
// [wItemID] - Identifies the Item in the Handler
// [pclsidHandler] - on return contains a pointer to the clsid of the Handler
// [offlineItem] - on returns contains a pointer to the OfflineItem for the item.
// [pfHiddenItem] - On return is a bool indicating if this item is hidden.
//
// Returns: Appropriate return codes
//
// Modifies:
//
// History: 17-Nov-97 rogerg Created.
//
//----------------------------------------------------------------------------
STDMETHODIMP CHndlrQueue::GetItemDataAtIndex(HANDLERINFO *pHandlerId,WORD wItemID,
CLSID *pclsidHandler,SYNCMGRITEM *offlineItem,BOOL *pfHiddenItem)
{
BOOL fFoundMatch = FALSE;
LPHANDLERINFO pCurHandlerInfo = NULL;
LPITEMLIST pCurItem = NULL;
CLock clockqueue(this);
clockqueue.Enter();
pCurHandlerInfo = m_pFirstHandler;
while (pCurHandlerInfo && !fFoundMatch)
{
// only valid if Hanlder is in the PrepareForSync state.
if (pHandlerId == pCurHandlerInfo->pHandlerId) // see if CLSID matches
{
// see if handler info has a matching item
pCurItem = pCurHandlerInfo->pFirstItem;
while (pCurItem)
{
if (wItemID == pCurItem->wItemId)
{
fFoundMatch = TRUE;
break;
}
pCurItem = pCurItem->pnextItem;
}
}
if (!fFoundMatch)
pCurHandlerInfo = pCurHandlerInfo->pNextHandler;
}
if (fFoundMatch)
{
if (pclsidHandler)
{
*pclsidHandler = pCurHandlerInfo->clsidHandler;
}
if (offlineItem)
{
*offlineItem = pCurItem->offlineItem;
}
if (pfHiddenItem)
{
*pfHiddenItem = pCurItem->fHiddenItem;
}
}
clockqueue.Leave();
return fFoundMatch ? S_OK : S_FALSE;
}
//+---------------------------------------------------------------------------
//
// Member: CHndlrQueue::GetItemDataAtIndex, public
//
// Synopsis: Gets Data associated with the HandlerID and OfflineItemID
//
// Arguments: [wHandlerId] - Id Of Handler the Item belongs too
// [ItemID] - identifies the Item by its OfflineItemID
// [pclsidHandler] - on return contains a pointer to the clsid of the Handler
// [offlineItem] - on returns contains a pointer to the OfflineItem for the item.
// [pfHiddenItem] - On return is a bool indicating if this item is a hidden item.
//
// Returns: Appropriate return codes
//
// Modifies:
//
// History: 17-Nov-97 rogerg Created.
//
//----------------------------------------------------------------------------
STDMETHODIMP CHndlrQueue::GetItemDataAtIndex(HANDLERINFO *pHandlerId,REFSYNCMGRITEMID ItemID,CLSID *pclsidHandler,
SYNCMGRITEM *offlineItem,BOOL *pfHiddenItem)
{
BOOL fFoundMatch = FALSE;
LPHANDLERINFO pCurHandlerInfo = NULL;
LPITEMLIST pCurItem = NULL;
CLock clockqueue(this);
clockqueue.Enter();
pCurHandlerInfo = m_pFirstHandler;
while (pCurHandlerInfo && !fFoundMatch)
{
// only valid if handler is in the PrepareForSync state.
if (pHandlerId == pCurHandlerInfo->pHandlerId) // see if CLSID matches
{
// see if handler info has a matching item
pCurItem = pCurHandlerInfo->pFirstItem;
while (pCurItem)
{
if (ItemID == pCurItem->offlineItem.ItemID)
{
fFoundMatch = TRUE;
break;
}
pCurItem = pCurItem->pnextItem;
}
}
if (!fFoundMatch)
pCurHandlerInfo = pCurHandlerInfo->pNextHandler;
}
if (fFoundMatch)
{
*pclsidHandler = pCurHandlerInfo->clsidHandler;
*offlineItem = pCurItem->offlineItem;
*pfHiddenItem = pCurItem->fHiddenItem;
}
clockqueue.Leave();
return fFoundMatch ? S_OK : S_FALSE;
}
//+---------------------------------------------------------------------------
//
// Member: CHndlrQueue::FindFirstItemInState, public
//
// Synopsis: Finds the first Item in the queue that matches the given state.
//
// Arguments:
// [hndlrState] - specifies matching state we are looking for.
// [pwHandlerId] - on return contains the HandlerID of the Item
// [pwItemID] - on returns contains the ItemID of the item in the queue.
//
// Returns: S_OK if an Item was found with an unassigned ListView.
// S_FALSE - if no Item was found.
// Appropriate error return codes
//
// Modifies:
//
// History: 30-Jul-98 rogerg Created.
//
//----------------------------------------------------------------------------
STDMETHODIMP CHndlrQueue::FindFirstItemInState(HANDLERSTATE hndlrState,
HANDLERINFO **ppHandlerId,WORD *pwItemID)
{
return FindNextItemInState(hndlrState,0,0,ppHandlerId,pwItemID);
}
//+---------------------------------------------------------------------------
//
// Member: CHndlrQueue::FindNextItemInState, public
//
// Synopsis: Finds the first Item in the queue that matches the given state.
// after the specified item.
//
// Arguments:
// [hndlrState] - specifies matching state we are looking for.
// [pOfflineItemID] - on returns contains a pointer to the OfflineItem for the item.
// [pwHandlerId] - on return contains the HandlerID of the Item
// [pwItemID] - on returns contains the ItemID of the item in the queue.
//
// Returns: S_OK if an Item was found with an unassigned ListView.
// S_FALSE - if no Item was found.
// Appropriate error return codes
//
// Modifies:
//
// History: 30-Jul-98 rogerg Created.
//
//----------------------------------------------------------------------------
STDMETHODIMP CHndlrQueue::FindNextItemInState(HANDLERSTATE hndlrState,
HANDLERINFO *pLastHandlerId,WORD wLastItemID,
HANDLERINFO **ppHandlerId,WORD *pwItemID)
{
BOOL fFoundMatch = FALSE;
LPHANDLERINFO pCurHandlerInfo = NULL;
LPITEMLIST pCurItem = NULL;
CLock clockqueue(this);
clockqueue.Enter();
pCurHandlerInfo = m_pFirstHandler;
if (pLastHandlerId)
{
// loop until find the specified handler or hit end of list.
while(pCurHandlerInfo && pLastHandlerId != pCurHandlerInfo->pHandlerId)
{
pCurHandlerInfo = pCurHandlerInfo->pNextHandler;
}
if (NULL == pCurHandlerInfo) // reached end of list without finding the Handler
{
Assert(0); // user must have passed an invalid start HandlerID.
clockqueue.Leave();
return S_FALSE;
}
// loop until find item or end of item list
pCurItem = pCurHandlerInfo->pFirstItem;
while (pCurItem && pCurItem->wItemId != wLastItemID)
{
pCurItem = pCurItem->pnextItem;
}
if (NULL == pCurItem) // reached end of item list without finding the specified item
{
Assert(0); // user must have passed an invalid start ItemID.
clockqueue.Leave();
return S_FALSE;
}
// now we found the Handler and item. loop through remaining items for this handler
// if it still has another item then just return that.
pCurItem = pCurItem->pnextItem;
if (pCurItem)
{
Assert(hndlrState == pCurHandlerInfo->HandlerState); // should only be called in PrepareForSyncState
fFoundMatch = TRUE;
}
if (!fFoundMatch)
pCurHandlerInfo = pCurHandlerInfo->pNextHandler; // increment to next handler if no match
}
if (!fFoundMatch)
{
// in didn't find a match in the
while (pCurHandlerInfo)
{
if ((hndlrState == pCurHandlerInfo->HandlerState) && (pCurHandlerInfo->pFirstItem) )
{
pCurItem = pCurHandlerInfo->pFirstItem;
fFoundMatch = TRUE;
break;
}
pCurHandlerInfo = pCurHandlerInfo->pNextHandler;
}
}
if (fFoundMatch)
{
*ppHandlerId = pCurHandlerInfo->pHandlerId;
*pwItemID = pCurItem->wItemId;
}
clockqueue.Leave();
return fFoundMatch ? S_OK : S_FALSE;
}
//+---------------------------------------------------------------------------
//
// Member: CHndlrQueue::SetItemState, public
//
// Synopsis: Set the Item state for the first item finds that it
// matches in the Queue. Sets all other matches to unchecked.
//
// Arguments:
//
// Returns: Appropriate error return codes
//
// Modifies:
//
// History: 30-Jul-98 rogerg Created.
//
//----------------------------------------------------------------------------
STDMETHODIMP CHndlrQueue::SetItemState(REFCLSID clsidHandler,REFSYNCMGRITEMID ItemID,DWORD dwState)
{
LPHANDLERINFO pCurHandlerInfo = NULL;
LPITEMLIST pCurItem = NULL;
BOOL fFoundMatch = FALSE;
CLock clockqueue(this);
if (QUEUETYPE_CHOICE != m_QueueType)
{
Assert(QUEUETYPE_CHOICE == m_QueueType);
return E_UNEXPECTED;
}
clockqueue.Enter();
pCurHandlerInfo = m_pFirstHandler;
while (pCurHandlerInfo)
{
if (clsidHandler == pCurHandlerInfo->clsidHandler)
{
pCurItem = pCurHandlerInfo->pFirstItem;
while (pCurItem)
{
if (ItemID == pCurItem->offlineItem.ItemID)
{
// if the handlerstate is not prepareforsync or not first match then uncheck
if ((HANDLERSTATE_PREPAREFORSYNC != pCurHandlerInfo->HandlerState) || fFoundMatch)
{
pCurItem->offlineItem.dwItemState = SYNCMGRITEMSTATE_UNCHECKED;
}
else
{
pCurItem->offlineItem.dwItemState = dwState;
fFoundMatch = TRUE;
}
}
pCurItem = pCurItem->pnextItem;
}
}
pCurHandlerInfo = pCurHandlerInfo->pNextHandler;
}
clockqueue.Leave();
Assert(fFoundMatch); // we should have found at least one match.
return S_OK;
}
//+---------------------------------------------------------------------------
//
// Member: CHndlrQueue::SkipItem, public
//
// Synopsis: loop through handler and mark the items appropriately that match..
//
// Arguments: [iItem] - List View Item to skip.
//
// Returns: Appropriate return codes.
//
// Modifies:
//
// History: 17-Nov-97 rogerg Created.
//
//----------------------------------------------------------------------------
STDMETHODIMP CHndlrQueue::SkipItem(REFCLSID clsidHandler,REFSYNCMGRITEMID ItemID)
{
LPHANDLERINFO pCurHandlerInfo = NULL;
LPITEMLIST pCurItem = NULL;
CLock clockqueue(this);
HRESULT hr = S_OK;
if (QUEUETYPE_PROGRESS != m_QueueType)
{
Assert(QUEUETYPE_PROGRESS == m_QueueType);
return E_UNEXPECTED;
}
clockqueue.Enter();
pCurHandlerInfo = m_pFirstHandler;
while (pCurHandlerInfo )
{
if (clsidHandler == pCurHandlerInfo->clsidHandler)
{
pCurItem = pCurHandlerInfo->pFirstItem;
while (pCurItem)
{
// if item is cancelled then also treat as a match to
// handle case cancel came in while in an out call.
if ( ItemID == pCurItem->offlineItem.ItemID)
{
// found an item, now if it hasn't started the sync or
// is not already complete set the value.
if ((pCurHandlerInfo->HandlerState < HANDLERSTATE_RELEASE) )
{
pCurItem->fItemCancelled = TRUE;
// If haven't called PrepareforSync yet then
// set uncheck the item so it isn't passed to PrepareForSync
// If PrepareForSync has already been called, call the items
// SkipMethod. if already in a setItemstatus call for this handler don't
// do anything.
// if not in another setitemstatus call loop through freeing all
// the items that have the cancel set.
// essentially a dup of cance and also handle case cancel
// comes win while this handler is in an out call.
if (!(pCurHandlerInfo->dwOutCallMessages & ThreadMsg_SetItemStatus))
{
pCurHandlerInfo->dwOutCallMessages |= ThreadMsg_SetItemStatus;
if (pCurHandlerInfo->HandlerState >= HANDLERSTATE_INPREPAREFORSYNC
&& pCurItem->fSynchronizingItem )
{
CThreadMsgProxy *pThreadProxy;
SYNCMGRITEMID ItemId;
pThreadProxy = pCurHandlerInfo->pThreadProxy;
ItemId = pCurItem->offlineItem.ItemID;
clockqueue.Leave();
if (pThreadProxy)
{
hr = pThreadProxy->SetItemStatus(ItemId, SYNCMGRSTATUS_SKIPPED);
}
clockqueue.Enter();
}
else
{
// once done skipping handler if state is <= preparefor sync we set the state accordingly.
// if were syncing up to handler.
if ( (pCurHandlerInfo->HandlerState <= HANDLERSTATE_PREPAREFORSYNC)
&& (pCurItem->fIncludeInProgressBar) )
{
SYNCMGRPROGRESSITEM SyncProgressItem;
// unheck the state so PrepareForsync doesn't include
// this item.
pCurItem->offlineItem.dwItemState = SYNCMGRITEMSTATE_UNCHECKED;
SyncProgressItem.cbSize = sizeof(SYNCMGRPROGRESSITEM);
SyncProgressItem.mask = SYNCMGRPROGRESSITEM_PROGVALUE | SYNCMGRPROGRESSITEM_MAXVALUE | SYNCMGRPROGRESSITEM_STATUSTYPE;
SyncProgressItem.iProgValue = HNDRLQUEUE_DEFAULT_PROGRESS_MAXVALUE;
SyncProgressItem.iMaxValue = HNDRLQUEUE_DEFAULT_PROGRESS_MAXVALUE;
SyncProgressItem.dwStatusType = SYNCMGRSTATUS_SKIPPED;
// need to setup HwndCallback so progres gets updated.
// review, after ship why can't setup HwndCallback on transferqueueu
pCurHandlerInfo->hWndCallback = m_hwndDlg;
clockqueue.Leave();
Progress(pCurHandlerInfo->pHandlerId, pCurItem->offlineItem.ItemID,&SyncProgressItem);
clockqueue.Enter();
}
}
pCurHandlerInfo->dwOutCallMessages &= ~ThreadMsg_SetItemStatus;
}
}
}
pCurItem = pCurItem->pnextItem;
}
}
pCurHandlerInfo = pCurHandlerInfo->pNextHandler;
}
clockqueue.Leave();
return hr;
}
//+---------------------------------------------------------------------------
//
// Member: CHndlrQueue::ItemHasProperties, public
//
// Synopsis: determines if the item in the queue has properties.
// Uses the first item match it finds.
//
// Arguments:
//
// Returns: Appropriate error return codes
//
// Modifies:
//
// History: 30-Jul-98 rogerg Created.
//
//----------------------------------------------------------------------------
STDMETHODIMP CHndlrQueue::ItemHasProperties(REFCLSID clsidHandler,REFSYNCMGRITEMID ItemID)
{
LPHANDLERINFO pHandlerInfo;
LPITEMLIST pItem;
HRESULT hr = S_FALSE;
CLock clockqueue(this);
Assert(QUEUETYPE_CHOICE == m_QueueType);
ASSERT_LOCKNOTHELD(this);
clockqueue.Enter();
// item is guidNULL this is toplevel so use the getHandlerInfo, else see
// if the item supports showProperties.
if (S_OK == FindItemData(clsidHandler,ItemID,
HANDLERSTATE_PREPAREFORSYNC,HANDLERSTATE_PREPAREFORSYNC,&pHandlerInfo,&pItem))
{
if (GUID_NULL == ItemID)
{
Assert(NULL == pItem);
hr = ((pHandlerInfo->SyncMgrHandlerInfo).SyncMgrHandlerFlags & SYNCMGRHANDLER_HASPROPERTIES) ? S_OK : S_FALSE;
}
else
{
Assert(pItem);
if (pItem)
{
hr = (pItem->offlineItem).dwFlags & SYNCMGRITEM_HASPROPERTIES ? S_OK : S_FALSE;
}
else
{
hr = S_FALSE;
}
}
}
clockqueue.Leave();
return hr;
}
//+---------------------------------------------------------------------------
//
// Member: CHndlrQueue::ShowProperties, public
//
// Synopsis: Calls the ShowProperties Method on the first items it finds.
// Uses the first item match it finds.
//
// Arguments:
//
// Returns: Appropriate error return codes
//
// Modifies:
//
// History: 30-Jul-98 rogerg Created.
//
//----------------------------------------------------------------------------
STDMETHODIMP CHndlrQueue::ShowProperties(REFCLSID clsidHandler,REFSYNCMGRITEMID ItemID,HWND hwndParent)
{
LPHANDLERINFO pHandlerInfo;
LPHANDLERINFO pHandlerId = NULL;
LPITEMLIST pItem;
HRESULT hr = E_UNEXPECTED;
BOOL fHandlerCalled = FALSE;
BOOL fHasProperties = FALSE;
CThreadMsgProxy *pThreadProxy;
CLock clockqueue(this);
Assert(QUEUETYPE_CHOICE == m_QueueType);
ASSERT_LOCKNOTHELD(this);
clockqueue.Enter();
if (S_OK == FindItemData(clsidHandler,ItemID,
HANDLERSTATE_PREPAREFORSYNC,HANDLERSTATE_PREPAREFORSYNC,&pHandlerInfo,&pItem))
{
Assert(HANDLERSTATE_PREPAREFORSYNC == pHandlerInfo->HandlerState);
pThreadProxy = pHandlerInfo->pThreadProxy;
pHandlerId = pHandlerInfo->pHandlerId;
Assert(!(ThreadMsg_ShowProperties & pHandlerInfo->dwOutCallMessages));
pHandlerInfo->dwOutCallMessages |= ThreadMsg_ShowProperties;
if (GUID_NULL == ItemID && pHandlerInfo)
{
Assert(NULL == pItem);
fHasProperties = (pHandlerInfo->SyncMgrHandlerInfo).SyncMgrHandlerFlags
& SYNCMGRHANDLER_HASPROPERTIES ? TRUE : FALSE;
}
else if (pItem)
{
Assert(SYNCMGRITEM_HASPROPERTIES & pItem->offlineItem.dwFlags);
fHasProperties = (pItem->offlineItem).dwFlags
& SYNCMGRITEM_HASPROPERTIES ? TRUE : FALSE;
}
else
{
fHasProperties = FALSE;
}
clockqueue.Leave();
// make sure properties flag isn't set.
if (fHasProperties && pThreadProxy )
{
fHandlerCalled = TRUE;
hr = pThreadProxy->ShowProperties(hwndParent,ItemID);
}
else
{
AssertSz(0,"ShowProperties called on an Item without properties");
hr = S_FALSE;
}
Assert(pHandlerId);
if ( (fHandlerCalled && (FAILED(hr))) || (!fHandlerCalled) )
{
GUID guidCompletion = ItemID;
CallCompletionRoutine(pHandlerId,ThreadMsg_ShowProperties,hr,1,&guidCompletion);
// since called completion routine map anything but S_OK to S_FALSE;
// so caller doesn't wait for the callback.
if (S_OK != hr)
{
hr = S_FALSE;
}
}
}
else
{
Assert(FAILED(hr)); // should return some failure so caller knows callback isn't coming.
clockqueue.Leave();
}
return hr;
}
//+---------------------------------------------------------------------------
//
// Member: CHndlrQueue::ReEnumHandlerItems, public
//
// Synopsis: Deletes any Items associated with any handlers that
// match the clsid of the handler and then
// call the first handlers in the list enumeration method
// again.
//
// Arguments:
//
// Returns: Appropriate error return codes
//
// Modifies:
//
// History: 30-Jul-98 rogerg Created.
//
//----------------------------------------------------------------------------
STDMETHODIMP CHndlrQueue::ReEnumHandlerItems(REFCLSID clsidHandler,REFSYNCMGRITEMID ItemID)
{
LPHANDLERINFO pCurHandlerInfo = NULL;
HANDLERINFO *pHandlerId = NULL;
LPITEMLIST pCurItem = NULL;
CLock clockqueue(this);
if (QUEUETYPE_CHOICE != m_QueueType)
{
Assert(QUEUETYPE_CHOICE == m_QueueType);
return E_UNEXPECTED;
}
clockqueue.Enter();
pCurHandlerInfo = m_pFirstHandler;
while (pCurHandlerInfo)
{
if (clsidHandler == pCurHandlerInfo->clsidHandler)
{
LPITEMLIST pNextItem;
// if first handler we found update the handlerID
if (pHandlerId)
{
pHandlerId = pCurHandlerInfo->pHandlerId;
pCurHandlerInfo->HandlerState = HANDLERSTATE_ADDHANDLERTEMS; // put back to addhandlerItems statest
}
pCurHandlerInfo->wItemCount = 0;
pCurItem = pCurHandlerInfo->pFirstItem;
while (pCurItem)
{
pNextItem = pCurItem->pnextItem;
FREE(pCurItem);
pCurItem = pNextItem;
}
pCurHandlerInfo->pFirstItem = NULL;
}
pCurHandlerInfo = pCurHandlerInfo->pNextHandler;
}
clockqueue.Leave();
// if have a handler id add them back to the queue
if (pHandlerId)
{
DWORD cbNumItemsAdded;
AddHandlerItemsToQueue(pHandlerId,&cbNumItemsAdded);
}
return S_OK;
}
//+---------------------------------------------------------------------------
//
// Member: CHndlrQueue::IsItemCompleted, private
//
// Synopsis: Given an handler item determines if its
// synchronization is completed
//
// !!!This is not efficient. n! solution. If get
// a lot of items may need to have to rewrite
// and cache some information concerning dup
// items.
//
// Arguments: [wHandlerId] - Handler the item belongs too.
// [wItemID] - Identifies the Item
//
// Returns:
//
// Modifies:
//
// History: 17-Nov-97 rogerg Created.
//
//----------------------------------------------------------------------------
BOOL CHndlrQueue::IsItemCompleted(LPHANDLERINFO pHandler,LPITEMLIST pItem)
{
CLSID clsidHandler;
SYNCMGRITEMID ItemId;
int iItemNotComplete = 0;
Assert(pHandler);
Assert(pItem);
ASSERT_LOCKHELD(this); // caller of this function should have already locked the queue.
clsidHandler = pHandler->clsidHandler;
ItemId = pItem->offlineItem.ItemID;
// back up to beginning of handler to simplify logic
// items must be pCurItem->fIncludeInProgressBar && !pCurItem->fProgressBarHandled
// to count toward not being a completion;
while (pHandler)
{
if (pHandler->clsidHandler == clsidHandler)
{
// see if handler info has a matching item
pItem = pHandler->pFirstItem;
while (pItem)
{
if (pItem->offlineItem.ItemID == ItemId)
{
if (pItem->fIncludeInProgressBar && !pItem->fProgressBarHandled)
{
if (pItem->iProgValue < pItem->iProgMaxValue)
{
++iItemNotComplete;
}
pItem->fProgressBarHandled = TRUE;
}
}
pItem = pItem->pnextItem;
}
}
pHandler = pHandler->pNextHandler;
}
return iItemNotComplete ? FALSE : TRUE;
}
//+---------------------------------------------------------------------------
//
// Member: CHndlrQueue::SetItemProgressInfo, public
//
// Synopsis: Updates the stored progress information for the
// Associated Items
//
// Arguments: [wHandlerId] - Handler the item belongs too.
// [wItemID] - Identifies the Item
// [pSyncProgressItem] - Pointer to Progress Information.
// [pfProgressChanged] - returns true if any progress values were changed
// for the item
//
// Returns: S_OK - at least one item with the iItem assigned was found
// S_FALSE - Item does not have properties.
// Appropriate error return codes
//
// Modifies:
//
// History: 17-Nov-97 rogerg Created.
//
//----------------------------------------------------------------------------
STDMETHODIMP CHndlrQueue::SetItemProgressInfo(HANDLERINFO *pHandlerId,WORD wItemID,
LPSYNCMGRPROGRESSITEM pSyncProgressItem,
BOOL *pfProgressChanged)
{
HRESULT hr = E_UNEXPECTED;
LPHANDLERINFO pHandlerInfo = NULL;
BOOL fFoundMatch = FALSE;
LPITEMLIST pCurItem = NULL;
CLock clockqueue(this);
Assert(pfProgressChanged);
*pfProgressChanged = FALSE;
if (QUEUETYPE_PROGRESS != m_QueueType)
{
Assert(QUEUETYPE_PROGRESS == m_QueueType);
return E_UNEXPECTED; // review error code.
}
clockqueue.Enter();
if (S_OK == LookupHandlerFromId(pHandlerId,&pHandlerInfo))
{
// try to find the matching item.
pCurItem = pHandlerInfo->pFirstItem;
while (pCurItem)
{
if (wItemID == pCurItem->wItemId)
{
fFoundMatch = TRUE;
break;
}
pCurItem = pCurItem->pnextItem;
}
}
if (fFoundMatch)
{
SetItemProgressInfo(pCurItem,pSyncProgressItem,pfProgressChanged);
}
clockqueue.Leave();
return fFoundMatch ? S_OK : S_FALSE;
}
//+---------------------------------------------------------------------------
//
// Member: CHndlrQueue::SetItemProgressInfo, private
//
// Synopsis: Updates the stored progress information for the
// Associated iTEM
//
// Arguments: [pItem] - Identifies the Item
// [pSyncProgressItem] - Pointer to Progress Information.
// [pfProgressChanged] - returns true if any progress values were changed
// for the item
//
// Returns: S_OK - at least one item with the iItem assigned was found
// Appropriate error return codes
//
// !!Caller must have already taken a lock.
//
// Modifies:
//
// History: 17-Nov-97 rogerg Created.
//
//----------------------------------------------------------------------------
STDMETHODIMP CHndlrQueue::SetItemProgressInfo(LPITEMLIST pItem,LPSYNCMGRPROGRESSITEM pSyncProgressItem,
BOOL *pfProgressChanged)
{
BOOL fProgressAlreadyCompleted;
ASSERT_LOCKHELD(this); // caller of this function should have already locked the queue.
// progress is considered complete if Values is >= Maxa
fProgressAlreadyCompleted = (pItem->iProgMaxValue <= pItem->iProgValue);
if (SYNCMGRPROGRESSITEM_MAXVALUE & pSyncProgressItem->mask)
{
// if Progress Max Value is negative then don't set.
if (pSyncProgressItem->iMaxValue >= 0)
{
if (pItem->iProgMaxValue != pSyncProgressItem->iMaxValue)
{
*pfProgressChanged = TRUE;
pItem->fProgValueDirty = TRUE;
pItem->iProgMaxValue = pSyncProgressItem->iMaxValue;
}
}
}
if (SYNCMGRPROGRESSITEM_PROGVALUE & pSyncProgressItem->mask)
{
// if progress value is negative, don't change it
if (pSyncProgressItem->iProgValue > 0)
{
if (pItem->iProgValue != pSyncProgressItem->iProgValue)
{
*pfProgressChanged = TRUE;
pItem->fProgValueDirty = TRUE;
pItem->iProgValue = pSyncProgressItem->iProgValue;
}
}
}
if (SYNCMGRPROGRESSITEM_STATUSTYPE & pSyncProgressItem->mask)
{
if (pItem->dwStatusType != pSyncProgressItem->dwStatusType)
{
*pfProgressChanged = TRUE;
pItem->dwStatusType = pSyncProgressItem->dwStatusType;
// if status is complete set the progvalue == to the max
// on behalf of the handler so the Items completed and progress bar
// gets updated.
if (pItem->dwStatusType == SYNCMGRSTATUS_SKIPPED
|| pItem->dwStatusType == SYNCMGRSTATUS_SUCCEEDED
|| pItem->dwStatusType == SYNCMGRSTATUS_FAILED )
{
pItem->fProgValueDirty = TRUE;
pItem->iProgValue = pItem->iProgMaxValue;
}
}
}
// if progressValue is > max then set it to max
if (pItem->iProgValue > pItem->iProgMaxValue)
{
// AssertSz(0,"Progress Value is > Max");
pItem->iProgValue = pItem->iProgMaxValue;
}
// see if need to recalc numItems completed next time
// GetProgressInfo is Called.
BOOL fProgressCompletedNow = (pItem->iProgMaxValue <= pItem->iProgValue);
if (fProgressAlreadyCompleted != fProgressCompletedNow)
{
m_fNumItemsCompleteNeedsARecalc = TRUE;
}
return S_OK;
}
//+---------------------------------------------------------------------------
//
// Member: CHndlrQueue::SetItemProgressValues, private
//
// Synopsis: Private helper function for updating/initializing
// an items progress bar values.
//
// Arguments: [pItem] - Identifies the Item
// [pSyncProgressItem] - Pointer to Progress Information.
// [pfProgressChanged] - returns true if any progress values were changed
// for the item
//
// Returns: S_OK - at least one item with the iItem assigned was found
// Appropriate error return codes
//
// !!Caller must have already taken a lock.
//
// Modifies:
//
// History: 17-Nov-97 rogerg Created.
//
//----------------------------------------------------------------------------
STDMETHODIMP CHndlrQueue::SetItemProgressValues(LPITEMLIST pItem,INT iProgValue,INT iProgMaxValue)
{
SYNCMGRPROGRESSITEM SyncProgressItem;
BOOL fProgressChanged;
ASSERT_LOCKHELD(this); // caller of this function should have already locked the queue.
SyncProgressItem.cbSize = sizeof(SYNCMGRPROGRESSITEM);
SyncProgressItem.mask = SYNCMGRPROGRESSITEM_PROGVALUE | SYNCMGRPROGRESSITEM_MAXVALUE;
SyncProgressItem.iProgValue = iProgValue;
SyncProgressItem.iMaxValue = iProgMaxValue;
return SetItemProgressInfo(pItem,&SyncProgressItem,&fProgressChanged);
}
//+---------------------------------------------------------------------------
//
// Member: CHndlrQueue::GetProgressInfo, public
//
// Synopsis: calculates current progress bar values and number of items complete.
//
// Arguments: [piProgValue] - on return contains the new Progress Bar Value.
// [piMaxValue] - on return contains the Progress Bar Max Value
// [piNumItemsComplete] - on returns contains number of items complete.
// [iNumItemsTotal] - on returns contains number of total items.
//
// Returns: Appropriate error codes
//
// Modifies:
//
// History: 17-Nov-97 rogerg Created.
//
//----------------------------------------------------------------------------
STDMETHODIMP CHndlrQueue::GetProgressInfo(INT *piProgValue,INT *piMaxValue,INT *piNumItemsComplete,
INT *piNumItemsTotal)
{
LPHANDLERINFO pCurHandlerInfo = NULL;
LPITEMLIST pCurItem = NULL;
INT iCurValue;
BOOL fNormalizedValueChanged = FALSE;
CLock clockqueue(this);
if (QUEUETYPE_PROGRESS != m_QueueType)
{
Assert(QUEUETYPE_PROGRESS == m_QueueType);
return E_UNEXPECTED; // review error code.
}
clockqueue.Enter();
// if m_fNumItemsCompleteNeedsARecalc is set need
// to recalc normalized and numItems Comlete and Total Items.
if (m_fNumItemsCompleteNeedsARecalc)
{
INT iNormalizedMax;
m_ulProgressItemCount = 0;
// get the number of selected items in the queue.
pCurHandlerInfo = m_pFirstHandler;
while (pCurHandlerInfo)
{
// see if handler info has a matching item
pCurItem = pCurHandlerInfo->pFirstItem;
while (pCurItem)
{
if (pCurItem->fIncludeInProgressBar)
{
//if this item should be included in the progress, increment the progress bar count.
++m_ulProgressItemCount;
pCurItem->fProgressBarHandled = FALSE; // reset handled
}
pCurItem = pCurItem->pnextItem;
}
pCurHandlerInfo = pCurHandlerInfo->pNextHandler;
}
if (0 == m_ulProgressItemCount)
{
iNormalizedMax = 0;
}
else
{
iNormalizedMax = MAXPROGRESSVALUE/m_ulProgressItemCount;
if (0 == iNormalizedMax)
{
iNormalizedMax = 1;
}
}
if (m_iNormalizedMax != iNormalizedMax)
{
fNormalizedValueChanged = TRUE;
m_iNormalizedMax = iNormalizedMax;
}
}
// now loop thruogh again getting total CurValue and finished items
// we say an item is finished if it is out of the synchronize method or the min==max.
pCurHandlerInfo = m_pFirstHandler;
iCurValue = 0;
// if numitemcount needs updated reset the member vars
if (m_fNumItemsCompleteNeedsARecalc)
{
m_iCompletedItems = 0;
m_iItemCount = 0;
}
while (pCurHandlerInfo)
{
// see if handler info has a matching item
pCurItem = pCurHandlerInfo->pFirstItem;
while (pCurItem)
{
if (pCurItem->fIncludeInProgressBar)
{
// if Progress is dirty or normalized value changed
// need to recalc this items progress value
if (pCurItem->fProgValueDirty || fNormalizedValueChanged)
{
int iProgValue = pCurItem->iProgValue;
int iProgMaxValue = pCurItem->iProgMaxValue;
if (iProgValue && iProgMaxValue)
{
pCurItem->iProgValueNormalized = (int) ((1.0*iProgValue*m_iNormalizedMax)/iProgMaxValue);
}
else
{
pCurItem->iProgValueNormalized = 0;
}
pCurItem->fProgValueDirty = FALSE;
}
iCurValue += pCurItem->iProgValueNormalized;
// Handle NumItems needing to be recalc'd
if (m_fNumItemsCompleteNeedsARecalc && !pCurItem->fProgressBarHandled)
{
++m_iItemCount;
// now loop through this item and remaining items and if any match
// mark as handled and if complete then incrment the compleated count;
if (IsItemCompleted(pCurHandlerInfo,pCurItem))
{
++m_iCompletedItems;
}
}
}
pCurItem = pCurItem->pnextItem;
}
pCurHandlerInfo = pCurHandlerInfo->pNextHandler;
}
m_fNumItemsCompleteNeedsARecalc = FALSE;
*piProgValue = iCurValue;
*piMaxValue = m_iNormalizedMax*m_ulProgressItemCount;
*piNumItemsComplete = m_iCompletedItems;
*piNumItemsTotal = m_iItemCount;
Assert(*piProgValue <= *piMaxValue);
clockqueue.Leave();
return S_OK;
}
//+---------------------------------------------------------------------------
//
// Member: CHndlrQueue::RemoveFinishedProgressItems, public
//
// Synopsis: Loops through handler setting any finished items
// fIncludeInProgressBar value to false
//
// Arguments:
//
// Returns: Appropriate return codes.
//
// Modifies:
//
// History: 17-Nov-97 rogerg Created.
//
//----------------------------------------------------------------------------
STDMETHODIMP CHndlrQueue::RemoveFinishedProgressItems()
{
LPHANDLERINFO pCurHandlerInfo = NULL;
LPITEMLIST pCurItem = NULL;
CLock clockqueue(this);
clockqueue.Enter();
m_fNumItemsCompleteNeedsARecalc = TRUE;
pCurHandlerInfo = m_pFirstHandler;
while (pCurHandlerInfo)
{
// mark any items that have completed their synchronization.
if (HANDLERSTATE_INSYNCHRONIZE < pCurHandlerInfo->HandlerState)
{
// see if handler info has a matching item
pCurItem = pCurHandlerInfo->pFirstItem;
while (pCurItem)
{
pCurItem->fIncludeInProgressBar = FALSE;
pCurItem = pCurItem->pnextItem;
}
}
pCurHandlerInfo = pCurHandlerInfo->pNextHandler;
}
clockqueue.Leave();
return S_OK;
}
//+---------------------------------------------------------------------------
//
// Member: CHndlrQueue::AreAnyItemsSelectedInQueue, public
//
// Synopsis: Determines if there are any items selected in the queue.
// can be called by choice dialog for example before creating
// progress and doing a transfer since there is no need to
// if nothing to sync anyways.
//
// Arguments:
//
// Returns: TRUE - At least one item is selected inthe queue
// FALSE - No Items are slected in the queue.
//
// Modifies:
//
// History: 17-Nov-97 rogerg Created.
//
//----------------------------------------------------------------------------
BOOL CHndlrQueue::AreAnyItemsSelectedInQueue()
{
LPHANDLERINFO pCurHandlerInfo = NULL;
LPITEMLIST pCurItem = NULL;
BOOL fFoundSelectedItem = FALSE;
CLock clockqueue(this);
clockqueue.Enter();
// invalidate UI that applies to entire queue
pCurHandlerInfo = m_pFirstHandler;
while (pCurHandlerInfo && !fFoundSelectedItem)
{
// if handler state is less than a completion go ahead and
// check the items.
if (HANDLERSTATE_HASERRORJUMPS > pCurHandlerInfo->HandlerState)
{
pCurItem = pCurHandlerInfo->pFirstItem;
while (pCurItem)
{
// clear Item UI information
if (pCurItem->offlineItem.dwItemState == SYNCMGRITEMSTATE_CHECKED)
{
fFoundSelectedItem = TRUE;
break;
}
pCurItem = pCurItem->pnextItem;
}
}
pCurHandlerInfo = pCurHandlerInfo->pNextHandler;
}
clockqueue.Leave();
return fFoundSelectedItem;
}
//+---------------------------------------------------------------------------
//
// Member: CHndlrQueue::PersistChoices, public
//
// Synopsis: Saves Selected Users choices for the next time
// the choice dialog is brought up. Only should
// be called from a choice queue.
//
// Arguments:
//
// Returns: Appropriate return codes.
//
// Modifies:
//
// History: 17-Nov-97 rogerg Created.
//
//----------------------------------------------------------------------------
STDMETHODIMP CHndlrQueue::PersistChoices(void)
{
LPHANDLERINFO pCurHandlerInfo = NULL;
LPITEMLIST pCurItem = NULL;
CLock clockqueue(this);
if (QUEUETYPE_CHOICE != m_QueueType)
{
Assert(QUEUETYPE_CHOICE == m_QueueType);
return S_FALSE;
}
ASSERT_LOCKNOTHELD(this);
clockqueue.Enter();
// currently only persist on a manual invoke since user
// has to go to settings to change other invoke types and
// that is persisted
// since this is the choice queue we know all handlers have the
// same JobID. if this ever changes, have to set on a case by
// case basis.
if (m_pFirstJobInfo && m_pFirstJobInfo->pConnectionObj &&
(SYNCMGRFLAG_MANUAL == (m_pFirstJobInfo->dwSyncFlags & SYNCMGRFLAG_EVENTMASK)) )
{
TCHAR *pszConnectionName = m_pFirstJobInfo->pConnectionObj[0]->pwszConnectionName;
DWORD dwSyncFlags = m_pFirstJobInfo->dwSyncFlags;
Assert(1 == m_pFirstJobInfo->cbNumConnectionObjs); // assert manual only ever has one connectionObj
// delete all previously stored preferences.
// this is valid because only called from choice queue that all ConnectionNames are the same.
if (!m_fItemsMissing)
{
RegRemoveManualSyncSettings(pszConnectionName);
}
pCurHandlerInfo = m_pFirstHandler;
while (pCurHandlerInfo)
{
// only save if Handler is in the PrepareForSync state.
// bug, need to make sure return code from enum wasn't missing items
if (HANDLERSTATE_PREPAREFORSYNC == pCurHandlerInfo->HandlerState )
{
// save out these items.
pCurItem = pCurHandlerInfo->pFirstItem;
while (pCurItem)
{
if (!pCurItem->fDuplicateItem)
{
switch(dwSyncFlags & SYNCMGRFLAG_EVENTMASK)
{
case SYNCMGRFLAG_MANUAL:
RegSetSyncItemSettings(SYNCTYPE_MANUAL,
pCurHandlerInfo->clsidHandler,
pCurItem->offlineItem.ItemID,
pszConnectionName,
pCurItem->offlineItem.dwItemState,
NULL);
break;
default:
AssertSz(0,"UnknownSyncFlag Event");
break;
};
}
pCurItem = pCurItem->pnextItem;
}
}
pCurHandlerInfo = pCurHandlerInfo->pNextHandler;
}
}
clockqueue.Leave();
return S_OK;
}
//+---------------------------------------------------------------------------
//
// Member: CHndlrQueue::FindFirstHandlerInState, public
//
// Synopsis: Finds the first Handler that matches the specified
// state in the queue.
//
// Arguments: [hndlrState] - Requested handler state.
// [pwHandlerID] - on success filled with HandlerID that was found
//
// Returns: Appropriate return codes.
//
// Modifies:
//
// History: 17-Nov-97 rogerg Created.
//
//----------------------------------------------------------------------------
STDMETHODIMP CHndlrQueue::FindFirstHandlerInState(HANDLERSTATE hndlrState, REFCLSID clsidHandler,
HANDLERINFO **ppHandlerId,CLSID *pMatchHandlerClsid)
{
return FindNextHandlerInState(0, clsidHandler,hndlrState, ppHandlerId, pMatchHandlerClsid);
}
//+---------------------------------------------------------------------------
//
// Member: CHndlrQueue::FindNextHandlerInState, public
//
// Synopsis: Finds next handler after LastHandlerID in the queue that matches
// the requested state. Passing in 0 for the LastHandlerID is the same
// as calling FindFirstHandlerInState
//
// if GUID_NULL is passed in for the clsidHandler the first handler that
// matches the specified state is returned.
//
// Arguments: [wLastHandlerID] - Id of last handler found.
// [clsidHandler] - specific handler classid is requested, only find matches with this clsid
// [hndlrState] - Requested handler state.
// [pwHandlerID] - on success filled with HandlerID that was found
// [pMatchHandlerClsid] - on sucdess clsid of handler found.
//
// Returns: Appropriate return codes.
//
// Modifies:
//
// History: 17-Nov-97 rogerg Created.
//
//----------------------------------------------------------------------------
STDMETHODIMP CHndlrQueue::FindNextHandlerInState(HANDLERINFO *pLastHandlerID,REFCLSID clsidHandler,
HANDLERSTATE hndlrState,HANDLERINFO **ppHandlerID,CLSID *pMatchHandlerClsid)
{
HRESULT hr = S_FALSE;
LPHANDLERINFO pCurHandler;
CLock clockqueue(this);
*ppHandlerID = 0;
clockqueue.Enter();
pCurHandler = m_pFirstHandler;
if (pLastHandlerID)
{
// loop foward until find the last handlerID we checked or hit the end
while (pCurHandler)
{
if (pLastHandlerID == pCurHandler->pHandlerId)
{
break;
}
pCurHandler = pCurHandler->pNextHandler;
}
if (pCurHandler)
{
pCurHandler = pCurHandler->pNextHandler; // increment to next handler.
}
}
while (pCurHandler)
{
if ( (hndlrState == pCurHandler->HandlerState)
&& ((GUID_NULL == clsidHandler) || (clsidHandler == pCurHandler->clsidHandler)) )
{
*ppHandlerID = pCurHandler->pHandlerId;
*pMatchHandlerClsid = pCurHandler->clsidHandler;
hr = S_OK;
break;
}
pCurHandler = pCurHandler->pNextHandler;
}
clockqueue.Leave();
return hr;
}
//+---------------------------------------------------------------------------
//
// Member: CHndlrQueue::CreateServer, public
//
// Synopsis: Creates a new proxy then calls proxy to create and instance of the
// specified handler.
//
// Arguments: [wHandlerId] - Id of handler to call.
// [pCLSIDServer] - CLSID of Handler to Create.
//
// Returns: Appropriate return codes.
//
// Modifies:
//
// History: 17-Nov-97 rogerg Created.
//
//----------------------------------------------------------------------------
STDMETHODIMP CHndlrQueue::CreateServer(HANDLERINFO *pHandlerId, const CLSID *pCLSIDServer)
{
HRESULT hr = E_UNEXPECTED;
LPHANDLERINFO pHandlerInfo = NULL;
CLock clockqueue(this);
ASSERT_LOCKNOTHELD(this);
clockqueue.Enter();
if (S_OK == LookupHandlerFromId(pHandlerId,&pHandlerInfo))
{
Assert(HANDLERSTATE_CREATE == pHandlerInfo->HandlerState);
Assert(0 == pHandlerInfo->dwCallNestCount);
pHandlerInfo->dwCallNestCount++;
if (HANDLERSTATE_CREATE == pHandlerInfo->HandlerState)
{
pHandlerInfo->HandlerState = HANDLERSTATE_INCREATE;
Assert(NULL == pHandlerInfo->pThreadProxy);
// see if there is already a thread for this handler's
// CLSID.
hr = CreateHandlerThread(&(pHandlerInfo->pThreadProxy), m_hwndDlg, *pCLSIDServer);
if (S_OK == hr)
{
HANDLERINFO *pHandlerIdArg;
CThreadMsgProxy *pThreadProxy;
pHandlerIdArg = pHandlerInfo->pHandlerId;
pThreadProxy = pHandlerInfo->pThreadProxy;
clockqueue.Leave();
hr = pThreadProxy->CreateServer(pCLSIDServer,this,pHandlerIdArg);
clockqueue.Enter();
pHandlerInfo->pThreadProxy = pThreadProxy;
}
if (S_OK == hr)
{
pHandlerInfo->clsidHandler = *pCLSIDServer;
pHandlerInfo->HandlerState = HANDLERSTATE_INITIALIZE;
}
else
{
pHandlerInfo->HandlerState = HANDLERSTATE_RELEASE;
}
}
pHandlerInfo->dwCallNestCount--;
}
clockqueue.Leave();
return hr;
}
//+---------------------------------------------------------------------------
//
// Member: CHndlrQueue::Initialize, public
//
// Synopsis: Calls Hanlder's Initialize method
//
// Arguments: [wHandlerId] - Id of handler to call.
// [dwReserved] - Initialize reserved parameter
// [dwSyncFlags] - Sync flags
// [cbCookie] - size of cookie data
// [lpCookie] - ptr to cookie data
//
// Returns: Appropriate return codes.
//
// Modifies:
//
// History: 17-Nov-97 rogerg Created.
//
//----------------------------------------------------------------------------
STDMETHODIMP CHndlrQueue::Initialize(HANDLERINFO *pHandlerId,DWORD dwReserved,DWORD dwSyncFlags,
DWORD cbCookie,const BYTE *lpCooke)
{
HRESULT hr = E_UNEXPECTED;
LPHANDLERINFO pHandlerInfo = NULL;
CLock clockqueue(this);
ASSERT_LOCKNOTHELD(this);
clockqueue.Enter();
if (S_OK == LookupHandlerFromId(pHandlerId, &pHandlerInfo))
{
Assert(HANDLERSTATE_INITIALIZE == pHandlerInfo->HandlerState);
Assert(pHandlerInfo->pThreadProxy);
Assert(0 == pHandlerInfo->dwCallNestCount);
pHandlerInfo->dwCallNestCount++;
if ( (HANDLERSTATE_INITIALIZE == pHandlerInfo->HandlerState) && (pHandlerInfo->pThreadProxy) )
{
CThreadMsgProxy *pThreadProxy;
Assert(dwSyncFlags & SYNCMGRFLAG_EVENTMASK); // an event should be set
pHandlerInfo->HandlerState = HANDLERSTATE_ININITIALIZE;
pThreadProxy = pHandlerInfo->pThreadProxy;
clockqueue.Leave();
hr = pThreadProxy->Initialize(dwReserved,dwSyncFlags,cbCookie,lpCooke);
clockqueue.Enter();
if (S_OK == hr)
{
pHandlerInfo->HandlerState = HANDLERSTATE_ADDHANDLERTEMS;
}
else
{
pHandlerInfo->HandlerState = HANDLERSTATE_RELEASE;
}
}
pHandlerInfo->dwCallNestCount--;
}
clockqueue.Leave();
return hr;
}
//+---------------------------------------------------------------------------
//
// Member: CHndlrQueue::AddHandlerItemsToQueue, public
//
// Synopsis: Calls through to proxy to add items to the queue
//
// Arguments: [wHandlerId] - Id of handler to call.
//
// Returns: Appropriate return codes.
//
// Modifies:
//
// History: 17-Nov-97 rogerg Created.
//
//----------------------------------------------------------------------------
STDMETHODIMP CHndlrQueue::AddHandlerItemsToQueue(HANDLERINFO *pHandlerId,DWORD *pcbNumItems)
{
HRESULT hr = E_UNEXPECTED;
LPHANDLERINFO pHandlerInfo = NULL;
CLock clockqueue(this);
ASSERT_LOCKNOTHELD(this);
clockqueue.Enter();
Assert(pcbNumItems);
Assert(QUEUETYPE_CHOICE == m_QueueType); // items should only be added in a choice queue.
*pcbNumItems = 0;
if (S_OK == LookupHandlerFromId(pHandlerId,&pHandlerInfo))
{
Assert(0 == pHandlerInfo->dwCallNestCount);
pHandlerInfo->dwCallNestCount++;
Assert(HANDLERSTATE_ADDHANDLERTEMS == pHandlerInfo->HandlerState);
Assert(pHandlerInfo->pThreadProxy);
if ( (HANDLERSTATE_ADDHANDLERTEMS == pHandlerInfo->HandlerState) && (pHandlerInfo->pThreadProxy) )
{
CThreadMsgProxy *pThreadProxy;
pHandlerInfo->HandlerState = HANDLERSTATE_INADDHANDLERITEMS;
pThreadProxy = pHandlerInfo->pThreadProxy;
clockqueue.Leave();
// on return all items should be filled in.
hr = pThreadProxy->AddHandlerItems(NULL /* HWND */,pcbNumItems);
clockqueue.Enter();
if ( (S_OK == hr) || (S_SYNCMGR_MISSINGITEMS == hr) )
{
if (S_SYNCMGR_MISSINGITEMS == hr)
m_fItemsMissing = TRUE;
hr = S_OK; // review, need to handler missing items in registry.
pHandlerInfo->HandlerState = HANDLERSTATE_PREPAREFORSYNC;
}
else
{
// on an error, go ahead and release the proxy if server can't enum
pHandlerInfo->HandlerState = HANDLERSTATE_RELEASE;
*pcbNumItems = 0;
}
}
pHandlerInfo->dwCallNestCount--;
}
clockqueue.Leave();
return hr;
}
//+---------------------------------------------------------------------------
//
// Member: CHndlrQueue::GetItemObject, public
//
// Synopsis: Calls through to proxy to get an items object pointer
//
// Arguments: [wHandlerId] - Id of handler to call.
// [wItemID] - ID of item to get the object of.
// [riid] - interface requested of the object
// [ppv] - on success is a pointer to the newly created object
//
// Returns: Currently all handlers should return E_NOTIMPL.
//
// Modifies:
//
// History: 17-Nov-97 rogerg Created.
//
//----------------------------------------------------------------------------
STDMETHODIMP CHndlrQueue::GetItemObject(HANDLERINFO *pHandlerId,WORD wItemID,REFIID riid,void** ppv)
{
HRESULT hr = E_UNEXPECTED;
LPHANDLERINFO pHandlerInfo = NULL;
CLock clockqueue(this);
Assert(QUEUETYPE_PROGRESS == m_QueueType);
ASSERT_LOCKNOTHELD(this);
clockqueue.Enter();
if (S_OK == LookupHandlerFromId(pHandlerId,&pHandlerInfo))
{
LPITEMLIST pCurItem;
Assert(HANDLERSTATE_PREPAREFORSYNC == pHandlerInfo->HandlerState);
Assert(pHandlerInfo->pThreadProxy);
Assert(0 == pHandlerInfo->dwCallNestCount);
pHandlerInfo->dwCallNestCount++;
if ( (HANDLERSTATE_PREPAREFORSYNC == pHandlerInfo->HandlerState) && (pHandlerInfo->pThreadProxy))
{
// now try to find the item.
pCurItem = pHandlerInfo->pFirstItem;
while (pCurItem)
{
if (wItemID == pCurItem->wItemId)
{
CThreadMsgProxy *pThreadProxy;
SYNCMGRITEMID ItemID;
pThreadProxy = pHandlerInfo->pThreadProxy;
ItemID = pCurItem->offlineItem.ItemID;
clockqueue.Leave();
hr = pThreadProxy->GetItemObject(ItemID,riid,ppv);
return hr;
}
pCurItem = pCurItem->pnextItem;
}
}
pHandlerInfo->dwCallNestCount--;
}
clockqueue.Leave();
AssertSz(0, "Specified object wasn't found");
return hr;
}
//+---------------------------------------------------------------------------
//
// Member: CHndlrQueue::SetUpProgressCallback, public
//
// Synopsis: Calls through to proxy to set up the progress callback
//
// Arguments: [wHandlerId] - Id of handler to call.
// [fSet] - TRUE == create, FALSE == destroy.
// [hwnd] - Callback info should be sent to specified window.
//
// Returns: Appropriate Error code
//
// Modifies:
//
// History: 17-Nov-97 rogerg Created.
//
//----------------------------------------------------------------------------
STDMETHODIMP CHndlrQueue::SetUpProgressCallback(HANDLERINFO *pHandlerId,BOOL fSet,HWND hwnd)
{
HRESULT hr = E_UNEXPECTED;
LPHANDLERINFO pHandlerInfo = NULL;
CLock clockqueue(this);
AssertSz(0,"this function no longer used");
return E_NOTIMPL;
}
//+---------------------------------------------------------------------------
//
// Member: CHndlrQueue::PrepareForSync, public
//
// Synopsis: Calls through to Handlers PrepareForSync method.
//
// Arguments: [wHandlerId] - Id of handler to call.
// [hWndParent] - Hwnd to use for any displayed dialogs.
//
// Returns: Appropriate Error code
//
// Modifies:
//
// History: 17-Nov-97 rogerg Created.
//
//----------------------------------------------------------------------------
STDMETHODIMP CHndlrQueue::PrepareForSync(HANDLERINFO *pHandlerId,HWND hWndParent)
{
HRESULT hr = E_UNEXPECTED;
LPHANDLERINFO pHandlerInfo = NULL;
ULONG cbNumItems;
SYNCMGRITEMID *pItemIDs;
BOOL fHandlerCalled = FALSE;
CLock clockqueue(this);
Assert(QUEUETYPE_PROGRESS == m_QueueType);
ASSERT_LOCKNOTHELD(this);
clockqueue.Enter();
if (S_OK == LookupHandlerFromId(pHandlerId,&pHandlerInfo))
{
Assert(HANDLERSTATE_PREPAREFORSYNC == pHandlerInfo->HandlerState);
Assert(pHandlerInfo->pThreadProxy);
Assert(0 == pHandlerInfo->dwCallNestCount);
pHandlerInfo->dwCallNestCount++;
Assert(!(ThreadMsg_PrepareForSync & pHandlerInfo->dwOutCallMessages));
pHandlerInfo->dwOutCallMessages |= ThreadMsg_PrepareForSync;
if (HANDLERSTATE_PREPAREFORSYNC == pHandlerInfo->HandlerState)
{
// if item doesn't have a ThreadProxy or it has been cancelled,
// put in the Release State
if ( (NULL == pHandlerInfo->pThreadProxy) || (pHandlerInfo->fCancelled) )
{
pHandlerInfo->HandlerState = HANDLERSTATE_RELEASE;
}
else
{
// create a list of the selected items and pass to PrepareForSync
cbNumItems = GetSelectedItemsInHandler(pHandlerInfo,0,NULL);
if (0 == cbNumItems)
{
// if no items selected don't call prepareforsync
// and set the HandlerState so it can be released
pHandlerInfo->HandlerState = HANDLERSTATE_RELEASE;
hr = S_FALSE;
}
else
{
pItemIDs = (SYNCMGRITEMID *) ALLOC(sizeof(SYNCMGRITEMID)*cbNumItems);
if (pItemIDs)
{
// loop through items filling in the proper data
GetSelectedItemsInHandler(pHandlerInfo,&cbNumItems,pItemIDs);
if (0 == cbNumItems)
{
hr = S_FALSE; // There are no selected items.
}
else
{
CThreadMsgProxy *pThreadProxy;
JOBINFO *pJobInfo = NULL;
pHandlerInfo->HandlerState = HANDLERSTATE_INPREPAREFORSYNC;
pThreadProxy = pHandlerInfo->pThreadProxy;
pHandlerInfo->hWndCallback = hWndParent;
pJobInfo = pHandlerInfo->pJobInfo;
// if we need to dial to make the connection do
// so now.
clockqueue.Leave();
DWORD dwSyncFlags = pJobInfo->dwSyncFlags & SYNCMGRFLAG_EVENTMASK;
BOOL fAutoDialDisable = TRUE;
if ( dwSyncFlags == SYNCMGRFLAG_MANUAL || dwSyncFlags == SYNCMGRFLAG_INVOKE )
fAutoDialDisable = FALSE;
//
// Ignore failure return from ApplySyncItemDialState
//
ApplySyncItemDialState( fAutoDialDisable );
hr = OpenConnection(pJobInfo);
if (S_OK == hr)
{
// if this is on an idle write out the last
// handler id
// review - if don't wait to call PrepareForSync
// on idle the setlastIdlehandler should be called on sync.
if (pJobInfo && (SYNCMGRFLAG_IDLE == (pJobInfo->dwSyncFlags & SYNCMGRFLAG_EVENTMASK)) )
{
SetLastIdleHandler(pHandlerInfo->clsidHandler);
}
fHandlerCalled = TRUE;
hr = pThreadProxy->PrepareForSync(cbNumItems, pItemIDs,
hWndParent, 0 /* dwReserved */ );
}
else
{
clockqueue.Enter();
pHandlerInfo->hWndCallback = NULL;
clockqueue.Leave();
}
}
// on return from PrepareFroSync or error need to free items
clockqueue.Enter();
FREE(pItemIDs);
}
else
{
hr = E_OUTOFMEMORY;
}
}
}
}
}
clockqueue.Leave();
// if the handler returns an errorfrom PrepareForSync we need
// to call the completion routine ourselves and/or we never got to the point
// of making the outcall.
if ( (fHandlerCalled && (S_OK != hr)) || (!fHandlerCalled))
{
CallCompletionRoutine(pHandlerId,ThreadMsg_PrepareForSync,hr,0,NULL);
}
return hr;
}
//+---------------------------------------------------------------------------
//
// Member: CHndlrQueue::PrepareForSyncCompleted, public
//
// Synopsis: Called by completion routine on a PrepareForSyncCompleted
//
// Warning: Assume queue is locked and pHandlerInfo has
// already been verified.
//
// Returns: Appropriate Error code
//
// Modifies:
//
// History: 02-Jun-98 rogerg Created.
//
//----------------------------------------------------------------------------
STDMETHODIMP CHndlrQueue::PrepareForSyncCompleted(LPHANDLERINFO pHandlerInfo,HRESULT hCallResult)
{
ASSERT_LOCKHELD(this); // caller of this function should have already locked the queue.
if (S_OK == hCallResult)
{
pHandlerInfo->HandlerState = HANDLERSTATE_SYNCHRONIZE;
}
else
{
pHandlerInfo->HandlerState = HANDLERSTATE_RELEASE;
}
if ( (pHandlerInfo->HandlerState != HANDLERSTATE_SYNCHRONIZE))
{
// if handler didn't make it to the synchronize state then fix up the items
LPITEMLIST pCurItem = NULL;
// prepare for sync either doesn't want to handle the
// items or an error occured,
// need to go ahead and mark the items as completed.
// same routine that is after synchronize.
pCurItem = pHandlerInfo->pFirstItem;
while (pCurItem)
{
SetItemProgressValues(pCurItem,
HNDRLQUEUE_DEFAULT_PROGRESS_MAXVALUE,
HNDRLQUEUE_DEFAULT_PROGRESS_MAXVALUE);
pCurItem->fSynchronizingItem = FALSE;
pCurItem = pCurItem->pnextItem;
}
}
pHandlerInfo->dwCallNestCount--; // decrement nestcount put on by PrepareForSync call.
// if the handler state has been released but it has some jumptext, which it can if
// the PrepareForsync was caused by a retry then set the results to HANDLERSTATE_HASERRORJUMPS
if ((HANDLERSTATE_RELEASE == pHandlerInfo->HandlerState) && (pHandlerInfo->fHasErrorJumps))
{
pHandlerInfo->HandlerState = HANDLERSTATE_HASERRORJUMPS;
}
return S_OK;
}
//+---------------------------------------------------------------------------
//
// Member: CHndlrQueue::Synchronize, public
//
// Synopsis: Calls through to Handlers Synchronize method.
//
// Arguments: [wHandlerId] - Id of handler to call.
// [hWndParent] - Hwnd to use for any displayed dialogs.
//
// Returns: Appropriate Error code
//
// Modifies:
//
// History: 17-Nov-97 rogerg Created.
//
//----------------------------------------------------------------------------
STDMETHODIMP CHndlrQueue::Synchronize(HANDLERINFO *pHandlerId,HWND hWndParent)
{
HRESULT hr = E_UNEXPECTED;
LPHANDLERINFO pHandlerInfo = NULL;
BOOL fHandlerCalled = FALSE;
CLock clockqueue(this);
Assert(QUEUETYPE_PROGRESS == m_QueueType);
ASSERT_LOCKNOTHELD(this);
clockqueue.Enter();
if (S_OK == LookupHandlerFromId(pHandlerId,&pHandlerInfo))
{
Assert(HANDLERSTATE_SYNCHRONIZE == pHandlerInfo->HandlerState);
Assert(pHandlerInfo->pThreadProxy);
Assert(0 == pHandlerInfo->dwCallNestCount);
pHandlerInfo->dwCallNestCount++;
Assert(!(ThreadMsg_Synchronize & pHandlerInfo->dwOutCallMessages));
pHandlerInfo->dwOutCallMessages |= ThreadMsg_Synchronize;
if ( (HANDLERSTATE_SYNCHRONIZE == pHandlerInfo->HandlerState) && (pHandlerInfo->pThreadProxy) )
{
// make sure the handler has a proxy and the item
// wasn't cancelled.
if ( (NULL == pHandlerInfo->pThreadProxy) || (pHandlerInfo->fCancelled))
{
pHandlerInfo->HandlerState = HANDLERSTATE_RELEASE;
}
else
{
CThreadMsgProxy *pThreadProxy;
pHandlerInfo->HandlerState = HANDLERSTATE_INSYNCHRONIZE;
pThreadProxy= pHandlerInfo->pThreadProxy;
clockqueue.Leave();
fHandlerCalled = TRUE;
hr = pThreadProxy->Synchronize(hWndParent);
clockqueue.Enter();
}
}
}
clockqueue.Leave();
// if the handler returns an error from Synchronize we need
// to call the completion routine ourselves and/or we never got to the point
// of making the outcall.
if ( (fHandlerCalled && (S_OK != hr)) || (!fHandlerCalled) )
{
CallCompletionRoutine(pHandlerId,ThreadMsg_Synchronize,hr,0,NULL);
}
return hr;
}
//+---------------------------------------------------------------------------
//
// Member: CHndlrQueue::SynchronizeCompleted, public
//
// Synopsis: Called by completion routine on a SynchronizeCompleted
//
// Warning: Assume queue is locked and pHandlerInfo has
// already been verified.
//
// Returns: Appropriate Error code
//
// Modifies:
//
// History: 02-Jun-98 rogerg Created.
//
//----------------------------------------------------------------------------
STDMETHODIMP CHndlrQueue::SynchronizeCompleted(LPHANDLERINFO pHandlerInfo,HRESULT hCallResult)
{
LPITEMLIST pCurItem = NULL;
BOOL fRetrySync = FALSE;
ASSERT_LOCKHELD(this); // caller of this function should have already locked the queue.
if (pHandlerInfo->fRetrySync)
{
// if a retry request came in during the sync, retry it.
pHandlerInfo->HandlerState = HANDLERSTATE_PREPAREFORSYNC;
pHandlerInfo->fRetrySync = FALSE; // reset the retry sync flag.
fRetrySync = TRUE;
}
else if (pHandlerInfo->fHasErrorJumps)
{
pHandlerInfo->HandlerState = HANDLERSTATE_HASERRORJUMPS;
}
else
{
pHandlerInfo->HandlerState = HANDLERSTATE_RELEASE;
}
// when come out of synchronize we set the items values for them.
// in case they were negligent.
pCurItem = pHandlerInfo->pFirstItem;
while (pCurItem)
{
SetItemProgressValues(pCurItem,
HNDRLQUEUE_DEFAULT_PROGRESS_MAXVALUE,
HNDRLQUEUE_DEFAULT_PROGRESS_MAXVALUE);
pCurItem->fSynchronizingItem = FALSE;
pCurItem = pCurItem->pnextItem;
}
pHandlerInfo->dwCallNestCount--; // remove nest count
// if the handler state has been released but it has some jumptext, which it can if
// the sycnrhonize was caused by a retry then set the results to HANDLERSTATE_HASERRORJUMPS
if ((HANDLERSTATE_RELEASE == pHandlerInfo->HandlerState) && (pHandlerInfo->fHasErrorJumps))
{
pHandlerInfo->HandlerState = HANDLERSTATE_HASERRORJUMPS;
}
return S_OK;
}
//+---------------------------------------------------------------------------
//
// Member: CHndlrQueue::ShowError, public
//
// Synopsis: Calls through to Handlers ShowError method.
//
// Arguments: [wHandlerId] - Id of handler to call.
// [hWndParent] - Hwnd to use for any displayed dialogs.
// [dwErrorID] - Identifies the error to show
//
// Returns: Appropriate Error code
//
// Modifies:
//
// History: 17-Nov-97 rogerg Created.
//
//----------------------------------------------------------------------------
STDMETHODIMP CHndlrQueue::ShowError(HANDLERINFO *pHandlerId,HWND hWndParent,REFSYNCMGRERRORID ErrorID)
{
HRESULT hr = E_UNEXPECTED;
LPHANDLERINFO pHandlerInfo = NULL;
BOOL fHandlerCalled = FALSE;
BOOL fAlreadyInShowErrors = TRUE;
CLock clockqueue(this);
Assert(QUEUETYPE_PROGRESS == m_QueueType);
clockqueue.Enter();
if (S_OK == LookupHandlerFromId(pHandlerId,&pHandlerInfo))
{
Assert(pHandlerInfo->fHasErrorJumps);
Assert(pHandlerInfo->pThreadProxy);
// if we are already handling a ShowError for this handler then don't
// start another one
if (!(pHandlerInfo->fInShowErrorCall))
{
fAlreadyInShowErrors = FALSE;
m_dwShowErrororOutCallCount++; // increment handlers ShowError OutCall Count.
Assert(!(ThreadMsg_ShowError & pHandlerInfo->dwOutCallMessages));
pHandlerInfo->dwOutCallMessages |= ThreadMsg_ShowError;
if (pHandlerInfo->pThreadProxy )
{
CThreadMsgProxy *pThreadProxy;
ULONG cbNumItems = 0; // review, these are not longer necessary.
SYNCMGRITEMID *pItemIDs = NULL;
pThreadProxy = pHandlerInfo->pThreadProxy;
fHandlerCalled = TRUE;
pHandlerInfo->fInShowErrorCall = TRUE;
clockqueue.Leave();
hr = pThreadProxy->ShowError(hWndParent,ErrorID,&cbNumItems,&pItemIDs);
clockqueue.Enter();
}
}
}
clockqueue.Leave();
// if the handler returns an error from ShowError we need
// to call the completion routine ourselves and/or we never got to the point
// of making the outcall and there wasn't already an outcall in progress.
if ( (fHandlerCalled && (S_OK != hr)) || (!fHandlerCalled && !fAlreadyInShowErrors) )
{
CallCompletionRoutine(pHandlerId,ThreadMsg_ShowError,hr,0,NULL);
}
return hr;
}
//+---------------------------------------------------------------------------
//
// Member: CHndlrQueue::ShowErrorCompleted, public
//
// Synopsis: Called by completion routine on a ShowErrorCompleted
//
// Warning: Assume queue is locked and pHandlerInfo has
// already been verified.
//
// Returns:
//
// Modifies:
//
// History: 02-Jun-98 rogerg Created.
//
//----------------------------------------------------------------------------
STDMETHODIMP CHndlrQueue::ShowErrorCompleted(LPHANDLERINFO pHandlerInfo,HRESULT hCallResult,
ULONG cbNumItems,SYNCMGRITEMID *pItemIDs)
{
ASSERT_LOCKHELD(this); // caller of this function should have already locked the queue.
if (S_SYNCMGR_RETRYSYNC == hCallResult)
{
// validate we got something back for cbNumItems and pItemIDs or
// don't do anything
if ( (0 == cbNumItems) || (NULL == pItemIDs))
{
Assert(cbNumItems); // assert in debug so can catch handlers.
Assert(pItemIDs);
}
else
{
SYNCMGRITEMID *pCurItemItemId;
ULONG cbNumItemsIndex;
// if the handler is in the release state then change to prepareForSync
// if it is still in a synchronize just set the fRetrySync flag in the
// handler for it to check when done.
// Cases
// Handlers PrepareForSync Method hasn't been called. Just add items to request
// Handlers is between InPrepareForSync and InSynchronize. Set RetrySyncFlag
// Handler has is done with it synchronize. reset state to PrepareForSync
// when prepareforsync is called on an item it state gets set back to unchecked
// so just need to worry about setting appropriate items to checked.
pCurItemItemId = pItemIDs;
for (cbNumItemsIndex = 0 ; cbNumItemsIndex < cbNumItems; cbNumItemsIndex++)
{
BOOL fFoundMatch = FALSE;
LPITEMLIST pHandlerItem;
pHandlerItem = pHandlerInfo->pFirstItem;
while (pHandlerItem)
{
if (*pCurItemItemId == pHandlerItem->offlineItem.ItemID)
{
pHandlerItem->offlineItem.dwItemState = SYNCMGRITEMSTATE_CHECKED;
SetItemProgressValues(pHandlerItem,0,
HNDRLQUEUE_DEFAULT_PROGRESS_MAXVALUE);
pHandlerItem->fIncludeInProgressBar = TRUE;
fFoundMatch = TRUE;
break;
}
pHandlerItem = pHandlerItem->pnextItem;
}
if (!fFoundMatch)
{
LPITEMLIST pNewItem;
SYNCMGRITEM syncItem;
// if didn't find a match this must be a new item, add it to the list
// and set up the appropriate states.
// Note: items added like this should not be included in the progress bar.
// first time progress is called on an item it will get included
// in the progress bar.
syncItem.cbSize = sizeof(SYNCMGRITEM);
syncItem.dwFlags = SYNCMGRITEM_TEMPORARY;
syncItem.ItemID = *pCurItemItemId;
syncItem.dwItemState = SYNCMGRITEMSTATE_CHECKED;
syncItem.hIcon = NULL;
*syncItem.wszItemName = L'\0';
pNewItem = AllocNewHandlerItem(pHandlerInfo,&syncItem);
if (pNewItem)
{
pNewItem->offlineItem.dwItemState = SYNCMGRITEMSTATE_CHECKED;
SetItemProgressValues(pNewItem,
HNDRLQUEUE_DEFAULT_PROGRESS_MAXVALUE,
HNDRLQUEUE_DEFAULT_PROGRESS_MAXVALUE);
pNewItem->fHiddenItem = TRUE; // set to indicate not part of UI.
pNewItem->fIncludeInProgressBar = FALSE;
}
}
++pCurItemItemId;
}
if (pHandlerInfo->HandlerState < HANDLERSTATE_INPREPAREFORSYNC)
{
// don't reset anything. just make sure requested items are added
// to the request.
}
else if (pHandlerInfo->HandlerState > HANDLERSTATE_INSYNCHRONIZE)
{
// if synchronize is complete reset the state to PrepareForSync.
pHandlerInfo->HandlerState = HANDLERSTATE_PREPAREFORSYNC;
}
else
{
// retry request came in between the PrepareForSync call and Synchronize
// being complete.
Assert(pHandlerInfo->HandlerState >= HANDLERSTATE_INPREPAREFORSYNC);
Assert(pHandlerInfo->HandlerState < HANDLERSTATE_DEAD);
pHandlerInfo->fRetrySync = TRUE;
}
//
// If the handler has been canceled, uncancel it to enable the retry
//
pHandlerInfo->fCancelled = FALSE;
}
}
--m_dwShowErrororOutCallCount; // decrement handlers ShowError OutCall Count.
// should never happen but in case out call goes negative fixup to zero.
Assert( ((LONG) m_dwShowErrororOutCallCount) >= 0);
if ( ((LONG) m_dwShowErrororOutCallCount) < 0)
{
m_dwShowErrororOutCallCount = 0;
}
pHandlerInfo->fInShowErrorCall = FALSE; // handler is no longer in a ShowError Call
return S_OK;
}
//+---------------------------------------------------------------------------
//
// Member: CHndlrQueue::FindItemData, private
//
// Synopsis: finds associated handler and item info. caller must be
// holding the lock and access the returned info before
// releasing the lock
//
// !! Only matches items that have a state between or equal
// to the handler state ranges.
//
// !!! If ItemID of GUID_NULL is passed it it returns a match
// of the first handler found and sets pItem out param to NULL
//
// Arguments:
//
// Returns: Appropriate return codes
//
// Modifies:
//
// History: 17-Nov-97 rogerg Created.
//
//----------------------------------------------------------------------------
STDMETHODIMP CHndlrQueue::FindItemData(CLSID clsidHandler,REFSYNCMGRITEMID OfflineItemID,
HANDLERSTATE hndlrStateFirst,HANDLERSTATE hndlrStateLast,
LPHANDLERINFO *ppHandlerInfo,LPITEMLIST *ppItem)
{
LPHANDLERINFO pCurHandlerInfo = NULL;
LPITEMLIST pCurItem = NULL;
BOOL fNoMatchFound = TRUE;
HRESULT hr = S_FALSE;
ASSERT_LOCKHELD(this);
Assert(ppHandlerInfo);
Assert(ppItem);
*ppHandlerInfo = NULL;
*ppItem = NULL;
pCurHandlerInfo = m_pFirstHandler;
while (pCurHandlerInfo && fNoMatchFound)
{
if ( (clsidHandler == pCurHandlerInfo->clsidHandler)
&& (hndlrStateLast >= pCurHandlerInfo->HandlerState)
&& (hndlrStateFirst <= pCurHandlerInfo->HandlerState) )
{
*ppHandlerInfo = pCurHandlerInfo;
// if top level item tem ppItem to NULL and return okay
if (GUID_NULL == OfflineItemID)
{
*ppItem = NULL;
hr = S_OK;
fNoMatchFound = FALSE;
}
else
{
pCurItem = pCurHandlerInfo->pFirstItem;
while (pCurItem)
{
if (OfflineItemID == pCurItem->offlineItem.ItemID)
{
*ppItem = pCurItem;
hr = S_OK;
fNoMatchFound = FALSE;
break;
}
pCurItem = pCurItem->pnextItem;
}
}
}
pCurHandlerInfo = pCurHandlerInfo->pNextHandler;
}
return hr;
}
//+---------------------------------------------------------------------------
//
// Member: CHndlrQueue::LookupHandlerFromId, private
//
// Synopsis: Finds associate handler info from the given Id
//
// Arguments: [wHandlerId] - Id of handler to call.
// [pHandlerInfo] - on S_OK pointer to handler info
//
// Returns: Appropriate Error code
//
// Modifies:
//
// History: 17-Nov-97 rogerg Created.
//
//----------------------------------------------------------------------------
STDMETHODIMP CHndlrQueue::LookupHandlerFromId(HANDLERINFO *pHandlerId,LPHANDLERINFO *pHandlerInfo)
{
HRESULT hr = E_UNEXPECTED;
LPHANDLERINFO pCurItem;
ASSERT_LOCKHELD(this); // caller of this function should have already locked the queue.
*pHandlerInfo = NULL;
pCurItem = m_pFirstHandler;
while (pCurItem)
{
if (pHandlerId == pCurItem->pHandlerId )
{
*pHandlerInfo = pCurItem;
Assert(pCurItem == pHandlerId);
hr = S_OK;
break;
}
pCurItem = pCurItem->pNextHandler;
}
Assert(S_OK == hr); // test assert to see if ever fires.
return hr;
}
//+---------------------------------------------------------------------------
//
// Member: CHndlrQueue::AllocNewHandlerItem, public
//
// Synopsis: Adds new item to the specified handler.
//
// Arguments: [wHandlerId] - Id of handler.
// [pOfflineItem] - Points to Items information to add.
//
// Returns: Appropriate Error code
//
// Modifies:
//
// History: 13-May-98 rogerg Created.
//
//----------------------------------------------------------------------------
LPITEMLIST CHndlrQueue::AllocNewHandlerItem(LPHANDLERINFO pHandlerInfo,SYNCMGRITEM *pOfflineItem)
{
LPITEMLIST pNewItem = NULL;
ASSERT_LOCKHELD(this); // caller of this function should have already locked the queue.
Assert(pHandlerInfo);
Assert(pOfflineItem);
// Allocate the item.
pNewItem = (LPITEMLIST) ALLOC(sizeof(ITEMLIST));
if (pNewItem)
{
// set up defaults.
memset(pNewItem, 0, sizeof(ITEMLIST));
pNewItem->wItemId = ++pHandlerInfo->wItemCount;
pNewItem->pHandlerInfo = pHandlerInfo;
pNewItem->fDuplicateItem = FALSE;
pNewItem->fIncludeInProgressBar = FALSE;
SetItemProgressValues(pNewItem, 0, HNDRLQUEUE_DEFAULT_PROGRESS_MAXVALUE);
pNewItem->dwStatusType = SYNCMGRSTATUS_PENDING;
pNewItem->fHiddenItem = FALSE;
pNewItem->fSynchronizingItem = FALSE;
pNewItem->offlineItem = *pOfflineItem;
// stick the item on the end of the list
if (NULL == pHandlerInfo->pFirstItem)
{
pHandlerInfo->pFirstItem = pNewItem;
Assert(1 == pHandlerInfo->wItemCount);
}
else
{
LPITEMLIST pCurItem;
pCurItem = pHandlerInfo->pFirstItem;
while (pCurItem->pnextItem)
pCurItem = pCurItem->pnextItem;
pCurItem->pnextItem = pNewItem;
Assert ((pCurItem->wItemId + 1) == pNewItem->wItemId);
}
}
return pNewItem;
}
//+---------------------------------------------------------------------------
//
// Member: CHndlrQueue::SetHandlerInfo, public
//
// Synopsis: Adds item to the specified handler.
// Called in context of the handlers thread.
//
// Arguments: [pHandlerId] - Id of handler.
// [pSyncMgrHandlerInfo] - Points to SyncMgrHandlerInfo to be filled in.
//
// Returns: Appropriate Error code
//
// Modifies:
//
// History: 28-Jul-98 rogerg Created.
//
//----------------------------------------------------------------------------
STDMETHODIMP CHndlrQueue::SetHandlerInfo(HANDLERINFO *pHandlerId,LPSYNCMGRHANDLERINFO pSyncMgrHandlerInfo)
{
HRESULT hr = E_UNEXPECTED;
LPHANDLERINFO pHandlerInfo = NULL;
CLock clockqueue(this);
if (!pSyncMgrHandlerInfo)
{
Assert(pSyncMgrHandlerInfo);
return E_INVALIDARG;
}
clockqueue.Enter();
Assert(m_QueueType == QUEUETYPE_CHOICE);
if (S_OK == LookupHandlerFromId(pHandlerId,&pHandlerInfo))
{
if (HANDLERSTATE_INADDHANDLERITEMS != pHandlerInfo->HandlerState)
{
Assert(HANDLERSTATE_INADDHANDLERITEMS == pHandlerInfo->HandlerState);
hr = E_UNEXPECTED;
}
else
{
// Quick Check of Size here. other paramters should already
// be validated by hndlrmsg
if (pSyncMgrHandlerInfo->cbSize != sizeof(SYNCMGRHANDLERINFO) )
{
Assert(pSyncMgrHandlerInfo->cbSize == sizeof(SYNCMGRHANDLERINFO));
hr = E_INVALIDARG;
}
else
{
pHandlerInfo->SyncMgrHandlerInfo = *pSyncMgrHandlerInfo;
hr = S_OK;
}
}
}
clockqueue.Leave();
return hr;
}
//+---------------------------------------------------------------------------
//
// Member: CHndlrQueue::IsAllHandlerInstancesCancelCompleted, private
//
// Synopsis: Asks queue if all interintances of a Handler CLSID
// are completed, Called in proxy terminate to see
// if after requesting user input there are still items to
// kill.
//
// Note: Only checks instances for this queue.
//
// Arguments:
//
// Returns: S_OK; if all handler instances are done.
// S_FALSE - if still items going that should be killed.
//
// Modifies:
//
// History: 17-Nov-97 rogerg Created.
//
//----------------------------------------------------------------------------
STDMETHODIMP CHndlrQueue::IsAllHandlerInstancesCancelCompleted(REFCLSID clsidHandler)
{
HRESULT hr = S_OK;
LPHANDLERINFO pCurHandlerInfo;
CLock clockqueue(this);
// just loop through handlers matching clsid and if any are <= SynchronizeCompleted
// and the cancelled flag set then an instance of the Handler is still
// stuck in a Cancel.
Assert(m_QueueType == QUEUETYPE_PROGRESS);
clockqueue.Enter();
pCurHandlerInfo = m_pFirstHandler;
while (pCurHandlerInfo)
{
if ( (clsidHandler == pCurHandlerInfo->clsidHandler) && (BAD_HANDLERSTATE(pCurHandlerInfo) )
&& (pCurHandlerInfo->fCancelled) )
{
hr = S_FALSE;
break;
}
pCurHandlerInfo = pCurHandlerInfo->pNextHandler;
}
clockqueue.Leave();
return hr;
}
//+---------------------------------------------------------------------------
//
// Member: CHndlrQueue::AddItemToHandler, public
//
// Synopsis: Adds item to the specified handler.
// Called in context of the handlers thread.
//
// Arguments: [wHandlerId] - Id of handler.
// [pOfflineItem] - Points to Items information to add.
//
// Returns: Appropriate Error code
//
// Modifies:
//
// History: 17-Nov-97 rogerg Created.
//
//----------------------------------------------------------------------------
STDMETHODIMP CHndlrQueue::AddItemToHandler(HANDLERINFO *pHandlerId,SYNCMGRITEM *pOfflineItem)
{
HRESULT hr = E_UNEXPECTED; // review for Lookup failures
LPHANDLERINFO pHandlerInfo = NULL;
LPITEMLIST pNewItem = NULL;
LPHANDLERINFO pHandlerMatched;
LPITEMLIST pItemListMatch;
CLock clockqueue(this);
clockqueue.Enter();
Assert(m_QueueType == QUEUETYPE_CHOICE);
if (S_OK == LookupHandlerFromId(pHandlerId,&pHandlerInfo))
{
if (HANDLERSTATE_INADDHANDLERITEMS != pHandlerInfo->HandlerState)
{
Assert(HANDLERSTATE_INADDHANDLERITEMS == pHandlerInfo->HandlerState);
hr = E_UNEXPECTED;
}
else
{
// make sure the handler has a jobID and ConnectionObj
// associated with it.
Assert(pHandlerInfo->pJobInfo);
Assert(pHandlerInfo->pJobInfo->pConnectionObj);
if (pHandlerInfo->pJobInfo && pHandlerInfo->pJobInfo->pConnectionObj)
{
DWORD dwSyncFlags = pHandlerInfo->pJobInfo->dwSyncFlags;
// Allocate the item.
pNewItem = AllocNewHandlerItem(pHandlerInfo,pOfflineItem);
if (NULL == pNewItem)
{
hr = E_OUTOFMEMORY;
}
else
{
DWORD dwCheckState;
DWORD dwDefaultCheck; // what default for the item should be.
DWORD ConnectionIndex;
DWORD dwSyncEvent = dwSyncFlags & SYNCMGRFLAG_EVENTMASK;
// if SyncType is SYNCMGRFLAG_CONNECT, SYNCMGRFLAG_PENDINGDISCONNECT
// or Idle, set the defaults based on registration flags
// If change this logic need to also change logic in dll hndlrq.
dwDefaultCheck = pOfflineItem->dwItemState;
if (
( (dwSyncEvent == SYNCMGRFLAG_IDLE) && !(pHandlerInfo->dwRegistrationFlags & SYNCMGRREGISTERFLAG_IDLE) )
|| ( (dwSyncEvent == SYNCMGRFLAG_CONNECT) && !(pHandlerInfo->dwRegistrationFlags & SYNCMGRREGISTERFLAG_CONNECT) )
|| ( (dwSyncEvent == SYNCMGRFLAG_PENDINGDISCONNECT) && !(pHandlerInfo->dwRegistrationFlags & SYNCMGRREGISTERFLAG_PENDINGDISCONNECT) )
)
{
dwDefaultCheck = SYNCMGRITEMSTATE_UNCHECKED;
}
// get appropriate stored setting based on the sync flags
// invoke we just use whatever the handler tells us it should be.
if (SYNCMGRFLAG_INVOKE != dwSyncEvent)
{
for (ConnectionIndex = 0; ConnectionIndex <
pHandlerInfo->pJobInfo->cbNumConnectionObjs;
++ConnectionIndex)
{
TCHAR *pszConnectionName =
pHandlerInfo->pJobInfo->pConnectionObj[ConnectionIndex]->pwszConnectionName;
switch(dwSyncEvent)
{
case SYNCMGRFLAG_MANUAL:
// only support one connection for manual
Assert(pHandlerInfo->pJobInfo->cbNumConnectionObjs == 1);
if (RegGetSyncItemSettings(SYNCTYPE_MANUAL,
pHandlerInfo->clsidHandler,
pOfflineItem->ItemID,
pszConnectionName,&dwCheckState,
dwDefaultCheck,
NULL))
{
pNewItem->offlineItem.dwItemState = dwCheckState;
}
break;
case SYNCMGRFLAG_CONNECT:
case SYNCMGRFLAG_PENDINGDISCONNECT:
if (RegGetSyncItemSettings(SYNCTYPE_AUTOSYNC,
pHandlerInfo->clsidHandler,
pOfflineItem->ItemID,
pszConnectionName,&dwCheckState,
dwDefaultCheck,
NULL))
{
// for logon/logoff a checkstate of set wins and
// as soon as it is set break out of the loop
if ( (0 == ConnectionIndex) ||
(SYNCMGRITEMSTATE_CHECKED == dwCheckState) )
{
pNewItem->offlineItem.dwItemState = dwCheckState;
}
if (SYNCMGRITEMSTATE_CHECKED == pNewItem->offlineItem.dwItemState)
{
break;
}
}
break;
case SYNCMGRFLAG_IDLE:
if (RegGetSyncItemSettings(SYNCTYPE_IDLE,
pHandlerInfo->clsidHandler,
pOfflineItem->ItemID,
pszConnectionName,&dwCheckState,
dwDefaultCheck,
NULL))
{
// for Idle a checkstate of set wins and
// as soon as it is set break out of the loop
if ( (0 == ConnectionIndex) ||
(SYNCMGRITEMSTATE_CHECKED == dwCheckState))
{
pNewItem->offlineItem.dwItemState = dwCheckState;
}
if (SYNCMGRITEMSTATE_CHECKED ==pNewItem->offlineItem.dwItemState)
{
break;
}
}
break;
case SYNCMGRFLAG_SCHEDULED: // if caused by an invoke, use whatever handler tells us.
// only support one connection for schedule
Assert(pHandlerInfo->pJobInfo->cbNumConnectionObjs == 1);
if (pHandlerInfo->pJobInfo)
{
if (RegGetSyncItemSettings(SYNCTYPE_SCHEDULED,
pHandlerInfo->clsidHandler,
pOfflineItem->ItemID,
pszConnectionName,
&dwCheckState,
SYNCMGRITEMSTATE_UNCHECKED, // if don't find item, don't check
pHandlerInfo->pJobInfo->szScheduleName))
{
pNewItem->offlineItem.dwItemState = dwCheckState;
}
else
{
// If don't find then default is to be unchecked.
pNewItem->offlineItem.dwItemState = SYNCMGRITEMSTATE_UNCHECKED;
}
}
break;
case SYNCMGRFLAG_INVOKE: // if caused by an invoke, use whatever handler tells us.
break;
default:
AssertSz(0, "UnknownSyncFlag Event");
break;
};
}
}
// Search and mark duplicate entries.
if (IsItemAlreadyInList(pHandlerInfo->clsidHandler,
(pOfflineItem->ItemID),pHandlerInfo->pHandlerId,
&pHandlerMatched,&pItemListMatch) )
{
Assert(QUEUETYPE_CHOICE == m_QueueType || QUEUETYPE_PROGRESS == m_QueueType);
pNewItem->fDuplicateItem = TRUE;
// duplicate handling
// if a manual sync then first writer to the queue wins,
if (QUEUETYPE_CHOICE == m_QueueType)
{
pNewItem->offlineItem.dwItemState = SYNCMGRITEMSTATE_UNCHECKED;
}
}
hr = S_OK;
}
}
}
}
clockqueue.Leave();
return hr;
}
//+---------------------------------------------------------------------------
//
// Member: CHndlrQueue::Progress, public
//
// Synopsis: Updates items progress information
// Called in the context of the Handlers thread
//
// Arguments: [wHandlerId] - Id of handler.
// [ItemID] - OfflineItemID of the specified item.
// [lpSyncProgressItem] - Pointer to SyncProgressItem.
//
// Returns: Appropriate Error code
//
// Modifies:
//
// History: 17-Nov-97 rogerg Created.
//
//----------------------------------------------------------------------------
STDMETHODIMP CHndlrQueue::Progress(HANDLERINFO *pHandlerId,REFSYNCMGRITEMID ItemID,
LPSYNCMGRPROGRESSITEM lpSyncProgressItem)
{
HRESULT hr = E_UNEXPECTED;
LPHANDLERINFO pHandlerInfo = NULL;
LPITEMLIST pCurItem = NULL;
BOOL fFoundMatch = FALSE;
PROGRESSUPDATEDATA progressData;
HWND hwndCallback;
CLock clockqueue(this);
progressData.pHandlerID = pHandlerId;
progressData.ItemID = ItemID;
Assert(QUEUETYPE_PROGRESS == m_QueueType);
clockqueue.Enter();
if (S_OK == LookupHandlerFromId(pHandlerId,&pHandlerInfo))
{
pCurItem = pHandlerInfo->pFirstItem;
while (pCurItem)
{
if (ItemID == pCurItem->offlineItem.ItemID)
{
fFoundMatch = TRUE;
break;
}
pCurItem = pCurItem->pnextItem;
}
if (pHandlerInfo->fCancelled)
hr = S_SYNCMGR_CANCELALL;
else if (!fFoundMatch || pCurItem->fItemCancelled)
{
Assert(fFoundMatch);
hr = S_SYNCMGR_CANCELITEM;
}
else
hr = S_OK;
}
if (fFoundMatch) // store everyting in local vars.
{
// if found match but shouldn't include in progress bar
// fix it up.
if ( (pCurItem->fHiddenItem) || (FALSE == pCurItem->fIncludeInProgressBar))
{
// if found a match it should be included in the progress bar
// Assert(TRUE == pCurItem->fIncludeInProgressBar); // Review if test app hits this.
Assert(FALSE == pCurItem->fHiddenItem); // shouldn't get progress on hidden items.
fFoundMatch = FALSE;
if (S_OK == hr)
{
hr = S_SYNCMGR_CANCELITEM; // return cancel item just as if item wasn't cancelled.
}
}
else
{
progressData.clsidHandler = pHandlerInfo->clsidHandler;
progressData.wItemId = pCurItem->wItemId;
hwndCallback = pHandlerInfo->hWndCallback;
}
}
clockqueue.Leave();
if (fFoundMatch)
{
// send off data to the callback window.
// it is responsible for updating the items progress values.
if (hwndCallback)
{
// validate the ProgressItem structure before passing it on.
if (IsValidSyncProgressItem(lpSyncProgressItem))
{
SendMessage(hwndCallback,WM_PROGRESS_UPDATE,
(WPARAM) &progressData,(LPARAM) lpSyncProgressItem);
}
else
{
if (S_OK == hr) // CANCEL RESULTS OVERRIDE ARG PROBLEMS
{
hr = E_INVALIDARG;
}
}
}
}
return hr;
}
//+---------------------------------------------------------------------------
//
// Member: CHndlrQueue::LogError, public
//
// Synopsis: Logs and error for the specified item
// Called in the context of the Handlers thread
//
// Arguments: [wHandlerId] - Id of handler.
// [dwErrorLevel] - ErrorLevel of the Error
// [lpcErrorText] - Text of the Error.
// [lpSyncLogError] - Pointer to SyncLogError structure
//
// Returns: Appropriate Error code
//
// Modifies:
//
// History: 17-Nov-97 rogerg Created.
//
//----------------------------------------------------------------------------
STDMETHODIMP CHndlrQueue::LogError(HANDLERINFO *pHandlerId,DWORD dwErrorLevel,
const WCHAR *lpcErrorText, LPSYNCMGRLOGERRORINFO lpSyncLogError)
{
HRESULT hr = E_UNEXPECTED;
LPHANDLERINFO pHandlerInfo = NULL;
LPITEMLIST pCurItem = NULL;
BOOL fFoundMatch = FALSE;
MSGLogErrors msgLogErrors;
HWND hWndCallback = NULL;
CLock clockqueue(this);
msgLogErrors.dwErrorLevel = dwErrorLevel;
msgLogErrors.lpcErrorText = lpcErrorText;
msgLogErrors.ErrorID = GUID_NULL;
msgLogErrors.fHasErrorJumps = FALSE;
msgLogErrors.mask = 0;
Assert(QUEUETYPE_PROGRESS == m_QueueType);
clockqueue.Enter();
if (S_OK == LookupHandlerFromId(pHandlerId,&pHandlerInfo))
{
hWndCallback = pHandlerInfo->hWndCallback;
// validate the paramaters.
if (NULL == hWndCallback)
{
hr = E_UNEXPECTED;
}
else if (!IsValidSyncLogErrorInfo(dwErrorLevel,lpcErrorText,lpSyncLogError))
{
hr = E_INVALIDARG;
}
else
{
if (lpSyncLogError && (lpSyncLogError->mask & SYNCMGRLOGERROR_ERRORID))
{
pHandlerInfo->fHasErrorJumps = TRUE;
msgLogErrors.mask |= SYNCMGRLOGERROR_ERRORID;
msgLogErrors.ErrorID = lpSyncLogError->ErrorID;
}
if (lpSyncLogError && (lpSyncLogError->mask & SYNCMGRLOGERROR_ERRORFLAGS))
{
if (SYNCMGRERRORFLAG_ENABLEJUMPTEXT & lpSyncLogError->dwSyncMgrErrorFlags)
{
pHandlerInfo->fHasErrorJumps = TRUE;
msgLogErrors.fHasErrorJumps = TRUE;
}
}
if (lpSyncLogError && (lpSyncLogError->mask & SYNCMGRLOGERROR_ITEMID))
{
msgLogErrors.mask |= SYNCMGRLOGERROR_ITEMID;
msgLogErrors.ItemID = lpSyncLogError->ItemID;
}
hr = S_OK;
}
}
clockqueue.Leave();
if (S_OK == hr)
{
Assert(sizeof(WPARAM) >= sizeof(HANDLERINFO *));
SendMessage(hWndCallback, WM_PROGRESS_LOGERROR, (WPARAM) pHandlerId, (LPARAM) &msgLogErrors);
}
return hr;
}
//+---------------------------------------------------------------------------
//
// Member: CHndlrQueue::DeleteLogError, public
//
// Synopsis: Deletes an Error from the Results pane that was previously logged.
//
// Arguments:
//
// Returns: Appropriate Error code
//
// Modifies:
//
// History: 17-Nov-97 rogerg Created.
//
//----------------------------------------------------------------------------
STDMETHODIMP CHndlrQueue::DeleteLogError(HANDLERINFO *pHandlerId,REFSYNCMGRERRORID ErrorID,DWORD dwReserved)
{
MSGDeleteLogErrors msgDeleteLogError;
HWND hWndCallback = NULL;
HANDLERINFO *pHandlerInfo;
CLock clockqueue(this);
clockqueue.Enter();
msgDeleteLogError.pHandlerId = pHandlerId;
msgDeleteLogError.ErrorID = ErrorID;
if (S_OK == LookupHandlerFromId(pHandlerId,&pHandlerInfo))
{
hWndCallback = pHandlerInfo->hWndCallback;
}
// review, if handler doesn't have any more error jumps after the deletelogError we can now
// release it (pHandlerInfo->fHasErrorJumps)
clockqueue.Leave();
if (hWndCallback)
{
SendMessage(hWndCallback, WM_PROGRESS_DELETELOGERROR, (WPARAM) 0, (LPARAM) &msgDeleteLogError);
}
return S_OK;
}
//+---------------------------------------------------------------------------
//
// Member: CHndlrQueue::CallCompletionRoutine, public
//
// Synopsis: Called by callback on handler thread
// to indicate a call with a completion callback
// has completed.
//
// Returns: Appropriate Error code
//
// Modifies:
//
// History: 02-Jun-98 rogerg Created.
//
//----------------------------------------------------------------------------
void CHndlrQueue::CallCompletionRoutine(HANDLERINFO *pHandlerId,DWORD dwThreadMsg,HRESULT hCallResult,
ULONG cbNumItems,SYNCMGRITEMID *pItemIDs)
{
HWND hWndDlg = NULL;
HRESULT hrHandlerCall = S_OK;
BOOL fCallbackAlreadyCalled = FALSE;
HANDLERINFO *pHandlerInfo;
CLock clockqueue(this);
if (!pHandlerId)
{
Assert(pHandlerId);
return;
}
// Note: cbNumItems and pItemIDs is only valid for ShowErrors
// make sure the handlid is valid and then if there
// is a pdlg call its completion routine via the postmessage
// method.
clockqueue.Enter();
hWndDlg = m_hwndDlg;
Assert(hWndDlg);
if ( pHandlerId && (S_OK == LookupHandlerFromId(pHandlerId,&pHandlerInfo)) )
{
// if flag isn't set for the message
// then it was already handled i.e. handler called
// us even though it returned an error.
if (dwThreadMsg & pHandlerInfo->dwOutCallMessages)
{
pHandlerInfo->dwOutCallMessages &= ~dwThreadMsg;
}
else
{
AssertSz(0,"Callback called twice"); // test apps currently do this.
fCallbackAlreadyCalled = TRUE;
}
// if already handled don't call these again.
if (!fCallbackAlreadyCalled)
{
// fix up internal states before informing caller
// the call is complete.
switch(dwThreadMsg)
{
case ThreadMsg_ShowProperties: // don't need to do anything on show properties.
break;
case ThreadMsg_PrepareForSync:
hrHandlerCall = PrepareForSyncCompleted(pHandlerInfo,hCallResult);
break;
case ThreadMsg_Synchronize:
hrHandlerCall = SynchronizeCompleted(pHandlerInfo,hCallResult);
break;
case ThreadMsg_ShowError:
hrHandlerCall = ShowErrorCompleted(pHandlerInfo,hCallResult,cbNumItems,pItemIDs);
break;
default:
AssertSz(0,"Unknown Queue Completion Callback");
break;
}
}
// possible completion routine comes in before handler has actually
// returned from the original call. Wait until proxy is no longer in an
// out call.
// If switch to COM for messaging need to find a better way of doing this.
if (pHandlerInfo->pThreadProxy &&
pHandlerInfo->pThreadProxy->IsProxyInOutCall()
&& hWndDlg)
{
// tell proxy to post the message whenver it gets done.
// CODE REVIEW:
// NOTENOTE:
// Remove this code..
/*
if ( 0 /* S_OK ==
pHandlerInfo->pThreadProxy->SetProxyCompletion(hWndDlg,WM_BASEDLG_COMPLETIONROUTINE,dwThreadMsg,hCallResult)*)
{
hWndDlg = NULL;
}
*/
}
}
else
{
// on handler lookup assert but still post the message to the hwnd
// so it won't get stuck waiting for the completion routine
// this is only valid for setproperties in the
// case the user clicked on a non-existant item but
// this shouldn't really happen either
AssertSz(dwThreadMsg == ThreadMsg_ShowProperties,"LookupHandler failed in CompletionRoutine");
}
LPCALLCOMPLETIONMSGLPARAM lpCallCompletelParam = (LPCALLCOMPLETIONMSGLPARAM) ALLOC(sizeof(CALLCOMPLETIONMSGLPARAM));
if (lpCallCompletelParam)
{
lpCallCompletelParam->hCallResult = hCallResult;
lpCallCompletelParam->clsidHandler = pHandlerId->clsidHandler;
// itemID is GUID_NULL unless its a ShowProperties completed.
if ((ThreadMsg_ShowProperties == dwThreadMsg) && (1 == cbNumItems))
{
lpCallCompletelParam->itemID = *pItemIDs;
}
else
{
lpCallCompletelParam->itemID = GUID_NULL;
}
}
clockqueue.Leave();
if (hWndDlg && !fCallbackAlreadyCalled) // if already out of out call or proxy failed post the messge ourselves.
{
// if alloc of completion lparam fails send message anyways so callback count
// remains accurate.
PostMessage(hWndDlg,WM_BASEDLG_COMPLETIONROUTINE,dwThreadMsg,(LPARAM) lpCallCompletelParam);
}
else
{
// if don't post message up to us to free the lpCallCopmlete.
if (lpCallCompletelParam)
{
FREE(lpCallCompletelParam);
}
}
}
//+---------------------------------------------------------------------------
//
// Member: CHndlrQueue::IsItemAlreadyInList, private
//
// Synopsis: Given a clsid and ItemID determines if a matchin
// item is already in the list
// Called in the context of the Handlers thread
//
// Arguments: [clsidHandler] - clsid of the handler
// [ItemID] - ItemID of the item
// [wHandlerId] - HandlerID of the item.
// [ppHandlerMatched] - on out the handler that matched
// [ppItemIdMatch] - on out Item that matched.
//
// Returns: Appropriate Error code
//
// Modifies:
//
// History: 17-Nov-97 rogerg Created.
//
//----------------------------------------------------------------------------
BOOL CHndlrQueue::IsItemAlreadyInList(CLSID clsidHandler,REFSYNCMGRITEMID ItemID,
HANDLERINFO *pHandlerId,
LPHANDLERINFO *ppHandlerMatched,
LPITEMLIST *ppItemListMatch)
{
BOOL fFoundMatch = FALSE;
LPHANDLERINFO pCurHandlerInfo = NULL;
LPITEMLIST pCurItem = NULL;
ASSERT_LOCKHELD(this); // caller of this function should have already locked the queue.
pCurHandlerInfo = m_pFirstHandler;
while (pCurHandlerInfo && !fFoundMatch)
{
if (pHandlerId == pCurHandlerInfo->pHandlerId) // when find hander know didn't find any before.
break;
if (clsidHandler == pCurHandlerInfo->clsidHandler) // see if CLSID matches
{
// see if handler info has a matching item
pCurItem = pCurHandlerInfo->pFirstItem;
while (pCurItem)
{
if (ItemID == pCurItem->offlineItem.ItemID)
{
*ppHandlerMatched = pCurHandlerInfo;
*ppItemListMatch = pCurItem;
fFoundMatch = TRUE;
break;
}
pCurItem = pCurItem->pnextItem;
}
}
pCurHandlerInfo = pCurHandlerInfo->pNextHandler;
}
return fFoundMatch;
}
//+---------------------------------------------------------------------------
//
// Member: CHndlrQueue::GetSelectedItemsInHandler, private
//
// Synopsis: Gets the number of selected items for this handler
//
// for our implementation if a cbCount is passed and it doesn't match
// the number of actually selected then assert since we call this routine
// internally.
//
//
// Arguments: [pHandlerInfo] - Pointer to the HandlerInfo to look at.
// [cbcount] - [in] cbCount == number of pItems allocated,
// [out] cbCpimt == number of items actually written.
// if the buffer is too small items written will be zero.
// [pItems] - Pointer to array of SYNCMGRITEMs to be filled in.
//
// Returns: Returns the number of selectd items.
//
// Modifies:
//
// History: 17-Nov-97 rogerg Created.
//
//----------------------------------------------------------------------------
DWORD CHndlrQueue::GetSelectedItemsInHandler(LPHANDLERINFO pHandlerInfo,ULONG *cbCount,
SYNCMGRITEMID* pItems)
{
LPITEMLIST pCurItem;
DWORD dwSelectCount = 0;
DWORD dwArraySizeIndex;
DWORD dwArraySize;
ASSERT_LOCKHELD(this); // caller of this function should have already locked the queue.
if (cbCount)
{
dwArraySizeIndex = *cbCount;
dwArraySize = *cbCount;
*cbCount = 0; // initialize to zero.
}
else
{
dwArraySizeIndex = 0;
dwArraySize = 0;
}
if ( dwArraySize && NULL == pItems)
{
Assert(0 == dwArraySize || pItems);
return 0;
}
if (NULL == pHandlerInfo)
{
Assert(pHandlerInfo);
return 0;
}
pCurItem = pHandlerInfo->pFirstItem;
while (pCurItem)
{
// dwItemState
if (SYNCMGRITEMSTATE_CHECKED == pCurItem->offlineItem.dwItemState)
{
++dwSelectCount;
if (dwArraySizeIndex)
{
*pItems = pCurItem->offlineItem.ItemID;
*cbCount += 1;
++pItems;
--dwArraySizeIndex;
if (!pCurItem->fHiddenItem) // if not a hidden item
{
Assert(TRUE == pCurItem->fIncludeInProgressBar);
Assert(HNDRLQUEUE_DEFAULT_PROGRESS_MAXVALUE == pCurItem->iProgMaxValue);
// reset iProgValue back to zero since may not be zero if retry came in while still synchronizing.
SetItemProgressValues(pCurItem,0,HNDRLQUEUE_DEFAULT_PROGRESS_MAXVALUE);
}
else
{
// if item is hidden,a assert it doesn't have UI
Assert(FALSE == pCurItem->fIncludeInProgressBar);
Assert(HNDRLQUEUE_DEFAULT_PROGRESS_MAXVALUE == pCurItem->iProgValue);
Assert(HNDRLQUEUE_DEFAULT_PROGRESS_MAXVALUE == pCurItem->iProgMaxValue);
}
pCurItem->fSynchronizingItem = TRUE; // item is now synchronizing
// once added to the array uncheck the item so on a retry we can just
// always reset items to checked
pCurItem->offlineItem.dwItemState = SYNCMGRITEMSTATE_UNCHECKED;
}
}
else
{
Assert(FALSE == pCurItem->fSynchronizingItem);
// Assert(FALSE == pCurItem->fIncludeInProgressBar); Can be included in progress bar if retry comes in before RemoveFinished is called.
Assert(HNDRLQUEUE_DEFAULT_PROGRESS_MAXVALUE == pCurItem->iProgValue);
Assert(HNDRLQUEUE_DEFAULT_PROGRESS_MAXVALUE == pCurItem->iProgMaxValue);
}
pCurItem = pCurItem->pnextItem;
}
// internal call should always request a proper array size.
Assert(dwSelectCount == dwArraySize || 0 == dwArraySize);
return dwSelectCount;
}
// job info methods
STDMETHODIMP CHndlrQueue::CreateJobInfo(JOBINFO **ppJobInfo,DWORD cbNumConnectionNames)
{
HRESULT hr = S_FALSE;
JOBINFO *pNewJobInfo = NULL;
ASSERT_LOCKHELD(this);
// create a new job and add it to the the JobInfo list.
// allocate space for JobInfo + number of connection objects that
// will be associated with this job.
Assert(cbNumConnectionNames);
if (cbNumConnectionNames < 1)
return S_FALSE;
pNewJobInfo = (JOBINFO *) ALLOC(sizeof(JOBINFO) +
sizeof(CONNECTIONOBJ)*(cbNumConnectionNames - 1));
if (pNewJobInfo)
{
memset(pNewJobInfo, 0, sizeof(JOBINFO));
pNewJobInfo->cRefs = 1;
pNewJobInfo->pNextJobInfo = m_pFirstJobInfo;
m_pFirstJobInfo = pNewJobInfo;
*ppJobInfo = pNewJobInfo;
hr = S_OK;
}
else
{
hr = E_OUTOFMEMORY;
}
return hr;
}
DWORD CHndlrQueue::ReleaseJobInfoExt(JOBINFO *pJobInfo)
{
DWORD dwRet;
CLock clockqueue(this);
clockqueue.Enter();
dwRet = ReleaseJobInfo(pJobInfo);
clockqueue.Leave();
return dwRet;
}
DWORD CHndlrQueue::ReleaseJobInfo(JOBINFO *pJobInfo)
{
DWORD cRefs;
ASSERT_LOCKHELD(this);
--(pJobInfo->cRefs);
cRefs = pJobInfo->cRefs;
Assert( ((LONG) cRefs) >= 0);
if (0 == cRefs)
{
JOBINFO *pCurJobInfo = NULL;
DWORD dwConnObjIndex;
// loop through release all connection objs on this job
for (dwConnObjIndex = 0 ; dwConnObjIndex < pJobInfo->cbNumConnectionObjs;
dwConnObjIndex++)
{
Assert(pJobInfo->pConnectionObj[dwConnObjIndex]);
if (pJobInfo->pConnectionObj[dwConnObjIndex])
{
ConnectObj_ReleaseConnectionObj(pJobInfo->pConnectionObj[dwConnObjIndex]);
pJobInfo->pConnectionObj[dwConnObjIndex] = NULL;
}
}
// remove this JobInfo from the list.
if (pJobInfo == m_pFirstJobInfo)
{
m_pFirstJobInfo = pJobInfo->pNextJobInfo;
}
else
{
pCurJobInfo = m_pFirstJobInfo;
while (pCurJobInfo->pNextJobInfo)
{
if (pJobInfo == pCurJobInfo->pNextJobInfo)
{
pCurJobInfo->pNextJobInfo = pJobInfo->pNextJobInfo;
break;
}
pCurJobInfo = pCurJobInfo->pNextJobInfo;
}
}
FREE(pJobInfo);
}
return cRefs;
}
DWORD CHndlrQueue::AddRefJobInfo(JOBINFO *pJobInfo)
{
DWORD cRefs;
ASSERT_LOCKHELD(this);
++(pJobInfo->cRefs);
cRefs = pJobInfo->cRefs;
return cRefs;
}
// determines ifthe specified JobInfo's connection can be openned.
// review should really call into connection Object help api.
STDMETHODIMP CHndlrQueue::OpenConnection(JOBINFO *pJobInfo)
{
CONNECTIONOBJ *pConnectionObj;
HRESULT hr;
Assert(pJobInfo);
if (NULL == pJobInfo) // if no job info go ahead and say the connection is open.
return S_OK;
// turn off workOffline during the sync CloseConnection will turn
// it back on if the user had it off.
ConnectObj_SetWorkOffline(FALSE);
// if this is anything but a schedule go ahead and say S_OK;
if (!(SYNCMGRFLAG_SCHEDULED == (pJobInfo->dwSyncFlags & SYNCMGRFLAG_EVENTMASK)) )
{
return S_OK;
}
// for schedule sink we only support one connection Object.
if (1 != pJobInfo->cbNumConnectionObjs)
{
Assert(1 == pJobInfo->cbNumConnectionObjs);
return E_UNEXPECTED;
}
pConnectionObj = pJobInfo->pConnectionObj[0];
if (NULL == pConnectionObj)
return S_OK;
// if we aren't suppose to make a connection of there is already
// a hRasConn as part of the connection object then just
// return S_OK;
// if connection is already open and we are on a job that
// has already tried to open it then return S_OK;
if (pJobInfo->pConnectionObj[0]->fConnectionOpen && pJobInfo->fTriedConnection)
return S_OK;
// if we haven't already tried to make the connection
// on this job then call OpenConnection to make sure the
// connection is still really open.
if (!pJobInfo->fTriedConnection)
{
pJobInfo->fTriedConnection = TRUE;
hr = ConnectObj_OpenConnection(pConnectionObj, pJobInfo->fCanMakeConnection, m_pDlg);
}
else
{
hr = S_FALSE;
}
// if get down to the bottom and still no hRasConn then return S_FALSE
return hr;
}
//+---------------------------------------------------------------------------
//
// Member: CHndlrQueue::ScrambleIdleHandlers, private
//
// Synopsis: Called on an Idle Choice queue just before transfer
// so the lastHandler is placed at the back of the list.
//
// Arguments:
//
// Returns:
//
// Modifies:
//
// History: 17-Nov-97 rogerg Created.
//
//----------------------------------------------------------------------------
STDMETHODIMP CHndlrQueue::ScrambleIdleHandlers(REFCLSID clsidLastHandler)
{
LPHANDLERINFO pMatchHandler;
LPHANDLERINFO pLastHandler;
CLock clockqueue(this);
Assert(m_QueueType == QUEUETYPE_CHOICE);
clockqueue.Enter();
// find the first occurance of specified handler and then place that handler
// at the end of the list and everything after at the beginning of the list
// no an error to not find the Handler since may have been deleted or
// no longer has items.
pMatchHandler = m_pFirstHandler;
while (pMatchHandler)
{
if (pMatchHandler->clsidHandler == clsidLastHandler)
{
// if there are no items after the match then just break;
if (NULL == pMatchHandler->pNextHandler)
{
break;
}
// loop until find the last handler.
pLastHandler = pMatchHandler->pNextHandler;
while (pLastHandler->pNextHandler)
{
pLastHandler = pLastHandler->pNextHandler;
}
// now set the handler after the matchHandler to be the
// head and set the next pointer of the LastHandler in
// the list to point to the MatchHandler.
pLastHandler->pNextHandler = m_pFirstHandler;
m_pFirstHandler = pMatchHandler->pNextHandler;
pMatchHandler->pNextHandler = NULL;
break;
}
pMatchHandler = pMatchHandler->pNextHandler;
}
clockqueue.Leave();
return S_OK;
}
//+---------------------------------------------------------------------------
//
// Member: CHndlrQueue::BeginSyncSession
//
// Synopsis: Called to signal the beginning of the core synchronization session
// to setup up dial support.
//
// History: 28-Jul-98 SitaramR Created
//
//----------------------------------------------------------------------------
STDMETHODIMP CHndlrQueue::BeginSyncSession()
{
HRESULT hr = ::BeginSyncSession();
return hr;
}
//+---------------------------------------------------------------------------
//
// Member: CHndlrQueue::EndSyncSession
//
// Synopsis: Called to signal the end of the core synchronization session
// to teardown dial support.
//
// History: 28-Jul-98 SitaramR Created
//
//----------------------------------------------------------------------------
STDMETHODIMP CHndlrQueue::EndSyncSession()
{
HRESULT hr = ::EndSyncSession();
return hr;
}
//+---------------------------------------------------------------------------
//
// Member: CHndlrQueue::SortHandlersByConnection
//
// Synopsis: Moves hanlders that won't establish connection to the end,
// ie after handlers that can establish connectoin.
//
// History: 28-Jul-98 SitaramR Created
//
//----------------------------------------------------------------------------
STDMETHODIMP CHndlrQueue::SortHandlersByConnection()
{
CLock clockqueue(this);
clockqueue.Enter();
Assert(m_QueueType == QUEUETYPE_CHOICE);
LPHANDLERINFO pFirstCannotDialHandler = NULL;
LPHANDLERINFO pLastCannotDialHandler = NULL;
LPHANDLERINFO pPrevHandler = NULL;
LPHANDLERINFO pCurHandler = m_pFirstHandler;
while ( pCurHandler )
{
if ( pCurHandler->SyncMgrHandlerInfo.SyncMgrHandlerFlags & SYNCMGRHANDLER_MAYESTABLISHCONNECTION )
{
//
// Move to next handler
//
pPrevHandler = pCurHandler;
pCurHandler = pCurHandler->pNextHandler;
}
else
{
//
// Move handler to cannot dial list
//
if ( pPrevHandler == NULL )
{
//
// This is the first handler in list
//
m_pFirstHandler = pCurHandler->pNextHandler;
pCurHandler->pNextHandler = NULL;
if ( pLastCannotDialHandler == NULL )
{
Assert( pFirstCannotDialHandler == NULL );
pFirstCannotDialHandler = pLastCannotDialHandler = pCurHandler;
}
else
{
pLastCannotDialHandler->pNextHandler = pCurHandler;
pLastCannotDialHandler = pCurHandler;
}
pCurHandler = m_pFirstHandler;
}
else
{
pPrevHandler->pNextHandler = pCurHandler->pNextHandler;
pCurHandler->pNextHandler = NULL;
if ( pLastCannotDialHandler == NULL )
{
Assert( pFirstCannotDialHandler == NULL );
pFirstCannotDialHandler = pLastCannotDialHandler = pCurHandler;
}
else
{
pLastCannotDialHandler->pNextHandler = pCurHandler;
pLastCannotDialHandler = pCurHandler;
}
pCurHandler = pPrevHandler->pNextHandler;
}
}
}
//
// Attach cannot dial list at end of m_pFirstHandler list
//
if ( pPrevHandler )
{
Assert( pPrevHandler->pNextHandler == NULL );
pPrevHandler->pNextHandler = pFirstCannotDialHandler;
}
else
{
//
// Case where the original list became empty
//
Assert( m_pFirstHandler == NULL );
m_pFirstHandler = pFirstCannotDialHandler;
}
clockqueue.Leave();
return S_OK;
}
//+---------------------------------------------------------------------------
//
// Member: CHndlrQueue::EstablishConnection
//
// Synopsis: Called by handler to establish a connection.
//
// Arguments: [pHandlerID] -- Ptr to handler
// [lpwszConnection] -- Connection to establish
// [dwReserved] -- Must be zero for now
//
// History: 28-Jul-98 SitaramR Created
//
//----------------------------------------------------------------------------
STDMETHODIMP CHndlrQueue::EstablishConnection( LPHANDLERINFO pHandlerID,
WCHAR const * lpwszConnection,
DWORD dwReserved )
{
HRESULT hr = S_OK;
CLock clockqueue(this);
clockqueue.Enter();
CONNECTIONOBJ *pConnObj = NULL;
BOOL fAutoDial = FALSE;
LPHANDLERINFO pHandlerInfo = NULL;
hr = LookupHandlerFromId( pHandlerID, &pHandlerInfo );
if ( S_OK == hr )
{
JOBINFO *pJobInfo = pHandlerInfo->pJobInfo;
DWORD dwSyncFlags = pJobInfo->dwSyncFlags & SYNCMGRFLAG_EVENTMASK;
if ( ( dwSyncFlags == SYNCMGRFLAG_MANUAL || dwSyncFlags == SYNCMGRFLAG_INVOKE )
&& pHandlerInfo->SyncMgrHandlerInfo.SyncMgrHandlerFlags & SYNCMGRHANDLER_MAYESTABLISHCONNECTION )
{
if ( lpwszConnection == NULL )
{
//
// Null connection means use the default autodial connection
//
fAutoDial = TRUE;
}
else
{
hr = ConnectObj_FindConnectionObj(lpwszConnection,TRUE,&pConnObj);
}
}
else
{
//
// Either the handler invoke type does not permit establishing connection,
// or GetHandlerInfo flags did not specify the EstablishConnection flag.
//
hr = E_UNEXPECTED;
}
}
clockqueue.Leave();
if (S_OK == hr)
{
if (fAutoDial)
{
hr = ConnectObj_AutoDial(INTERNET_AUTODIAL_FORCE_ONLINE,m_pDlg);
}
else
{
Assert( pConnObj );
if ( !pConnObj->fConnectionOpen )
{
hr = ConnectObj_OpenConnection(pConnObj, TRUE, m_pDlg );
ConnectObj_ReleaseConnectionObj(pConnObj);
}
}
}
return hr;
}
| 33.101929 | 158 | 0.526905 | [
"object"
] |
a8d27aca13985fa906a5596603d2f4d96e255ca6 | 2,006 | hh | C++ | include/mcnla/core/matrix/collection/base/vector_collection_wrapper.hh | emfomy/mcnla | 9f9717f4d6449bbd467c186651856d6212035667 | [
"MIT"
] | null | null | null | include/mcnla/core/matrix/collection/base/vector_collection_wrapper.hh | emfomy/mcnla | 9f9717f4d6449bbd467c186651856d6212035667 | [
"MIT"
] | null | null | null | include/mcnla/core/matrix/collection/base/vector_collection_wrapper.hh | emfomy/mcnla | 9f9717f4d6449bbd467c186651856d6212035667 | [
"MIT"
] | null | null | null | ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @file include/mcnla/core/matrix/collection/base/vector_collection_wrapper.hh
/// @brief The definition of vector collection wrapper.
///
/// @author Mu Yang <<emfomy@gmail.com>>
///
#ifndef MCNLA_CORE_MATRIX_COLLECTION_BASE_VECTOR_COLLECTION_WRAPPER_HH_
#define MCNLA_CORE_MATRIX_COLLECTION_BASE_VECTOR_COLLECTION_WRAPPER_HH_
#include <mcnla/core/matrix/collection/def.hpp>
#include <tuple>
#include <mcnla/core/matrix/dense.hpp>
#include <mcnla/core/utility/crtp.hpp>
#include <mcnla/core/utility/traits.hpp>
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// The MCNLA namespace.
//
namespace mcnla {
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// The matrix namespace.
//
namespace matrix {
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// The vector collection wrapper.
///
/// @tparam _Derived The derived type.
///
template <class _Derived>
class VectorCollectionWrapper {
private:
using VectorType = VectorT<_Derived>;
protected:
// Constructors
inline VectorCollectionWrapper() noexcept = default;
public:
// Gets information
inline bool isEmpty() const noexcept;
inline index_t len() const noexcept;
inline index_t nvec() const noexcept;
inline index_t nelem() const noexcept;
inline std::tuple<index_t, index_t> sizes() const noexcept;
// Gets vector
inline VectorType operator()( const index_t idx ) noexcept;
inline const VectorType operator()( const index_t idx ) const noexcept;
protected:
MCNLA_CRTP_DERIVED(_Derived)
};
} // namespace matrix
} // namespace mcnla
#endif // MCNLA_CORE_MATRIX_COLLECTION_BASE_VECTOR_COLLECTION_WRAPPER_HH_
| 29.5 | 128 | 0.557328 | [
"vector"
] |
a8dd5b26fdd3715a25062d79de89918d5304361c | 11,722 | hpp | C++ | src/Bubbles.hpp | rlorigro/shasta | 06522d841362ee22265d006062759b0cbcf3a1ea | [
"BSD-3-Clause-Open-MPI"
] | 1 | 2019-02-11T02:46:16.000Z | 2019-02-11T02:46:16.000Z | src/Bubbles.hpp | rlorigro/shasta | 06522d841362ee22265d006062759b0cbcf3a1ea | [
"BSD-3-Clause-Open-MPI"
] | null | null | null | src/Bubbles.hpp | rlorigro/shasta | 06522d841362ee22265d006062759b0cbcf3a1ea | [
"BSD-3-Clause-Open-MPI"
] | 1 | 2019-08-14T22:56:29.000Z | 2019-08-14T22:56:29.000Z | #ifndef SHASTA_BUBBLES_HPP
#define SHASTA_BUBBLES_HPP
/*******************************************************************************
Class to describe an analyze bubbles in the assembly graph.
*******************************************************************************/
#include "AssemblyGraph.hpp"
#include <boost/graph/adjacency_list.hpp>
#include <limits>
#include "vector.hpp"
namespace shasta {
class Bubbles;
class Assembler;
class OrientedReadPair;
}
class shasta::Bubbles {
public:
Bubbles(
const Assembler&,
bool debug = false
);
private:
// For now we only consider diploid bubbles, defined using the
// following strict criteria:
// - Source vertex v0 has out-degree 2.
// - Target vertex v1 has in-degree 2.
// - There are two parallel edges eA and eB, both v0->v1.
class Bubble {
public:
// The bubble as seen in the AssemblyGraph.
AssemblyGraph::VertexId av0;
AssemblyGraph::VertexId av1;
array<AssemblyGraph::EdgeId, 2> aEdgeIds;
// For convenience also store the MarkerGraph vertex ids.
MarkerGraph::VertexId mv0;
MarkerGraph::VertexId mv1;
// The OrientedReadIds on each of the two sides.
// Sorted by OrientedReadId, without duplicates.
// Values that are present on both sides are removed.
array<vector<OrientedReadId>, 2> orientedReadIds;
// Concordant/discordant sums computed by flagBadBubbles.
uint64_t concordantSum = 0;
uint64_t discordantSum = 0;
double discordantRatio() const
{
return double(discordantSum) / double(concordantSum + discordantSum);
}
// This flag is set for bubbles flagged as bad and removed from the BubbleGraph.
bool isBad = false;
// Constructor.
Bubble(
AssemblyGraph::VertexId av0,
AssemblyGraph::VertexId av1,
AssemblyGraph::EdgeId eA,
AssemblyGraph::EdgeId eB,
const MarkerGraph&,
const AssemblyGraph&);
private:
void fillInOrientedReadIds(
const MarkerGraph&,
const AssemblyGraph&);
};
vector<Bubble> bubbles;
void findBubbles();
void writeBubbles();
// A data structure that tells us, for each OrientedReadId,
// which sides of which bubbles that OrientedReadId appears in.
// Indexed by OrientedReadId::getValue().
// Contains pairs (bubbleId, side)
// where bubbleId is an index into the bubbles vector
// and side is 0 or 1.
// For each OrientedReadId, sorted by bubbleId and side.
// Note an oriented read cannot appearf on both sides of a bubble,
// by construction.
vector< vector <pair <uint64_t, uint64_t> > > orientedReadsTable;
void fillOrientedReadsTable();
void writeOrientedReadsTable();
// Given two OrientedReadIds, use the orientedReadsTable
// to count the number of times they appear on the same
// side or opposite sides of the same bubble.
void findOrientedReadsRelativePhase(
OrientedReadId,
OrientedReadId,
uint64_t& sameSideCount,
uint64_t& oppositeSideCount
) const;
// Find OrientedReadIds that appear in at least one bubble
// together with a given OrientedReadId.
// They are returned sorted.
void findNeighborOrientedReadIds(
OrientedReadId,
vector<OrientedReadId>&
) const;
// Figure out if two sequences differ only by copy numbers in
// a 2- or 3-base repeat.
static bool isShortRepeatCopyNumberDifference(
const vector<Base>&,
const vector<Base>&);
// Bubble graph.
// An undirected graph in which each vertex represents a Bubble.
// Two vertices are joined by an undirected edge if the corresponding Bubbles
// have one or more common OrientedReadIds.
class BubbleGraphVertex {
public:
uint64_t bubbleId;
BubbleGraphVertex(uint64_t bubbleId) :
bubbleId(bubbleId) {}
BubbleGraphVertex() : bubbleId(std::numeric_limits<uint64_t>::max()) {}
uint64_t componentId = std::numeric_limits<uint64_t>::max();
uint64_t color;
int64_t phase = std::numeric_limits<int64_t>::max();
};
class BubbleGraphEdge {
public:
// Store the number of common oriented reads for each pair of
// branches in the two bubbles.
// matrix[sideA][sideB] stores the number of OrientedReadIds
// that appear on sideA of the "first" bubble and on
// sideB of the "second" bubble of this edge.
// The "first" bubble of the edge is the lowered numbered.
array<array<uint64_t, 2>, 2> matrix;
uint64_t diagonalCount() const
{
return matrix[0][0] + matrix[1][1];
}
uint64_t offDiagonalCount() const
{
return matrix[0][1] + matrix[1][0];
}
uint64_t totalCount() const
{
return matrix[0][0] + matrix[1][1]+ matrix[0][1] + matrix[1][0];
}
uint64_t concordantCount() const
{
return max(diagonalCount(), offDiagonalCount());
}
uint64_t discordantCount() const
{
return min(diagonalCount(), offDiagonalCount());
}
// Ambiguity of the edge is 0 if discordantCount() is 0
// and 1 if discordantCount() = totalCount()/2, in which case
// discordantCount() = concordantCount();
double ambiguity() const
{
return double(2 * discordantCount()) / double(totalCount());
}
// Return the relative phase implied by this edge, which is
// +1 if offdiagonalCount() is 0 and
// -1 if diagonalCount() is 0.
double relativePhase() const
{
const double diagonalRatio = double(diagonalCount()) / double(totalCount());
return 2. * diagonalRatio - 1.;
}
BubbleGraphEdge()
{
for(uint64_t sideA=0; sideA<2; sideA++) {
for(uint64_t sideB=0; sideB<2; sideB++) {
matrix[sideA][sideB] = 0;
}
}
}
};
// We use boost::vecS for thew vertices, so vertex_descriptors are the same
// as bubble ids (indices into the bubbles vector).
using BubbleGraphBaseClass =
boost::adjacency_list<boost::listS, boost::listS, boost::undirectedS,
BubbleGraphVertex, BubbleGraphEdge>;
class BubbleGraph: public BubbleGraphBaseClass {
public:
// The vertex descriptor corresponding to each bubbleId.
vector<vertex_descriptor> vertexTable;
vertex_descriptor vertexDescriptor(uint64_t bubbleId) const
{
return vertexTable[bubbleId];
}
void computeConnectedComponents();
vector< vector<vertex_descriptor> > connectedComponents;
};
BubbleGraph bubbleGraph;
void createBubbleGraph();
// Write the BubbleGraph in graphviz format, coloring
// the bubbles by discordant ratio and the edges by ambiguity.
void writeBubbleGraphGraphviz() const;
// Write a single component of the BubbleGraph in html/svg format.
// To compute sfdp layout, only consider edges
// for which relativePhase() >= minRelativePhase.
void writeBubbleGraphComponentHtml(
uint64_t componentId,
const vector<BubbleGraph::vertex_descriptor>& component,
double minRelativePhase) const;
// ComponentGraph is used by writeBubbleGraphComponentSvg.
class ComponentGraphVertex {
public:
array<double, 2> position;
};
using ComponentGraph = boost::adjacency_list<boost::listS, boost::vecS, boost::undirectedS, ComponentGraphVertex>;
// Use the BubbleGraph to flag bad bubbles.
void flagBadBubbles();
void removeBadBubbles(double discordantRatioThreshold);
// In the PhasingGraph, each vertex represents an OrientedReadId.
// Two vertices are joined by an undirected edge
// if the corresponding OrientedReadIds appear
// together in at least one bubble.
// There is no global PhasingGraph object.
// We construct a separate PhasingGraph for each connected
// component of the BubbleGraph.
class PhasingGraphVertex {
public:
OrientedReadId orientedReadId;
int64_t phase = 0;
double eigenvectorComponent = 0.;
array<double, 2> position;
};
class PhasingGraphEdge {
public:
uint64_t sameSideCount;
uint64_t oppositeSideCount;
double relativePhase() const
{
const double ratio = double(sameSideCount) / double(sameSideCount + oppositeSideCount); // In [0,1]
return 2. * ratio - 1.; // In (-1, 1)
}
};
using PhasingGraphBaseClass =
boost::adjacency_list<boost::listS, boost::listS, boost::undirectedS,
PhasingGraphVertex, PhasingGraphEdge>;
class PhasingGraph: public PhasingGraphBaseClass {
public:
std::map<OrientedReadId, vertex_descriptor> vertexMap;
void createVertices(const vector<OrientedReadId>&);
void phaseSpectral(bool debug);
// Write in html/svg format.
// To compute sfdp layout, only consider edges
// for which relativePhase() >= minRelativePhase.
void writeHtml(
const string& fileName,
double minRelativePhase) const;
};
void createPhasingGraph(
const vector<OrientedReadId>&,
PhasingGraph&) const;
// Phase a connected component using the SVD.
void phaseSvd(
const vector<BubbleGraph::vertex_descriptor>&,
PhasingGraph&);
// A predicate used to filter PhasingGraph edges for which
// relativePhase() >= minrelativePhase.
class PhasingGraphEdgePredicate {
public:
PhasingGraphEdgePredicate(
const PhasingGraph& phasingGraph,
double minRelativePhase) :
phasingGraph(&phasingGraph),
minRelativePhase(minRelativePhase) {}
const PhasingGraph* phasingGraph;
double minRelativePhase;
bool operator() (const PhasingGraph::edge_descriptor e) const
{
return (*phasingGraph)[e].relativePhase() >= minRelativePhase;
}
};
// Top level function for phasing.
void phase(double minRelativePhase);
// Phase the bubbles of a connected component of the BubbleGraph.
// This stores the phases in the component vertices.
void phaseComponentBubbles(
const vector<BubbleGraph::vertex_descriptor>&);
// The component and phase of each oriented read.
// The phase is 0 or 1.
// Indexed by OrientedRead::getValue().
vector< pair<uint32_t, uint32_t> > orientedReadsPhase;
// Given a connected component of the BubbleGraph,
// find the OrientedReadIds that appear in it.
// The OrientedReadIds are returned sorted.
void findComponentOrientedReads(
const vector<BubbleGraph::vertex_descriptor>&,
vector<OrientedReadId>&
) const;
// Functions used to decide if an alignment should be used.
public:
bool allowAlignment(
const OrientedReadPair&,
bool useClustering) const;
private:
bool allowAlignment(
const OrientedReadId&,
const OrientedReadId&,
bool useClustering) const;
bool allowAlignmentUsingClustering(
const OrientedReadId&,
const OrientedReadId&) const;
bool allowAlignmentUsingBubbles(
const OrientedReadId&,
const OrientedReadId&) const;
const Assembler& assembler;
bool debug;
};
#endif
| 32.203297 | 118 | 0.636154 | [
"object",
"vector"
] |
a8dfee65b2336dbe74b15c50582bae7cf004fa78 | 7,555 | cpp | C++ | OpenTESArena/src/Interface/MainMenuUiModel.cpp | TotalCaesar659/OpenTESArena | e72eda7a5e03869309b5ed7375f432d0ad826ff3 | [
"MIT"
] | null | null | null | OpenTESArena/src/Interface/MainMenuUiModel.cpp | TotalCaesar659/OpenTESArena | e72eda7a5e03869309b5ed7375f432d0ad826ff3 | [
"MIT"
] | null | null | null | OpenTESArena/src/Interface/MainMenuUiModel.cpp | TotalCaesar659/OpenTESArena | e72eda7a5e03869309b5ed7375f432d0ad826ff3 | [
"MIT"
] | null | null | null | #include <numeric>
#include "MainMenuUiModel.h"
#include "../Assets/ExeData.h"
#include "../Game/Game.h"
#include "../Math/RandomUtils.h"
#include "../World/MapType.h"
#include "../WorldMap/ArenaLocationUtils.h"
#include "../WorldMap/ProvinceDefinition.h"
#include "components/debug/Debug.h"
#include "components/utilities/String.h"
std::string MainMenuUiModel::getTestButtonText()
{
return "Test";
}
std::string MainMenuUiModel::getTestTypeName(int type)
{
if (type == TestType_MainQuest)
{
return "Main Quest";
}
else if (type == TestType_Interior)
{
return "Interior";
}
else if (type == TestType_City)
{
return "City";
}
else if (type == TestType_Wilderness)
{
return "Wilderness";
}
else if (type == TestType_Dungeon)
{
return "Dungeon";
}
else
{
DebugUnhandledReturnMsg(std::string, std::to_string(type));
}
}
std::string MainMenuUiModel::getSelectedTestName(Game &game, int testType, int testIndex, int testIndex2)
{
if (testType == MainMenuUiModel::TestType_MainQuest)
{
const auto &binaryAssetLibrary = game.getBinaryAssetLibrary();
const auto &exeData = binaryAssetLibrary.getExeData();
// Decide how to get the main quest dungeon name.
if (testIndex == 0)
{
// Start dungeon.
return String::toUppercase(exeData.locations.startDungeonMifName);
}
else if (testIndex == (MainMenuUiModel::MainQuestLocationCount - 1))
{
// Final dungeon.
return String::toUppercase(exeData.locations.finalDungeonMifName);
}
else
{
// Generate the location from the executable data, fetching data from a
// global function.
int locationID, provinceID;
MainMenuUiModel::SpecialCaseType specialCaseType;
MainMenuUiModel::getMainQuestLocationFromIndex(testIndex, exeData, &locationID, &provinceID, &specialCaseType);
DebugAssert(specialCaseType == MainMenuUiModel::SpecialCaseType::None);
// Calculate the .MIF name from the dungeon seed.
const auto &cityData = binaryAssetLibrary.getCityDataFile();
const uint32_t dungeonSeed = [&cityData, locationID, provinceID]()
{
const auto &province = cityData.getProvinceData(provinceID);
const int localDungeonID = locationID - 32;
return ArenaLocationUtils::getDungeonSeed(localDungeonID, provinceID, province);
}();
const std::string mifName = ArenaLocationUtils::getMainQuestDungeonMifName(dungeonSeed);
return String::toUppercase(mifName);
}
}
else if (testType == MainMenuUiModel::TestType_Interior)
{
const auto &interior = MainMenuUiModel::InteriorLocations.at(testIndex);
return std::get<0>(interior) + std::to_string(testIndex2) + ".MIF";
}
else if (testType == MainMenuUiModel::TestType_City)
{
return MainMenuUiModel::CityLocations.at(testIndex);
}
else if (testType == MainMenuUiModel::TestType_Wilderness)
{
return MainMenuUiModel::WildernessLocations.at(testIndex);
}
else if (testType == MainMenuUiModel::TestType_Dungeon)
{
return MainMenuUiModel::DungeonLocations.at(testIndex);
}
else
{
DebugUnhandledReturnMsg(std::string, std::to_string(testType));
}
}
std::optional<ArenaTypes::InteriorType> MainMenuUiModel::getSelectedTestInteriorType(int testType, int testIndex)
{
if ((testType == MainMenuUiModel::TestType_MainQuest) || (testType == MainMenuUiModel::TestType_Dungeon))
{
return ArenaTypes::InteriorType::Dungeon;
}
else if (testType == MainMenuUiModel::TestType_Interior)
{
DebugAssertIndex(MainMenuUiModel::InteriorLocations, testIndex);
const auto &interior = MainMenuUiModel::InteriorLocations[testIndex];
return std::get<2>(interior);
}
else if ((testType == MainMenuUiModel::TestType_City) || (testType == MainMenuUiModel::TestType_Wilderness))
{
return std::nullopt;
}
else
{
DebugUnhandledReturnMsg(std::optional<ArenaTypes::InteriorType>, std::to_string(testType));
}
}
ArenaTypes::WeatherType MainMenuUiModel::getSelectedTestWeatherType(int testWeather)
{
DebugAssertIndex(MainMenuUiModel::Weathers, testWeather);
return MainMenuUiModel::Weathers[testWeather];
}
MapType MainMenuUiModel::getSelectedTestMapType(int testType)
{
if ((testType == MainMenuUiModel::TestType_MainQuest) ||
(testType == MainMenuUiModel::TestType_Interior) ||
(testType == MainMenuUiModel::TestType_Dungeon))
{
return MapType::Interior;
}
else if (testType == MainMenuUiModel::TestType_City)
{
return MapType::City;
}
else if (testType == MainMenuUiModel::TestType_Wilderness)
{
return MapType::Wilderness;
}
else
{
DebugUnhandledReturnMsg(MapType, std::to_string(testType));
}
}
void MainMenuUiModel::getMainQuestLocationFromIndex(int testIndex, const ExeData &exeData, int *outLocationID,
int *outProvinceID, SpecialCaseType *outSpecialCaseType)
{
if (testIndex == 0)
{
*outLocationID = -1;
*outProvinceID = ArenaLocationUtils::CENTER_PROVINCE_ID;
*outSpecialCaseType = SpecialCaseType::StartDungeon;
}
else if (testIndex == (MainQuestLocationCount - 1))
{
*outLocationID = 0;
*outProvinceID = ArenaLocationUtils::CENTER_PROVINCE_ID;
*outSpecialCaseType = SpecialCaseType::None;
}
else
{
// Generate the location from the executable data.
const auto &staffProvinces = exeData.locations.staffProvinces;
const int staffProvincesIndex = (testIndex - 1) / 2;
DebugAssertIndex(staffProvinces, staffProvincesIndex);
*outProvinceID = staffProvinces[staffProvincesIndex];
*outLocationID = ArenaLocationUtils::dungeonToLocationID(testIndex % 2);
*outSpecialCaseType = SpecialCaseType::None;
}
}
std::vector<int> MainMenuUiModel::makeShuffledLocationIndices(const ProvinceDefinition &provinceDef)
{
std::vector<int> indices(provinceDef.getLocationCount());
std::iota(indices.begin(), indices.end(), 0);
RandomUtils::shuffle(indices.data(), static_cast<int>(indices.size()));
return indices;
}
std::optional<int> MainMenuUiModel::getRandomCityLocationDefIndexIfType(const ProvinceDefinition &provinceDef,
ArenaTypes::CityType cityType)
{
// Iterate over locations in the province in a random order.
const std::vector<int> randomLocationIndices = MainMenuUiModel::makeShuffledLocationIndices(provinceDef);
for (const int locationIndex : randomLocationIndices)
{
const LocationDefinition &curLocationDef = provinceDef.getLocationDef(locationIndex);
if (curLocationDef.getType() == LocationDefinition::Type::City)
{
const auto &curCityDef = curLocationDef.getCityDefinition();
if (curCityDef.type == cityType)
{
return locationIndex;
}
}
}
return std::nullopt;
}
int MainMenuUiModel::getRandomCityLocationIndex(const ProvinceDefinition &provinceDef)
{
// Iterate over locations in the province in a random order.
const std::vector<int> randomLocationIndices = MainMenuUiModel::makeShuffledLocationIndices(provinceDef);
for (const int locationIndex : randomLocationIndices)
{
const LocationDefinition &curLocationDef = provinceDef.getLocationDef(locationIndex);
if (curLocationDef.getType() == LocationDefinition::Type::City)
{
return locationIndex;
}
}
return -1;
}
std::optional<int> MainMenuUiModel::getRandomDungeonLocationDefIndex(const ProvinceDefinition &provinceDef)
{
// Iterate over locations in the province in a random order.
const std::vector<int> randomLocationIndices = MainMenuUiModel::makeShuffledLocationIndices(provinceDef);
for (const int locationIndex : randomLocationIndices)
{
const LocationDefinition &curLocationDef = provinceDef.getLocationDef(locationIndex);
if (curLocationDef.getType() == LocationDefinition::Type::Dungeon)
{
return locationIndex;
}
}
return std::nullopt;
}
| 30.22 | 114 | 0.757114 | [
"vector"
] |
a8e0ba334f7a5f41f06b61e9cb19c8aecc7438f1 | 92,525 | cpp | C++ | src/testbed/performancetests/main.cpp | aproeme/libgeodecomp | f78899c67ad62540fd153cba132a0a363a7b3fa9 | [
"BSL-1.0"
] | 40 | 2015-03-18T16:36:25.000Z | 2020-08-19T07:35:19.000Z | src/testbed/performancetests/main.cpp | aproeme/libgeodecomp | f78899c67ad62540fd153cba132a0a363a7b3fa9 | [
"BSL-1.0"
] | 72 | 2015-02-05T10:41:30.000Z | 2022-03-03T12:02:47.000Z | src/testbed/performancetests/main.cpp | aproeme/libgeodecomp | f78899c67ad62540fd153cba132a0a363a7b3fa9 | [
"BSL-1.0"
] | 17 | 2015-11-22T14:49:16.000Z | 2020-01-15T19:05:04.000Z | #include <libgeodecomp/config.h>
#include <libgeodecomp/misc/apitraits.h>
#include <libgeodecomp/io/simpleinitializer.h>
#include <libgeodecomp/misc/chronometer.h>
#include <libgeodecomp/geometry/convexpolytope.h>
#include <libgeodecomp/geometry/coord.h>
#include <libgeodecomp/geometry/floatcoord.h>
#include <libgeodecomp/geometry/region.h>
#include <libgeodecomp/geometry/stencils.h>
#include <libgeodecomp/geometry/partitions/hindexingpartition.h>
#include <libgeodecomp/geometry/partitions/hilbertpartition.h>
#include <libgeodecomp/geometry/partitions/stripingpartition.h>
#include <libgeodecomp/geometry/partitions/zcurvepartition.h>
#include <libgeodecomp/storage/grid.h>
#include <libgeodecomp/storage/linepointerassembly.h>
#include <libgeodecomp/storage/linepointerupdatefunctor.h>
#include <libgeodecomp/storage/updatefunctor.h>
#include <libgeodecomp/parallelization/openmpsimulator.h>
#include <libgeodecomp/parallelization/serialsimulator.h>
#include <libgeodecomp/storage/unstructuredgrid.h>
#include <libgeodecomp/storage/unstructuredlooppeeler.h>
#include <libgeodecomp/storage/unstructuredneighborhood.h>
#include <libgeodecomp/storage/unstructuredsoagrid.h>
#include <libgeodecomp/storage/unstructuredsoaneighborhood.h>
#include <libgeodecomp/storage/unstructuredupdatefunctor.h>
#include <libflatarray/short_vec.hpp>
#include <libflatarray/testbed/cpu_benchmark.hpp>
#include <libflatarray/testbed/evaluate.hpp>
#include <libflatarray/api_traits.hpp>
#include <libflatarray/macros.hpp>
#include <emmintrin.h>
#ifdef __AVX__
#include <immintrin.h>
#endif
#include <iomanip>
#include <iostream>
#include <stdio.h>
#include "cell.h"
#include "cpubenchmark.h"
using namespace LibGeoDecomp;
using namespace LibFlatArray;
class RegionCount : public CPUBenchmark
{
public:
std::string family()
{
return "RegionCount";
}
std::string species()
{
return "gold";
}
double performance(std::vector<int> rawDim)
{
Coord<3> dim(rawDim[0], rawDim[1], rawDim[2]);
int sum = 0;
Region<3> r;
for (int z = 0; z < dim.z(); ++z) {
for (int y = 0; y < dim.y(); ++y) {
r << Streak<3>(Coord<3>(0, y, z), dim.x());
}
}
double seconds = 0;
{
ScopedTimer t(&seconds);
for (int z = 0; z < dim.z(); z += 4) {
for (int y = 0; y < dim.y(); y += 4) {
for (int x = 0; x < dim.x(); x += 4) {
sum += r.count(Coord<3>(x, y, z));
}
}
}
}
if (sum == 31) {
std::cout << "pure debug statement to prevent the compiler from optimizing away the previous loop";
}
return seconds;
}
std::string unit()
{
return "s";
}
};
class RegionInsert : public CPUBenchmark
{
public:
std::string family()
{
return "RegionInsert";
}
std::string species()
{
return "gold";
}
double performance(std::vector<int> rawDim)
{
Coord<3> dim(rawDim[0], rawDim[1], rawDim[2]);
double seconds = 0;
{
ScopedTimer t(&seconds);
Region<3> r;
for (int z = 0; z < dim.z(); ++z) {
for (int y = 0; y < dim.y(); ++y) {
r << Streak<3>(Coord<3>(0, y, z), dim.x());
}
}
}
return seconds;
}
std::string unit()
{
return "s";
}
};
class RegionIntersect : public CPUBenchmark
{
public:
std::string family()
{
return "RegionIntersect";
}
std::string species()
{
return "gold";
}
double performance(std::vector<int> rawDim)
{
Coord<3> dim(rawDim[0], rawDim[1], rawDim[2]);
double seconds = 0;
{
ScopedTimer t(&seconds);
Region<3> r1;
Region<3> r2;
for (int z = 0; z < dim.z(); ++z) {
for (int y = 0; y < dim.y(); ++y) {
r1 << Streak<3>(Coord<3>(0, y, z), dim.x());
}
}
for (int z = 1; z < (dim.z() - 1); ++z) {
for (int y = 1; y < (dim.y() - 1); ++y) {
r2 << Streak<3>(Coord<3>(1, y, z), dim.x() - 1);
}
}
Region<3> r3 = r1 & r2;
}
return seconds;
}
std::string unit()
{
return "s";
}
};
class RegionSubtract : public CPUBenchmark
{
public:
std::string family()
{
return "RegionSubtract";
}
std::string species()
{
return "gold";
}
double performance(std::vector<int> rawDim)
{
Coord<3> dim(rawDim[0], rawDim[1], rawDim[2]);
double seconds = 0;
{
ScopedTimer t(&seconds);
Region<3> r1;
Region<3> r2;
for (int z = 0; z < dim.z(); ++z) {
for (int y = 0; y < dim.y(); ++y) {
r1 << Streak<3>(Coord<3>(0, y, z), dim.x());
}
}
for (int z = 1; z < (dim.z() - 1); ++z) {
for (int y = 1; y < (dim.y() - 1); ++y) {
r2 << Streak<3>(Coord<3>(1, y, z), dim.x() - 1);
}
}
Region<3> r3 = r1 - r2;
}
return seconds;
}
std::string unit()
{
return "s";
}
};
class RegionUnion : public CPUBenchmark
{
public:
std::string family()
{
return "RegionUnion";
}
std::string species()
{
return "gold";
}
double performance(std::vector<int> rawDim)
{
Coord<3> dim(rawDim[0], rawDim[1], rawDim[2]);
double seconds = 0;
{
ScopedTimer t(&seconds);
Region<3> r1;
Region<3> r2;
for (int z = 0; z < dim.z(); ++z) {
for (int y = 0; y < dim.y(); ++y) {
r1 << Streak<3>(Coord<3>(0, y, z), dim.x());
}
}
for (int z = 1; z < (dim.z() - 1); ++z) {
for (int y = 1; y < (dim.y() - 1); ++y) {
r2 << Streak<3>(Coord<3>(1, y, z), dim.x() - 1);
}
}
Region<3> r3 = r1 + r2;
}
return seconds;
}
std::string unit()
{
return "s";
}
};
class RegionAppend : public CPUBenchmark
{
public:
std::string family()
{
return "RegionAppend";
}
std::string species()
{
return "gold";
}
double performance(std::vector<int> rawDim)
{
Coord<3> dim(rawDim[0], rawDim[1], rawDim[2]);
double seconds = 0;
{
Region<3> r1;
Region<3> r2;
for (int z = 0; z < dim.z(); ++z) {
for (int y = 0; y < dim.y(); ++y) {
r1 << Streak<3>(Coord<3>(0, y, z), dim.x());
}
}
for (int z = dim.z(); z < (2 * dim.z()); ++z) {
for (int y = 0; y < dim.y(); ++y) {
r2 << Streak<3>(Coord<3>(0, y, z), dim.x());
}
}
Region<3> akku1 = r1;
Region<3> akku2 = r2;
int sum = 0;
{
ScopedTimer t(&seconds);
akku1 += r2;
akku2 += r1;
sum += akku1.size();
sum += akku2.size();
sum += (r1 + r2).size();
sum += (r2 + r1).size();
}
}
return seconds;
}
std::string unit()
{
return "s";
}
};
class RegionExpand : public CPUBenchmark
{
public:
explicit RegionExpand(int expansionWidth) :
expansionWidth(expansionWidth)
{}
std::string family()
{
std::stringstream buf;
buf << "RegionExpand" << expansionWidth;
return buf.str();
}
std::string species()
{
return "gold";
}
double performance(std::vector<int> rawDim)
{
Coord<3> dim(rawDim[0], rawDim[1], rawDim[2]);
double seconds = 0;
{
ScopedTimer t(&seconds);
Region<3> r1;
for (int z = 0; z < dim.z(); ++z) {
for (int y = 0; y < dim.y(); ++y) {
r1 << Streak<3>(Coord<3>(0, y, z), dim.x());
}
}
Region<3> r2 = r1.expand(expansionWidth);
}
return seconds;
}
std::string unit()
{
return "s";
}
private:
int expansionWidth;
};
class RegionExpandWithAdjacency : public CPUBenchmark
{
public:
explicit RegionExpandWithAdjacency(
std::map<int, ConvexPolytope<FloatCoord<2> > > cells) :
rawCells(cells)
{}
std::string family()
{
std::stringstream buf;
// we don't name this RegionExpandWithAdjacency so users can
// still selectively run RegionExpand sans this test.
buf << "RegionExpWithAdjacency";
return buf.str();
}
std::string species()
{
return "gold";
}
static std::map<int, ConvexPolytope<FloatCoord<2> > > genGrid(int numCells)
{
int elementsPerChunk = 5;
int numChunks = numCells / elementsPerChunk;
Coord<2> gridSize = Coord<2>::diagonal(sqrt(numChunks));
Coord<2> chunkDim(100, 100);
Coord<2> globalDim = chunkDim.scale(gridSize);
double minDistance = 10;
int counter = 0;
Grid<std::map<int, Coord<2> >, Topologies::Torus<2>::Topology> grid(gridSize);
for (int y = 0; y < gridSize.y(); ++y) {
for (int x = 0; x < gridSize.x(); ++x) {
Coord<2> gridIndex(x, y);
fillChunk(&grid, gridIndex, &counter, elementsPerChunk, chunkDim, minDistance);
}
}
std::map<int, ConvexPolytope<FloatCoord<2> > > cells;
Coord<2> relativeCoords[] = {
Coord<2>( 0, 0),
Coord<2>(-1, 0),
Coord<2>( 1, 0),
Coord<2>( 0, -1),
Coord<2>( 0, 1),
Coord<2>(-1, -1),
Coord<2>( 1, -1),
Coord<2>(-1, 1),
Coord<2>( 1, 1)
};
for (int y = 0; y < gridSize.y(); ++y) {
for (int x = 0; x < gridSize.x(); ++x) {
Coord<2> gridIndex(x, y);
const std::map<int, Coord<2> >& chunk = grid[gridIndex];
for (std::map<int, Coord<2> >::const_iterator i = chunk.begin(); i != chunk.end(); ++i) {
ConvexPolytope<FloatCoord<2> > element(i->second, globalDim);
for (int c = 0; c < 9; ++c) {
Coord<2> currentIndex = gridIndex + relativeCoords[c];
const std::map<int, Coord<2> >& neighbors = grid[currentIndex];
for (std::map<int, Coord<2> >::const_iterator j = neighbors.begin(); j != neighbors.end(); ++j) {
if (j->second == i->second) {
continue;
}
element << std::make_pair(j->second, j->first);
}
if (c == 0) {
element.updateGeometryData(true);
}
}
cells[i->first] = element;
}
}
}
return cells;
}
double performance(std::vector<int> dim)
{
double seconds = 0;
// I. Adapt Voronio Mesh (i.e. Set of Cells)
int skipCells = dim[1];
int expansionWidth = dim[2];
int idStreakLength = dim[3];
std::map<int, ConvexPolytope<FloatCoord<2> > > cells = mapIDs(rawCells, idStreakLength);
// II. Extract Adjacency List from Cells
RegionBasedAdjacency adjacency;
std::vector<int> ids;
for (std::map<int, ConvexPolytope<FloatCoord<2> > >::iterator i = cells.begin(); i != cells.end(); ++i) {
int id = i->first;
const ConvexPolytope<FloatCoord<2> > element = i->second;
ids << id;
addNeighbors(adjacency, id, element.getLimits());
}
// III. Fill Region
std::sort(ids.begin(), ids.end());
Region<1> r;
int counter = 0;
bool select = true;
for (std::vector<int>::iterator i = ids.begin(); i != ids.end(); ++i) {
++counter;
if (counter >= skipCells) {
counter = 0;
select = !select;
}
if (select) {
r << Coord<1>(*i);
}
}
// IV. Performance Measurement
{
ScopedTimer t(&seconds);
Region<1> q = r.expandWithTopology(expansionWidth, Coord<1>(), Topologies::Unstructured::Topology(), adjacency);
if (q.size() == 4711) {
std::cout << "pure debug statement to prevent the compiler from optimizing away the previous function";
}
}
return seconds;
}
std::string unit()
{
return "s";
}
private:
std::map<int, ConvexPolytope<FloatCoord<2> > > rawCells;
static std::map<int, ConvexPolytope<FloatCoord<2> > > mapIDs(
const std::map<int, ConvexPolytope<FloatCoord<2> > >& rawCells, int idStreakLength)
{
std::map<int, ConvexPolytope<FloatCoord<2> > > ret;
for (std::map<int, ConvexPolytope<FloatCoord<2> > >::const_iterator i = rawCells.begin(); i != rawCells.end(); ++i) {
ConvexPolytope<FloatCoord<2> > element = i->second;
mapLimitIDs(&element.getLimits(), idStreakLength);
ret[mapID(i->first, idStreakLength)] = element;
}
return ret;
}
template<typename LIMITS_CONTAINER>
static void mapLimitIDs(LIMITS_CONTAINER *limits, int idStreakLength)
{
for (typename LIMITS_CONTAINER::iterator i = limits->begin(); i != limits->end(); ++i) {
i->neighborID = mapID(i->neighborID, idStreakLength);
}
}
static int mapID(int id, int idStreakLength)
{
if (idStreakLength == -1) {
return id;
}
return id / idStreakLength * 2 * idStreakLength + id % idStreakLength;
}
template<typename GRID>
static void fillChunk(GRID *grid, const Coord<2>& gridIndex, int *counter, int elementsPerChunk, const Coord<2>& chunkDim, double minDistance)
{
Coord<2> chunkOffset = gridIndex.scale(chunkDim);
for (int i = 0; i < elementsPerChunk; ++i) {
Coord<2> randomCoord = Coord<2>(Random::genUnsigned(chunkDim.x()),
Random::genUnsigned(chunkDim.y()));
randomCoord += chunkOffset;
if (doesNotCollide(randomCoord, *grid, gridIndex, minDistance)) {
int id = (*counter)++;
(*grid)[gridIndex][id] = randomCoord;
}
}
}
template<typename COORD, typename GRID>
static bool doesNotCollide(COORD position, const GRID& grid, Coord<2> gridIndex, double minDistance)
{
for (int y = -1; y < 2; ++y) {
for (int x = -1; x < 2; ++x) {
Coord<2> currentIndex = gridIndex + Coord<2>(x, y);
bool valid = positionMaintainsMinDistanceToOthers(
position,
grid[currentIndex].begin(),
grid[currentIndex].end(),
minDistance);
if (!valid) {
return false;
}
}
}
return true;
}
template<typename COORD, typename ITERATOR1, typename ITERATOR2>
static bool positionMaintainsMinDistanceToOthers(
const COORD& position, const ITERATOR1& begin, const ITERATOR2& end, double minDistance)
{
for (ITERATOR1 i = begin; i != end; ++i) {
COORD delta = i->second - position;
if (delta.abs().maxElement() < minDistance) {
return false;
}
}
return true;
}
template<typename LIMITS>
void addNeighbors(Adjacency& adjacency, int from, const LIMITS& limits)
{
for (typename LIMITS::const_iterator i = limits.begin(); i != limits.end(); ++i) {
adjacency.insert(from, i->neighborID);
}
}
};
class CoordEnumerationVanilla : public CPUBenchmark
{
public:
std::string family()
{
return "CoordEnumeration";
}
std::string species()
{
return "vanilla";
}
double performance(std::vector<int> rawDim)
{
Coord<3> dim(rawDim[0], rawDim[1], rawDim[2]);
double seconds = 0;
{
ScopedTimer t(&seconds);
Coord<3> sum;
for (int z = 0; z < dim.z(); ++z) {
for (int y = 0; y < dim.y(); ++y) {
for (int x = 0; x < dim.x(); ++x) {
sum += Coord<3>(x, y, z);
}
}
}
// trick the compiler to not optimize away the loop above
if (sum == Coord<3>(1, 2, 3)) {
std::cout << "whatever";
}
}
return seconds;
}
std::string unit()
{
return "s";
}
};
class CoordEnumerationBronze : public CPUBenchmark
{
public:
std::string family()
{
return "CoordEnumeration";
}
std::string species()
{
return "bronze";
}
double performance(std::vector<int> rawDim)
{
Coord<3> dim(rawDim[0], rawDim[1], rawDim[2]);
Region<3> region;
for (int z = 0; z < dim.z(); ++z) {
for (int y = 0; y < dim.y(); ++y) {
region << Streak<3>(Coord<3>(0, y, z), dim.x());
}
}
double seconds = 0;
{
ScopedTimer t(&seconds);
Coord<3> sum;
for (Region<3>::Iterator i = region.begin(); i != region.end(); ++i) {
sum += *i;
}
// trick the compiler to not optimize away the loop above
if (sum == Coord<3>(1, 2, 3)) {
std::cout << "whatever";
}
}
return seconds;
}
std::string unit()
{
return "s";
}
};
class CoordEnumerationGold : public CPUBenchmark
{
public:
std::string family()
{
return "CoordEnumeration";
}
std::string species()
{
return "gold";
}
double performance(std::vector<int> rawDim)
{
Coord<3> dim(rawDim[0], rawDim[1], rawDim[2]);
Region<3> region;
for (int z = 0; z < dim.z(); ++z) {
for (int y = 0; y < dim.y(); ++y) {
region << Streak<3>(Coord<3>(0, y, z), dim.x());
}
}
double seconds = 0;
{
ScopedTimer t(&seconds);
Coord<3> sum;
for (Region<3>::StreakIterator i = region.beginStreak(); i != region.endStreak(); ++i) {
Coord<3> c = i->origin;
for (; c.x() < i->endX; c.x() += 1) {
sum += c;
}
}
// trick the compiler to not optimize away the loop above
if (sum == Coord<3>(1, 2, 3)) {
std::cout << "whatever";
}
}
return seconds;
}
std::string unit()
{
return "s";
}
};
class FloatCoordAccumulationGold : public CPUBenchmark
{
public:
std::string family()
{
return "FloatCoordAccumulation";
}
std::string species()
{
return "gold";
}
double performance(std::vector<int> rawDim)
{
Coord<3> dim(rawDim[0], rawDim[1], rawDim[2]);
double seconds = 0;
{
ScopedTimer t(&seconds);
FloatCoord<3> sum;
for (int z = 0; z < dim.z(); ++z) {
for (int y = 0; y < dim.y(); ++y) {
for (int x = 0; x < dim.x(); ++x) {
FloatCoord<3> addent(x, y, z);
sum += addent;
}
}
}
// trick the compiler to not optimize away the loop above
if (sum == FloatCoord<3>(1, 2, 3)) {
std::cout << "whatever";
}
}
return seconds;
}
std::string unit()
{
return "s";
}
};
class Jacobi3DVanilla : public CPUBenchmark
{
public:
std::string family()
{
return "Jacobi3D";
}
std::string species()
{
return "vanilla";
}
double performance(std::vector<int> rawDim)
{
Coord<3> dim(rawDim[0], rawDim[1], rawDim[2]);
int dimX = dim.x();
int dimY = dim.y();
int dimZ = dim.z();
int offsetZ = dimX * dimY;
int maxT = 20;
double *gridOld = new double[dimX * dimY * dimZ];
double *gridNew = new double[dimX * dimY * dimZ];
for (int z = 0; z < dimZ; ++z) {
for (int y = 0; y < dimY; ++y) {
for (int x = 0; x < dimY; ++x) {
gridOld[z * offsetZ + y * dimY + x] = x + y + z;
gridNew[z * offsetZ + y * dimY + x] = x + y + z;
}
}
}
double seconds = 0;
{
ScopedTimer t(&seconds);
for (int t = 0; t < maxT; ++t) {
for (int z = 1; z < (dimZ - 1); ++z) {
for (int y = 1; y < (dimY - 1); ++y) {
for (int x = 1; x < (dimX - 1); ++x) {
gridNew[z * offsetZ + y * dimY + x] =
(gridOld[z * offsetZ + y * dimX + x - offsetZ] +
gridOld[z * offsetZ + y * dimX + x - dimX] +
gridOld[z * offsetZ + y * dimX + x - 1] +
gridOld[z * offsetZ + y * dimX + x + 0] +
gridOld[z * offsetZ + y * dimX + x + 1] +
gridOld[z * offsetZ + y * dimX + x + dimX] +
gridOld[z * offsetZ + y * dimX + x + offsetZ]) * (1.0 / 7.0);
}
}
}
}
}
if (gridOld[offsetZ + dimX + 1] == 4711) {
std::cout << "this statement just serves to prevent the compiler from"
<< "optimizing away the loops above\n";
}
Coord<3> actualDim = dim - Coord<3>(2, 2, 2);
double updates = 1.0 * maxT * actualDim.prod();
double gLUPS = 1e-9 * updates / seconds;
delete[] gridOld;
delete[] gridNew;
return gLUPS;
}
std::string unit()
{
return "GLUPS";
}
};
class Jacobi3DSSE : public CPUBenchmark
{
public:
std::string family()
{
return "Jacobi3D";
}
std::string species()
{
return "pepper";
}
double performance(std::vector<int> rawDim)
{
Coord<3> dim(rawDim[0], rawDim[1], rawDim[2]);
int dimX = dim.x();
int dimY = dim.y();
int dimZ = dim.z();
int offsetZ = dimX * dimY;
int maxT = 20;
double *gridOld = new double[dimX * dimY * dimZ];
double *gridNew = new double[dimX * dimY * dimZ];
for (int z = 0; z < dimZ; ++z) {
for (int y = 0; y < dimY; ++y) {
for (int x = 0; x < dimY; ++x) {
gridOld[z * offsetZ + y * dimY + x] = x + y + z;
gridNew[z * offsetZ + y * dimY + x] = x + y + z;
}
}
}
double seconds = 0;
{
ScopedTimer t(&seconds);
for (int t = 0; t < maxT; ++t) {
for (int z = 1; z < (dimZ - 1); ++z) {
for (int y = 1; y < (dimY - 1); ++y) {
updateLine(&gridNew[z * offsetZ + y * dimY + 0],
&gridOld[z * offsetZ + y * dimX - offsetZ],
&gridOld[z * offsetZ + y * dimX - dimX],
&gridOld[z * offsetZ + y * dimX + 0],
&gridOld[z * offsetZ + y * dimX + dimX],
&gridOld[z * offsetZ + y * dimX + offsetZ],
1,
dimX - 1);
}
}
}
}
if (gridOld[offsetZ + dimX + 1] == 4711) {
std::cout << "this statement just serves to prevent the compiler from"
<< "optimizing away the loops above\n";
}
Coord<3> actualDim = dim - Coord<3>(2, 2, 2);
double updates = 1.0 * maxT * actualDim.prod();
double gLUPS = 1e-9 * updates / seconds;
delete[] gridOld;
delete[] gridNew;
return gLUPS;
}
std::string unit()
{
return "GLUPS";
}
private:
void updateLine(
double *target,
double *south,
double *top,
double *same,
double *bottom,
double *north,
int startX,
int endX)
{
int x = startX;
if ((x % 2) == 1) {
updatePoint(target, south, top, same, bottom, north, x);
++x;
}
__m128d oneSeventh = _mm_set_pd(1.0/7.0, 1.0/7.0);
__m128d same1 = _mm_load_pd(same + x + 0);
__m128d odds0 = _mm_loadu_pd(same + x - 1);
for (; x < (endX - 7); x += 8) {
__m128d same2 = _mm_load_pd(same + x + 2);
__m128d same3 = _mm_load_pd(same + x + 4);
__m128d same4 = _mm_load_pd(same + x + 6);
__m128d same5 = _mm_load_pd(same + x + 8);
// shuffle values obtain left/right neighbors
__m128d odds1 = _mm_shuffle_pd(same1, same2, (1 << 0) | (0 << 2));
__m128d odds2 = _mm_shuffle_pd(same2, same3, (1 << 0) | (0 << 2));
__m128d odds3 = _mm_shuffle_pd(same3, same4, (1 << 0) | (0 << 2));
__m128d odds4 = _mm_shuffle_pd(same4, same5, (1 << 0) | (0 << 2));
// load south neighbors
__m128d buf0 = _mm_load_pd(south + x + 0);
__m128d buf1 = _mm_load_pd(south + x + 2);
__m128d buf2 = _mm_load_pd(south + x + 4);
__m128d buf3 = _mm_load_pd(south + x + 6);
// add left neighbors
same1 = _mm_add_pd(same1, odds0);
same2 = _mm_add_pd(same2, odds1);
same3 = _mm_add_pd(same3, odds2);
same4 = _mm_add_pd(same4, odds3);
// add right neighbors
same1 = _mm_add_pd(same1, odds1);
same2 = _mm_add_pd(same2, odds2);
same3 = _mm_add_pd(same3, odds3);
same4 = _mm_add_pd(same4, odds4);
// load top neighbors
odds0 = _mm_load_pd(top + x + 0);
odds1 = _mm_load_pd(top + x + 2);
odds2 = _mm_load_pd(top + x + 4);
odds3 = _mm_load_pd(top + x + 6);
// add south neighbors
same1 = _mm_add_pd(same1, buf0);
same2 = _mm_add_pd(same2, buf1);
same3 = _mm_add_pd(same3, buf2);
same4 = _mm_add_pd(same4, buf3);
// load bottom neighbors
buf0 = _mm_load_pd(bottom + x + 0);
buf1 = _mm_load_pd(bottom + x + 2);
buf2 = _mm_load_pd(bottom + x + 4);
buf3 = _mm_load_pd(bottom + x + 6);
// add top neighbors
same1 = _mm_add_pd(same1, odds0);
same2 = _mm_add_pd(same2, odds1);
same3 = _mm_add_pd(same3, odds2);
same4 = _mm_add_pd(same4, odds3);
// load north neighbors
odds0 = _mm_load_pd(north + x + 0);
odds1 = _mm_load_pd(north + x + 2);
odds2 = _mm_load_pd(north + x + 4);
odds3 = _mm_load_pd(north + x + 6);
// add bottom neighbors
same1 = _mm_add_pd(same1, buf0);
same2 = _mm_add_pd(same2, buf1);
same3 = _mm_add_pd(same3, buf2);
same4 = _mm_add_pd(same4, buf3);
// add north neighbors
same1 = _mm_add_pd(same1, odds0);
same2 = _mm_add_pd(same2, odds1);
same3 = _mm_add_pd(same3, odds2);
same4 = _mm_add_pd(same4, odds3);
// scale by 1/7
same1 = _mm_mul_pd(same1, oneSeventh);
same2 = _mm_mul_pd(same2, oneSeventh);
same3 = _mm_mul_pd(same3, oneSeventh);
same4 = _mm_mul_pd(same4, oneSeventh);
// store results
_mm_store_pd(target + x + 0, same1);
_mm_store_pd(target + x + 2, same2);
_mm_store_pd(target + x + 4, same3);
_mm_store_pd(target + x + 6, same4);
odds0 = odds4;
same1 = same5;
}
for (; x < endX; ++x) {
updatePoint(target, south, top, same, bottom, north, x);
}
}
void updatePoint(
double *target,
double *south,
double *top,
double *same,
double *bottom,
double *north,
int x)
{
target[x] =
(south[x] +
top[x] +
same[x - 1] + same[x + 0] + same[x + 1] +
bottom[x] +
north[x]) * (1.0 / 7.0);
}
};
template<typename CELL>
class NoOpInitializer : public SimpleInitializer<CELL>
{
public:
typedef typename SimpleInitializer<CELL>::Topology Topology;
NoOpInitializer(
const Coord<3>& dimensions,
unsigned steps) :
SimpleInitializer<CELL>(dimensions, steps)
{}
virtual void grid(GridBase<CELL, Topology::DIM> *target)
{}
};
class JacobiCellClassic
{
public:
class API :
public APITraits::HasStencil<Stencils::VonNeumann<3, 1> >,
public APITraits::HasCubeTopology<3>
{};
explicit JacobiCellClassic(double t = 0) :
temp(t)
{}
template<typename NEIGHBORHOOD>
void update(const NEIGHBORHOOD& hood, int /* nanoStep */)
{
temp = (hood[Coord<3>( 0, 0, -1)].temp +
hood[Coord<3>( 0, -1, 0)].temp +
hood[Coord<3>(-1, 0, 0)].temp +
hood[Coord<3>( 0, 0, 0)].temp +
hood[Coord<3>( 1, 0, 0)].temp +
hood[Coord<3>( 0, 1, 0)].temp +
hood[Coord<3>( 0, 0, 1)].temp) * (1.0 / 7.0);
}
double temp;
};
class Jacobi3DClassic : public CPUBenchmark
{
public:
std::string family()
{
return "Jacobi3D";
}
std::string species()
{
return "bronze";
}
double performance(std::vector<int> rawDim)
{
Coord<3> dim(rawDim[0], rawDim[1], rawDim[2]);
int maxT = 5;
SerialSimulator<JacobiCellClassic> sim(
new NoOpInitializer<JacobiCellClassic>(dim, maxT));
double seconds = 0;
{
ScopedTimer t(&seconds);
sim.run();
}
if (sim.getGrid()->get(Coord<3>(1, 1, 1)).temp == 4711) {
std::cout << "this statement just serves to prevent the compiler from"
<< "optimizing away the loops above\n";
}
double updates = 1.0 * maxT * dim.prod();
double gLUPS = 1e-9 * updates / seconds;
return gLUPS;
}
std::string unit()
{
return "GLUPS";
}
};
class JacobiCellFixedHood
{
public:
class API :
public APITraits::HasFixedCoordsOnlyUpdate,
public APITraits::HasStencil<Stencils::VonNeumann<3, 1> >,
public APITraits::HasCubeTopology<3>
{};
explicit JacobiCellFixedHood(double t = 0) :
temp(t)
{}
template<typename NEIGHBORHOOD>
void update(const NEIGHBORHOOD& hood, int /* nanoStep */)
{
temp = (hood[FixedCoord< 0, 0, -1>()].temp +
hood[FixedCoord< 0, -1, 0>()].temp +
hood[FixedCoord<-1, 0, 0>()].temp +
hood[FixedCoord< 0, 0, 0>()].temp +
hood[FixedCoord< 1, 0, 0>()].temp +
hood[FixedCoord< 0, 1, 0>()].temp +
hood[FixedCoord< 0, 0, 1>()].temp) * (1.0 / 7.0);
}
double temp;
};
class Jacobi3DFixedHood : public CPUBenchmark
{
public:
std::string family()
{
return "Jacobi3D";
}
std::string species()
{
return "silver";
}
double performance(std::vector<int> rawDim)
{
Coord<3> dim(rawDim[0], rawDim[1], rawDim[2]);
int maxT = 20;
SerialSimulator<JacobiCellFixedHood> sim(
new NoOpInitializer<JacobiCellFixedHood>(dim, maxT));
double seconds = 0;
{
ScopedTimer t(&seconds);
sim.run();
}
if (sim.getGrid()->get(Coord<3>(1, 1, 1)).temp == 4711) {
std::cout << "this statement just serves to prevent the compiler from"
<< "optimizing away the loops above\n";
}
double updates = 1.0 * maxT * dim.prod();
double gLUPS = 1e-9 * updates / seconds;
return gLUPS;
}
std::string unit()
{
return "GLUPS";
}
};
class QuadM128
{
public:
__m128d a;
__m128d b;
__m128d c;
__m128d d;
};
class PentaM128
{
public:
__m128d a;
__m128d b;
__m128d c;
__m128d d;
__m128d e;
};
class JacobiCellStreakUpdate
{
public:
class API :
public APITraits::HasFixedCoordsOnlyUpdate,
public APITraits::HasUpdateLineX,
public APITraits::HasStencil<Stencils::VonNeumann<3, 1> >,
public APITraits::HasCubeTopology<3>,
public APITraits::HasSoA
{};
explicit JacobiCellStreakUpdate(double t = 0) :
temp(t)
{}
template<typename HOOD_OLD, typename HOOD_NEW>
static void updateSingle(HOOD_OLD& hoodOld, HOOD_NEW& hoodNew)
{
hoodNew.temp() =
(hoodOld[FixedCoord<0, 0, -1>()].temp() +
hoodOld[FixedCoord<0, -1, 0>()].temp() +
hoodOld[FixedCoord<1, 0, 0>()].temp() +
hoodOld[FixedCoord<0, 0, 0>()].temp() +
hoodOld[FixedCoord<1, 0, 0>()].temp() +
hoodOld[FixedCoord<0, 1, 0>()].temp() +
hoodOld[FixedCoord<0, 0, 1>()].temp()) * (1.0 / 7.0);
}
template<typename HOOD_OLD, typename HOOD_NEW>
static void updateLineX(HOOD_OLD& hoodOld, int indexEnd,
HOOD_NEW& hoodNew, int /* nanoStep */)
{
if (hoodOld.index() % 2 == 1) {
updateSingle(hoodOld, hoodNew);
++hoodOld.index();
++hoodNew.index();
}
__m128d oneSeventh = _mm_set1_pd(1.0 / 7.0);
PentaM128 same;
same.a = _mm_load_pd( &hoodOld[FixedCoord< 0, 0, 0>()].temp());
__m128d odds0 = _mm_loadu_pd(&hoodOld[FixedCoord<-1, 0, 0>()].temp());
for (; hoodOld.index() < (indexEnd - 8 + 1); hoodOld.index() += 8, hoodNew.index() += 8) {
load(&same, hoodOld, FixedCoord<0, 0, 0>());
// shuffle values obtain left/right neighbors
__m128d odds1 = _mm_shuffle_pd(same.a, same.b, (1 << 0) | (0 << 2));
__m128d odds2 = _mm_shuffle_pd(same.b, same.c, (1 << 0) | (0 << 2));
__m128d odds3 = _mm_shuffle_pd(same.c, same.d, (1 << 0) | (0 << 2));
__m128d odds4 = _mm_shuffle_pd(same.d, same.e, (1 << 0) | (0 << 2));
// load south neighbors
QuadM128 buf;
load(&buf, hoodOld, FixedCoord<0, 0, -1>());
// add left neighbors
same.a = _mm_add_pd(same.a, odds0);
same.b = _mm_add_pd(same.b, odds1);
same.c = _mm_add_pd(same.c, odds2);
same.d = _mm_add_pd(same.d, odds3);
// add right neighbors
same.a = _mm_add_pd(same.a, odds1);
same.b = _mm_add_pd(same.b, odds2);
same.c = _mm_add_pd(same.c, odds3);
same.d = _mm_add_pd(same.d, odds4);
// load top neighbors
odds0 = load<0>(hoodOld, FixedCoord< 0, -1, 0>());
odds1 = load<2>(hoodOld, FixedCoord< 0, -1, 0>());
odds2 = load<4>(hoodOld, FixedCoord< 0, -1, 0>());
odds3 = load<6>(hoodOld, FixedCoord< 0, -1, 0>());
// add south neighbors
same.a = _mm_add_pd(same.a, buf.a);
same.b = _mm_add_pd(same.b, buf.b);
same.c = _mm_add_pd(same.c, buf.c);
same.d = _mm_add_pd(same.d, buf.d);
// load bottom neighbors
load(&buf, hoodOld, FixedCoord<0, 1, 0>());
// add top neighbors
same.a = _mm_add_pd(same.a, odds0);
same.b = _mm_add_pd(same.b, odds1);
same.c = _mm_add_pd(same.c, odds2);
same.d = _mm_add_pd(same.d, odds3);
// load north neighbors
odds0 = load<0>(hoodOld, FixedCoord< 0, 0, 1>());
odds1 = load<2>(hoodOld, FixedCoord< 0, 0, 1>());
odds2 = load<4>(hoodOld, FixedCoord< 0, 0, 1>());
odds3 = load<6>(hoodOld, FixedCoord< 0, 0, 1>());
// add bottom neighbors
same.a = _mm_add_pd(same.a, buf.a);
same.b = _mm_add_pd(same.b, buf.b);
same.c = _mm_add_pd(same.c, buf.c);
same.d = _mm_add_pd(same.d, buf.d);
// add north neighbors
same.a = _mm_add_pd(same.a, odds0);
same.b = _mm_add_pd(same.b, odds1);
same.c = _mm_add_pd(same.c, odds2);
same.d = _mm_add_pd(same.d, odds3);
// scale by 1/7
same.a = _mm_mul_pd(same.a, oneSeventh);
same.b = _mm_mul_pd(same.b, oneSeventh);
same.c = _mm_mul_pd(same.c, oneSeventh);
same.d = _mm_mul_pd(same.d, oneSeventh);
// store results
_mm_store_pd(&hoodNew[LibFlatArray::coord<0, 0, 0>()].temp(), same.a);
_mm_store_pd(&hoodNew[LibFlatArray::coord<2, 0, 0>()].temp(), same.b);
_mm_store_pd(&hoodNew[LibFlatArray::coord<4, 0, 0>()].temp(), same.c);
_mm_store_pd(&hoodNew[LibFlatArray::coord<6, 0, 0>()].temp(), same.d);
// cycle members
odds0 = odds4;
same.a = same.e;
}
for (; hoodOld.index() < indexEnd; ++hoodOld.index(), ++hoodNew.index()) {
updateSingle(hoodOld, hoodNew);
}
}
template<typename NEIGHBORHOOD, int X, int Y, int Z>
static void load(QuadM128 *q, const NEIGHBORHOOD& hood, FixedCoord<X, Y, Z> coord)
{
q->a = load<0>(hood, coord);
q->b = load<2>(hood, coord);
q->c = load<4>(hood, coord);
q->d = load<6>(hood, coord);
}
template<typename NEIGHBORHOOD, int X, int Y, int Z>
static void load(PentaM128 *q, const NEIGHBORHOOD& hood, FixedCoord<X, Y, Z> coord)
{
q->b = load<2>(hood, coord);
q->c = load<4>(hood, coord);
q->d = load<6>(hood, coord);
q->e = load<8>(hood, coord);
}
template<int OFFSET, typename NEIGHBORHOOD, int X, int Y, int Z>
static __m128d load(const NEIGHBORHOOD& hood, FixedCoord<X, Y, Z> coord)
{
return load<OFFSET>(&hood[coord].temp());
}
template<int OFFSET>
static __m128d load(const double *p)
{
return _mm_load_pd(p + OFFSET);
}
double temp;
};
LIBFLATARRAY_REGISTER_SOA(
JacobiCellStreakUpdate,
((double)(temp))
)
class Jacobi3DStreakUpdate : public CPUBenchmark
{
public:
std::string family()
{
return "Jacobi3D";
}
std::string species()
{
return "gold";
}
double performance(std::vector<int> rawDim)
{
using std::swap;
Coord<3> dim(rawDim[0], rawDim[1], rawDim[2]);
typedef SoAGrid<
JacobiCellStreakUpdate,
APITraits::SelectTopology<JacobiCellStreakUpdate>::Value> GridType;
Coord<3> topoDim = dim + Coord<3>(2, 2, 2);
CoordBox<3> box(Coord<3>(), topoDim);
GridType gridA(box, JacobiCellStreakUpdate(1.0));
GridType gridB(box, JacobiCellStreakUpdate(2.0));
GridType *gridOld = &gridA;
GridType *gridNew = &gridB;
int maxT = 20;
Region<3> region;
region << CoordBox<3>(Coord<3>(), dim);
double seconds = 0;
{
ScopedTimer t(&seconds);
for (int t = 0; t < maxT; ++t) {
typedef UpdateFunctorHelpers::Selector<
JacobiCellStreakUpdate>::SoARegionUpdateHelper<
UpdateFunctorHelpers::ConcurrencyNoP, APITraits::SelectThreadedUpdate<void>::Value> Updater;
Coord<3> offset(1, 1, 1);
Updater updater(®ion, &offset, &offset, &box.dimensions, &box.dimensions, &topoDim, 0, 0, 0);
gridNew->callback(gridOld, updater);
swap(gridOld, gridNew);
}
}
if (gridA.get(Coord<3>(1, 1, 1)).temp == 4711) {
std::cout << "this statement just serves to prevent the compiler from"
<< "optimizing away the loops above\n";
}
double updates = 1.0 * maxT * dim.prod();
double gLUPS = 1e-9 * updates / seconds;
return gLUPS;
}
std::string unit()
{
return "GLUPS";
}
};
class Jacobi3DStreakUpdateFunctor : public CPUBenchmark
{
public:
std::string family()
{
return "Jacobi3D";
}
std::string species()
{
return "platinum";
}
double performance(std::vector<int> rawDim)
{
Coord<3> dim(rawDim[0], rawDim[1], rawDim[2]);
int maxT = 20;
SerialSimulator<JacobiCellStreakUpdate> sim(
new NoOpInitializer<JacobiCellStreakUpdate>(dim, maxT));
double seconds = 0;
{
ScopedTimer t(&seconds);
sim.run();
}
if (sim.getGrid()->get(Coord<3>(1, 1, 1)).temp == 4711) {
std::cout << "this statement just serves to prevent the compiler from"
<< "optimizing away the loops above\n";
}
double updates = 1.0 * maxT * dim.prod();
double gLUPS = 1e-9 * updates / seconds;
return gLUPS;
}
std::string unit()
{
return "GLUPS";
}
};
class LBMCell
{
public:
class API :
public APITraits::HasStencil<Stencils::Moore<3, 1> >,
public APITraits::HasCubeTopology<3>
{};
enum State {LIQUID, WEST_NOSLIP, EAST_NOSLIP, TOP, BOTTOM, NORTH_ACC, SOUTH_NOSLIP};
#define C 0
#define N 1
#define E 2
#define W 3
#define S 4
#define T 5
#define B 6
#define NW 7
#define SW 8
#define NE 9
#define SE 10
#define TW 11
#define BW 12
#define TE 13
#define BE 14
#define TN 15
#define BN 16
#define TS 17
#define BS 18
inline explicit LBMCell(double v = 1.0, State s = LIQUID) :
state(s)
{
comp[C] = v;
for (int i = 1; i < 19; ++i) {
comp[i] = 0.0;
}
density = 1.0;
}
template<typename COORD_MAP>
void update(const COORD_MAP& neighborhood, const unsigned /* nanoStep */)
{
*this = neighborhood[FixedCoord<0, 0>()];
switch (state) {
case LIQUID:
updateFluid(neighborhood);
break;
case WEST_NOSLIP:
updateWestNoSlip(neighborhood);
break;
case EAST_NOSLIP:
updateEastNoSlip(neighborhood);
break;
case TOP :
updateTop(neighborhood);
break;
case BOTTOM:
updateBottom(neighborhood);
break;
case NORTH_ACC:
updateNorthAcc(neighborhood);
break;
case SOUTH_NOSLIP:
updateSouthNoSlip(neighborhood);
break;
}
}
template<typename COORD_MAP>
void updateFluid(const COORD_MAP& neighborhood)
{
#define GET_COMP(X, Y, Z, COMP) neighborhood[Coord<3>(X, Y, Z)].comp[COMP]
#define SQR(X) ((X)*(X))
const double omega = 1.0/1.7;
const double omega_trm = 1.0 - omega;
const double omega_w0 = 3.0 * 1.0 / 3.0 * omega;
const double omega_w1 = 3.0*1.0/18.0*omega;
const double omega_w2 = 3.0*1.0/36.0*omega;
const double one_third = 1.0 / 3.0;
const int x = 0;
const int y = 0;
const int z = 0;
double velX, velY, velZ;
velX =
GET_COMP(x-1,y,z,E) + GET_COMP(x-1,y-1,z,NE) +
GET_COMP(x-1,y+1,z,SE) + GET_COMP(x-1,y,z-1,TE) +
GET_COMP(x-1,y,z+1,BE);
velY = GET_COMP(x,y-1,z,N) + GET_COMP(x+1,y-1,z,NW) +
GET_COMP(x,y-1,z-1,TN) + GET_COMP(x,y-1,z+1,BN);
velZ = GET_COMP(x,y,z-1,T) + GET_COMP(x,y+1,z-1,TS) +
GET_COMP(x+1,y,z-1,TW);
const double rho =
GET_COMP(x,y,z,C) + GET_COMP(x,y+1,z,S) +
GET_COMP(x+1,y,z,W) + GET_COMP(x,y,z+1,B) +
GET_COMP(x+1,y+1,z,SW) + GET_COMP(x,y+1,z+1,BS) +
GET_COMP(x+1,y,z+1,BW) + velX + velY + velZ;
velX = velX
- GET_COMP(x+1,y,z,W) - GET_COMP(x+1,y-1,z,NW)
- GET_COMP(x+1,y+1,z,SW) - GET_COMP(x+1,y,z-1,TW)
- GET_COMP(x+1,y,z+1,BW);
velY = velY
+ GET_COMP(x-1,y-1,z,NE) - GET_COMP(x,y+1,z,S)
- GET_COMP(x+1,y+1,z,SW) - GET_COMP(x-1,y+1,z,SE)
- GET_COMP(x,y+1,z-1,TS) - GET_COMP(x,y+1,z+1,BS);
velZ = velZ+GET_COMP(x,y-1,z-1,TN) + GET_COMP(x-1,y,z-1,TE) - GET_COMP(x,y,z+1,B) - GET_COMP(x,y-1,z+1,BN) - GET_COMP(x,y+1,z+1,BS) - GET_COMP(x+1,y,z+1,BW) - GET_COMP(x-1,y,z+1,BE);
density = rho;
velocityX = velX;
velocityX = velX;
velocityY = velY;
velocityZ = velZ;
const double dir_indep_trm = one_third*rho - 0.5*( velX*velX + velY*velY + velZ*velZ );
comp[C]=omega_trm * GET_COMP(x,y,z,C) + omega_w0*( dir_indep_trm );
comp[NW]=omega_trm * GET_COMP(x+1,y-1,z,NW) +
omega_w2*( dir_indep_trm - ( velX-velY ) + 1.5*SQR( velX-velY ) );
comp[SE]=omega_trm * GET_COMP(x-1,y+1,z,SE) +
omega_w2*( dir_indep_trm + ( velX-velY ) + 1.5*SQR( velX-velY ) );
comp[NE]=omega_trm * GET_COMP(x-1,y-1,z,NE) +
omega_w2*( dir_indep_trm + ( velX+velY ) + 1.5*SQR( velX+velY ) );
comp[SW]=omega_trm * GET_COMP(x+1,y+1,z,SW) +
omega_w2*( dir_indep_trm - ( velX+velY ) + 1.5*SQR( velX+velY ) );
comp[TW]=omega_trm * GET_COMP(x+1,y,z-1,TW) + omega_w2*( dir_indep_trm - ( velX-velZ ) + 1.5*SQR( velX-velZ ) );
comp[BE]=omega_trm * GET_COMP(x-1,y,z+1,BE) + omega_w2*( dir_indep_trm + ( velX-velZ ) + 1.5*SQR( velX-velZ ) );
comp[TE]=omega_trm * GET_COMP(x-1,y,z-1,TE) + omega_w2*( dir_indep_trm + ( velX+velZ ) + 1.5*SQR( velX+velZ ) );
comp[BW]=omega_trm * GET_COMP(x+1,y,z+1,BW) + omega_w2*( dir_indep_trm - ( velX+velZ ) + 1.5*SQR( velX+velZ ) );
comp[TS]=omega_trm * GET_COMP(x,y+1,z-1,TS) + omega_w2*( dir_indep_trm - ( velY-velZ ) + 1.5*SQR( velY-velZ ) );
comp[BN]=omega_trm * GET_COMP(x,y-1,z+1,BN) + omega_w2*( dir_indep_trm + ( velY-velZ ) + 1.5*SQR( velY-velZ ) );
comp[TN]=omega_trm * GET_COMP(x,y-1,z-1,TN) + omega_w2*( dir_indep_trm + ( velY+velZ ) + 1.5*SQR( velY+velZ ) );
comp[BS]=omega_trm * GET_COMP(x,y+1,z+1,BS) + omega_w2*( dir_indep_trm - ( velY+velZ ) + 1.5*SQR( velY+velZ ) );
comp[N]=omega_trm * GET_COMP(x,y-1,z,N) + omega_w1*( dir_indep_trm + velY + 1.5*SQR(velY));
comp[S]=omega_trm * GET_COMP(x,y+1,z,S) + omega_w1*( dir_indep_trm - velY + 1.5*SQR(velY));
comp[E]=omega_trm * GET_COMP(x-1,y,z,E) + omega_w1*( dir_indep_trm + velX + 1.5*SQR(velX));
comp[W]=omega_trm * GET_COMP(x+1,y,z,W) + omega_w1*( dir_indep_trm - velX + 1.5*SQR(velX));
comp[T]=omega_trm * GET_COMP(x,y,z-1,T) + omega_w1*( dir_indep_trm + velZ + 1.5*SQR(velZ));
comp[B]=omega_trm * GET_COMP(x,y,z+1,B) + omega_w1*( dir_indep_trm - velZ + 1.5*SQR(velZ));
}
template<typename COORD_MAP>
void updateWestNoSlip(const COORD_MAP& neighborhood)
{
comp[E ]=GET_COMP(1, 0, 0, W);
comp[NE]=GET_COMP(1, 1, 0, SW);
comp[SE]=GET_COMP(1,-1, 0, NW);
comp[TE]=GET_COMP(1, 0, 1, BW);
comp[BE]=GET_COMP(1, 0, -1, TW);
}
template<typename COORD_MAP>
void updateEastNoSlip(const COORD_MAP& neighborhood)
{
comp[W ]=GET_COMP(-1, 0, 0, E);
comp[NW]=GET_COMP(-1, 0, 1, SE);
comp[SW]=GET_COMP(-1,-1, 0, NE);
comp[TW]=GET_COMP(-1, 0, 1, BE);
comp[BW]=GET_COMP(-1, 0,-1, TE);
}
template<typename COORD_MAP>
void updateTop(const COORD_MAP& neighborhood)
{
comp[B] =GET_COMP(0,0,-1,T);
comp[BE]=GET_COMP(1,0,-1,TW);
comp[BW]=GET_COMP(-1,0,-1,TE);
comp[BN]=GET_COMP(0,1,-1,TS);
comp[BS]=GET_COMP(0,-1,-1,TN);
}
template<typename COORD_MAP>
void updateBottom(const COORD_MAP& neighborhood)
{
comp[T] =GET_COMP(0,0,1,B);
comp[TE]=GET_COMP(1,0,1,BW);
comp[TW]=GET_COMP(-1,0,1,BE);
comp[TN]=GET_COMP(0,1,1,BS);
comp[TS]=GET_COMP(0,-1,1,BN);
}
template<typename COORD_MAP>
void updateNorthAcc(const COORD_MAP& neighborhood)
{
const double w_1 = 0.01;
comp[S] =GET_COMP(0,-1,0,N);
comp[SE]=GET_COMP(1,-1,0,NW)+6*w_1*0.1;
comp[SW]=GET_COMP(-1,-1,0,NE)-6*w_1*0.1;
comp[TS]=GET_COMP(0,-1,1,BN);
comp[BS]=GET_COMP(0,-1,-1,TN);
}
template<typename COORD_MAP>
void updateSouthNoSlip(const COORD_MAP& neighborhood)
{
comp[N] =GET_COMP(0,1,0,S);
comp[NE]=GET_COMP(1,1,0,SW);
comp[NW]=GET_COMP(-1,1,0,SE);
comp[TN]=GET_COMP(0,1,1,BS);
comp[BN]=GET_COMP(0,1,-1,TS);
}
double comp[19];
double density;
double velocityX;
double velocityY;
double velocityZ;
State state;
#undef C
#undef N
#undef E
#undef W
#undef S
#undef T
#undef B
#undef NW
#undef SW
#undef NE
#undef SE
#undef TW
#undef BW
#undef TE
#undef BE
#undef TN
#undef BN
#undef TS
#undef BS
#undef GET_COMP
#undef SQR
};
class LBMSoACell
{
public:
typedef LibFlatArray::short_vec<double, 16> Double;
class API : public APITraits::HasFixedCoordsOnlyUpdate,
public APITraits::HasSoA,
public APITraits::HasUpdateLineX,
public APITraits::HasStencil<Stencils::Moore<3, 1> >,
public APITraits::HasCubeTopology<3>
{};
enum State {LIQUID, WEST_NOSLIP, EAST_NOSLIP, TOP, BOTTOM, NORTH_ACC, SOUTH_NOSLIP};
inline explicit LBMSoACell(double v=1.0, const State& s=LIQUID) :
C(v),
N(0),
E(0),
W(0),
S(0),
T(0),
B(0),
NW(0),
SW(0),
NE(0),
SE(0),
TW(0),
BW(0),
TE(0),
BE(0),
TN(0),
BN(0),
TS(0),
BS(0),
density(1.0),
velocityX(0),
velocityY(0),
velocityZ(0),
state(s)
{}
template<typename ACCESSOR1, typename ACCESSOR2>
static void updateLineX(
ACCESSOR1& hoodOld, int indexEnd,
ACCESSOR2& hoodNew, int nanoStep)
{
updateLineXFluid(hoodOld, indexEnd, hoodNew);
}
template<typename ACCESSOR1, typename ACCESSOR2>
static void updateLineXFluid(
ACCESSOR1& hoodOld, int indexEnd,
ACCESSOR2& hoodNew)
{
#define GET_COMP(X, Y, Z, COMP) Double(&hoodOld[FixedCoord<X, Y, Z>()].COMP())
#define SQR(X) ((X)*(X))
const Double omega = 1.0/1.7;
const Double omega_trm = Double(1.0) - omega;
const Double omega_w0 = Double(3.0 * 1.0 / 3.0) * omega;
const Double omega_w1 = Double(3.0*1.0/18.0)*omega;
const Double omega_w2 = Double(3.0*1.0/36.0)*omega;
const Double one_third = 1.0 / 3.0;
const Double one_half = 0.5;
const Double one_point_five = 1.5;
const int x = 0;
const int y = 0;
const int z = 0;
Double velX, velY, velZ;
for (; hoodOld.index() < indexEnd; hoodNew.index() += Double::ARITY, hoodOld.index() += Double::ARITY) {
velX =
GET_COMP(x-1,y,z,E) + GET_COMP(x-1,y-1,z,NE) +
GET_COMP(x-1,y+1,z,SE) + GET_COMP(x-1,y,z-1,TE) +
GET_COMP(x-1,y,z+1,BE);
velY =
GET_COMP(x,y-1,z,N) + GET_COMP(x+1,y-1,z,NW) +
GET_COMP(x,y-1,z-1,TN) + GET_COMP(x,y-1,z+1,BN);
velZ =
GET_COMP(x,y,z-1,T) + GET_COMP(x,y+1,z-1,TS) +
GET_COMP(x+1,y,z-1,TW);
const Double rho =
GET_COMP(x,y,z,C) + GET_COMP(x,y+1,z,S) +
GET_COMP(x+1,y,z,W) + GET_COMP(x,y,z+1,B) +
GET_COMP(x+1,y+1,z,SW) + GET_COMP(x,y+1,z+1,BS) +
GET_COMP(x+1,y,z+1,BW) + velX + velY + velZ;
velX = velX
- GET_COMP(x+1,y,z,W) - GET_COMP(x+1,y-1,z,NW)
- GET_COMP(x+1,y+1,z,SW) - GET_COMP(x+1,y,z-1,TW)
- GET_COMP(x+1,y,z+1,BW);
velY = velY
+ GET_COMP(x-1,y-1,z,NE) - GET_COMP(x,y+1,z,S)
- GET_COMP(x+1,y+1,z,SW) - GET_COMP(x-1,y+1,z,SE)
- GET_COMP(x,y+1,z-1,TS) - GET_COMP(x,y+1,z+1,BS);
velZ = velZ+GET_COMP(x,y-1,z-1,TN) + GET_COMP(x-1,y,z-1,TE) - GET_COMP(x,y,z+1,B) - GET_COMP(x,y-1,z+1,BN) - GET_COMP(x,y+1,z+1,BS) - GET_COMP(x+1,y,z+1,BW) - GET_COMP(x-1,y,z+1,BE);
&hoodNew.density() << rho;
&hoodNew.velocityX() << velX;
&hoodNew.velocityY() << velY;
&hoodNew.velocityZ() << velZ;
const Double dir_indep_trm = one_third*rho - one_half *( velX*velX + velY*velY + velZ*velZ );
&hoodNew.C() << (omega_trm * GET_COMP(x,y,z,C) + omega_w0 * dir_indep_trm );
&hoodNew.NW() << (omega_trm * GET_COMP(x+1,y-1,z,NW) + omega_w2*( dir_indep_trm - ( velX - velY ) + one_point_five * SQR( velX-velY ) ));
&hoodNew.SE() << (omega_trm * GET_COMP(x-1,y+1,z,SE) + omega_w2*( dir_indep_trm + ( velX - velY ) + one_point_five * SQR( velX-velY ) ));
&hoodNew.NE() << (omega_trm * GET_COMP(x-1,y-1,z,NE) + omega_w2*( dir_indep_trm + ( velX + velY ) + one_point_five * SQR( velX+velY ) ));
&hoodNew.SW() << (omega_trm * GET_COMP(x+1,y+1,z,SW) + omega_w2*( dir_indep_trm - ( velX + velY ) + one_point_five * SQR( velX+velY ) ));
&hoodNew.TW() << (omega_trm * GET_COMP(x+1,y,z-1,TW) + omega_w2*( dir_indep_trm - ( velX - velZ ) + one_point_five * SQR( velX-velZ ) ));
&hoodNew.BE() << (omega_trm * GET_COMP(x-1,y,z+1,BE) + omega_w2*( dir_indep_trm + ( velX - velZ ) + one_point_five * SQR( velX-velZ ) ));
&hoodNew.TE() << (omega_trm * GET_COMP(x-1,y,z-1,TE) + omega_w2*( dir_indep_trm + ( velX + velZ ) + one_point_five * SQR( velX+velZ ) ));
&hoodNew.BW() << (omega_trm * GET_COMP(x+1,y,z+1,BW) + omega_w2*( dir_indep_trm - ( velX + velZ ) + one_point_five * SQR( velX+velZ ) ));
&hoodNew.TS() << (omega_trm * GET_COMP(x,y+1,z-1,TS) + omega_w2*( dir_indep_trm - ( velY - velZ ) + one_point_five * SQR( velY-velZ ) ));
&hoodNew.BN() << (omega_trm * GET_COMP(x,y-1,z+1,BN) + omega_w2*( dir_indep_trm + ( velY - velZ ) + one_point_five * SQR( velY-velZ ) ));
&hoodNew.TN() << (omega_trm * GET_COMP(x,y-1,z-1,TN) + omega_w2*( dir_indep_trm + ( velY + velZ ) + one_point_five * SQR( velY+velZ ) ));
&hoodNew.BS() << (omega_trm * GET_COMP(x,y+1,z+1,BS) + omega_w2*( dir_indep_trm - ( velY + velZ ) + one_point_five * SQR( velY+velZ ) ));
&hoodNew.N() << (omega_trm * GET_COMP(x,y-1,z,N) + omega_w1*( dir_indep_trm + velY + one_point_five * SQR(velY)));
&hoodNew.S() << (omega_trm * GET_COMP(x,y+1,z,S) + omega_w1*( dir_indep_trm - velY + one_point_five * SQR(velY)));
&hoodNew.E() << (omega_trm * GET_COMP(x-1,y,z,E) + omega_w1*( dir_indep_trm + velX + one_point_five * SQR(velX)));
&hoodNew.W() << (omega_trm * GET_COMP(x+1,y,z,W) + omega_w1*( dir_indep_trm - velX + one_point_five * SQR(velX)));
&hoodNew.T() << (omega_trm * GET_COMP(x,y,z-1,T) + omega_w1*( dir_indep_trm + velZ + one_point_five * SQR(velZ)));
&hoodNew.B() << (omega_trm * GET_COMP(x,y,z+1,B) + omega_w1*( dir_indep_trm - velZ + one_point_five * SQR(velZ)));
}
}
double C;
double N;
double E;
double W;
double S;
double T;
double B;
double NW;
double SW;
double NE;
double SE;
double TW;
double BW;
double TE;
double BE;
double TN;
double BN;
double TS;
double BS;
double density;
double velocityX;
double velocityY;
double velocityZ;
State state;
};
LIBFLATARRAY_REGISTER_SOA(
LBMSoACell,
((double)(C))
((double)(N))
((double)(E))
((double)(W))
((double)(S))
((double)(T))
((double)(B))
((double)(NW))
((double)(SW))
((double)(NE))
((double)(SE))
((double)(TW))
((double)(BW))
((double)(TE))
((double)(BE))
((double)(TN))
((double)(BN))
((double)(TS))
((double)(BS))
((double)(density))
((double)(velocityX))
((double)(velocityY))
((double)(velocityZ))
((LBMSoACell::State)(state))
)
class LBMClassic : public CPUBenchmark
{
public:
std::string family()
{
return "LBM";
}
std::string species()
{
return "bronze";
}
double performance(std::vector<int> rawDim)
{
Coord<3> dim(rawDim[0], rawDim[1], rawDim[2]);
int maxT = 20;
SerialSimulator<LBMCell> sim(
new NoOpInitializer<LBMCell>(dim, maxT));
double seconds = 0;
{
ScopedTimer t(&seconds);
sim.run();
}
if (sim.getGrid()->get(Coord<3>(1, 1, 1)).density == 4711) {
std::cout << "this statement just serves to prevent the compiler from"
<< "optimizing away the loops above\n";
}
double updates = 1.0 * maxT * dim.prod();
double gLUPS = 1e-9 * updates / seconds;
return gLUPS;
}
std::string unit()
{
return "GLUPS";
}
};
class LBMSoA : public CPUBenchmark
{
public:
std::string family()
{
return "LBM";
}
std::string species()
{
return "gold";
}
double performance(std::vector<int> rawDim)
{
Coord<3> dim(rawDim[0], rawDim[1], rawDim[2]);
int maxT = 200;
OpenMPSimulator<LBMSoACell> sim(
new NoOpInitializer<LBMSoACell>(dim, maxT));
double seconds = 0;
{
ScopedTimer t(&seconds);
sim.run();
}
if (sim.getGrid()->get(Coord<3>(1, 1, 1)).density == 4711) {
std::cout << "this statement just serves to prevent the compiler from"
<< "optimizing away the loops above\n";
}
double updates = 1.0 * maxT * dim.prod();
double gLUPS = 1e-9 * updates / seconds;
return gLUPS;
}
std::string unit()
{
return "GLUPS";
}
};
template<class PARTITION>
class PartitionBenchmark : public CPUBenchmark
{
public:
explicit PartitionBenchmark(const std::string& name) :
name(name)
{}
std::string species()
{
return "gold";
}
std::string family()
{
return name;
}
double performance(std::vector<int> rawDim)
{
Coord<3> dim(rawDim[0], rawDim[1], rawDim[2]);
double duration = 0;
Coord<2> accu;
Coord<2> realDim(dim.x(), dim.y());
{
ScopedTimer t(&duration);
PARTITION h(Coord<2>(100, 200), realDim);
typename PARTITION::Iterator end = h.end();
for (typename PARTITION::Iterator i = h.begin(); i != end; ++i) {
accu += *i;
}
}
if (accu == Coord<2>()) {
throw std::runtime_error("oops, partition iteration went bad!");
}
return duration;
}
std::string unit()
{
return "s";
}
private:
std::string name;
};
#ifdef LIBGEODECOMP_WITH_CPP14
typedef double ValueType;
const std::size_t MATRICES = 1;
const int C = 4; // AVX
const int SIGMA = 1;
typedef short_vec<ValueType, C> ShortVec;
class SPMVMCell
{
public:
class API :
public APITraits::HasUnstructuredTopology,
public APITraits::HasSellType<ValueType>,
public APITraits::HasSellMatrices<MATRICES>,
public APITraits::HasSellC<C>,
public APITraits::HasSellSigma<SIGMA>,
public APITraits::HasThreadedUpdate<1024>
{};
inline explicit SPMVMCell(double v = 8.0) :
value(v), sum(0)
{}
template<typename NEIGHBORHOOD>
void update(NEIGHBORHOOD& neighborhood, unsigned /* nanoStep */)
{
sum = 0.;
for (const auto& j: neighborhood.weights(0)) {
sum += neighborhood[j.first()].value * j.second();
}
}
double value;
double sum;
};
class SPMVMCellStreak
{
public:
class API :
public APITraits::HasUpdateLineX,
public APITraits::HasUnstructuredTopology,
public APITraits::HasSellType<ValueType>,
public APITraits::HasSellMatrices<MATRICES>,
public APITraits::HasSellC<C>,
public APITraits::HasSellSigma<SIGMA>,
public APITraits::HasThreadedUpdate<1024>
{};
inline explicit SPMVMCellStreak(double v = 8.0) :
value(v), sum(0)
{}
template<typename HOOD_NEW, typename HOOD_OLD>
static void updateLineX(HOOD_NEW& hoodNew, int indexEnd, HOOD_OLD& hoodOld, unsigned /* nanoStep */)
{
for (int i = hoodOld.index(); i < indexEnd; ++i, ++hoodOld) {
hoodNew[i].sum = 0.;
for (const auto& j: hoodOld.weights(0)) {
hoodNew[i].sum += hoodOld[j.first].value * j.second;
}
}
}
double value;
double sum;
};
class SPMVMSoACell
{
public:
class API :
public APITraits::HasSoA,
public APITraits::HasUpdateLineX,
public APITraits::HasUnstructuredTopology,
public APITraits::HasSellType<ValueType>,
public APITraits::HasSellMatrices<MATRICES>,
public APITraits::HasSellC<C>,
public APITraits::HasSellSigma<SIGMA>,
public APITraits::HasThreadedUpdate<1024>,
public LibFlatArray::api_traits::has_default_1d_sizes
{};
inline explicit SPMVMSoACell(double v = 8.0) :
value(v), sum(0)
{}
template<typename SHORT_VEC_TYPE, typename COUNTER_TYPE1, typename COUNTER_TYPE2, typename HOOD_OLD, typename HOOD_NEW>
static void updateBody(SHORT_VEC_TYPE /* shortVec */, COUNTER_TYPE1 *counter, const COUNTER_TYPE2& end, HOOD_OLD& hoodOld, HOOD_NEW& hoodNew)
{
typedef SHORT_VEC_TYPE ShortVec;
for (; hoodNew.index() < end; hoodNew += ShortVec::ARITY, ++hoodOld) {
ShortVec tmp;
tmp.load_aligned(&hoodNew->sum());
for (const auto& j: hoodOld.weights(0)) {
ShortVec weights, values;
weights.load_aligned(j.second());
values.gather(&hoodOld->value(), j.first());
tmp += values * weights;
}
tmp.store_aligned(&hoodNew->sum());
}
}
template<typename HOOD_NEW, typename HOOD_OLD>
static void updateLineX(HOOD_NEW& hoodNew, int indexEnd, HOOD_OLD& hoodOld, unsigned /* nanoStep */)
{
UNSTRUCTURED_LOOP_PEELER(ShortVec, long, &hoodNew.index(), indexEnd, HOOD_OLD, hoodOld, updateBody, hoodNew);
// fixme: use lambda again once CUDA supports C++14
// unstructuredLoopPeeler<ShortVec>(
// &hoodNew.index(),
// indexEnd,
// hoodOld,
// [&hoodNew](auto shortVec, auto *counter, auto end, auto& hoodOld) {
// typedef decltype(shortVec) ShortVec;
// for (; hoodNew.index() < end; hoodNew += ShortVec::ARITY, ++hoodOld) {
// ShortVec tmp;
// tmp.load_aligned(&hoodNew->sum());
// for (const auto& j: hoodOld.weights(0)) {
// ShortVec weights, values;
// weights.load_aligned(j.second());
// values.gather(&hoodOld->value(), j.first());
// tmp += values * weights;
// }
// tmp.store_aligned(&hoodNew->sum());
// }
// });
}
double value;
double sum;
};
LIBFLATARRAY_REGISTER_SOA(SPMVMSoACell, ((double)(sum))((double)(value)))
class SPMVMSoACellInf
{
public:
using REAL = ShortVec;
class API :
public APITraits::HasSoA,
public APITraits::HasUpdateLineX,
public APITraits::HasUnstructuredTopology,
public APITraits::HasSellType<ValueType>,
public APITraits::HasSellMatrices<MATRICES>,
public APITraits::HasSellC<C>,
public APITraits::HasSellSigma<SIGMA>,
public APITraits::HasThreadedUpdate<1024>,
public LibFlatArray::api_traits::has_default_1d_sizes
{};
inline explicit SPMVMSoACellInf(double v = 8.0) :
value(v), sum(0)
{}
template<typename SHORT_VEC_TYPE, typename COUNTER_TYPE1, typename COUNTER_TYPE2, typename HOOD_OLD, typename HOOD_NEW>
static void updateBody(SHORT_VEC_TYPE /* shortVec */, COUNTER_TYPE1 *counter, const COUNTER_TYPE2& end, HOOD_OLD& hoodOld, HOOD_NEW& hoodNew)
{
typedef SHORT_VEC_TYPE ShortVec;
ShortVec tmp, weights, values;
for (; hoodNew.index() < end; hoodNew += ShortVec::ARITY, ++hoodOld) {
tmp = &hoodNew->sum();
for (const auto& j: hoodOld.weights(0)) {
weights = j.second();
values.gather(&hoodOld->value(), j.first());
tmp += values * weights;
}
(&hoodNew->sum()) << tmp;
}
}
template<typename HOOD_NEW, typename HOOD_OLD>
static void updateLineX(HOOD_NEW& hoodNew, int indexEnd, HOOD_OLD& hoodOld, unsigned /* nanoStep */)
{
UNSTRUCTURED_LOOP_PEELER(ShortVec, long, &hoodNew.index(), indexEnd, HOOD_OLD, hoodOld, updateBody, hoodNew);
// fixme: use lambda again once CUDA supports C++14
// unstructuredLoopPeeler<ShortVec>(
// &hoodNew.index(),
// indexEnd,
// hoodOld,
// [&hoodNew](auto shortVec, auto *counter, auto end, auto& hoodOld) {
// typedef decltype(shortVec) ShortVec;
// ShortVec tmp, weights, values;
// for (; hoodNew.index() < end; hoodNew += ShortVec::ARITY, ++hoodOld) {
// tmp = &hoodNew->sum();
// for (const auto& j: hoodOld.weights(0)) {
// weights = j.second();
// values.gather(&hoodOld->value(), j.first());
// tmp += values * weights;
// }
// (&hoodNew->sum()) << tmp;
// }
// });
}
double value;
double sum;
};
LIBFLATARRAY_REGISTER_SOA(SPMVMSoACellInf, ((double)(sum))((double)(value)))
// setup a sparse matrix
template<typename CELL, typename GRID>
class SparseMatrixInitializer : public SimpleInitializer<CELL>
{
private:
int size;
public:
inline
SparseMatrixInitializer(const Coord<3>& dim, int maxT) :
SimpleInitializer<CELL>(Coord<1>(dim.x()), maxT),
size(dim.x())
{}
virtual void grid(GridBase<CELL, 1> *grid)
{
// setup sparse matrix
typename GridBase<CELL, 1>::SparseMatrix weights;
// setup matrix: immitate basic structure of MP_Geer matrix
// from Matrix Market:
// http://www.cise.ufl.edu/research/sparse/matrices/Janna/ML_Geer.html
for (int row = 0; row < size; ++row) {
double factor = 1.0 * row / size;
for (int i = -3400; i < -3385; ++i) {
int column = row + i;
if ((column >= 0) && (column < size)) {
weights << std::make_pair(Coord<2>(column, row), 1000.0 + 1.0 * factor + column);
}
}
for (int i = -20; i < 20; ++i) {
int column = row + i;
if ((column >= 0) && (column < size)) {
weights << std::make_pair(Coord<2>(column, row), 1000.0 + 1.0 * factor + column);
}
}
for (int i = 3385; i < 3400; ++i) {
int column = row + i;
if ((column >= 0) && (column < size)) {
weights << std::make_pair(Coord<2>(column, row), 1000.0 + 1.0 * factor + column);
}
}
}
grid->setWeights(0, weights);
// setup rhs: not needed, since the grid is intialized with default cells
// default value of SPMVMCell is 8.0
}
};
class SellMatrixInitializer : public CPUBenchmark
{
public:
std::string family()
{
return "SELLInit";
}
std::string species()
{
return "bronze";
}
double performance(std::vector<int> rawDim)
{
Coord<3> dim(rawDim[0], rawDim[1], rawDim[2]);
const Coord<1> dim1d(dim.x());
const int size = dim.x();
UnstructuredGrid<SPMVMCell, MATRICES, ValueType, C, SIGMA> grid(dim1d);
GridBase<SPMVMCell, 1>::SparseMatrix weights;
// setup matrix: ~1 % non zero entries
for (int row = 0; row < size; ++row) {
for (int col = 0; col < size / 100; ++col) {
weights << std::make_pair(Coord<2>(row, col * 100), 5.0);
}
}
double seconds = 0;
{
ScopedTimer t(&seconds);
grid.setWeights(0, weights);
}
if (grid.get(Coord<1>(1)).sum == 4711) {
std::cout << "this statement just serves to prevent the compiler from"
<< "optimizing away the loops above\n";
}
return seconds;
}
std::string unit()
{
return "s";
}
};
class SparseMatrixVectorMultiplication : public CPUBenchmark
{
public:
std::string family()
{
return "SPMVM";
}
std::string species()
{
return "bronze";
}
double performance(std::vector<int> rawDim)
{
Coord<3> dim(rawDim[0], rawDim[1], rawDim[2]);
// 1. create grids
typedef ReorderingUnstructuredGrid<UnstructuredGrid<SPMVMCell, MATRICES, ValueType, C, SIGMA> > Grid;
const Coord<1> size(dim.x());
Region<1> region;
region << CoordBox<1>(Coord<1>(), size);
Grid grid1(region);
// 2. init grid old
const int maxT = 3.0e8 / dim.x();
SparseMatrixInitializer<SPMVMCell, Grid> init(dim, maxT);
init.grid(&grid1);
Grid grid2 = grid1;
// 3. call updateFunctor()
double seconds = 0;
Streak<1> streak(Coord<1>(0), size.x());
UnstructuredUpdateFunctor<SPMVMCell> updateFunctor;
UpdateFunctorHelpers::ConcurrencyEnableOpenMP concurrencySpec(true, true);
APITraits::SelectThreadedUpdate<SPMVMCell>::Value threadedUpdateSpec;
{
ScopedTimer timer(&seconds);
Grid *gridOld = &grid1;
Grid *gridNew = &grid2;
for (int t = 0; t < maxT; ++t) {
using std::swap;
updateFunctor(region, *gridOld, gridNew, 0, concurrencySpec, threadedUpdateSpec);
swap(gridOld, gridNew);
}
}
if (grid1.get(Coord<1>(1)).sum == 4711) {
std::cout << "this statement just serves to prevent the compiler from"
<< "optimizing away the loops above\n";
}
const double entries = 40 * dim.x() + 30 * (dim.x() - 2 * 3400);
const double numOps = 2.0 * entries * maxT;
const double gflops = 1.0e-9 * numOps / seconds;
return gflops;
}
std::string unit()
{
return "GFLOP/s";
}
};
class SparseMatrixVectorMultiplicationVectorized : public CPUBenchmark
{
public:
std::string family()
{
return "SPMVM";
}
std::string species()
{
return "platinum";
}
double performance(std::vector<int> rawDim)
{
Coord<3> dim(rawDim[0], rawDim[1], rawDim[2]);
// 1. create grids
typedef UnstructuredSoAGrid<SPMVMSoACell, MATRICES, ValueType, C, SIGMA> Grid;
const Coord<1> size(dim.x());
Grid grid1(size);
// 2. init grid old
const int maxT = 3.0e8 / dim.x();
SparseMatrixInitializer<SPMVMSoACell, Grid> init(dim, maxT);
init.grid(&grid1);
Grid grid2 = grid1;
// 3. call updateFunctor()
double seconds = 0;
Region<1> region;
region << Streak<1>(Coord<1>(0), size.x());
UnstructuredUpdateFunctor<SPMVMSoACell> updateFunctor;
UpdateFunctorHelpers::ConcurrencyEnableOpenMP concurrencySpec(true, true);
APITraits::SelectThreadedUpdate<SPMVMSoACell>::Value threadedUpdateSpec;
{
ScopedTimer timer(&seconds);
Grid *gridOld = &grid1;
Grid *gridNew = &grid2;
for (int t = 0; t < maxT; ++t) {
using std::swap;
updateFunctor(region, *gridOld, gridNew, 0, concurrencySpec, threadedUpdateSpec);
swap(gridOld, gridNew);
}
}
if (grid1.get(Coord<1>(1)).sum == 4711) {
std::cout << "this statement just serves to prevent the compiler from"
<< "optimizing away the loops above\n";
}
const double entries = 40 * dim.x() + 30 * (dim.x() - 2 * 3400);
const double numOps = 2.0 * entries * maxT;
const double gflops = 1.0e-9 * numOps / seconds;
return gflops;
}
std::string unit()
{
return "GFLOP/s";
}
};
class SparseMatrixVectorMultiplicationVectorizedInf : public CPUBenchmark
{
public:
std::string family()
{
return "SPMVM";
}
std::string species()
{
return "gold";
}
double performance(std::vector<int> rawDim)
{
Coord<3> dim(rawDim[0], rawDim[1], rawDim[2]);
// 1. create grids
typedef UnstructuredSoAGrid<SPMVMSoACellInf, MATRICES, ValueType, C, SIGMA> Grid;
const Coord<1> size(dim.x());
Grid grid1(size);
// 2. init grid old
const int maxT = 3.0e8 / dim.x();
SparseMatrixInitializer<SPMVMSoACellInf, Grid> init(dim, maxT);
init.grid(&grid1);
Grid grid2 = grid1;
// 3. call updateFunctor()
double seconds = 0;
Region<1> region;
region << Streak<1>(Coord<1>(0), size.x());
UnstructuredUpdateFunctor<SPMVMSoACellInf> updateFunctor;
UpdateFunctorHelpers::ConcurrencyEnableOpenMP concurrencySpec(true, true);
APITraits::SelectThreadedUpdate<SPMVMSoACellInf>::Value threadedUpdateSpec;
{
ScopedTimer timer(&seconds);
Grid *gridOld = &grid1;
Grid *gridNew = &grid2;
for (int t = 0; t < maxT; ++t) {
using std::swap;
updateFunctor(region, *gridOld, gridNew, 0, concurrencySpec, threadedUpdateSpec);
swap(gridOld, gridNew);
}
}
if (grid1.get(Coord<1>(1)).sum == 4711) {
std::cout << "this statement just serves to prevent the compiler from"
<< "optimizing away the loops above\n";
}
const double entries = 40 * dim.x() + 30 * (dim.x() - 2 * 3400);
const double numOps = 2.0 * entries * maxT;
const double gflops = 1.0e-9 * numOps / seconds;
return gflops;
}
std::string unit()
{
return "GFLOP/s";
}
};
#ifdef __AVX__
class SparseMatrixVectorMultiplicationNative : public CPUBenchmark
{
private:
// callback to get cell's member pointer
template<typename CELL, typename VALUE_TYPE>
class GetPointer
{
private:
VALUE_TYPE **sumPtr;
VALUE_TYPE **valuePtr;
public:
GetPointer(VALUE_TYPE **sumPtr, VALUE_TYPE **valuePtr) :
sumPtr(sumPtr), valuePtr(valuePtr)
{}
template<
typename CELL1, long MY_DIM_X1, long MY_DIM_Y1, long MY_DIM_Z1, long INDEX1,
typename CELL2, long MY_DIM_X2, long MY_DIM_Y2, long MY_DIM_Z2, long INDEX2>
void operator()(
LibFlatArray::soa_accessor<CELL1, MY_DIM_X1, MY_DIM_Y1, MY_DIM_Z1, INDEX1>& oldAccessor,
LibFlatArray::soa_accessor<CELL2, MY_DIM_X2, MY_DIM_Y2, MY_DIM_Z2, INDEX2>& newAccessor) const
{
*sumPtr = &newAccessor.sum();
*valuePtr = &oldAccessor.value();
}
};
public:
std::string family()
{
return "SPMVM";
}
std::string species()
{
return "pepper";
}
double performance(std::vector<int> rawDim)
{
Coord<3> dim(rawDim[0], rawDim[1], rawDim[2]);
// 1. create grids
typedef UnstructuredSoAGrid<SPMVMSoACell, MATRICES, ValueType, C, SIGMA> Grid;
typedef SellCSigmaSparseMatrixContainer<ValueType, C, SIGMA> Matrix;
const Coord<1> size(dim.x());
Grid gridOld(size);
Grid gridNew(size);
// 2. init grid old
const int maxT = 3.0e8 / dim.x();
SparseMatrixInitializer<SPMVMSoACell, Grid> init(dim, maxT);
init.grid(&gridOld);
// 3. native kernel
const Matrix& matrix = gridOld.getWeights(0);
const ValueType *values = matrix.valuesVec().data();
const int *cl = matrix.chunkLengthVec().data();
const int *cs = matrix.chunkOffsetVec().data();
const int *col = matrix.columnVec().data();
ValueType *rhsPtr; // = hoodOld.valuePtr;
ValueType *resPtr; // = hoodNew.sumPtr;
gridOld.callback(&gridNew, GetPointer<SPMVMSoACell, ValueType>(&resPtr, &rhsPtr));
const int rowsPadded = ((size.x() - 1) / C + 1) * C;
double seconds = 0;
{
ScopedTimer timer(&seconds);
for (int t = 0; t < maxT; ++t) {
for (int i = 0; i < rowsPadded / C; ++i) {
int offs = cs[i];
__m256d tmp = _mm256_load_pd(resPtr + i*C);
for (int j = 0; j < cl[i]; ++j) {
__m256d rhs;
__m256d val;
rhs = _mm256_set_pd(
*(rhsPtr + col[offs + 3]),
*(rhsPtr + col[offs + 2]),
*(rhsPtr + col[offs + 1]),
*(rhsPtr + col[offs + 0]));
val = _mm256_load_pd(values + offs);
tmp = _mm256_add_pd(tmp, _mm256_mul_pd(val, rhs));
offs += 4;
}
_mm256_store_pd(resPtr + i*C, tmp);
}
using std::swap;
swap(rhsPtr, resPtr);
}
}
if (gridNew.get(Coord<1>(1)).sum == 4711) {
std::cout << "this statement just serves to prevent the compiler from"
<< "optimizing away the loops above\n";
}
const double entries = 40 * dim.x() + 30 * (dim.x() - 2 * 3400);
const double numOps = 2.0 * entries * maxT;
const double gflops = 1.0e-9 * numOps / seconds;
return gflops;
}
std::string unit()
{
return "GFLOP/s";
}
};
#endif
#endif
class UpdateFunctorThreadingBase : public CPUBenchmark
{
public:
typedef UpdateFunctorHelpers::ConcurrencyEnableOpenMP MyConcurrencySpec;
typedef UpdateFunctor<JacobiCellFixedHood, MyConcurrencySpec> MyUpdateFunctor;
std::string family()
{
return "UpdateFunctorThreading";
}
double performance(std::vector<int> rawDim)
{
int size = rawDim[0];
// stencil radius:
int radius = 1;
int dimX = 10 - 1 - 2 * radius;
int endY = size - 2 - radius;
int steps = rawDim[1];
Coord<3> dim(10, size, 10);
typedef Grid<JacobiCellFixedHood, Topologies::Cube<3>::Topology> GridType;
GridType *gridOld = new GridType(dim, JacobiCellFixedHood(1.0));
GridType *gridNew = new GridType(dim, JacobiCellFixedHood(0.0));
Region<3> region;
for (int i = radius; i < endY; i += 2) {
region << CoordBox<3>(Coord<3>(radius, i, radius + 0), Coord<3>(dimX, 1, 1));
}
for (int i = radius; i < (endY / 2); i += 2) {
region << CoordBox<3>(Coord<3>(radius, i, radius + 1), Coord<3>(dimX, 1, 1));
}
using std::swap;
double seconds = 0;
{
ScopedTimer timer(&seconds);
for (int i = 0; i < steps; ++i) {
MyUpdateFunctor()(region, Coord<3>(), Coord<3>(), *gridOld, gridNew, 0, generateConcurrencySpec());
swap(gridOld, gridNew);
}
}
if (gridNew->get(Coord<3>(radius, radius, radius)).temp == 4711) {
std::cout << "this statement just serves to prevent the compiler from"
<< "optimizing away the loops above\n";
}
const double numOps = region.size() * steps;
const double gflops = 1.0e-9 * numOps / seconds;
return gflops;
}
std::string unit()
{
return "GLUPS";
}
private:
virtual MyConcurrencySpec generateConcurrencySpec() = 0;
};
class UpdateFunctorThreadingGold : public UpdateFunctorThreadingBase
{
public:
std::string species()
{
return "gold";
}
private:
MyConcurrencySpec generateConcurrencySpec()
{
return MyConcurrencySpec(true, true);
}
};
template<typename CELL_TYPE, typename GRID_TYPE>
class GridLoadSaveRegion : public CPUBenchmark
{
public:
std::string family()
{
return "GridLoadSaveRegion";
}
std::string unit()
{
return "GB/s";
}
double performance(std::vector<int> dim)
{
CoordBox<3> bigBox(Coord<3>(), Coord<3>(dim[0], dim[0], dim[0]));
CoordBox<3> smallBox(Coord<3>(1, 1, 1), Coord<3>::diagonal(dim[0] - 2));
Region<3> region(bigBox);
region << CoordBox<3>(Coord<3>(0, 0, 0), Coord<3>(1, dim[0], dim[0]));
region << CoordBox<3>(Coord<3>(dim[0] - 1, 0, 0), Coord<3>(1, dim[0], dim[0]));
region << CoordBox<3>(Coord<3>(0, 0, 0), Coord<3>(dim[0], 1, dim[0]));
region << CoordBox<3>(Coord<3>(0, dim[0] - 1, 0), Coord<3>(dim[0], 1, dim[0]));
region << CoordBox<3>(Coord<3>(0, 0, 0), Coord<3>(dim[0], dim[0], 1));
region << CoordBox<3>(Coord<3>(0, 0, dim[0] - 1), Coord<3>(dim[0], dim[0], 1));
GRID_TYPE grid1(bigBox);
GRID_TYPE grid2(bigBox);
typename SerializationBuffer<CELL_TYPE>::BufferType buffer1 = SerializationBuffer<CELL_TYPE>::create(region);
typename SerializationBuffer<CELL_TYPE>::BufferType buffer2 = SerializationBuffer<CELL_TYPE>::create(region);
int repeats = dim[2];
double seconds = 0;
{
ScopedTimer t(&seconds);
for (int i = 0; i < repeats; ++i) {
grid1.saveRegion(&buffer1, region);
grid2.saveRegion(&buffer2, region);
grid1.loadRegion(buffer2, region);
grid2.loadRegion(buffer1, region);
}
}
double bytesTransferred = 4.0 * region.size() * sizeof(CELL_TYPE);
return 1e-9 * bytesTransferred / seconds;
}
};
class GridLoadSaveRegionAoS : public GridLoadSaveRegion<Cell, DisplacedGrid<Cell, Topologies::Torus<3>::Topology> >
{
public:
std::string species()
{
return "silver";
}
};
class GridLoadSaveRegionSoA : public GridLoadSaveRegion<SoACell, SoAGrid<SoACell, Topologies::Torus<3>::Topology> >
{
public:
std::string species()
{
return "gold";
}
};
class UpdateFunctorThreadingSilver : public UpdateFunctorThreadingBase
{
public:
std::string species()
{
return "silver";
}
private:
MyConcurrencySpec generateConcurrencySpec()
{
return MyConcurrencySpec(true, false);
}
};
#ifdef LIBGEODECOMP_WITH_CUDA
void cudaTests(std::string name, std::string revision, int cudaDevice);
#endif
int main(int argc, char **argv)
{
if ((argc < 3) || (argc == 4) || (argc > 5)) {
std::cerr << "usage: " << argv[0] << " [-n,--name SUBSTRING] REVISION CUDA_DEVICE \n"
<< " - optional: only run tests whose name contains a SUBSTRING,\n"
<< " - REVISION is purely for output reasons,\n"
<< " - CUDA_DEVICE causes CUDA tests to run on the device with the given ID.\n";
return 1;
}
std::string name = "";
int argumentIndex = 1;
if (argc == 5) {
if ((std::string(argv[1]) == "-n") ||
(std::string(argv[1]) == "--name")) {
name = std::string(argv[2]);
}
argumentIndex = 3;
}
std::string revision = argv[argumentIndex + 0];
std::stringstream s;
s << argv[argumentIndex + 1];
int cudaDevice;
s >> cudaDevice;
LibFlatArray::evaluate eval(name, revision);
eval.print_header();
std::vector<Coord<3> > sizes;
#ifdef LIBGEODECOMP_WITH_CPP14
sizes << Coord<3>(10648 , 1, 1)
<< Coord<3>(35937 , 1, 1)
<< Coord<3>(85184 , 1, 1);
for (std::size_t i = 0; i < sizes.size(); ++i) {
eval(SellMatrixInitializer(), toVector(sizes[i]));
}
for (std::size_t i = 0; i < sizes.size(); ++i) {
eval(SparseMatrixVectorMultiplication(), toVector(sizes[i]));
}
#ifdef __AVX__
for (std::size_t i = 0; i < sizes.size(); ++i) {
eval(SparseMatrixVectorMultiplicationNative(), toVector(sizes[i]));
}
#endif
for (std::size_t i = 0; i < sizes.size(); ++i) {
eval(SparseMatrixVectorMultiplicationVectorized(), toVector(sizes[i]));
}
for (std::size_t i = 0; i < sizes.size(); ++i) {
eval(SparseMatrixVectorMultiplicationVectorizedInf(), toVector(sizes[i]));
}
sizes.clear();
#endif
eval(RegionCount(), toVector(Coord<3>( 128, 128, 128)));
eval(RegionCount(), toVector(Coord<3>( 512, 512, 512)));
eval(RegionCount(), toVector(Coord<3>(2048, 2048, 2048)));
eval(RegionInsert(), toVector(Coord<3>( 128, 128, 128)));
eval(RegionInsert(), toVector(Coord<3>( 512, 512, 512)));
eval(RegionInsert(), toVector(Coord<3>(2048, 2048, 2048)));
eval(RegionIntersect(), toVector(Coord<3>( 128, 128, 128)));
eval(RegionIntersect(), toVector(Coord<3>( 512, 512, 512)));
eval(RegionIntersect(), toVector(Coord<3>(2048, 2048, 2048)));
eval(RegionSubtract(), toVector(Coord<3>( 128, 128, 128)));
eval(RegionSubtract(), toVector(Coord<3>( 512, 512, 512)));
eval(RegionSubtract(), toVector(Coord<3>(2048, 2048, 2048)));
eval(RegionUnion(), toVector(Coord<3>( 128, 128, 128)));
eval(RegionUnion(), toVector(Coord<3>( 512, 512, 512)));
eval(RegionUnion(), toVector(Coord<3>(2048, 2048, 2048)));
eval(RegionAppend(), toVector(Coord<3>( 128, 128, 128)));
eval(RegionAppend(), toVector(Coord<3>( 512, 512, 512)));
eval(RegionAppend(), toVector(Coord<3>(2048, 2048, 2048)));
eval(RegionExpand(1), toVector(Coord<3>( 128, 128, 128)));
eval(RegionExpand(1), toVector(Coord<3>( 512, 512, 512)));
eval(RegionExpand(1), toVector(Coord<3>(2048, 2048, 2048)));
eval(RegionExpand(5), toVector(Coord<3>( 128, 128, 128)));
eval(RegionExpand(5), toVector(Coord<3>( 512, 512, 512)));
eval(RegionExpand(5), toVector(Coord<3>(2048, 2048, 2048)));
{
std::vector<int> params(4);
int numCells = 2000000;
std::map<int, ConvexPolytope<FloatCoord<2> > > cells = RegionExpandWithAdjacency::genGrid(numCells);
params[0] = numCells;
params[1] = 0; // skip cells
params[2] = 1; // expansion width
params[3] = -1; // id streak lenght
eval(RegionExpandWithAdjacency(cells), params);
params[1] = 5000; // skip cells
params[3] = 500; // id streak lenght
eval(RegionExpandWithAdjacency(cells), params);
params[1] = 100;
params[2] = 50;
params[3] = 100;
eval(RegionExpandWithAdjacency(cells), params);
params[2] = 20;
params[3] = 10;
eval(RegionExpandWithAdjacency(cells), params);
params[2] = 10;
params[3] = 2;
eval(RegionExpandWithAdjacency(cells), params);
}
eval(CoordEnumerationVanilla(), toVector(Coord<3>( 128, 128, 128)));
eval(CoordEnumerationVanilla(), toVector(Coord<3>( 512, 512, 512)));
eval(CoordEnumerationVanilla(), toVector(Coord<3>(2048, 2048, 2048)));
eval(CoordEnumerationBronze(), toVector(Coord<3>( 128, 128, 128)));
eval(CoordEnumerationBronze(), toVector(Coord<3>( 512, 512, 512)));
eval(CoordEnumerationBronze(), toVector(Coord<3>(2048, 2048, 2048)));
eval(CoordEnumerationGold(), toVector(Coord<3>( 128, 128, 128)));
eval(CoordEnumerationGold(), toVector(Coord<3>( 512, 512, 512)));
eval(CoordEnumerationGold(), toVector(Coord<3>(2048, 2048, 2048)));
eval(FloatCoordAccumulationGold(), toVector(Coord<3>(2048, 2048, 2048)));
sizes << Coord<3>(22, 22, 22)
<< Coord<3>(64, 64, 64)
<< Coord<3>(68, 68, 68)
<< Coord<3>(106, 106, 106)
<< Coord<3>(128, 128, 128)
<< Coord<3>(150, 150, 150)
<< Coord<3>(512, 512, 32)
<< Coord<3>(518, 518, 32);
sizes << Coord<3>(1024, 1024, 32)
<< Coord<3>(1026, 1026, 32);
for (std::size_t i = 0; i < sizes.size(); ++i) {
eval(Jacobi3DVanilla(), toVector(sizes[i]));
}
for (std::size_t i = 0; i < sizes.size(); ++i) {
eval(Jacobi3DSSE(), toVector(sizes[i]));
}
for (std::size_t i = 0; i < sizes.size(); ++i) {
eval(Jacobi3DClassic(), toVector(sizes[i]));
}
for (std::size_t i = 0; i < sizes.size(); ++i) {
eval(Jacobi3DFixedHood(), toVector(sizes[i]));
}
for (std::size_t i = 0; i < sizes.size(); ++i) {
eval(Jacobi3DStreakUpdate(), toVector(sizes[i]));
}
for (std::size_t i = 0; i < sizes.size(); ++i) {
eval(Jacobi3DStreakUpdateFunctor(), toVector(sizes[i]));
}
sizes.clear();
sizes << Coord<3>(22, 22, 22)
<< Coord<3>(64, 64, 64)
<< Coord<3>(68, 68, 68)
<< Coord<3>(106, 106, 106)
<< Coord<3>(128, 128, 128);
sizes << Coord<3>(160, 160, 160);
for (std::size_t i = 0; i < sizes.size(); ++i) {
eval(LBMClassic(), toVector(sizes[i]));
}
for (std::size_t i = 0; i < sizes.size(); ++i) {
eval(LBMSoA(), toVector(sizes[i]));
}
std::vector<int> dim = toVector(Coord<3>(32 * 1024, 32 * 1024, 1));
eval(PartitionBenchmark<HIndexingPartition >("PartitionHIndexing"), dim);
eval(PartitionBenchmark<StripingPartition<2> >("PartitionStriping"), dim);
eval(PartitionBenchmark<HilbertPartition >("PartitionHilbert"), dim);
eval(PartitionBenchmark<ZCurvePartition<2> >("PartitionZCurve"), dim);
dim = toVector(Coord<3>(10000, 2000, 0));
eval(UpdateFunctorThreadingSilver(), dim);
eval(UpdateFunctorThreadingGold(), dim);
eval(GridLoadSaveRegionAoS(), toVector(Coord<3>(256, 0, 32)));
eval(GridLoadSaveRegionSoA(), toVector(Coord<3>(256, 0, 32)));
#ifdef LIBGEODECOMP_WITH_CUDA
cudaTests(name, revision, cudaDevice);
#endif
return 0;
}
| 29.598528 | 195 | 0.52361 | [
"mesh",
"geometry",
"vector"
] |
a8e39c47ea3ce83ef8601b83b751582137f58e78 | 23,074 | hpp | C++ | cisco-ios-xe/ydk/models/cisco_ios_xe/MPLS_LSR_STD_MIB.hpp | CiscoDevNet/ydk-cpp | ef7d75970f2ef1154100e0f7b0a2ee823609b481 | [
"ECL-2.0",
"Apache-2.0"
] | 17 | 2016-12-02T05:45:49.000Z | 2022-02-10T19:32:54.000Z | cisco-ios-xe/ydk/models/cisco_ios_xe/MPLS_LSR_STD_MIB.hpp | CiscoDevNet/ydk-cpp | ef7d75970f2ef1154100e0f7b0a2ee823609b481 | [
"ECL-2.0",
"Apache-2.0"
] | 2 | 2017-03-27T15:22:38.000Z | 2019-11-05T08:30:16.000Z | cisco-ios-xe/ydk/models/cisco_ios_xe/MPLS_LSR_STD_MIB.hpp | CiscoDevNet/ydk-cpp | ef7d75970f2ef1154100e0f7b0a2ee823609b481 | [
"ECL-2.0",
"Apache-2.0"
] | 11 | 2016-12-02T05:45:52.000Z | 2019-11-07T08:28:17.000Z | #ifndef _MPLS_LSR_STD_MIB_
#define _MPLS_LSR_STD_MIB_
#include <memory>
#include <vector>
#include <string>
#include <ydk/types.hpp>
#include <ydk/errors.hpp>
namespace cisco_ios_xe {
namespace MPLS_LSR_STD_MIB {
class MPLSLSRSTDMIB : public ydk::Entity
{
public:
MPLSLSRSTDMIB();
~MPLSLSRSTDMIB();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::shared_ptr<ydk::Entity> clone_ptr() const override;
ydk::augment_capabilities_function get_augment_capabilities_function() const override;
std::string get_bundle_yang_models_location() const override;
std::string get_bundle_name() const override;
std::map<std::pair<std::string, std::string>, std::string> get_namespace_identity_lookup() const override;
class MplsLsrObjects; //type: MPLSLSRSTDMIB::MplsLsrObjects
class MplsInterfaceTable; //type: MPLSLSRSTDMIB::MplsInterfaceTable
class MplsInSegmentTable; //type: MPLSLSRSTDMIB::MplsInSegmentTable
class MplsOutSegmentTable; //type: MPLSLSRSTDMIB::MplsOutSegmentTable
class MplsXCTable; //type: MPLSLSRSTDMIB::MplsXCTable
class MplsLabelStackTable; //type: MPLSLSRSTDMIB::MplsLabelStackTable
class MplsInSegmentMapTable; //type: MPLSLSRSTDMIB::MplsInSegmentMapTable
std::shared_ptr<cisco_ios_xe::MPLS_LSR_STD_MIB::MPLSLSRSTDMIB::MplsLsrObjects> mplslsrobjects;
std::shared_ptr<cisco_ios_xe::MPLS_LSR_STD_MIB::MPLSLSRSTDMIB::MplsInterfaceTable> mplsinterfacetable;
std::shared_ptr<cisco_ios_xe::MPLS_LSR_STD_MIB::MPLSLSRSTDMIB::MplsInSegmentTable> mplsinsegmenttable;
std::shared_ptr<cisco_ios_xe::MPLS_LSR_STD_MIB::MPLSLSRSTDMIB::MplsOutSegmentTable> mplsoutsegmenttable;
std::shared_ptr<cisco_ios_xe::MPLS_LSR_STD_MIB::MPLSLSRSTDMIB::MplsXCTable> mplsxctable;
std::shared_ptr<cisco_ios_xe::MPLS_LSR_STD_MIB::MPLSLSRSTDMIB::MplsLabelStackTable> mplslabelstacktable;
std::shared_ptr<cisco_ios_xe::MPLS_LSR_STD_MIB::MPLSLSRSTDMIB::MplsInSegmentMapTable> mplsinsegmentmaptable;
}; // MPLSLSRSTDMIB
class MPLSLSRSTDMIB::MplsLsrObjects : public ydk::Entity
{
public:
MplsLsrObjects();
~MplsLsrObjects();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::string get_absolute_path() const override;
ydk::YLeaf mplsinsegmentindexnext; //type: binary
ydk::YLeaf mplsoutsegmentindexnext; //type: binary
ydk::YLeaf mplsxcindexnext; //type: binary
ydk::YLeaf mplsmaxlabelstackdepth; //type: uint32
ydk::YLeaf mplslabelstackindexnext; //type: binary
ydk::YLeaf mplsxcnotificationsenable; //type: boolean
}; // MPLSLSRSTDMIB::MplsLsrObjects
class MPLSLSRSTDMIB::MplsInterfaceTable : public ydk::Entity
{
public:
MplsInterfaceTable();
~MplsInterfaceTable();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::string get_absolute_path() const override;
class MplsInterfaceEntry; //type: MPLSLSRSTDMIB::MplsInterfaceTable::MplsInterfaceEntry
ydk::YList mplsinterfaceentry;
}; // MPLSLSRSTDMIB::MplsInterfaceTable
class MPLSLSRSTDMIB::MplsInterfaceTable::MplsInterfaceEntry : public ydk::Entity
{
public:
MplsInterfaceEntry();
~MplsInterfaceEntry();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::string get_absolute_path() const override;
ydk::YLeaf mplsinterfaceindex; //type: int32
ydk::YLeaf mplsinterfacelabelminin; //type: uint32
ydk::YLeaf mplsinterfacelabelmaxin; //type: uint32
ydk::YLeaf mplsinterfacelabelminout; //type: uint32
ydk::YLeaf mplsinterfacelabelmaxout; //type: uint32
ydk::YLeaf mplsinterfacetotalbandwidth; //type: uint32
ydk::YLeaf mplsinterfaceavailablebandwidth; //type: uint32
ydk::YLeaf mplsinterfacelabelparticipationtype; //type: MplsInterfaceLabelParticipationType
ydk::YLeaf mplsinterfaceperfinlabelsinuse; //type: uint32
ydk::YLeaf mplsinterfaceperfinlabellookupfailures; //type: uint32
ydk::YLeaf mplsinterfaceperfoutlabelsinuse; //type: uint32
ydk::YLeaf mplsinterfaceperfoutfragmentedpkts; //type: uint32
}; // MPLSLSRSTDMIB::MplsInterfaceTable::MplsInterfaceEntry
class MPLSLSRSTDMIB::MplsInSegmentTable : public ydk::Entity
{
public:
MplsInSegmentTable();
~MplsInSegmentTable();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::string get_absolute_path() const override;
class MplsInSegmentEntry; //type: MPLSLSRSTDMIB::MplsInSegmentTable::MplsInSegmentEntry
ydk::YList mplsinsegmententry;
}; // MPLSLSRSTDMIB::MplsInSegmentTable
class MPLSLSRSTDMIB::MplsInSegmentTable::MplsInSegmentEntry : public ydk::Entity
{
public:
MplsInSegmentEntry();
~MplsInSegmentEntry();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::string get_absolute_path() const override;
ydk::YLeaf mplsinsegmentindex; //type: binary
ydk::YLeaf mplsinsegmentinterface; //type: int32
ydk::YLeaf mplsinsegmentlabel; //type: uint32
ydk::YLeaf mplsinsegmentlabelptr; //type: string
ydk::YLeaf mplsinsegmentnpop; //type: int32
ydk::YLeaf mplsinsegmentaddrfamily; //type: AddressFamilyNumbers
ydk::YLeaf mplsinsegmentxcindex; //type: binary
ydk::YLeaf mplsinsegmentowner; //type: MplsOwner
ydk::YLeaf mplsinsegmenttrafficparamptr; //type: string
ydk::YLeaf mplsinsegmentrowstatus; //type: RowStatus
ydk::YLeaf mplsinsegmentstoragetype; //type: StorageType
ydk::YLeaf mplsinsegmentperfoctets; //type: uint32
ydk::YLeaf mplsinsegmentperfpackets; //type: uint32
ydk::YLeaf mplsinsegmentperferrors; //type: uint32
ydk::YLeaf mplsinsegmentperfdiscards; //type: uint32
ydk::YLeaf mplsinsegmentperfhcoctets; //type: uint64
ydk::YLeaf mplsinsegmentperfdiscontinuitytime; //type: uint32
}; // MPLSLSRSTDMIB::MplsInSegmentTable::MplsInSegmentEntry
class MPLSLSRSTDMIB::MplsOutSegmentTable : public ydk::Entity
{
public:
MplsOutSegmentTable();
~MplsOutSegmentTable();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::string get_absolute_path() const override;
class MplsOutSegmentEntry; //type: MPLSLSRSTDMIB::MplsOutSegmentTable::MplsOutSegmentEntry
ydk::YList mplsoutsegmententry;
}; // MPLSLSRSTDMIB::MplsOutSegmentTable
class MPLSLSRSTDMIB::MplsOutSegmentTable::MplsOutSegmentEntry : public ydk::Entity
{
public:
MplsOutSegmentEntry();
~MplsOutSegmentEntry();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::string get_absolute_path() const override;
ydk::YLeaf mplsoutsegmentindex; //type: binary
ydk::YLeaf mplsoutsegmentinterface; //type: int32
ydk::YLeaf mplsoutsegmentpushtoplabel; //type: boolean
ydk::YLeaf mplsoutsegmenttoplabel; //type: uint32
ydk::YLeaf mplsoutsegmenttoplabelptr; //type: string
ydk::YLeaf mplsoutsegmentnexthopaddrtype; //type: InetAddressType
ydk::YLeaf mplsoutsegmentnexthopaddr; //type: binary
ydk::YLeaf mplsoutsegmentxcindex; //type: binary
ydk::YLeaf mplsoutsegmentowner; //type: MplsOwner
ydk::YLeaf mplsoutsegmenttrafficparamptr; //type: string
ydk::YLeaf mplsoutsegmentrowstatus; //type: RowStatus
ydk::YLeaf mplsoutsegmentstoragetype; //type: StorageType
ydk::YLeaf mplsoutsegmentperfoctets; //type: uint32
ydk::YLeaf mplsoutsegmentperfpackets; //type: uint32
ydk::YLeaf mplsoutsegmentperferrors; //type: uint32
ydk::YLeaf mplsoutsegmentperfdiscards; //type: uint32
ydk::YLeaf mplsoutsegmentperfhcoctets; //type: uint64
ydk::YLeaf mplsoutsegmentperfdiscontinuitytime; //type: uint32
}; // MPLSLSRSTDMIB::MplsOutSegmentTable::MplsOutSegmentEntry
class MPLSLSRSTDMIB::MplsXCTable : public ydk::Entity
{
public:
MplsXCTable();
~MplsXCTable();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::string get_absolute_path() const override;
class MplsXCEntry; //type: MPLSLSRSTDMIB::MplsXCTable::MplsXCEntry
ydk::YList mplsxcentry;
}; // MPLSLSRSTDMIB::MplsXCTable
class MPLSLSRSTDMIB::MplsXCTable::MplsXCEntry : public ydk::Entity
{
public:
MplsXCEntry();
~MplsXCEntry();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::string get_absolute_path() const override;
ydk::YLeaf mplsxcindex; //type: binary
ydk::YLeaf mplsxcinsegmentindex; //type: binary
ydk::YLeaf mplsxcoutsegmentindex; //type: binary
ydk::YLeaf mplsxclspid; //type: binary
ydk::YLeaf mplsxclabelstackindex; //type: binary
ydk::YLeaf mplsxcowner; //type: MplsOwner
ydk::YLeaf mplsxcrowstatus; //type: RowStatus
ydk::YLeaf mplsxcstoragetype; //type: StorageType
ydk::YLeaf mplsxcadminstatus; //type: MplsXCAdminStatus
ydk::YLeaf mplsxcoperstatus; //type: MplsXCOperStatus
class MplsXCAdminStatus;
class MplsXCOperStatus;
}; // MPLSLSRSTDMIB::MplsXCTable::MplsXCEntry
class MPLSLSRSTDMIB::MplsLabelStackTable : public ydk::Entity
{
public:
MplsLabelStackTable();
~MplsLabelStackTable();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::string get_absolute_path() const override;
class MplsLabelStackEntry; //type: MPLSLSRSTDMIB::MplsLabelStackTable::MplsLabelStackEntry
ydk::YList mplslabelstackentry;
}; // MPLSLSRSTDMIB::MplsLabelStackTable
class MPLSLSRSTDMIB::MplsLabelStackTable::MplsLabelStackEntry : public ydk::Entity
{
public:
MplsLabelStackEntry();
~MplsLabelStackEntry();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::string get_absolute_path() const override;
ydk::YLeaf mplslabelstackindex; //type: binary
ydk::YLeaf mplslabelstacklabelindex; //type: uint32
ydk::YLeaf mplslabelstacklabel; //type: uint32
ydk::YLeaf mplslabelstacklabelptr; //type: string
ydk::YLeaf mplslabelstackrowstatus; //type: RowStatus
ydk::YLeaf mplslabelstackstoragetype; //type: StorageType
}; // MPLSLSRSTDMIB::MplsLabelStackTable::MplsLabelStackEntry
class MPLSLSRSTDMIB::MplsInSegmentMapTable : public ydk::Entity
{
public:
MplsInSegmentMapTable();
~MplsInSegmentMapTable();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::string get_absolute_path() const override;
class MplsInSegmentMapEntry; //type: MPLSLSRSTDMIB::MplsInSegmentMapTable::MplsInSegmentMapEntry
ydk::YList mplsinsegmentmapentry;
}; // MPLSLSRSTDMIB::MplsInSegmentMapTable
class MPLSLSRSTDMIB::MplsInSegmentMapTable::MplsInSegmentMapEntry : public ydk::Entity
{
public:
MplsInSegmentMapEntry();
~MplsInSegmentMapEntry();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::string get_absolute_path() const override;
ydk::YLeaf mplsinsegmentmapinterface; //type: int32
ydk::YLeaf mplsinsegmentmaplabel; //type: uint32
ydk::YLeaf mplsinsegmentmaplabelptrindex; //type: string
ydk::YLeaf mplsinsegmentmapindex; //type: binary
}; // MPLSLSRSTDMIB::MplsInSegmentMapTable::MplsInSegmentMapEntry
class MPLSLSRSTDMIB::MplsXCTable::MplsXCEntry::MplsXCAdminStatus : public ydk::Enum
{
public:
static const ydk::Enum::YLeaf up;
static const ydk::Enum::YLeaf down;
static const ydk::Enum::YLeaf testing;
static int get_enum_value(const std::string & name) {
if (name == "up") return 1;
if (name == "down") return 2;
if (name == "testing") return 3;
return -1;
}
};
class MPLSLSRSTDMIB::MplsXCTable::MplsXCEntry::MplsXCOperStatus : public ydk::Enum
{
public:
static const ydk::Enum::YLeaf up;
static const ydk::Enum::YLeaf down;
static const ydk::Enum::YLeaf testing;
static const ydk::Enum::YLeaf unknown;
static const ydk::Enum::YLeaf dormant;
static const ydk::Enum::YLeaf notPresent;
static const ydk::Enum::YLeaf lowerLayerDown;
static int get_enum_value(const std::string & name) {
if (name == "up") return 1;
if (name == "down") return 2;
if (name == "testing") return 3;
if (name == "unknown") return 4;
if (name == "dormant") return 5;
if (name == "notPresent") return 6;
if (name == "lowerLayerDown") return 7;
return -1;
}
};
}
}
#endif /* _MPLS_LSR_STD_MIB_ */
| 49.835853 | 162 | 0.702522 | [
"vector"
] |
a8e993c1db3ef9c63eb6022f713bde18b8c15454 | 10,931 | cpp | C++ | api/ProgramCL.cpp | cjang/chai | 7faba752cc4491d1b30590abef21edc4efffa0f6 | [
"Unlicense"
] | 11 | 2015-06-12T19:54:14.000Z | 2021-11-26T10:45:18.000Z | api/ProgramCL.cpp | cjang/chai | 7faba752cc4491d1b30590abef21edc4efffa0f6 | [
"Unlicense"
] | null | null | null | api/ProgramCL.cpp | cjang/chai | 7faba752cc4491d1b30590abef21edc4efffa0f6 | [
"Unlicense"
] | null | null | null | // Copyright 2012 Chris Jang (fastkor@gmail.com) under The Artistic License 2.0
#include <sstream>
#include <stdarg.h>
#include "ArrayClient.hpp"
#include "AstOpenCL.hpp"
#include "ByteCodes.hpp"
#include "chai/chai.h"
#include "PrecType.hpp"
#include "SingleNut.hpp"
#include "TEA.hpp"
using namespace chai_internal;
using namespace std;
namespace chai {
////////////////////////////////////////
// inline OpenCL
void ProgramCL::initKeywords(void)
{
_arrayBaseKeywords.insert( "__global" );
_arrayBaseKeywords.insert( "global" );
_arrayBaseKeywords.insert( "image2d_t" );
_localMemKeywords.insert( "__local" );
_localMemKeywords.insert( "local" );
_scalarKeywords[ "unsigned" ] = PrecType::UInt32;
_scalarKeywords[ "uint" ] = PrecType::UInt32;
_scalarKeywords[ "int" ] = PrecType::Int32;
_scalarKeywords[ "float" ] = PrecType::Float;
_scalarKeywords[ "double" ] = PrecType::Double;
}
bool ProgramCL::parseKernelArgs(const string& strT)
{
bool endOfArgs = false;
vector< string > argTok;
vector< size_t > argIdx;
stringstream ss;
for (size_t i = 0; !endOfArgs && i < strT.size(); i++)
{
switch (strT[i])
{
case ('(') :
// ignore
break;
case (')') :
argTok.push_back(ss.str());
argIdx.push_back(_argIndex++);
ss.str(string());
endOfArgs = true;
break;
case (',') :
argTok.push_back(ss.str());
argIdx.push_back(_argIndex++);
ss.str(string());
break;
default :
if ('*' != strT[i]) ss << strT[i];
}
}
if (! endOfArgs)
{
argTok.push_back(ss.str());
argIdx.push_back(_argIndex);
}
for (size_t i = 0; i < argTok.size(); i++)
{
const string tok = argTok[i];
const size_t idx = argIdx[i];
if (_arrayBaseKeywords.count(tok))
{
_argKind[ idx ] = ARRAY_BASE;
}
else if (_localMemKeywords.count(tok))
{
_argKind[ idx ] = LOCAL_MEM;
}
else if (_scalarKeywords.count(tok))
{
if (0 == _argKind.count(idx))
{
_argKind[ idx ] = SCALAR;
}
_argPrecType[ idx ] = _scalarKeywords[ tok ];
}
}
return ! endOfArgs;
}
void ProgramCL::setKernelArgs(const string& kernelName)
{
bool argsOk = true;
for (size_t i = 0; i < _argIndex; i++)
{
if (_argKind.count(i))
{
_kernelArgKind[ kernelName ].push_back( _argKind[i] );
// image2d_t does not have a precision type in kernel source
_kernelArgPrecType[ kernelName ].push_back( _argPrecType.count(i)
? _argPrecType[i]
: -1 );
}
else
{
argsOk = false;
}
}
if (! argsOk)
{
_kernelArgKind.erase( kernelName );
_kernelArgPrecType.erase( kernelName );
}
}
void ProgramCL::parseProgramText(void)
{
bool kernelKey = false, voidKey = false;
string kernelName;
for (vector< string >::const_iterator
it = _programText.begin();
it != _programText.end();
it++)
{
stringstream ss(*it);
string strT;
while (! ss.eof() && (ss >> strT))
{
if (kernelKey)
{
if (voidKey)
{
if (! kernelName.empty())
{
if (! parseKernelArgs(strT))
{
setKernelArgs(kernelName);
kernelName.clear();
voidKey = kernelKey = false;
}
}
else
{
// read kernel name
_argIndex = 0;
_argKind.clear();
_argPrecType.clear();
const size_t end = strT.find("(");
kernelName = strT.substr(0, end);
if (string::npos != end &&
! parseKernelArgs(strT.substr(end)))
{
setKernelArgs(kernelName);
kernelName.clear();
voidKey = kernelKey = false;
}
}
}
else if ("void" == strT) // no return value from kernel
{
voidKey = true;
}
}
else if ("__kernel" == strT || "kernel" == strT)
{
kernelKey = true;
}
}
}
}
ProgramCL::Kernel::Kernel(ProgramCL& progCL,
const string& kernelName)
: _progCL(progCL),
_kernelName(kernelName),
_astObj(new AstOpenCL(progCL._programText,
progCL._programHashCode,
kernelName)),
_client(NULL),
_refs(),
_nut(new SingleNut),
_argIndex(0)
{
_refs.checkout(_nut);
_refs.checkout(_astObj);
}
ProgramCL::Kernel::~Kernel(void)
{
if (_client)
{
// ok
const uint32_t variable = _client->variable();
const uint32_t version = 1;
_client->constructor(variable, _nut);
Stak<BC>& v = _client->assignment(variable, version);
v.push( _client->frontMem(variable, _astObj) );
v.push( ByteCodes::kernel_from_opencl );
_client->destructor(variable);
}
}
ProgramCL::Kernel& ProgramCL::Kernel::operator, (const ArrayBase& arrayVar)
{
if (! _client)
{
_client = arrayVar.getArrayClient();
}
_astObj->setArgArray(_argIndex++,
arrayVar.getArrayPrec(),
arrayVar.getArrayVarNum());
return *this;
}
ProgramCL::Kernel& ProgramCL::Kernel::operator, (const size_t length)
{
switch ( _progCL._kernelArgKind[ _kernelName ][ _argIndex ] )
{
case (LOCAL_MEM) :
_astObj->setArgLocal(_argIndex++,
_progCL._kernelArgPrecType[ _kernelName ]
[ _argIndex ],
length);
break;
case (SCALAR) :
_astObj->setArgScalar(_argIndex++,
_progCL._kernelArgPrecType[ _kernelName ]
[ _argIndex ],
static_cast<double>(length));
break;
}
return *this;
}
ProgramCL::Kernel& ProgramCL::Kernel::operator, (const uint32_t scalar)
{
switch ( _progCL._kernelArgKind[ _kernelName ][ _argIndex ] )
{
case (LOCAL_MEM) :
_astObj->setArgLocal(_argIndex++,
_progCL._kernelArgPrecType[ _kernelName ]
[ _argIndex ],
scalar);
break;
case (SCALAR) :
_astObj->setArgScalar(_argIndex++,
_progCL._kernelArgPrecType[ _kernelName ]
[ _argIndex ],
scalar);
break;
}
return *this;
}
ProgramCL::Kernel& ProgramCL::Kernel::operator, (const int32_t scalar)
{
switch ( _progCL._kernelArgKind[ _kernelName ][ _argIndex ] )
{
case (LOCAL_MEM) :
_astObj->setArgLocal(_argIndex++,
_progCL._kernelArgPrecType[ _kernelName ]
[ _argIndex ],
scalar);
break;
case (SCALAR) :
_astObj->setArgScalar(_argIndex++,
_progCL._kernelArgPrecType[ _kernelName ]
[ _argIndex ],
scalar);
break;
}
return *this;
}
ProgramCL::Kernel& ProgramCL::Kernel::operator, (const float scalar)
{
switch ( _progCL._kernelArgKind[ _kernelName ][ _argIndex ] )
{
case (LOCAL_MEM) :
_astObj->setArgLocal(_argIndex++,
_progCL._kernelArgPrecType[ _kernelName ]
[ _argIndex ],
scalar);
break;
case (SCALAR) :
_astObj->setArgScalar(_argIndex++,
_progCL._kernelArgPrecType[ _kernelName ]
[ _argIndex ],
scalar);
break;
}
return *this;
}
ProgramCL::Kernel& ProgramCL::Kernel::operator, (const double scalar)
{
switch ( _progCL._kernelArgKind[ _kernelName ][ _argIndex ] )
{
case (LOCAL_MEM) :
_astObj->setArgLocal(_argIndex++,
_progCL._kernelArgPrecType[ _kernelName ]
[ _argIndex ],
scalar);
break;
case (SCALAR) :
_astObj->setArgScalar(_argIndex++,
_progCL._kernelArgPrecType[ _kernelName ]
[ _argIndex ],
scalar);
break;
}
return *this;
}
void ProgramCL::Kernel::operator() (const size_t global0,
const size_t local0)
{
_astObj->setWorkSpace(global0, local0);
}
void ProgramCL::Kernel::operator() (const size_t global0,
const size_t global1,
const size_t local0,
const size_t local1)
{
_astObj->setWorkSpace(global0, global1, local0, local1);
}
ProgramCL::ProgramCL(const string& programText)
: _programHashCode(TEA::hash(programText)),
_programText()
{
_programText.push_back( programText );
initKeywords();
parseProgramText();
}
ProgramCL::ProgramCL(const vector< string >& programText)
: _programHashCode(TEA::hash(programText)),
_programText(programText)
{
initKeywords();
parseProgramText();
}
ProgramCL::~ProgramCL(void) { }
ProgramCL::Kernel ProgramCL::operator, (const string& kernelName)
{
return Kernel(*this, kernelName);
}
}; // namespace chai
| 27.743655 | 79 | 0.463453 | [
"vector"
] |
5ef2d9637210565da622ffc301b11462cf5ee808 | 12,370 | cpp | C++ | edk/network/PackageGroup.cpp | Edimartin/edk-source | de9a152e91344e201669b0421e5f44dea40cebf9 | [
"MIT"
] | null | null | null | edk/network/PackageGroup.cpp | Edimartin/edk-source | de9a152e91344e201669b0421e5f44dea40cebf9 | [
"MIT"
] | null | null | null | edk/network/PackageGroup.cpp | Edimartin/edk-source | de9a152e91344e201669b0421e5f44dea40cebf9 | [
"MIT"
] | null | null | null | #include "PackageGroup.h"
/*
Library PackageGroup - Manage a group of packages to be sended by the edk::Socket
Copyright 2013 Eduardo Moura Sales Martins (edimartin@gmail.com)
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.
*/
edk::network::PackageGroup::PackageTree::PackageTree(){
//
}
edk::network::PackageGroup::PackageTree::~PackageTree(){
//
}
//compare if the value is bigger
bool edk::network::PackageGroup::PackageTree::firstBiggerSecond(edk::network::Package* first,edk::network::Package* second){
//
if(first->getPosition()>second->getPosition()){
//
return true;
}
return false;
}
bool edk::network::PackageGroup::PackageTree::firstEqualSecond(edk::network::Package* first,edk::network::Package* second){
//
if(first->getPosition()==second->getPosition()){
//
return true;
}
return false;
}
//get the pachage
edk::network::Package* edk::network::PackageGroup::PackageTree::getPackage(edk::uint32 id){
//
edk::network::Package find;
find.setHeader(id,0u,id);
return this->getElement(&find);
}
edk::network::PackageGroup::PackageGroup(){
//
this->setPackSize(0u);
this->data=NULL;
this->deleteVector();
}
edk::network::PackageGroup::~PackageGroup(){
//
}
//set the packSize
void edk::network::PackageGroup::setPackSize(edk::uint32 packSize){
if(packSize){
this->totalSize = packSize;
}
else{
//else set the normal packSize
this->totalSize=1000u;
}
}
//Add the vector to generate the packages
bool edk::network::PackageGroup::addVector(edk::classID vec,edk::uint32 size,edk::uint32 id,edk::uint32 packSize){
//clean the group
if(vec && size){
if(packSize){
//test if the packSize is diferent
if(this->totalSize!=packSize)
this->setPackSize(packSize);
}
bool ret=true;
//get the size of packages
edk::uint32 total = size / this->totalSize;
//size of the last package
edk::uint32 lastSize = size % this->totalSize;
edk::network::Package* pack=NULL;
edk::uint8* temp = (edk::uint8*)vec;
edk::uint32 i=0u;
edk::uint32 packages = 0u;
//test the total
if(total){
//create the packages
packages = total;
//test if have a last package without the full size
if(lastSize)
packages++;
for(i=0u;i<total;i++){
//create the package
pack = new edk::network::Package;
if(pack){
//draw in the package
if(pack->drawVector(temp,this->totalSize,0u,i,id,packages)){
//add the pack in the tree
if(!this->tree.add(pack)){
delete pack;
ret=false;
break;
}
}
else{
//else delete the pack
delete pack;
ret=false;
break;
}
temp+=this->totalSize;
//clean the pack
pack=NULL;
}
else{
//else get the error
ret=false;
break;
}
}
}
else{
packages = 1u;
}
//test the ret and the last package
if(ret && lastSize){
//add the last package
pack = new edk::network::Package;
if(pack){
//draw in the package
if(pack->drawVector(temp,lastSize,this->totalSize,i,id,packages)){
//add the pack in the tree
if(!this->tree.add(pack)){
delete pack;
ret=false;
}
}
else{
//else delete the pack
delete pack;
ret=false;
}
pack=NULL;
}
else{
ret=false;
}
}
//if ret is false; clean the group
if(!ret)
this->cleanGroup();
return ret;
}
return false;
}
//delete the vector
void edk::network::PackageGroup::deleteVector(){
if(this->data){
delete[] this->data;
}
this->data=NULL;
this->dataSize=0u;
this->id=0u;
}
//return the vector
edk::uint8* edk::network::PackageGroup::getVector(){
return this->data;
}
edk::uint32 edk::network::PackageGroup::getVectorSize(){
return this->dataSize;
}
//return the ID
edk::uint32 edk::network::PackageGroup::getID(){
return this->id;
}
//add a package
void edk::network::PackageGroup::addPackageBegin(){
this->cleanGroup();
this->deleteVector();
}
bool edk::network::PackageGroup::addPackage(edk::classID vec,edk::uint32 size){
//test the package
if(vec && size){
//test if the pack is the first
if(!this->tree.size()){
//test if the package is broked
if(!edk::network::Package::headerIsBroken(vec)){
//then save the data
this->totalSize = edk::network::Package::getHeaderPackages(vec);
if(totalSize){
//save the ID
this->id = edk::network::Package::getHeaderId(vec);
}
else return false;
}
else return false;
}
else{
//else compare the new package with the data
if(!edk::network::Package::headerIsBroken(vec)){
//test if the header is diferent
if(this->totalSize!=edk::network::Package::getHeaderPackages(vec)
||
this->id!=edk::network::Package::getHeaderId(vec)
)
//then return false
return false;
}
else return false;
}
//create a new package
edk::network::Package* pack = new edk::network::Package;
if(pack){
//then set the header
if(pack->addPackage(vec,size)){
//add the pack on the tree
if(this->tree.add(pack)){
return true;
}
}
delete pack;
}
}
return false;
}
//end the add packages
bool edk::network::PackageGroup::addPackageEnd(){
//test if the packages are full
if(this->isPackagesFull()){
bool ret=true;
//load the packages size
edk::uint32 size=0u;
edk::network::Package* pack=NULL;
for(edk::uint32 i =0u;i<this->tree.size();i++){
//load the package
pack = this->tree.getElementInPosition(i);
if(pack){
//increment the size
size+=pack->getPackageSize();
}
else{
//else clean the size and break
size=0u;
ret=false;
break;
}
}
//test the size
if(size){
//create the new vector with the size
this->deleteVector();
this->dataSize = size;
this->data = new edk::uint8[this->dataSize];
if(this->data){
edk::uint32 dataPosition=0u;
//copy the vectors to the data
for(edk::uint32 i =0u;i<this->tree.size();i++){
//load the package
pack = this->tree.getElementInPosition(i);
if(pack){
//increment the size
memcpy(&this->data[dataPosition],pack->getPackageVector(),pack->getPackageSize());
//increment dataPosition
dataPosition+=pack->getPackageSize();
}
else{
ret=false;
break;
}
}
//test if the ret are false
if(!ret){
//delete the vector
this->deleteVector();
}
}
else{
ret=false;
this->deleteVector();
}
}
//delete the packages
this->cleanGroup();
return ret;
}
return false;
}
//test if the packages reach the end
bool edk::network::PackageGroup::isPackagesFull(){
//test if have totalPackages
if(this->totalSize){
//test if on the tree are que total
if(this->tree.size()==this->totalSize){
return true;
}
}
return false;
}
//test if have a vector in the position
bool edk::network::PackageGroup::haveVector(edk::uint32 position){
//test the position
if(position < this->tree.size()){
//return if have the vector
if(this->tree.getElementInPosition(position)){
return true;
}
}
return false;
}
//get a vector in the group
edk::classID edk::network::PackageGroup::getVector(edk::uint32 position){
//test the position
if(position < this->tree.size()){
//return the vector
edk::network::Package* pack = this->tree.getElementInPosition(position);
if(pack){
return pack->getVec();
}
}
return NULL;
}
edk::uint32 edk::network::PackageGroup::getVectorSize(edk::uint32 position){
//test the position
if(position < this->tree.size()){
//return the vector
edk::network::Package* pack = this->tree.getElementInPosition(position);
if(pack){
return pack->getVecSize();
}
}
return 0u;
}
edk::uint32 edk::network::PackageGroup::getPackageID(edk::uint32 position){
//test the position
if(position < this->tree.size()){
//return the vector
edk::network::Package* pack = this->tree.getElementInPosition(position);
if(pack){
return pack->getID();
}
}
return 0u;
}
//clean the group
void edk::network::PackageGroup::cleanGroup(){
//delete all packages in the tree
edk::network::Package* temp=NULL;
for(register edk::uint32 i=0u;i<this->tree.size();i++){
temp = this->tree.getElementInPosition(i);
if(temp){
delete temp;
}
temp=NULL;
}
this->tree.clean();
}
//get the tree size
edk::uint32 edk::network::PackageGroup::getPackages(){
return this->tree.size();
}
//get the total size of packagess
edk::uint32 edk::network::PackageGroup::getTotalPackages(){
//test if have some package
if(this->tree.size()){
//get the first package
edk::network::Package* pack = this->tree.getElementInPosition(0u);
if(pack){
//get the number of packages
return pack->getPackages();
}
}
return 0u;
}
//read the package size
edk::uint32 edk::network::PackageGroup::readPackageSize(edk::classID vec){
//test the vector
if(vec){
//get the header
return edk::network::Package::getHeaderFullSize(vec);
}
return 0u;
}
| 30.39312 | 124 | 0.535004 | [
"vector"
] |
5ef826693e24d7e263576e9aab3e4053c5635334 | 36,937 | cpp | C++ | lib/src/models/image.cpp | efe13/imgbrd-grabber | 63251cb5170ac0dc7add391f233e7a0edb2f9094 | [
"Apache-2.0"
] | null | null | null | lib/src/models/image.cpp | efe13/imgbrd-grabber | 63251cb5170ac0dc7add391f233e7a0edb2f9094 | [
"Apache-2.0"
] | null | null | null | lib/src/models/image.cpp | efe13/imgbrd-grabber | 63251cb5170ac0dc7add391f233e7a0edb2f9094 | [
"Apache-2.0"
] | null | null | null | #include <QEventLoop>
#include <QRegularExpression>
#include "commands/commands.h"
#include "downloader/extension-rotator.h"
#include "downloader/file-downloader.h"
#include "functions.h"
#include "models/api/api.h"
#include "models/filename.h"
#include "models/image.h"
#include "models/page.h"
#include "models/post-filter.h"
#include "models/profile.h"
#include "models/site.h"
#include "models/source.h"
#include "tags/tag-database.h"
#include "tags/tag-stylist.h"
#define MAX_LOAD_FILESIZE (1024*1024*50)
QString removeCacheUrl(QString url)
{
QString get = url.section('?', 1, 1);
if (get.isEmpty())
return url;
// Only remove ?integer
bool ok;
get.toInt(&ok);
if (ok)
return url.section('?', 0, 0);
return url;
}
Image::Image()
: QObject(), m_profile(nullptr), m_extensionRotator(nullptr)
{ }
// TODO(Bionus): clean up this mess
Image::Image(const Image &other)
: QObject(other.parent())
{
m_parent = other.m_parent;
m_isGallery = other.m_isGallery;
m_id = other.m_id;
m_score = other.m_score;
m_parentId = other.m_parentId;
m_fileSize = other.m_fileSize;
m_authorId = other.m_authorId;
m_hasChildren = other.m_hasChildren;
m_hasNote = other.m_hasNote;
m_hasComments = other.m_hasComments;
m_hasScore = other.m_hasScore;
m_url = other.m_url;
m_md5 = other.m_md5;
m_author = other.m_author;
m_name = other.m_name;
m_status = other.m_status;
m_rating = other.m_rating;
m_source = other.m_source;
m_savePath = other.m_savePath;
m_pageUrl = other.m_pageUrl;
m_fileUrl = other.m_fileUrl;
m_sampleUrl = other.m_sampleUrl;
m_previewUrl = other.m_previewUrl;
m_size = other.m_size;
m_imagePreview = other.m_imagePreview;
m_createdAt = other.m_createdAt;
m_data = other.m_data;
m_loadDetails = other.m_loadDetails;
m_loadImage = other.m_loadImage;
m_tags = other.m_tags;
m_pools = other.m_pools;
m_timer = other.m_timer;
m_profile = other.m_profile;
m_settings = other.m_settings;
m_search = other.m_search;
m_parentSite = other.m_parentSite;
m_extensionRotator = other.m_extensionRotator;
m_loadingPreview = other.m_loadingPreview;
m_loadingDetails = other.m_loadingDetails;
m_loadingImage = other.m_loadingImage;
m_tryingSample = other.m_tryingSample;
}
Image::Image(Site *site, QMap<QString, QString> details, Profile *profile, Page* parent)
: m_profile(profile), m_id(0), m_parentSite(site), m_extensionRotator(nullptr)
{
m_settings = m_profile->getSettings();
// Parents
if (m_parentSite == nullptr)
{
log(QStringLiteral("Image has nullptr parent, aborting creation."));
return;
}
// Other details
m_isGallery = details.contains("type") && details["type"] == "gallery";
m_md5 = details.contains("md5") ? details["md5"] : "";
m_author = details.contains("author") ? details["author"] : "";
m_name = details.contains("name") ? details["name"] : "";
m_status = details.contains("status") ? details["status"] : "";
m_search = parent != nullptr ? parent->search() : (details.contains("search") ? details["search"].split(' ') : QStringList());
m_id = details.contains("id") ? details["id"].toULongLong() : 0;
m_score = details.contains("score") ? details["score"].toInt() : 0;
m_hasScore = details.contains("score");
m_parentId = details.contains("parent_id") ? details["parent_id"].toInt() : 0;
m_fileSize = details.contains("file_size") ? details["file_size"].toInt() : 0;
m_authorId = details.contains("creator_id") ? details["creator_id"].toInt() : 0;
m_hasChildren = details.contains("has_children") && details["has_children"] == "true";
m_hasNote = details.contains("has_note") && details["has_note"] == "true";
m_hasComments = details.contains("has_comments") && details["has_comments"] == "true";
m_fileUrl = details.contains("file_url") ? m_parentSite->fixUrl(details["file_url"]) : QUrl();
m_sampleUrl = details.contains("sample_url") ? m_parentSite->fixUrl(details["sample_url"]) : QUrl();
m_previewUrl = details.contains("preview_url") ? m_parentSite->fixUrl(details["preview_url"]) : QUrl();
m_size = QSize(details.contains("width") ? details["width"].toInt() : 0, details.contains("height") ? details["height"].toInt() : 0);
m_source = details.contains("source") ? details["source"] : "";
// Page url
if (details.contains("page_url"))
{ m_pageUrl = details["page_url"]; }
else
{
Api *api = m_parentSite->detailsApi();
if (api != Q_NULLPTR)
{ m_pageUrl = api->detailsUrl(m_id, m_md5, m_parentSite).url; }
}
m_pageUrl = site->fixUrl(m_pageUrl).toString();
// Rating
setRating(details.contains("rating") ? details["rating"] : "");
// Tags
QStringList types = QStringList() << "general" << "artist" << "character" << "copyright" << "model" << "species" << "meta";
for (const QString &typ : types)
{
QString key = "tags_" + typ;
if (!details.contains(key))
continue;
TagType ttype(typ);
QStringList t = details[key].split(' ', QString::SkipEmptyParts);
for (QString tg : t)
{
tg.replace("&", "&");
m_tags.append(Tag(tg, ttype));
}
}
if (m_tags.isEmpty() && details.contains("tags"))
{
QString tgs = QString(details["tags"]).replace(QRegularExpression("[\r\n\t]+"), " ");
// Automatically find tag separator and split the list
int commas = tgs.count(", ");
int spaces = tgs.count(" ");
const QStringList &t = commas >= 10 || (commas > 0 && (spaces - commas) / commas < 2)
? tgs.split(", ", QString::SkipEmptyParts)
: tgs.split(" ", QString::SkipEmptyParts);
for (QString tg : t)
{
tg.replace("&", "&");
int colon = tg.indexOf(':');
if (colon != -1)
{
QString tp = tg.left(colon).toLower();
if (tp == "user")
{ m_author = tg.mid(colon + 1); }
else if (tp == "score")
{ m_score = tg.midRef(colon + 1).toInt(); }
else if (tp == "size")
{
QStringList size = tg.mid(colon + 1).split('x');
if (size.size() == 2)
m_size = QSize(size[0].toInt(), size[1].toInt());
}
else if (tp == "rating")
{ setRating(tg.mid(colon + 1)); }
else
{ m_tags.append(Tag(tg)); }
}
else
{ m_tags.append(Tag(tg)); }
}
}
// Complete missing tag type information
m_parentSite->tagDatabase()->load();
QStringList unknownTags;
for (Tag const &tag : qAsConst(m_tags))
if (tag.type().name() == "unknown")
unknownTags.append(tag.text());
QMap<QString, TagType> dbTypes = m_parentSite->tagDatabase()->getTagTypes(unknownTags);
for (Tag &tag : m_tags)
if (dbTypes.contains(tag.text()))
tag.setType(dbTypes[tag.text()]);
// Get file url and try to improve it to save bandwidth
m_url = m_fileUrl.toString();
QString ext = getExtension(m_url);
if (details.contains("ext") && !details["ext"].isEmpty())
{
QString realExt = details["ext"];
if (ext != realExt)
{ setFileExtension(realExt); }
}
else if (ext == QLatin1String("jpg") && !m_previewUrl.isEmpty())
{
bool fixed = false;
QString previewExt = getExtension(details["preview_url"]);
if (!m_sampleUrl.isEmpty())
{
// Guess extension from sample url
QString sampleExt = getExtension(details["sample_url"]);
if (sampleExt != QLatin1String("jpg") && sampleExt != QLatin1String("png") && sampleExt != ext && previewExt == ext)
{
m_url = setExtension(m_url, sampleExt);
fixed = true;
}
}
// Guess the extension from the tags
if (!fixed)
{
if ((hasTag(QStringLiteral("swf")) || hasTag(QStringLiteral("flash"))) && ext != QLatin1String("swf"))
{ setFileExtension(QStringLiteral("swf")); }
else if ((hasTag(QStringLiteral("gif")) || hasTag(QStringLiteral("animated_gif"))) && ext != QLatin1String("webm") && ext != QLatin1String("mp4"))
{ setFileExtension(QStringLiteral("gif")); }
else if (hasTag(QStringLiteral("mp4")) && ext != QLatin1String("gif") && ext != QLatin1String("webm"))
{ setFileExtension(QStringLiteral("mp4")); }
else if (hasTag(QStringLiteral("animated_png")) && ext != QLatin1String("webm") && ext != QLatin1String("mp4"))
{ setFileExtension(QStringLiteral("png")); }
else if ((hasTag(QStringLiteral("webm")) || hasTag(QStringLiteral("animated"))) && ext != QLatin1String("gif") && ext != QLatin1String("mp4"))
{ setFileExtension(QStringLiteral("webm")); }
}
}
else if (details.contains("image") && details["image"].contains("MB // gif\" height=\"") && !m_url.endsWith(".gif", Qt::CaseInsensitive))
{ m_url = setExtension(m_url, QStringLiteral("gif")); }
// Remove ? in urls
m_url = removeCacheUrl(m_url);
m_fileUrl = removeCacheUrl(m_fileUrl.toString());
m_sampleUrl = removeCacheUrl(m_sampleUrl.toString());
m_previewUrl = removeCacheUrl(m_previewUrl.toString());
// We use the sample URL as the URL for zip files (ugoira) or if the setting is set
bool downloadOriginals = m_settings->value("Save/downloadoriginals", true).toBool();
if (!m_sampleUrl.isEmpty() && (getExtension(m_url) == "zip" || !downloadOriginals))
m_url = m_sampleUrl.toString();
// Creation date
m_createdAt = QDateTime();
if (details.contains("created_at"))
{ m_createdAt = qDateTimeFromString(details["created_at"]); }
else if (details.contains("date"))
{ m_createdAt = QDateTime::fromString(details["date"], Qt::ISODate); }
// Setup extension rotator
bool animated = hasTag("gif") || hasTag("animated_gif") || hasTag("mp4") || hasTag("animated_png") || hasTag("webm") || hasTag("animated");
QStringList extensions = animated
? QStringList() << "webm" << "mp4" << "gif" << "jpg" << "png" << "jpeg" << "swf"
: QStringList() << "jpg" << "png" << "gif" << "jpeg" << "webm" << "swf" << "mp4";
m_extensionRotator = new ExtensionRotator(getExtension(m_url), extensions, this);
// Tech details
m_parent = parent;
m_loadDetails = nullptr;
m_loadImage = nullptr;
m_loadingPreview = false;
m_loadingDetails = false;
m_loadedDetails = false;
m_loadedImage = false;
m_loadingImage = false;
m_tryingSample = false;
m_pools = QList<Pool>();
}
void Image::loadDetails(bool rateLimit)
{
if (m_loadingDetails)
return;
if (m_loadedDetails || m_pageUrl.isEmpty())
{
emit finishedLoadingTags();
return;
}
m_parentSite->getAsync(rateLimit ? Site::QueryType::Retry : Site::QueryType::Details, m_pageUrl, [this](QNetworkReply *reply) {
if (m_loadDetails != nullptr)
m_loadDetails->deleteLater();
m_loadDetails = reply;
m_loadDetails->setParent(this);
m_loadingDetails = true;
connect(m_loadDetails, &QNetworkReply::finished, this, &Image::parseDetails);
});
}
void Image::abortTags()
{
if (m_loadingDetails && m_loadDetails->isRunning())
{
m_loadDetails->abort();
m_loadingDetails = false;
}
}
void Image::parseDetails()
{
m_loadingDetails = false;
// Aborted
if (m_loadDetails->error() == QNetworkReply::OperationCanceledError)
{
m_loadDetails->deleteLater();
m_loadDetails = nullptr;
return;
}
// Check redirection
QUrl redir = m_loadDetails->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl();
if (!redir.isEmpty())
{
m_pageUrl = redir;
loadDetails();
return;
}
int statusCode = m_loadDetails->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
if (statusCode == 429)
{
log(QStringLiteral("Details limit reached (429). New try."));
loadDetails(true);
return;
}
QString source = QString::fromUtf8(m_loadDetails->readAll());
// Get an api able to parse details
Api *api = m_parentSite->detailsApi();
if (api == Q_NULLPTR)
return;
// Parse source
ParsedDetails ret = api->parseDetails(source, m_parentSite);
if (!ret.error.isEmpty())
{
log(QStringLiteral("[%1][%2] %3").arg(m_parentSite->url(), api->getName(), ret.error), Logger::Warning);
emit finishedLoadingTags();
return;
}
// Fill data from parsing result
if (!ret.pools.isEmpty())
{ m_pools = ret.pools; }
if (!ret.tags.isEmpty())
{ m_tags = ret.tags; }
if (ret.createdAt.isValid())
{ m_createdAt = ret.createdAt; }
// Image url
if (!ret.imageUrl.isEmpty())
{
QString before = m_url;
QUrl newUrl = m_parentSite->fixUrl(ret.imageUrl, before);
m_url = newUrl.toString();
m_fileUrl = newUrl;
if (before != m_url)
{
delete m_extensionRotator;
m_extensionRotator = nullptr;
setFileSize(0);
emit urlChanged(before, m_url);
}
}
// Get rating from tags
if (m_rating.isEmpty())
{
int ratingTagIndex = -1;
for (int it = 0; it < m_tags.count(); ++it)
{
if (m_tags[it].type().name() == "rating")
{
m_rating = m_tags[it].text();
ratingTagIndex = it;
break;
}
}
if (ratingTagIndex != -1)
{ m_tags.removeAt(ratingTagIndex); }
}
m_loadDetails->deleteLater();
m_loadDetails = nullptr;
m_loadedDetails = true;
refreshTokens();
emit finishedLoadingTags();
}
/**
* Return the filename of the image according to the user's settings.
* @param fn The user's filename.
* @param pth The user's root save path.
* @param counter Current image count (used for batch downloads).
* @param complex Whether the filename is complex or not (contains conditionals).
* @param simple True to force using the fn and pth parameters.
* @return The filename of the image, with any token replaced.
*/
QStringList Image::path(QString fn, QString pth, int counter, bool complex, bool simple, bool maxLength, bool shouldFixFilename, bool getFull) const
{
if (!simple)
{
if (fn.isEmpty())
{ fn = m_settings->value("Save/filename").toString(); }
if (pth.isEmpty())
{ pth = m_settings->value("Save/path").toString(); }
}
Filename filename(fn);
return filename.path(*this, m_profile, pth, counter, complex, maxLength, shouldFixFilename, getFull);
}
void Image::loadImage(bool inMemory, bool force)
{
if (m_loadingImage)
return;
if (m_loadedImage && !force)
{
emit finishedImage(QNetworkReply::NoError, "");
return;
}
if (m_fileSize > MAX_LOAD_FILESIZE && inMemory)
{
emit finishedImage(static_cast<QNetworkReply::NetworkError>(500), "");
return;
}
if (m_loadImage != nullptr)
m_loadImage->deleteLater();
if (force)
setUrl(fileUrl().toString());
m_loadImage = m_parentSite->get(m_parentSite->fixUrl(m_url), m_parent, "image", this);
m_loadImage->setParent(this);
m_loadingImage = true;
m_loadedImage = false;
m_data.clear();
if (inMemory)
{
connect(m_loadImage, &QNetworkReply::downloadProgress, this, &Image::downloadProgressImageInMemory);
connect(m_loadImage, &QNetworkReply::finished, this, &Image::finishedImageInMemory);
}
else
{
connect(m_loadImage, &QNetworkReply::downloadProgress, this, &Image::downloadProgressImageBasic);
connect(m_loadImage, &QNetworkReply::finished, this, &Image::finishedImageBasic);
}
}
void Image::finishedImageBasic()
{
finishedImageS(false);
}
void Image::finishedImageInMemory()
{
finishedImageS(true);
}
void Image::finishedImageS(bool inMemory)
{
m_loadingImage = false;
// Aborted
if (m_loadImage->error() == QNetworkReply::OperationCanceledError)
{
m_loadImage->deleteLater();
m_loadImage = nullptr;
if (m_fileSize > MAX_LOAD_FILESIZE)
{ emit finishedImage(static_cast<QNetworkReply::NetworkError>(500), ""); }
else
{ emit finishedImage(QNetworkReply::OperationCanceledError, ""); }
return;
}
QUrl redir = m_loadImage->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl();
if (!redir.isEmpty())
{
m_loadImage->deleteLater();
m_loadImage = nullptr;
m_url = redir.toString();
loadImage();
return;
}
if (m_loadImage->error() == QNetworkReply::ContentNotFoundError)
{
bool sampleFallback = m_settings->value("Save/samplefallback", true).toBool();
QString newext = m_extensionRotator != nullptr ? m_extensionRotator->next() : "";
bool shouldFallback = sampleFallback && !m_sampleUrl.isEmpty();
bool isLast = newext.isEmpty() || (shouldFallback && m_tryingSample);
if (!isLast || (shouldFallback && !m_tryingSample))
{
if (isLast)
{
setUrl(m_sampleUrl.toString());
m_tryingSample = true;
log(QStringLiteral("Image not found. New try with its sample..."));
}
else
{
m_url = setExtension(m_url, newext);
log(QStringLiteral("Image not found. New try with extension %1 (%2)...").arg(newext, m_url));
}
loadImage();
return;
}
else
{
log(QStringLiteral("Image not found."));
}
}
else if (inMemory)
{
m_data.append(m_loadImage->readAll());
if (m_fileSize <= 0)
{ m_fileSize = m_data.size(); }
}
QNetworkReply::NetworkError error = m_loadImage->error();
QString errorString = m_loadImage->errorString();
m_loadedImage = (error == QNetworkReply::ContentNotFoundError || error == QNetworkReply::NoError);
m_loadImageError = error;
m_loadImage->deleteLater();
m_loadImage = nullptr;
emit finishedImage(m_loadImageError, errorString);
}
void Image::downloadProgressImageBasic(qint64 v1, qint64 v2)
{
downloadProgressImageS(v1, v2, false);
}
void Image::downloadProgressImageInMemory(qint64 v1, qint64 v2)
{
downloadProgressImageS(v1, v2, true);
}
void Image::downloadProgressImageS(qint64 v1, qint64 v2, bool inMemory)
{
// Set filesize if not set
if (m_fileSize == 0 || m_fileSize < v2 / 2)
m_fileSize = v2;
if (m_loadImage == nullptr || v2 <= 0)
return;
if (inMemory)
{
if (m_fileSize > MAX_LOAD_FILESIZE)
{
m_loadImage->abort();
return;
}
m_data.append(m_loadImage->readAll());
}
emit downloadProgressImage(v1, v2);
}
void Image::abortImage()
{
if (m_loadingImage && m_loadImage->isRunning())
{
m_loadImage->abort();
m_loadingImage = false;
}
}
/**
* Try to guess the size of the image in pixels for sorting.
* @return The guessed number of pixels in the image.
*/
int Image::value() const
{
// Get from image size
if (!m_size.isEmpty())
return m_size.width() * m_size.height();
// Get from tags
if (hasTag("incredibly_absurdres"))
return 10000 * 10000;
else if (hasTag("absurdres"))
return 3200 * 2400;
else if (hasTag("highres"))
return 1600 * 1200;
else if (hasTag("lowres"))
return 500 * 500;
return 1200 * 900;
}
QStringList Image::stylishedTags(Profile *profile) const
{
TagStylist stylist(profile);
return stylist.stylished(m_tags);
}
Image::SaveResult Image::save(const QString &path, bool force, bool basic, bool addMd5, bool startCommands, int count, bool postSave)
{
SaveResult res = SaveResult::Saved;
QFile f(path);
if (!f.exists() || force)
{
QPair<QString, QString> md5action = m_profile->md5Action(md5());
QString whatToDo = md5action.first;
QString md5Duplicate = md5action.second;
// Only create the destination directory if we're going to put a file there
if (md5Duplicate.isEmpty() || force || whatToDo != "ignore")
{
QString p = path.section(QDir::separator(), 0, -2);
QDir path_to_file(p), dir;
if (!path_to_file.exists() && !dir.mkpath(p))
{
log(QStringLiteral("Impossible to create the destination folder: %1.").arg(p), Logger::Error);
return SaveResult::Error;
}
}
if (md5Duplicate.isEmpty() || whatToDo == "save" || force)
{
if (!m_savePath.isEmpty() && QFile::exists(m_savePath))
{
log(QStringLiteral("Saving image in <a href=\"file:///%1\">%1</a> (from <a href=\"file:///%2\">%2</a>)").arg(path, m_savePath));
QFile(m_savePath).copy(path);
}
else
{
if (m_data.isEmpty())
{ return SaveResult::NotLoaded; }
log(QStringLiteral("Saving image in <a href=\"file:///%1\">%1</a>").arg(path));
if (f.open(QFile::WriteOnly))
{
if (f.write(m_data) < 0)
{
f.close();
f.remove();
log(QStringLiteral("File saving error: %1)").arg(f.errorString()), Logger::Error);
return SaveResult::Error;
}
f.close();
}
else
{
log(QStringLiteral("Unable to open file"));
return SaveResult::Error;
}
}
}
else if (whatToDo == "copy")
{
log(QStringLiteral("Copy from <a href=\"file:///%1\">%1</a> to <a href=\"file:///%2\">%2</a>").arg(md5Duplicate, path));
QFile(md5Duplicate).copy(path);
res = SaveResult::Copied;
}
else if (whatToDo == "move")
{
log(QStringLiteral("Moving from <a href=\"file:///%1\">%1</a> to <a href=\"file:///%2\">%2</a>").arg(md5Duplicate, path));
QFile::rename(md5Duplicate, path);
m_profile->setMd5(md5(), path);
res = SaveResult::Moved;
}
else
{
log(QStringLiteral("MD5 \"%1\" of the image <a href=\"%2\">%2</a> already found in file <a href=\"file:///%3\">%3</a>").arg(md5(), url(), md5Duplicate));
return SaveResult::Ignored;
}
if (postSave)
{ postSaving(path, addMd5 && res == SaveResult::Saved, startCommands, count, basic); }
}
else
{ res = SaveResult::AlreadyExists; }
return res;
}
void Image::postSaving(const QString &path, bool addMd5, bool startCommands, int count, bool basic)
{
if (addMd5)
{ m_profile->addMd5(md5(), path); }
// Save info to a text file
if (!basic)
{
auto logFiles = getExternalLogFiles(m_settings);
for (auto it = logFiles.begin(); it != logFiles.end(); ++it)
{
auto logFile = it.value();
QString textfileFormat = logFile["content"].toString();
QStringList cont = this->path(textfileFormat, "", count, true, true, false, false, false);
if (!cont.isEmpty())
{
int locationType = logFile["locationType"].toInt();
QString contents = cont.first();
// File path
QString fileTagsPath;
if (locationType == 0)
fileTagsPath = this->path(logFile["filename"].toString(), logFile["path"].toString(), 0, true, false, true, true, true).first();
else if (locationType == 1)
fileTagsPath = logFile["uniquePath"].toString();
else if (locationType == 2)
fileTagsPath = path + logFile["suffix"].toString();
// Replace some post-save tokens
contents.replace("%path:nobackslash%", QDir::toNativeSeparators(path).replace("\\", "/"))
.replace("%path%", QDir::toNativeSeparators(path));
// Append to file if necessary
QFile fileTags(fileTagsPath);
bool append = fileTags.exists();
if (fileTags.open(QFile::WriteOnly | QFile::Append | QFile::Text))
{
if (append)
fileTags.write("\n");
fileTags.write(contents.toUtf8());
fileTags.close();
}
}
}
}
// Keep original date
if (m_settings->value("Save/keepDate", true).toBool())
setFileCreationDate(path, createdAt());
// Commands
Commands &commands = m_profile->getCommands();
if (startCommands)
{ commands.before(); }
for (const Tag &tag : qAsConst(m_tags))
{ commands.tag(*this, tag, false); }
commands.image(*this, path);
for (const Tag &tag : qAsConst(m_tags))
{ commands.tag(*this, tag, true); }
if (startCommands)
{ commands.after(); }
setSavePath(path);
}
QMap<QString, Image::SaveResult> Image::save(const QStringList &paths, bool addMd5, bool startCommands, int count, bool force)
{
QMap<QString, Image::SaveResult> res;
for (const QString &path : paths)
res.insert(path, save(path, force, false, addMd5, startCommands, count));
return res;
}
QMap<QString, Image::SaveResult> Image::save(const QString &filename, const QString &path, bool addMd5, bool startCommands, int count)
{
QStringList paths = this->path(filename, path, count, true, false, true, true, true);
return save(paths, addMd5, startCommands, count, false);
}
QList<Tag> Image::filteredTags(const QStringList &remove) const
{
QList<Tag> tags;
QRegExp reg;
reg.setCaseSensitivity(Qt::CaseInsensitive);
reg.setPatternSyntax(QRegExp::Wildcard);
for (const Tag &tag : m_tags)
{
bool removed = false;
for (const QString &rem : remove)
{
reg.setPattern(rem);
if (reg.exactMatch(tag.text()))
{
removed = true;
break;
}
}
if (!removed)
tags.append(tag);
}
return tags;
}
QString Image::url() const { return m_url; }
QString Image::rating() const { return m_rating; }
Site *Image::parentSite() const { return m_parentSite; }
QList<Tag> Image::tags() const { return m_tags; }
QList<Pool> Image::pools() const { return m_pools; }
qulonglong Image::id() const { return m_id; }
int Image::fileSize() const { return m_fileSize; }
int Image::width() const { return m_size.width(); }
int Image::height() const { return m_size.height(); }
QDateTime Image::createdAt() const { return m_createdAt; }
QUrl Image::fileUrl() const { return m_fileUrl; }
QUrl Image::pageUrl() const { return m_pageUrl; }
QSize Image::size() const { return m_size; }
QPixmap Image::previewImage() const { return m_imagePreview; }
const QPixmap &Image::previewImage() { return m_imagePreview; }
Page *Image::page() const { return m_parent; }
const QByteArray&Image::data() const { return m_data; }
bool Image::isGallery() const { return m_isGallery; }
ExtensionRotator *Image::extensionRotator() const { return m_extensionRotator; }
void Image::setPreviewImage(const QPixmap &preview)
{ m_imagePreview = preview; }
void Image::setSavePath(const QString &path)
{
m_savePath = path;
refreshTokens();
}
bool Image::shouldDisplaySample() const
{
bool getOriginals = m_settings->value("Save/downloadoriginals", true).toBool();
bool viewSample = m_settings->value("Zoom/viewSamples", false).toBool();
return !m_sampleUrl.isEmpty() && (!getOriginals || viewSample);
}
QUrl Image::getDisplayableUrl() const
{ return shouldDisplaySample() ? m_sampleUrl : m_url; }
QStringList Image::tagsString() const
{
QStringList tags;
tags.reserve(m_tags.count());
for (const Tag &tag : m_tags)
tags.append(tag.text());
return tags;
}
void Image::setUrl(const QString &u)
{
setFileSize(0);
emit urlChanged(m_url, u);
m_url = u;
refreshTokens();
}
void Image::setSize(QSize size) { m_size = size; refreshTokens(); }
void Image::setFileSize(int s) { m_fileSize = s; refreshTokens(); }
void Image::setData(const QByteArray &d)
{
m_data = d;
// Detect file extension from data headers
bool headerDetection = m_settings->value("Save/headerDetection", true).toBool();
if (headerDetection)
{
QString ext = getExtensionFromHeader(m_data.left(12));
QString currentExt = getExtension(m_url);
if (!ext.isEmpty() && ext != currentExt)
{
log(QStringLiteral("Setting image extension from header: '%1' (was '%2').").arg(ext, currentExt), Logger::Info);
setFileExtension(ext);
}
}
// Set MD5 by hashing this data if we don't already have it
if (m_md5.isEmpty())
{
m_md5 = QCryptographicHash::hash(m_data, QCryptographicHash::Md5).toHex();
refreshTokens();
}
}
void Image::setTags(const QList<Tag> &tags)
{
m_tags = tags;
refreshTokens();
}
QColor Image::color() const
{
// Blacklisted
QStringList detected = PostFilter::blacklisted(tokens(m_profile), m_profile->getBlacklist());
if (!detected.isEmpty())
return QColor(0, 0, 0);
// Favorited (except for exact favorite search)
auto favorites = m_profile->getFavorites();
for (const Tag &tag : m_tags)
if (!m_parent->search().contains(tag.text()))
for (const Favorite &fav : favorites)
if (fav.getName() == tag.text())
return QColor(255, 192, 203);
// Image with a parent
if (m_parentId != 0)
return QColor(204, 204, 0);
// Image with children
if (m_hasChildren)
return QColor(0, 255, 0);
// Pending image
if (m_status == "pending")
return QColor(0, 0, 255);
return QColor();
}
QString Image::tooltip() const
{
if (m_isGallery)
return QStringLiteral("%1%2")
.arg(m_id == 0 ? " " : tr("<b>ID:</b> %1<br/>").arg(m_id))
.arg(m_name.isEmpty() ? " " : tr("<b>Name:</b> %1<br/>").arg(m_name));
double size = m_fileSize;
QString unit = getUnit(&size);
return QStringLiteral("%1%2%3%4%5%6%7%8")
.arg(m_tags.isEmpty() ? " " : tr("<b>Tags:</b> %1<br/><br/>").arg(stylishedTags(m_profile).join(" ")))
.arg(m_id == 0 ? " " : tr("<b>ID:</b> %1<br/>").arg(m_id))
.arg(m_rating.isEmpty() ? " " : tr("<b>Rating:</b> %1<br/>").arg(m_rating))
.arg(m_hasScore ? tr("<b>Score:</b> %1<br/>").arg(m_score) : " ")
.arg(m_author.isEmpty() ? " " : tr("<b>User:</b> %1<br/><br/>").arg(m_author))
.arg(m_size.width() == 0 || m_size.height() == 0 ? " " : tr("<b>Size:</b> %1 x %2<br/>").arg(QString::number(m_size.width()), QString::number(m_size.height())))
.arg(m_fileSize == 0 ? " " : tr("<b>Filesize:</b> %1 %2<br/>").arg(QString::number(size), unit))
.arg(!m_createdAt.isValid() ? " " : tr("<b>Date:</b> %1").arg(m_createdAt.toString(tr("'the 'MM/dd/yyyy' at 'hh:mm"))));
}
QList<QStrP> Image::detailsData() const
{
QString unknown = tr("<i>Unknown</i>");
QString yes = tr("yes");
QString no = tr("no");
return {
QStrP(tr("Tags"), stylishedTags(m_profile).join(' ')),
QStrP(),
QStrP(tr("ID"), m_id != 0 ? QString::number(m_id) : unknown),
QStrP(tr("MD5"), !m_md5.isEmpty() ? m_md5 : unknown),
QStrP(tr("Rating"), !m_rating.isEmpty() ? m_rating : unknown),
QStrP(tr("Score"), QString::number(m_score)),
QStrP(tr("Author"), !m_author.isEmpty() ? m_author : unknown),
QStrP(),
QStrP(tr("Date"), m_createdAt.isValid() ? m_createdAt.toString(tr("'the' MM/dd/yyyy 'at' hh:mm")) : unknown),
QStrP(tr("Size"), !m_size.isEmpty() ? QString::number(m_size.width())+"x"+QString::number(m_size.height()) : unknown),
QStrP(tr("Filesize"), m_fileSize != 0 ? formatFilesize(m_fileSize) : unknown),
QStrP(),
QStrP(tr("Page"), !m_pageUrl.isEmpty() ? QString("<a href=\"%1\">%1</a>").arg(m_pageUrl.toString()) : unknown),
QStrP(tr("URL"), !m_fileUrl.isEmpty() ? QString("<a href=\"%1\">%1</a>").arg(m_fileUrl.toString()) : unknown),
QStrP(tr("Source"), !m_source.isEmpty() ? QString("<a href=\"%1\">%1</a>").arg(m_source) : unknown),
QStrP(tr("Sample"), !m_sampleUrl.isEmpty() ? QString("<a href=\"%1\">%1</a>").arg(m_sampleUrl.toString()) : unknown),
QStrP(tr("Thumbnail"), !m_previewUrl.isEmpty() ? QString("<a href=\"%1\">%1</a>").arg(m_previewUrl.toString()) : unknown),
QStrP(),
QStrP(tr("Parent"), m_parentId != 0 ? tr("yes (#%1)").arg(m_parentId) : no),
QStrP(tr("Comments"), m_hasComments ? yes : no),
QStrP(tr("Children"), m_hasChildren ? yes : no),
QStrP(tr("Notes"), m_hasNote ? yes : no),
};
}
QString Image::md5() const
{
// If we know the path to the image or its content but not its md5, we calculate it first
if (m_md5.isEmpty() && (!m_savePath.isEmpty() || !m_data.isEmpty()))
{
QCryptographicHash hash(QCryptographicHash::Md5);
// Calculate from image data
if (!m_data.isEmpty())
{
hash.addData(m_data);
}
// Calculate from image path
else
{
QFile f(m_savePath);
f.open(QFile::ReadOnly);
hash.addData(&f);
f.close();
}
m_md5 = hash.result().toHex();
}
return m_md5;
}
bool Image::hasTag(QString tag) const
{
tag = tag.trimmed();
for (const Tag &t : m_tags)
if (QString::compare(t.text(), tag, Qt::CaseInsensitive) == 0)
return true;
return false;
}
bool Image::hasAnyTag(const QStringList &tags) const
{
for (const QString &tag : tags)
if (this->hasTag(tag))
return true;
return false;
}
bool Image::hasAllTags(const QStringList &tags) const
{
for (const QString &tag : tags)
if (!this->hasTag(tag))
return false;
return true;
}
void Image::unload()
{
m_loadedImage = false;
m_data.clear();
}
void Image::setRating(const QString &rating)
{
QMap<QString, QString> assoc;
assoc["s"] = "safe";
assoc["q"] = "questionable";
assoc["e"] = "explicit";
if (assoc.contains(rating))
{ m_rating = assoc.value(rating); }
else
{ m_rating = rating.toLower(); }
refreshTokens();
}
void Image::setFileExtension(const QString &ext)
{
m_url = setExtension(m_url, ext);
m_fileUrl = setExtension(m_fileUrl.toString(), ext);
refreshTokens();
}
bool Image::isVideo() const
{
QString ext = getExtension(m_url).toLower();
return ext == "mp4" || ext == "webm";
}
QString Image::isAnimated() const
{
QString ext = getExtension(m_url).toLower();
if (ext == "gif" || ext == "apng")
return ext;
if (ext == "png" && (hasTag(QStringLiteral("animated")) || hasTag(QStringLiteral("animated_png"))))
return QStringLiteral("apng");
return QString();
}
QString Image::url(Size size) const
{
switch (size)
{
case Size::Thumbnail: return m_previewUrl.toString();
case Size::Sample: return m_sampleUrl.toString();
default: return m_url;
}
}
void Image::preload(const Filename &filename)
{
if (!filename.needExactTags(m_parentSite))
return;
QEventLoop loop;
QObject::connect(this, &Image::finishedLoadingTags, &loop, &QEventLoop::quit);
loadDetails();
loop.exec();
}
QStringList Image::paths(const Filename &filename, const QString &folder, int count) const
{
return path(filename.getFormat(), folder, count, true, false, true, true, true);
}
QMap<QString, Token> Image::generateTokens(Profile *profile) const
{
QSettings *settings = profile->getSettings();
QStringList ignore = profile->getIgnored();
QStringList remove = settings->value("ignoredtags").toString().split(' ', QString::SkipEmptyParts);
QMap<QString, Token> tokens;
// Pool
QRegularExpression poolRegexp("pool:(\\d+)");
QRegularExpressionMatch poolMatch = poolRegexp.match(m_search.join(' '));
tokens.insert("pool", Token(poolMatch.hasMatch() ? poolMatch.captured(1) : "", ""));
// Metadata
tokens.insert("filename", Token(QUrl::fromPercentEncoding(m_url.section('/', -1).section('.', 0, -2).toUtf8()), ""));
tokens.insert("website", Token(m_parentSite->url(), ""));
tokens.insert("websitename", Token(m_parentSite->name(), ""));
tokens.insert("md5", Token(md5(), ""));
tokens.insert("date", Token(m_createdAt, QDateTime()));
tokens.insert("id", Token(m_id, 0));
tokens.insert("rating", Token(m_rating, "unknown"));
tokens.insert("score", Token(m_score, 0));
tokens.insert("height", Token(m_size.height(), 0));
tokens.insert("width", Token(m_size.width(), 0));
tokens.insert("mpixels", Token(m_size.width() * m_size.height(), 0));
tokens.insert("url_file", Token(m_url, ""));
tokens.insert("url_sample", Token(m_sampleUrl.toString(), ""));
tokens.insert("url_thumbnail", Token(m_previewUrl.toString(), ""));
tokens.insert("url_page", Token(m_pageUrl.toString(), ""));
tokens.insert("source", Token(m_source, ""));
tokens.insert("filesize", Token(m_fileSize, 0));
tokens.insert("author", Token(m_author, ""));
tokens.insert("authorid", Token(m_authorId, 0));
tokens.insert("parentid", Token(m_parentId, 0));
// Flags
tokens.insert("has_children", Token(m_hasChildren, false));
tokens.insert("has_note", Token(m_hasNote, false));
tokens.insert("has_comments", Token(m_hasComments, false));
// Search
for (int i = 0; i < m_search.size(); ++i)
{ tokens.insert("search_" + QString::number(i + 1), Token(m_search[i], "")); }
for (int i = m_search.size(); i < 10; ++i)
{ tokens.insert("search_" + QString::number(i + 1), Token("", "")); }
tokens.insert("search", Token(m_search.join(' '), ""));
// Tags
QMap<QString, QStringList> details;
for (const Tag &tag : filteredTags(remove))
{
QString t = tag.text();
details[ignore.contains(t, Qt::CaseInsensitive) ? "general" : tag.type().name()].append(t);
details["alls"].append(t);
details["alls_namespaces"].append(tag.type().name());
QString underscored = QString(t);
underscored.replace(' ', '_');
details["allos"].append(underscored);
}
// Shorten copyrights
if (settings->value("Save/copyright_useshorter", true).toBool())
{
QStringList copyrights;
for (const QString &cop : details["copyright"])
{
bool found = false;
for (int r = 0; r < copyrights.size(); ++r)
{
if (copyrights.at(r).left(cop.size()) == cop.left(copyrights.at(r).size()))
{
if (cop.size() < copyrights.at(r).size())
{ copyrights[r] = cop; }
found = true;
}
}
if (!found)
{ copyrights.append(cop); }
}
details["copyright"] = copyrights;
}
// Tags
tokens.insert("general", Token(details["general"]));
tokens.insert("artist", Token(details["artist"], "replaceAll", "anonymous", "multiple artists"));
tokens.insert("copyright", Token(details["copyright"], "replaceAll", "misc", "crossover"));
tokens.insert("character", Token(details["character"], "replaceAll", "unknown", "group"));
tokens.insert("model", Token(details["model"], "replaceAll", "unknown", "multiple"));
tokens.insert("species", Token(details["species"], "replaceAll", "unknown", "multiple"));
tokens.insert("meta", Token(details["meta"], "replaceAll", "none", "multiple"));
tokens.insert("allos", Token(details["allos"]));
tokens.insert("allo", Token(details["allos"].join(' '), ""));
tokens.insert("tags", Token(details["alls"]));
tokens.insert("all", Token(details["alls"]));
tokens.insert("all_namespaces", Token(details["alls_namespaces"]));
// Extension
QString ext = getExtension(m_url);
if (settings->value("Save/noJpeg", true).toBool() && ext == "jpeg")
ext = "jpg";
tokens.insert("ext", Token(ext, "jpg"));
tokens.insert("filetype", Token(ext, "jpg"));
return tokens;
}
Image::SaveResult Image::preSave(const QString &path)
{
return save(path, false, false, false, false, 1, false);
}
void Image::postSave(QMap<QString, Image::SaveResult> result, bool addMd5, bool startCommands, int count)
{
const QString &path = result.firstKey();
Image::SaveResult res = result[path];
postSaving(path, addMd5 && res == SaveResult::Saved, startCommands, count);
}
| 29.981331 | 162 | 0.670033 | [
"model"
] |
5efb8989e8df2678a0f9f20e6474f5955c05b411 | 5,324 | cpp | C++ | src/yars/util/PlyLoader.cpp | kzahedi/YARS | 48d9fe4178d699fba38114d3b299a228da41293d | [
"MIT"
] | 4 | 2017-08-05T03:33:21.000Z | 2021-11-08T09:15:42.000Z | src/yars/util/PlyLoader.cpp | kzahedi/YARS | 48d9fe4178d699fba38114d3b299a228da41293d | [
"MIT"
] | null | null | null | src/yars/util/PlyLoader.cpp | kzahedi/YARS | 48d9fe4178d699fba38114d3b299a228da41293d | [
"MIT"
] | 1 | 2019-03-24T08:35:25.000Z | 2019-03-24T08:35:25.000Z | #include <yars/util/PlyLoader.h>
#include <yars/util/StringTokeniser.h>
#include <yars/types/Vertex.h>
#include <yars/util/FileSystemOperations.h>
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <vector>
PlyLoader* PlyLoader::_me = NULL;
PlyLoader* PlyLoader::instance()
{
if(_me == NULL) _me = new PlyLoader();
return _me;
}
PlyLoader::PlyLoader()
{
}
PlyLoader::~PlyLoader()
{
}
PlyData PlyLoader::get(string filename)
{
// for(map<string, PlyData>::iterator i = _data.begin(); i != _data.end(); i++)
// {
// if(i->first == filename) return i->second;
// }
if(_data.find(filename) == _data.end())
{
return __load(filename);
}
return _data[filename];
}
PlyData PlyLoader::__load(string filename)
{
if(!FileSystemOperations::doesFileExist(filename))
{
YarsErrorHandler::push("Ply loader: '%s' not found.", filename.c_str());
exit(-1);
}
int nrOfTokens = 0;
int nrOfFaces = 0;
int nrOfVertices = 0;
bool header = true;
int facesRead = 0;
int verticesRead = 0;
vector< vector<int> > faces;
Vertices vertices;
Triangles triangles;
ifstream input(filename.c_str());
for( string line; getline( input, line ); )
{
if(header)
{
if(line.find("element vertex") != string::npos)
{
vector<string> st = StringTokeniser::tokenise(line, " ");
nrOfVertices = atoi(st[2].c_str());
}
if(line.find("element face") != string::npos)
{
vector<string> st = StringTokeniser::tokenise(line, " ");
nrOfFaces = atoi(st[2].c_str());
}
if(line.find("property float") != string::npos)
{
nrOfTokens++;
}
if(line.find("end_header") != string::npos)
{
header = false;
}
}
else
{
if(verticesRead < nrOfVertices)
{
vector<string> st = StringTokeniser::tokenise(line, " ");
vector<float> values;
for(vector<string>::iterator s = st.begin(); s != st.end(); s++)
{
values.push_back(atof((*s).c_str()));
}
verticesRead++;
Vertex vertex;
if(values.size() > 6)
{
vertex.x = values[0];
vertex.y = values[1];
vertex.z = values[2];
vertex.nx = values[3];
vertex.ny = values[4];
vertex.nz = values[5];
vertex.s = values[6];
vertex.t = values[7];
vertex.stGiven = true;
}
else
{
vertex.x = values[0];
vertex.y = values[1];
vertex.z = values[2];
vertex.nx = values[3];
vertex.ny = values[4];
vertex.nz = values[5];
vertex.stGiven = false;
}
vertices.push_back(vertex);
}
else if(facesRead < nrOfFaces)
{
vector<string> st = StringTokeniser::tokenise(line, " ");
vector<int> values;
for(vector<string>::iterator s = st.begin(); s != st.end(); s++)
{
values.push_back(atoi((*s).c_str()));
}
facesRead++;
faces.push_back(values);
}
}
}
for(vector< vector<int> >::iterator v = faces.begin(); v != faces.end(); v++)
{
if((*v).size() == 4) // Triangle
{
Vertex a = vertices[(*v)[1]];
Vertex b = vertices[(*v)[2]];
Vertex c = vertices[(*v)[3]];
P3D a_normal(a.nx, a.ny, a.nz);
P3D b_normal(b.nx, b.ny, b.nz);
P3D c_normal(c.nx, c.ny, c.nz);
Triangle t((*v)[1], (*v)[2], (*v)[3],
a_normal, b_normal, c_normal,
P3D(a.x, a.y, a.z),
P3D(b.x, b.y, b.z),
P3D(c.x, c.y, c.z)
);
triangles.push_back(t);
}
else
{
Vertex a = vertices[(*v)[1]];
Vertex b = vertices[(*v)[2]];
Vertex c = vertices[(*v)[3]];
Vertex d = vertices[(*v)[4]];
P3D a_normal(a.nx, a.ny, a.nz);
P3D b_normal(b.nx, b.ny, b.nz);
P3D c_normal(c.nx, c.ny, c.nz);
P3D d_normal(d.nx, d.ny, d.nz);
if(a.stGiven)
{
Triangle t1((*v)[1], (*v)[3], (*v)[4],
a_normal, c_normal, d_normal,
P3D(a.x, a.y, a.z),
P3D(c.x, c.y, c.z),
P3D(d.x, d.y, d.z),
a.s, a.t,
c.s, c.t,
d.s, d.t);
Triangle t2((*v)[1], (*v)[2], (*v)[3],
a_normal, b_normal, c_normal,
P3D(a.x, a.y, a.z),
P3D(b.x, b.y, b.z),
P3D(c.x, c.y, c.z),
a.s, a.t,
b.s, b.t,
c.s, c.t);
triangles.push_back(t1);
triangles.push_back(t2);
}
else
{
Triangle t1((*v)[1], (*v)[3], (*v)[4],
a_normal, c_normal, d_normal,
P3D(a.x, a.y, a.z),
P3D(c.x, c.y, c.z),
P3D(d.x, d.y, d.z)
);
Triangle t2((*v)[1], (*v)[2], (*v)[3],
a_normal, b_normal, c_normal,
P3D(a.x, a.y, a.z),
P3D(b.x, b.y, b.z),
P3D(c.x, c.y, c.z)
);
triangles.push_back(t1);
triangles.push_back(t2);
}
}
}
PlyData pd(vertices, triangles);
// pd.removeDoubles();
_data.insert(std::make_pair(filename, pd));
return pd;
}
| 24.878505 | 81 | 0.485162 | [
"vector"
] |
6f05accccffbb0c8781f1bbe56ddd0ae8c7a6c5b | 4,064 | cpp | C++ | tests/math_unit/math/rev/mat/fun/promote_common_test.cpp | alashworth/stan-monorepo | 75596bc1f860ededd7b3e9ae9002aea97ee1cd46 | [
"BSD-3-Clause"
] | 1 | 2019-09-06T15:53:17.000Z | 2019-09-06T15:53:17.000Z | tests/math_unit/math/rev/mat/fun/promote_common_test.cpp | alashworth/stan-monorepo | 75596bc1f860ededd7b3e9ae9002aea97ee1cd46 | [
"BSD-3-Clause"
] | 8 | 2019-01-17T18:51:16.000Z | 2019-01-17T18:51:39.000Z | tests/math_unit/math/rev/mat/fun/promote_common_test.cpp | alashworth/stan-monorepo | 75596bc1f860ededd7b3e9ae9002aea97ee1cd46 | [
"BSD-3-Clause"
] | null | null | null | #include <stan/math/rev/mat.hpp>
#include <gtest/gtest.h>
#include <math/rev/mat/fun/util.hpp>
#include <vector>
using stan::math::matrix_d;
using stan::math::matrix_v;
using stan::math::promote_common;
using stan::math::row_vector_d;
using stan::math::row_vector_v;
using stan::math::var;
using stan::math::vector_d;
using stan::math::vector_v;
using std::vector;
TEST(AgradRevMatrix, promote_common_scal) {
double a = promote_common<double, double>(3.0);
var b = promote_common<double, var>(4.0);
var c = promote_common<double, var>(var(5.0));
var d = promote_common<var, double>(4);
var e = promote_common<var, double>(var(4.0));
EXPECT_FLOAT_EQ(3.0, a);
EXPECT_FLOAT_EQ(4.0, b.val());
EXPECT_FLOAT_EQ(5.0, c.val());
EXPECT_FLOAT_EQ(4.0, d.val());
EXPECT_FLOAT_EQ(4.0, e.val());
}
TEST(AgradRevMatrix, promote_common_stdvec) {
vector<double> x(5);
for (int i = 0; i < 5; ++i)
x[i] = i * i;
vector<double> y = promote_common<vector<double>, vector<double> >(x);
EXPECT_EQ(5U, y.size());
for (int i = 0; i < 5; ++i)
EXPECT_FLOAT_EQ(x[i], y[i]);
vector<var> z = promote_common<vector<double>, vector<var> >(x);
EXPECT_EQ(5U, z.size());
for (int i = 0; i < 5; ++i)
EXPECT_FLOAT_EQ(x[i], z[i].val());
vector<var> w = promote_common<vector<var>, vector<var> >(z);
EXPECT_EQ(5U, w.size());
for (int i = 0; i < 5; ++i)
EXPECT_FLOAT_EQ(x[i], w[i].val());
vector<var> u = promote_common<vector<var>, vector<double> >(z);
EXPECT_EQ(5U, u.size());
for (int i = 0; i < 5; ++i)
EXPECT_FLOAT_EQ(x[i], u[i].val());
}
TEST(AgradRevMatrix, promote_common_vec_d) {
vector_d U(3);
for (int i = 0; i < 3; ++i)
U(i) = i * i;
vector_d V = promote_common<vector_d, vector_d>(U);
EXPECT_EQ(3, V.size());
for (int i = 0; i < 3; ++i)
EXPECT_FLOAT_EQ(U(i), V(i));
vector_v W = promote_common<vector_d, vector_v>(U);
EXPECT_EQ(3, W.size());
for (int i = 0; i < 3; ++i)
EXPECT_FLOAT_EQ(U(i), W(i).val());
vector_v X = promote_common<vector_v, vector_d>(U);
EXPECT_EQ(3, X.size());
for (int i = 0; i < 3; ++i)
EXPECT_FLOAT_EQ(U(i), X(i).val());
vector_v Y = promote_common<vector_v, vector_v>(W);
EXPECT_EQ(3, Y.size());
for (int i = 0; i < 3; ++i)
EXPECT_FLOAT_EQ(U(i), Y(i).val());
}
TEST(AgradRevMatrix, promote_common_row_vec_d) {
row_vector_d G(3);
for (int i = 0; i < 3; ++i)
G(i) = i * i;
row_vector_d H = promote_common<row_vector_d, row_vector_d>(G);
EXPECT_EQ(3, H.size());
for (int i = 0; i < 3; ++i)
EXPECT_FLOAT_EQ(G(i), H(i));
row_vector_v I = promote_common<row_vector_d, row_vector_v>(G);
EXPECT_EQ(3, I.size());
for (int i = 0; i < 3; ++i)
EXPECT_FLOAT_EQ(G(i), I(i).val());
row_vector_v J = promote_common<row_vector_v, row_vector_d>(G);
EXPECT_EQ(3, J.size());
for (int i = 0; i < 3; ++i)
EXPECT_FLOAT_EQ(G(i), J(i).val());
row_vector_v K = promote_common<row_vector_v, row_vector_v>(I);
EXPECT_EQ(3, K.size());
for (int i = 0; i < 3; ++i)
EXPECT_FLOAT_EQ(H(i), K(i).val());
}
TEST(AgradRevMatrix, promote_common_matrix_d) {
matrix_d A(3, 4);
for (int i = 0; i < 3; ++i)
for (int j = 0; j < 4; ++j)
A(i, j) = (i + 1) + (j * 10);
matrix_d B = promote_common<matrix_d, matrix_d>(A);
EXPECT_EQ(3, B.rows());
EXPECT_EQ(4, B.cols());
for (int i = 0; i < 3; ++i)
for (int j = 0; j < 4; ++j)
EXPECT_FLOAT_EQ(A(i, j), B(i, j));
matrix_v C = promote_common<matrix_d, matrix_v>(A);
EXPECT_EQ(3, C.rows());
EXPECT_EQ(4, C.cols());
for (int i = 0; i < 3; ++i)
for (int j = 0; j < 4; ++j)
EXPECT_FLOAT_EQ(A(i, j), C(i, j).val());
matrix_v D = promote_common<matrix_v, matrix_d>(A);
EXPECT_EQ(3, D.rows());
EXPECT_EQ(4, D.cols());
for (int i = 0; i < 3; ++i)
for (int j = 0; j < 4; ++j)
EXPECT_FLOAT_EQ(A(i, j), D(i, j).val());
matrix_v E = promote_common<matrix_v, matrix_v>(C);
EXPECT_EQ(3, E.rows());
EXPECT_EQ(4, E.cols());
for (int i = 0; i < 3; ++i)
for (int j = 0; j < 4; ++j)
EXPECT_FLOAT_EQ(A(i, j), E(i, j).val());
}
| 31.503876 | 72 | 0.600148 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.