text
stringlengths 8
6.88M
|
|---|
class Solution
{
public:
ListNode *swapPairs(ListNode *head)
{
ListNode *ret = NULL, *cur = head;
ListNode **insert = &ret;
while (cur != NULL)
{
ListNode *node = cur;
if (node->next != NULL)
{
cur = (node->next)->next;
*insert = node->next;
(node->next)->next = node;
insert = &(node->next);
*insert = NULL;
}
else
{
*insert = node;
return ret;
}
}
return ret;
}
};
|
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
/* This is our thread function. It is like main(), but for a thread */
void *threadFunc(void *c)
{
// char *str;
int i = 0;
// str=(char*)arg;
while(i < 10 )
{
usleep(1);
printf("threadFunc says");
++i;
}
return NULL;
}
int main(void)
{
pthread_t pth; // this is our thread identifier
int i = 0;
void *v;
/* Create worker thread */
pthread_create(&pth,NULL,threadFunc,v );
/* wait for our thread to finish before continuing */
pthread_join(pth, NULL /* void ** return value could go here */);
while(i < 10 )
{
usleep(1);
printf("main() is running...\n");
++i;
}
return 0;
}
|
#include<bits/stdc++.h>
#define ll long long int
using namespace std;
int main()
{
ll n,b;
cin>>n;
vector<ll> v;
for(ll i=0;i<n;i++)
{
cin>>b;
v.push_back(b);
}
sort(v.begin(),v.end());
//counting first similar
ll firstsm=0;
for(ll i=0;i<n;i++)
{
if(v[i]==v[0])
firstsm++;
}
//counting last similar
ll lastsm=0;
for(ll i=n-1;i>=0;i--)
{
if(v[i]==v[n-1])
lastsm++;
}
if(firstsm==n)
cout<<v[n-1]-v[0]<<" "<<(n*(n-1))/2<<endl;
else
cout<<v[n-1]-v[0]<<" "<<firstsm*lastsm<<endl;
}
|
#include "LightShader.h"
#include <glm/ext.hpp>
LightShader::LightShader() : Shader() {
}
LightShader::LightShader(glm::vec3 viewPos, const char *vs, const char *fs, bool isFile) : Shader(vs, fs, isFile) {
this->viewPos = viewPos;
}
LightShader::~LightShader()
{
}
void LightShader::addDirectionalLight(glm::vec3 direction, glm::vec3 diffuse, glm::vec3 specular){
dirLight.direction = direction;
dirLight.diffuse = diffuse;
dirLight.specular = specular;
}
void LightShader::addPointLight(glm::vec3 position, glm::vec3 diffuse, glm::vec3 specular,
float constant, float linear, float quadratic){
PointLight pointLight;
pointLight.position = position;
pointLight.diffuse = diffuse;
pointLight.specular = specular;
pointLight.constant = constant;
pointLight.linear = linear;
pointLight.quadratic = quadratic;
pointLights.push_back(pointLight);
}
void LightShader::addSpotLight(glm::vec3 position, glm::vec3 direction, float cutOff, float outerCutOff,
glm::vec3 diffuse, glm::vec3 specular,
float constant, float linear, float quadratic){
SpotLight spotLight;
spotLight.position = position;
spotLight.direction = direction;
spotLight.cutOff = cutOff;
spotLight.outerCutOff = outerCutOff;
spotLight.diffuse = diffuse;
spotLight.specular = specular;
spotLight.constant = constant;
spotLight.linear = linear;
spotLight.quadratic = quadratic;
spotLights.push_back(spotLight);
}
void LightShader::bind()
{
if (currentlyBoundShaderID != pid)
{
currentlyBoundShaderID = pid;
glUseProgram(pid);
glUniform3fv(glGetUniformLocation(this->currentlyBoundShaderID, "viewPos"), 1, glm::value_ptr(viewPos));
attachDirectionalLight();
attachPointLight();
attachSpotLight();
}
}
void LightShader::unbind()
{
if (currentlyBoundShaderID != (0x0))
{
currentlyBoundShaderID = (0x0);
glUseProgram(0);
}
}
void LightShader::setViewPos(glm::vec3 viewPos){
this->viewPos = viewPos;
}
void LightShader::attachDirectionalLight(){
glUniform3fv(glGetUniformLocation(this->currentlyBoundShaderID, "dirLight.direction"), 1, glm::value_ptr(dirLight.direction));
glUniform3fv(glGetUniformLocation(this->currentlyBoundShaderID, "dirLight.diffuse"), 1, glm::value_ptr(dirLight.diffuse));
glUniform3fv(glGetUniformLocation(this->currentlyBoundShaderID, "dirLight.specular"), 1, glm::value_ptr(dirLight.specular));
}
void LightShader::attachPointLight(){
glUniform1i(glGetUniformLocation(this->currentlyBoundShaderID, "PointSize"), pointLights.size());
for (size_t i = 0; i < pointLights.size(); i++){
string tmp = "pointLights[" + to_string(i) + "].";
glUniform3fv(glGetUniformLocation(this->currentlyBoundShaderID, (tmp + "position").c_str()), 1, glm::value_ptr(pointLights[i].position));
glUniform3fv(glGetUniformLocation(this->currentlyBoundShaderID, (tmp + "diffuse").c_str()), 1, glm::value_ptr(pointLights[i].diffuse));
glUniform3fv(glGetUniformLocation(this->currentlyBoundShaderID, (tmp + "specular").c_str()), 1, glm::value_ptr(pointLights[i].specular));
glUniform1f(glGetUniformLocation(this->currentlyBoundShaderID, (tmp + "constant").c_str()), pointLights[i].constant);
glUniform1f(glGetUniformLocation(this->currentlyBoundShaderID, (tmp + "linear").c_str()), pointLights[i].linear);
glUniform1f(glGetUniformLocation(this->currentlyBoundShaderID, (tmp + "quadratic").c_str()), pointLights[i].quadratic);
}
}
void LightShader::attachSpotLight(){
glUniform1i(glGetUniformLocation(this->currentlyBoundShaderID, "SpotSize"), spotLights.size());
for (size_t i = 0; i < spotLights.size(); i++){
string tmp = "spotLights[" + to_string(i) + "].";
glUniform3fv(glGetUniformLocation(this->currentlyBoundShaderID, (tmp + "position").c_str()), 1, glm::value_ptr(spotLights[i].position));
glUniform3fv(glGetUniformLocation(this->currentlyBoundShaderID, (tmp + "direction").c_str()), 1, glm::value_ptr(spotLights[i].direction));
glUniform3fv(glGetUniformLocation(this->currentlyBoundShaderID, (tmp + "diffuse").c_str()), 1, glm::value_ptr(spotLights[i].diffuse));
glUniform3fv(glGetUniformLocation(this->currentlyBoundShaderID, (tmp + "specular").c_str()), 1, glm::value_ptr(spotLights[i].specular));
glUniform1f(glGetUniformLocation(this->currentlyBoundShaderID, (tmp + "constant").c_str()), spotLights[i].constant);
glUniform1f(glGetUniformLocation(this->currentlyBoundShaderID, (tmp + "linear").c_str()), spotLights[i].linear);
glUniform1f(glGetUniformLocation(this->currentlyBoundShaderID, (tmp + "quadratic").c_str()), spotLights[i].quadratic);
glUniform1f(glGetUniformLocation(this->currentlyBoundShaderID, (tmp + "cutOff").c_str()), spotLights[i].cutOff);
glUniform1f(glGetUniformLocation(this->currentlyBoundShaderID, (tmp + "outerCutOff").c_str()), spotLights[i].outerCutOff);
}
}
|
/*
* UAE - The Un*x Amiga Emulator
*
* Win32 interface
*
* Copyright 1997 Mathias Ortmann
* Copyright 1997-2001 Brian King
* Copyright 2000-2002 Bernd Roesch
*/
#define NATIVBUFFNUM 4
#define RECORDBUFFER 50 //survive 9 sec of blocking at 44100
#include "sysconfig.h"
#include "sysdeps.h"
#if defined(AHI)
#include <ctype.h>
#include <assert.h>
#include <windows.h>
#include <stdlib.h>
#include <stdarg.h>
#include <dsound.h>
#include <stdio.h>
#include "options.h"
#include "audio.h"
#include "memory.h"
#include "events.h"
#include "custom.h"
#include "newcpu.h"
#include "traps.h"
#include "sounddep/sound.h"
#include "render.h"
#include "win32.h"
#include "parser.h"
#include "enforcer.h"
#include "ahidsound.h"
#include "picasso96_win.h"
static long samples, playchannel, intcount;
static int record_enabled;
int ahi_on;
static uae_u8 *sndptrmax;
static uae_u8 soundneutral;
static LPSTR lpData,sndptrout;
extern uae_u32 chipmem_mask;
static uae_u8 *ahisndbuffer, *sndrecbuffer;
static int ahisndbufsize, *ahisndbufpt, ahitweak;;
int ahi_pollrate = 40;
int sound_freq_ahi, sound_channels_ahi, sound_bits_ahi;
static int vin, devicenum;
static int amigablksize;
static DWORD sound_flushes2 = 0;
static LPDIRECTSOUND lpDS2 = NULL;
static LPDIRECTSOUNDBUFFER lpDSBprimary2 = NULL;
static LPDIRECTSOUNDBUFFER lpDSB2 = NULL;
static LPDIRECTSOUNDNOTIFY lpDSBN2 = NULL;
// for record
static LPDIRECTSOUNDCAPTURE lpDS2r = NULL;
static LPDIRECTSOUNDCAPTUREBUFFER lpDSBprimary2r = NULL;
static LPDIRECTSOUNDCAPTUREBUFFER lpDSB2r = NULL;
struct winuae //this struct is put in a6 if you call
//execute native function
{
HWND amigawnd; //address of amiga Window Windows Handle
unsigned int changenum; //number to detect screen close/open
unsigned int z3offset; //the offset to add to acsess Z3 mem from Dll side
};
static struct winuae uaevar;
static struct winuae *a6;
#if defined(X86_MSVC_ASSEMBLY)
#define CREATE_NATIVE_FUNC_PTR2 uae_u32 (*native_func)(uae_u32, uae_u32, uae_u32, uae_u32, uae_u32, uae_u32, uae_u32,\
uae_u32, uae_u32, uae_u32, uae_u32, uae_u32, uae_u32,uae_u32,uae_u32)
#define SET_NATIVE_FUNC2(x) native_func = (uae_u32 (*)(uae_u32, uae_u32, uae_u32, uae_u32, uae_u32, uae_u32, uae_u32, uae_u32, uae_u32, uae_u32, uae_u32, uae_u32, uae_u32,uae_u32,uae_u32))(x)
#define CALL_NATIVE_FUNC2(d1,d2,d3,d4,d5,d6,d7,a1,a2,a3,a4,a5,a6,a7) if(native_func) return native_func(d1,d2,d3,d4,d5,d6,d7,a1,a2,a3,a4,a5,a6,a7,regs_)
static uae_u32 REGPARAM2 emulib_ExecuteNativeCode2 (TrapContext *context)
{
struct AmigaMonitor *mon = &AMonitors[0];
unsigned int espstore;
uae_u8* object_UAM = (uae_u8*) m68k_areg (regs, 0);
uae_u32 d1 = m68k_dreg (regs, 1);
uae_u32 d2 = m68k_dreg (regs, 2);
uae_u32 d3 = m68k_dreg (regs, 3);
uae_u32 d4 = m68k_dreg (regs, 4);
uae_u32 d5 = m68k_dreg (regs, 5);
uae_u32 d6 = m68k_dreg (regs, 6);
uae_u32 d7 = m68k_dreg (regs, 7);
uae_u32 a1 = m68k_areg (regs, 1);
uae_u32 a2 = m68k_areg (regs, 2);
uae_u32 a3 = m68k_areg (regs, 3);
uae_u32 a4 = m68k_areg (regs, 4);
uae_u32 a5 = m68k_areg (regs, 5);
uae_u32 a7 = m68k_areg (regs, 7);
uae_u32 regs_ = (uae_u32)®s;
CREATE_NATIVE_FUNC_PTR2;
uaevar.z3offset = (uae_u32)(get_real_address (z3fastmem_bank[0].start) - z3fastmem_bank[0].start);
uaevar.amigawnd = mon->hAmigaWnd;
a6 = &uaevar;
if (object_UAM) {
SET_NATIVE_FUNC2 (object_UAM);
__asm
{ mov espstore,esp
push regs_
push a7
push a6
push a5
push a4
push a3
push a2
push a1
push d7
push d6
push d5
push d4
push d3
push d2
push d1
call native_func
mov esp,espstore
}
//CALL_NATIVE_FUNC2( d1, d2,d3, d4, d5, d6, d7, a1, a2, a3, a4 , a5 , a6 , a7);
} else {
return 0;
}
}
#endif
void ahi_close_sound (void)
{
HRESULT hr = DS_OK;
if (!ahi_on)
return;
ahi_on = 0;
record_enabled = 0;
ahisndbufpt = (int*)ahisndbuffer;
if (lpDSB2) {
hr = IDirectSoundBuffer_Stop (lpDSB2);
if(FAILED (hr))
write_log (_T("AHI: SoundStop() failure: %s\n"), DXError (hr));
} else {
write_log (_T("AHI: Sound Stopped...\n"));
}
if (lpDSB2)
IDirectSoundBuffer_Release (lpDSB2);
lpDSB2 = NULL;
if (lpDSBprimary2)
IDirectSoundBuffer_Release (lpDSBprimary2);
lpDSBprimary2 = NULL;
if (lpDS2)
IDirectSound_Release (lpDS2);
lpDS2 = NULL;
if (lpDSB2r)
IDirectSoundCaptureBuffer_Release (lpDSB2r);
lpDSB2r = NULL;
if (lpDS2r)
IDirectSound_Release (lpDS2r);
lpDS2r = NULL;
if (ahisndbuffer)
free (ahisndbuffer);
ahisndbuffer = NULL;
}
void ahi_updatesound(int force)
{
HRESULT hr;
DWORD pos;
DWORD dwBytes1, dwBytes2;
LPVOID dwData1, dwData2;
static int oldpos;
if (sound_flushes2 == 1) {
oldpos = 0;
intcount = 1;
INTREQ (0x8000 | 0x2000);
hr = lpDSB2->Play (0, 0, DSBPLAY_LOOPING);
if(hr == DSERR_BUFFERLOST) {
lpDSB2->Restore ();
hr = lpDSB2->Play (0, 0, DSBPLAY_LOOPING);
}
}
hr = lpDSB2->GetCurrentPosition (&pos, 0);
if (hr != DSERR_BUFFERLOST) {
pos -= ahitweak;
if (pos < 0)
pos += ahisndbufsize;
if (pos >= ahisndbufsize)
pos -= ahisndbufsize;
pos = (pos / (amigablksize * 4)) * (amigablksize * 4);
if (force == 1) {
if (oldpos != pos) {
intcount = 1;
INTREQ (0x8000 | 0x2000);
return; //to generate amiga ints every amigablksize
} else {
return;
}
}
}
hr = lpDSB2->Lock (oldpos, amigablksize * 4, &dwData1, &dwBytes1, &dwData2, &dwBytes2, 0);
if(hr == DSERR_BUFFERLOST) {
write_log (_T("AHI: lostbuf %d %x\n"), pos, amigablksize);
IDirectSoundBuffer_Restore (lpDSB2);
hr = lpDSB2->Lock (oldpos, amigablksize * 4, &dwData1, &dwBytes1, &dwData2, &dwBytes2, 0);
}
if(FAILED(hr))
return;
if (currprefs.sound_stereo_swap_ahi) {
int i;
uae_s16 *p = (uae_s16*)ahisndbuffer;
for (i = 0; i < (dwBytes1 + dwBytes2) / 2; i += 2) {
uae_s16 tmp;
tmp = p[i + 0];
p[i + 0] = p[i + 1];
p[i + 1] = tmp;
}
}
memcpy (dwData1, ahisndbuffer, dwBytes1);
if (dwData2)
memcpy (dwData2, (uae_u8*)ahisndbuffer + dwBytes1, dwBytes2);
sndptrmax = ahisndbuffer + ahisndbufsize;
ahisndbufpt = (int*)ahisndbuffer;
IDirectSoundBuffer_Unlock (lpDSB2, dwData1, dwBytes1, dwData2, dwBytes2);
oldpos += amigablksize * 4;
if (oldpos >= ahisndbufsize)
oldpos -= ahisndbufsize;
if (oldpos != pos) {
intcount = 1;
INTREQ (0x8000 | 0x2000);
}
}
void ahi_finish_sound_buffer (void)
{
sound_flushes2++;
ahi_updatesound(2);
}
static WAVEFORMATEX wavfmt;
static int ahi_init_record_win32 (void)
{
HRESULT hr;
DSCBUFFERDESC sound_buffer_rec;
// Record begin
hr = DirectSoundCaptureCreate (NULL, &lpDS2r, NULL);
if (FAILED (hr)) {
write_log (_T("AHI: DirectSoundCaptureCreate() failure: %s\n"), DXError (hr));
record_enabled = -1;
return 0;
}
memset (&sound_buffer_rec, 0, sizeof (DSCBUFFERDESC));
sound_buffer_rec.dwSize = sizeof (DSCBUFFERDESC);
sound_buffer_rec.dwBufferBytes = amigablksize * 4 * RECORDBUFFER;
sound_buffer_rec.lpwfxFormat = &wavfmt;
sound_buffer_rec.dwFlags = 0 ;
hr = IDirectSoundCapture_CreateCaptureBuffer (lpDS2r, &sound_buffer_rec, &lpDSB2r, NULL);
if (FAILED (hr)) {
write_log (_T("AHI: CreateCaptureSoundBuffer() failure: %s\n"), DXError(hr));
record_enabled = -1;
return 0;
}
hr = IDirectSoundCaptureBuffer_Start (lpDSB2r, DSCBSTART_LOOPING);
if (FAILED (hr)) {
write_log (_T("AHI: DirectSoundCaptureBuffer_Start failed: %s\n"), DXError (hr));
record_enabled = -1;
return 0;
}
record_enabled = 1;
write_log (_T("AHI: Init AHI Audio Recording \n"));
return 1;
}
void setvolume_ahi (LONG vol)
{
HRESULT hr;
if (!lpDS2)
return;
hr = IDirectSoundBuffer_SetVolume (lpDSB2, vol);
if (FAILED (hr))
write_log (_T("AHI: SetVolume(%d) failed: %s\n"), vol, DXError (hr));
}
static int ahi_init_sound_win32 (void)
{
struct AmigaMonitor *mon = &AMonitors[0];
HRESULT hr;
DSBUFFERDESC sound_buffer;
DSCAPS DSCaps;
if (lpDS2)
return 0;
enumerate_sound_devices ();
wavfmt.wFormatTag = WAVE_FORMAT_PCM;
wavfmt.nChannels = sound_channels_ahi;
wavfmt.nSamplesPerSec = sound_freq_ahi;
wavfmt.wBitsPerSample = sound_bits_ahi;
wavfmt.nBlockAlign = wavfmt.wBitsPerSample / 8 * wavfmt.nChannels;
wavfmt.nAvgBytesPerSec = wavfmt.nBlockAlign * sound_freq_ahi;
wavfmt.cbSize = 0;
write_log (_T("AHI: Init AHI Sound Rate %d, Channels %d, Bits %d, Buffsize %d\n"),
sound_freq_ahi, sound_channels_ahi, sound_bits_ahi, amigablksize);
if (!amigablksize)
return 0;
soundneutral = 0;
ahisndbufsize = (amigablksize * 4) * NATIVBUFFNUM; // use 4 native buffer
ahisndbuffer = xmalloc (uae_u8, ahisndbufsize + 32);
if (!ahisndbuffer)
return 0;
if (sound_devices[currprefs.win32_soundcard]->type != SOUND_DEVICE_DS)
hr = DirectSoundCreate (NULL, &lpDS2, NULL);
else
hr = DirectSoundCreate (&sound_devices[currprefs.win32_soundcard]->guid, &lpDS2, NULL);
if (FAILED (hr)) {
write_log (_T("AHI: DirectSoundCreate() failure: %s\n"), DXError (hr));
return 0;
}
memset (&sound_buffer, 0, sizeof (DSBUFFERDESC));
sound_buffer.dwSize = sizeof (DSBUFFERDESC);
sound_buffer.dwFlags = DSBCAPS_PRIMARYBUFFER;
sound_buffer.dwBufferBytes = 0;
sound_buffer.lpwfxFormat = NULL;
DSCaps.dwSize = sizeof(DSCAPS);
hr = IDirectSound_GetCaps (lpDS2, &DSCaps);
if (SUCCEEDED (hr)) {
if (DSCaps.dwFlags & DSCAPS_EMULDRIVER)
write_log (_T("AHI: Your DirectSound Driver is emulated via WaveOut - yuck!\n"));
}
if (FAILED (IDirectSound_SetCooperativeLevel (lpDS2, mon->hMainWnd, DSSCL_PRIORITY)))
return 0;
hr = IDirectSound_CreateSoundBuffer (lpDS2, &sound_buffer, &lpDSBprimary2, NULL);
if (FAILED (hr)) {
write_log (_T("AHI: CreateSoundBuffer() failure: %s\n"), DXError(hr));
return 0;
}
hr = IDirectSoundBuffer_SetFormat (lpDSBprimary2, &wavfmt);
if (FAILED (hr)) {
write_log (_T("AHI: SetFormat() failure: %s\n"), DXError (hr));
return 0;
}
sound_buffer.dwBufferBytes = ahisndbufsize;
sound_buffer.lpwfxFormat = &wavfmt;
sound_buffer.dwFlags = DSBCAPS_CTRLFREQUENCY | DSBCAPS_CTRLVOLUME
| DSBCAPS_GETCURRENTPOSITION2 | DSBCAPS_GLOBALFOCUS | DSBCAPS_LOCSOFTWARE;
sound_buffer.guid3DAlgorithm = GUID_NULL;
hr = IDirectSound_CreateSoundBuffer (lpDS2, &sound_buffer, &lpDSB2, NULL);
if (FAILED (hr)) {
write_log (_T("AHI: CreateSoundBuffer() failure: %s\n"), DXError (hr));
return 0;
}
setvolume_ahi (0);
hr = IDirectSoundBuffer_GetFormat (lpDSBprimary2,&wavfmt,500,0);
if (FAILED (hr)) {
write_log (_T("AHI: GetFormat() failure: %s\n"), DXError (hr));
return 0;
}
ahisndbufpt =(int*)ahisndbuffer;
sndptrmax = ahisndbuffer + ahisndbufsize;
memset (ahisndbuffer, soundneutral, amigablksize * 8);
ahi_on = 1;
return sound_freq_ahi;
}
int ahi_open_sound (void)
{
int rate;
uaevar.changenum++;
if (!sound_freq_ahi)
return 0;
if (ahi_on)
ahi_close_sound ();
sound_flushes2 = 1;
if ((rate = ahi_init_sound_win32 ()))
return rate;
return 0;
}
static void *bswap_buffer = NULL;
static uae_u32 bswap_buffer_size = 0;
static float syncdivisor;
#if CPU_64_BIT
#define FAKE_HANDLE_WINLAUNCH 0xfffffffeLL
#else
#define FAKE_HANDLE_WINLAUNCH 0xfffffffe
#endif
typedef uae_u32 (*fake_func_get)(struct fake_handle_struct*, const char*);
typedef uae_u32 (*fake_func_exec)(struct fake_handle_struct*, TrapContext*);
struct fake_handle_struct
{
uae_u32 handle;
uae_u32 func_start;
uae_u32 func_end;
fake_func_get get;
fake_func_exec exec;
};
// "Emulate" winlaunch
static uae_u32 fake_winlaunch_get(struct fake_handle_struct *me, const char *name)
{
if (!stricmp(name, "_launch"))
return me->func_start;
return 0;
}
static const int fake_winlaunch_cmdval[] =
{
SW_HIDE, SW_MAXIMIZE, SW_MINIMIZE, SW_RESTORE, SW_SHOW, SW_SHOWDEFAULT, SW_SHOWMAXIMIZED,
SW_SHOWMINIMIZED, SW_SHOWMINNOACTIVE, SW_SHOWNA, SW_SHOWNOACTIVATE, SW_SHOWNORMAL
};
static uae_u32 fake_winlaunch_exec(struct fake_handle_struct *me, TrapContext *ctx)
{
uae_u32 file = m68k_dreg(regs, 1);
if (!valid_address(file, 2))
return 0;
uae_u32 parms = m68k_dreg(regs, 2);
uae_u8 *fileptr = get_real_address(file);
uae_u8 *parmsptr = NULL;
if (parms)
parmsptr = get_real_address(parms);
uae_u32 showcmdval = m68k_dreg(regs, 3);
if (showcmdval > 11)
return 0;
uae_u32 ret = (uae_u32)(uae_u64)ShellExecuteA(NULL, NULL, (char*)fileptr, (char*)parmsptr, "", fake_winlaunch_cmdval[showcmdval]);
uae_u32 aret = 0;
switch (ret) {
case 0:
aret = 1;
break;
case ERROR_FILE_NOT_FOUND:
aret = 2;
break;
case ERROR_PATH_NOT_FOUND:
aret = 3;
break;
case ERROR_BAD_FORMAT:
aret = 4;
break;
case SE_ERR_ACCESSDENIED:
aret = 5;
break;
case SE_ERR_ASSOCINCOMPLETE:
aret = 6;
break;
case SE_ERR_DDEBUSY:
aret = 7;
break;
case SE_ERR_DDEFAIL:
aret = 8;
break;
case SE_ERR_DDETIMEOUT:
aret = 9;
break;
case SE_ERR_DLLNOTFOUND:
aret = 10;
break;
case SE_ERR_NOASSOC:
aret = 11;
break;
case SE_ERR_OOM:
aret = 12;
break;
case SE_ERR_SHARE:
aret = 13;
break;
}
return aret;
}
static struct fake_handle_struct fake_handles[] =
{
{ FAKE_HANDLE_WINLAUNCH, 4, 4, fake_winlaunch_get, fake_winlaunch_exec, },
{ 0 }
};
static HMODULE native_override(const TCHAR *dllname, TrapContext *ctx)
{
const TCHAR *s = _tcsrchr(dllname, '/');
if (!s)
s = _tcsrchr(dllname, '\\');
if (!s) {
s = dllname;
} else if (s) {
s++;
}
if (!_tcsicmp(s, _T("winlaunch.alib"))) {
return (HMODULE)FAKE_HANDLE_WINLAUNCH;
}
return 0;
}
uae_u32 REGPARAM2 ahi_demux (TrapContext *context)
{
//use the extern int (6 #13)
// d0 0=opensound d1=unit d2=samplerate d3=blksize ret: sound frequency
// d0 6=opensound_new d1=unit d2=samplerate d3=blksize ret d4=channels d5=bits d6=zero: sound frequency
// d0 1=closesound d1=unit
// d0 2=writesamples d1=unit a0=addr write blksize samples to card
// d0 3=readsamples d1=unit a0=addr read samples from card ret: d0=samples read
// make sure you have from amigaside blksize*4 mem alloced
// d0=-1 no data available d0=-2 no recording open
// d0 > 0 there are more blksize Data in the que
// do the loop until d0 get 0
// if d0 is greater than 200 bring a message
// that show the user that data is lost
// maximum blocksbuffered are 250 (8,5 sec)
// d0 4=writeinterrupt d1=unit d0=0 no interrupt happen for this unit
// d0=-2 no playing open
//note units for now not support use only unit 0
// d0 5=?
// d0=10 get clipboard size d0=size in bytes
// d0=11 get clipboard data a0=clipboarddata
//Note: a get clipboard size must do before
// d0=12 write clipboard data a0=clipboarddata
// d0=13 setp96mouserate d1=hz value
// d0=100 open dll d1=dll name in windows name conventions
// d0=101 get dll function addr d1=dllhandle a0 function/var name
// d0=102 exec dllcode a0=addr of function (see 101)
// d0=103 close dll
// d0=104 screenlost
// d0=105 mem offset
// d0=106 16Bit byteswap
// d0=107 32Bit byteswap
// d0=108 free swap array
// d0=200 ahitweak d1=offset for dsound position pointer
int opcode = m68k_dreg (regs, 0);
switch (opcode)
{
static int cap_pos, clipsize;
static TCHAR *clipdat;
case 0:
cap_pos = 0;
sound_bits_ahi = 16;
sound_channels_ahi = 2;
sound_freq_ahi = m68k_dreg (regs, 2);
amigablksize = m68k_dreg (regs, 3);
sound_freq_ahi = ahi_open_sound();
uaevar.changenum--;
return sound_freq_ahi;
case 6: /* new open function */
cap_pos = 0;
sound_freq_ahi = m68k_dreg (regs, 2);
amigablksize = m68k_dreg (regs, 3);
sound_channels_ahi = m68k_dreg (regs, 4);
sound_bits_ahi = m68k_dreg (regs, 5);
sound_freq_ahi = ahi_open_sound();
uaevar.changenum--;
return sound_freq_ahi;
case 1:
ahi_close_sound();
sound_freq_ahi = 0;
return 0;
case 2:
{
int i;
uaecptr addr = m68k_areg (regs, 0);
for (i = 0; i < amigablksize * 4; i += 4)
*ahisndbufpt++ = get_long (addr + i);
ahi_finish_sound_buffer();
}
return amigablksize;
case 3:
{
LPVOID pos1, pos2;
DWORD t, cur_pos;
uaecptr addr;
HRESULT hr;
int i, todo;
DWORD byte1, byte2;
if (!ahi_on)
return -2;
if (record_enabled == 0)
ahi_init_record_win32();
if (record_enabled < 0)
return -2;
hr = lpDSB2r->GetCurrentPosition(&t, &cur_pos);
if (FAILED(hr))
return -1;
t = amigablksize * 4;
if (cap_pos <= cur_pos)
todo = cur_pos - cap_pos;
else
todo = cur_pos + (RECORDBUFFER * t) - cap_pos;
if (todo < t) //if no complete buffer ready exit
return -1;
hr = lpDSB2r->Lock(cap_pos, t, &pos1, &byte1, &pos2, &byte2, 0);
if (FAILED(hr))
return -1;
if ((cap_pos + t) < (t * RECORDBUFFER))
cap_pos = cap_pos + t;
else
cap_pos = 0;
addr = m68k_areg (regs, 0);
uae_u16 *sndbufrecpt = (uae_u16*)pos1;
t /= 4;
for (i = 0; i < t; i++) {
uae_u32 s1, s2;
if (currprefs.sound_stereo_swap_ahi) {
s1 = sndbufrecpt[1];
s2 = sndbufrecpt[0];
} else {
s1 = sndbufrecpt[0];
s2 = sndbufrecpt[1];
}
sndbufrecpt += 2;
put_long (addr, (s1 << 16) | s2);
addr += 4;
}
t *= 4;
lpDSB2r->Unlock(pos1, byte1, pos2, byte2);
return (todo - t) / t;
}
case 4:
{
int i;
if (!ahi_on)
return -2;
i = intcount;
intcount = 0;
return i;
}
case 5:
if (!ahi_on)
return 0;
ahi_updatesound ( 1 );
return 1;
case 10:
#if 1
if (OpenClipboard (0)) {
clipdat = (TCHAR*)GetClipboardData (CF_UNICODETEXT);
if (clipdat) {
clipsize = uaetcslen(clipdat);
clipsize++;
return clipsize;
}
}
#endif
return 0;
case 11:
{
#if 1
put_byte (m68k_areg (regs, 0), 0);
if (clipdat) {
char *tmp = ua (clipdat);
int i;
for (i = 0; i < clipsize && i < strlen (tmp); i++)
put_byte (m68k_areg (regs, 0) + i, tmp[i]);
put_byte (m68k_areg (regs, 0) + clipsize - 1, 0);
xfree (tmp);
}
CloseClipboard ();
#endif
}
return 0;
case 12:
{
#if 1
TCHAR *s = au ((char*)get_real_address (m68k_areg (regs, 0)));
static LPTSTR p;
int slen;
if (OpenClipboard (0)) {
EmptyClipboard();
slen = uaetcslen(s);
if (p)
GlobalFree (p);
p = (LPTSTR)GlobalAlloc (GMEM_MOVEABLE, (slen + 1) * sizeof (TCHAR));
if (p) {
TCHAR *p2 = (TCHAR*)GlobalLock (p);
if (p2) {
_tcscpy (p2, s);
GlobalUnlock (p);
SetClipboardData (CF_UNICODETEXT, p);
}
}
CloseClipboard ();
}
xfree (s);
#endif
}
return 0;
case 13: /* HACK */
{ //for higher P96 mouse draw rate
set_picasso_hack_rate (m68k_dreg (regs, 1) * 2);
} //end for higher P96 mouse draw rate
return 0;
case 20:
return enforcer_enable(m68k_dreg (regs, 1));
case 21:
return enforcer_disable();
case 25:
flushprinter ();
return 0;
case 100: // open dll
{
if (!currprefs.native_code)
return 0;
TCHAR *dlldir = TEXT ("winuae_dll");
TCHAR *dllname;
uaecptr dllptr;
HMODULE h = NULL;
int ok = 0;
DWORD err = 0;
dllptr = m68k_areg (regs, 0);
if (!valid_address(dllptr, 2))
return 0;
dllname = au ((uae_char*)get_real_address (dllptr));
h = native_override(dllname, context);
#if defined(X86_MSVC_ASSEMBLY)
if (h == 0) {
TCHAR *filepart;
TCHAR dpath[MAX_DPATH];
TCHAR newdllpath[MAX_DPATH];
dpath[0] = 0;
GetFullPathName (dllname, sizeof dpath / sizeof (TCHAR), dpath, &filepart);
if (_tcslen (dpath) > _tcslen (start_path_data) && !_tcsncmp (dpath, start_path_data, _tcslen (start_path_data))) {
/* path really is relative to winuae directory */
ok = 1;
_tcscpy (newdllpath, dpath + _tcslen (start_path_data));
if (!_tcsncmp (newdllpath, dlldir, _tcslen (dlldir))) /* remove "winuae_dll" */
_tcscpy (newdllpath, dpath + _tcslen (start_path_data) + 1 + _tcslen (dlldir));
_stprintf (dpath, _T("%s%s%s"), start_path_data, WIN32_PLUGINDIR, newdllpath);
h = LoadLibrary (dpath);
if (h == NULL)
err = GetLastError();
if (h == NULL) {
_stprintf (dpath, _T("%s%s\\%s"), start_path_data, dlldir, newdllpath);
h = LoadLibrary (dllname);
if (h == NULL) {
DWORD err2 = GetLastError();
if (h == NULL) {
write_log (_T("fallback native open: '%s' = %d, %d\n"), dpath, err2, err);
}
}
}
} else {
write_log (_T("native open outside of installation dir '%s'!\n"), dpath);
}
}
#endif
xfree (dllname);
syncdivisor = (3580000.0f * CYCLE_UNIT) / (float)syncbase;
return (uae_u32)(uae_u64)h;
}
case 101: //get dll label
{
if (currprefs.native_code) {
uaecptr funcaddr;
char *funcname;
uae_u32 m = m68k_dreg (regs, 1);
funcaddr = m68k_areg (regs, 0);
funcname = (char*)get_real_address (funcaddr);
for (int i = 0; fake_handles[i].handle; i++) {
if (fake_handles[i].handle == m) {
return fake_handles[i].get(&fake_handles[i], funcname);
}
}
#if defined(X86_MSVC_ASSEMBLY)
return (uae_u32) GetProcAddress ((HMODULE)m, funcname);
#endif
}
return 0;
}
case 102: //execute native code
{
uae_u32 ret = 0;
if (currprefs.native_code) {
uaecptr funcptr = m68k_areg(regs, 0);
for (int i = 0; fake_handles[i].handle; i++) {
if (fake_handles[i].func_start >= funcptr && fake_handles[i].func_end <= funcptr) {
return fake_handles[i].exec(&fake_handles[i], context);
}
}
#if defined(X86_MSVC_ASSEMBLY)
frame_time_t rate1;
double v;
rate1 = read_processor_time ();
ret = emulib_ExecuteNativeCode2 (context);
rate1 = read_processor_time () - rate1;
v = syncdivisor * rate1;
if (v > 0) {
if (v > 1000000 * CYCLE_UNIT)
v = 1000000 * CYCLE_UNIT;
do_extra_cycles ((unsigned long)(syncdivisor * rate1)); //compensate the time stay in native func
}
#endif
}
return ret;
}
case 103: //close dll
{
if (currprefs.native_code) {
uae_u32 addr = m68k_dreg (regs, 1);
for (int i = 0; fake_handles[i].handle; i++) {
if (addr == fake_handles[i].handle) {
addr = 0;
break;
}
}
#if defined(X86_MSVC_ASSEMBLY)
if (addr) {
HMODULE libaddr = (HMODULE)addr;
FreeLibrary (libaddr);
}
#endif
}
return 0;
}
case 104: //screenlost
{
static int oldnum = 0;
if (uaevar.changenum == oldnum)
return 0;
oldnum = uaevar.changenum;
return 1;
}
#if defined(X86_MSVC_ASSEMBLY)
case 105: //returns memory offset
return (uae_u32) get_real_address (0);
case 106: //byteswap 16bit vars
{
//a0 = start address
//d1 = number of 16bit vars
//returns address of new array
uae_u32 src = m68k_areg (regs, 0);
uae_u32 num_vars = m68k_dreg (regs, 1);
if (bswap_buffer_size < num_vars * 2) {
bswap_buffer_size = (num_vars + 1024) * 2;
free(bswap_buffer);
bswap_buffer = (void*)malloc(bswap_buffer_size);
}
if (!bswap_buffer)
return 0;
__asm {
mov esi, dword ptr [src]
mov edi, dword ptr [bswap_buffer]
mov ecx, num_vars
mov ebx, ecx
and ecx, 3
je BSWAP_WORD_4X
BSWAP_WORD_LOOP:
mov ax, [esi]
mov dl, al
mov al, ah
mov ah, dl
mov [edi], ax
add esi, 2
add edi, 2
loopne BSWAP_WORD_LOOP
BSWAP_WORD_4X:
mov ecx, ebx
shr ecx, 2
je BSWAP_WORD_END
BSWAP_WORD_4X_LOOP:
mov ax, [esi]
mov dl, al
mov al, ah
mov ah, dl
mov [edi], ax
mov ax, [esi+2]
mov dl, al
mov al, ah
mov ah, dl
mov [edi+2], ax
mov ax, [esi+4]
mov dl, al
mov al, ah
mov ah, dl
mov [edi+4], ax
mov ax, [esi+6]
mov dl, al
mov al, ah
mov ah, dl
mov [edi+6], ax
add esi, 8
add edi, 8
loopne BSWAP_WORD_4X_LOOP
BSWAP_WORD_END:
}
return (uae_u32) bswap_buffer;
}
case 107: //byteswap 32bit vars - see case 106
{
//a0 = start address
//d1 = number of 32bit vars
//returns address of new array
uae_u32 src = m68k_areg (regs, 0);
uae_u32 num_vars = m68k_dreg (regs, 1);
if (bswap_buffer_size < num_vars * 4) {
bswap_buffer_size = (num_vars + 16384) * 4;
free(bswap_buffer);
bswap_buffer = (void*)malloc(bswap_buffer_size);
}
if (!bswap_buffer)
return 0;
__asm {
mov esi, dword ptr [src]
mov edi, dword ptr [bswap_buffer]
mov ecx, num_vars
mov ebx, ecx
and ecx, 3
je BSWAP_DWORD_4X
BSWAP_DWORD_LOOP:
mov eax, [esi]
bswap eax
mov [edi], eax
add esi, 4
add edi, 4
loopne BSWAP_DWORD_LOOP
BSWAP_DWORD_4X:
mov ecx, ebx
shr ecx, 2
je BSWAP_DWORD_END
BSWAP_DWORD_4X_LOOP:
mov eax, [esi]
bswap eax
mov [edi], eax
mov eax, [esi+4]
bswap eax
mov [edi+4], eax
mov eax, [esi+8]
bswap eax
mov [edi+8], eax
mov eax, [esi+12]
bswap eax
mov [edi+12], eax
add esi, 16
add edi, 16
loopne BSWAP_DWORD_4X_LOOP
BSWAP_DWORD_END:
}
return (uae_u32) bswap_buffer;
}
case 108: //frees swap array
bswap_buffer_size = 0;
free (bswap_buffer);
bswap_buffer = NULL;
return 0;
case 110:
{
LARGE_INTEGER p;
QueryPerformanceFrequency (&p);
put_long (m68k_areg (regs, 0), p.HighPart);
put_long (m68k_areg (regs, 0) + 4, p.LowPart);
}
return 1;
case 111:
{
LARGE_INTEGER p;
QueryPerformanceCounter (&p);
put_long (m68k_areg (regs, 0), p.HighPart);
put_long (m68k_areg (regs, 0) + 4, p.LowPart);
}
return 1;
#endif
case 200:
ahitweak = m68k_dreg (regs, 1);
ahi_pollrate = m68k_dreg (regs, 2);
if (ahi_pollrate < 10)
ahi_pollrate = 10;
if (ahi_pollrate > 60)
ahi_pollrate = 60;
return 1;
default:
return 0x12345678; // Code for not supportet function
}
}
#endif
|
/*************************************************************
* > File Name : UVa11168.cpp
* > Author : Tony
* > Created Time : 2019/04/25 12:45:01
**************************************************************/
#include <bits/stdc++.h>
using namespace std;
struct Point {
double x, y;
Point(double x = 0, double y = 0): x(x), y(y) {}
};
typedef Point Vector;
typedef vector<Point> Polygon;
Vector operator + (Vector a, Vector b) { return Vector(a.x + b.x, a.y + b.y); }
Vector operator - (Vector a, Vector b) { return Vector(a.x - b.x, a.y - b.y); }
Vector operator * (Vector a, double p) { return Vector(a.x * p, a.y * p); }
Vector operator / (Vector a, double p) { return Vector(a.x / p, a.y / p); }
bool operator < (const Point& a, const Point& b) {
return a.x < b.x || (a.x == b.x && a.y < b.y);
}
bool operator == (const Point& a, const Point& b) {
return a.x == b.x && a.y == b.y;
}
double Cross(Vector a, Vector b) { return a.x * b.y - a.y * b.x; }
Polygon ConvexHull(vector<Point> p) {
sort(p.begin(), p.end());
p.erase(unique(p.begin(), p.end()), p.end());
int n = p.size();
int m = 0;
Polygon ch(n + 1);
for (int i = 0; i < n; ++i) {
while (m > 1 && Cross(ch[m - 1] - ch[m - 2], p[i] - ch[m - 2]) <= 0) m--;
ch[m++] = p[i];
}
int k = m;
for (int i = n - 2; i >= 0; --i) {
while (m > k && Cross(ch[m - 1] - ch[m - 2], p[i] - ch[m - 2]) <= 0) m--;
ch[m++] = p[i];
}
if (n > 1) m--;
ch.resize(m);
return ch;
}
double PolygonArea(Polygon p) {
double area = 0;
int n = p.size();
for(int i = 1; i < n-1; i++)
area += Cross(p[i] - p[0], p[i + 1] - p[0]);
return area / 2;
}
void toNormal(Point p1, Point p2, double& a, double& b, double& c) {
a = p2.y - p1.y;
b = p1.x - p2.x;
c = -a * p1.x - b * p1.y;
}
int main() {
int T;
scanf("%d", &T);
for (int k = 1; k <= T; ++k) {
int n;
scanf("%d", &n);
vector<Point> p;
double sumx = 0, sumy = 0;
for (int i = 0; i < n; ++i) {
double x, y;
scanf("%lf %lf", &x, &y);
p.push_back(Point(x, y));
sumx += x; sumy += y;
}
vector<Point> convex = ConvexHull(p);
int m = convex.size();
double ans = 1e9;
if (m <= 2) ans = 0;
else for (int i = 0; i < m; ++i) {
double a, b, c;
toNormal(convex[i], convex[(i + 1) % m], a, b, c);
ans = min(ans, fabs(a * sumx + b * sumy + c * n) / (sqrt(a * a + b * b)));
}
printf("Case #%d: %.3lf\n", k, ans / n);
}
return 0;
}
|
#ifndef _TRINITY_WIDGET_OBJECT_H_
#define _TRINITY_WIDGET_OBJECT_H_
#include "trinity_object_id.h"
#include "base/nextai_app.h"
#include "render_system/render_system.h"
typedef unsigned long ObjectId;
namespace NextAI
{
/* 点击结果 */
enum class HitResult
{
Hit = 0, /* 命中 */
Missed, /* 未命中 */
};
/* 控件 */
class WidgetObject : public std::enable_shared_from_this<WidgetObject>
{
public:
/* 构造函数和析构函数 */
WidgetObject(ObjectId id);
virtual ~WidgetObject();
virtual void setId(ObjectId id) { m_id = id; }
virtual ObjectId getId() { return m_id; }
/* 管理子控件 */
virtual void addChild(std::shared_ptr<WidgetObject> child);
virtual void removeChild(const std::shared_ptr<WidgetObject> child);
virtual bool isChild(const std::shared_ptr<WidgetObject> child);
/* 获得子控件 */
virtual std::shared_ptr<WidgetObject> getItem(size_t index);
virtual std::shared_ptr<WidgetObject> operator[](size_t index);
virtual size_t getItemCount();
/* 获得ObjectID */
virtual WidgetObject* find(ObjectId id);
/* 语法糖 */
virtual void setArea(const Rect& area)
{
setDrawableArea(area);
setHitableArea(area);
}
/* #### 描画相关 #### */
/* 描画 */
virtual void draw();
virtual void drawImpl();
virtual void setDrawableArea(const Rect& area);
virtual const Rect& getDrawableArea();
/* 是否可见 */
virtual void setVisible(bool visible);
virtual bool getVisible();
/* 是否需要进行刷新 */
virtual void invalidate();
virtual bool isNeedsRefresh();
/* #### 点击相关 #### */
/* 点击 */
virtual HitResult hit(TouchType touch, int32 touchCount, const int32 touchId[], const Point touchPos[]);
virtual HitResult hitImpl(TouchType touch, int32 touchCount, const int32 touchId[], const Point touchPos[]);
virtual void setHitableArea(const Rect& area);
virtual const Rect& getHitableArea();
/* 点击事件 */
virtual void setHitEnable(bool hitEnable);
virtual bool isHitEnable();
/* 点击透过 */
virtual void setHitTransEnable(bool hitTransEnable);
virtual bool isHitTransEnable();
/* 设定捕捉Touch事件 */
virtual void setCaptureTouch(bool isCapture);
virtual bool isCaptureTouch() { return m_isCaptureTouch; }
private:
/* 禁用拷贝构造函数 */
DISABLE_CLASS_COPY(WidgetObject);
/* 禁用常用的一些操作符号 */
bool operator==(WidgetObject& object);
bool operator!=(WidgetObject& object);
bool operator!();
private:
ObjectId m_id; /* 唯一ID */
std::vector<std::shared_ptr<WidgetObject>> m_children; /* 子控件 */
/* #### 描画相关 #### */
bool m_visible; /* 是否可见,默认值[TRUE] */
bool m_needsRefresh; /* 是否需要刷新,默认值[TRUE] */
Rect m_drawableArea; /* 描画区域 */
/* #### 点击相关 #### */
Rect m_hitableArea; /* 点击区域 */
bool m_hitEnable; /* 是否能够点击,默认值[FALSE] */
bool m_hitTransEnable; /* 是否能够向子控件传递,默认值[TRUE] */
bool m_isCaptureTouch; /* 当前是否捕捉Touch操作 */
};
}
#endif // !_TRINITY_WIDGET_OBJECT_H_
|
#include "..\inc.h"
class Solution {
public:
//I & II
vector<vector<int> > permute(vector<int> &num) {
vector<vector<int> > r;
if(num.empty())
return r;
sort(num.begin(), num.end());
r.push_back(num);
if(num.size() == 1)
return r;
for(;;){
int i = num.size() - 2;
for(;i >= 0;--i)
if(num[i] < num[i + 1])
break;
if(i < 0)
break;
int j = num.size() - 1;
for(;j > i;--j)
if(num[i] < num[j])
break;
assert(i < j);
swap(num[i], num[j]);
reverse(num, i + 1);
r.push_back(num);
}
}
void reverse(vector<int> &num, int from){
for(int to = num.size() - 1;from < to;++from, --to)
swap(num[from], num[to]);
}
void nextPermutation(vector<int> &num) {
if(num.size() < 2)
return;
int i = num.size() - 2;
for(;i >= 0;--i)
if(num[i] < num[i + 1])
break;
if(i < 0){
reverse(num, 0);
return;
}
int j = num.size() - 1;
for(;j > i;--j)
if(num[j] > num[i])
break;
swap(num[i], num[j]);
reverse(num, i + 1);
}
string getPermutation(int n, int k) {
string r;
if(n <= 0)
return r;
//calc (n-1)!
int nn = 1;
for(int i = 2;i < n;++i)
nn *= i;
//push char
assert(k > 0);
--k;
vector<bool> used(n);
for(int i = n - 1;i > 0;--i){
int idx = k / nn;
int j = 0, c = 0;
for(;j < n;++j){
if(used[j])
continue;
if(++c > idx)
break;
}
r.push_back(j + '1');
used[j] = true;
k %= nn;
nn /= i;
}
for(int i = 0;i < n;++i)
if(!used[i])
r.push_back(i + '1');
return r;
}
bool prev_permutation(vector<int> & arr)
{
if (arr.empty())
return false;
size_t i = arr.size() - 1;
for (; i > 0 && arr[i - 1] <= arr[i]; --i);
reverse(arr, i);
if (!i) //this is already the first permutation, reverse to the last permutation and return
return false;
size_t j = arr.size() - 1;
for (; j > i && arr[j - 1] <= arr[i - 1]; --j);
swap(arr[i - 1], arr[j]);
return true;
}
};
int main()
{
cout<<Solution().getPermutation(3, 1)<<endl;
cout<<Solution().getPermutation(3, 2)<<endl;
cout << Solution().getPermutation(3, 3) << endl;
{
vector<int> a;
for (int i = 0; i < 4; ++i)
a.push_back(i+1);
Solution().prev_permutation(a);
do{
print(a);
} while (Solution().prev_permutation(a));
}
}
|
#include "camera.hpp"
#include <cmath>
Camera::Camera(int width, int height) :
center(),
size(),
rotation(0),
viewport(0, 0, 1, 1)
{
reset(FloatRect(0, 0, width, height));
}
void Camera::setCenter(float x, float y)
{
center.x = x;
center.y = y;
}
void Camera::setCenter(const sf::Vector2f& center)
{
setCenter(center.x, center.y);
}
void Camera::setSize(float width, float height)
{
size.x = width;
size.y = height;
}
void Camera::setSize(const sf::Vector2f& size)
{
setSize(size.x, size.y);
}
void Camera::setViewport(const FloatRect& viewport)
{
this->viewport = viewport;
}
void Camera::reset(const FloatRect& rectangle)
{
center.x = rectangle.left + rectangle.width / 2.f;
center.y = rectangle.top + rectangle.height / 2.f;
size.x = rectangle.width;
size.y = rectangle.height;
rotation = 0;
}
const sf::Vector2f& Camera::getCenter() const
{
return center;
}
const sf::Vector2f& Camera::getSize() const
{
return size;
}
const FloatRect& Camera::getViewport() const
{
return viewport;
}
void Camera::move(float offsetX, float offsetY)
{
setCenter(center.x + offsetX, center.y + offsetY);
}
void Camera::move(const sf::Vector2f& offset)
{
setCenter(center + offset);
}
void Camera::setPosition(const sf::Vector2f & setPosition)
{
setCenter(setPosition.x, setPosition.y);
}
glm::vec2 Camera::getPosition()const
{
return glm::vec2(center.x, center.y);
}
void Camera::zoom(float factor)
{
setSize(size.x * factor, size.y * factor);
}
glm::mat4 Camera::getProjection()
{
return glm::ortho(0.f, size.x, size.y, 0.f, -1.0f, 1.0f);
}
glm::mat4 Camera::getView()
{
float x = center.x - size.x / 2;
float y = center.y - size.y / 2;
glm::vec3 position(x, y, 0.f);
glm::vec3 front(0.f, 0.f, -1.f);
glm::vec3 up(0.f, 1.f, 0.f);
return glm::lookAt(position, position + front, up);
}
|
#include<bits/stdc++.h>
using namespace std;
#define ll long long
int main(){
ll n, c;
cin >> n >> c;
ll h[n];
for(int i = 0; i < n; i++){
cin >> h[i];
}
ll dp[n];
for(int i = 0; i < n; i++){
int ans = -1;
for(int j = i - 1; j >= 0; j--){
}
}
return 0;
}
|
//
// Copyright (c) 2003--2009
// Toon Knapen, Karl Meerbergen, Kresimir Fresl,
// Thomas Klimpel and Rutger ter Borg
//
// 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)
//
// THIS FILE IS AUTOMATICALLY GENERATED
// PLEASE DO NOT EDIT!
//
#ifndef BOOST_NUMERIC_BINDINGS_LAPACK_COMPUTATIONAL_LARZ_HPP
#define BOOST_NUMERIC_BINDINGS_LAPACK_COMPUTATIONAL_LARZ_HPP
#include <boost/assert.hpp>
#include <boost/mpl/bool.hpp>
#include <boost/numeric/bindings/lapack/detail/lapack.h>
#include <boost/numeric/bindings/lapack/workspace.hpp>
#include <boost/numeric/bindings/traits/detail/array.hpp>
#include <boost/numeric/bindings/traits/is_complex.hpp>
#include <boost/numeric/bindings/traits/is_real.hpp>
#include <boost/numeric/bindings/traits/traits.hpp>
#include <boost/numeric/bindings/traits/type_traits.hpp>
#include <boost/static_assert.hpp>
#include <boost/type_traits/is_same.hpp>
#include <boost/utility/enable_if.hpp>
namespace boost {
namespace numeric {
namespace bindings {
namespace lapack {
//$DESCRIPTION
// overloaded functions to call lapack
namespace detail {
inline void larz( char const side, integer_t const m, integer_t const n,
integer_t const l, float* v, integer_t const incv,
float const tau, float* c, integer_t const ldc, float* work ) {
LAPACK_SLARZ( &side, &m, &n, &l, v, &incv, &tau, c, &ldc, work );
}
inline void larz( char const side, integer_t const m, integer_t const n,
integer_t const l, double* v, integer_t const incv,
double const tau, double* c, integer_t const ldc, double* work ) {
LAPACK_DLARZ( &side, &m, &n, &l, v, &incv, &tau, c, &ldc, work );
}
inline void larz( char const side, integer_t const m, integer_t const n,
integer_t const l, traits::complex_f* v, integer_t const incv,
traits::complex_f const tau, traits::complex_f* c,
integer_t const ldc, traits::complex_f* work ) {
LAPACK_CLARZ( &side, &m, &n, &l, traits::complex_ptr(v), &incv,
traits::complex_ptr(&tau), traits::complex_ptr(c), &ldc,
traits::complex_ptr(work) );
}
inline void larz( char const side, integer_t const m, integer_t const n,
integer_t const l, traits::complex_d* v, integer_t const incv,
traits::complex_d const tau, traits::complex_d* c,
integer_t const ldc, traits::complex_d* work ) {
LAPACK_ZLARZ( &side, &m, &n, &l, traits::complex_ptr(v), &incv,
traits::complex_ptr(&tau), traits::complex_ptr(c), &ldc,
traits::complex_ptr(work) );
}
}
// value-type based template
template< typename ValueType, typename Enable = void >
struct larz_impl{};
// real specialization
template< typename ValueType >
struct larz_impl< ValueType, typename boost::enable_if< traits::is_real<ValueType> >::type > {
typedef ValueType value_type;
typedef typename traits::type_traits<ValueType>::real_type real_type;
// user-defined workspace specialization
template< typename VectorV, typename MatrixC, typename WORK >
static void invoke( char const side, integer_t const l, VectorV& v,
integer_t const incv, real_type const tau, MatrixC& c,
detail::workspace1< WORK > work ) {
BOOST_STATIC_ASSERT( (boost::is_same< typename traits::vector_traits<
VectorV >::value_type, typename traits::matrix_traits<
MatrixC >::value_type >::value) );
BOOST_ASSERT( side == 'L' || side == 'R' );
BOOST_ASSERT( traits::leading_dimension(c) >= std::max(1,
traits::matrix_num_rows(c)) );
BOOST_ASSERT( traits::vector_size(work.select(real_type())) >=
min_size_work( side, traits::matrix_num_rows(c),
traits::matrix_num_columns(c) ));
detail::larz( side, traits::matrix_num_rows(c),
traits::matrix_num_columns(c), l, traits::vector_storage(v),
incv, tau, traits::matrix_storage(c),
traits::leading_dimension(c),
traits::vector_storage(work.select(real_type())) );
}
// minimal workspace specialization
template< typename VectorV, typename MatrixC >
static void invoke( char const side, integer_t const l, VectorV& v,
integer_t const incv, real_type const tau, MatrixC& c,
minimal_workspace work ) {
traits::detail::array< real_type > tmp_work( min_size_work( side,
traits::matrix_num_rows(c), traits::matrix_num_columns(c) ) );
invoke( side, l, v, incv, tau, c, workspace( tmp_work ) );
}
// optimal workspace specialization
template< typename VectorV, typename MatrixC >
static void invoke( char const side, integer_t const l, VectorV& v,
integer_t const incv, real_type const tau, MatrixC& c,
optimal_workspace work ) {
invoke( side, l, v, incv, tau, c, minimal_workspace() );
}
static integer_t min_size_work( char const side, integer_t const m,
integer_t const n ) {
if ( side == 'L' )
return n;
else
return m;
}
};
// complex specialization
template< typename ValueType >
struct larz_impl< ValueType, typename boost::enable_if< traits::is_complex<ValueType> >::type > {
typedef ValueType value_type;
typedef typename traits::type_traits<ValueType>::real_type real_type;
// user-defined workspace specialization
template< typename VectorV, typename MatrixC, typename WORK >
static void invoke( char const side, integer_t const l, VectorV& v,
integer_t const incv, value_type const tau, MatrixC& c,
detail::workspace1< WORK > work ) {
BOOST_STATIC_ASSERT( (boost::is_same< typename traits::vector_traits<
VectorV >::value_type, typename traits::matrix_traits<
MatrixC >::value_type >::value) );
BOOST_ASSERT( side == 'L' || side == 'R' );
BOOST_ASSERT( traits::leading_dimension(c) >= std::max(1,
traits::matrix_num_rows(c)) );
BOOST_ASSERT( traits::vector_size(work.select(value_type())) >=
min_size_work( side, traits::matrix_num_rows(c),
traits::matrix_num_columns(c) ));
detail::larz( side, traits::matrix_num_rows(c),
traits::matrix_num_columns(c), l, traits::vector_storage(v),
incv, tau, traits::matrix_storage(c),
traits::leading_dimension(c),
traits::vector_storage(work.select(value_type())) );
}
// minimal workspace specialization
template< typename VectorV, typename MatrixC >
static void invoke( char const side, integer_t const l, VectorV& v,
integer_t const incv, value_type const tau, MatrixC& c,
minimal_workspace work ) {
traits::detail::array< value_type > tmp_work( min_size_work( side,
traits::matrix_num_rows(c), traits::matrix_num_columns(c) ) );
invoke( side, l, v, incv, tau, c, workspace( tmp_work ) );
}
// optimal workspace specialization
template< typename VectorV, typename MatrixC >
static void invoke( char const side, integer_t const l, VectorV& v,
integer_t const incv, value_type const tau, MatrixC& c,
optimal_workspace work ) {
invoke( side, l, v, incv, tau, c, minimal_workspace() );
}
static integer_t min_size_work( char const side, integer_t const m,
integer_t const n ) {
if ( side == 'L' )
return n;
else
return m;
}
};
// template function to call larz
template< typename VectorV, typename MatrixC, typename Workspace >
inline integer_t larz( char const side, integer_t const l, VectorV& v,
integer_t const incv, typename traits::type_traits<
typename traits::vector_traits<
VectorV >::value_type >::real_type const tau, MatrixC& c,
Workspace work ) {
typedef typename traits::vector_traits< VectorV >::value_type value_type;
integer_t info(0);
larz_impl< value_type >::invoke( side, l, v, incv, tau, c, work );
return info;
}
// template function to call larz, default workspace type
template< typename VectorV, typename MatrixC >
inline integer_t larz( char const side, integer_t const l, VectorV& v,
integer_t const incv, typename traits::type_traits<
typename traits::vector_traits<
VectorV >::value_type >::real_type const tau, MatrixC& c ) {
typedef typename traits::vector_traits< VectorV >::value_type value_type;
integer_t info(0);
larz_impl< value_type >::invoke( side, l, v, incv, tau, c,
optimal_workspace() );
return info;
}
// template function to call larz
template< typename VectorV, typename MatrixC, typename Workspace >
inline integer_t larz( char const side, integer_t const l, VectorV& v,
integer_t const incv, typename traits::vector_traits<
VectorV >::value_type const tau, MatrixC& c, Workspace work ) {
typedef typename traits::vector_traits< VectorV >::value_type value_type;
integer_t info(0);
larz_impl< value_type >::invoke( side, l, v, incv, tau, c, work );
return info;
}
// template function to call larz, default workspace type
template< typename VectorV, typename MatrixC >
inline integer_t larz( char const side, integer_t const l, VectorV& v,
integer_t const incv, typename traits::vector_traits<
VectorV >::value_type const tau, MatrixC& c ) {
typedef typename traits::vector_traits< VectorV >::value_type value_type;
integer_t info(0);
larz_impl< value_type >::invoke( side, l, v, incv, tau, c,
optimal_workspace() );
return info;
}
}}}} // namespace boost::numeric::bindings::lapack
#endif
|
/*
* Copyright (C) 2018-2019 wuuhii. All rights reserved.
*
* The file is encoding with utf-8 (with BOM). It is a part of QtSwissArmyKnife
* project. The project is a open source project, you can get the source from:
* https://github.com/wuuhii/QtSwissArmyKnife
* https://gitee.com/wuuhii/QtSwissArmyKnife
*
* If you want to know more about the project, please join our QQ group(952218522).
* In addition, the email address of the project author is wuuhii@outlook.com.
*/
#ifndef SAKUDPDEVICE_HH
#define SAKUDPDEVICE_HH
#include <QMutex>
#include <QThread>
#include <QUdpSocket>
class SAKDebugPage;
class SAKUdpDevice:public QThread
{
Q_OBJECT
public:
SAKUdpDevice(QString localHost, quint16 localPort,
bool enableCustomLocalSetting,
QString targetHost, quint16 targetPort,
SAKDebugPage *debugPage,
QObject *parent = Q_NULLPTR);
~SAKUdpDevice();
/**
* @brief readBytes 读取数据
*/
void readBytes();
/**
* @brief writeBytes 写数据
* @param data 代写数据
*/
void writeBytes(QByteArray data);
/**
* @brief 参数上下文
*/
struct ParametersContext{
bool enableUnicast;
bool enableMulticast;
bool enableBroadcast;
quint16 broadcastPort;
struct MulticastInfo{
bool enable;
QString address;
quint16 port;
};
QList<MulticastInfo> multicastInfoList;
};
/**
* @brief setUnicastEnable 启用/禁止单播功能
* @param enable 该值为true时,启用单播功能,否则禁止单播功能
*/
void setUnicastEnable(bool enable);
/**
* @brief setBroadcastInfo 启用/禁止广播功能
* @param enable 该值为true时,启用广播功能,否则禁止广播功能
*/
void setBroadcastEnable(bool enable);
/**
* @brief setBroadcastPort 设置广播端口
* @param port 广播端口
*/
void setBroadcastPort(quint16 port);
/**
* @brief addMulticastInfo 添加组播
* @param enable 该值为true是,使能该组播地址
* @param address 组播地址
* @param port 组播端口
*/
void addMulticastInfo(bool enable, QString address, quint16 port);
/**
* @brief removeMulticastInfo 移除组播
* @param address 组播地址
* @param port 组播端口
*/
void removeMulticastInfo(QString address, quint16 port);
/**
* @brief setMulticastEnable 启用/静止单个组播
* @param enable 该值为true是允许该组播
* @param address 广播地址
* @param port 广播端口
*/
void setMulticastEnable(bool enable, QString address, quint16 port);
/**
* @brief setMulticastEnable 启用/静止组播功能(总开关)
* @param enable 该值为true是,使能组播功能,否则禁止全部组播。
*/
void setMulticastEnable(bool enable);
private:
QMutex parametersContextMutex;
ParametersContext parametersContext;
const ParametersContext parametersContextInstance();
private:
void run();
private:
QString localHost;
quint16 localPort;
bool enableCustomLocalSetting;
QString targetHost;
quint16 targetPort;
SAKDebugPage *debugPage;
QUdpSocket *udpSocket;
signals:
void bytesRead(QByteArray);
void bytesWriten(QByteArray);
void deviceStatuChanged(bool opened);
void messageChanged(QString message, bool isInfo);
};
#endif
|
//Water Pump Loop stuff
void pumpOn(){
// Serial.println("Pump On");//For Debug
digitalWrite(WATER_PUMP_PIN, LOW);
// lcd.setCursor ( 6, 1 );
// lcd.print("W+");
t.after(600000, pumpOff);
}
void pumpOff(){
// Serial.println("Pump Off");//For Debug
//lcd.setCursor ( 6, 1 );
// lcd.print("W-");
digitalWrite(WATER_PUMP_PIN, HIGH);
}
|
#include<bits/stdc++.h>
using namespace std;
int main(){
int t;
cin >> t;
while( t-- ){
int n;
cin >> n;
int ans = 0;
int d = log10(n) + 1;
ans = (d - 1) * 9;
for(int j = 1; j <= 9; j++){
int curr = 0;
for(int i = 0; i < d ; i++){
curr = curr*10 + j;
}
if( curr <= n) ans++;
else break;
}
cout << ans << endl;
}
return 0;
}
|
#include <iostream>
#include <pcl/io/pcd_io.h>
#include <pcl/point_types.h>
#include <pcl/point_cloud.h>
#include <pcl/octree/octree.h>
#include <pcl/filters/voxel_grid_covariance.h>
#include <pcl/visualization/cloud_viewer.h>
float voxel_size = 0.1;
int count = 0;
int counttarget = 0;
void XOR(pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_model, pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_target)
{
//Empty Box
pcl::VoxelGridCovariance<pcl::PointXYZ> cell_model;
cell_model.setLeafSize(voxel_size,voxel_size,voxel_size);
cell_model.setInputCloud(cloud_model);
cell_model.filter(true);
const std::map<size_t, pcl::VoxelGridCovariance<pcl::PointXYZ>::Leaf> &leaves_model = cell_model.getLeaves();
//Target Box
pcl::VoxelGridCovariance<pcl::PointXYZ> cell_target;
cell_target.setLeafSize(voxel_size,voxel_size,voxel_size);
cell_target.setInputCloud(cloud_target);
cell_target.filter(true);
const std::map<size_t, pcl::VoxelGridCovariance<pcl::PointXYZ>::Leaf> &leaves_target = cell_target.getLeaves();
//XOR
for(std::map<size_t, pcl::VoxelGridCovariance<pcl::PointXYZ>::Leaf>::const_iterator it = leaves_target.begin(); it != leaves_target.end(); ++it)
{
const pcl::VoxelGridCovariance<pcl::PointXYZ>::Leaf &leaf_target = it->second;
Eigen::Vector3f p_target = leaf_target.getMean().cast<float>();;
const pcl::VoxelGridCovariance<pcl::PointXYZ>::Leaf *leaf_model = cell_model.getLeaf(p_target);
if(leaf_model == NULL){
std::cout << "in point" << std::endl;
count++;
//Eigen::Vector3f p_model = leaf_model->getMean().cast<float>();;
std::cout << leaf_target.getPointCount() << std::endl;
//std::cout << leaf_model->getPointCount() << std::endl;
std::cout << p_target << std::endl;
//std::cout << p_model << std::endl;
}
counttarget++;
}
std::cout << count << std::endl;
std::cout << counttarget << std::endl;
}
pcl::PointCloud<pcl::PointXYZ> difference_extraction(pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_base, pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_test)
{
//cloud_baseは元となる点群
//cloud_testは比較対象の点群
//cloud_diffは比較の結果差分とされた点群
double resolution = 0.00001;//Octreeの解像度を指定
pcl::octree::OctreePointCloudChangeDetector<pcl::PointXYZ> octree (resolution);//Octreeを作成
octree.setInputCloud (cloud_base);//元となる点群を入力
octree.addPointsFromInputCloud ();
octree.switchBuffers ();//バッファの切り替え
octree.setInputCloud (cloud_test);//比較対象の点群を入力
octree.addPointsFromInputCloud ();
std::vector<int> newPointIdxVector;//
octree.getPointIndicesFromNewVoxels (newPointIdxVector);//比較の結果差分と判断された点郡の情報を保管
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_diff (new pcl::PointCloud<pcl::PointXYZ> );//出力先
//保管先のサイズの設定
cloud_diff->width = cloud_base->points.size() + cloud_test->points.size();
cloud_diff->height = 1;
cloud_diff->points.resize (cloud_diff->width * cloud_diff->height);
int n = 0;//差分点群の数を保存する
for(size_t i = 0; i < newPointIdxVector.size (); i++)
{
cloud_diff->points[i].x = cloud_test->points[newPointIdxVector[i]].x;
cloud_diff->points[i].y = cloud_test->points[newPointIdxVector[i]].y;
cloud_diff->points[i].z = cloud_test->points[newPointIdxVector[i]].z;
n++;
}
//差分点群のサイズの再設定
cloud_diff->width = n;
cloud_diff->height = 1;
cloud_diff->points.resize (cloud_diff->width * cloud_diff->height);
return *cloud_diff;
}
int main(int argc, char **argv)
{
//srand ((unsigned int) time (NULL));
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_target (new pcl::PointCloud<pcl::PointXYZ> );
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_model (new pcl::PointCloud<pcl::PointXYZ> );
pcl::io::loadPCDFile("bunny.pcd", *cloud_model);
pcl::io::loadPCDFile("test_pcd.pcd", *cloud_target);
XOR(cloud_target,cloud_model);
//pcl::io::savePCDFileBinary("difference.pcd", difference_extraction(cloud_base, cloud_test));
// pcl::PointCloud<pcl::PointXYZ> cloud;
// // Fill in the cloud data
// cloud.width = 100;
// cloud.height = 100;
// cloud.is_dense = false;
// cloud.points.resize(cloud.width * cloud.height);
// for (size_t i = 0; i < cloud.points.size(); ++i)
// {
// cloud.points[i].x = 1024 * rand() / (RAND_MAX + 1.0f);
// cloud.points[i].y = 1024 * rand() / (RAND_MAX + 1.0f);
// cloud.points[i].z = 1024 * rand() / (RAND_MAX + 1.0f);
// }
// pcl::io::savePCDFileASCII("test_pcd.pcd", cloud);
// std::cerr << "Saved " << cloud.points.size() << " data points to test_pcd.pcd." << std::endl;
// for (size_t i = 0; i < cloud.points.size(); ++i)
// std::cerr << " " << cloud.points[i].x << " " << cloud.points[i].y << " " << cloud.points[i].z << std::endl;
pcl::visualization::CloudViewer viewer ("Simple Cloud Viewer");
viewer.showCloud (cloud_target);
while (!viewer.wasStopped ())
{
}
return (0);
}
|
#include "AboutLayer.h"
#include "WelcomeLayer.h"
AboutLayer::AboutLayer()
{
}
AboutLayer::~AboutLayer()
{
}
bool AboutLayer::init()
{
bool s=false;
do
{
CC_BREAK_IF(!BasicLayer::init());
SetView();
s=true;
} while (0);
return s;
}
void AboutLayer::SetView()
{
setBackgroundImage("loading.png");
auto lb_abt=Sprite::create("menuTitle.png",Rect(0,34,134,39));
lb_abt->setAnchorPoint(Point(0.5,1));
lb_abt->setPosition(Point(getwinsize().width/2+5,getwinsize().height-40));
addChild(lb_abt);
auto lbf=Label::createWithBMFont("arial-14.fnt","Learn from Longlongxiu !");
lbf->setPosition(VisibleRect::center());
addChild(lbf);
auto lb_back=Label::createWithBMFont("arial-14.fnt","go back");
auto item_back=MenuItemLabel::create(lb_back,CC_CALLBACK_1(AboutLayer::keyBackClicked,this));
item_back->setAnchorPoint(Point(1,0));
item_back->setScale(1.3f);
item_back->setPosition(Point(getwinsize().width,30));
auto menu_back=Menu::create(item_back,NULL);
menu_back->setPosition(Point(0,0));
addChild(menu_back);
}
void AboutLayer::keyBackClicked(Ref* sender)
{
Director::getInstance()->replaceScene(TransitionFade::create(0.5f,WelcomeLayer::scene()));
}
Scene* AboutLayer::scene()
{
auto scene=Scene::create();
auto layer=AboutLayer::create();
scene->addChild(layer);
return scene;
}
|
// file : liblava/util/file.hpp
// copyright : Copyright (c) 2018-present, Lava Block OÜ
// license : MIT; see accompanying LICENSE file
#pragma once
#include <liblava/core/data.hpp>
#include <liblava/util/log.hpp>
#include <fstream>
#include <filesystem>
#include <nlohmann/json.hpp>
// fwd
struct PHYSFS_File;
namespace lava {
constexpr name _zip_ = "zip";
constexpr name _config_file_ = "config.json";
using json = nlohmann::json;
namespace fs = std::filesystem;
bool read_file(std::vector<char>& out, name filename);
bool write_file(name filename, char const* data, size_t data_size);
bool extension(name file_name, name extension);
bool extension(name filename, names extensions);
string get_filename_from(string_ref path, bool with_extension = false);
bool remove_existing_path(string& target, string_ref path);
struct file_guard : no_copy_no_move {
explicit file_guard(name filename = "") : filename(filename) {}
explicit file_guard(string filename) : filename(filename) {}
~file_guard() {
if (remove)
fs::remove(filename);
}
string filename;
bool remove = true;
};
struct file_system : no_copy_no_move {
static file_system& instance() {
static file_system fs;
return fs;
}
static internal_version get_version();
static name get_base_dir();
static string get_base_dir_str();
static name get_pref_dir();
static string get_res_dir();
static bool mount(string_ref path);
static bool mount(name base_dir_path);
static bool exists(name file);
static name get_real_dir(name file);
static string_list enumerate_files(name path);
bool initialize(name argv_0, name org, name app, name ext);
void terminate();
void mount_res();
bool create_data_folder();
name get_org() const { return org; }
name get_app() const { return app; }
name get_ext() const { return ext; }
bool ready() const { return initialized; }
private:
file_system() = default;
bool initialized = false;
name org = nullptr;
name app = nullptr;
name ext = nullptr;
string res_path;
};
enum class file_type : type {
none = 0,
fs,
f_stream
};
constexpr i64 const file_error_result = -1;
inline bool file_error(i64 result) { return result == file_error_result; }
struct file : no_copy_no_move {
explicit file(name path = nullptr, bool write = false);
~file();
bool open(name path, bool write = false);
void close();
bool opened() const;
i64 get_size() const;
i64 read(data_ptr data) { return read(data, to_ui64(get_size())); }
i64 read(data_ptr data, ui64 size);
i64 write(data_cptr data, ui64 size);
bool writable() const { return write_mode; }
file_type get_type() const { return type; }
name get_path() const { return path; }
private:
file_type type = file_type::none;
bool write_mode = false;
name path = nullptr;
PHYSFS_File* fs_file = nullptr;
mutable std::ifstream i_stream;
mutable std::ofstream o_stream;
};
bool load_file_data(string_ref filename, data& target);
struct file_data {
explicit file_data(string_ref filename) { load_file_data(filename, scope_data); }
data const& get() const { return scope_data; }
private:
lava::scope_data scope_data;
};
struct file_callback {
using list = std::vector<file_callback*>;
using func = std::function<void(json&)>;
func on_load;
func on_save;
};
struct json_file {
explicit json_file(name path = _config_file_);
void add(file_callback* callback);
void remove(file_callback* callback);
void set(name value) { path = value; }
name get() const { return str(path); }
bool load();
bool save();
private:
string path;
file_callback::list callbacks;
};
} // lava
|
/*************************************************************************
> File Name : Crl.cpp
> Author : YangShuai
> Created Time: 2016年07月29日 星期五 20时43分44秒
> Description :
************************************************************************/
#include"Itsdata.h"
#include"data_handle.h"
int32 Crl::_encode(Data& data){
u8* buf = data.getbufptr();
int32 initsize = data.currpos;
int32& size = data.currpos;
if(data.unused() < _datasize()){
ERROR_PRINT_AND_RETURN("缓存空间不足");
}
*buf++ = version;
size++;
if(signer._encode(data) < 0){
ERROR_PRINT_AND_RETURN("SignerInfo编码失败");
}
if(unsigned_crl._encode(data) < 0){
ERROR_PRINT_AND_RETURN("ToBeSignedCrl编码失败");
}
if(signature._encode(data) < 0){
ERROR_PRINT_AND_RETURN("Signature编码失败");
}
return size - initsize;
}
int32 Crl::_decode(Data& data){
u8* buf = data.getbufptr();
int32 initsize = data.currpos;
int32& size = data.currpos;
if(data.unused() < 34){
ERROR_PRINT_AND_RETURN("填充数据不足");
}
version = *buf++;
size++;
if(signer._decode(data) < 0){
ERROR_PRINT_AND_RETURN("SignerInfo解码失败");
}
if(unsigned_crl._decode(data) < 0){
ERROR_PRINT_AND_RETURN("ToBeSignedCrl解码失败");
}
if(signature._decode(data) < 0){
ERROR_PRINT_AND_RETURN("Signature解码失败");
}
datasize = size - initsize;
return size - initsize;
}
int32 Crl::_datasize(){
if(datasize) goto end;
datasize++;
datasize += signer._datasize();
datasize += unsigned_crl._datasize();
datasize += signature._datasize();
end:
return datasize;
}
|
#include "JavaFunction.h"
/*
JNIEnv *env; // JVM environment
jobject instance; // the Java function instance
jmethodID fct; // the Java method
jstring jname; // the Java function name
jdoubleArray array; // the Java array as argument
*/
JavaFunction::JavaFunction(JNIEnv* env, jobject instance) {
this->env = env;
this->instance = instance;
jclass clazz = env->GetObjectClass(instance);
this->fct = env->GetMethodID(clazz, "eval", "([D)D");
this->array = env->NewDoubleArray(1);
}
JavaFunction::~JavaFunction() = default;
|
//$Id: USNTwoWayRange.cpp 1398 2011-04-21 20:39:37Z $
//------------------------------------------------------------------------------
// USNTwoWayRange
//------------------------------------------------------------------------------
// GMAT: General Mission Analysis Tool
//
// Copyright (c) 2002 - 2015 United States Government as represented by the
// Administrator of The National Aeronautics and Space Administration.
// All Other 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.
//
// Developed jointly by NASA/GSFC and Thinking Systems, Inc. under contract
// number NNG06CA54C
//
// Author: Darrel J. Conway, Thinking Systems, Inc.
// Created: 2009/12/18
//
/**
* The USN 2-way range core measurement model.
*/
//------------------------------------------------------------------------------
// this needs to be at the top for Ionosphere to work on Mac!
#include "RandomNumber.hpp"
#include "USNTwoWayRange.hpp"
#include "gmatdefs.hpp"
#include "MeasurementException.hpp"
#include "MessageInterface.hpp"
#include "GmatConstants.hpp"
#include "Spacecraft.hpp"
#include "GroundstationInterface.hpp"
#include "Antenna.hpp"
#include "Transmitter.hpp"
#include "Receiver.hpp"
#include "Transponder.hpp"
#include "TimeSystemConverter.hpp"
#include "SpacePoint.hpp"
//#define DEBUG_RANGE_CALC_WITH_EVENTS
//#define VIEW_PARTICIPANT_STATES_WITH_EVENTS
//#define DEBUG_RANGE_CALC
//#define VIEW_PARTICIPANT_STATES
//#define CHECK_PARTICIPANT_LOCATIONS
//#define DEBUG_DERIVATIVES
//#define PRELIMINARY_DERIVATIVE_CHECK // Calc derivative while simulating
//------------------------------------------------------------------------------
// USNTwoWayRange(const std::string nomme)
//------------------------------------------------------------------------------
/**
* Default constructor
*
* @param nomme The name of the core measurement model
*/
//------------------------------------------------------------------------------
USNTwoWayRange::USNTwoWayRange(const std::string nomme) :
TwoWayRange ("USNTwoWayRange", nomme),
targetRangeRate (0.0),
uplinkRangeRate (0.0),
downlinkRangeRate (0.0)
{
objectTypeNames.push_back("USNTwoWayRange");
// Prep value array in measurement
currentMeasurement.value.push_back(0.0);
currentMeasurement.typeName = "USNTwoWayRange";
currentMeasurement.type = Gmat::USN_TWOWAYRANGE;
currentMeasurement.eventCount = 2;
covariance.SetDimension(1);
covariance(0,0) = 1.0;
}
//------------------------------------------------------------------------------
// ~USNTwoWayRange()
//------------------------------------------------------------------------------
/**
* Destructor
*/
//------------------------------------------------------------------------------
USNTwoWayRange::~USNTwoWayRange()
{
}
//------------------------------------------------------------------------------
// USNTwoWayRange(const USNTwoWayRange& usn)
//------------------------------------------------------------------------------
/**
* Copy constructor
*
* @param usn The model that is getting copied
*/
//------------------------------------------------------------------------------
USNTwoWayRange::USNTwoWayRange(const USNTwoWayRange& usn) :
TwoWayRange (usn),
targetRangeRate (usn.targetRangeRate),
uplinkRangeRate (usn.uplinkRangeRate),
downlinkRangeRate (usn.downlinkRangeRate)
{
currentMeasurement.value.push_back(0.0);
currentMeasurement.typeName = "USNTwoWayRange";
currentMeasurement.type = Gmat::USN_TWOWAYRANGE;
currentMeasurement.eventCount = 2;
currentMeasurement.uniqueID = usn.currentMeasurement.uniqueID;
currentMeasurement.participantIDs.push_back("NotSet");
currentMeasurement.participantIDs.push_back("NotSet");
covariance = usn.covariance;
}
//------------------------------------------------------------------------------
// USNTwoWayRange& operator=(const USNTwoWayRange& usn)
//------------------------------------------------------------------------------
/**
* Assignment operator
*
* @param usn The model that is getting copied
*
* @return This USN 2-way range model, configured to match usn.
*/
//------------------------------------------------------------------------------
USNTwoWayRange& USNTwoWayRange::operator=(const USNTwoWayRange& usn)
{
if (this != &usn)
{
TwoWayRange::operator=(usn);
// Allocate exactly one value in current measurement for range
currentMeasurement.value.clear();
currentMeasurement.value.push_back(0.0);
currentMeasurement.typeName = "USNTwoWayRange";
currentMeasurement.type = Gmat::USN_TWOWAYRANGE;
currentMeasurement.uniqueID = usn.currentMeasurement.uniqueID;
targetRangeRate = usn.targetRangeRate;
uplinkRangeRate = usn.uplinkRangeRate;
downlinkRangeRate = usn.downlinkRangeRate;
covariance = usn.covariance;
}
return *this;
}
//------------------------------------------------------------------------------
// GmatBase* Clone() const
//------------------------------------------------------------------------------
/**
* Creates a new model that matches this one, and returns it as a GmatBase
* pointer
*
* @return A new USN 2-way range model configured to match this one
*/
//------------------------------------------------------------------------------
GmatBase* USNTwoWayRange::Clone() const
{
return new USNTwoWayRange(*this);
}
//------------------------------------------------------------------------------
// bool Initialize()
//------------------------------------------------------------------------------
/**
* Initializes the model prior to performing measurement computations
*
* @return true on success, false on failure
*/
//------------------------------------------------------------------------------
bool USNTwoWayRange::Initialize()
{
#ifdef DEBUG_RANGE_CALC
MessageInterface::ShowMessage("Entered RangeMeasurement::Initialize(); "
"this = %p\n", this);
#endif
bool retval = false;
if (TwoWayRange::Initialize())
retval = true;
#ifdef DEBUG_RANGE_CALC
MessageInterface::ShowMessage(" Initialization %s with %d "
"participants\n", (retval ? "succeeded" : "failed"),
participants.size());
#endif
return retval;
}
//------------------------------------------------------------------------------
// const std::vector<RealArray>& CalculateMeasurementDerivatives(
// GmatBase *obj, Integer id)
//------------------------------------------------------------------------------
/**
* Calculates the measurement derivatives for the model
*
* @param obj The object supplying the "with respect to" parameter
* @param id The ID of the parameter
*
* @return A matrix of the derivative data, contained in a vector of Real
* vectors
*/
//------------------------------------------------------------------------------
const std::vector<RealArray>& USNTwoWayRange::CalculateMeasurementDerivatives(
GmatBase *obj, Integer id)
{
#ifdef DEBUG_DERIVATIVES
MessageInterface::ShowMessage("USNTwoWayRange::CalculateMeasurement"
"Derivatives(%s, %d) called\n", obj->GetName().c_str(), id);
#endif
if (!initialized)
InitializeMeasurement();
GmatBase *objPtr = NULL;
Integer size = obj->GetEstimationParameterSize(id);
Integer objNumber = -1;
#ifdef DEBUG_DERIVATIVES
MessageInterface::ShowMessage(" ParameterSize = %d\n", size);
#endif
if (size <= 0)
throw MeasurementException("The derivative parameter on derivative "
"object " + obj->GetName() + "is not recognized");
// Check to see if obj is a participant
for (UnsignedInt i = 0; i < participants.size(); ++i)
{
if (participants[i] == obj)
{
objPtr = participants[i];
objNumber = i + 1;
#ifdef DEBUG_DERIVATIVES
MessageInterface::ShowMessage(" Participant %s found\n",
objPtr->GetName().c_str());
#endif
break;
}
}
// Or if it is the measurement model for this object
if (obj->IsOfType(Gmat::MEASUREMENT_MODEL))
if (obj->GetRefObject(Gmat::CORE_MEASUREMENT, "") == this)
{
objPtr = obj;
objNumber = 0;
#ifdef DEBUG_DERIVATIVES
MessageInterface::ShowMessage(" The measurement is the object\n",
objPtr->GetName().c_str());
#endif
}
if (objNumber == -1)
throw MeasurementException(
"USNTwoWayRange error - object is neither participant nor "
"measurement model.");
RealArray oneRow;
oneRow.assign(size, 0.0);
currentDerivatives.clear();
currentDerivatives.push_back(oneRow);
Integer parameterID = GetParmIdFromEstID(id, obj);
#ifdef DEBUG_DERIVATIVES
MessageInterface::ShowMessage(" Looking up id %d\n", parameterID);
#endif
if (objPtr != NULL)
{
if (objNumber == 1) // participant number 1, either a GroundStation or a Spacecraft
{
#ifdef DEBUG_DERIVATIVES
MessageInterface::ShowMessage(" Deriv is w.r.t. %s of Participant"
" 1\n", objPtr->GetParameterText(parameterID).c_str());
#endif
if (objPtr->GetParameterText(parameterID) == "Position")
{
throw MeasurementException("Derivative w.r.t. " +
participants[0]->GetName() +" position is not yet implemented");
// CalculateRangeVectorInertial();
// Rvector3 tmp, result;
// Rvector3 rangeUnit = rangeVecInertial.GetUnitVector();
// #ifdef DEBUG_DERIVATIVES
// MessageInterface::ShowMessage(" RVInertial = %.12lf %.12lf %.12lf\n",
// rangeVecInertial[0], rangeVecInertial[1], rangeVecInertial[2]);
// MessageInterface::ShowMessage(" Unit RVInertial = %.12lf %.12lf %.12lf ",
// rangeUnit[0], rangeUnit[1], rangeUnit[2]);
// #endif
// if (stationParticipant)
// {
// for (UnsignedInt i = 0; i < 3; ++i)
// tmp[i] = - rangeUnit[i];
//
// // for a Ground Station, need to rotate to the F1 frame
// result = tmp * R_j2k_1;
// for (UnsignedInt jj = 0; jj < 3; jj++)
// currentDerivatives[0][jj] = result[jj];
// }
// else
// {
// // for a spacecraft participant 1, we don't need the rotation matrices (I33)
// for (UnsignedInt i = 0; i < 3; ++i)
// currentDerivatives[0][i] = - rangeUnit[i];
// }
}
else if (objPtr->GetParameterText(parameterID) == "Velocity")
{
throw MeasurementException("Derivative w.r.t. " +
participants[0]->GetName() +" velocity is not yet implemented");
// for (UnsignedInt i = 0; i < 3; ++i)
// currentDerivatives[0][i] = 0.0;
}
else if (objPtr->GetParameterText(parameterID) == "CartesianX")
{
throw MeasurementException("Derivative w.r.t. " +
participants[0]->GetName() + " CartesianState is not yet implemented");
//
// CalculateRangeVectorInertial();
// Rvector3 tmp, result;
// Rvector3 rangeUnit = rangeVecInertial.GetUnitVector();
// #ifdef DEBUG_DERIVATIVES
// MessageInterface::ShowMessage(" RVInertial = %.12lf %.12lf %.12lf\n",
// rangeVecInertial[0], rangeVecInertial[1], rangeVecInertial[2]);
// MessageInterface::ShowMessage(" Unit RVInertial = %.12lf %.12lf %.12lf ",
// rangeUnit[0], rangeUnit[1], rangeUnit[2]);
// #endif
// if (stationParticipant)
// {
// for (UnsignedInt i = 0; i < size; ++i)
// tmp[i] = - rangeUnit[i];
//
// // for a Ground Station, need to rotate to the F1 frame
// result = tmp * R_j2k_1;
// for (UnsignedInt jj = 0; jj < size; jj++)
// currentDerivatives[0][jj] = result[jj];
// }
// else
// {
// // for a spacecraft participant 1, we don't need the rotation matrices (I33)
// for (UnsignedInt i = 0; i < size; ++i)
// currentDerivatives[0][i] = - rangeUnit[i];
// }
// // velocity all zeroes
// for (UnsignedInt ii = 3; ii < size; ii++)
// currentDerivatives[0][ii] = 0.0;
}
else if (objPtr->GetParameterText(parameterID) == "Bias")
{
for (Integer i = 0; i < size; ++i)
currentDerivatives[0][i] = 1.0;
}
else
{
#ifdef DEBUG_DERIVATIVES
MessageInterface::ShowMessage(" Deriv is w.r.t. something "
"independent, so zero\n");
#endif
for (Integer i = 0; i < size; ++i)
currentDerivatives[0][i] = 0.0;
}
}
else if (objNumber == 2) // participant 2, always a Spacecraft
{
#ifdef DEBUG_DERIVATIVES
MessageInterface::ShowMessage(" Deriv is w.r.t. %s of Participant"
" 2\n", objPtr->GetParameterText(parameterID).c_str());
#endif
if (objPtr->GetParameterText(parameterID) == "Position")
{
// Get the inverse of the orbit STM at the measurement epoch
// Will need adjustment if stm changes
Rmatrix stmInv(6,6);
GetInverseSTM(obj, stmInv);
Rvector3 uplinkRderiv;
GetRangeDerivative(uplinkLeg, stmInv, uplinkRderiv, false, 0, 1,
true, false);
// Downlink leg
Rvector3 downlinkRderiv;
GetRangeDerivative(downlinkLeg, stmInv, downlinkRderiv, false, 0, 1,
true, false);
// Add 'em up per eq 7.52 and 7.53
for (Integer i = 0; i < size; ++i)
currentDerivatives[0][i] =
0.5 * (uplinkRderiv[i] + downlinkRderiv[i]);
#ifdef DEBUG_DERIVATIVES
MessageInterface::ShowMessage("Position Derivative: [%.12lf "
"%.12lf %.12lf]\n", currentDerivatives[0][0],
currentDerivatives[0][1], currentDerivatives[0][2]);
#endif
}
else if (objPtr->GetParameterText(parameterID) == "Velocity")
{
// Get the inverse of the orbit STM at the measurement epoch
// Will need adjustment if stm changes
Rmatrix stmInv(6,6);
GetInverseSTM(obj, stmInv);
Rvector3 uplinkVderiv;
GetRangeDerivative(uplinkLeg, stmInv, uplinkVderiv, false, 0, 1,
false);
// Downlink leg
Rvector3 downlinkVderiv;
GetRangeDerivative(downlinkLeg, stmInv, downlinkVderiv, false, 0, 1,
false);
// Add 'em up per eq 7.52 and 7.53
for (Integer i = 0; i < size; ++i)
currentDerivatives[0][i] =
0.5 * (uplinkVderiv[i] + downlinkVderiv[i]);
#ifdef DEBUG_DERIVATIVES
MessageInterface::ShowMessage("Velocity Derivative: [%.12lf "
"%.12lf %.12lf]\n", currentDerivatives[0][0],
currentDerivatives[0][1], currentDerivatives[0][2]);
#endif
}
else if (objPtr->GetParameterText(parameterID) == "CartesianX")
{
// Get the inverse of the orbit STM at the measurement epoch
// Will need adjustment if stm changes
Rmatrix stmInv(6,6);
GetInverseSTM(obj, stmInv);
Rvector6 uplinkDeriv;
GetRangeDerivative(uplinkLeg, stmInv, uplinkDeriv, false);
// GetRangeDerivative(uplinkLeg, stmInv, uplinkDeriv, false, 0, 1, true, true);
// Downlink leg
Rvector6 downlinkDeriv;
GetRangeDerivative(downlinkLeg, stmInv, downlinkDeriv, false);
// GetRangeDerivative(downlinkLeg, stmInv, downlinkDeriv, true, 1, 0, true, true);
// Add 'em up per eq 7.52 and 7.53
for (Integer i = 0; i < 6; ++i)
currentDerivatives[0][i] =
0.5 * (uplinkDeriv[i] + downlinkDeriv[i]);
#ifdef DEBUG_DERIVATIVES
MessageInterface::ShowMessage("CartesianState Derivative: "
"[%.12lf %.12lf %.12lf %.12lf %.12lf %.12lf]\n",
currentDerivatives[0][0], currentDerivatives[0][1],
currentDerivatives[0][2], currentDerivatives[0][3],
currentDerivatives[0][4], currentDerivatives[0][5]);
#endif
}
else if (objPtr->GetParameterText(parameterID) == "Bias")
{
for (Integer i = 0; i < size; ++i)
currentDerivatives[0][i] = 1.0;
}
else
{
for (Integer i = 0; i < size; ++i)
currentDerivatives[0][i] = 0.0;
}
}
else if (objNumber == 0) // measurement model
{
#ifdef DEBUG_DERIVATIVES
MessageInterface::ShowMessage(" Deriv is w.r.t. %s of the "
"measurement model\n",
objPtr->GetParameterText(parameterID).c_str());
#endif
if (objPtr->GetParameterText(parameterID) == "Bias")
{
for (Integer i = 0; i < size; ++i)
currentDerivatives[0][i] = 1.0;
}
}
else
{
#ifdef DEBUG_DERIVATIVES
MessageInterface::ShowMessage(" Deriv is w.r.t. %s of a non-"
"Participant\n",
objPtr->GetParameterText(parameterID).c_str());
#endif
for (Integer i = 0; i < size; ++i)
currentDerivatives[0][i] = 0.0;
}
#ifdef DEBUG_DERIVATIVES
MessageInterface::ShowMessage(" Deriv =\n ");
for (Integer i = 0; i < size; ++i)
MessageInterface::ShowMessage(" %.12le",currentDerivatives[0][i]);
MessageInterface::ShowMessage("\n");
#endif
}
return currentDerivatives;
}
//------------------------------------------------------------------------------
// bool Evaluate(bool withEvents)
//------------------------------------------------------------------------------
/**
* Calculates measurement values based on the current state of the participants.
*
* This method can perform the calculations either with or without event
* corrections. When calculating without events, the purpose of the calculation
* is to determine feasibility of the measurement.
*
* @param withEvents Flag used to toggle event inclusion
*
* @return true if the measurement was calculated, false if not
*/
//------------------------------------------------------------------------------
bool USNTwoWayRange::Evaluate(bool withEvents)
{
bool retval = false;
if (!initialized)
InitializeMeasurement();
#ifdef DEBUG_RANGE_CALC
MessageInterface::ShowMessage("Entered USNTwoWayRange::Evaluate()\n");
MessageInterface::ShowMessage(" ParticipantCount: %d\n",
participants.size());
#endif
// Get minimum elevation angle for ground station
Real minAngle;
if (participants[0]->IsOfType(Gmat::GROUND_STATION))
minAngle = ((GroundstationInterface*)participants[0])->GetRealParameter("MinimumElevationAngle");
else if (participants[1]->IsOfType(Gmat::GROUND_STATION))
minAngle = ((GroundstationInterface*)participants[1])->GetRealParameter("MinimumElevationAngle");
if (withEvents == false)
{
#ifdef DEBUG_RANGE_CALC
MessageInterface::ShowMessage("USN 2-Way Range Calculation without "
"events\n");
#endif
#ifdef VIEW_PARTICIPANT_STATES
DumpParticipantStates("++++++++++++++++++++++++++++++++++++++++++++\n"
"Evaluating USN 2-Way Range without events");
#endif
CalculateRangeVectorInertial();
Rvector3 outState;
// Set feasibility off of topocentric horizon, set by the Z value in topo
// coords
std::string updateAll = "All";
UpdateRotationMatrix(currentMeasurement.epoch, updateAll);
// outState = R_o_j2k * rangeVecInertial;
// currentMeasurement.feasibilityValue = outState[2];
outState = (R_o_j2k * rangeVecInertial).GetUnitVector();
currentMeasurement.feasibilityValue = asin(outState[2])*GmatMathConstants::DEG_PER_RAD; // elevation angle in degree
#ifdef CHECK_PARTICIPANT_LOCATIONS
MessageInterface::ShowMessage("Evaluating without events\n");
MessageInterface::ShowMessage("Calculating USN 2-Way Range at epoch "
"%.12lf\n", currentMeasurement.epoch);
MessageInterface::ShowMessage(" J2K Location of %s, id = '%s': %s",
participants[0]->GetName().c_str(),
currentMeasurement.participantIDs[0].c_str(),
p1Loc.ToString().c_str());
MessageInterface::ShowMessage(" J2K Location of %s, id = '%s': %s",
participants[1]->GetName().c_str(),
currentMeasurement.participantIDs[1].c_str(),
p2Loc.ToString().c_str());
Rvector3 bfLoc = R_o_j2k * p1Loc;
MessageInterface::ShowMessage(" BodyFixed Location of %s: %s",
participants[0]->GetName().c_str(),
bfLoc.ToString().c_str());
bfLoc = R_o_j2k * p2Loc;
MessageInterface::ShowMessage(" BodyFixed Location of %s: %s\n",
participants[1]->GetName().c_str(),
bfLoc.ToString().c_str());
#endif
//if (currentMeasurement.feasibilityValue > minAngle)
{
currentMeasurement.isFeasible = true;
currentMeasurement.value[0] = rangeVecInertial.GetMagnitude();
currentMeasurement.eventCount = 2;
SetHardwareDelays(false);
retval = true;
}
//else
//{
// currentMeasurement.isFeasible = false;
// currentMeasurement.value[0] = 0.0;
// currentMeasurement.eventCount = 0;
//}
#ifdef DEBUG_RANGE_CALC
MessageInterface::ShowMessage("Calculating Range at epoch %.12lf\n",
currentMeasurement.epoch);
MessageInterface::ShowMessage(" Location of %s, id = '%s': %s",
participants[0]->GetName().c_str(),
currentMeasurement.participantIDs[0].c_str(),
p1Loc.ToString().c_str());
MessageInterface::ShowMessage(" Location of %s, id = '%s': %s",
participants[1]->GetName().c_str(),
currentMeasurement.participantIDs[1].c_str(),
p2Loc.ToString().c_str());
MessageInterface::ShowMessage(" Range Vector: %s\n",
rangeVecInertial.ToString().c_str());
MessageInterface::ShowMessage(" Elevation angle = %lf degree\n",
currentMeasurement.feasibilityValue);
MessageInterface::ShowMessage(" Feasibility: %s\n",
(currentMeasurement.isFeasible ? "true" : "false"));
MessageInterface::ShowMessage(" Range is %.12lf\n",
currentMeasurement.value[0]);
MessageInterface::ShowMessage(" EventCount is %d\n",
currentMeasurement.eventCount);
#endif
#ifdef SHOW_RANGE_CALC
MessageInterface::ShowMessage("Range at epoch %.12lf is ",
currentMeasurement.epoch);
if (currentMeasurement.isFeasible)
MessageInterface::ShowMessage("feasible, value = %.12lf\n",
currentMeasurement.value[0]);
else
MessageInterface::ShowMessage("not feasible\n");
#endif
}
else
{
// Calculate the corrected range measurement
#ifdef DEBUG_RANGE_CALC_WITH_EVENTS
MessageInterface::ShowMessage("USN 2-Way Range Calculation:\n");
#endif
#ifdef VIEW_PARTICIPANT_STATES_WITH_EVENTS
DumpParticipantStates("********************************************\n"
"Evaluating USN 2-Way Range with located events");
#endif
SpecialCelestialPoint* ssb = solarSystem->GetSpecialPoint("SolarSystemBarycenter");
std::string cbName1 = ((SpacePoint*)participants[0])->GetJ2000BodyName();
CelestialBody* cb1 = solarSystem->GetBody(cbName1);
std::string cbName2 = ((SpacePoint*)participants[1])->GetJ2000BodyName();
CelestialBody* cb2 = solarSystem->GetBody(cbName2);
// 1. Get the range from the down link
Rvector3 r1, r2; // position of downlink leg's participants in central body MJ2000Eq coordinate system
Rvector3 r1B, r2B; // position of downlink leg's participants in solar system bary center MJ2000Eq coordinate system
r1 = downlinkLeg.GetPosition(participants[0]); // position of station at reception time t3R in central body MJ2000Eq coordinate system
r2 = downlinkLeg.GetPosition(participants[1]); // position of spacecraft at transmit time t2T in central body MJ2000Eq coordinate system
t3R = downlinkLeg.GetEventData((GmatBase*) participants[0]).epoch; // reception time at station for downlink leg
t2T = downlinkLeg.GetEventData((GmatBase*) participants[1]).epoch; // transmit time at spacecraft for downlink leg
#ifdef DEBUG_RANGE_CALC_WITH_EVENTS
MessageInterface::ShowMessage("Debug downlinkLeg <'%s',%p>: r1 = (%lf %lf %lf)\n", downlinkLeg.GetName().c_str(), &downlinkLeg, r1[0], r1[1], r1[2]);
MessageInterface::ShowMessage(" r2 = (%lf %lf %lf)\n", r2[0], r2[1], r2[2]);
#endif
Rvector3 ssb2cb_t3R = cb1->GetMJ2000Position(t3R) - ssb->GetMJ2000Position(t3R); // vector from solar system bary center to central body in SSB MJ2000Eq coordinate system at time t3R
Rvector3 ssb2cb_t2T = cb2->GetMJ2000Position(t2T) - ssb->GetMJ2000Position(t2T); // vector from solar system bary center to central body in SSB MJ2000Eq coordinate system at time t2T
r1B = ssb2cb_t3R + r1; // position of station at reception time t3R in SSB coordinate system
r2B = ssb2cb_t2T + r2; // position of spacecraft at transmit time t2T in SSB coordinate system
#ifdef DEBUG_RANGE_CALC_WITH_EVENTS
Rmatrix33 mt = downlinkLeg.GetEventData((GmatBase*) participants[0]).rInertial2obj.Transpose();
MessageInterface::ShowMessage("1. Get downlink leg range:\n");
MessageInterface::ShowMessage(" Station %s position in %sMJ2000 coordinate system : r1 = (%.12lf, %.12lf, %.12lf)km at epoch t3R = %.12lf\n", participants[0]->GetName().c_str(), participants[0]->GetJ2000BodyName().c_str(), r1.Get(0), r1.Get(1), r1.Get(2), t3R);
MessageInterface::ShowMessage(" Spacecraft %s position in %sMJ2000 coordinate system : r2 = (%.12lf, %.12lf, %.12lf)km at epoch t2T = %.12lf\n", participants[1]->GetName().c_str(), participants[1]->GetJ2000BodyName().c_str(), r2.Get(0), r2.Get(1), r2.Get(2), t2T);
MessageInterface::ShowMessage(" Station %s position in SSB coordinate system : r1B = (%.12lf, %.12lf, %.12lf)km at epoch t3R = %.12lf\n", participants[0]->GetName().c_str(), r1B.Get(0), r1B.Get(1), r1B.Get(2), t3R);
MessageInterface::ShowMessage(" Spacecraft %s position in SSB coordinate system : r2B = (%.12lf, %.12lf, %.12lf)km at epoch t2T = %.12lf\n", participants[1]->GetName().c_str(), r2B.Get(0), r2B.Get(1), r2B.Get(2), t2T);
MessageInterface::ShowMessage(" Transformation matrix from Earth fixed coordinate system to EarthFK5 coordinate system at epoch t3R = %.12lf:\n", t3R);
MessageInterface::ShowMessage(" %18.12lf %18.12lf %18.12lf\n", mt(0,0), mt(0,1), mt(0,2));
MessageInterface::ShowMessage(" %18.12lf %18.12lf %18.12lf\n", mt(1,0), mt(1,1), mt(1,2));
MessageInterface::ShowMessage(" %18.12lf %18.12lf %18.12lf\n", mt(2,0), mt(2,1), mt(2,2));
#endif
#ifdef USE_EARTHMJ2000EQ_CS
Rvector3 downlinkVector = r2 - r1;
#else
Rvector3 downlinkVector = r2B - r1B; // rVector = r2 - r1;
#endif
downlinkRange = downlinkVector.GetMagnitude();
// Calculate ET-TAI at t3R:
Real ettaiT3 = downlinkLeg.ETminusTAI(t3R, (GmatBase*)participants[0]);
#ifdef DEBUG_RANGE_CALC_WITH_EVENTS
#ifdef USE_EARTHMJ2000EQ_CS
MessageInterface::ShowMessage(" Downlink range without relativity correction = r2-r1: %.12lf km\n", downlinkRange);
#else
MessageInterface::ShowMessage(" Downlink range without relativity correction = r2B-r1B: %.12lf km\n", downlinkRange);
#endif
MessageInterface::ShowMessage(" Relativity correction for downlink leg = %.12lf km\n", downlinkLeg.GetRelativityCorrection());
MessageInterface::ShowMessage(" Downlink range with relativity correction = %.12lf km\n", downlinkRange + downlinkLeg.GetRelativityCorrection());
MessageInterface::ShowMessage(" (ET-TAI) at t3R = %.12le s\n", ettaiT3);
#endif
// 2. Calculate down link range rate:
Rvector3 p1V = downlinkLeg.GetVelocity(participants[0]); // velocity of station at reception time t3R in central body MJ2000 coordinate system
Rvector3 p2V = downlinkLeg.GetVelocity(participants[1]); // velocity of specraft at transmit time t2T in central body MJ2000 coordinate system
Rvector3 ssb2cbV_t3R = cb1->GetMJ2000Velocity(t3R) - ssb->GetMJ2000Velocity(t3R); // velocity of central body at time t3R w.r.t SSB MJ2000Eq coordinate system
Rvector3 ssb2cbV_t2T = cb2->GetMJ2000Velocity(t2T) - ssb->GetMJ2000Velocity(t2T); // velocity of central body at time t2T w.r.t SSB MJ2000Eq coordinate system
Rvector3 p1VB = ssb2cbV_t3R + p1V; // velocity of station at reception time t3R in SSB coordinate system
Rvector3 p2VB = ssb2cbV_t2T + p2V; // velocity of spacecraft at transmit time t2T in SSB coordinate system
#ifdef DEBUG_RANGE_CALC_WITH_EVENTS
MessageInterface::ShowMessage("2. Get downlink leg range rate:\n");
MessageInterface::ShowMessage(" Station %s velocity in %sMJ2000 coordinate system : p1V = (%.12lf, %.12lf, %.12lf)km/s\n", participants[0]->GetName().c_str(), participants[0]->GetJ2000BodyName().c_str(), p1V.Get(0), p1V.Get(1), p1V.Get(2));
MessageInterface::ShowMessage(" Spacecraft %s velocity in %sMJ2000 coordinate system : p2V = (%.12lf, %.12lf, %.12lf)km/s\n", participants[1]->GetName().c_str(), participants[1]->GetJ2000BodyName().c_str(), p2V.Get(0), p2V.Get(1), p2V.Get(2));
MessageInterface::ShowMessage(" Station %s velocity in SSB coordinate system : p1VB = (%.12lf, %.12lf, %.12lf)km/s\n", participants[0]->GetName().c_str(), p1VB.Get(0), p1VB.Get(1), p1VB.Get(2));
MessageInterface::ShowMessage(" Spacecraft %s velocity in SSB coordinate system : p2VB = (%.12lf, %.12lf, %.12lf)km/s\n", participants[1]->GetName().c_str(), p2VB.Get(0), p2VB.Get(1), p2VB.Get(2));
#endif
// @todo Relative origin velocities need to be subtracted when the origins
// differ; check and fix that part using r12_j2k_vel here. It's not yet
// incorporated because we need to handle the different epochs for the
// bodies, and we ought to do this part in barycentric coordinates
#ifdef USE_EARTHMJ2000EQ_CS
Rvector downRRateVec = p2V - p1V /* - r12_j2k_vel*/;
#else
Rvector downRRateVec = p2VB - p1VB /* - r12_j2k_vel*/;
#endif
Rvector3 rangeUnit = downlinkVector.GetUnitVector();
downlinkRangeRate = downRRateVec * rangeUnit;
#ifdef DEBUG_RANGE_CALC_WITH_EVENTS
MessageInterface::ShowMessage(" Downlink Range Rate: %.12lf km/s\n",
downlinkRangeRate);
#endif
//// 3. Get the transponder delay
//targetDelay = GetDelay(1,0);
//#ifdef DEBUG_RANGE_CALC_WITH_EVENTS
// MessageInterface::ShowMessage(
// " USN Transponder delay for %s = %.12lf s\n",
// participants[1]->GetName().c_str(), targetDelay);
//#endif
// 3. Get the range from the uplink
Rvector3 r3, r4; // position of uplink leg's participants in central body MJ2000Eq coordinate system
Rvector3 r3B, r4B; // position of uplink leg's participants in solar system bary center MJ2000Eq coordinate system
r3 = uplinkLeg.GetPosition(participants[0]); // position of station at transmit time t1T in central body MJ2000Eq coordinate system
r4 = uplinkLeg.GetPosition(participants[1]); // position of spacecraft at reception time t2R in central body MJ2000Eq coordinate system
t1T = uplinkLeg.GetEventData((GmatBase*) participants[0]).epoch; // transmit time at station for uplink leg
t2R = uplinkLeg.GetEventData((GmatBase*) participants[1]).epoch; // reception time at spacecraft for uplink leg
Rvector3 ssb2cb_t2R = cb2->GetMJ2000Position(t2R) - ssb->GetMJ2000Position(t2R); // vector from solar system bary center to central body in SSB MJ2000Eq coordinate system at time t2R
Rvector3 ssb2cb_t1T = cb1->GetMJ2000Position(t1T) - ssb->GetMJ2000Position(t1T); // vector from solar system bary center to central body in SSB MJ2000Eq coordinate system at time t1T
r3B = ssb2cb_t1T + r3; // position of station at transmit time t1T in SSB coordinate system
r4B = ssb2cb_t2R + r4; // position of spacecraft at reception time t2R in SSB coordinate system
#ifdef DEBUG_RANGE_CALC_WITH_EVENTS
Rmatrix33 mt1 = uplinkLeg.GetEventData((GmatBase*) participants[0]).rInertial2obj.Transpose();
MessageInterface::ShowMessage("3. Get uplink leg range:\n");
MessageInterface::ShowMessage(" Spacecraft %s position in %sMJ2000 coordinate system : r4 = (%.12lf, %.12lf, %.12lf)km at epoch t2R = %.12lf\n", participants[1]->GetName().c_str(), participants[1]->GetJ2000BodyName().c_str(), r4.Get(0), r4.Get(1), r4.Get(2), t2R);
MessageInterface::ShowMessage(" Station %s position in %sMJ2000 coordinate system : r3 = (%.12lf, %.12lf, %.12lf)km at epoch t1T = %.12lf\n", participants[0]->GetName().c_str(), participants[0]->GetJ2000BodyName().c_str(), r3.Get(0), r3.Get(1), r3.Get(2), t1T);
MessageInterface::ShowMessage(" Spacecraft %s position in SSB coordinate system : r4B = (%.12lf, %.12lf, %.12lf)km at epoch t2R = %.12lf\n", participants[1]->GetName().c_str(), r4B.Get(0), r4B.Get(1), r4B.Get(2), t2R);
MessageInterface::ShowMessage(" Station %s position in SSB coordinate system : r3B = (%.12lf, %.12lf, %.12lf)km at epoch t1T = %.12lf\n", participants[0]->GetName().c_str(), r3B.Get(0), r3B.Get(1), r3B.Get(2), t1T);
MessageInterface::ShowMessage(" Transformation matrix from Earth fixed coordinate system to EarthFK5 coordinate system at epoch t1T = %.12lf:\n", t1T);
MessageInterface::ShowMessage(" %18.12lf %18.12lf %18.12lf\n", mt1(0,0), mt1(0,1), mt1(0,2));
MessageInterface::ShowMessage(" %18.12lf %18.12lf %18.12lf\n", mt1(1,0), mt1(1,1), mt1(1,2));
MessageInterface::ShowMessage(" %18.12lf %18.12lf %18.12lf\n", mt1(2,0), mt1(2,1), mt1(2,2));
#endif
#ifdef USE_EARTHMJ2000EQ_CS
Rvector3 uplinkVector = r4 - r3;
#else
Rvector3 uplinkVector = r4B - r3B;
#endif
uplinkRange = uplinkVector.GetMagnitude();
// Calculate ET-TAI at t1T:
Real ettaiT1 = downlinkLeg.ETminusTAI(t1T, (GmatBase*)participants[0]);
#ifdef DEBUG_RANGE_CALC_WITH_EVENTS
#ifdef USE_EARTHMJ2000EQ_CS
MessageInterface::ShowMessage(" Uplink range without relativity correction = r4-r3: %.12lf km\n", uplinkRange);
#else
MessageInterface::ShowMessage(" Uplink range without relativity correction = r4B-r3B: %.12lf km\n", uplinkRange);
#endif
MessageInterface::ShowMessage(" Relativity correction for uplink leg = %.12lf km\n", uplinkLeg.GetRelativityCorrection());
MessageInterface::ShowMessage(" Uplink range without relativity correction = %.12lf km\n", uplinkRange + uplinkLeg.GetRelativityCorrection());
MessageInterface::ShowMessage(" (ET-TAI) at t1T = %.12le s\n", ettaiT1);
#endif
// 4. Calculate uplink range rate
Rvector3 p3V = uplinkLeg.GetVelocity(participants[0]);
Rvector3 p4V = uplinkLeg.GetVelocity(participants[1]);
Rvector3 ssb2cbV_t2R = cb2->GetMJ2000Velocity(t2R) - ssb->GetMJ2000Velocity(t2R); // velocity of central body at time t2R w.r.t SSB MJ2000Eq coordinate system
Rvector3 ssb2cbV_t1T = cb1->GetMJ2000Velocity(t1T) - ssb->GetMJ2000Velocity(t1T); // velocity of central body at time t1T w.r.t SSB MJ2000Eq coordinate system
Rvector3 p3VB = ssb2cbV_t1T + p3V; // velocity of station at reception time t1T in SSB coordinate system
Rvector3 p4VB = ssb2cbV_t2R + p4V; // velocity of spacecraft at transmit time t2R in SSB coordinate system
// @todo Relative origin velocities need to be subtracted when the origins
// differ; check and fix that part using r12_j2k_vel here. It's not yet
// incorporated because we need to handle the different epochs for the
// bodies, and we ought to do this part in barycentric coordinates
#ifdef USE_EARTHMJ2000EQ_CS
Rvector upRRateVec = p4V - p3V /* - r12_j2k_vel*/ ;
#else
Rvector upRRateVec = p4VB - p3VB /* - r12_j2k_vel*/ ;
#endif
rangeUnit = uplinkVector.GetUnitVector();
uplinkRangeRate = upRRateVec * rangeUnit;
// 4.1. Target range rate: Do we need this as well?
targetRangeRate = (downlinkRangeRate + uplinkRangeRate) / 2.0;
#ifdef DEBUG_RANGE_CALC_WITH_EVENTS
MessageInterface::ShowMessage("4. Get uplink leg range rate:\n");
MessageInterface::ShowMessage(" Station %s velocity in %sMJ2000 coordinate system : p3V = (%.12lf, %.12lf, %.12lf)km/s\n", participants[0]->GetName().c_str(), participants[0]->GetJ2000BodyName().c_str(), p3V.Get(0), p3V.Get(1), p3V.Get(2));
MessageInterface::ShowMessage(" Spacecraft %s velocity in %sMJ2000 coordinate system : p4V = (%.12lf, %.12lf, %.12lf)km/s\n", participants[1]->GetName().c_str(), participants[1]->GetJ2000BodyName().c_str(), p4V.Get(0), p4V.Get(1), p4V.Get(2));
MessageInterface::ShowMessage(" Station %s velocity in SSB coordinate system : p3VB = (%.12lf, %.12lf, %.12lf)km/s\n", participants[0]->GetName().c_str(), p3VB.Get(0), p3VB.Get(1), p3VB.Get(2));
MessageInterface::ShowMessage(" Spacecraft %s velocity in SSB coordinate system : p4VB = (%.12lf, %.12lf, %.12lf)km/s\n", participants[1]->GetName().c_str(), p4VB.Get(0), p4VB.Get(1), p4VB.Get(2));
MessageInterface::ShowMessage(" Uplink Range Rate: %.12lf km/s\n", uplinkRangeRate);
MessageInterface::ShowMessage(" Target Range Rate: %.12lf km/s\n", targetRangeRate);
MessageInterface::ShowMessage(" Delay between transmiting signal and receiving signal at transponder: t2T - t2R = %.12le s\n", (t2T-t2R)*86400);
#endif
// 5. Calculate ET-TAI correction
Real ettaiCorrection = (useETminusTAICorrection?(ettaiT1 - ettaiT3):0.0);
RealArray uplinkCorrection, downlinkCorrection;
Real uplinkRangeCorrection, downlinkRangeCorrection, realRange;
uplinkRangeCorrection = downlinkRangeCorrection = 0.0;
for (int i= 0; i < 3; ++i)
{
uplinkCorrection.push_back(0.0);
downlinkCorrection.push_back(0.0);
}
// 6. Get sensors used in USN 2-ways range
ObjectArray objList1;
ObjectArray objList2;
ObjectArray objList3;
// objList1 := all transmitters in participantHardware list
// objList2 := all receivers in participantHardware list
// objList3 := all transponders in participantHardware list
UpdateHardware();
if (!(participantHardware.empty()||
((!participantHardware.empty())&&
participantHardware[0].empty()&&
participantHardware[1].empty()
)
)
)
{
for(std::vector<Hardware*>::iterator hw = participantHardware[0].begin();
hw != this->participantHardware[0].end(); ++hw)
{
if ((*hw) != NULL)
{
if ((*hw)->GetTypeName() == "Transmitter")
objList1.push_back(*hw);
if ((*hw)->GetTypeName() == "Receiver")
objList2.push_back(*hw);
}
else
MessageInterface::ShowMessage(" sensor = NULL\n");
}
for(std::vector<Hardware*>::iterator hw = participantHardware[1].begin();
hw != this->participantHardware[1].end(); ++hw)
{
if ((*hw) != NULL)
{
if ((*hw)->GetTypeName() == "Transponder")
objList3.push_back(*hw);
}
else
MessageInterface::ShowMessage(" sensor = NULL\n");
}
if (objList1.size() != 1)
throw MeasurementException(((objList1.size() == 0)?"Error: The first participant does not have a transmitter to send signal.\n":"Error: The first participant has more than one transmitter.\n"));
if (objList2.size() != 1)
throw MeasurementException(((objList2.size() == 0)?"Error: The first participant does not have a receiver to receive signal.\n":"Error: The first participant has more than one receiver.\n"));
if (objList3.size() != 1)
throw MeasurementException((objList3.size() == 0)?"Error: The second participant does not have a transponder to transpond signal.\n":"Error: The second participant has more than one transponder.\n");
Transmitter* gsTransmitter = (Transmitter*)objList1[0];
Receiver* gsReceiver = (Receiver*)objList2[0];
Transponder* scTransponder = (Transponder*)objList3[0];
if (gsTransmitter == NULL)
throw MeasurementException("Transmitter is NULL object.\n");
if (gsReceiver == NULL)
throw MeasurementException("Receiver is NULL object.\n");
if (scTransponder == NULL)
throw MeasurementException("Transponder is NULL object.\n");
#ifdef DEBUG_RANGE_CALC_WITH_EVENTS
MessageInterface::ShowMessage("5. Sensors, delays, and signals:\n");
MessageInterface::ShowMessage(" List of sensors: %s, %s, %s\n",
gsTransmitter->GetName().c_str(), gsReceiver->GetName().c_str(),
scTransponder->GetName().c_str());
#endif
// 7. Get transponder delays: (Note that: USN 2-way range only needs transponder delay for calculation)
targetDelay = scTransponder->GetDelay();
#ifdef DEBUG_RANGE_CALC_WITH_EVENTS
MessageInterface::ShowMessage(" Transponder delay = %le s\n", scTransponder->GetDelay());
#endif
// 8. Get frequency from transmitter of ground station (participants[0])
Real uplinkFreq; // unit: MHz
Real uplinkFreqAtRecei; // unit: MHz // uplink frequency at receive epoch
if (obsData == NULL)
{
if (rampTB == NULL)
{
// Get uplink frequency from GMAT script when ramp table is not used
Signal* uplinkSignal = gsTransmitter->GetSignal();
uplinkFreq = uplinkSignal->GetValue(); // unit: MHz
uplinkFreqAtRecei = uplinkFreq; // unit: MHz // for constant frequency
frequency = uplinkFreq*1.0e6; // unit: Hz
// Get uplink band based on definition of frequency range
freqBand = FrequencyBand(frequency);
// Range modulo constant is specified by GMAT script
#ifdef DEBUG_RANGE_CALC_WITH_EVENTS
MessageInterface::ShowMessage(" Uplink frequency is gotten from GMAT script...\n");
#endif
}
else
{
// Get uplink frequency at a given time from ramped frequency table
frequency = GetFrequencyFromRampTable(t1T); // unit: Hz // Get frequency at transmit time t1T
uplinkFreq = frequency/1.0e6; // unit MHz
uplinkFreqAtRecei = GetFrequencyFromRampTable(t3R) / 1.0e6; // unit MHz // for ramped frequency
// Get frequency band from ramp table at given time
freqBand = GetUplinkBandFromRampTable(t1T);
// Range modulo constant is specified by GMAT script
#ifdef DEBUG_RANGE_CALC_WITH_EVENTS
MessageInterface::ShowMessage(" Uplink frequency is gotten from ramp table...: frequency = %.12le\n", frequency);
#endif
}
}
else
{
if (rampTB == NULL)
{
//// Get uplink frequency at a given time from observation data
//frequency = obsData->uplinkFreq; // unit: Hz
// Get uplink frequency from GMAT script when ramp table is not used
Signal* uplinkSignal = gsTransmitter->GetSignal();
uplinkFreq = uplinkSignal->GetValue(); // unit: MHz
uplinkFreqAtRecei = uplinkFreq; // unit: MHz // for constant frequency
frequency = uplinkFreq*1.0e6; // unit: Hz
// Get uplink band based on definition of frequency range
freqBand = FrequencyBand(frequency);
// Range modulo constant is specified by GMAT script
#ifdef DEBUG_RANGE_CALC_WITH_EVENTS
MessageInterface::ShowMessage(" Uplink frequency is gotten from observation data...: frequency = %.12le\n", frequency);
#endif
}
else
{
//// Get uplink frequency at a given time from ramped frequency table
//frequency = GetFrequencyFromRampTable(t1T); // unit: Hz // Get frequency at transmit time t1T
// Get uplink frequency at a given time from ramped frequency table
frequency = GetFrequencyFromRampTable(t1T); // unit: Hz // Get frequency at transmit time t1T
uplinkFreq = frequency / 1.0e6; // unit MHz
uplinkFreqAtRecei = GetFrequencyFromRampTable(t3R) / 1.0e6; // unit MHz // for ramped frequency
// Get frequency band from ramp table at given time
freqBand = GetUplinkBandFromRampTable(t1T);
// Range modulo constant is specified by GMAT script
#ifdef DEBUG_RANGE_CALC_WITH_EVENTS
MessageInterface::ShowMessage(" Uplink frequency is gotten from ramp table...: frequency = %.12le\n", frequency);
#endif
}
//uplinkFreq = frequency/1.0e6; // unit: MHz
//freqBand = obsData->uplinkBand;
obsValue = obsData->value; // unit: range unit
#ifdef DEBUG_RANGE_CALC_WITH_EVENTS
MessageInterface::ShowMessage(" Uplink band, range modulo constant, and observation value are gotten from observation data...\n");
#endif
}
// 9. Calculate media correction for uplink leg:
#ifdef DEBUG_RANGE_CALC_WITH_EVENTS
MessageInterface::ShowMessage("6. Media correction for uplink leg\n");
MessageInterface::ShowMessage(" UpLink signal frequency = %.12lf MHz\n", uplinkFreq);
#endif
// In uplink leg, r3B and r4B are location of station and spacecraft in SSBMJ2000Eq coordinate system
uplinkCorrection = CalculateMediaCorrection(uplinkFreq, r3B, r4B, t1T, t2R, minAngle);
uplinkRangeCorrection = uplinkCorrection[0]*GmatMathConstants::M_TO_KM + uplinkLeg.GetRelativityCorrection();
Real uplinkRealRange = uplinkRange + uplinkRangeCorrection;
#ifdef DEBUG_RANGE_CALC_WITH_EVENTS
MessageInterface::ShowMessage(" Uplink media correction = %.12lf m\n",uplinkCorrection[0]);
MessageInterface::ShowMessage(" Uplink relativity correction = %.12lf km\n",uplinkLeg.GetRelativityCorrection());
MessageInterface::ShowMessage(" Uplink total range correction = %.12lf km\n",uplinkRangeCorrection);
MessageInterface::ShowMessage(" Uplink precision light time range = %.12lf km\n",uplinkRange);
MessageInterface::ShowMessage(" Uplink real range = %.12lf km\n",uplinkRealRange);
#endif
// 10. Doppler shift the frequency from the transmitter using uplinkRangeRate:
Real uplinkDSFreq = (1 - uplinkRangeRate*GmatMathConstants::KM_TO_M/GmatPhysicalConstants::SPEED_OF_LIGHT_VACUUM)*uplinkFreq;
#ifdef DEBUG_RANGE_CALC_WITH_EVENTS
MessageInterface::ShowMessage("7. Transponder input and output frequencies\n");
MessageInterface::ShowMessage(" Uplink Doppler shift frequency = %.12lf MHz\n", uplinkDSFreq);
#endif
// 11.Set frequency for the input signal of transponder
Signal* inputSignal = scTransponder->GetSignal(0);
inputSignal->SetValue(uplinkDSFreq);
scTransponder->SetSignal(inputSignal, 0);
// 12. Check the transponder feasibility to receive the input signal:
if (scTransponder->IsFeasible(0) == false)
{
currentMeasurement.isFeasible = false;
currentMeasurement.value[0] = 0;
throw MeasurementException("The transponder is unfeasible to receive uplink signal.\n");
}
// 13. Get frequency of transponder output signal
Signal* outputSignal = scTransponder->GetSignal(1);
Real downlinkFreq = outputSignal->GetValue();
#ifdef DEBUG_RANGE_CALC_WITH_EVENTS
MessageInterface::ShowMessage(" Downlink frequency = %.12lf Mhz\n", downlinkFreq);
#endif
// 14. Doppler shift the transponder output frequency:
Real downlinkDSFreq = (1 - downlinkRangeRate*GmatMathConstants::KM_TO_M/GmatPhysicalConstants::SPEED_OF_LIGHT_VACUUM)*downlinkFreq;
#ifdef DEBUG_RANGE_CALC_WITH_EVENTS
MessageInterface::ShowMessage(" Downlink Doppler shift frequency = %.12lf MHz\n", downlinkDSFreq);
#endif
// 15. Set frequency on receiver
Signal* downlinkSignal = gsReceiver->GetSignal();
downlinkSignal->SetValue(downlinkDSFreq);
// 16. Check the receiver feasibility to receive the downlink signal
if (gsReceiver->IsFeasible() == false)
{
currentMeasurement.isFeasible = false;
currentMeasurement.value[0] = 0;
throw MeasurementException("The receiver is unfeasible to receive downlink signal.\n");
}
// 17. Calculate media correction for downlink leg:
#ifdef DEBUG_RANGE_CALC_WITH_EVENTS
MessageInterface::ShowMessage("8. Media correction for downlink leg\n");
#endif
// In down link leg, r1B and r2B are location of station and spacecraft in SSBMJ2000Eq coordinate system
downlinkCorrection = CalculateMediaCorrection(downlinkDSFreq, r1B, r2B, t3R, t2T, minAngle);
downlinkRangeCorrection = downlinkCorrection[0]*GmatMathConstants::M_TO_KM + downlinkLeg.GetRelativityCorrection();
Real downlinkRealRange = downlinkRange + downlinkRangeCorrection;
#ifdef DEBUG_RANGE_CALC_WITH_EVENTS
MessageInterface::ShowMessage(" Downlink media correction = %.12lf m\n",downlinkCorrection[0]);
MessageInterface::ShowMessage(" Downlink relativity correction = %.12lf km\n",downlinkLeg.GetRelativityCorrection());
MessageInterface::ShowMessage(" Downlink total range correction = %.12lf km\n",downlinkRangeCorrection);
MessageInterface::ShowMessage(" Downlink precision light time range = %.12lf km\n",downlinkRange);
MessageInterface::ShowMessage(" Downlink real range = %.12lf km\n",downlinkRealRange);
#endif
// 18. Calculate real range
realRange = uplinkRealRange + downlinkRealRange +
(targetDelay + ettaiCorrection)*GmatPhysicalConstants::SPEED_OF_LIGHT_VACUUM / GmatMathConstants::KM_TO_M;
currentMeasurement.uplinkFreq = uplinkFreq * 1.0e6;
currentMeasurement.uplinkFreq = uplinkFreqAtRecei * 1.0e6;
}
else
{
#ifdef IONOSPHERE
if ((troposphere != NULL)||(ionosphere != NULL))
#else
if (troposphere != NULL)
#endif
throw MeasurementException("Error: missing transmiter, transponder, or receiver in order to compute media correction\n");
// No hardware useage in this case. It will have no media correction and hardware delay
// light time correction, relativity correction, and ET-TAI correction is still added
realRange = uplinkRange + downlinkRange + ettaiCorrection*GmatPhysicalConstants::SPEED_OF_LIGHT_VACUUM / GmatMathConstants::KM_TO_M;
}
//19. Verify uplink leg light path not to be blocked by station's central body
UpdateRotationMatrix(t1T, "o_j2k");
Rvector3 outState = (R_o_j2k * (r4B - r3B)).GetUnitVector();
currentMeasurement.feasibilityValue = asin(outState[2])*GmatMathConstants::DEG_PER_RAD; // elevation angle in degree
#ifdef DEBUG_RANGE_CALC_WITH_EVENTS
MessageInterface::ShowMessage("Uplink elevation angle = %.8lf minAngle = %.8lf\n", currentMeasurement.feasibilityValue, minAngle);
#endif
if (currentMeasurement.feasibilityValue > minAngle)
{
UpdateRotationMatrix(t3R, "o_j2k");
outState = (R_o_j2k * (r2B - r1B)).GetUnitVector();
Real feasibilityValue = asin(outState[2])*GmatMathConstants::DEG_PER_RAD; // elevation angle in degree
#ifdef DEBUG_RANGE_CALC_WITH_EVENTS
MessageInterface::ShowMessage("Downlink elevation angle = %.8lf\n", currentMeasurement.feasibilityValue);
#endif
if (feasibilityValue > minAngle)
{
currentMeasurement.unfeasibleReason = "N";
currentMeasurement.isFeasible = true;
}
else
{
currentMeasurement.feasibilityValue = feasibilityValue;
currentMeasurement.unfeasibleReason = "B2";
currentMeasurement.isFeasible = false;
}
}
else
{
currentMeasurement.unfeasibleReason = "B1";
currentMeasurement.isFeasible = false;
}
#ifdef DEBUG_RANGE_CALC_WITH_EVENTS
MessageInterface::ShowMessage("5. Calculated half range:\n");
MessageInterface::ShowMessage(" Media correction = %.12lf km\n", (uplinkCorrection[0] + downlinkCorrection[0])/2);
MessageInterface::ShowMessage(" Relativity correction = %.12lf km\n", (uplinkLeg.GetRelativityCorrection() + downlinkLeg.GetRelativityCorrection())/2);
MessageInterface::ShowMessage(" Total range correction = %.12lf km\n", (uplinkRangeCorrection + downlinkRangeCorrection)/2);
MessageInterface::ShowMessage(" Downlink precision light time range = %.12lf km\n", (uplinkRange + downlinkRange)/2);
MessageInterface::ShowMessage(" ET-TAI correction = %.12le km\n", (ettaiCorrection/2)*GmatPhysicalConstants::SPEED_OF_LIGHT_VACUUM / GmatMathConstants::KM_TO_M);
MessageInterface::ShowMessage(" transponder delay correction = %.12le km\n", (targetDelay/2)*GmatPhysicalConstants::SPEED_OF_LIGHT_VACUUM / GmatMathConstants::KM_TO_M);
MessageInterface::ShowMessage(" Calculated real range = %.12lf km\n", realRange/2);
#endif
// 20. Set value for currentMeasurement
currentMeasurement.value[0] = realRange / 2.0;
#ifdef PRELIMINARY_DERIVATIVE_CHECK
MessageInterface::ShowMessage("Participants:\n ");
for (UnsignedInt i = 0; i < participants.size(); ++i)
MessageInterface::ShowMessage(" %d: %s of type %s\n", i,
participants[i]->GetName().c_str(),
participants[i]->GetTypeName().c_str());
Integer id = participants[1]->GetType() * 250 +
participants[1]->GetParameterID("CartesianX");
CalculateMeasurementDerivatives(participants[1], id);
#endif
// 21. Add noise to current measurement if it is needed
if (noiseSigma != NULL)
{
RandomNumber* rn = RandomNumber::Instance();
Real val = rn->Gaussian(currentMeasurement.value[0], noiseSigma->GetElement(0));
while (val <= 0.0)
val = rn->Gaussian(currentMeasurement.value[0], noiseSigma->GetElement(0));
currentMeasurement.value[0] = val;
}
retval = true;
}
return retval;
}
|
#ifndef __GUICON_H__
#define __GUICON_H__
#include <iostream>
#include <fstream>
#include <conio.h>
#include <stdio.h>
void redirectIO(char *filename);
void toConsole();
void closeRedirectIO();
void setPath();
#endif
|
// This file has been generated by Py++.
#ifndef PropertyDefinitionSizef_hpp__pyplusplus_wrapper
#define PropertyDefinitionSizef_hpp__pyplusplus_wrapper
void register_PropertyDefinitionSizef_class();
#endif//PropertyDefinitionSizef_hpp__pyplusplus_wrapper
|
// Copyright Steinwurf ApS 2011-2013.
// Distributed under the "STEINWURF RESEARCH LICENSE 1.0".
// See accompanying file LICENSE.rst or
// http://www.steinwurf.com/licensing
#pragma once
#include <cstdint>
#include <cassert>
#include <kodoc/kodoc.h>
#include "field.hpp"
#include "codec.hpp"
#include "factory.hpp"
#include "decoder.hpp"
namespace kodocpp
{
class decoder_factory : public factory
{
public:
using coder_type = decoder;
public:
/// Constructs a new decoder factory (for shallow storage decoders)
/// @param codec This parameter determines the decoding algorithms used.
/// @param field The finite field that should be used by the
/// decoder.
/// @param max_symbols The maximum number of symbols supported by
/// decoders built with this factory.
/// @param max_symbol_size The maximum symbol size in bytes supported
/// by decoders built using the returned factory
decoder_factory(codec codec, field field,
uint32_t max_symbols, uint32_t max_symbol_size) :
factory(kodoc_new_decoder_factory(
(int32_t)codec, (int32_t)field, max_symbols, max_symbol_size),
[](kodoc_factory_t factory) { kodoc_delete_factory(factory); })
{ }
/// Builds a new decoder with the factory using the specified parameters
/// @return The new decoder
coder_type build()
{
kodoc_coder_t coder = kodoc_factory_build_coder(m_factory.get());
return coder_type(coder);
}
};
}
|
#include "CollisionAvoidanceScene.h"
using namespace std;
CollisionAvoidanceScene::CollisionAvoidanceScene() {
Agent *agent = new Agent;
agent->setPosition(Vector2D(640, 360));
agent->setTarget(Vector2D(640, 360));
agent->loadSpriteTexture("../res/soldier.png", 4);
agents.push_back(agent);
target = Vector2D(640, 360);
text = new Image(Vector2D(TheApp::Instance()->getWinSize().x / 2, 100));
text->LoadImage("../res/Text/collisionAvoidance.png");
}
CollisionAvoidanceScene::~CollisionAvoidanceScene() {
for (int i = 0; i < (int)agents.size(); i++)
{
delete agents[i];
}
delete text;
}
void CollisionAvoidanceScene::update(float dtime, SDL_Event *event) {
// Keyboard & Mouse events
switch (event->type) {
case SDL_MOUSEMOTION:
case SDL_MOUSEBUTTONDOWN:
if (event->button.button == SDL_BUTTON_LEFT)
{
path.push_back(Vector2D((float)(event->button.x), (float)(event->button.y)));
}
break;
default:
break;
}
Vector2D steering_force = agents[0]->Behavior()->AdvancedPathFollowing(agents[0], agents[0]->getTarget(), dtime, &path);
agents[0]->update(steering_force, dtime, event);
}
void CollisionAvoidanceScene::draw() {
Line line;
line.setOrigin(agents[0]->getPosition());
for (int i = 0; i < path.size(); i++) {
line.setDestiny(path[i]);
line.drawLine();
draw_circle(TheApp::Instance()->getRenderer(), (int)path[i].x, (int)path[i].y, 10, 255, 0, 0, 255);
line.setOrigin(path[i]);
}
agents[0]->draw();
text->Draw();
}
const char* CollisionAvoidanceScene::getTitle() {
return "SDL Steering Behaviors :: Collision Avoidance Finding Demo";
}
|
#ifndef RENDERCONTEXT_H_
#define RENDERCONTEXT_H_
#include "SDL.h"
#include "Color.h"
#include "geo/Rectangle.h"
#include <memory>
#include "renderer/TextureUnit.h"
#include "renderer/ClearState.h"
#include "renderer/VertexArray.h"
#include "renderer/GraphicsDevice.h"
#include "renderer/Framebuffer.h"
#include "PrimitiveType.h"
#include "Device.h"
#include "Types.h"
namespace revel
{
namespace geo { class Mesh; }
namespace renderer
{
class Framebuffer;
//class RenderWindow;
class DrawState;
class SceneState;
class RenderContext
{
protected:
geo::Rect_f32 m_Viewport;
//Color4<f32> m_ClearColor;
std::shared_ptr<Framebuffer> m_pFramebuffer;
std::shared_ptr<ClearState> m_pClearState;
std::vector<std::unique_ptr<TextureUnit>> m_TextureUnits;
public:
RenderContext() {}
virtual ~RenderContext() {}
virtual void make_current() = 0;
geo::Rect_f32 viewport() { return m_Viewport; }
void set_viewport(const geo::Rect_f32& viewport) { m_Viewport = viewport; }
virtual std::shared_ptr<VertexArray> create_vertex_array() = 0;
virtual std::shared_ptr<VertexArray> create_vertex_array(const std::shared_ptr<geo::Mesh>& pMesh);
virtual std::shared_ptr<Framebuffer> create_framebuffer() = 0;
/*
virtual const std::shared_ptr<Framebuffer>& get_framebuffer() = 0;
virtual void set_framebuffer(const std::shared_ptr<Framebuffer>& fb) = 0;
*/
const std::unique_ptr<TextureUnit>& texture_unit(u32 i = 0) { return m_TextureUnits.at(i); }
virtual void clear(const std::shared_ptr<ClearState>& cs) = 0;
virtual void clear(const ClearState& cs) = 0;
virtual void draw(PrimitiveType type, const std::shared_ptr<DrawState>& drawstate, const std::shared_ptr<SceneState>& scenestate) = 0;
virtual void draw(const std::shared_ptr<geo::Mesh>& mesh) = 0;
virtual void draw(const std::shared_ptr<VertexBuffer>& vbo) = 0;
};
} // ::revel::renderer
} // ::revel
#endif // RENDERCONTEXT_H_
|
// This file is subject to the terms and conditions defined in 'LICENSE' in the source code package
#ifndef JACTORIO_INCLUDE_RENDER_OPENGL_MVP_MANAGER_H
#define JACTORIO_INCLUDE_RENDER_OPENGL_MVP_MANAGER_H
#pragma once
#include <glm/glm.hpp>
#include "jactorio.h"
namespace jactorio::render
{
class MvpManager
{
public:
/// Uniform location for "u_model_view_projection_matrix"
/// Must be set before MVP can be updated
void SetMvpUniformLocation(int location);
/// Sends current mvp matrices to GPU
void UpdateShaderMvp();
/// Returns mvp matrix if calculated, otherwise invalid call
J_NODISCARD const glm::mat4& GetMvpMatrix() const;
/// Calculates mvp matrix if not already calculated
J_NODISCARD const glm::mat4& CalculateGetMvpMatrix();
/// Calculates MVP matrix if calculate_matrix is true
void CalculateMvpMatrix();
void GlSetModelMatrix(const glm::mat4& matrix);
void GlSetViewMatrix(const glm::mat4& matrix);
void GlSetProjectionMatrix(const glm::mat4& matrix);
/// Modifying the returned pointer will change the location of the camera
glm::vec3* GetViewTransform() noexcept {
return &cameraTransform_;
}
/// Sets the current view transform
void UpdateViewTransform();
/// Converts provided parameters into a matrix, guarantees a zoom of minimum of offset on all axis
/// May offset more in a certain axis to preserve aspect ratio
/// \param window_width width of display area in pixels
/// \param window_height Height of display area in pixels
/// \param pixel_zoom Number of pixels to hide starting from the border,
/// will zoom more if necessary on an axis to maintain aspect ratio
/// Cannot be 0
///
/// Cannot be 0 as a each pixel would then have width of < 1 (e.g 0.99), which is invalid
/// (OpenGL does not render)
static glm::mat4 ToProjMatrix(unsigned window_width, unsigned window_height, float pixel_zoom);
private:
int mvpUniformLocation_ = -1;
/// If true, the matrix will be calculated and stored upon calling update_shader_mvp() or get_matrix()
bool calculateMatrix_ = false;
glm::mat4 model_{};
glm::mat4 view_{};
glm::mat4 projection_{};
glm::mat4 mvpMatrix_{};
bool debugHasModel_ = false;
bool debugHasView_ = false;
bool debugHasProjection_ = false;
glm::vec3 cameraTransform_ = glm::vec3(0, 0, 0);
};
} // namespace jactorio::render
#endif // JACTORIO_INCLUDE_RENDER_OPENGL_MVP_MANAGER_H
|
#include "stdafx.h"
#include "DcmVR.h"
MAP_VRPROPERTY CDcmVR::m_VrProperty;
bool CDcmVR::m_bInit = CDcmVR::Init();
CDcmVR::CDcmVR(void)
{
}
CDcmVR::~CDcmVR(void)
{
}
bool CDcmVR::Init()
{
Insert(VR_00,"私有Tag", 0, 4, 1,10,0,4,2,"VR_00");
Insert(VR_SQ,"Sequence of Items", 0, 4, 1,12,0,4,4,"VR_SQ");
Insert(VR_OB,"Other Byte String", 0, 259, 1,12,1,4,4,"VR_OB");
Insert(VR_OW,"Other Word String", 0, 259, 2,12,1,4,4,"VR_OW");
Insert(VR_UN,"Unknown", 0, 259, 1,12,1,4,4,"VR_UN");
Insert(VR_UT,"Unlimited Text", 4294967294, 1025, 1,12,1,4,4,"VR_UT");
Insert(VR_OF,"Other Float String", 4294967292, 257, 4,12,1,4,4,"VR_OF");
Insert(VR_AE,"Application Entity", 16, 513, 1,8,2,2,2,"VR_AE");
Insert(VR_AS,"Age String", 4, 512, 1,8,2,2,2,"VR_AS");
Insert(VR_AT,"Attribute Tag", 4, 256, 4,8,2,2,2,"VR_AT");
Insert(VR_CS,"Code String", 16, 513, 1,8,2,2,2,"VR_CS");
Insert(VR_DA,"Date", 8, 512, 1,8,2,2,2,"VR_DA");
Insert(VR_DS,"Decimal String", 16, 513, 1,8,2,2,2,"VR_DS");
Insert(VR_DT,"Date Time", 26, 513, 1,8,2,2,2,"VR_DT");
Insert(VR_FD,"Floating Point Double", 8, 256, 8,8,2,2,2,"VR_FD");
Insert(VR_FL,"Floating Point Single", 4, 256, 4,8,2,2,2,"VR_FL");
Insert(VR_IS,"Integer String", 12, 513, 1,8,2,2,2,"VR_IS");
Insert(VR_LO,"Long String", 64, 513, 1,8,2,2,2,"VR_LO");
Insert(VR_LT,"Long Text", 10240, 1025, 1,8,2,2,2,"VR_LT");
Insert(VR_PN,"Person Name", 64, 514, 1,8,2,2,2,"VR_PN");
Insert(VR_SH,"Short String", 16, 513, 1,8,2,2,2,"VR_SH");
Insert(VR_SL,"Signed Long", 4, 256, 4,8,2,2,2,"VR_SL");
Insert(VR_SS,"Signed Short", 2, 256, 2,8,2,2,2,"VR_SS");
Insert(VR_ST,"Short Text", 1024, 1025, 1,8,2,2,2,"VR_ST");
Insert(VR_TM,"Time", 16, 513, 1,8,2,2,2,"VR_TM");
Insert(VR_UI,"Unique Identifier", 64, 513, 1,8,2,2,2,"VR_UI");
Insert(VR_UL,"Unsigned Long", 4, 256, 4,8,2,2,2,"VR_UL");
Insert(VR_US,"Unsigned Short", 2, 256, 2,8,2,2,2,"VR_US");
return true;
}
pDcmVR CDcmVR::Find(unsigned long nVrCode)
{
return &(m_VrProperty[nVrCode]);
}
pDcmVR CDcmVR::Insert(int nCode,char *pszName,int nValueLength,int nRestrict,int nUnitSize,int nOffset,int nVrType,unsigned long nLenOfLenDes,unsigned long nLenOfVrDes,char* pShortName)
{
m_VrProperty[nCode].nCode = nCode;
m_VrProperty[nCode].nValueLeng = nValueLength;
m_VrProperty[nCode].nOffset = nOffset;//这里的offset不是绝对的.还有个重要因素:该Tag是否含有VR域
m_VrProperty[nCode].nRestrict = nRestrict;
m_VrProperty[nCode].nUnitSize = nUnitSize;
m_VrProperty[nCode].nLenOfVrDes = nLenOfVrDes;
m_VrProperty[nCode].nVrType = nVrType;
strcpy_s(m_VrProperty[nCode].pszName,256,pszName);
strcpy_s(m_VrProperty[nCode].pszShortName,10,pShortName);
m_VrProperty[nCode].nLenOfLenDes = nLenOfLenDes;
return &(m_VrProperty[nCode]);
}
|
#include <iostream>
#include "../../CACLFloat/CACLFloat.hpp"
int main(int argc, char **argv) {
cacl::CACLFloat test, test1, test2;
std::cin >> test1 >> test2;
test = test1 / test2;
std::cout << test;
return 0;
}
|
#include <jni.h>
#include <string>
#ifndef LEMONWALLETC_STRCONV_H
#define LEMONWALLETC_STRCONV_H
using namespace std;
jstring CStr2Jstring(JNIEnv* env, const char* pat);
const char* Jstring2CStr(JNIEnv* env, jstring jstr);
jbyteArray CBytes2JByteArray(JNIEnv* env, const char* bytes, size_t size);
#endif //LEMONWALLETC_STRCONV_H
|
#include <string>
#include <vector>
using namespace std;
vector<int> solution(vector<int> lottos, vector<int> win_nums) {
vector<int> answer;
int count = 0;
int zero_count = 0;
for (auto lotto : lottos)
{
if (lotto == 0)
{
zero_count++;
continue;
}
for (auto win : win_nums)
if (lotto == win)
count++;
}
answer.push_back(7 - max(count + zero_count, 1));
answer.push_back(7 - max(count, 1));
return answer;
}
|
/*
* Time.h - Library for maintaining discrete date and time representation for PrNet nodes.
* Created by Dwyane George, November 16, 2015
* Social Computing Group, MIT Media Lab
*/
#ifndef PrTime_h
#define PrTime_h
#include "Arduino.h"
// Time structure
struct t {
int month;
int date;
int year;
int day;
int hours;
int minutes;
int seconds;
};
class Time
{
public:
struct t initialTime;
struct t t;
volatile unsigned long secondsElapsed;
bool isTimeSet;
Time();
void setInitialTime(int month, int date, int year, int day, int hours, int minutes, int seconds);
void updateTime();
bool timeout(unsigned long *counter, int milliseconds);
bool inDataCollectionPeriod(int startHour, int startMinute, int endHour, int endMinute);
bool afterSchool(int endHour, int endMinute);
void displayDateTime();
void NextSecond();
};
#endif
|
/*
* non_oop.cpp
*
* Created on: Sep 4, 2015
* Author: ferrazlealrm@ornl.gov
*
* Non OOP example of URL:
* scheme:[//domain[:port]][/]path
*/
#include <iostream>
#include <string>
std::string domain = "ornl.gov";
std::string http_port = "80";
std::string https_port = "443";
std::string ftp_port = "20";
std::string build_url(const std::string &scheme,
const std::string &domain,
const std::string &port) {
return scheme + "://" + domain + ":" + port;
}
int main_non_oop(int argc, char* argv[]) {
if (argc != 2) {
std::cerr << "Use " + std::string(argv[0]) + " [http, https, ftp]"<<std::endl;
exit(-1);
}
std::string scheme = argv[1];
if (scheme == "http"){
std::cout << build_url(scheme,domain,http_port) <<std::endl;
}
else if (scheme == "https"){
std::cout << build_url(scheme,domain,https_port) <<std::endl;
}
else if (scheme == "ftp"){
std::cout << build_url(scheme,domain,ftp_port) <<std::endl;
}
else {
std::cerr << "Scheme not valid. Use of these: http, https, ftp"<<std::endl;
}
return 0;
}
|
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n,p;
vector<int> ps;
cout<<"Enter the length of the page string.\n";
cin>>n;
set<int> s;
queue<int> q;
cout<<"Enter the page frame size.\n";
int pframe;
cin>>pframe;
int currsize=0;
int phit=0,pfault=0;
cout<<"Enter the page string.\n";
for(int i=1;i<=n;i++)
{
cin>>p;
if(s.count(p))
phit++;
else
{
if(currsize==pframe)
{
s.erase(q.front());
q.pop();
currsize--;
}
q.push(p);
s.insert(p);
pfault++;
currsize++;
}
}
cout<<"The number of page hits is "<<phit<<endl;
cout<<"The number of page faults is "<<pfault<<endl;
}
|
#ifndef D3D9INDEXBUFFER_H
#define D3D9INDEXBUFFER_H
#include "iindexbuffer.h"
#include <d3d9.h>
#if USE_LONG_INDICES
#define D3DINDEXFORMAT D3DFMT_INDEX32
#else
#define D3DINDEXFORMAT D3DFMT_INDEX16
#endif
class D3D9IndexBuffer : public IIndexBuffer
{
protected:
virtual ~D3D9IndexBuffer();
public:
D3D9IndexBuffer( IDirect3DDevice9* D3DDevice );
virtual void Init( uint NumIndices, index_t* Indices );
virtual void* GetIndices();
virtual uint GetNumIndices();
virtual void SetNumIndices( uint NumIndices );
virtual uint GetNumPrimitives();
virtual void SetPrimitiveType( EPrimitiveType PrimitiveType );
virtual int AddReference();
virtual int Release();
D3DPRIMITIVETYPE GetPrimitiveType() { return m_PrimitiveType; }
private:
int m_RefCount;
uint m_NumIndices;
IDirect3DIndexBuffer9* m_Indices;
IDirect3DDevice9* m_D3DDevice;
D3DPRIMITIVETYPE m_PrimitiveType;
};
#endif // D3D9INDEXBUFFER_H
|
#include"globalDefine.h"
#include"PerspectiveCamera.h"
#include"ObjFile.h"
#include"DirectionalLight.h"
#include<iostream>
#include<string>
#pragma comment(lib,"legacy_stdio_definitions.lib")
#if _MSC_VER>=1900
#include "stdio.h"
_ACRTIMP_ALT FILE* __cdecl __acrt_iob_func(unsigned);
#ifdef __cplusplus
extern "C"
#endif
FILE* __cdecl __iob_func(unsigned i) {
return __acrt_iob_func(i);
}
#endif /* _MSC_VER>=1900 */
using namespace vmath;
using namespace std;
//define all global variables. globalDefine.h externs these variables.
namespace gg {
//matrixs location:
GLuint program;
GLint modelMatrixLoc;
GLint projectionMatrixLoc;
GLint viewMatrixLoc;
GLint ambientLoc;
GLint lightColorLoc;
GLint lightDirectionLoc;
GLint eyePosLoc;
GLint shininessLoc;
GLint strengthLoc;
GLint lightFromLoc;
GLint lightToLoc;
GLint materialLoc;
GLint lightsArrayLoc;
list<Object*> allObjects;
list<Camera*> allCameras;
list<Light*> allLights;
Camera* activeCamera;
PerspectiveCamera* defaultCamera;
DirectionalLight* defaultLight;
LightProperties lightsArray[MaxLights];
void uniformLightProperties(int i, GLuint _program) {
GLint loc = -1;
char tmp[50];
sprintf(tmp, "lightsArray[%d].isEnabled", i);
loc = glGetUniformLocation(_program, tmp);
glUniform1i(loc, lightsArray[i].isEnabled);
sprintf(tmp, "lightsArray[%d].isPoint", i);
loc = glGetUniformLocation(_program, tmp);
glUniform1i(loc, lightsArray[i].isPoint);
sprintf(tmp, "lightsArray[%d].isSpot", i);
loc = glGetUniformLocation(_program, tmp);
glUniform1i(loc, lightsArray[i].isSpot);
sprintf(tmp, "lightsArray[%d].isDirectional", i);
loc = glGetUniformLocation(_program, tmp);
glUniform1i(loc, lightsArray[i].isDirectional);
sprintf(tmp, "lightsArray[%d].isHemisphere", i);
loc = glGetUniformLocation(_program, tmp);
glUniform1i(loc, lightsArray[i].isHemisphere);
sprintf(tmp, "lightsArray[%d].ambient", i);
loc = glGetUniformLocation(_program, tmp);
glUniform3fv(loc, 1, lightsArray[i].ambient);
sprintf(tmp, "lightsArray[%d].color", i);
loc = glGetUniformLocation(_program, tmp);
glUniform3fv(loc, 1, lightsArray[i].color);
sprintf(tmp, "lightsArray[%d].position", i);
loc = glGetUniformLocation(_program, tmp);
glUniform3fv(loc, 1, lightsArray[i].position);
sprintf(tmp, "lightsArray[%d].coneCenter", i);
loc = glGetUniformLocation(_program, tmp);
glUniform3fv(loc, 1, lightsArray[i].coneCenter);
sprintf(tmp, "lightsArray[%d].lightFrom", i);
loc = glGetUniformLocation(_program, tmp);
glUniform3fv(loc, 1, lightsArray[i].lightFrom);
sprintf(tmp, "lightsArray[%d].lightTo", i);
loc = glGetUniformLocation(_program, tmp);
glUniform3fv(loc, 1, lightsArray[i].lightTo);
sprintf(tmp, "lightsArray[%d].spotCosCutoff", i);
loc = glGetUniformLocation(_program, tmp);
glUniform1f(loc, lightsArray[i].spotCosCutoff);
sprintf(tmp, "lightsArray[%d].spotExponent", i);
loc = glGetUniformLocation(_program, tmp);
glUniform1f(loc, lightsArray[i].spotExponent);
sprintf(tmp, "lightsArray[%d].constantAttenuation", i);
loc = glGetUniformLocation(_program, tmp);
glUniform1f(loc, lightsArray[i].constantAttenuation);
sprintf(tmp, "lightsArray[%d].linearAttenuation", i);
loc = glGetUniformLocation(_program, tmp);
glUniform1f(loc, lightsArray[i].linearAttenuation);
sprintf(tmp, "lightsArray[%d].quadraticAttenuation", i);
loc = glGetUniformLocation(_program, tmp);
glUniform1f(loc, lightsArray[i].quadraticAttenuation);
}
void gardenInit() {//this function should be called after glUseProgram()
for (int i = 0; i < MaxLights; i++) {
lightsArray[i].isEnabled = false;
}
modelMatrixLoc = glGetUniformLocation(program, "model_matrix");
projectionMatrixLoc = glGetUniformLocation(program, "projection_matrix");
viewMatrixLoc = glGetUniformLocation(program, "view_matrix");
lightsArrayLoc = glGetUniformLocation(program, "lightsArray");
shininessLoc = glGetUniformLocation(program, "shininess");
strengthLoc = glGetUniformLocation(program, "strength");
materialLoc = glGetUniformLocation(program, "material");
//default camera:
defaultCamera = createPerspectiveCamera(
vec3(0.0f, 0.0f, 1.0f),
vec3(0.0f, 0.0f, -1.0f),
vec3(0.0f, 1.0f, 0.0f),
-1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 300.0f
);
defaultCamera->setActive();
//default light:
defaultLight = createDirectionalLight();
defaultLight->setActive();
//TODO: init others
}
void gardenRelease() {
//release all new objects
int objectCount = allObjects.size();
for (list<Object*>::iterator ite = allObjects.begin();
ite!=allObjects.end();
ite++
) {
delete *ite;
*ite = NULL;
}
allObjects.clear();
int cameraCount = allCameras.size();
for (list<Camera*>::iterator ite = allCameras.begin();
ite != allCameras.end();
ite++
) {
delete *ite;
*ite = NULL;
}
allCameras.clear();
int lightCount = allLights.size();
for (list<Light*>::iterator ite = allLights.begin();
ite != allLights.end();
ite++
) {
(*ite)->setInactive();
delete *ite;
*ite = NULL;
}
allLights.clear();
cout << objectCount << " objects have been released." << endl;
cout << cameraCount << " cameras have been released." << endl;
cout << lightCount << " lights have been released." << endl;
}
Object* findObject(int id) {
for (list<Object*>::iterator ite;
ite != allObjects.end();
ite++) {
if ((*ite)->getId() == id) {
return *ite;
}
}
return NULL;
}
Light* findLight(int id) {
for (list<Light*>::iterator ite;
ite != allLights.end();
ite++) {
if ((*ite)->getId() == id) {
return *ite;
}
}
return NULL;
}
Camera* findCamera(int id) {
for (list<Camera*>::iterator ite;
ite != allCameras.end();
ite++) {
if ((*ite)->getId() == id) {
return *ite;
}
}
return NULL;
}
}
|
// PaintFindIndexVisitor.h
#ifndef _PAINTFINDINDEXVISITOR_H
#define _PAINTFINDINDEXVISITOR_H
#include "Visitor.h"
#include <afxwin.h>
class PaintFindIndexVisitor : public Visitor {
public:
PaintFindIndexVisitor(CDC *dc);
PaintFindIndexVisitor(const PaintFindIndexVisitor& source);
virtual ~PaintFindIndexVisitor();
PaintFindIndexVisitor& operator=(const PaintFindIndexVisitor& source);
virtual void Visit(Note *note);
virtual void Visit(Page *page);
virtual void Visit(Memo *memo);
virtual void Visit(Line *line);
virtual void Visit(Character *character);
virtual void Visit(SingleCharacter *singleCharacter);
virtual void Visit(DoubleCharacter *doubleCharacter);
virtual void Visit(OtherNoteForm *otherNoteForm);
private:
CDC *dc;
};
#endif // _PAINTFINDINDEXVISITOR_H
|
// This file is subject to the terms and conditions defined in 'LICENSE' in the source code package
#ifndef JACTORIO_INCLUDE_RENDER_RENDERER_EXCEPTION_H
#define JACTORIO_INCLUDE_RENDER_RENDERER_EXCEPTION_H
#pragma once
#include <stdexcept>
namespace jactorio::render
{
// These are raised by render classes if an error occurred
class RendererException : public std::runtime_error
{
using std::runtime_error::runtime_error;
};
} // namespace jactorio::render
#endif // JACTORIO_INCLUDE_RENDER_RENDERER_EXCEPTION_H
|
#include "audio\Singularity.Audio.h"
namespace Singularity
{
namespace Audio
{
IMPLEMENT_OBJECT_TYPE(Singularity.Audio, AudioListener, Component);
#pragma region Constructors and Finalizers
// Constructor. Takes in a name for the AudioListener.
AudioListener::AudioListener(String name) : Singularity::Components::Component(name)
{
m_name = name;
m_offset = Vector3(0,0,0);
m_offsetDirection = Vector3(0,0,0);
// m_previousRotation = NULL;
// One of many ways to zero out the memory for the struct.
ZeroMemory( &m_listener, sizeof( X3DAUDIO_LISTENER ) );
}
// Destructor.
AudioListener::~AudioListener()
{
}
#pragma endregion
#pragma region Overriden Methods
// Called whenever this component is added to a GameObject.
void AudioListener::OnComponentAdded(Singularity::Components::GameObject* gameObject)
{
Quaternion q = Get_GameObject()->Get_Transform()->Get_LocalRotation();
m_listener.Position = (D3DXVECTOR3)Get_GameObject()->Get_Transform()->Get_Position();
m_listener.Velocity = (D3DXVECTOR3)Vector3(0, 0, 0);
m_listener.OrientFront = (D3DXVECTOR3)Vector3(q.x, q.y, q.z); // probably needs more testing...
m_listener.OrientTop = (D3DXVECTOR3)Vector3(0, 1, 0);
AudioExtension::Instantiate()->RegisterListener(this);
}
// Called whenever this component is removed from a GameObject.
void AudioListener::OnComponentRemoved(Singularity::Components::GameObject* gameObject)
{
// clear out the position
m_listener.Position = (D3DXVECTOR3)Vector3(0,0,0);
m_listener.Velocity = (D3DXVECTOR3)Vector3(0,0,0);
m_listener.OrientFront = (D3DXVECTOR3)Vector3(0,0,0);
m_listener.OrientTop = (D3DXVECTOR3)Vector3(0,0,0);
AudioExtension::Instantiate()->UnregisterListener(this);
}
#pragma endregion
#pragma region Methods
// Initializes the AudioListener.
void AudioListener::Initialize()
{
}
// Sets the offset and the offset direction from the GameObject for the AudioListener.
void AudioListener::SetOffset(Vector3 offset, Vector3 offsetDirection)
{
m_offset = offset;
m_offsetDirection = offsetDirection;
}
// Updates the state of the AudioListener.
void AudioListener::UpdateState()
{
if (Get_GameObject() != NULL)
{
m_listener.Position = (D3DXVECTOR3)Get_GameObject()->Get_Transform()->Get_Position();
//m_listener.OrientFront.x = Get_GameObject()->Get_Transform()->Get_Rotation().x;
//m_listener.OrientFront.y = Get_GameObject()->Get_Transform()->Get_Rotation().y;
//m_listener.OrientFront.z = Get_GameObject()->Get_Transform()->Get_Rotation().z+1;
}
//if (m_previousRotation != NULL)
{
Quaternion curRot;
curRot = this->Get_GameObject()->Get_Transform()->Get_Rotation();
if (m_previousRotation != curRot)
{
Quaternion vecRot, inverse, result;
//curRot = this->Get_GameObject()->Get_Transform()->Get_Rotation();
vecRot.x = 0.0f;
vecRot.y = 0.0f;
vecRot.z = 1.0f;
vecRot.w = 0.0f;
inverse = curRot.conjugate();
result = curRot * vecRot * inverse;
m_listener.OrientFront.x = result.x;
m_listener.OrientFront.y = result.y;
m_listener.OrientFront.z = result.z;
}
}
// ew, this is a nasty hack.
//Singularity::Graphics::Camera::Get_Current();
}
#pragma endregion
#pragma region Properties
// Returns the X3DAudio struct for the listener.
X3DAUDIO_LISTENER AudioListener::GetX3dListener()
{
return m_listener;
}
#pragma endregion
}
}
|
#ifndef REFCOUNT_H
#define REFCOUNT_H
template <class T>
class IRefCount{
template <class U> friend class SharedPointer;
protected:
virtual void incRefCount() = 0;
virtual void decRefCount() = 0;
virtual T* getPtr() const = 0;
public:
virtual int getCounter() const = 0;
};
//--------------------------------------------------------------//
template <class T>
class RefCount : public IRefCount < T >{
int counter;
void inline printCounter() { std::cout << counter << "\n"; }
protected:
virtual void incRefCount() { counter++;}
virtual void decRefCount() {
counter--;
if (counter <= 0) destroyRef();
}
virtual T* getPtr() const { return (T*)this;}
virtual void destroyRef(){ if (getPtr()) delete getPtr(); }
RefCount() : counter(0) {}
public:
virtual int getCounter() const {
return counter;
}
};
#endif
|
/*************************************************************
* > File Name : UVa1396.cpp
* > Author : Tony
* > Created Time : 2019/05/02 16:55:22
**************************************************************/
#include <bits/stdc++.h>
using namespace std;
const double eps = 1e-7;
struct Point {
double x, y;
Point(double x = 0, double y = 0): x(x), y(y) {}
};
typedef Point Vector;
Vector operator + (Vector a, Vector b) { return Vector(a.x + b.x, a.y + b.y); }
Vector operator - (Vector a, Vector b) { return Vector(a.x - b.x, a.y - b.y); }
Vector operator * (Vector a, double p) { return Vector(a.x * p, a.y * p); }
Vector operator / (Vector a, double p) { return Vector(a.x / p, a.y / p); }
double Dot(Vector a, Vector b) { return a.x * b.x + a.y * b.y; }
double Length(Vector a) { return sqrt(Dot(a, a)); }
double Cross(Vector a, Vector b) { return a.x * b.y - a.y * b.x; }
Vector Normal(Vector a) { double L = Length(a); return Vector(-a.y / L, a.x / L); }
struct Line {
Point p;
Vector v;
double ang;
Line() {}
Line(Point p, Vector v): p(p), v(v) { ang = atan2(v.y, v.x); }
bool operator < (const Line& L) const {
return ang < L.ang;
}
Point point(double t) {
return p + v * t;
}
Line move(double d) {
return Line(p + Normal(v) * d, v);
}
};
bool OnLeft(Line L, Point p) {
return Cross(L.v, p - L.p) > 0;
}
Point GetLineIntersection(Line a, Line b) {
Vector u = a.p - b.p;
double t = Cross(b.v, u) / Cross(a.v, b.v);
return a.p + a.v * t;
}
double PolygonArea(vector<Point> p) {
int n = p.size();
double area = 0;
for (int i = 1; i < n - 1; ++i) {
area += Cross(p[i] - p[0], p[i + 1] - p[0]);
}
return area / 2;
}
vector<Point> HalfplaneIntersection(vector<Line> L) {
int n = L.size();
sort(L.begin(), L.end());
int first, last;
vector<Point> p(n);
vector<Line> q(n);
vector<Point> ans;
q[first = last = 0] = L[0];
for (int i = 1; i < n; i++) {
while (first < last && !OnLeft(L[i], p[last - 1])) last--;
while (first < last && !OnLeft(L[i], p[first])) first++;
q[++last] = L[i];
if (fabs(Cross(q[last].v, q[last - 1].v)) < eps) {
last--;
if (OnLeft(q[last], L[i].p)) q[last] = L[i];
}
if (first < last) p[last - 1] = GetLineIntersection(q[last - 1], q[last]);
}
while (first < last && !OnLeft(q[first], p[last - 1])) last--;
if (last - first <= 1) return ans;
p[last] = GetLineIntersection(q[last], q[first]);
for (int i = first; i <= last; i++) ans.push_back(p[i]);
return ans;
}
int main() {
int n;
while (scanf("%d", &n) == 1 && n) {
vector<Point> p, v, normal;
int m, x, y;
for (int i = 0; i < n; ++i) {
scanf("%d %d", &x, &y);
p.push_back(Point(x, y));
}
if (PolygonArea(p) < 0) reverse(p.begin(), p.end());
for (int i = 0; i < n; ++i) {
v.push_back(p[(i + 1) % n] - p[i]);
normal.push_back(Normal(v[i]));
}
double l = 0, r = 20000;
while (r - l > eps) {
vector<Line> L;
double mid = l + (r - l) / 2;
for (int i = 0; i < n; ++i) {
L.push_back(Line(p[i] + normal[i] * mid, v[i]));
}
vector<Point> poly = HalfplaneIntersection(L);
if (poly.empty()) {
r = mid;
} else {
l = mid;
}
}
printf("%.6lf\n", l);
}
return 0;
}
|
#ifndef __QINT_H__
#define __QINT_H__
#define _BIT_UINT32_ 32
#define _DEFAULT_SIZE 16
#define _POSITION ((Binary.size() - 1 - i) / (sizeof(_Uint32t) * CHAR_BIT))
#define _SHIFT_OFFSET (((Binary.size() - 1) % (CHAR_BIT * sizeof(_Uint32t))) - (i % (CHAR_BIT * sizeof(_Uint32t))))
#include <string>
#include <iostream>
using namespace std;
class QInt
{
protected:
unsigned int data[4];
public:
QInt();
~QInt();
QInt(const string&Binary);
unsigned int getData(int i);
void setData(int pos, unsigned int x);
QInt operator & (const QInt &x) const;
QInt operator << (const int &ShiftOffset);
QInt operator ^ (const QInt &x) const;
QInt operator + (QInt x) const;
QInt operator - (QInt x) const;
QInt& operator ~ ();
QInt QInttoTwosComplement();
bool checkIfZero();
};
#endif
|
/****************************************
*
* INSERT-PROJECT-NAME-HERE - INSERT-GENERIC-NAME-HERE
* Copyright (C) 2019 Victor Tran
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* *************************************/
#ifndef PAUSEOVERLAY_H
#define PAUSEOVERLAY_H
#include "libentertaining_global.h"
#include <QWidget>
#include <functional>
struct PauseOverlayPrivate;
class LIBENTERTAINING_EXPORT PauseOverlay : public QWidget
{
Q_OBJECT
public:
static void registerOverlayForWindow(QWidget* window, QWidget* blurOver);
static PauseOverlay* overlayForWindow(QWidget* window);
~PauseOverlay();
void showOverlay();
void hideOverlay();
void setOverlayWidget(QWidget* overlayWidget);
void pushOverlayWidget(QWidget* overlayWidget);
void popOverlayWidget(std::function<void()> after = []{});
signals:
void widgetPopped();
public slots:
private:
explicit PauseOverlay(QWidget* blurOver, QWidget *parent = nullptr);
PauseOverlayPrivate* d;
bool eventFilter(QObject* watched, QEvent* event);
void paintEvent(QPaintEvent* event);
void animateCurrentOut(std::function<void()> after = []{});
void setNewOverlayWidget(QWidget* widget, std::function<void()> after = []{});
};
#endif // PAUSEOVERLAY_H
|
#include<bits/stdc++.h>
using namespace std;
int main(){
string s;
cin >> s;
bool flag = true;
for(int i=0;i<s.size();i++){
if(s[i] == 'X'){
cout << i << endl;
flag = false;
break;
}
}
if(flag) cout << s.size() << endl;
}
|
#include <iostream>
#include <queue>
#include <climits>
using namespace std;
class node
{
public:
int data;
node* left;
node* right;
node(int d):data(d),left(NULL),right(NULL){
}
};
void Preorder(node* root){
if(root==NULL){
return;
}
cout<<root->data<<" ";
Preorder(root->left);
Preorder(root->right);
}
void Inorder(node* root){
if(root==NULL){
return;
}
Inorder(root->left);
cout<<root->data<<" ";
Inorder(root->right);
}
void Postorder(node* root){
if(root==NULL){
return;
}
Postorder(root->left);
Postorder(root->right);
cout<<root->data<<" ";
}
node* InsertInBst(node* root,int data){
if(root==NULL){
root=new node(data);
return root;
}
if(data<root->data){
root->left=InsertInBst(root->left,data);
}
else{
root->right=InsertInBst(root->right,data);
}
return root;
}
node* buildTree()
{
node* root=NULL;
int data;
cin>>data;
while(data!=-1){
root=InsertInBst(root,data);
cin>>data;
}
return root;
}
class LinkedList
{
public:
node* head;
node* tail;
};
LinkedList BSTtoLL(node *root)
{
LinkedList l;
if(root==NULL)
{
l.head=NULL;
l.tail=NULL;
return l;
}
if(root->left!=NULL && root->right==NULL)
{
LinkedList left=BSTtoLL(root->left);
left.tail->right=root;
l.head=left.head;
l.tail=root;
return l;
}
else if(root->right!=NULL && root->left==NULL)
{
LinkedList right=BSTtoLL(root->right);
root->right=right.head;
l.head=root;
l.tail=right.tail;
return l;
}
else if(root->right==NULL && root->left==NULL)
{
l.head=root;
l.tail=root;
return l;
}
else
{
LinkedList left=BSTtoLL(root->left);
LinkedList right=BSTtoLL(root->right);
left.tail->right=root;
root->right=right.head;
l.head=left.head;
l.tail=right.tail;
return l;
}
}
void print(node *head)
{
while(head)
{
cout<<head->data<<" ";
head=head->right;
}
}
int main()
{
node *root=buildTree();
LinkedList l=BSTtoLL(root);
print(l.head);
return 0;
}
|
/*
* Callback.h
*
* Created on: Dec 28, 2013
* Author: Jakub 'kuhar' Kuderski , Dawid Drozd
*/
#pragma once
#include <vector>
#include <utility>
#include <type_traits>
#include <functional>
#include "cocos2d.h"
#define CALLBACK_ENABLE_ASSERTIONS 1
#if CALLBACK_ENABLE_ASSERTIONS == 1
#include <cassert>
#endif
#if CALLBACK_ENABLE_ASSERTIONS == 1
#define CALLBACK_ASSERT( CONDITION ) assert( CONDITION )
#else
#define CALLBACK_ASSERT( CONDITION )
#endif
namespace Utils
{
/**
* WARNING FOR VISUAL C++: set additional /vmg flag, otherwise generated code may not work!
*
* Example usage:
*
* Callback<void(int)> callback; // void --> return type, other types --> argument types
* callback.set(pObject ,&CCObject::methodWithInt);
*
* or Callback<void(int)> callback(pObject, &CCObject::methodWithInt);
*
* or Callback<int(int, float)> callback = makeCallback( pObject, &SomeClass::someMethod );
*
* or even: auto callback = makeCallback( pObject, &SomeClass::someMethod );
*
* then call methods with some args: int result = callback.call ( some, args );
*
* You can also use functions/static methods and non-capturing lambdas.
* Ex. auto callback = Callback<void(int)>( []( int n ){ cout << n; } );
*
* Please note that the following implementation uses chakra magic - be careful when modifying.
* If you are out of mana, see previous revisions that used std::function.
*/
using BaseClass = cocos2d::CCObject;
template<typename T>
class Callback;
template<typename ReturnType, typename... Args>
class Callback<ReturnType( Args... )>
{
private:
enum class PointerType : unsigned char
{
Unknown,
NonConstMethod,
ConstMethod,
Function
};
public:
Callback() = default;
template<typename ClassType, typename MethodType>
Callback( ClassType* pObject, const MethodType& method ) :
m_pointerType( PointerType::NonConstMethod )
{
static_assert( std::is_member_function_pointer<MethodType>::value,
"The second argument must be a pointer to a method" );
set( pObject, method );
}
template<typename FunctionType>
Callback( const FunctionType& functor ) :
m_pointerType( PointerType::Function )
{
set( functor );
}
Callback( const Callback& otherCallback )
{
m_callableObject = otherCallback.m_callableObject;
m_pointerType = otherCallback.m_pointerType;
}
Callback& operator= ( const Callback& otherCallback )
{
m_callableObject = otherCallback.m_callableObject;
m_pointerType = otherCallback.m_pointerType;
return *this;
}
inline bool isCallable() const
{
return m_callableObject.first != nullptr ||
m_pointerType == PointerType::Function;
}
inline BaseClass* getObject() const
{
return m_callableObject.first;
}
template<typename ObjectType, typename ClassType, typename ClassReturnType, typename... ClassArgs>
Callback& set( ObjectType* pObject,
ClassReturnType( ClassType::*method )( ClassArgs... ) )
{
static_assert( std::is_base_of<BaseClass, ClassType>::value,
"CCObject must be the base of used class" );
static_assert( std::is_base_of<ClassType, ObjectType>::value,
"Pointer to method must be the base of object's pointer" );
m_pointerType = PointerType::NonConstMethod;
MethodPointer methodPointer;
methodPointer.nonConstMethod =
static_cast<ReturnType( BaseClass::* )( Args... )> ( method );
m_callableObject = std::make_pair( pObject, methodPointer );
return *this;
}
template<typename ObjectType, typename ClassType, typename ClassReturnType, typename... ClassArgs>
Callback& set( ObjectType* pObject,
ClassReturnType( ClassType::*method )( ClassArgs... ) const )
{
static_assert( std::is_base_of<BaseClass, ClassType>::value,
"CCObject must be the base of used class" );
static_assert( std::is_base_of<ClassType, ObjectType>::value,
"Pointer to method must be the base of object's pointer" );
m_pointerType = PointerType::ConstMethod;
MethodPointer methodPointer;
methodPointer.constMethod =
static_cast<ReturnType( BaseClass::* )( Args... ) const> ( method );
m_callableObject = std::make_pair( pObject, methodPointer );
return *this;
}
template<typename FunctionType>
Callback& set( const FunctionType& functor )
{
static_assert(
std::is_convertible<FunctionType, std::function<ReturnType( Args... )>>::value,
"Parameter must be either function (static method) pointer or non-capturing lambda. Or simply your arguments doesn't match." );
m_pointerType = PointerType::Function;
MethodPointer methodPointer;
methodPointer.function = static_cast<ReturnType( * )( Args... )> ( functor );
m_callableObject = std::make_pair( nullptr, methodPointer );
return *this;
}
template<typename... CallArgs>
ReturnType call( CallArgs&& ... params ) const
{
CALLBACK_ASSERT( isCallable() );
CALLBACK_ASSERT( m_pointerType != PointerType::Unknown );
if( m_pointerType == PointerType::NonConstMethod )
{
return ( m_callableObject.first->*m_callableObject.second.nonConstMethod )(
std::forward<CallArgs> ( params )... );
}
if( m_pointerType == PointerType::ConstMethod )
{
return ( m_callableObject.first->*m_callableObject.second.constMethod )(
std::forward<CallArgs> ( params )... );
}
return ( *m_callableObject.second.function )( std::forward<CallArgs> ( params )... );
}
template<typename... CallArgs>
void callIfCallable( CallArgs&& ... params ) const
{
if( isCallable() )
{
call( std::forward<CallArgs> ( params )... );
}
}
#ifdef DEBUG
#pragma GCC diagnostic push // require GCC 4.6
#pragma GCC diagnostic ignored "-Wcast-qual"
//I know this isn't good way to do this but i don't have any other option for now
void* getFunctionPointer()const
{
if( m_pointerType == PointerType::NonConstMethod )
{
return ( void*& )m_callableObject.second.nonConstMethod;
}
if( m_pointerType == PointerType::ConstMethod )
{
return ( void*& )m_callableObject.second.nonConstMethod;
}
return ( void*& )m_callableObject.second.function;
}
#pragma GCC diagnostic pop // require GCC 4.6
#endif
private:
union MethodPointer
{
ReturnType( BaseClass::*nonConstMethod )( Args... );
ReturnType( BaseClass::*constMethod )( Args... ) const;
ReturnType( *function )( Args... );
};
typedef std::pair<BaseClass*, MethodPointer> ObjectMethodPair;
ObjectMethodPair m_callableObject;
PointerType m_pointerType = PointerType::Unknown;
};
template<typename ReturnType, typename ObjectType, typename MethodType, typename... Args>
Callback<ReturnType( Args... )> makeCallback( ObjectType* pObject,
ReturnType( MethodType::*method )( Args... ) )
{
return Callback<ReturnType( Args... )> ( pObject, method );
}
template<typename ReturnType, typename ObjectType, typename MethodType, typename... Args>
Callback<ReturnType( Args... )> makeCallback( ObjectType* pObject,
ReturnType( MethodType::*method )( Args... ) const )
{
return Callback<ReturnType( Args... )> ( pObject, method );
}
template<typename ReturnType, typename... Args>
Callback<ReturnType( Args... )> makeCallback( ReturnType( *function )(
Args... ) )
{
return Callback<ReturnType( Args... )> ( function );
}
} // namespace Utils
|
#include "Sprites.h"
#include "SpriteManager.h"
#include "Testing.h"
#include "Settings.h"
void Sprite::Unvalidate()
{
if( Valid )
{
if( ValidCallback )
{
*ValidCallback = false;
ValidCallback = nullptr;
}
Valid = false;
if( Parent )
{
Parent->Child = nullptr;
Parent->Unvalidate();
}
if( Child )
{
Child->Parent = nullptr;
Child->Unvalidate();
}
if( ExtraChainRoot )
*ExtraChainRoot = ExtraChainChild;
if( ExtraChainParent )
ExtraChainParent->ExtraChainChild = ExtraChainChild;
if( ExtraChainChild )
ExtraChainChild->ExtraChainParent = ExtraChainParent;
if( ExtraChainRoot && ExtraChainChild )
ExtraChainChild->ExtraChainRoot = ExtraChainRoot;
ExtraChainRoot = nullptr;
ExtraChainParent = nullptr;
ExtraChainChild = nullptr;
if( MapSpr )
{
MapSpr->Release();
MapSpr = nullptr;
}
UnvalidatedPlace->push_back( this );
UnvalidatedPlace = nullptr;
if( ChainRoot )
*ChainRoot = ChainChild;
if( ChainLast )
*ChainLast = ChainParent;
if( ChainParent )
ChainParent->ChainChild = ChainChild;
if( ChainChild )
ChainChild->ChainParent = ChainParent;
if( ChainRoot && ChainChild )
ChainChild->ChainRoot = ChainRoot;
if( ChainLast && ChainParent )
ChainParent->ChainLast = ChainLast;
ChainRoot = nullptr;
ChainLast = nullptr;
ChainParent = nullptr;
ChainChild = nullptr;
}
}
Sprite* Sprite::GetIntersected( int ox, int oy )
{
// Check for cutting
if( ox < 0 || oy < 0 )
return nullptr;
if( !CutType )
return SprMngr.IsPixNoTransp( PSprId ? *PSprId : SprId, ox, oy ) ? this : nullptr;
// Find root sprite
Sprite* spr = this;
while( spr->Parent )
spr = spr->Parent;
// Check sprites
float oxf = (float) ox * GameOpt.SpritesZoom;
while( spr )
{
if( oxf >= spr->CutX && oxf < spr->CutX + spr->CutW )
return SprMngr.IsPixNoTransp( spr->PSprId ? *spr->PSprId : spr->SprId, ox, oy ) ? spr : nullptr;
spr = spr->Child;
}
return nullptr;
}
#define SPRITE_SETTER( func, type, val ) \
void Sprite::func( type val ## __ ) { if( !Valid ) \
return; Valid = false; val = val ## __; if( Parent ) \
Parent->func( val ## __ ); if( Child ) \
Child->func( val ## __ ); Valid = true; }
#define SPRITE_SETTER2( func, type, val, type2, val2 ) \
void Sprite::func( type val ## __, type2 val2 ## __ ) { if( !Valid ) \
return; Valid = false; val = val ## __; val2 = val2 ## __; if( Parent ) \
Parent->func( val ## __, val2 ## __ ); if( Child ) \
Child->func( val ## __, val2 ## __ ); Valid = true; }
SPRITE_SETTER( SetEgg, int, EggType );
SPRITE_SETTER( SetContour, int, ContourType );
SPRITE_SETTER2( SetContour, int, ContourType, uint, ContourColor );
SPRITE_SETTER( SetColor, uint, Color );
SPRITE_SETTER( SetAlpha, uchar *, Alpha );
SPRITE_SETTER( SetFlash, uint, FlashMask );
void Sprite::SetLight( int corner, uchar* light, int maxhx, int maxhy )
{
if( !Valid )
return;
Valid = false;
if( HexX >= 1 && HexX < maxhx - 1 && HexY >= 1 && HexY < maxhy - 1 )
{
Light = &light[ HexY * maxhx * 3 + HexX * 3 ];
switch( corner )
{
default:
case CORNER_EAST_WEST:
case CORNER_EAST:
LightRight = Light - 3;
LightLeft = Light + 3;
break;
case CORNER_NORTH_SOUTH:
case CORNER_WEST:
LightRight = Light + ( maxhx * 3 );
LightLeft = Light - ( maxhx * 3 );
break;
case CORNER_SOUTH:
LightRight = Light - 3;
LightLeft = Light - ( maxhx * 3 );
break;
case CORNER_NORTH:
LightRight = Light + ( maxhx * 3 );
LightLeft = Light + 3;
break;
}
}
else
{
Light = nullptr;
LightRight = nullptr;
LightLeft = nullptr;
}
if( Parent )
Parent->SetLight( corner, light, maxhx, maxhy );
if( Child )
Child->SetLight( corner, light, maxhx, maxhy );
Valid = true;
}
void Sprite::SetFixedAlpha( uchar alpha )
{
if( !Valid )
return;
Valid = false;
Alpha = ( (uchar*) &Color ) + 3;
*Alpha = alpha;
if( Parent )
Parent->SetFixedAlpha( alpha );
if( Child )
Child->SetFixedAlpha( alpha );
Valid = true;
}
SpriteVec Sprites::spritesPool;
void Sprites::GrowPool()
{
spritesPool.reserve( spritesPool.size() + SPRITES_POOL_GROW_SIZE );
for( uint i = 0; i < SPRITES_POOL_GROW_SIZE; i++ )
spritesPool.push_back( new Sprite() );
}
Sprites::Sprites()
{
rootSprite = nullptr;
lastSprite = nullptr;
spriteCount = 0;
}
Sprites::~Sprites()
{
Clear();
}
Sprite* Sprites::RootSprite()
{
return rootSprite;
}
Sprite& Sprites::PutSprite( Sprite* child, int draw_order, int hx, int hy, int cut, int x, int y, int* sx, int* sy, uint id, uint* id_ptr, short* ox, short* oy, uchar* alpha, Effect** effect, bool* callback )
{
spriteCount++;
Sprite* spr;
if( !unvalidatedSprites.empty() )
{
spr = unvalidatedSprites.back();
unvalidatedSprites.pop_back();
}
else
{
if( spritesPool.empty() )
GrowPool();
spr = spritesPool.back();
spritesPool.pop_back();
}
spr->UnvalidatedPlace = &unvalidatedSprites;
if( !child )
{
if( !lastSprite )
{
rootSprite = spr;
lastSprite = spr;
spr->ChainRoot = &rootSprite;
spr->ChainLast = &lastSprite;
spr->ChainParent = nullptr;
spr->ChainChild = nullptr;
spr->TreeIndex = 0;
}
else
{
spr->ChainParent = lastSprite;
spr->ChainChild = nullptr;
lastSprite->ChainChild = spr;
lastSprite->ChainLast = nullptr;
spr->ChainLast = &lastSprite;
spr->TreeIndex = lastSprite->TreeIndex + 1;
lastSprite = spr;
}
}
else
{
spr->ChainChild = child;
spr->ChainParent = child->ChainParent;
child->ChainParent = spr;
if( spr->ChainParent )
spr->ChainParent->ChainChild = spr;
// Recalculate indices
uint index = ( spr->ChainParent ? spr->ChainParent->TreeIndex + 1 : 0 );
Sprite* spr_ = spr;
while( spr_ )
{
spr_->TreeIndex = index;
spr_ = spr_->ChainChild;
index++;
}
if( !spr->ChainParent )
{
RUNTIME_ASSERT( child->ChainRoot );
rootSprite = spr;
spr->ChainRoot = &rootSprite;
child->ChainRoot = nullptr;
}
}
spr->HexX = hx;
spr->HexY = hy;
spr->CutType = 0;
spr->ScrX = x;
spr->ScrY = y;
spr->PScrX = sx;
spr->PScrY = sy;
spr->SprId = id;
spr->PSprId = id_ptr;
spr->OffsX = ox;
spr->OffsY = oy;
spr->Alpha = alpha;
spr->Light = nullptr;
spr->LightRight = nullptr;
spr->LightLeft = nullptr;
spr->Valid = true;
spr->ValidCallback = callback;
if( callback )
*callback = true;
spr->EggType = 0;
spr->ContourType = 0;
spr->ContourColor = 0;
spr->Color = 0;
spr->FlashMask = 0;
spr->DrawEffect = effect;
spr->Parent = nullptr;
spr->Child = nullptr;
// Cutting
if( cut == SPRITE_CUT_HORIZONTAL || cut == SPRITE_CUT_VERTICAL )
{
bool hor = ( cut == SPRITE_CUT_HORIZONTAL );
int stepi = GameOpt.MapHexWidth / 2;
if( GameOpt.MapHexagonal && hor )
stepi = ( GameOpt.MapHexWidth + GameOpt.MapHexWidth / 2 ) / 2;
float stepf = (float) stepi;
SpriteInfo* si = SprMngr.GetSpriteInfo( id_ptr ? *id_ptr : id );
if( !si || si->Width < stepi * 2 )
return *spr;
spr->CutType = cut;
int h1, h2;
if( hor )
{
h1 = spr->HexX + si->Width / 2 / stepi;
h2 = spr->HexX - si->Width / 2 / stepi - ( si->Width / 2 % stepi ? 1 : 0 );
spr->HexX = h1;
}
else
{
h1 = spr->HexY - si->Width / 2 / stepi;
h2 = spr->HexY + si->Width / 2 / stepi + ( si->Width / 2 % stepi ? 1 : 0 );
spr->HexY = h1;
}
float widthf = (float) si->Width;
float xx = 0.0f;
Sprite* parent = spr;
for( int i = h1; ;)
{
float ww = stepf;
if( xx + ww > widthf )
ww = widthf - xx;
Sprite& spr_ = ( i != h1 ? PutSprite( nullptr, draw_order, hor ? i : hx, hor ? hy : i, 0, x, y, sx, sy, id, id_ptr, ox, oy, alpha, effect, nullptr ) : *spr );
if( i != h1 )
spr_.Parent = parent;
parent->Child = &spr_;
parent = &spr_;
spr_.CutX = xx;
spr_.CutW = ww;
spr_.CutTexL = si->SprRect.L + ( si->SprRect.R - si->SprRect.L ) * ( xx / widthf );
spr_.CutTexR = si->SprRect.L + ( si->SprRect.R - si->SprRect.L ) * ( ( xx + ww ) / widthf );
spr_.CutType = cut;
#ifdef FONLINE_EDITOR
spr_.CutOyL = ( hor ? -6 : -12 ) * ( ( hor ? hx : hy ) - i );
spr_.CutOyR = spr_.CutOyL;
if( ww < stepf )
spr_.CutOyR += (int) ( ( hor ? 3.6f : -8.0f ) * ( 1.0f - ( ww / stepf ) ) );
#endif
xx += stepf;
if( xx > widthf )
break;
if( ( hor && --i < h2 ) || ( !hor && ++i > h2 ) )
break;
}
}
// Draw order
spr->DrawOrderType = draw_order;
spr->DrawOrderPos = ( draw_order >= DRAW_ORDER_FLAT && draw_order < DRAW_ORDER ?
spr->HexY * MAXHEX_MAX + spr->HexX + MAXHEX_MAX * MAXHEX_MAX * ( draw_order - DRAW_ORDER_FLAT ) :
MAXHEX_MAX * MAXHEX_MAX * DRAW_ORDER + spr->HexY * DRAW_ORDER * MAXHEX_MAX + spr->HexX * DRAW_ORDER + ( draw_order - DRAW_ORDER ) );
return *spr;
}
Sprite& Sprites::AddSprite( int draw_order, int hx, int hy, int cut, int x, int y, int* sx, int* sy, uint id, uint* id_ptr, short* ox, short* oy, uchar* alpha, Effect** effect, bool* callback )
{
return PutSprite( nullptr, draw_order, hx, hy, cut, x, y, sx, sy, id, id_ptr, ox, oy, alpha, effect, callback );
}
Sprite& Sprites::InsertSprite( int draw_order, int hx, int hy, int cut, int x, int y, int* sx, int* sy, uint id, uint* id_ptr, short* ox, short* oy, uchar* alpha, Effect** effect, bool* callback )
{
// For cutted sprites need resort all tree
if( cut == SPRITE_CUT_HORIZONTAL || cut == SPRITE_CUT_VERTICAL )
{
Sprite& spr = PutSprite( nullptr, draw_order, hx, hy, cut, x, y, sx, sy, id, id_ptr, ox, oy, alpha, effect, callback );
SortByMapPos();
return spr;
}
// Find place
uint index = 0;
uint pos = ( draw_order >= DRAW_ORDER_FLAT && draw_order < DRAW_ORDER ?
hy * MAXHEX_MAX + hx + MAXHEX_MAX * MAXHEX_MAX * ( draw_order - DRAW_ORDER_FLAT ) :
MAXHEX_MAX * MAXHEX_MAX * DRAW_ORDER + hy * DRAW_ORDER * MAXHEX_MAX + hx * DRAW_ORDER + ( draw_order - DRAW_ORDER ) );
Sprite* parent = rootSprite;
while( parent )
{
if( !parent->Valid )
continue;
if( pos < parent->DrawOrderPos )
break;
parent = parent->ChainChild;
}
return PutSprite( parent, draw_order, hx, hy, cut, x, y, sx, sy, id, id_ptr, ox, oy, alpha, effect, callback );
}
void Sprites::Unvalidate()
{
while( rootSprite )
rootSprite->Unvalidate();
spriteCount = 0;
}
SprInfoVec* SortSpritesSurfSprData = nullptr;
void Sprites::SortByMapPos()
{
if( !rootSprite )
return;
struct Sorter
{
static bool SortBySurfaces( Sprite* spr1, Sprite* spr2 )
{
SpriteInfo* si1 = ( *SortSpritesSurfSprData )[ spr1->PSprId ? *spr1->PSprId : spr1->SprId ];
SpriteInfo* si2 = ( *SortSpritesSurfSprData )[ spr2->PSprId ? *spr2->PSprId : spr2->SprId ];
return si1 && si2 && si1->Atlas && si2->Atlas && si1->Atlas->TextureOwner < si2->Atlas->TextureOwner;
}
static bool SortByMapPos( Sprite* spr1, Sprite* spr2 )
{
if( spr1->DrawOrderPos == spr2->DrawOrderPos )
return spr1->TreeIndex < spr2->TreeIndex;
return spr1->DrawOrderPos < spr2->DrawOrderPos;
}
};
SortSpritesSurfSprData = &SprMngr.GetSpritesInfo();
SpriteVec sprites;
sprites.reserve( spriteCount );
Sprite* spr = rootSprite;
while( spr )
{
sprites.push_back( spr );
spr = spr->ChainChild;
}
std::sort( sprites.begin(), sprites.end(), Sorter::SortBySurfaces );
std::sort( sprites.begin(), sprites.end(), Sorter::SortByMapPos );
for( size_t i = 0; i < sprites.size(); i++ )
{
sprites[ i ]->ChainParent = nullptr;
sprites[ i ]->ChainChild = nullptr;
sprites[ i ]->ChainRoot = nullptr;
sprites[ i ]->ChainLast = nullptr;
}
for( size_t i = 1; i < sprites.size(); i++ )
{
sprites[ i - 1 ]->ChainChild = sprites[ i ];
sprites[ i ]->ChainParent = sprites[ i - 1 ];
}
rootSprite = sprites.front();
lastSprite = sprites.back();
rootSprite->ChainRoot = &rootSprite;
lastSprite->ChainLast = &lastSprite;
}
uint Sprites::Size()
{
return spriteCount;
}
void Sprites::Clear()
{
Unvalidate();
for( Sprite* spr : unvalidatedSprites )
spritesPool.push_back( spr );
unvalidatedSprites.clear();
}
|
#include "actor.h"
Arena::Arena(int width, int height) {
w_ = width;
h_ = height;
}
void Arena::add(Actor* a) {
auto pos = find(begin(actors_), end(actors_), a);
if (pos == actors_.end()) {
actors_.push_back(a);
}
}
void Arena::remove(Actor* a) {
auto pos = find(begin(actors_), end(actors_), a);
if (pos != actors_.end()) {
actors_.erase(pos);
}
}
void Arena::move_all() {
auto acts = actors();
reverse(begin(acts), end(acts));
for (auto a : acts) {
auto prev = a->rect();
a->move();
auto curr = a->rect();
if (curr.x != prev.x || curr.y != prev.y
|| curr.w != prev.w || curr.h != prev.h) {
for (auto other : acts) {
if (other != a && check_collision(a, other)) {
a->collide(other);
other->collide(a);
}
}
}
}
}
bool Arena::check_collision(Actor* a1, Actor* a2) {
auto r1 = a1->rect();
auto r2 = a2->rect();
return (r2.y < r1.y + r1.h && r1.y < r2.y + r2.h
&& r2.x < r1.x + r1.w and r1.x < r2.x + r2.w);
}
vector<Actor*> Arena::actors() { return actors_; }
vector<int> Arena::rect() { return {w_, h_}; }
Arena::~Arena() {
while (!actors_.empty()) {
delete actors_.back();
actors_.pop_back();
}
}
|
/**
* @author Levi Armstrong
* @date January 1, 2016
*
* @copyright Copyright (c) 2016, Southwest Research Institute
*
* @license Software License Agreement (Apache License)\n
* \n
* 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\n
* \n
* http://www.apache.org/licenses/LICENSE-2.0\n
* \n
* 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 "ros_build_configuration.h"
#include "ros_make_step.h"
#include "ros_project.h"
#include "ros_project_constants.h"
#include "ros_utils.h"
#include "ui_ros_build_configuration.h"
#include <coreplugin/icore.h>
#include <projectexplorer/buildinfo.h>
#include <projectexplorer/buildsteplist.h>
#include <projectexplorer/kitinformation.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <projectexplorer/toolchain.h>
#include <utils/mimetypes/mimedatabase.h>
#include <utils/pathchooser.h>
#include <utils/qtcassert.h>
#include <QFormLayout>
#include <QInputDialog>
using namespace ProjectExplorer;
namespace ROSProjectManager {
namespace Internal {
const char ROS_BC_ID[] = "ROSProjectManager.ROSBuildConfiguration";
const char ROS_BC_INITIAL_ARGUMENTS[] = "ROSProjectManager.ROSBuildConfiguration.InitialArguments";
const char ROS_BC_DISTRIBUTION[] = "ROSProjectManager.ROSBuildConfiguration.Distribution";
ROSBuildConfiguration::ROSBuildConfiguration(Target *parent)
: BuildConfiguration(parent, Core::Id(ROS_BC_ID))
{
}
ROSBuildConfiguration::ROSBuildConfiguration(Target *parent, Core::Id id)
: BuildConfiguration(parent, id)
{
}
ROSBuildConfiguration::ROSBuildConfiguration(Target *parent, ROSBuildConfiguration *source) :
BuildConfiguration(parent, source),m_initialArguments(source->m_initialArguments),
m_rosDistribution(source->m_rosDistribution)
{
cloneSteps(source);
}
QVariantMap ROSBuildConfiguration::toMap() const
{
QVariantMap map(BuildConfiguration::toMap());
map.insert(QLatin1String(ROS_BC_INITIAL_ARGUMENTS), m_initialArguments);
map.insert(QLatin1String(ROS_BC_DISTRIBUTION), m_rosDistribution);
return map;
}
bool ROSBuildConfiguration::fromMap(const QVariantMap &map)
{
m_initialArguments = map.value(QLatin1String(ROS_BC_INITIAL_ARGUMENTS)).toString();
m_rosDistribution = map.value(QLatin1String(ROS_BC_DISTRIBUTION)).toString();
return BuildConfiguration::fromMap(map);
}
void ROSBuildConfiguration::setInitialArguments(const QString &arguments)
{
m_initialArguments = arguments;
}
QString ROSBuildConfiguration::initialArguments() const
{
return m_initialArguments;
}
void ROSBuildConfiguration::setROSDistribution(const QString &distribution)
{
m_rosDistribution = distribution;
}
QString ROSBuildConfiguration::rosDistribution() const
{
return m_rosDistribution;
}
void ROSBuildConfiguration::sourceWorkspace()
{
// Need to source ros and devel directory to setup enviroment variables
Utils::FileName ws_dir = target()->project()->projectDirectory();
QProcess process;
if (ROSUtils::sourceWorkspace(&process, ws_dir , rosDistribution()))
{
Utils::Environment source_env = Utils::Environment(process.processEnvironment().toStringList());
source_env.set(QLatin1String("PWD"), ws_dir.toString());
QList<Utils::EnvironmentItem> diff = baseEnvironment().diff(source_env);
if (!diff.isEmpty())
setUserEnvironmentChanges(diff);
}
}
NamedWidget *ROSBuildConfiguration::createConfigWidget()
{
return new ROSBuildSettingsWidget(this);
}
QList<NamedWidget *> ROSBuildConfiguration::createSubConfigWidgets()
{
return QList<NamedWidget *>() << new ROSBuildEnvironmentWidget(this);
}
/*!
\class ROSBuildConfigurationFactory
*/
ROSBuildConfigurationFactory::ROSBuildConfigurationFactory(QObject *parent) :
IBuildConfigurationFactory(parent)
{
}
ROSBuildConfigurationFactory::~ROSBuildConfigurationFactory()
{
}
int ROSBuildConfigurationFactory::priority(const Target *parent) const
{
return canHandle(parent) ? 0 : -1;
}
QList<BuildInfo *> ROSBuildConfigurationFactory::availableBuilds(const Target *parent) const
{
QList<BuildInfo *> result;
QString project_path = parent->project()->projectDirectory().toString();
for (int type = BuildTypeNone; type != BuildTypeLast; ++type)
{
ROSBuildInfo *info = createBuildInfo(parent->kit(), project_path, BuildType(type));
result << info;
}
return result;
}
int ROSBuildConfigurationFactory::priority(const Kit *k, const QString &projectPath) const
{
Utils::MimeDatabase mdb;
if (k && mdb.mimeTypeForFile(projectPath).matchesName(QLatin1String(Constants::ROSMIMETYPE)))
return 0;
return -1;
}
QList<BuildInfo *> ROSBuildConfigurationFactory::availableSetups(const Kit *k, const QString &projectPath) const
{
QList<BuildInfo *> result;
for (int type = BuildTypeNone; type != BuildTypeLast; ++type) {
ROSBuildInfo *info = createBuildInfo(k, projectPath, BuildType(type));
result << info;
}
//TO DO: Should probably check if the directory that was selected was the workspace
return result;
}
BuildConfiguration *ROSBuildConfigurationFactory::create(Target *parent, const BuildInfo *info) const
{
QTC_ASSERT(info->factory() == this, return 0);
QTC_ASSERT(info->kitId == parent->kit()->id(), return 0);
QTC_ASSERT(!info->displayName.isEmpty(), return 0);
ROSBuildInfo ros_info(*static_cast<const ROSBuildInfo *>(info));
ROSBuildConfiguration *bc = new ROSBuildConfiguration(parent);
bc->setDisplayName(ros_info.displayName);
bc->setDefaultDisplayName(ros_info.displayName);
bc->setBuildDirectory(ros_info.buildDirectory);
bc->setInitialArguments(ros_info.arguments);
BuildStepList *buildSteps = bc->stepList(ProjectExplorer::Constants::BUILDSTEPS_BUILD);
BuildStepList *cleanSteps = bc->stepList(ProjectExplorer::Constants::BUILDSTEPS_CLEAN);
Q_ASSERT(buildSteps);
Q_ASSERT(cleanSteps);
ROSMakeStep *makeStep = new ROSMakeStep(buildSteps);
buildSteps->insertStep(0, makeStep);
makeStep->setBuildTarget(QLatin1String("all"), /* on = */ true);
ROSMakeStep *cleanMakeStep = new ROSMakeStep(cleanSteps);
cleanSteps->insertStep(0, cleanMakeStep);
cleanMakeStep->setBuildTarget(QLatin1String("clean"), /* on = */ true);
cleanMakeStep->setClean(true);
//Source the workspace to setup initial environment variables for build configuration.
bc->sourceWorkspace();
return bc;
}
bool ROSBuildConfigurationFactory::canClone(const Target *parent, BuildConfiguration *source) const
{
if (!canHandle(parent))
return false;
return source->id() == ROS_BC_ID;
}
BuildConfiguration *ROSBuildConfigurationFactory::clone(Target *parent, BuildConfiguration *source)
{
if (!canClone(parent, source))
return 0;
return new ROSBuildConfiguration(parent, qobject_cast<ROSBuildConfiguration *>(source));
}
bool ROSBuildConfigurationFactory::canRestore(const Target *parent, const QVariantMap &map) const
{
if (!canHandle(parent))
return false;
return ProjectExplorer::idFromMap(map) == ROS_BC_ID;
}
BuildConfiguration *ROSBuildConfigurationFactory::restore(Target *parent, const QVariantMap &map)
{
if (!canRestore(parent, map))
return 0;
ROSBuildConfiguration *bc(new ROSBuildConfiguration(parent));
if (bc->fromMap(map))
return bc;
delete bc;
return 0;
}
bool ROSBuildConfigurationFactory::canHandle(const Target *t) const
{
if (!t->project()->supportsKit(t->kit()))
return false;
return qobject_cast<ROSProject *>(t->project());
}
ROSBuildInfo *ROSBuildConfigurationFactory::createBuildInfo(const Kit *k,
const QString &projectPath,
BuildType type) const
{
ROSBuildInfo *info = new ROSBuildInfo(this);
info->kitId = k->id();
info->buildDirectory = Project::projectDirectory(Utils::FileName::fromString(projectPath)).appendPath(tr("build"));
switch (type) {
case BuildTypeNone:
info->displayName = tr("Default");
info->typeName = tr("Build");
break;
case BuildTypeDebug:
info->arguments = QLatin1String("-DCMAKE_BUILD_TYPE=Debug");
info->typeName = tr("Debug");
info->displayName = info->typeName;
info->buildType = BuildConfiguration::Debug;
break;
case BuildTypeRelease:
info->arguments = QLatin1String("-DCMAKE_BUILD_TYPE=Release");
info->typeName = tr("Release");
info->displayName = info->typeName;
info->buildType = BuildConfiguration::Release;
break;
case BuildTypeMinSizeRel:
info->arguments = QLatin1String("-DCMAKE_BUILD_TYPE=MinSizeRel");
info->typeName = tr("Minimum Size Release");
info->displayName = info->typeName;
info->buildType = BuildConfiguration::Release;
break;
case BuildTypeRelWithDebInfo:
info->arguments = QLatin1String("-DCMAKE_BUILD_TYPE=RelWithDebInfo");
info->typeName = tr("Release with Debug Information");
info->displayName = info->typeName;
info->buildType = BuildConfiguration::Profile;
break;
default:
QTC_CHECK(false);
break;
}
return info;
}
BuildConfiguration::BuildType ROSBuildConfiguration::buildType() const
{
if (m_initialArguments == QLatin1String("-DCMAKE_BUILD_TYPE=Debug"))
{
return Debug;
}
else if ((m_initialArguments == QLatin1String("-DCMAKE_BUILD_TYPE=Debug")) || (m_initialArguments == QLatin1String("-DCMAKE_BUILD_TYPE=MinSizeRel")))
{
return Release;
}
else if (m_initialArguments == QLatin1String("-DCMAKE_BUILD_TYPE=RelWithDebInfo"))
{
return Profile;
}
else
{
return Unknown;
}
}
////////////////////////////////////////////////////////////////////////////////////
// ROSBuildSettingsWidget
////////////////////////////////////////////////////////////////////////////////////
ROSBuildSettingsWidget::ROSBuildSettingsWidget(ROSBuildConfiguration *bc)
: m_buildConfiguration(bc)
{
m_ui = new Ui::ROSBuildConfiguration;
m_ui->setupUi(this);
// Get list of install ros distributions
m_ui->ros_distribution_comboBox->addItems(ROSUtils::installedDistributions());
m_ui->ros_distribution_comboBox->setCurrentIndex(m_ui->ros_distribution_comboBox->findText(bc->rosDistribution()));
connect(m_ui->source_pushButton, SIGNAL(clicked()),
this, SLOT(on_source_pushButton_clicked()));
connect(m_ui->ros_distribution_comboBox, SIGNAL(currentIndexChanged(QString)),
this, SLOT(on_ros_distribution_comboBox_currentIndexChanged(QString)));
setDisplayName(tr("ROS Manager"));
}
ROSBuildSettingsWidget::~ROSBuildSettingsWidget()
{
delete m_ui;
}
void ROSBuildSettingsWidget::on_source_pushButton_clicked()
{
m_buildConfiguration->sourceWorkspace();
}
void ROSBuildSettingsWidget::on_ros_distribution_comboBox_currentIndexChanged(const QString &arg1)
{
m_buildConfiguration->setROSDistribution(arg1);
}
////////////////////////////////////////////////////////////////////////////////////
// ROSBuildEnvironmentWidget
////////////////////////////////////////////////////////////////////////////////////
ROSBuildEnvironmentWidget::ROSBuildEnvironmentWidget(BuildConfiguration *bc)
: m_buildConfiguration(0)
{
QVBoxLayout *vbox = new QVBoxLayout(this);
vbox->setMargin(0);
m_clearSystemEnvironmentCheckBox = new QCheckBox(this);
m_clearSystemEnvironmentCheckBox->setText(tr("Clear system environment"));
m_buildEnvironmentWidget = new EnvironmentWidget(this, m_clearSystemEnvironmentCheckBox);
vbox->addWidget(m_buildEnvironmentWidget);
connect(m_buildEnvironmentWidget, SIGNAL(userChangesChanged()),
this, SLOT(environmentModelUserChangesChanged()));
connect(m_clearSystemEnvironmentCheckBox, SIGNAL(toggled(bool)),
this, SLOT(clearSystemEnvironmentCheckBoxClicked(bool)));
m_buildConfiguration = bc;
connect(m_buildConfiguration->target(), SIGNAL(environmentChanged()),
this, SLOT(environmentChanged()));
m_clearSystemEnvironmentCheckBox->setChecked(!m_buildConfiguration->useSystemEnvironment());
m_buildEnvironmentWidget->setBaseEnvironment(m_buildConfiguration->baseEnvironment());
m_buildEnvironmentWidget->setBaseEnvironmentText(m_buildConfiguration->baseEnvironmentText());
m_buildEnvironmentWidget->setUserChanges(m_buildConfiguration->userEnvironmentChanges());
setDisplayName(tr("Build Environment"));
}
void ROSBuildEnvironmentWidget::environmentModelUserChangesChanged()
{
m_buildConfiguration->setUserEnvironmentChanges(m_buildEnvironmentWidget->userChanges());
}
void ROSBuildEnvironmentWidget::clearSystemEnvironmentCheckBoxClicked(bool checked)
{
m_buildConfiguration->setUseSystemEnvironment(!checked);
m_buildEnvironmentWidget->setBaseEnvironment(m_buildConfiguration->baseEnvironment());
m_buildEnvironmentWidget->setBaseEnvironmentText(m_buildConfiguration->baseEnvironmentText());
}
void ROSBuildEnvironmentWidget::environmentChanged()
{
m_buildEnvironmentWidget->setBaseEnvironment(m_buildConfiguration->baseEnvironment());
m_buildEnvironmentWidget->setBaseEnvironmentText(m_buildConfiguration->baseEnvironmentText());
m_buildEnvironmentWidget->setUserChanges(m_buildConfiguration->userEnvironmentChanges());
}
} // namespace Internal
} // namespace GenericProjectManager
|
/*
* This program is to illustrate concept of call by reference.
* In this swap function is used.
*/
#include <iostream>
using namespace std;
void swap(int &a,int &b){ // swap function which have call by reference concept so it will take address as parameter.
int temp=a;
a=b;
b=temp;
}
int main(){
int a=10,b=20;
cout<<"Values before swapping : \nA = "<<a<<" B = "<<b<<endl;
swap(a,b); // calling swap function. Any change in this function variable will directly affect on main function variables.
cout<<"Values after swapping : \nA = "<<a<<" B = "<<b<<endl;
return 0;
}
|
#include<bits/stdc++.h>
using namespace std;
int main(){
int t;
cin>>t;
while(t--){
long n;
cin>>n;
vector<long>arr(n);
vector<long>marr(n);
for(long i=0; i<n; i++){
cin>>arr[i];
}
marr[0] = arr[0];
for(long i=1;i<n; i++){
marr[i] = min(marr[i-1],arr[i]);
}
long long count=0;
for(long i=0; i<n; i++){
count+=marr[i];
}
cout<<count<<"\n";
}
return 0;
}
|
#include<bits/stdc++.h>
using namespace std;
string solve(string input)
{
int li,ri;
int max_size = 0;
for(int i=0;i<input.size();i++)
{
// odd length
string temp;
int left = i;
int count = 0;
int right = i;
while(left>=0 && right <input.size() && input[left]==input[right])
{
count = right - left + 1;
if(count > max_size)
{
max_size = count;
li = left;
ri = right;
}
left--;
right++;
}
// even length
left = i;
right = i+1;
count = 0;
while(left >=0 && right < input.size() && input[left]==input[right])
{
count = right - left + 1;
if(count > max_size)
{
max_size = count;
li = left;
ri = right;
}
left--;
right++;
}
}
return input.substr(li,max_size);
}
bool check(string input)
{
int i=0;
int j=input.size()-1;
while(i<=j && i<input.size() && j>=0)
{
if(input[i]!=input[j])
{
return false;
}
i++;
j--;
}
return true;
}
// o(n^3) time outer for loop o(n2)* check palindrome funcion o(n)
string solve2(string input)
{
string max_;
int max_size = 0;
for(int i=0;i<input.size()-1;i++)
{
string temp = "";
temp+=input[i];
for(int j=i;j<input.size();j++)
{
temp=temp+input[j];
// check palindrome
if(check(temp))
{
if(temp.size() > max_size)
{
max_size = temp.size();
max_ = temp;
}
}
}
}
return max_;
}
int main()
{
int t;
cin >> t;
while(t--)
{
string input;
cin >> input;
cout << solve(input) << endl;
cout << solve2(input) << endl;
}
return 0;
}
|
#include <boost/optional.hpp>
#include <cmath>
#include <ctime>
#include <iostream>
#include <vector>
boost::optional<int> get_even_random_number() {
int i = std::rand();
return (i % 2 == 0) ? i : boost::optional<int>{};
}
boost::optional<int> get_even_random_number2() {
int i = std::rand();
return boost::optional<int>{i % 2 == 0, i};
}
boost::optional<int> get_even_random_number3() {
int i = std::rand();
return boost::make_optional(i % 2 == 0, i);
}
std::vector<std::string> names = {"hello"};
std::vector<std::string> values = {"world"};
boost::optional<std::string&> getParam(const std::string &name) {
for (auto i = 0; i < names.size(); i++) {
if (names[i] == name) {
return values[i];
}
}
return boost::optional<std::string&>{};
}
int main() {
std::srand(static_cast<unsigned int>(std::time(nullptr)));
boost::optional<int> i = get_even_random_number();
if (i) {
std::cout << std::sqrt(static_cast<float>(*i)) << '\n';
}
i = get_even_random_number2();
if (i.is_initialized()) {
std::cout << std::sqrt(static_cast<float>(i.get())) << '\n';
}
i = get_even_random_number3();
double d = i.get_value_or(0);
std::cout << std::sqrt(d) << '\n';
auto val = getParam("hello");
if (val) {
std::cout << val.get() << '\n';
}
val = getParam("world");
if (!val) {
std::cout << "param does not exist for world" << '\n';
}
return 0;
}
|
// C++ for the Windows Runtime vv1.0.170303.6
// Copyright (c) 2017 Microsoft Corporation. All rights reserved.
#pragma once
#include "Windows.System.Power.2.h"
WINRT_EXPORT namespace winrt {
namespace Windows::System::Power {
struct BackgroundEnergyManager
{
BackgroundEnergyManager() = delete;
static uint32_t LowUsageLevel();
static uint32_t NearMaxAcceptableUsageLevel();
static uint32_t MaxAcceptableUsageLevel();
static uint32_t ExcessiveUsageLevel();
static uint32_t NearTerminationUsageLevel();
static uint32_t TerminationUsageLevel();
static uint32_t RecentEnergyUsage();
static uint32_t RecentEnergyUsageLevel();
static event_token RecentEnergyUsageIncreased(const Windows::Foundation::EventHandler<Windows::Foundation::IInspectable> & handler);
using RecentEnergyUsageIncreased_revoker = factory_event_revoker<IBackgroundEnergyManagerStatics>;
static RecentEnergyUsageIncreased_revoker RecentEnergyUsageIncreased(auto_revoke_t, const Windows::Foundation::EventHandler<Windows::Foundation::IInspectable> & handler);
static void RecentEnergyUsageIncreased(event_token token);
static event_token RecentEnergyUsageReturnedToLow(const Windows::Foundation::EventHandler<Windows::Foundation::IInspectable> & handler);
using RecentEnergyUsageReturnedToLow_revoker = factory_event_revoker<IBackgroundEnergyManagerStatics>;
static RecentEnergyUsageReturnedToLow_revoker RecentEnergyUsageReturnedToLow(auto_revoke_t, const Windows::Foundation::EventHandler<Windows::Foundation::IInspectable> & handler);
static void RecentEnergyUsageReturnedToLow(event_token token);
};
struct ForegroundEnergyManager
{
ForegroundEnergyManager() = delete;
static uint32_t LowUsageLevel();
static uint32_t NearMaxAcceptableUsageLevel();
static uint32_t MaxAcceptableUsageLevel();
static uint32_t ExcessiveUsageLevel();
static uint32_t RecentEnergyUsage();
static uint32_t RecentEnergyUsageLevel();
static event_token RecentEnergyUsageIncreased(const Windows::Foundation::EventHandler<Windows::Foundation::IInspectable> & handler);
using RecentEnergyUsageIncreased_revoker = factory_event_revoker<IForegroundEnergyManagerStatics>;
static RecentEnergyUsageIncreased_revoker RecentEnergyUsageIncreased(auto_revoke_t, const Windows::Foundation::EventHandler<Windows::Foundation::IInspectable> & handler);
static void RecentEnergyUsageIncreased(event_token token);
static event_token RecentEnergyUsageReturnedToLow(const Windows::Foundation::EventHandler<Windows::Foundation::IInspectable> & handler);
using RecentEnergyUsageReturnedToLow_revoker = factory_event_revoker<IForegroundEnergyManagerStatics>;
static RecentEnergyUsageReturnedToLow_revoker RecentEnergyUsageReturnedToLow(auto_revoke_t, const Windows::Foundation::EventHandler<Windows::Foundation::IInspectable> & handler);
static void RecentEnergyUsageReturnedToLow(event_token token);
};
struct PowerManager
{
PowerManager() = delete;
static Windows::System::Power::EnergySaverStatus EnergySaverStatus();
static event_token EnergySaverStatusChanged(const Windows::Foundation::EventHandler<Windows::Foundation::IInspectable> & handler);
using EnergySaverStatusChanged_revoker = factory_event_revoker<IPowerManagerStatics>;
static EnergySaverStatusChanged_revoker EnergySaverStatusChanged(auto_revoke_t, const Windows::Foundation::EventHandler<Windows::Foundation::IInspectable> & handler);
static void EnergySaverStatusChanged(event_token token);
static Windows::System::Power::BatteryStatus BatteryStatus();
static event_token BatteryStatusChanged(const Windows::Foundation::EventHandler<Windows::Foundation::IInspectable> & handler);
using BatteryStatusChanged_revoker = factory_event_revoker<IPowerManagerStatics>;
static BatteryStatusChanged_revoker BatteryStatusChanged(auto_revoke_t, const Windows::Foundation::EventHandler<Windows::Foundation::IInspectable> & handler);
static void BatteryStatusChanged(event_token token);
static Windows::System::Power::PowerSupplyStatus PowerSupplyStatus();
static event_token PowerSupplyStatusChanged(const Windows::Foundation::EventHandler<Windows::Foundation::IInspectable> & handler);
using PowerSupplyStatusChanged_revoker = factory_event_revoker<IPowerManagerStatics>;
static PowerSupplyStatusChanged_revoker PowerSupplyStatusChanged(auto_revoke_t, const Windows::Foundation::EventHandler<Windows::Foundation::IInspectable> & handler);
static void PowerSupplyStatusChanged(event_token token);
static int32_t RemainingChargePercent();
static event_token RemainingChargePercentChanged(const Windows::Foundation::EventHandler<Windows::Foundation::IInspectable> & handler);
using RemainingChargePercentChanged_revoker = factory_event_revoker<IPowerManagerStatics>;
static RemainingChargePercentChanged_revoker RemainingChargePercentChanged(auto_revoke_t, const Windows::Foundation::EventHandler<Windows::Foundation::IInspectable> & handler);
static void RemainingChargePercentChanged(event_token token);
static Windows::Foundation::TimeSpan RemainingDischargeTime();
static event_token RemainingDischargeTimeChanged(const Windows::Foundation::EventHandler<Windows::Foundation::IInspectable> & handler);
using RemainingDischargeTimeChanged_revoker = factory_event_revoker<IPowerManagerStatics>;
static RemainingDischargeTimeChanged_revoker RemainingDischargeTimeChanged(auto_revoke_t, const Windows::Foundation::EventHandler<Windows::Foundation::IInspectable> & handler);
static void RemainingDischargeTimeChanged(event_token token);
};
}
}
|
//
// Created by alex on 9/26/19.
//
#ifndef ALG_LAB1_MAIN_H
#define ALG_LAB1_MAIN_H
#include <cstdlib>
#include <bits/stdc++.h>
#define WrongFormatException 11000
#define UnidentifiedOperatorException 12000
#define VariableCountingException 13000
class AtomicList;
using namespace std;
union Content {
AtomicList* child;
struct Operand {
char variable;
double num;
} operand;
};
class AtomicList {
private:
char algOperator;
bool isUni;
bool isFilled;
bool isFirstNum;
Content firstOperand;
bool isSecondNum;
Content secondOperand;
double bindVariable(string &data, char c);
bool isOperator(char c);
public:
explicit AtomicList(string &expression, unsigned long recursivePosition = 0);
virtual ~AtomicList();
void fill(string &data);
void toFile(string &fileSign, int recurrentCounter = 0);
double count(string &fileSign, int recurrentCounter = 0);
};
#endif //ALG_LAB1_MAIN_H
|
#include <cstdio>
#include <climits>
#include <cmath>
#include <iostream>
#include <algorithm>
#include <map>
#include <set>
#include <vector>
using namespace std;
const int MAX_N = 15;
const int MAX_M = 15;
const int INF = std::numeric_limits<int>::max(); //2,147,483,647 == 2^31 -1
int dp[2][1 << MAX_M];
//INPUT
int n,m,M;
bool color[MAX_N][MAX_M]; // false:white, true:black
void solve(){
int *crt = dp[0], *next = dp[1];
crt[0] = 1;
for(int i = n-1; i >= 0; i--){
for(int j = m-1; j >= 0; j--){
for(int used = 0; used < 1<<m; used++){
if( (used >> j & 1) || color[i][j]) {
next[used] = crt[used & ~(1 << j)];
} else {
int res = 0;
//Yoko
if ( j+1 < m && !(used >> (j+1) & 1) && !color[i][j+1]){
res += crt[used | 1 << (j+1)];
}
//Tate
if ( i+1 < n && !color[i+1][j]){
res += crt[used | 1 << j];
}
next[used] = res % M;
}
}
swap(crt, next);
}
}
printf("%d\n", crt[0]);
}
int main(){
solve();
return 0;
}
|
#ifndef RSIM_Adapter_H
#define RSIM_Adapter_H
/** Adapters.
*
* An adapter is an object that can be attached to a simulator to change the simulator's behavior, and then detached to
* restore the simulator to its original behavior.
*
* An example of an adapter is TraceIO, which monitors data transfers on specified file descriptors and reports them using the
* tracing facility. In order to accomplish this, the adapter augments a number of system calls by registering additional
* callbacks for those system calls. Users can manually augment system calls, but using an adapter is a good way for the user
* to ensure that all system calls relevant to a certain kind of analysis are properly agumented.
*
* Various subclasses of TraceIO add additional features, such as automatically enabling and disabling file descriptors of
* various types as they are created and closed. For instance, RSIM_Adapter::TraceFileIO traces normal files by tracking
* sys_open(), sys_creat(), sys_close(), etc.
*
* More than one adapter can be attached to a simulator, and a a single adapter can be attached to multiple simulators. But
* the adapter should not be destroyed until after it's detached from all simulators. See RSIM_Adapter::AdapterBase::attach() and
* RSIM_Adapter::AdapterBase::detach() for details.
*
* @section RSIM_Adapter_Example1 Example: Using an adapter
*
* @code
* RSIM_Linux32 simulator;
* RSIM_Adapter::TraceFileIO tracer;
*
* // Activate tracing for files that are already open; other files
* // will be discovered when they're opened.
* tracer.trace_fd(0); // standard input
* tracer.trace_fd(1); // standard output
* tracer.trace_fd(2); // standard error
*
* // Attach the tracing adapter to the simulator in order to modify
* // the simulator's behavior.
* tracer.attach(&simulator);
* ...
*
* // Detach the tracing adapter to restore the simulator to its
* // previous behavior.
* tracer.detach(&simulator);
* @endcode
*/
namespace RSIM_Adapter {
/** Base class for all adapters. See the RSIM_Adapter namespace for details. */
class AdapterBase {
public:
AdapterBase(): NOT_IMPLEMENTED(this) {}
virtual ~AdapterBase() {}
/** Attach this adapter to a simulator. The adapter must not be deleted until after it's detached or the simulator has
* been destroyed. In general, it is possible to attach more than one adapter to a simulator, or to attach a single
* adapter to multiple simulators.
*
* Thread safety: Thread safety is determined by the subclasses. */
virtual void attach(RSIM_Simulator*) = 0;
/** Detach this adapter from a simulator. An adapter should be detached the same number of times it was attached. When
* multiple adapters are attached to a simulator they can typically be detached in any order. Detaching an adapter
* that isn't attached isn't usually a problem--it just doesn't do anything.
*
* Thread safety: Thread safety is determined by the subclasses. */
virtual void detach(RSIM_Simulator*) = 0;
/** Returns a string that should be printed at the beginning of each line of output. The default string is typically
* the name of the adapter followed by a colon and space.
*
* Thread safety: Thread safe. */
std::string prefix() const {
return prefix_str;
}
/** Sets the string to print at the beginning of each line of output. All adapters should provide a reasonable default
* so users only need to do this if they have attached the same kind of adapter more than once and want to distinguish
* between the outputs.
*
* Thread safety: Not thread safe. Do not call if other threads are concurrently accessing this adapter. */
void prefix(const std::string &prefix) {
prefix_str = prefix;
}
protected:
/* Callback for syscalls that should be traced but aren't. These are mostly esoteric system calls that are not yet
* implemented in the simulator and so which would be pretty useless to implement for tracing. */
class NotImplemented: public RSIM_Simulator::SystemCall::Callback {
private:
AdapterBase *adapter;
public:
explicit NotImplemented(AdapterBase *adapter)
: adapter(adapter) {}
bool operator()(bool b, const Args&);
};
protected:
std::string prefix_str;
NotImplemented NOT_IMPLEMENTED;
};
/**************************************************************************************************************************
* Selective Syscall Disabling Adapter
**************************************************************************************************************************/
/** An adapter to enable/disable specific system calls.
*
* This adapter, when attached to a simulator, allows a user to enable or disable specific system calls. System calls are
* either enabled, disabled, or in a default state (either enabled or disabled depending on the constructor
* arguments). System calls are identified by call number and can be found in <asm/unistd_32.h> for the RSIM_Linux32
* simulator.
*
* Simply speaking, whenever the specimen attempts to invoke a disabled system call the call is made to appear to fail by
* returning a "Function not implemented" error. However, the adapter can be configured via a callback list which is
* executed when a system call is about to be skipped.
*
* Here's what happens in detail when the specimen tries to invoke a disabled system call:
*
* <ol>
* <li>That system call's "enter" callbacks are performed, possibly emiting system call tracing messages.</li>
* <li>A message is printed to the TRACE_MISC facility indicating that the system call is disabled.</li>
* <li>The system call return value is set to -ENOSYS ("Function not implemented"). The callbacks in the next step may
* replace this with some other return value.</li>
* <li>All user specified callbacks registered with this adapter (see get_callbacks()) are invoked on behalf of the
* system call. The list is invoked with the Boolean value initially set to false. If this callback list returns
* true then:
* <ol>
* <li>the system call is immediately enabled</li>
* <li>a message to that effect is emitted to the TRACE_MISC facility</li>
* <li>the system call will eventually execute (after the remaining pre-syscall callbacks finish and return
* true)</li>
* </ol>
* otherwise
* <ol>
* <li>The system call remains disabled</li>
* <li>All syscall "leave" callbacks run, possibly tracing the syscall return value.</li>
* </ol>
* </li>
* </ol>
*
* @section SyscallDisabler_Example1 Example: Disabling networking
*
* Here's how to make it impossible for a non-root specimen to make a network connection. The sys_socketcall()
* encapsulates all socket operations on x86 Linux: socket, bind, listen, connect, accept, send, recv, etc. So disabling
* that one system call disables any ability for the specimen to connect to the network.
*
* @code
* // Leave all system calls enabled by default
* RSIM_Adapter::SyscallDisabler no_network(true);
*
* // Give the adapter a name other than SyscallDisabler. This makes the
* // reason-for-disabled more obvious in the tracing output.
* no_network.prefix("NoNetwork: ");
*
* // Disable system calls that are required to open a network connection
* no_network.disable_syscall(102); // 102 is sys_socketcall
*
* // Attach the adapter to the simulator
* no_network.attach(simulator);
* @endcode
*
* The output, when the simulator is run with "--debug=syscall", may look something like this:
* @verbatim
2782:1 1.892 0x401162b2[362543]: socket[102](PF_INET, SOCK_STREAM, IPPROTO_TCP) <socket continued below>
2782:1 1.892 0x401162b2[362543]: NoNetwork: syscall 102 is disabled
2782:1 1.892 0x401162b2[362543]: <socket resumed> = -38 ENOSYS (Function not implemented)
2782:1 1.904 0x401059be[364084]: write[4](2, 0xbfffb684 [Can't get socket], 16) = 16
2782:1 1.925 0x401059be[367112]: write[4](2, 0xbfffb23c [ : Function not implemented\n], 28) = 28
2782:1 1.934 0x401058d7[368842]: close[6](-1) = -9 EBADF (Bad file descriptor)
2782:1 1.957 0x400d1bef[371854]: exit_group[252](1) = <throwing Exit>
2782:1 1.957 0x400d1bef[371854]: this thread is terminating (for entire process) @endverbatim
*
* @section SyscallDisabler_Example2 Example: Interactive enabling
*
* By default, if the specimen attempts to invoke a disabled system call the call is simply skipped and the EAX register
* is adjusted to make it appear as if the error "Function not implemented" was returned. However, the adapter allows
* disabled system calls to be enabled. This is accomplished by registering a callback with the adapter. The callback
* should return true to enable the system call.
*
* This example initialially disables all system calls, and then queries the user about whether each call should be
* invoked as the system call is reached. This example is not thread safe.
*
* @code
* struct Ask: public RSIM_Simulator::SystemCall::Callback {
* std::set<int> asked; // syscalls we asked about
* bool operator()(bool syscall_enabled, const Args &args) {
* if (asked.find(args.callno)==asked.end()) {
* asked.insert(args.callno);
* fprintf(stderr, "System call %d is currently disabled. "
* "What should I do? (s=skip, e=enable) [s] ", args.callno);
* char buf[200];
* if (fgets(buf, sizeof buf, stdin) && buf[0]=='e')
* syscall_enabled = true;
* }
* return syscall_enabled;
* }
* };
*
* static RSIM_Adapter::SyscallDisabler disabler(false); // disable all system calls
* disabler.get_callbacks().append(new Ask); // callback for disabled syscalls
* disabler.attach(&sim); // modify the simulator's behavior
* @endcode
*/
class SyscallDisabler: public AdapterBase {
public:
/** Constructor that sets default state. The default state, @p dflt, is used as the state for system calls that have
* been neither explicitly enabled nor explicitly disabled. */
explicit SyscallDisabler(bool dflt)
: syscall_cb(NULL), dflt_state(dflt) {
RTS_mutex_init(&mutex, RTS_LAYER_RSIM_SYSCALLDISABLER_OBJ, NULL);
prefix("SyscallDisabler: ");
}
virtual ~SyscallDisabler() {
delete syscall_cb;
}
virtual void attach(RSIM_Simulator *sim); /**< See base class. */
virtual void detach(RSIM_Simulator *sim); /**< See base class. */
/** Enable a system call. The optional @p state argument can be used to disable the system call (when false), or a
* system call can be disabled with disable_syscall(). The specified system call number, @p callno, need not reference
* a system call that's actually defined yet.
*
* Thread safety: This method is thread safe. */
void enable_syscall(int callno, bool state=true);
/** Disable a system call. A system call can also be disabled by passing false as the @p state argument of the
* enable_syscall() method. The specified system call number, @p callno, need not reference a system call that's
* actually defined yet.
*
* Thread safety: This method is thread safe. */
void disable_syscall(int callno) {
enable_syscall(callno, false);
}
/** Set the default state of system calls. If a system call has not been explicitly enabled or disabled, then its
* state is the default state set by this method or by the constructor.
*
* Thread safety: This method is thread safe. */
void set_default(bool state);
/** Get the state of a system call. This method returns true if the system call is enabled, false if not enabled.
*
* Thread safety: This method is thread safe. */
bool is_enabled(int callno) const;
/** Callbacks for disabled system calls. This list initially has a single item: a functor that invokes the normal
* system call "enter" and "leave" boilerplate but replaces the body with code that causes the system call to return
* -ENOSYS ("Function not implemented"). The user can modify this list as they desire, perhaps to return a different
* value or to do some other system call.
*
* Thread safety: This method is thread safe and most methods on the returned object are also thread safe. */
ROSE_Callbacks::List<RSIM_Simulator::SystemCall::Callback> &get_callbacks() {
return cblist;
}
protected:
/** Callback for all system calls. */
class SyscallCB: public RSIM_Callbacks::SyscallCallback {
private:
SyscallDisabler *adapter;
public:
explicit SyscallCB(SyscallDisabler *adapter)
: adapter(adapter) {}
virtual SyscallCB *clone() { return this; }
virtual bool operator()(bool b, const Args&);
};
protected:
/* Non mutex-protected data members */
SyscallCB *syscall_cb;
mutable RTS_mutex_t mutex;
ROSE_Callbacks::List<RSIM_Simulator::SystemCall::Callback> cblist;
/* Mutex-protected data members */
bool dflt_state;
std::map<int/*callno*/, bool/*state*/> syscall_state;
};
/**************************************************************************************************************************
* I/O Tracing Adapter
**************************************************************************************************************************/
/** I/O Tracing Adapter.
*
* This adapter augments system calls related to I/O on file descriptors so that whenever data is transfered over a
* descriptor the data is also displayed in the TRACE_MISC tracing facility. Because this adapter prints data that is
* transfered, the underlying system call must be allowed to run before the transfer is logged, otherwise the adapter
* would not know how much data was actually transfered.
*
* This adapter has one function to activate/deactivate file descriptors, trace_fd(), but does not manipulate the set of
* traced descriptors itself. Subclasses of TraceIO are expected to activate/deactivate file descriptors based on other
* system calls that typically don't perform I/O, such as open(), creat(), and close(). */
class TraceIO: public AdapterBase {
public:
HexdumpFormat hd_format; /**< Format to use for hexdump() */
public:
TraceIO()
: read_cb(this, "input"), write_cb(this, "output"),
readv_cb(this, "input"), writev_cb(this, "output"),
mmap_cb(this), ftruncate_cb(this) {
RTS_mutex_init(&mutex, RTS_LAYER_RSIM_TRACEIO_OBJ, NULL);
prefix("TraceIO: ");
hd_format.prefix = " ";
hd_format.multiline = true;
}
virtual void attach(RSIM_Simulator *sim); /**< See base class. */
virtual void detach(RSIM_Simulator *sim); /**< See base class. */
/** Determines if a file descriptor is currently being traced. Returns true if the specified file descriptor is being
* traced. That is, if data transfers on that file descriptor are logged.
*
* Thread safety: This method is thread safe. */
bool is_tracing_fd(int fd);
/** Enables or disables tracing for a file descriptor.
*
* Thread safety: This method is thread safe. */
void trace_fd(int fd, bool how=true);
protected:
/* Callback for sys_read (#3), sys_write (#4), or any other system call that takes a file descriptor as the first
* argument, a buffer as the second argument, and returns the number of bytes transfered. This callback checks to see
* if the file descriptor is one that's being traced. If it is, and the system call transfered data (returned positive)
* then grab the data and dump it to the tracer's output stream. */
class ReadWriteSyscall: public RSIM_Simulator::SystemCall::Callback {
private:
TraceIO *tracer;
std::string label;
public:
explicit ReadWriteSyscall(TraceIO *tracer, const std::string &label)
: tracer(tracer), label(label) {}
bool operator()(bool b, const Args&);
};
/* Callback for vector I/O sys_readv (#145) and sys_writev (#146). If the syscall returns a positive value, then we
* traverse the iov array to read buffer addresses and sizes. We use the iov array to grab each buffer and dump it
* using hexdump. */
class ReadWriteVectorSyscall: public RSIM_Simulator::SystemCall::Callback {
private:
TraceIO *tracer;
std::string label;
public:
explicit ReadWriteVectorSyscall(TraceIO *tracer, const std::string &label)
: tracer(tracer), label(label) {}
bool operator()(bool b, const Args&);
};
/* Callback for sys_mmap2 (#90). If the fd argument is non-negative then print a message that we're not tracing mapped
* I/O for that file. */
class MmapSyscall: public RSIM_Simulator::SystemCall::Callback {
private:
TraceIO *tracer;
public:
explicit MmapSyscall(TraceIO *tracer)
: tracer(tracer) {}
bool operator()(bool b, const Args&);
};
/* Callback for sys_ftruncate prints the file descriptor and the truncation position. */
class FtruncateSyscall: public RSIM_Simulator::SystemCall::Callback {
private:
TraceIO *tracer;
public:
explicit FtruncateSyscall(TraceIO *tracer)
: tracer(tracer) {}
bool operator()(bool b, const Args&);
};
protected:
std::set<int32_t> tracefd; /* Set of file descriptors being traced. */
RTS_mutex_t mutex; /* Protects tracefd */
ReadWriteSyscall read_cb, write_cb; /* Callbacks for sys_read, sys_write, etc. */
ReadWriteVectorSyscall readv_cb, writev_cb; /* Callbacks for sys_readv and sys_writev */
MmapSyscall mmap_cb; /* Callback for sys_mmap and sys_mmap2 */
FtruncateSyscall ftruncate_cb; /* Callback for sys_ftruncate */
};
/**************************************************************************************************************************
* File I/O Tracing Adapter
**************************************************************************************************************************/
/** File I/O tracing adapter.
*
* This adapter is a specialization of TraceIO for tracing data transfers to and from files. It augments TraceIO by
* hooking into sys_open(), sys_creat(), sys_dup(), sys_dup2(), and sys_close() to automatically activate/deactivate
* tracing of particular file descriptors.
*
* Since file descriptors 0, 1, and 2 are typically open already, the user will probably need to explicitly activate these
* by invoking trace_fd(). Similarly for any other file descriptors that might already be open.
*
* @section TraceFileIO_Example1 Example
*
* The following code causes the simulator to notice when a new file is opened and will produce some I/O tracing on the
* TRACE_MISC facility.
*
* @code
* RSIM_Linux32 sim;
* RSIM_Adapter::TraceFileIO tracer;
* tracer.attach(&sim);
* @endcode
*
* If the simulator was configured with "--debug=syscall", then the output might look like this:
* @verbatim
3621:1 0.147 0x4001759d[22405]: close[6](7) <close continued below>
3621:1 0.147 0x4001759d[22405]: TraceFileIO: deactivating fd=7
3621:1 0.147 0x4001759d[22405]: <close resumed> = 0
3621:1 0.150 0x400176a1[22670]: access[33]("/etc/ld.so.nohwcap", 0) = -2 ENOENT (No such file or directory)
3621:1 0.160 0x40017564[24140]: open[5]("/lib32/libc.so.6", 0, <unused>) <open continued below>
3621:1 0.160 0x40017564[24140]: TraceFileIO: activating fd=7
3621:1 0.160 0x40017564[24140]: <open resumed> = 7
3621:1 0.161 0x400175e4[24161]: read[3](7, 0xbfffd624, 512) <read continued below>
3621:1 0.161 0x400175e4[24161]: TraceFileIO: input fd=7, nbytes=512:
0x00000000: 7f 45 4c 46 01 01 01 00 00 00 00 00 00 00 00 00 |.ELF............|
0x00000010: 03 00 03 00 01 00 00 00 5e 65 01 00 34 00 00 00 |........^e..4...|
0x00000020: 74 f6 14 00 00 00 00 00 34 00 20 00 0a 00 28 00 |t.......4. ...(.|
0x00000030: 43 00 42 00 06 00 00 00 34 00 00 00 34 00 00 00 |C.B.....4...4...|
0x00000040: 34 00 00 00 40 01 00 00 40 01 00 00 05 00 00 00 |4...@...@.......|
0x00000050: 04 00 00 00 03 00 00 00 80 79 13 00 80 79 13 00 |.........y...y..|
0x00000060: 80 79 13 00 13 00 00 00 13 00 00 00 04 00 00 00 |.y..............|
0x00000070: 01 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 |................|
0x00000080: 00 00 00 00 98 b2 14 00 98 b2 14 00 05 00 00 00 |................|
0x00000090: 00 10 00 00 01 00 00 00 fc c1 14 00 fc c1 14 00 |................|
0x000000a0: fc c1 14 00 a0 27 00 00 74 54 00 00 06 00 00 00 |.....'..tT......|
0x000000b0: 00 10 00 00 02 00 00 00 9c dd 14 00 9c dd 14 00 |................|
0x000000c0: 9c dd 14 00 f0 00 00 00 f0 00 00 00 06 00 00 00 |................|
0x000000d0: 04 00 00 00 04 00 00 00 74 01 00 00 74 01 00 00 |........t...t...|
0x000000e0: 74 01 00 00 20 00 00 00 20 00 00 00 04 00 00 00 |t... ... .......|
0x000000f0: 04 00 00 00 07 00 00 00 fc c1 14 00 fc c1 14 00 |................|
0x00000100: fc c1 14 00 08 00 00 00 2c 00 00 00 04 00 00 00 |........,.......|
0x00000110: 04 00 00 00 50 e5 74 64 94 79 13 00 94 79 13 00 |....P.td.y...y..|
0x00000120: 94 79 13 00 cc 2a 00 00 cc 2a 00 00 04 00 00 00 |.y...*...*......|
0x00000130: 04 00 00 00 51 e5 74 64 00 00 00 00 00 00 00 00 |....Q.td........|
0x00000140: 00 00 00 00 00 00 00 00 00 00 00 00 06 00 00 00 |................|
0x00000150: 04 00 00 00 52 e5 74 64 04 c2 14 00 fc c1 14 00 |....R.td........|
0x00000160: fc c1 14 00 88 1c 00 00 80 1c 00 00 04 00 00 00 |................|
0x00000170: 01 00 00 00 04 00 00 00 10 00 00 00 01 00 00 00 |................|
0x00000180: 47 4e 55 00 00 00 00 00 02 00 00 00 06 00 00 00 |GNU.............|
0x00000190: 08 00 00 00 f3 03 00 00 0a 00 00 00 00 02 00 00 |................|
0x000001a0: 0e 00 00 00 a0 30 10 44 80 20 02 01 8c 03 e6 90 |.....0.D. ......|
0x000001b0: 41 45 88 00 84 00 08 00 41 80 00 40 c0 80 00 0c |AE......A..@....|
0x000001c0: 02 0c 00 01 30 00 08 40 22 08 a6 04 88 48 36 6c |....0..@"....H6l|
0x000001d0: a0 16 30 00 26 84 80 8e 04 08 42 24 02 0c a6 a4 |..0.&.....B$....|
0x000001e0: 1a 06 63 c8 00 c2 20 01 c0 00 52 00 21 81 08 04 |..c... ...R.!...|
0x000001f0: 0a 20 20 a8 14 00 14 28 60 00 00 50 a0 ca 44 42 |. ....(`..P..DB|
3621:1 0.161 0x400175e4[24161]: <read resumed> = 512
3621:1 0.161 0x400175e4[24161]: result arg1 = 0xbfffd624 [\177ELF\001\001\001\000\000]...
@endverbatim
*/
class TraceFileIO: public TraceIO {
public:
TraceFileIO()
: open_cb(this), dup_cb(this), pipe_cb(this), close_cb(this) {
prefix("TraceFileIO: ");
}
virtual void attach(RSIM_Simulator *sim); /**< See base class. */
virtual void detach(RSIM_Simulator *sim); /**< See base class. */
protected:
/* Callback for sys_open (#5) and sys_creat (#8), which return a new file descriptor that should be traced. The file
* descriptor is added to the set of file descriptors being traced. */
class OpenSyscall: public RSIM_Simulator::SystemCall::Callback {
private:
TraceIO *tracer;
public:
explicit OpenSyscall(TraceIO *tracer)
: tracer(tracer) {}
bool operator()(bool b, const Args&);
};
/* Callback for sys_dup (#41) and sys_dup2 (#63), which return a new file descriptor that should be traced if and only
* if the file descriptor specified by the first argument is traced. */
class DupSyscall: public RSIM_Simulator::SystemCall::Callback {
private:
TraceIO *tracer;
public:
explicit DupSyscall(TraceIO *tracer)
: tracer(tracer) {}
bool operator()(bool b, const Args&);
};
/* Callback for sys_pipe (#42) which returns two new file descriptors in a 2-element array pointed to by the first
* argument. */
class PipeSyscall: public RSIM_Simulator::SystemCall::Callback {
private:
TraceIO *tracer;
public:
explicit PipeSyscall(TraceIO *tracer)
: tracer(tracer) {}
bool operator()(bool b, const Args&);
};
/* Callback for sys_close (#6) or any other system call that closes a file descriptor which is provided as the first
* argument. */
class CloseSyscall: public RSIM_Simulator::SystemCall::Callback {
private:
TraceIO *tracer;
public:
explicit CloseSyscall(TraceIO *tracer)
: tracer(tracer) {}
bool operator()(bool b, const Args&);
};
private:
OpenSyscall open_cb;
DupSyscall dup_cb;
PipeSyscall pipe_cb;
CloseSyscall close_cb;
};
/**************************************************************************************************************************
* TCP Network Tracing Adapter
**************************************************************************************************************************/
/** Not fully implemented yet. [RPM 2011-04-15] */
class TraceTcpIO: public TraceIO {
public:
TraceTcpIO() {
prefix("TraceTcpIO: ");
}
virtual void attach(RSIM_Simulator *sim); /**< See base class. */
virtual void detach(RSIM_Simulator *sim); /**< See base class. */
protected:
};
};
#endif /* !RSIM_Adapter_H !*/
|
// antchaos.cpp - verbesserte antchaos-version
// (c) 1999 Michael Fink
/*
Originaler Kommentar von Christian Strobl:
Programm, das mittels eines Graphikbeispiels verdeutlicht, wie
in vllig zuflligen Strukturen, also Chaos, pltzlich regel-
máige Muster auftauchen knnen, also Ordnung.
Das Programm fllt zuerst per Zufallsgenerator den Bildschirm
mit einer gleichen Anzahl von roten und gelben Punkten. Die
roten Punkte stellen Ameisen dar und die gelben Nahrung. An-
schlieáend werden die Ameisen per Zufallsgenerator auf dem
Bildschirm hin- und herbewegt. Stát eine Ameise auf Nahrung,
so hebt sie sie auf und nimmt sie mit, bis sie wieder auf
Nahrung trifft. Dort lát sie das alte fallen und hebt das neue
auf.
Nach einer gewissen Zeit, zeigen sich pltzlich regelmáige
Muster in der Verteilung der Nahrung auf dem Bildschirm, so
kann sich zum Beispiel die gesamte Nahrung in der Mitte des
Bildschirms ansammeln o..
Somit ist also aus vlligem Chaos ( zufllige Verteilung von
Ameisen und Nahrung, zufllige Bewegungen der Ameisen ),
schlieálich Ordnung hervorgegeangen.
*/
#define AMEISENANZAHL 2000
#define NAHRUNGSANZAHL 2000
#define ROT 4
#define GELB 14
#define GRUEN 2
#define BLAU 1
#define SCHWARZ 0
#define XMAX 320
#define YMAX 200
// -------------------------------
#include "defs.h"
#include "xmode.h"
#include <stdlib.h>
#include <conio.h>
class ant
{
xmode* xm;
word ameisen[AMEISENANZAHL][3];
word nahrung[NAHRUNGSANZAHL][2];
public:
ant();
void start();
void male_schirm();
void bewege_ameisen();
private:
void arrays_fuellen();
};
ant::ant()
{
xm = new xmode;
randomize();
arrays_fuellen();
};
void ant::start()
{
xm->on();
xm->clearpage(1);
xm->clearpage(0);
xm->setpage(0);
xm->showpage(1);
male_schirm();
xm->switchpage();
while (!kbhit())
{
// copy pixels from currently set page to currently active page
xm->pagemove(1 - xm->activepage());
bewege_ameisen();
xm->switchpage();
};
if (getch() == 0)
getch();
if (getch() == 0)
getch();
xm->off();
};
void ant::arrays_fuellen()
{
// Ameisen zufllig verteilen
for (int a = 0; a < AMEISENANZAHL; a++)
{
ameisen[a][0] = random(XMAX);
ameisen[a][1] = random(YMAX);
ameisen[a][2] = ROT;
};
// Brot zufllig verteilen
for (int n = 0; n < NAHRUNGSANZAHL; n++)
{
nahrung[n][0] = random(XMAX);
nahrung[n][1] = random(YMAX);
};
};
void ant::male_schirm()
{
for (int a = 0; a < AMEISENANZAHL; a++)
xm->setpix(ameisen[a][0], ameisen[a][1],
ameisen[a][2]);
for (int n = 0; n < NAHRUNGSANZAHL; n++)
xm->setpix(nahrung[n][0], nahrung[n][1], GELB);
};
void ant::bewege_ameisen()
{
for (int a = 0; a < AMEISENANZAHL; a++)
{
byte richtung = random(8); // 8 mgliche Richtungen
int neux = ameisen[a][0];
int neuy = ameisen[a][1];
// y
// 0 1 2 A
// Nummerierung der Richtungen: 3 X 4 |
// 5 6 7 +--> x
switch (richtung)
{
case 0: neux--; neuy--; break;
case 1: neuy--; break;
case 2: neux++; neuy--; break;
case 3: neux--; break;
case 4: neux++; break;
case 5: neux--; neuy++; break;
case 6: neuy++; break;
case 7: neux++; neuy++; break;
};
byte neufarbe = xm->getpix(neux, neuy);
// neue Position nicht innerhalb des Bildschirms
// oder Farbe des neuen Feldes nicht unbesetzt oder Nahrung
if (neux < 0 || neux >= XMAX || neuy < 0 || neuy >= YMAX ||
(neufarbe != SCHWARZ && neufarbe != GELB))
continue;
word altfarbe = ameisen[a][2];
// altes Objekt lschen bzw. alte Nahrung ablegen
xm->setpix(ameisen[a][0], ameisen[a][1],
altfarbe == BLAU ? GELB : SCHWARZ);
switch (altfarbe)
{
case ROT: // Ameise ohne Nahrung
if (neufarbe == SCHWARZ) // neues Feld unbesetzt
neufarbe = ROT;
else // neues Feld mit Nahrung besetzt
neufarbe = GRUEN;
break;
default: // Ameise vorher grn oder blau, mit Nahrung
if (neufarbe == SCHWARZ) // neues Feld unbesetzt
{
xm->setpix(ameisen[a][0], ameisen[a][1], SCHWARZ);
// neue Ameise wieder mit Last (grn) malen
neufarbe = GRUEN;
}
else // neues Feld mit Nahrung besetzt
{
xm->setpix(ameisen[a][0], ameisen[a][1], GELB);
// neue Ameise beim Umladen (blau) malen
neufarbe = BLAU;
}
break;
};
// neue Ameise setzen
ameisen[a][0] = neux;
ameisen[a][1] = neuy;
ameisen[a][2] = neufarbe;
xm->setpix(neux, neuy, neufarbe);
};
};
void main()
{
ant a;
a.start();
};
|
#ifndef CHEQUING_ACCOUNT_H
#define CHEQUING_ACCOUNT_H
#include "Account.h" // Base class: Account.h
class Chequing_Account : public Account
{
friend std::ostream &operator<<(std::ostream &os, const Chequing_Account &account);
private:
static constexpr const char *def_name = "Unnamed Chequing Account";
static constexpr double def_balance = 0.0;
public:
Chequing_Account(std::string name = def_name, double balance = def_balance);
bool withdraw(double amount);
};
#endif // CHEQUING_ACCOUNT_H
|
/*
* UAE
*
* mp3 decoder helper class
*
* Copyright 2010 Toni Wilen
*
*/
#include "sysconfig.h"
#include "sysdeps.h"
#include <zfile.h>
#include <mp3decoder.h>
#include <windows.h>
#include <mmreg.h>
#include <msacm.h>
#define MP3_BLOCK_SIZE 522
static int mp3_bitrates[] = {
0, 32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448, -1,
0, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, -1,
0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, -1,
0, 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256, -1,
0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160, -1
};
static int mp3_frequencies[] = {
44100, 48000, 32000, 0,
22050, 24000, 16000, 0,
11025, 12000, 8000, 0
};
static int mp3_samplesperframe[] = {
384, 384, 384,
1152, 1152, 1152,
1152, 576, 576
};
struct mpegaudio_header
{
int ver;
int layer;
int bitrate;
int freq;
int padding;
int iscrc;
int samplerate;
int channelmode;
int modeext;
int isstereo;
int framesize;
int firstframe;
};
static int get_header(struct zfile *zf, struct mpegaudio_header *head, bool keeplooking)
{
for (;;) {
int bitindex, bitrateidx;
uae_u8 header[4];
if (zfile_fread(header, sizeof header, 1, zf) != 1)
return -1;
if (header[0] != 0xff || ((header[1] & (0x80 | 0x40 | 0x20)) != (0x80 | 0x40 | 0x20))) {
zfile_fseek(zf, -3, SEEK_CUR);
if (keeplooking)
continue;
return 0;
}
if (head->firstframe < 0)
head->firstframe = zfile_ftell32(zf);
head->ver = (header[1] >> 3) & 3;
if (head->ver == 1) {
write_log(_T("MP3: ver==1?!\n"));
return 0;
}
if (head->ver == 0)
head->ver = 2;
else if (head->ver == 2)
head->ver = 1;
else if (head->ver == 3)
head->ver = 0;
head->layer = 4 - ((header[1] >> 1) & 3);
if (head->layer == 4) {
write_log(_T("MP3: layer==4?!\n"));
if (keeplooking)
continue;
return 0;
}
head->iscrc = ((header[1] >> 0) & 1) ? 0 : 2;
bitrateidx = (header[2] >> 4) & 15;
head->freq = mp3_frequencies[(header[2] >> 2) & 3];
if (!head->freq) {
write_log(_T("MP3: reserved frequency?!\n"));
if (keeplooking)
continue;
return 0;
}
head->channelmode = (header[3] >> 6) & 3;
head->modeext = (header[3] >> 4) & 3;
head->isstereo = head->channelmode != 3;
if (head->ver == 0) {
bitindex = head->layer - 1;
} else {
if (head->layer == 1)
bitindex = 3;
else
bitindex = 4;
}
head->bitrate = mp3_bitrates[bitindex * 16 + bitrateidx] * 1000;
if (head->bitrate <= 0) {
write_log(_T("MP3: reserved bitrate?!\n"));
return 0;
}
head->padding = (header[2] >> 1) & 1;
head->samplerate = mp3_samplesperframe[(head->layer - 1) * 3 + head->ver];
switch (head->layer)
{
case 1:
head->framesize = (12 * head->bitrate / head->freq + head->padding) * 4;
break;
case 2:
case 3:
head->framesize = 144 * head->bitrate / head->freq + head->padding;
break;
}
if (head->framesize <= 4) {
write_log(_T("MP3: too small frame size?!\n"));
if (keeplooking)
continue;
return 0;
}
return 1;
}
}
mp3decoder::~mp3decoder()
{
if (g_mp3stream)
acmStreamClose((HACMSTREAM)g_mp3stream, 0);
g_mp3stream = NULL;
}
mp3decoder::mp3decoder(struct zfile *zf)
{
MMRESULT mmr;
LPWAVEFORMATEX waveFormat, inwave;
LPMPEGLAYER3WAVEFORMAT mp3format = NULL;
LPMPEG1WAVEFORMAT mp2format = NULL;
DWORD maxFormatSize;
struct mpegaudio_header head;
if (get_header(zf, &head, true) <= 0) {
write_log(_T("MPA: couldn't find mpeg audio header\n"));
throw exception();
}
// find the biggest format size
maxFormatSize = 0;
mmr = acmMetrics(NULL, ACM_METRIC_MAX_SIZE_FORMAT, &maxFormatSize);
// define desired output format
waveFormat = (LPWAVEFORMATEX)LocalAlloc(LPTR, maxFormatSize);
waveFormat->wFormatTag = WAVE_FORMAT_PCM;
waveFormat->nChannels = head.isstereo ? 2 : 1;
waveFormat->nSamplesPerSec = 44100;
waveFormat->wBitsPerSample = 16; // 16 bits
waveFormat->nBlockAlign = 2 * waveFormat->nChannels;
waveFormat->nAvgBytesPerSec = waveFormat->nBlockAlign * waveFormat->nSamplesPerSec; // byte-rate
waveFormat->cbSize = 0; // no more data to follow
if (head.layer == 3) {
// define MP3 input format
mp3format = (LPMPEGLAYER3WAVEFORMAT)LocalAlloc(LPTR, maxFormatSize);
inwave = &mp3format->wfx;
inwave->cbSize = MPEGLAYER3_WFX_EXTRA_BYTES;
inwave->wFormatTag = WAVE_FORMAT_MPEGLAYER3;
mp3format->fdwFlags = MPEGLAYER3_FLAG_PADDING_OFF;
mp3format->nBlockSize = MP3_BLOCK_SIZE; // voodoo value #1
mp3format->nFramesPerBlock = 1; // MUST BE ONE
mp3format->nCodecDelay = 1393; // voodoo value #2
mp3format->wID = MPEGLAYER3_ID_MPEG;
} else {
// There is no Windows MP2 ACM codec. This code is totally useless.
mp2format = (LPMPEG1WAVEFORMAT)LocalAlloc(LPTR, maxFormatSize);
inwave = &mp2format->wfx;
mp2format->dwHeadBitrate = head.bitrate;
mp2format->fwHeadMode = head.isstereo ? (head.channelmode == 1 ? ACM_MPEG_JOINTSTEREO : ACM_MPEG_STEREO) : ACM_MPEG_SINGLECHANNEL;
mp2format->fwHeadLayer = head.layer == 1 ? ACM_MPEG_LAYER1 : ACM_MPEG_LAYER2;
mp2format->fwHeadFlags = ACM_MPEG_ID_MPEG1;
mp2format->fwHeadModeExt = 0x0f;
mp2format->wHeadEmphasis = 1;
inwave->cbSize = sizeof(MPEG1WAVEFORMAT) - sizeof(WAVEFORMATEX);
inwave->wFormatTag = WAVE_FORMAT_MPEG;
}
inwave->nBlockAlign = 1;
inwave->wBitsPerSample = 0; // MUST BE ZERO
inwave->nChannels = head.isstereo ? 2 : 1;
inwave->nSamplesPerSec = head.freq;
inwave->nAvgBytesPerSec = head.bitrate / 8;
mmr = acmStreamOpen((LPHACMSTREAM)&g_mp3stream, // open an ACM conversion stream
NULL, // querying all ACM drivers
(LPWAVEFORMATEX)inwave, // converting from MP3
waveFormat, // to WAV
NULL, // with no filter
0, // or async callbacks
0, // (and no data for the callback)
0 // and no flags
);
LocalFree(mp3format);
LocalFree(mp2format);
LocalFree(waveFormat);
if (mmr != MMSYSERR_NOERROR) {
write_log(_T("MP3: couldn't open ACM mp3 decoder, %d\n"), mmr);
throw exception();
}
}
mp3decoder::mp3decoder()
{
MMRESULT mmr;
LPWAVEFORMATEX waveFormat;
LPMPEGLAYER3WAVEFORMAT mp3format;
DWORD maxFormatSize;
// find the biggest format size
maxFormatSize = 0;
mmr = acmMetrics(NULL, ACM_METRIC_MAX_SIZE_FORMAT, &maxFormatSize);
// define desired output format
waveFormat = (LPWAVEFORMATEX)LocalAlloc(LPTR, maxFormatSize);
waveFormat->wFormatTag = WAVE_FORMAT_PCM;
waveFormat->nChannels = 2; // stereo
waveFormat->nSamplesPerSec = 44100; // 44.1kHz
waveFormat->wBitsPerSample = 16; // 16 bits
waveFormat->nBlockAlign = 4; // 4 bytes of data at a time are useful (1 sample)
waveFormat->nAvgBytesPerSec = 4 * 44100; // byte-rate
waveFormat->cbSize = 0; // no more data to follow
// define MP3 input format
mp3format = (LPMPEGLAYER3WAVEFORMAT)LocalAlloc(LPTR, maxFormatSize);
mp3format->wfx.cbSize = MPEGLAYER3_WFX_EXTRA_BYTES;
mp3format->wfx.wFormatTag = WAVE_FORMAT_MPEGLAYER3;
mp3format->wfx.nChannels = 2;
mp3format->wfx.nAvgBytesPerSec = 128 * (1024 / 8); // not really used but must be one of 64, 96, 112, 128, 160kbps
mp3format->wfx.wBitsPerSample = 0; // MUST BE ZERO
mp3format->wfx.nBlockAlign = 1; // MUST BE ONE
mp3format->wfx.nSamplesPerSec = 44100; // 44.1kHz
mp3format->fdwFlags = MPEGLAYER3_FLAG_PADDING_OFF;
mp3format->nBlockSize = MP3_BLOCK_SIZE; // voodoo value #1
mp3format->nFramesPerBlock = 1; // MUST BE ONE
mp3format->nCodecDelay = 1393; // voodoo value #2
mp3format->wID = MPEGLAYER3_ID_MPEG;
mmr = acmStreamOpen((LPHACMSTREAM)&g_mp3stream, // open an ACM conversion stream
NULL, // querying all ACM drivers
(LPWAVEFORMATEX) mp3format, // converting from MP3
waveFormat, // to WAV
NULL, // with no filter
0, // or async callbacks
0, // (and no data for the callback)
0 // and no flags
);
LocalFree(mp3format);
LocalFree(waveFormat);
if (mmr != MMSYSERR_NOERROR) {
write_log(_T("MP3: couldn't open ACM mp3 decoder, %d\n"), mmr);
throw exception();
}
}
uae_u8 *mp3decoder::get (struct zfile *zf, uae_u8 *outbuf, int maxsize)
{
MMRESULT mmr;
unsigned long rawbufsize = 0;
LPBYTE mp3buf;
LPBYTE rawbuf;
int outoffset = 0;
ACMSTREAMHEADER mp3streamHead;
HACMSTREAM h = (HACMSTREAM)g_mp3stream;
write_log(_T("MP3: decoding '%s'..\n"), zfile_getname(zf));
mmr = acmStreamSize(h, MP3_BLOCK_SIZE, &rawbufsize, ACM_STREAMSIZEF_SOURCE);
if (mmr != MMSYSERR_NOERROR) {
write_log (_T("MP3: acmStreamSize, %d\n"), mmr);
return NULL;
}
// allocate our I/O buffers
mp3buf = (LPBYTE)LocalAlloc(LPTR, MP3_BLOCK_SIZE);
rawbuf = (LPBYTE)LocalAlloc(LPTR, rawbufsize);
// prepare the decoder
ZeroMemory(&mp3streamHead, sizeof (ACMSTREAMHEADER));
mp3streamHead.cbStruct = sizeof (ACMSTREAMHEADER);
mp3streamHead.pbSrc = mp3buf;
mp3streamHead.cbSrcLength = MP3_BLOCK_SIZE;
mp3streamHead.pbDst = rawbuf;
mp3streamHead.cbDstLength = rawbufsize;
mmr = acmStreamPrepareHeader(h, &mp3streamHead, 0);
if (mmr != MMSYSERR_NOERROR) {
write_log(_T("MP3: acmStreamPrepareHeader, %d\n"), mmr);
return NULL;
}
zfile_fseek(zf, 0, SEEK_SET);
for (;;) {
size_t count = zfile_fread(mp3buf, 1, MP3_BLOCK_SIZE, zf);
if (count != MP3_BLOCK_SIZE)
break;
// convert the data
mmr = acmStreamConvert(h, &mp3streamHead, ACM_STREAMCONVERTF_BLOCKALIGN);
if (mmr != MMSYSERR_NOERROR) {
write_log(_T("MP3: acmStreamConvert, %d\n"), mmr);
return NULL;
}
if (outoffset + mp3streamHead.cbDstLengthUsed > maxsize)
break;
memcpy(outbuf + outoffset, rawbuf, mp3streamHead.cbDstLengthUsed);
outoffset += mp3streamHead.cbDstLengthUsed;
}
acmStreamUnprepareHeader(h, &mp3streamHead, 0);
LocalFree(rawbuf);
LocalFree(mp3buf);
write_log(_T("MP3: unpacked size %d bytes\n"), outoffset);
return outbuf;
}
uae_u32 mp3decoder::getsize (struct zfile *zf)
{
uae_u32 size;
int frames, sameframes;
int firstframe;
int oldbitrate;
int timelen = -1;
firstframe = -1;
oldbitrate = -1;
sameframes = -1;
frames = 0;
size = 0;
uae_u8 id3[10];
if (zfile_fread(id3, sizeof id3, 1, zf) != 1)
return 0;
if (id3[0] == 'I' && id3[1] == 'D' && id3[2] == '3' && id3[3] == 3 && id3[4] != 0xff && id3[6] < 0x80 && id3[7] < 0x80 && id3[8] < 0x80 && id3[9] < 0x80) {
int unsync = id3[5] & 0x80;
int exthead = id3[5] & 0x40;
int len = (id3[9] << 0) | (id3[8] << 7) | (id3[7] << 14) | (id3[6] << 21);
len &= 0x0fffffff;
uae_u8 *tag = xmalloc (uae_u8, len + 1);
if (zfile_fread (tag, len, 1, zf) != 1) {
xfree (tag);
return 0;
}
uae_u8 *p = tag;
if (exthead) {
int size = (p[4] << 21) | (p[5] << 14) | (p[6] << 7);
size &= 0x0fffffff;
p += size;
len -= size;
}
while (len > 0) {
int size = unsync ? (p[4] << 21) | (p[5] << 14) | (p[6] << 7) | (p[7] << 0) : (p[4] << 24) | (p[5] << 16) | (p[6] << 8) | (p[7] << 0);
size &= 0x0fffffff;
if (size > len)
break;
int compr = p[9] & 0x80;
int enc = p[9] & 0x40;
if (compr == 0 && enc == 0) {
if (!memcmp (p, "TLEN", 4)) {
uae_u8 *data = p + 10;
data[size] = 0;
if (data[0] == 0)
timelen = atol ((char*)(data + 1));
else
timelen = _tstol ((wchar_t*)(data + 1));
}
}
size += 10;
p += size;
len -= size;
}
xfree (tag);
} else {
zfile_fseek(zf, -(int)sizeof id3, SEEK_CUR);
}
for (;;) {
struct mpegaudio_header mh;
mh.firstframe = -1;
int v = get_header(zf, &mh, true);
if (v < 0)
return size;
zfile_fseek(zf, mh.framesize - 4, SEEK_CUR);
frames++;
if (timelen > 0) {
size = ((uae_u64)timelen * mh.freq * 2 * (mh.isstereo ? 2 : 1)) / 1000;
break;
}
size += mh.samplerate * 2 * (mh.isstereo ? 2 : 1);
if (mh.bitrate != oldbitrate) {
oldbitrate = mh.bitrate;
sameframes++;
}
if (sameframes == 0 && frames > 100) {
// assume this is CBR MP3
size = mh.samplerate * 2 * (mh.isstereo ? 2 : 1) * ((zfile_size32(zf) - firstframe) / ((mh.samplerate / 8 * mh.bitrate) / mh.freq));
break;
}
}
return size;
}
|
// C++ for the Windows Runtime vv1.0.170303.6
// Copyright (c) 2017 Microsoft Corporation. All rights reserved.
#pragma once
#include "base.h"
WINRT_WARNING_PUSH
#include "internal/Windows.Foundation.3.h"
#include "internal/Windows.UI.Xaml.Interop.3.h"
#include "internal/Windows.UI.Xaml.Media.Animation.3.h"
#include "internal/Windows.UI.Xaml.3.h"
#include "internal/Windows.UI.Xaml.Navigation.3.h"
#include "Windows.UI.Xaml.h"
WINRT_EXPORT namespace winrt {
namespace Windows::UI::Xaml::Navigation {
template <typename L> LoadCompletedEventHandler::LoadCompletedEventHandler(L lambda) :
LoadCompletedEventHandler(impl::make_delegate<impl_LoadCompletedEventHandler<L>, LoadCompletedEventHandler>(std::forward<L>(lambda)))
{}
template <typename F> LoadCompletedEventHandler::LoadCompletedEventHandler(F * function) :
LoadCompletedEventHandler([=](auto && ... args) { function(args ...); })
{}
template <typename O, typename M> LoadCompletedEventHandler::LoadCompletedEventHandler(O * object, M method) :
LoadCompletedEventHandler([=](auto && ... args) { ((*object).*(method))(args ...); })
{}
inline void LoadCompletedEventHandler::operator()(const Windows::Foundation::IInspectable & sender, const Windows::UI::Xaml::Navigation::NavigationEventArgs & e) const
{
check_hresult((*(abi<LoadCompletedEventHandler> **)this)->abi_Invoke(get_abi(sender), get_abi(e)));
}
template <typename L> NavigatedEventHandler::NavigatedEventHandler(L lambda) :
NavigatedEventHandler(impl::make_delegate<impl_NavigatedEventHandler<L>, NavigatedEventHandler>(std::forward<L>(lambda)))
{}
template <typename F> NavigatedEventHandler::NavigatedEventHandler(F * function) :
NavigatedEventHandler([=](auto && ... args) { function(args ...); })
{}
template <typename O, typename M> NavigatedEventHandler::NavigatedEventHandler(O * object, M method) :
NavigatedEventHandler([=](auto && ... args) { ((*object).*(method))(args ...); })
{}
inline void NavigatedEventHandler::operator()(const Windows::Foundation::IInspectable & sender, const Windows::UI::Xaml::Navigation::NavigationEventArgs & e) const
{
check_hresult((*(abi<NavigatedEventHandler> **)this)->abi_Invoke(get_abi(sender), get_abi(e)));
}
template <typename L> NavigatingCancelEventHandler::NavigatingCancelEventHandler(L lambda) :
NavigatingCancelEventHandler(impl::make_delegate<impl_NavigatingCancelEventHandler<L>, NavigatingCancelEventHandler>(std::forward<L>(lambda)))
{}
template <typename F> NavigatingCancelEventHandler::NavigatingCancelEventHandler(F * function) :
NavigatingCancelEventHandler([=](auto && ... args) { function(args ...); })
{}
template <typename O, typename M> NavigatingCancelEventHandler::NavigatingCancelEventHandler(O * object, M method) :
NavigatingCancelEventHandler([=](auto && ... args) { ((*object).*(method))(args ...); })
{}
inline void NavigatingCancelEventHandler::operator()(const Windows::Foundation::IInspectable & sender, const Windows::UI::Xaml::Navigation::NavigatingCancelEventArgs & e) const
{
check_hresult((*(abi<NavigatingCancelEventHandler> **)this)->abi_Invoke(get_abi(sender), get_abi(e)));
}
template <typename L> NavigationFailedEventHandler::NavigationFailedEventHandler(L lambda) :
NavigationFailedEventHandler(impl::make_delegate<impl_NavigationFailedEventHandler<L>, NavigationFailedEventHandler>(std::forward<L>(lambda)))
{}
template <typename F> NavigationFailedEventHandler::NavigationFailedEventHandler(F * function) :
NavigationFailedEventHandler([=](auto && ... args) { function(args ...); })
{}
template <typename O, typename M> NavigationFailedEventHandler::NavigationFailedEventHandler(O * object, M method) :
NavigationFailedEventHandler([=](auto && ... args) { ((*object).*(method))(args ...); })
{}
inline void NavigationFailedEventHandler::operator()(const Windows::Foundation::IInspectable & sender, const Windows::UI::Xaml::Navigation::NavigationFailedEventArgs & e) const
{
check_hresult((*(abi<NavigationFailedEventHandler> **)this)->abi_Invoke(get_abi(sender), get_abi(e)));
}
template <typename L> NavigationStoppedEventHandler::NavigationStoppedEventHandler(L lambda) :
NavigationStoppedEventHandler(impl::make_delegate<impl_NavigationStoppedEventHandler<L>, NavigationStoppedEventHandler>(std::forward<L>(lambda)))
{}
template <typename F> NavigationStoppedEventHandler::NavigationStoppedEventHandler(F * function) :
NavigationStoppedEventHandler([=](auto && ... args) { function(args ...); })
{}
template <typename O, typename M> NavigationStoppedEventHandler::NavigationStoppedEventHandler(O * object, M method) :
NavigationStoppedEventHandler([=](auto && ... args) { ((*object).*(method))(args ...); })
{}
inline void NavigationStoppedEventHandler::operator()(const Windows::Foundation::IInspectable & sender, const Windows::UI::Xaml::Navigation::NavigationEventArgs & e) const
{
check_hresult((*(abi<NavigationStoppedEventHandler> **)this)->abi_Invoke(get_abi(sender), get_abi(e)));
}
}
namespace impl {
template <typename D>
struct produce<D, Windows::UI::Xaml::Navigation::INavigatingCancelEventArgs> : produce_base<D, Windows::UI::Xaml::Navigation::INavigatingCancelEventArgs>
{
HRESULT __stdcall get_Cancel(bool * value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().Cancel());
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall put_Cancel(bool value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().Cancel(value);
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall get_NavigationMode(Windows::UI::Xaml::Navigation::NavigationMode * value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().NavigationMode());
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall get_SourcePageType(impl::abi_arg_out<Windows::UI::Xaml::Interop::TypeName> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().SourcePageType());
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::UI::Xaml::Navigation::INavigatingCancelEventArgs2> : produce_base<D, Windows::UI::Xaml::Navigation::INavigatingCancelEventArgs2>
{
HRESULT __stdcall get_Parameter(impl::abi_arg_out<Windows::Foundation::IInspectable> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().Parameter());
return S_OK;
}
catch (...)
{
*value = nullptr;
return impl::to_hresult();
}
}
HRESULT __stdcall get_NavigationTransitionInfo(impl::abi_arg_out<Windows::UI::Xaml::Media::Animation::INavigationTransitionInfo> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().NavigationTransitionInfo());
return S_OK;
}
catch (...)
{
*value = nullptr;
return impl::to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::UI::Xaml::Navigation::INavigationEventArgs> : produce_base<D, Windows::UI::Xaml::Navigation::INavigationEventArgs>
{
HRESULT __stdcall get_Content(impl::abi_arg_out<Windows::Foundation::IInspectable> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().Content());
return S_OK;
}
catch (...)
{
*value = nullptr;
return impl::to_hresult();
}
}
HRESULT __stdcall get_Parameter(impl::abi_arg_out<Windows::Foundation::IInspectable> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().Parameter());
return S_OK;
}
catch (...)
{
*value = nullptr;
return impl::to_hresult();
}
}
HRESULT __stdcall get_SourcePageType(impl::abi_arg_out<Windows::UI::Xaml::Interop::TypeName> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().SourcePageType());
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall get_NavigationMode(Windows::UI::Xaml::Navigation::NavigationMode * value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().NavigationMode());
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall get_Uri(impl::abi_arg_out<Windows::Foundation::IUriRuntimeClass> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().Uri());
return S_OK;
}
catch (...)
{
*value = nullptr;
return impl::to_hresult();
}
}
HRESULT __stdcall put_Uri(impl::abi_arg_in<Windows::Foundation::IUriRuntimeClass> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().Uri(*reinterpret_cast<const Windows::Foundation::Uri *>(&value));
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::UI::Xaml::Navigation::INavigationEventArgs2> : produce_base<D, Windows::UI::Xaml::Navigation::INavigationEventArgs2>
{
HRESULT __stdcall get_NavigationTransitionInfo(impl::abi_arg_out<Windows::UI::Xaml::Media::Animation::INavigationTransitionInfo> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().NavigationTransitionInfo());
return S_OK;
}
catch (...)
{
*value = nullptr;
return impl::to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::UI::Xaml::Navigation::INavigationFailedEventArgs> : produce_base<D, Windows::UI::Xaml::Navigation::INavigationFailedEventArgs>
{
HRESULT __stdcall get_Exception(HRESULT * value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().Exception());
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall get_Handled(bool * value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().Handled());
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall put_Handled(bool value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().Handled(value);
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall get_SourcePageType(impl::abi_arg_out<Windows::UI::Xaml::Interop::TypeName> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().SourcePageType());
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::UI::Xaml::Navigation::IPageStackEntry> : produce_base<D, Windows::UI::Xaml::Navigation::IPageStackEntry>
{
HRESULT __stdcall get_SourcePageType(impl::abi_arg_out<Windows::UI::Xaml::Interop::TypeName> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().SourcePageType());
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall get_Parameter(impl::abi_arg_out<Windows::Foundation::IInspectable> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().Parameter());
return S_OK;
}
catch (...)
{
*value = nullptr;
return impl::to_hresult();
}
}
HRESULT __stdcall get_NavigationTransitionInfo(impl::abi_arg_out<Windows::UI::Xaml::Media::Animation::INavigationTransitionInfo> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().NavigationTransitionInfo());
return S_OK;
}
catch (...)
{
*value = nullptr;
return impl::to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::UI::Xaml::Navigation::IPageStackEntryFactory> : produce_base<D, Windows::UI::Xaml::Navigation::IPageStackEntryFactory>
{
HRESULT __stdcall abi_CreateInstance(impl::abi_arg_in<Windows::UI::Xaml::Interop::TypeName> sourcePageType, impl::abi_arg_in<Windows::Foundation::IInspectable> parameter, impl::abi_arg_in<Windows::UI::Xaml::Media::Animation::INavigationTransitionInfo> navigationTransitionInfo, impl::abi_arg_out<Windows::UI::Xaml::Navigation::IPageStackEntry> instance) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*instance = detach_abi(this->shim().CreateInstance(*reinterpret_cast<const Windows::UI::Xaml::Interop::TypeName *>(&sourcePageType), *reinterpret_cast<const Windows::Foundation::IInspectable *>(¶meter), *reinterpret_cast<const Windows::UI::Xaml::Media::Animation::NavigationTransitionInfo *>(&navigationTransitionInfo)));
return S_OK;
}
catch (...)
{
*instance = nullptr;
return impl::to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::UI::Xaml::Navigation::IPageStackEntryStatics> : produce_base<D, Windows::UI::Xaml::Navigation::IPageStackEntryStatics>
{
HRESULT __stdcall get_SourcePageTypeProperty(impl::abi_arg_out<Windows::UI::Xaml::IDependencyProperty> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().SourcePageTypeProperty());
return S_OK;
}
catch (...)
{
*value = nullptr;
return impl::to_hresult();
}
}
};
}
namespace Windows::UI::Xaml::Navigation {
template <typename D> bool impl_INavigatingCancelEventArgs<D>::Cancel() const
{
bool value {};
check_hresult(WINRT_SHIM(INavigatingCancelEventArgs)->get_Cancel(&value));
return value;
}
template <typename D> void impl_INavigatingCancelEventArgs<D>::Cancel(bool value) const
{
check_hresult(WINRT_SHIM(INavigatingCancelEventArgs)->put_Cancel(value));
}
template <typename D> Windows::UI::Xaml::Navigation::NavigationMode impl_INavigatingCancelEventArgs<D>::NavigationMode() const
{
Windows::UI::Xaml::Navigation::NavigationMode value {};
check_hresult(WINRT_SHIM(INavigatingCancelEventArgs)->get_NavigationMode(&value));
return value;
}
template <typename D> Windows::UI::Xaml::Interop::TypeName impl_INavigatingCancelEventArgs<D>::SourcePageType() const
{
Windows::UI::Xaml::Interop::TypeName value {};
check_hresult(WINRT_SHIM(INavigatingCancelEventArgs)->get_SourcePageType(put_abi(value)));
return value;
}
template <typename D> Windows::Foundation::IInspectable impl_INavigatingCancelEventArgs2<D>::Parameter() const
{
Windows::Foundation::IInspectable value;
check_hresult(WINRT_SHIM(INavigatingCancelEventArgs2)->get_Parameter(put_abi(value)));
return value;
}
template <typename D> Windows::UI::Xaml::Media::Animation::NavigationTransitionInfo impl_INavigatingCancelEventArgs2<D>::NavigationTransitionInfo() const
{
Windows::UI::Xaml::Media::Animation::NavigationTransitionInfo value { nullptr };
check_hresult(WINRT_SHIM(INavigatingCancelEventArgs2)->get_NavigationTransitionInfo(put_abi(value)));
return value;
}
template <typename D> Windows::Foundation::IInspectable impl_INavigationEventArgs<D>::Content() const
{
Windows::Foundation::IInspectable value;
check_hresult(WINRT_SHIM(INavigationEventArgs)->get_Content(put_abi(value)));
return value;
}
template <typename D> Windows::Foundation::IInspectable impl_INavigationEventArgs<D>::Parameter() const
{
Windows::Foundation::IInspectable value;
check_hresult(WINRT_SHIM(INavigationEventArgs)->get_Parameter(put_abi(value)));
return value;
}
template <typename D> Windows::UI::Xaml::Interop::TypeName impl_INavigationEventArgs<D>::SourcePageType() const
{
Windows::UI::Xaml::Interop::TypeName value {};
check_hresult(WINRT_SHIM(INavigationEventArgs)->get_SourcePageType(put_abi(value)));
return value;
}
template <typename D> Windows::UI::Xaml::Navigation::NavigationMode impl_INavigationEventArgs<D>::NavigationMode() const
{
Windows::UI::Xaml::Navigation::NavigationMode value {};
check_hresult(WINRT_SHIM(INavigationEventArgs)->get_NavigationMode(&value));
return value;
}
template <typename D> Windows::Foundation::Uri impl_INavigationEventArgs<D>::Uri() const
{
Windows::Foundation::Uri value { nullptr };
check_hresult(WINRT_SHIM(INavigationEventArgs)->get_Uri(put_abi(value)));
return value;
}
template <typename D> void impl_INavigationEventArgs<D>::Uri(const Windows::Foundation::Uri & value) const
{
check_hresult(WINRT_SHIM(INavigationEventArgs)->put_Uri(get_abi(value)));
}
template <typename D> Windows::UI::Xaml::Media::Animation::NavigationTransitionInfo impl_INavigationEventArgs2<D>::NavigationTransitionInfo() const
{
Windows::UI::Xaml::Media::Animation::NavigationTransitionInfo value { nullptr };
check_hresult(WINRT_SHIM(INavigationEventArgs2)->get_NavigationTransitionInfo(put_abi(value)));
return value;
}
template <typename D> HRESULT impl_INavigationFailedEventArgs<D>::Exception() const
{
HRESULT value {};
check_hresult(WINRT_SHIM(INavigationFailedEventArgs)->get_Exception(&value));
return value;
}
template <typename D> bool impl_INavigationFailedEventArgs<D>::Handled() const
{
bool value {};
check_hresult(WINRT_SHIM(INavigationFailedEventArgs)->get_Handled(&value));
return value;
}
template <typename D> void impl_INavigationFailedEventArgs<D>::Handled(bool value) const
{
check_hresult(WINRT_SHIM(INavigationFailedEventArgs)->put_Handled(value));
}
template <typename D> Windows::UI::Xaml::Interop::TypeName impl_INavigationFailedEventArgs<D>::SourcePageType() const
{
Windows::UI::Xaml::Interop::TypeName value {};
check_hresult(WINRT_SHIM(INavigationFailedEventArgs)->get_SourcePageType(put_abi(value)));
return value;
}
template <typename D> Windows::UI::Xaml::Interop::TypeName impl_IPageStackEntry<D>::SourcePageType() const
{
Windows::UI::Xaml::Interop::TypeName value {};
check_hresult(WINRT_SHIM(IPageStackEntry)->get_SourcePageType(put_abi(value)));
return value;
}
template <typename D> Windows::Foundation::IInspectable impl_IPageStackEntry<D>::Parameter() const
{
Windows::Foundation::IInspectable value;
check_hresult(WINRT_SHIM(IPageStackEntry)->get_Parameter(put_abi(value)));
return value;
}
template <typename D> Windows::UI::Xaml::Media::Animation::NavigationTransitionInfo impl_IPageStackEntry<D>::NavigationTransitionInfo() const
{
Windows::UI::Xaml::Media::Animation::NavigationTransitionInfo value { nullptr };
check_hresult(WINRT_SHIM(IPageStackEntry)->get_NavigationTransitionInfo(put_abi(value)));
return value;
}
template <typename D> Windows::UI::Xaml::DependencyProperty impl_IPageStackEntryStatics<D>::SourcePageTypeProperty() const
{
Windows::UI::Xaml::DependencyProperty value { nullptr };
check_hresult(WINRT_SHIM(IPageStackEntryStatics)->get_SourcePageTypeProperty(put_abi(value)));
return value;
}
template <typename D> Windows::UI::Xaml::Navigation::PageStackEntry impl_IPageStackEntryFactory<D>::CreateInstance(const Windows::UI::Xaml::Interop::TypeName & sourcePageType, const Windows::Foundation::IInspectable & parameter, const Windows::UI::Xaml::Media::Animation::NavigationTransitionInfo & navigationTransitionInfo) const
{
Windows::UI::Xaml::Navigation::PageStackEntry instance { nullptr };
check_hresult(WINRT_SHIM(IPageStackEntryFactory)->abi_CreateInstance(get_abi(sourcePageType), get_abi(parameter), get_abi(navigationTransitionInfo), put_abi(instance)));
return instance;
}
inline PageStackEntry::PageStackEntry(const Windows::UI::Xaml::Interop::TypeName & sourcePageType, const Windows::Foundation::IInspectable & parameter, const Windows::UI::Xaml::Media::Animation::NavigationTransitionInfo & navigationTransitionInfo) :
PageStackEntry(get_activation_factory<PageStackEntry, IPageStackEntryFactory>().CreateInstance(sourcePageType, parameter, navigationTransitionInfo))
{}
inline Windows::UI::Xaml::DependencyProperty PageStackEntry::SourcePageTypeProperty()
{
return get_activation_factory<PageStackEntry, IPageStackEntryStatics>().SourcePageTypeProperty();
}
}
}
template<>
struct std::hash<winrt::Windows::UI::Xaml::Navigation::INavigatingCancelEventArgs>
{
size_t operator()(const winrt::Windows::UI::Xaml::Navigation::INavigatingCancelEventArgs & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::UI::Xaml::Navigation::INavigatingCancelEventArgs2>
{
size_t operator()(const winrt::Windows::UI::Xaml::Navigation::INavigatingCancelEventArgs2 & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::UI::Xaml::Navigation::INavigationEventArgs>
{
size_t operator()(const winrt::Windows::UI::Xaml::Navigation::INavigationEventArgs & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::UI::Xaml::Navigation::INavigationEventArgs2>
{
size_t operator()(const winrt::Windows::UI::Xaml::Navigation::INavigationEventArgs2 & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::UI::Xaml::Navigation::INavigationFailedEventArgs>
{
size_t operator()(const winrt::Windows::UI::Xaml::Navigation::INavigationFailedEventArgs & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::UI::Xaml::Navigation::IPageStackEntry>
{
size_t operator()(const winrt::Windows::UI::Xaml::Navigation::IPageStackEntry & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::UI::Xaml::Navigation::IPageStackEntryFactory>
{
size_t operator()(const winrt::Windows::UI::Xaml::Navigation::IPageStackEntryFactory & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::UI::Xaml::Navigation::IPageStackEntryStatics>
{
size_t operator()(const winrt::Windows::UI::Xaml::Navigation::IPageStackEntryStatics & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::UI::Xaml::Navigation::NavigatingCancelEventArgs>
{
size_t operator()(const winrt::Windows::UI::Xaml::Navigation::NavigatingCancelEventArgs & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::UI::Xaml::Navigation::NavigationEventArgs>
{
size_t operator()(const winrt::Windows::UI::Xaml::Navigation::NavigationEventArgs & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::UI::Xaml::Navigation::NavigationFailedEventArgs>
{
size_t operator()(const winrt::Windows::UI::Xaml::Navigation::NavigationFailedEventArgs & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::UI::Xaml::Navigation::PageStackEntry>
{
size_t operator()(const winrt::Windows::UI::Xaml::Navigation::PageStackEntry & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
WINRT_WARNING_POP
|
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "GameFramework\Actor.h"
#include "Components\BoxComponent.h"
#include "Components\StaticMeshComponent.h"
#include "TimerManager.h"
#include "DoorKeyStruct.h"
#include "DoorKey.h"
#include "GameInstances\RPGGameInstance.h"
#include "Engine\DataTable.h"
#include "Door.generated.h"
class APlayerPawn;
UENUM()
enum class EOpening : int32
{
ClockWise = 1 UMETA(DisplayName = "ClockWise"),
CounterClockWise = -1 UMETA(DisplayName = "CounterClockWise")
};
UCLASS()
class RPG_API ADoor : public AActor
{
GENERATED_BODY()
public:
// Sets default values for this actor's properties
ADoor();
virtual void PostInitializeComponents() override;
virtual void OnConstruction(const FTransform& Transform) override;
protected:
// Called when the game starts or when spawned
virtual void BeginPlay() override;
public:
// Called every frame
virtual void Tick(float DeltaTime) override;
protected:
UPROPERTY(VisibleAnywhere, BlueprintReadWrite)
UBoxComponent* BoxComponent = nullptr;
UPROPERTY(VisibleAnywhere, BlueprintReadWrite)
UStaticMeshComponent* StaticMesh = nullptr;
UPROPERTY(VisibleAnywhere, BlueprintReadWrite)
USceneComponent* SceneComponent = nullptr;
FTimerHandle TimerHandle;
bool bIsLocked = true;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = DoorKey)
TSubclassOf<ADoorKey> DoorKeyClass = nullptr;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = DoorKey)
FName DoorKeyName;
UPROPERTY(EditAnywhere, BlueprintReadWrite)
EOpening DOpening = EOpening::ClockWise;
UPROPERTY(EditAnywhere, meta = (ClampMin = -1, ClampMax = 1), BlueprintReadWrite)
int32 DoorOpening = (int32) DOpening;
UPROPERTY()
URPGGameInstance* GameInstance = nullptr;
UPROPERTY()
UDataTable* DoorKeyDataTable = nullptr;
UPROPERTY()
FDataTableRowHandle DataTableRowHandle;
protected:
void OpenDoor(APlayerPawn* PlayerPawn);
void CloseDoor(float DeltaTime);
UFUNCTION()
void OnBoxBeginOverlap(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult &SweepResult);
UFUNCTION()
void OnBoxEndOverlap(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex);
void StartTimer();
UFUNCTION()
void UpdateTimer(float InStartTime);
void StopTimer();
};
|
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/nonfree/features2d.hpp>
#include <opencv2/legacy/legacy.hpp>
#include <vector>
#include "SiftTest.h"
using namespace cv;
using namespace std;
int siftTest::one_Img_Sift(Mat img)
{
//---------------------------------------------------
// 检测并显示一张图片的SIFT特征点
//---------------------------------------------------
SIFT sift; //实例化SIFT类
// SIFT sift(40); //只检测40个特征点
vector<KeyPoint> key_points; //特征点
Mat descriptors, mascara; // descriptors为描述符,mascara为掩码矩阵
Mat output_img; //输出图像矩阵
sift(img, mascara, key_points, descriptors); //执行SIFT运算,在输出图像中绘制特征点
drawKeypoints(img, //输入图像
key_points, //特征点矢量
output_img, //输出图像
Scalar::all(-1), //绘制特征点的颜色,为随机
//以特征点为中心画圆,圆的半径表示特征点的大小,直线表示特征点的方向
DrawMatchesFlags::DRAW_RICH_KEYPOINTS);
namedWindow("SIFT");
imshow("SIFT", output_img);
waitKey(0);
return 0;
}
int siftTest::two_Img_Sift(Mat img1, Mat img2)
{
//---------------------------------------------------
// 分别检测两张图片的SIFT特征点,并匹配
//---------------------------------------------------
//sift特征检测
SiftFeatureDetector siftdtc;
vector<KeyPoint>kp1, kp2;
siftdtc.detect(img1, kp1);
siftdtc.detect(img2, kp2);
//画出sift特征点
Mat outimg1;
drawKeypoints(img1, kp1, outimg1);
// imshow("image1 keypoints", outimg1);
waitKey();
Mat outimg2;
drawKeypoints(img2, kp2, outimg2);
// imshow("image2 keypoints", outimg2);
waitKey();
//提取特征点描述,即特征向量
SiftDescriptorExtractor extractor; //SIFT特征探测器
Mat descriptor1, descriptor2; //保存特征点对应的特征向量
extractor.compute(img1, kp1, descriptor1);
extractor.compute(img2, kp2, descriptor2);
// keypoint只保存了sift检测到的特征点的一些基本信息,
// 但sift所提取出来的特征向量其实不是在这个里面,
// 特征向量通过SiftDescriptorExtractor 提取,结果放在一个Mat的数据结构中
//*****************************************
//特征向量提取的另一种表达方式
//SIFT sift1,sift2;
//vector<KeyPoint>kp1, kp2;
//Mat descriptor1, descriptor2,mascara;
//sift1(img1,mascara,kp1,descriptor1);
//sift2(img2,mascara,kp2,descriptor2);
//*****************************************
//特征向量匹配
BruteForceMatcher<L2<float>> matcher; //暴力匹配器
vector<DMatch> matches; //保存匹配结果,即匹配器算子
matcher.match(descriptor1, descriptor2, matches);
//排序,提取出前30个最佳匹配结果,即距离最小
std::nth_element(matches.begin(), //匹配器算子的初始位置
matches.begin() + 29, // 排序的数量
matches.end()); // 结束位置
matches.erase(matches.begin() + 30, matches.end()); //剔除掉其余的匹配结果
//画出匹配图
Mat img_matches;
drawMatches(img1, kp1, img2, kp2, matches, img_matches);
imshow("matches", img_matches);
// waitKey();
return 0;
}
|
#include "Pololu37D.h"
#include <mutex>
using namespace Encoder;
Pololu37D::Pololu37D(const Config &config)
: m_QEI(config.ChannelA, config.ChannelB, config.Index, config.quadratureEncoding),
m_zeroOffsetDeg(config.offsetDeg) {}
bool Pololu37D::getAngleDeg(float &angle) {
std::scoped_lock<Mutex> lock(m_mutex);
angle = (m_QEI.getPulses() * m_degreesPerCount) - m_zeroOffsetDeg;
return true;
}
bool Pololu37D::getAngularVelocityDegPerSec(float &speed) {
std::scoped_lock<Mutex> lock(m_mutex);
speed = m_QEI.getPulseVelocity_PulsesPerSec() * m_degreesPerCount;
return true;
}
bool Pololu37D::reset() {
std::scoped_lock<Mutex> lock(m_mutex);
m_QEI.reset();
return true;
}
|
// C++ for the Windows Runtime vv1.0.170303.6
// Copyright (c) 2017 Microsoft Corporation. All rights reserved.
#pragma once
WINRT_EXPORT namespace winrt {
namespace ABI::Windows::Devices::SerialCommunication {
struct IErrorReceivedEventArgs;
struct IPinChangedEventArgs;
struct ISerialDevice;
struct ISerialDeviceStatics;
struct ErrorReceivedEventArgs;
struct PinChangedEventArgs;
struct SerialDevice;
}
namespace Windows::Devices::SerialCommunication {
struct IErrorReceivedEventArgs;
struct IPinChangedEventArgs;
struct ISerialDevice;
struct ISerialDeviceStatics;
struct ErrorReceivedEventArgs;
struct PinChangedEventArgs;
struct SerialDevice;
}
namespace Windows::Devices::SerialCommunication {
template <typename T> struct impl_IErrorReceivedEventArgs;
template <typename T> struct impl_IPinChangedEventArgs;
template <typename T> struct impl_ISerialDevice;
template <typename T> struct impl_ISerialDeviceStatics;
}
namespace Windows::Devices::SerialCommunication {
enum class SerialError
{
Frame = 0,
BufferOverrun = 1,
ReceiveFull = 2,
ReceiveParity = 3,
TransmitFull = 4,
};
enum class SerialHandshake
{
None = 0,
RequestToSend = 1,
XOnXOff = 2,
RequestToSendXOnXOff = 3,
};
enum class SerialParity
{
None = 0,
Odd = 1,
Even = 2,
Mark = 3,
Space = 4,
};
enum class SerialPinChange
{
BreakSignal = 0,
CarrierDetect = 1,
ClearToSend = 2,
DataSetReady = 3,
RingIndicator = 4,
};
enum class SerialStopBitCount
{
One = 0,
OnePointFive = 1,
Two = 2,
};
}
}
|
#include <iostream>
#include "list.hpp"
#include "putovanje.h"
using namespace std;
int main()
{
return 0;
}
|
///udppeer_co.h
#ifndef NETPEER_CO_H
#define NETPEER_CO_H
#include "fddef.h"
#include "addr.h"
#include "namespdef.h"
#include <coroutine>
#include <deque>
NAMESP_BEGIN
namespace net
{
template<class MsgWrapper>
class NetPeer_co
{
public:
NetPeer_co()
{
}
virtual ~NetPeer_co(){
}
protected:
void clear();
struct AwaitableWrite{
bool await_ready(){
return true;
}
void await_suspend(std::coroutine_handle<> awaiting_coro){
m_awaiting_coro = awaiting_coro;
}
int await_resume(){
return m_requested_msg.size();;
}
const MsgWrapper& m_requested_msg;
std::coroutine_handle<> m_awaiting_coro;
};
using Peer = NetPeer_co<MsgWrapper>;
struct AwaitableRecv{
bool await_ready(){
if(m_peer->in_msg_size() > 0){
return true;
}
return false;
}
void await_suspend(std::coroutine_handle<> awaiting_coro){
m_awaiting_coro = awaiting_coro;
m_peer->pushAwaitingCoro(m_awaiting_coro);
}
MsgWrapper await_resume(){
auto msg = m_peer->popInMsg();
if(m_remote_addr != nullptr){
*m_remote_addr = msg.addr;
}
return msg.msg;
}
Peer* m_peer=nullptr;
AddrPair* m_remote_addr=nullptr;
std::coroutine_handle<> m_awaiting_coro;
};
void onRecv(const AddrPair& remote, const MsgWrapper& msg);
private:
size_t in_msg_size();
auto popInMsg();
void pushAwaitingCoro(std::coroutine_handle<> coro);
std::coroutine_handle<> popAwaitingCoro();
private:
struct Msg{
MsgWrapper msg;
AddrPair addr;
};
std::deque<Msg> _in_msg_buf;
int _max_in_msg_size = 1024;
std::deque<std::coroutine_handle<>> _awaiting_coros;
};
}//net
NAMESP_END
#include "netpeer_co.inl"
#endif /*NETPEER_CO_H*/
|
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <cstring>
#include <queue>
#include <sstream>
using namespace std;
/*
输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)
e.g.:
{8,8,7,9,2,#,#,#,#,4,7},{8,9,2}
输出true
*/
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
bool HasSubtree(TreeNode* r1, TreeNode* r2){
if(r1 == NULL || r2 == NULL) return false;
return partial_identity(r1, r2)
|| HasSubtree(r1->left, r2) || HasSubtree(r1->right, r2);
}
private:
bool partial_identity(TreeNode* r1, TreeNode* r2){
if(r2 == NULL) return true;
if(r1 == NULL) return false;
if(r1->val != r2->val) return false;
return partial_identity(r1->left, r2->left)
&& partial_identity(r1->right, r2->right);
}
};
/*
// 手生了以后做的
class Solution {
public:
bool check(TreeNode* r1, TreeNode* r2){
if(r2 == NULL) return true;
if(r1 == NULL) return false;
if(r1->val != r2->val) return false;
return check(r1->left, r2->left) && check(r1->right, r2->right);
}
void helper(TreeNode* r1, TreeNode* r2){
if(r1 == NULL || res) return;
if(check(r1, r2)){
res = true;
return;
}
helper(r1->left, r2);
if(!res)
helper(r1->right, r2);
}
bool HasSubtree(TreeNode* pRoot1, TreeNode* pRoot2)
{
if(pRoot2 == NULL) return false;
res = false;
helper(pRoot1, pRoot2);
return res;
}
private:
bool res;
};
*/
int main(){
return 0;
}
|
#include "ovpCBoxAlgorithmSignalMaximum.h"
using namespace OpenViBE;
using namespace OpenViBE::Kernel;
using namespace OpenViBE::Plugins;
using namespace OpenViBEPlugins;
using namespace OpenViBEPlugins::SignalProcessing;
boolean CBoxAlgorithmSignalMaximum::initialize(void)
{
m_oSignalDecoder.initialize(*this);
m_pMatrixMaximumAlgorithm = NULL;
m_pMatrixMaximumAlgorithm=&this->getAlgorithmManager().getAlgorithm(this->getAlgorithmManager().createAlgorithm(OVP_ClassId_Algorithm_MatrixMaximum));
m_pMatrixMaximumAlgorithm->initialize();
//bind concrete matrix to input and output parameters
ip_pMatrixMaximumAlgorithm_Matrix.initialize(m_pMatrixMaximumAlgorithm->getInputParameter(OVP_Algorithm_MatrixMaximum_InputParameterId_Matrix));
op_pMatrixMaximumAlgorithm_Matrix.initialize(m_pMatrixMaximumAlgorithm->getOutputParameter(OVP_Algorithm_MatrixMaximum_OutputParameterId_Matrix));
//now we can use ip_pMatrixMaximumAlgorithm_Matrix and op_pMatrixMaximumAlgorithm_Matrix
//below we set the output from op_pMatrixMaximumAlgorithm_Matrix to the box final encoder
//also the decoder sends its output to the algorithm through ip_pMatrixMaximumAlgorithm_Matrix
m_oSignalEncoder.initialize(*this);
// we connect the algorithms
// the Signal Maximum algorithm will take the matrix coming from the signal decoder:
ip_pMatrixMaximumAlgorithm_Matrix.setReferenceTarget(m_oSignalDecoder.getOutputMatrix());
// The Signal Encoder will take the sampling rate from the Signal Decoder:
m_oSignalEncoder.getInputSamplingRate().setReferenceTarget(m_oSignalDecoder.getOutputSamplingRate());
// And the matrix from the Signal Maximum algorithm:
m_oSignalEncoder.getInputMatrix().setReferenceTarget(op_pMatrixMaximumAlgorithm_Matrix);
return true;
}
/*******************************************************************************/
boolean CBoxAlgorithmSignalMaximum::uninitialize(void)
{
m_oSignalDecoder.uninitialize();
op_pMatrixMaximumAlgorithm_Matrix.uninitialize();
ip_pMatrixMaximumAlgorithm_Matrix.uninitialize();
//if(m_pMatrixMaximumAlgorithm!=NULL){
m_pMatrixMaximumAlgorithm->uninitialize();
this->getAlgorithmManager().releaseAlgorithm(*m_pMatrixMaximumAlgorithm);
//}
m_oSignalEncoder.uninitialize();
return true;
}
/*******************************************************************************/
boolean CBoxAlgorithmSignalMaximum::processInput(uint32 ui32InputIndex)
{
getBoxAlgorithmContext()->markAlgorithmAsReadyToProcess();
return true;
}
/*******************************************************************************/
boolean CBoxAlgorithmSignalMaximum::process(void)
{
IBoxIO& l_rDynamicBoxContext=this->getDynamicBoxContext();
//we decode the input signal chunks - we have only one input at index 0
for(uint32 i=0; i<l_rDynamicBoxContext.getInputChunkCount(0); i++)
{
m_oSignalDecoder.decode(0,i);//get some data
if(m_oSignalDecoder.isHeaderReceived())
{
//ip_pMatrixMaximumAlgorithm_Matrix->setDimensionCount(3);
if(!m_pMatrixMaximumAlgorithm->process(OVP_Algorithm_MatrixMaximum_InputTriggerId_Initialize)) return false;
//forward
m_oSignalEncoder.encodeHeader(0);
l_rDynamicBoxContext.markOutputAsReadyToSend(0, l_rDynamicBoxContext.getInputChunkStartTime(0, i), l_rDynamicBoxContext.getInputChunkEndTime(0, i));
}
//when it is received then it is supplied to the m_pMatrixMaximumAlgorithm
if(m_oSignalDecoder.isBufferReceived())
{
// we process the signal matrix with our algorithm
m_pMatrixMaximumAlgorithm->process(OVP_Algorithm_MatrixMaximum_InputTriggerId_Process);
// If the process is done successfully, we can encode the buffer
if(m_pMatrixMaximumAlgorithm->isOutputTriggerActive(OVP_Algorithm_MatrixMaximum_OutputTriggerId_ProcessDone))
{
//forward
m_oSignalEncoder.encodeBuffer(0);
l_rDynamicBoxContext.markOutputAsReadyToSend(0, l_rDynamicBoxContext.getInputChunkStartTime(0, i), l_rDynamicBoxContext.getInputChunkEndTime(0, i));
}
}
//forward
if(m_oSignalDecoder.isEndReceived())
{
m_oSignalEncoder.encodeEnd(0);
l_rDynamicBoxContext.markOutputAsReadyToSend(0, l_rDynamicBoxContext.getInputChunkStartTime(0, i), l_rDynamicBoxContext.getInputChunkEndTime(0, i));
}
}
return true;
}
|
#include <iostream>
using namespace std;
int heapsize = 0;
int *heap;
int n, m,tmp;
void heapinsert (int x) {
int now = heapsize;
while (now > 0 && x<=heap[(now-1)/2]) {
heap[now] = heap[(now-1)/2];
now = (now-1)/2;
}
heap[now] = x;
heapsize++;
}
void adjust (int number) {
int now = 0;
int son = now*2+1;
while (son<heapsize) {
if (son < heapsize-1 && heap[son]>=heap[son+1])
son++;
if (heap[son]<=number) {
heap[now] = heap[son];
now = son;
son = now*2 + 1;
}
}
heap[now] = number;
for (int i=0; i<m; i++)
cout<<heap[i]<<" ";
cout<<endl;
}
int main () {
cin>>n>>m;
heap = new int [m];
for (int i=1; i<=m; i++) {
cin>>tmp;
heapinsert (tmp);
}
for (int i=0; i<m; i++)
cout<<heap[i]<<" ";
cout<<endl;
for (int i=m+1; i<=n; i++) {
cin>>tmp;
tmp = tmp + heap[0];
heap[0] = tmp;
adjust (tmp);
}
int ans = 0;
for (int i=0; i<m; i++) {
if (ans<heap[i])
ans = heap[i];
}
cout<<ans;
return 0;
}
|
#pragma once
#include <utility>
#include <memory>
#include <functional>
using tensor_shape = std::pair<size_t, size_t>;
using tensor_index = tensor_shape;
template <typename Type, size_t Height, size_t Width>
using array2d = std::array<std::array<Type, Width>, Height>;
template <typename Type>
using tensor_data = std::unique_ptr<Type[], std::function<void(Type*)>>;
|
#include "SampleRobot.h"
SampleRobot::SampleRobot()
{
sensors = std::tr1::shared_ptr<Sensors>(new Sensors());
}
SampleRobot::~SampleRobot()
{
}
void SampleRobot::run()
{
std::vector<float> anglesServo;
//sensors->mBodySensors["RHipPitch"]->setPosition(-90*RAD_OVER_DEG);
sensors->getReadyServoByName(JOINT_STRINGS[14])->setPosition(-90*RAD_OVER_DEG);
sensors->getArrayServoSensors(anglesServo,RLEG_SERVOS);
std::cout<<"angles";
for (unsigned int i=0;i<anglesServo.size();i++)
{
std::cout<<" "<<anglesServo[i]*MMath::DEG_OVER_RAD;
}
std::cout<<std::endl;
std::cout<<"coord"<<Kinematics::forwardKinematics(Kinematics::RLEG_CHAIN,anglesServo)<<"/coord"<<std::endl;
}
|
/***************************************************************************
dialogocaso.cpp - description
-------------------
begin : sep 13 2003
copyright : (C) 2003 by Oscar G. Duarte
email : ogduarte@ing.unal.edu.co
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include "dialogocaso.h"
BEGIN_EVENT_TABLE(DialogoCaso, wxDialog)
EVT_BUTTON(DLG_CASO_BTN_EDITAR_VARIABLE, DialogoCaso::editarVariable)
EVT_BUTTON(DLG_CASO_BTN_NUEVA_VARIABLE, DialogoCaso::nuevaVariable)
EVT_BUTTON(DLG_CASO_BTN_BORRAR_VARIABLE, DialogoCaso::borrarVariable)
EVT_BUTTON(DLG_CASO_BTN_COPIAR_VARIABLE, DialogoCaso::copiarVariable)
EVT_BUTTON(DLG_CASO_BTN_PROPIEDADES, DialogoCaso::propiedades)
EVT_BUTTON(DLG_CASO_BTN_OK, DialogoCaso::cerrarOk)
// EVT_BUTTON(DLG_CASO_BTN_CANCELAR, DialogoCaso::noImplementada)
EVT_BUTTON(DLG_CASO_BTN_AYUDA, DialogoCaso::ayuda)
EVT_BUTTON(DLG_CASO_BTN_LIBRERIAS, DialogoCaso::librerias)
END_EVENT_TABLE()
DialogoCaso::DialogoCaso(MiCanvas *canvas,Caso *cas,
Proyecto *proy, wxWindow *parent, wxHtmlHelpController *ayuda)
:wxDialog(parent,wxID_ANY,wxString(wxT("Prueba")))
{
Canvas=canvas;
Cas=cas;
Proy=proy;
Ayuda=ayuda;
ButtonEditarVariable =new wxButton (this,DLG_CASO_BTN_EDITAR_VARIABLE, wxT("Editar"));
ButtonNuevaVariable =new wxButton (this,DLG_CASO_BTN_NUEVA_VARIABLE, wxT("Nueva"));
ButtonBorrarVariable =new wxButton (this,DLG_CASO_BTN_BORRAR_VARIABLE, wxT("Borrar"));
ButtonCopiarVariables =new wxButton (this,DLG_CASO_BTN_COPIAR_VARIABLE, wxT("Copiar"));
ButtonPropiedades =new wxButton (this,DLG_CASO_BTN_PROPIEDADES, wxT("Propiedades"));
ButtonOK =new wxButton (this,DLG_CASO_BTN_OK, wxT("OK"));
// ButtonCancelar =new wxButton (this,DLG_CASO_BTN_CANCEL, wxT("Cancelar"));
ButtonAyuda =new wxButton (this,DLG_CASO_BTN_AYUDA, wxT("Ayuda"));
ButtonLibrerias =new wxButton (this,DLG_CASO_BTN_LIBRERIAS, wxT("Librerías"));
ListBoxVariables =new wxListBox (this,DLG_CASO_LISTBOX_VARIABLES,wxPoint(20,20),wxSize(200,100), 0, 0, wxLB_SINGLE|wxLB_ALWAYS_SB);
TextNombre =new wxTextCtrl(this,DLG_CASO_TEXT_NOMBRE);
StaticNombre =new wxStaticText (this,DLG_CASO_STATIC_NOMBRE, wxT("Nombre"));
StaticVariables =new wxStaticText (this,DLG_CASO_STATIC_VARIABLES, wxT("Variables"));
StaticDescripcion = new wxStaticText(this,DLG_CASO_STATIC_DESCRIPCION,wxT("Descripción"));
TextDescripcion = new wxTextCtrl(this,DLG_CASO_TEXT_DESCRIPCION,wxT(""),wxDefaultPosition,wxDefaultSize, wxTE_MULTILINE);
TextDescripcion->SetMinSize(wxSize(300,80));
TextNombre->SetMinSize(wxSize(200,20));
ButtonPropiedades->SetMinSize(wxSize(120,30));
wxBoxSizer *sizerNombre = new wxBoxSizer(wxHORIZONTAL);
sizerNombre->Add(StaticNombre, 0, wxALIGN_RIGHT | wxLEFT |wxRIGHT, 5);
sizerNombre->Add(TextNombre, 0, wxALIGN_LEFT | wxLEFT |wxRIGHT, 5);
wxBoxSizer *sizerVariables = new wxBoxSizer(wxVERTICAL);
sizerVariables->Add(StaticVariables, 0, wxALIGN_CENTER | wxLEFT |wxRIGHT, 5);
sizerVariables->Add(ListBoxVariables, 0, wxALIGN_CENTER | wxLEFT |wxRIGHT, 5);
wxBoxSizer *sizerBut = new wxBoxSizer(wxVERTICAL);
sizerBut->Add(ButtonEditarVariable, 0, wxALIGN_CENTER | wxLEFT |wxRIGHT, 5);
sizerBut->Add(ButtonNuevaVariable, 0, wxALIGN_CENTER | wxLEFT |wxRIGHT, 5);
sizerBut->Add(ButtonBorrarVariable, 0, wxALIGN_CENTER | wxLEFT |wxRIGHT, 5);
sizerBut->Add(20,30, 0, wxALIGN_CENTER | wxLEFT |wxRIGHT, 5);
sizerBut->Add(ButtonCopiarVariables, 0, wxALIGN_CENTER | wxLEFT |wxRIGHT, 5);
wxBoxSizer *sizerEditVariables = new wxBoxSizer(wxHORIZONTAL);
sizerEditVariables->Add(sizerVariables, 0, wxALIGN_CENTER | wxLEFT |wxRIGHT, 5);
sizerEditVariables->Add(sizerBut, 0, wxALIGN_CENTER | wxLEFT |wxRIGHT, 5);
wxBoxSizer *sizerButInf = new wxBoxSizer(wxHORIZONTAL);
sizerButInf->Add(ButtonOK, 0, wxALIGN_CENTER | wxALL, 5);
// sizerButInf->Add(ButtonCancelar, 0, wxALIGN_CENTER | wxALL, 5);
sizerButInf->Add(ButtonAyuda, 0, wxALIGN_CENTER | wxALL, 5);
sizerButInf->Add(ButtonLibrerias, 0, wxALIGN_CENTER | wxALL, 5);
wxBoxSizer *sizerDescr = new wxBoxSizer(wxVERTICAL);
sizerDescr->Add(StaticDescripcion, 0, wxALIGN_CENTER | wxLEFT |wxRIGHT, 5);
sizerDescr->Add(TextDescripcion, 0, wxALIGN_CENTER | wxLEFT |wxRIGHT, 5);
wxBoxSizer *sizerTotal = new wxBoxSizer(wxVERTICAL);
sizerTotal->Add(sizerNombre, 0, wxALIGN_CENTER | wxALL, 5);
sizerTotal->Add(sizerEditVariables, 0, wxALIGN_CENTER | wxALL, 5);
sizerTotal->Add(ButtonPropiedades, 0, wxALIGN_CENTER | wxALL, 5);
sizerTotal->Add(sizerDescr, 0, wxALIGN_CENTER | wxALL, 5);
sizerTotal->Add(sizerButInf, 0, wxALIGN_CENTER | wxALL, 5);
SetAutoLayout(TRUE);
SetSizer(sizerTotal);
sizerTotal->SetSizeHints(this);
sizerTotal->Fit(this);
llenarCuadro();
}
DialogoCaso::~DialogoCaso()
{
}
void DialogoCaso::llenarCuadro()
{
TextNombre->SetValue(Cas->Nombre);
TextDescripcion->SetValue(Cas->Descripcion);
ListBoxVariables->Clear();
int i,tam;
tam=Cas->Variables.GetCount();
for(i=0;i<tam;i++)
{
wxString cad;
cad=Cas->Variables.Item(i).Nombre;
ListBoxVariables->Append(cad);
}
if(tam>0)
{
ListBoxVariables->SetSelection(0);
}
}
void DialogoCaso::editarVariable(wxCommandEvent&)
{
int n;
n=ListBoxVariables->GetSelection();
if(n<0){return;}
VariableLinguistica *Var;
Var=&Cas->Variables.Item(n);
DialogoVariable dlg(Var,Proy,this,wxT("Prueba"), Ayuda);
dlg.ShowModal();
llenarCuadro();
ListBoxVariables->SetSelection(n);
}
void DialogoCaso::nuevaVariable(wxCommandEvent&)
{
wxTextEntryDialog dlg(this,wxT("Nombre de la Variable"));
if(dlg.ShowModal()==wxID_OK)
{
wxString cad;
cad=dlg.GetValue();
if(ListBoxVariables->FindString(cad)!=-1)
{
wxMessageBox(wxT("Ya existe una Variable con ese nombre"),wxT("Alerta"),wxOK,this);
}else
{
VariableLinguistica *Var;
Var=new VariableLinguistica();
Var->Nombre=cad;
int n=ListBoxVariables->GetSelection();
Cas->Variables.Insert(Var,n+1);
}
Cas->Descripcion=TextDescripcion->GetValue();
wxString cad2;
cad2=TextNombre->GetValue();
Cas->Nombre=cad2;
llenarCuadro();
}
}
void DialogoCaso::borrarVariable(wxCommandEvent&)
{
int n;
n=ListBoxVariables->GetSelection();
if(n<0){return;}
wxString cad;
cad << wxT("Desea borrar La Variable '") <<ListBoxVariables->GetStringSelection() << wxT("'?");
if(wxMessageBox(cad,wxT("Alerta"),wxICON_QUESTION | wxYES_NO,this)==wxYES)
{
Cas->Variables.RemoveAt(n);
llenarCuadro();
if(Cas->Variables.GetCount()>n)
{
ListBoxVariables->SetSelection(n);
}else
{
ListBoxVariables->SetSelection(n-1);
}
}
}
void DialogoCaso::copiarVariable(wxCommandEvent&)
{
int Est=-1;
int Flag=0;
int Flag2=1;
DialogoSeleccionarEstrategia dlg(&Est,&Flag,&Flag2,Proy,this, Ayuda);
dlg.ShowModal();
switch(Flag)
{
case -1 : return;
case 0 : // adicionar
break;
case 1 : // borrar
Cas->Variables.Empty();
break;
default : return;
}
if(Est>-1)
{
Estrategia *est=&Proy->Estrategias.Item(Est);
est->llenarCasoIndefinido(Cas,Flag2);
}
Cas->Descripcion=TextDescripcion->GetValue();
wxString cad2;
cad2=TextNombre->GetValue();
Cas->Nombre=cad2;
llenarCuadro();
}
void DialogoCaso::propiedades(wxCommandEvent&)
{
Cas->Descripcion=TextDescripcion->GetValue();
Cas->Nombre=TextNombre->GetValue();
DialogoPropiedades dlg(&Cas->Generalidades,this, Ayuda);
dlg.ShowModal();
// llenarCuadro();
}
void DialogoCaso::cerrarOk(wxCommandEvent&)
{
Cas->Descripcion=TextDescripcion->GetValue();
wxString cad2;
cad2=TextNombre->GetValue();
Cas->Nombre=cad2;
Close();
}
void DialogoCaso::ayuda(wxCommandEvent&)
{
Ayuda->Display(wxT("Edición de Casos"));
}
void DialogoCaso::librerias(wxCommandEvent&)
{
Canvas->NoPintar=TRUE;
wxString dirActual;
dirActual=wxGetCwd();
DialogoLibreria dlg(NULL,Cas,NULL,this,wxT("Librerías de Fuzzynet"), Ayuda);
dlg.ShowModal();
wxSetWorkingDirectory(dirActual);
Canvas->NoPintar=FALSE;
Canvas->Ver=VER_RED;
Canvas->llenarRegiones();
Canvas->Refresh();
}
|
#ifndef MENU_ELPOLLOLOCO_TESTS
#define MENU_ELPOLLOLOCO_TESTS
#include "gtest/gtest.h"
#include "../../composite/menu_component.hpp"
#include "../../composite/menu_taco/header/menu_items_elpolloloco.hpp"
#include "../../composite/menu_taco/header/menu_elpolloloco.hpp"
#include <iostream>
using namespace std;
TEST(MenuTest, elpolloloco_Customer_Favorites)
{
menu_component *m_elpolloloco_customer_favorites = new menu_elpolloloco("Customer Favorites", "Following Options are the Most Popular Items at El Pollo Loco");
EXPECT_EQ(m_elpolloloco_customer_favorites->get_name(), "Customer Favorites");
EXPECT_EQ(m_elpolloloco_customer_favorites->get_description(), "Following Options are the Most Popular Items at El Pollo Loco");
menu_component *chicken_avocado_taco = new menu_items_elpolloloco(1, "Chicken Avocado Taco", "Fire-grilled chicken, avocado, shredded lettuce, queso fresco, and pico on a handcrafted tortilla and finished with creamy cilantro dressing.", 2.99);
m_elpolloloco_customer_favorites->add(chicken_avocado_taco);
cout << "EXPECTED ITEM NUMBER: 1"
<< "\nRECEIVIED: " << chicken_avocado_taco->get_item_number() << endl;
EXPECT_EQ(chicken_avocado_taco->get_item_number(), 1);
menu_component *chickenless_pollo_taco = new menu_items_elpolloloco(2, "Chickenless Pollo Taco", "Tender shreds of plant-based protein cooked in adobo-- a slow simmered sauce of fire roasted peppers, onions and tomatoes then topped with queso fresco, shredded lettuce, and avocado on a handcrafted tortilla.", 2.99);
m_elpolloloco_customer_favorites->add(chickenless_pollo_taco);
cout << "EXPECTED ITEM NUMBER: 2"
<< "\nRECEIVIED: " << chickenless_pollo_taco->get_item_number() << endl;
EXPECT_EQ(chickenless_pollo_taco->get_item_number(), 2);
menu_component *california_queso_burrito = new menu_items_elpolloloco(3, "Chicken Queso Burrito", "The California Queso Burrito has tender pieces of our famous fire-grilled chicken, signature Tapatio fries, fresh handmade guacamole, pinto beans, queso blanco and house-made pico de gallo. All this goodness comes wrapped in a warm flour tortilla.", 6.99);
m_elpolloloco_customer_favorites->add(california_queso_burrito);
cout << "EXPECTED ITEM NUMBER: 3"
<< "\nRECEIVIED: " << california_queso_burrito->get_item_number() << endl;
EXPECT_EQ(california_queso_burrito->get_item_number(), 3);
menu_component *chicken_tinga_burrito = new menu_items_elpolloloco(4, "Chicken Tinga Burrito", "The Chicken Tinga Burrito has savory, lightly smoky chicken tinga, seasoned rice, pinto beans, fresh sliced avocado, and is topped with queso fresco and house-made pico de gallo – all wrapped in a warm flour tortilla.", 7.19);
m_elpolloloco_customer_favorites->add(chicken_tinga_burrito);
cout << "EXPECTED ITEM NUMBER: 4"
<< "\nRECEIVIED: " << chicken_tinga_burrito->get_item_number() << endl;
EXPECT_EQ(chicken_tinga_burrito->get_item_number(), 4);
menu_component *original_pollo_bowl = new menu_items_elpolloloco(5, "Original Pollo Bowl", "Our chicken breast is fire-grilled to perfection then chopped and added to slow-simmered pinto beans, rice, diced onions, fresh cilantro and pico de gallo salsa.", 4.99);
m_elpolloloco_customer_favorites->add(original_pollo_bowl);
cout << "EXPECTED ITEM NUMBER: 5"
<< "\nRECEIVIED: " << original_pollo_bowl->get_item_number() << endl;
EXPECT_EQ(original_pollo_bowl->get_item_number(), 5);
menu_component *double_chicken_bowl = new menu_items_elpolloloco(6, "Double Chicken Bowl", "Double up on a double portion of delicious citrus-marinated chopped chicken breast on top of authentic pinto beans, rice, cabbage and garnished with sour cream, shredded jack cheese, avocado slices and pico de gallo salsa.", 7.79);
m_elpolloloco_customer_favorites->add(double_chicken_bowl);
cout << "EXPECTED ITEM NUMBER: 6"
<< "\nRECEIVIED: " << double_chicken_bowl->get_item_number() << endl;
EXPECT_EQ(double_chicken_bowl->get_item_number(), 6);
menu_component *chips_and_guacamole_small = new menu_items_elpolloloco(7, "Small Chips & Guacamole", "Made fresh daily, our new guacamole is loaded with chunks of avocado and paired with our authentic tortilla chips.", 2.49);
m_elpolloloco_customer_favorites->add(chips_and_guacamole_small);
cout << "EXPECTED ITEM NUMBER: 7"
<< "\nRECEIVIED: " << chips_and_guacamole_small->get_item_number() << endl;
EXPECT_EQ(chips_and_guacamole_small->get_item_number(), 7);
menu_component *chips_and_guacamole_regular = new menu_items_elpolloloco(8, "Regular Chip & Guacamole", "What's better than our white corn tortilla chips, hand salted and made fresh daily? Our tortilla chips with freshly, hand-made guacamole, of course.", 3.99);
m_elpolloloco_customer_favorites->add(chips_and_guacamole_regular);
cout << "EXPECTED ITEM NUMBER: 8"
<< "\nRECEIVIED: " << chips_and_guacamole_regular->get_item_number() << endl;
EXPECT_EQ(chips_and_guacamole_regular->get_item_number(), 8);
menu_component *drink_regular = new menu_items_elpolloloco(9, "Drink (Regular)", "Refreshing beverage including Coca-cola, Diet Coke, Cherry Coke, Sprite, Dr. Pepper, Strawberry Lemonade, Hi-C Fruit Punch, Fanta Orange, Fuze Raspberry Iced Tea, Passion Fruit Mango Iced Tea, Unsweetened Ice Tea, Barq's Root Beer.", 2.19);
m_elpolloloco_customer_favorites->add(drink_regular);
cout << "EXPECTED ITEM NUMBER: 9"
<< "\nRECEIVIED: " << drink_regular->get_item_number() << endl;
EXPECT_EQ(drink_regular->get_item_number(), 9);
menu_component *drink_large = new menu_items_elpolloloco(10, "Drink (Large)", "Refreshing beverage including Coca-cola, Diet Coke, Cherry Coke, Sprite, Dr. Pepper, Strawberry Lemonade, Hi-C Fruit Punch, Fanta Orange, Fuze Raspberry Iced Tea, Passion Fruit Mango Iced Tea, Unsweetened Ice Tea, Barq's Root Beer.", 2.39);
m_elpolloloco_customer_favorites->add(drink_large);
cout << "EXPECTED ITEM NUMBER: 10"
<< "\nRECEIVIED: " << drink_large->get_item_number() << endl;
EXPECT_EQ(drink_large->get_item_number(), 10);
m_elpolloloco_customer_favorites->print();
}
#endif /* MENU_ELPOLLOLOCO_TESTS */
|
/*
Copyright (c) 2005-2023, University of Oxford.
All rights reserved.
University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.
This file is part of Chaste.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the University of Oxford 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.
*/
#ifndef CMGUIDEFORMEDSOLUTIONSWRITER_HPP_
#define CMGUIDEFORMEDSOLUTIONSWRITER_HPP_
#include "CmguiMeshWriter.hpp"
#include "AbstractTetrahedralMesh.hpp"
#include "QuadraticMesh.hpp"
#include "DistributedQuadraticMesh.hpp"
/**
* Small enumeration for representing whether we want linear
* visualisation of the quadratic mesh (just vertices output)
* or full quadratic visualisation
*/
typedef enum CmguiMeshWriteType_
{
WRITE_LINEAR_MESH = 0,
WRITE_QUADRATIC_MESH
} CmguiMeshWriteType;
/**
* CmguiDeformedSolutionsWriter
*
* A class for writing a mesh, and solutions from a solid mechanics (ie deformed meshes) problem,
* in Cmgui output format.
*
* Inherits from CmguiMeshWriter
*/
template<unsigned DIM>
class CmguiDeformedSolutionsWriter : public CmguiMeshWriter<DIM, DIM>
{
private:
/**
* The quadratic mesh used in the mechanics simulation. solution_0.exnode and solution_0.exelem
* (the only exelem file written) will be written using this mesh
*/
AbstractTetrahedralMesh<DIM,DIM>* mpQuadraticMesh;
/**
* A counter is given whenever WriteDeformationPositions() is called, this variable
* stores the last one used
*/
unsigned mFinalCounter;
/**
* Number of nodes to output - either mpQuadraticMesh->GetNumVertices() (linear visualisation)
* mpQuadraticMesh->GetNumNodes() (quadratic visualisation)
*/
unsigned mNumNodesToUse;
/**
* Overloaded GetNumNodes().
* @return either mpQuadraticMesh->GetNumVertices() for linear
* visualisation or mpQuadraticMesh->GetNumNodes() for quadratic visualisation
*/
unsigned GetNumNodes()
{
return mNumNodesToUse;
}
public:
/**
* Constructor
* @param outputDirectory The output directory for the Cmgui files
* @param baseName The base name for the Cmgui output files - the files written will be
* [basename_0.exnode, [basename]_0.exelem; [basename]_1.exnode, [basename]_2.exnode, ..
* @param rQuadraticMesh The quadratic mesh used in the mechanics simulation
* @param writeType Should be equal to either WRITE_LINEAR_MESH or WRITE_QUADRATIC_MESH,
* depending on whether linear visualisation of the quadratic mesh (just vertices output)
* or full quadratic visualisation is required.
*/
CmguiDeformedSolutionsWriter(std::string outputDirectory,
std::string baseName,
AbstractTetrahedralMesh<DIM,DIM>& rQuadraticMesh,
CmguiMeshWriteType writeType);
/**
* Write [basename]_0.exnode, [basename]_0.exelem using the quadratic mesh
* If the optional argument fileName is given, writes [fileName].exnode
* and [fileName].exelem instead
*
* @param fileName Optional file name (stem).
*/
void WriteInitialMesh(std::string fileName = "");
/**
* Write [basename]_i.exnode using the given deformed positions
* @param rDeformedPositions std::vector of deformed positions to be used, must have size equal to number
* of nodes in the mesh
* @param counter the value "i" in "[basename]_i.exnode" to be used.
*/
void WriteDeformationPositions(std::vector<c_vector<double,DIM> >& rDeformedPositions,
unsigned counter);
/**
* Writes a small cmgui script called LoadSolutions.com, for loading the output that has been written.
* Assumes the output was solution_0.exnode .. solution_N.exnode, where N is the counter that was
* given in the last call to WriteDeformationPositions()
*
* @param fieldBaseName If there is a field to visualise on top of the deforming mesh, give it's
* path (relative to the cmgui deformation directory), and filename prefix. Leave empty
* if no field to visualise.
* For example,
* WriteCmguiScript("../../electrics/cmgui_output/voltage_mechanics_mesh");
* for the script to read files voltage_mechanics_mesh_0.exnode .. voltage_mechanics_mesh_N.exnode.
*
* @param undeformedBaseName is assumed to be "solution_0.exnode" and .exelem unless this optional
* parameter is given. Depends on what parameters were given to WriteInitialMesh(). If
* undeformedBaseName the time given to plot the undeformed shape is set to -1, otherwise
* it is set to 0.
*/
void WriteCmguiScript(std::string fieldBaseName="", std::string undeformedBaseName="");
/**
* For a simulation that has already been run, convert the chaste output to cmgui format.
* @param inputDirectory The directory the chaste output is in
* @param inputFileBaseName The base name for the chaste output
* @param finalCounter The final counter, ie the value N for the final file [basename]_N.nodes.
* The first file is assumed to be [basename]_0.nodes. The files [basename]_0.nodes up to
* [basename]_N.nodes will be converted to cmgui format and put in the output directory
* given in the constructor.
*/
void ConvertOutput(std::string inputDirectory,
std::string inputFileBaseName,
unsigned finalCounter);
};
#endif /*CMGUIDEFORMEDSOLUTIONSWRITER_HPP_*/
|
/* Copyright (c) 2008-2015 Jordi Santiago Provencio
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 "emyl.h"
#include <atomic>
#include <memory>
#include <vector>
#include <set>
#include <map>
#include <string>
#include <iostream>
#include <cstring>
#include <cstdint>
#include <chrono>
#ifdef _WINDOWS
#include <al.h>
#include <alc.h>
#else
#include <AL/al.h>
#include <AL/alc.h>
#endif
#ifdef ANDROID
#include <android/asset_manager.h>
#endif
#include <ogg/ogg.h>
#include <vorbis/codec.h>
#include <vorbis/vorbisenc.h>
#include <vorbis/vorbisfile.h>
using std::shared_ptr;
#include <spdlog/spdlog.h>
#include <Log.hpp>
namespace Emyl
{
namespace internal
{
void alCheckError(const char* file, unsigned int line, const char* expression)
{
// Get the last error
ALenum errorCode = alGetError();
if (errorCode != AL_NO_ERROR)
{
std::string fileString = file;
std::string error = "Unknown error";
std::string description = "No description";
// Decode the error code
switch (errorCode)
{
case AL_INVALID_NAME:
{
error = "AL_INVALID_NAME";
description = "A bad name (ID) has been specified.";
break;
}
case AL_INVALID_ENUM:
{
error = "AL_INVALID_ENUM";
description = "An unacceptable value has been specified for an enumerated argument.";
break;
}
case AL_INVALID_VALUE:
{
error = "AL_INVALID_VALUE";
description = "A numeric argument is out of range.";
break;
}
case AL_INVALID_OPERATION:
{
error = "AL_INVALID_OPERATION";
description = "The specified operation is not allowed in the current state.";
break;
}
case AL_OUT_OF_MEMORY:
{
error = "AL_OUT_OF_MEMORY";
description = "There is not enough memory left to execute the command.";
break;
}
}
/*
EMYL_WARN("An internal OpenAL call failed in %s (%d).\n",
"Expression:\n%s\n",
"Error description:\n %s\n %s\n",
fileString.substr(fileString.find_last_of("\\/") + 1).c_str(),
line, expression, error.c_str(), description.c_str());
*/
}
}
//---------------------------------------------------------------------------//
Device* Device::instance(nullptr);
bool Device::is_initialized(false);
std::string Device::name("");
std::string Device::ext("");
float Device::listenerVolume(100.f);
Vec3 Device::listenerPosition(0.f, 0.f, 0.f);
Vec3 Device::listenerDirection(0.f, 0.f, -1.f);
Vec3 Device::listenerUpVector (0.f, 1.f, 0.f);
//---------------------------------------------------------------------------//
Device::Device()
: m_alDev(nullptr)
, m_alContext(nullptr)
{
initialize();
}
//---------------------------------------------------------------------------//
Device::~Device()
{
deinitialize();
}
//---------------------------------------------------------------------------//
bool Device::initialize()
{
using namespace std::string_literals;
m_alDev = alcOpenDevice(nullptr);
if (m_alDev)
{
name = alcGetString(m_alDev, ALC_DEVICE_SPECIFIER);
ext = alcGetString(m_alDev, ALC_EXTENSIONS);
m_alContext = alcCreateContext(m_alDev, nullptr);
if (m_alContext)
{
alcMakeContextCurrent(m_alContext);
float orientation[] = {
listenerDirection.x,
listenerDirection.y,
listenerDirection.z,
listenerUpVector.x,
listenerUpVector.y,
listenerUpVector.z
};
alCheck(alListenerf(AL_GAIN, listenerVolume * 0.01f));
alCheck(alListener3f(AL_POSITION, listenerPosition.x, listenerPosition.y, listenerPosition.z));
alCheck(alListenerfv(AL_ORIENTATION, orientation));
}
else
{
EMYL_WARN("OpenAL error: Context can't be created.");
return false;
}
}
else
{
EMYL_WARN("OpenAL error: Could not init OpenAL.\n");
return false;
}
return true;
}
//---------------------------------------------------------------------------//
void Device::deinitialize()
{
alcMakeContextCurrent(nullptr);
if (m_alContext)
alcDestroyContext(m_alContext);
if (m_alDev)
alcCloseDevice(m_alDev);
}
//---------------------------------------------------------------------------//
bool Device::isExtensionSupported(const std::string& extension)
{
// Create a temporary audio device in case none exists yet.
// This device will not be used in this function and merely
// makes sure there is a valid OpenAL device for extension
// queries if none has been created yet.
ALCdevice* audioDevice;
std::unique_ptr<Device> device;
if (instance != nullptr && instance->m_alDev != nullptr)
audioDevice = instance->m_alDev;
else
{
device = std::unique_ptr<Device>(new Device());
audioDevice = device->m_alDev;
}
if ((extension.length() > 2) && (extension.substr(0, 3) == "ALC"))
return alcIsExtensionPresent(audioDevice, extension.c_str()) != AL_FALSE;
else
return alIsExtensionPresent(extension.c_str()) != AL_FALSE;
}
//---------------------------------------------------------------------------//
int Device::getFormatFromChannelCount(unsigned int channelCount)
{
// Create a temporary audio device in case none exists yet.
// This device will not be used in this function and merely
// makes sure there is a valid OpenAL device for format
// queries if none has been created yet.
std::unique_ptr<Device> device;
if (instance == nullptr || instance->m_alDev == nullptr)
device = std::unique_ptr<Device>(new Device());
// Find the good format according to the number of channels
int format = 0;
switch (channelCount)
{
case 1: format = AL_FORMAT_MONO16; break;
case 2: format = AL_FORMAT_STEREO16; break;
case 4: format = alGetEnumValue("AL_FORMAT_QUAD16"); break;
case 6: format = alGetEnumValue("AL_FORMAT_51CHN16"); break;
case 7: format = alGetEnumValue("AL_FORMAT_61CHN16"); break;
case 8: format = alGetEnumValue("AL_FORMAT_71CHN16"); break;
default: format = 0; break;
}
// Fixes a bug on OS X
if (format == -1)
format = 0;
return format;
}
//---------------------------------------------------------------------------//
void Device::setGlobalVolume(float volume)
{
if (instance && instance->m_alContext)
alCheck(alListenerf(AL_GAIN, volume * 0.01f));
listenerVolume = volume;
}
//---------------------------------------------------------------------------//
float Device::getGlobalVolume()
{
return listenerVolume;
}
//---------------------------------------------------------------------------//
void Device::setPosition(const Vec3& position)
{
if (instance && instance->m_alContext)
alCheck(alListener3f(AL_POSITION, position.x, position.y, position.z));
listenerPosition = position;
}
//---------------------------------------------------------------------------//
Vec3 Device::getPosition()
{
return listenerPosition;
}
//---------------------------------------------------------------------------//
void Device::setDirection(const Vec3& direction)
{
if (instance && instance->m_alContext)
{
float orientation[] = {direction.x, direction.y, direction.z, listenerUpVector.x, listenerUpVector.y, listenerUpVector.z};
alCheck(alListenerfv(AL_ORIENTATION, orientation));
}
listenerDirection = direction;
}
//---------------------------------------------------------------------------//
Vec3 Device::getDirection()
{
return listenerDirection;
}
//---------------------------------------------------------------------------//
void Device::setUpVector(const Vec3& upVector)
{
if (instance && instance->m_alContext)
{
float orientation[] = {
listenerDirection.x,
listenerDirection.y,
listenerDirection.z,
upVector.x, upVector.y, upVector.z};
alCheck(alListenerfv(AL_ORIENTATION, orientation));
}
listenerUpVector = upVector;
}
//---------------------------------------------------------------------------//
Vec3 Device::getUpVector()
{
return listenerUpVector;
}
//---------------------------------------------------------------------------//
//-Resource------------------------------------------------------------------//
//---------------------------------------------------------------------------//
std::atomic<unsigned int> s_resourceCount(0);
//---------------------------------------------------------------------------//
Resource::Resource()
{
unsigned int currentCount = s_resourceCount++;
if (currentCount == 0)
{
Device::instance = new Device;
}
}
//---------------------------------------------------------------------------//
Resource::~Resource()
{
unsigned int currentCount = --s_resourceCount;
if (currentCount == 0)
{
delete Device::instance;
Device::instance = nullptr;
}
}
//---------------------------------------------------------------------------//
//-Android-ResourceStream----------------------------------------------------//
//---------------------------------------------------------------------------//
#ifdef ANDROID
class ResourceStream : public InputStream
{
public:
ResourceStream(const std::string& filename);
~ResourceStream();
std::int64_t read(void *data, std::int64_t size);
std::int64_t seek(std::int64_t position);
std::int64_t tell();
std::int64_t getSize();
private:
AAsset* m_file; ///< The asset file to read
};
//---------------------------------------------------------------------------//
ResourceStream::ResourceStream(const std::string& filename) :
m_file (NULL)
{
ActivityStates* states = getActivity(NULL);
Lock(states->mutex);
m_file = AAssetManager_open(states->activity->assetManager, filename.c_str(), AASSET_MODE_UNKNOWN);
}
//---------------------------------------------------------------------------//
ResourceStream::~ResourceStream()
{
AAsset_close(m_file);
}
//---------------------------------------------------------------------------//
std::int64_t ResourceStream::read(void *data, std::int64_t size)
{
return AAsset_read(m_file, data, size);
}
//---------------------------------------------------------------------------//
std::int64_t ResourceStream::seek(std::int64_t position)
{
return AAsset_seek(m_file, position, SEEK_SET);
}
//---------------------------------------------------------------------------//
std::int64_t ResourceStream::tell()
{
return getSize() - AAsset_getRemainingLength(m_file);
}
//---------------------------------------------------------------------------//
std::int64_t ResourceStream::getSize()
{
return AAsset_getLength(m_file);
}
#endif
//---------------------------------------------------------------------------//
//-SoundFileFactory----------------------------------------------------------//
//---------------------------------------------------------------------------//
class SoundFileFactory
{
public:
static SoundFileReader* createReaderFromFilename(const std::string& filename);
static SoundFileReader* createReaderFromMemory(const void* data, std::size_t sizeInBytes);
static SoundFileReader* createReaderFromStream(InputStream& stream);
static void AddReader(ReaderFactory& factory);
static void RemoveReader(SoundFileReader* (*create)());
private:
typedef std::vector<ReaderFactory> ReaderFactoryArray;
static ReaderFactoryArray s_readers;
};
//---------------------------------------------------------------------------//
SoundFileFactory::ReaderFactoryArray SoundFileFactory::s_readers;
//---------------------------------------------------------------------------//
SoundFileReader* SoundFileFactory::createReaderFromFilename(const std::string& filename)
{
// Wrap the input file into a file stream
FileInputStream stream;
if (!stream.open(filename)) {
be::utils::log::warn("Failed to open sound file {} (couldb't open stream)", filename);
//EMYL_WARN("Failed to open sound file \"%s\" (couldn't open stream)\n", filename.c_str());
return nullptr;
}
// Test the filename in all the registered factories
for (ReaderFactoryArray::const_iterator it = s_readers.begin(); it != s_readers.end(); ++it)
{
stream.seek(0);
if (it->check(stream))
return it->create();
}
// No suitable reader found
be::utils::log::warn("Failed to open sound file {} (format not supported)", filename);
//EMYL_WARN("Failed to open sound file \"%s\" (format not supported)\n", filename.c_str());
return nullptr;
}
//---------------------------------------------------------------------------//
SoundFileReader* SoundFileFactory::createReaderFromMemory(const void* data, std::size_t sizeInBytes)
{
// Wrap the memory file into a file stream
MemoryInputStream stream;
stream.open(data, sizeInBytes);
// Test the stream for all the registered factories
for (ReaderFactoryArray::const_iterator it = s_readers.begin(); it != s_readers.end(); ++it)
{
stream.seek(0);
if (it->check(stream))
return it->create();
}
// No suitable reader found
be::utils::log::warn("Failed to open sound file from memory {} (format not supported)");
//EMYL_WARN("Failed to open sound file from memory (format not supported)\n");
return nullptr;
}
//---------------------------------------------------------------------------//
SoundFileReader* SoundFileFactory::createReaderFromStream(InputStream& stream)
{
// Test the stream for all the registered factories
for (ReaderFactoryArray::const_iterator it = s_readers.begin(); it != s_readers.end(); ++it)
{
stream.seek(0);
if (it->check(stream))
return it->create();
}
// No suitable reader found
be::utils::log::warn("Failed to open sound file from stream {} (format not supported)");
//EMYL_WARN("Failed to open sound file from stream (format not supported)\n");
return nullptr;
}
//---------------------------------------------------------------------------//
void SoundFileFactory::AddReader(ReaderFactory& factory)
{
s_readers.push_back(factory);
}
//---------------------------------------------------------------------------//
void SoundFileFactory::RemoveReader(SoundFileReader* (*create)())
{
for (ReaderFactoryArray::iterator it = s_readers.begin(); it != s_readers.end(); )
{
if (it->create == create)
it = s_readers.erase(it);
else
++it;
}
}
//---------------------------------------------------------------------------//
//-ReaderFactory-------------------------------------------------------------//
//---------------------------------------------------------------------------//
void ReaderFactoryAdd(ReaderFactory& factory)
{
SoundFileFactory::AddReader(factory);
}
//---------------------------------------------------------------------------//
void ReaderFactoryRemove(SoundFileReader* (*create)())
{
SoundFileFactory::RemoveReader(create);
}
} //namespace internal
//---------------------------------------------------------------------------//
//-Listener------------------------------------------------------------------//
//---------------------------------------------------------------------------//
void Listener::setGlobalVolume(float volume)
{
internal::Device::setGlobalVolume(volume);
}
//---------------------------------------------------------------------------//
float Listener::getGlobalVolume()
{
return internal::Device::getGlobalVolume();
}
//---------------------------------------------------------------------------//
void Listener::setPosition(float x, float y, float z)
{
setPosition(Vec3(x, y, z));
}
//---------------------------------------------------------------------------//
void Listener::setPosition(const Vec3& position)
{
internal::Device::setPosition(position);
}
//---------------------------------------------------------------------------//
Vec3 Listener::getPosition()
{
return internal::Device::getPosition();
}
//---------------------------------------------------------------------------//
void Listener::setDirection(float x, float y, float z)
{
setDirection(Vec3(x, y, z));
}
//---------------------------------------------------------------------------//
void Listener::setDirection(const Vec3& direction)
{
internal::Device::setDirection(direction);
}
//---------------------------------------------------------------------------//
Vec3 Listener::getDirection()
{
return internal::Device::getDirection();
}
//---------------------------------------------------------------------------//
void Listener::setUpVector(float x, float y, float z)
{
setUpVector(Vec3(x, y, z));
}
//---------------------------------------------------------------------------//
void Listener::setUpVector(const Vec3& upVector)
{
internal::Device::setUpVector(upVector);
}
//---------------------------------------------------------------------------//
Vec3 Listener::getUpVector()
{
return internal::Device::getUpVector();
}
//---------------------------------------------------------------------------//
//-Source--------------------------------------------------------------------//
//---------------------------------------------------------------------------//
Source::Source()
{
alCheck(alGenSources(1, &m_source));
alCheck(alSourcei(m_source, AL_BUFFER, 0));
}
//---------------------------------------------------------------------------//
Source::Source(const Source& copy)
{
alCheck(alGenSources(1, &m_source));
alCheck(alSourcei(m_source, AL_BUFFER, 0));
setPitch(copy.getPitch());
setVolume(copy.getVolume());
setPosition(copy.getPosition());
setRelativeToListener(copy.isRelativeToListener());
setMinDistance(copy.getMinDistance());
setAttenuation(copy.getAttenuation());
}
//---------------------------------------------------------------------------//
Source::~Source()
{
alCheck(alSourcei(m_source, AL_BUFFER, 0));
alCheck(alDeleteSources(1, &m_source));
}
//---------------------------------------------------------------------------//
void Source::setPitch(float pitch)
{
alCheck(alSourcef(m_source, AL_PITCH, pitch));
}
//---------------------------------------------------------------------------//
void Source::setVolume(float volume)
{
alCheck(alSourcef(m_source, AL_GAIN, volume * 0.01f));
}
//---------------------------------------------------------------------------//
void Source::setPosition(float x, float y, float z)
{
alCheck(alSource3f(m_source, AL_POSITION, x, y, z));
}
//---------------------------------------------------------------------------//
void Source::setPosition(const Vec3& position)
{
setPosition(position.x, position.y, position.z);
}
//---------------------------------------------------------------------------//
void Source::setRelativeToListener(bool relative)
{
alCheck(alSourcei(m_source, AL_SOURCE_RELATIVE, relative));
}
//---------------------------------------------------------------------------//
void Source::setMinDistance(float distance)
{
alCheck(alSourcef(m_source, AL_REFERENCE_DISTANCE, distance));
}
//---------------------------------------------------------------------------//
void Source::setAttenuation(float attenuation)
{
alCheck(alSourcef(m_source, AL_ROLLOFF_FACTOR, attenuation));
}
//---------------------------------------------------------------------------//
float Source::getPitch() const
{
ALfloat pitch;
alCheck(alGetSourcef(m_source, AL_PITCH, &pitch));
return pitch;
}
//---------------------------------------------------------------------------//
float Source::getVolume() const
{
ALfloat gain;
alCheck(alGetSourcef(m_source, AL_GAIN, &gain));
return gain * 100.f;
}
//---------------------------------------------------------------------------//
Vec3 Source::getPosition() const
{
Vec3 position;
alCheck(alGetSource3f(m_source, AL_POSITION, &position.x, &position.y, &position.z));
return position;
}
//---------------------------------------------------------------------------//
bool Source::isRelativeToListener() const
{
ALint relative;
alCheck(alGetSourcei(m_source, AL_SOURCE_RELATIVE, &relative));
return relative != 0;
}
//---------------------------------------------------------------------------//
float Source::getMinDistance() const
{
ALfloat distance;
alCheck(alGetSourcef(m_source, AL_REFERENCE_DISTANCE, &distance));
return distance;
}
//---------------------------------------------------------------------------//
float Source::getAttenuation() const
{
ALfloat attenuation;
alCheck(alGetSourcef(m_source, AL_ROLLOFF_FACTOR, &attenuation));
return attenuation;
}
//---------------------------------------------------------------------------//
Source& Source::operator=(const Source& right)
{
setPitch(right.getPitch());
setVolume(right.getVolume());
setPosition(right.getPosition());
setRelativeToListener(right.isRelativeToListener());
setMinDistance(right.getMinDistance());
setAttenuation(right.getAttenuation());
return *this;
}
//---------------------------------------------------------------------------//
Source::State Source::getState() const
{
ALint status;
alCheck(alGetSourcei(m_source, AL_SOURCE_STATE, &status));
switch (status)
{
case AL_INITIAL:
case AL_STOPPED: return Stopped;
case AL_PAUSED: return Paused;
case AL_PLAYING: return Playing;
}
return Stopped;
}
//---------------------------------------------------------------------------//
//-Sound---------------------------------------------------------------------//
//---------------------------------------------------------------------------//
Sound::Sound()
: m_buffer(nullptr)
{
}
//---------------------------------------------------------------------------//
Sound::Sound(const Buffer& buffer)
: m_buffer(nullptr)
{
setBuffer(buffer);
}
//---------------------------------------------------------------------------//
Sound::Sound(const Sound& copy)
: Source(copy)
, m_buffer(nullptr)
{
if (copy.m_buffer)
setBuffer(*copy.m_buffer);
setLoop(copy.getLoop());
}
//---------------------------------------------------------------------------//
Sound::~Sound()
{
stop();
if (m_buffer)
m_buffer->detachSound(this);
}
//---------------------------------------------------------------------------//
void Sound::play()
{
alCheck(alSourcePlay(m_source));
}
//---------------------------------------------------------------------------//
void Sound::pause()
{
alCheck(alSourcePause(m_source));
}
//---------------------------------------------------------------------------//
void Sound::stop()
{
alCheck(alSourceStop(m_source));
}
//---------------------------------------------------------------------------//
void Sound::setBuffer(const Buffer& buffer)
{
// First detach from the previous buffer
if (m_buffer)
{
stop();
m_buffer->detachSound(this);
}
// Assign and use the new buffer
m_buffer = &buffer;
m_buffer->attachSound(this);
alCheck(alSourcei(m_source, AL_BUFFER, m_buffer->m_buffer));
}
//---------------------------------------------------------------------------//
void Sound::setLoop(bool loop)
{
alCheck(alSourcei(m_source, AL_LOOPING, loop));
}
//---------------------------------------------------------------------------//
void Sound::setPlayingOffset(ALfloat timeOffset)
{
alCheck(alSourcef(m_source, AL_SEC_OFFSET, timeOffset));
}
//---------------------------------------------------------------------------//
const Buffer* Sound::getBuffer() const
{
return m_buffer;
}
//---------------------------------------------------------------------------//
bool Sound::getLoop() const
{
ALint loop;
alCheck(alGetSourcei(m_source, AL_LOOPING, &loop));
return loop != 0;
}
//---------------------------------------------------------------------------//
ALfloat Sound::getPlayingOffset() const
{
ALfloat secs = 0.f;
alCheck(alGetSourcef(m_source, AL_SEC_OFFSET, &secs));
return secs;
}
//---------------------------------------------------------------------------//
Sound::State Sound::getState() const
{
return Source::getState();
}
//---------------------------------------------------------------------------//
Sound& Sound::operator =(const Sound& right)
{
Source::operator=(right);
if (m_buffer)
{
stop();
m_buffer->detachSound(this);
m_buffer = NULL;
}
if (right.m_buffer)
setBuffer(*right.m_buffer);
setLoop(right.getLoop());
return *this;
}
//---------------------------------------------------------------------------//
void Sound::resetBuffer()
{
stop();
if (m_buffer)
{
alCheck(alSourcei(m_source, AL_BUFFER, 0));
m_buffer->detachSound(this);
m_buffer = nullptr;
}
}
//---------------------------------------------------------------------------//
//-FileInputStream-----------------------------------------------------------//
//---------------------------------------------------------------------------//
#ifdef ANDROID
FileInputStream::FileInputStream()
: m_file(NULL)
{
}
//---------------------------------------------------------------------------//
FileInputStream::~FileInputStream()
{
if (m_file)
delete m_file;
}
//---------------------------------------------------------------------------//
bool FileInputStream::open(const std::string& filename)
{
if (m_file)
delete m_file;
m_file = new priv::ResourceStream(filename);
return m_file->tell() != -1;
}
//---------------------------------------------------------------------------//
std::int64_t FileInputStream::read(void* data, std::int64_t size)
{
return m_file->read(data, size);
}
//---------------------------------------------------------------------------//
std::int64_t FileInputStream::seek(std::int64_t position)
{
return m_file->seek(position);
}
//---------------------------------------------------------------------------//
std::int64_t FileInputStream::tell()
{
return m_file->tell();
}
//---------------------------------------------------------------------------//
std::int64_t FileInputStream::getSize()
{
return m_file->getSize();
}
#else //---------------------------------------------------------------------//
FileInputStream::FileInputStream()
: m_file(NULL)
{
}
//---------------------------------------------------------------------------//
FileInputStream::~FileInputStream()
{
if (m_file)
std::fclose(m_file);
}
//---------------------------------------------------------------------------//
bool FileInputStream::open(const std::string& filename)
{
if (m_file)
std::fclose(m_file);
fopen_s(&m_file, filename.c_str(), "rb");
return m_file != NULL;
}
//---------------------------------------------------------------------------//
std::int64_t FileInputStream::read(void* data, std::int64_t size)
{
if (m_file)
return std::fread(data, 1, static_cast<std::size_t>(size), m_file);
else
return -1;
}
//---------------------------------------------------------------------------//
std::int64_t FileInputStream::seek(std::int64_t position)
{
if (m_file)
{
std::fseek(m_file, static_cast<long>(position), SEEK_SET);
return tell();
}
else
{
return -1;
}
}
//---------------------------------------------------------------------------//
std::int64_t FileInputStream::tell()
{
if (m_file)
return std::ftell(m_file);
else
return -1;
}
//---------------------------------------------------------------------------//
std::int64_t FileInputStream::getSize()
{
if (m_file)
{
std::int64_t position = tell();
std::fseek(m_file, 0, SEEK_END);
std::int64_t size = tell();
seek(position);
return size;
}
else
{
return -1;
}
}
#endif
//---------------------------------------------------------------------------//
//-MemoryInputStream---------------------------------------------------------//
//---------------------------------------------------------------------------//
MemoryInputStream::MemoryInputStream()
: m_data (NULL)
, m_size (0)
, m_offset(0)
{
}
//---------------------------------------------------------------------------//
void MemoryInputStream::open(const void* data, std::size_t sizeInBytes)
{
m_data = static_cast<const char*>(data);
m_size = sizeInBytes;
m_offset = 0;
}
//---------------------------------------------------------------------------//
std::int64_t MemoryInputStream::read(void* data, std::int64_t size)
{
if (!m_data)
return -1;
std::int64_t endPosition = m_offset + size;
std::int64_t count = endPosition <= m_size ? size : m_size - m_offset;
if (count > 0)
{
std::memcpy(data, m_data + m_offset, static_cast<std::size_t>(count));
m_offset += count;
}
return count;
}
//---------------------------------------------------------------------------//
std::int64_t MemoryInputStream::seek(std::int64_t position)
{
if (!m_data)
return -1;
m_offset = position < m_size ? position : m_size;
return m_offset;
}
//---------------------------------------------------------------------------//
std::int64_t MemoryInputStream::tell()
{
if (!m_data)
return -1;
return m_offset;
}
//---------------------------------------------------------------------------//
std::int64_t MemoryInputStream::getSize()
{
if (!m_data)
return -1;
return m_size;
}
//---------------------------------------------------------------------------//
//-InputSoundFile------------------------------------------------------------//
//---------------------------------------------------------------------------//
InputSoundFile::InputSoundFile()
: m_reader(NULL)
, m_stream(NULL)
, m_streamOwned (false)
, m_sampleCount (0)
, m_channelCount(0)
, m_sampleRate(0)
{
}
//---------------------------------------------------------------------------//
InputSoundFile::~InputSoundFile()
{
close();
}
//---------------------------------------------------------------------------//
bool InputSoundFile::openFromFile(const std::string& filename)
{
// If the file is already open, first close it
close();
// Find a suitable reader for the file type
m_reader = internal::SoundFileFactory::createReaderFromFilename(filename);
if (!m_reader)
return false;
// Wrap the file into a stream
FileInputStream* file = new FileInputStream;
m_stream = file;
m_streamOwned = true;
// Open it
if (!file->open(filename))
{
close();
return false;
}
// Pass the stream to the reader
SoundFileReader::Info info;
if (!m_reader->open(*file, info))
{
close();
return false;
}
// Retrieve the attributes of the open sound file
m_sampleCount = info.sampleCount;
m_channelCount = info.channelCount;
m_sampleRate = info.sampleRate;
return true;
}
//---------------------------------------------------------------------------//
bool InputSoundFile::openFromMemory(const void* data, std::size_t sizeInBytes)
{
// If the file is already open, first close it
close();
// Find a suitable reader for the file type
m_reader = internal::SoundFileFactory::createReaderFromMemory(data, sizeInBytes);
if (!m_reader)
return false;
// Wrap the memory file into a stream
MemoryInputStream* memory = new MemoryInputStream;
m_stream = memory;
m_streamOwned = true;
// Open it
memory->open(data, sizeInBytes);
// Pass the stream to the reader
SoundFileReader::Info info;
if (!m_reader->open(*memory, info))
{
close();
return false;
}
// Retrieve the attributes of the open sound file
m_sampleCount = info.sampleCount;
m_channelCount = info.channelCount;
m_sampleRate = info.sampleRate;
return true;
}
//---------------------------------------------------------------------------//
bool InputSoundFile::openFromStream(InputStream& stream)
{
// If the file is already open, first close it
close();
// Find a suitable reader for the file type
m_reader = internal::SoundFileFactory::createReaderFromStream(stream);
if (!m_reader)
return false;
// store the stream
m_stream = &stream;
m_streamOwned = false;
// Don't forget to reset the stream to its beginning before re-opening it
if (stream.seek(0) != 0)
{
be::utils::log::warn("Failed to open sound file from stream (cannot restart stream)");
//internal::EMYL_LOG("Failed to open sound file from stream (cannot restart stream)\n");
return false;
}
// Pass the stream to the reader
SoundFileReader::Info info;
if (!m_reader->open(stream, info))
{
close();
return false;
}
// Retrieve the attributes of the open sound file
m_sampleCount = info.sampleCount;
m_channelCount = info.channelCount;
m_sampleRate = info.sampleRate;
return true;
}
//---------------------------------------------------------------------------//
std::uint64_t InputSoundFile::getSampleCount() const
{
return m_sampleCount;
}
//---------------------------------------------------------------------------//
unsigned int InputSoundFile::getChannelCount() const
{
return m_channelCount;
}
//---------------------------------------------------------------------------//
unsigned int InputSoundFile::getSampleRate() const
{
return m_sampleRate;
}
//---------------------------------------------------------------------------//
ALfloat InputSoundFile::getDuration() const
{
return static_cast<float>(m_sampleCount) / m_channelCount / m_sampleRate;
}
//---------------------------------------------------------------------------//
void InputSoundFile::seek(std::uint64_t sampleOffset)
{
if (m_reader)
m_reader->seek(sampleOffset);
}
//---------------------------------------------------------------------------//
void InputSoundFile::seek(ALfloat timeOffset)
{
seek(static_cast<std::uint64_t>(timeOffset * m_sampleRate * m_channelCount));
}
//---------------------------------------------------------------------------//
std::uint64_t InputSoundFile::read(std::int16_t* samples, std::uint64_t maxCount)
{
if (m_reader && samples && maxCount)
return m_reader->read(samples, maxCount);
else
return 0;
}
//---------------------------------------------------------------------------//
void InputSoundFile::close()
{
// Destroy the reader
delete m_reader;
m_reader = NULL;
// Destroy the stream if we own it
if (m_streamOwned)
{
delete m_stream;
m_streamOwned = false;
}
m_stream = NULL;
// Reset the sound file attributes
m_sampleCount = 0;
m_channelCount = 0;
m_sampleRate = 0;
}
//---------------------------------------------------------------------------//
//-Buffer--------------------------------------------------------------------//
//---------------------------------------------------------------------------//
Buffer::Buffer()
: m_buffer(0)
, m_duration()
{
alCheck(alGenBuffers(1, &m_buffer));
}
//---------------------------------------------------------------------------//
Buffer::Buffer(const Buffer& copy)
: m_buffer(0)
, m_samples(copy.m_samples)
, m_duration(copy.m_duration)
, m_sounds()
{
alCheck(alGenBuffers(1, &m_buffer));
// Update the internal buffer with the new samples
update(copy.getChannelCount(), copy.getSampleRate());
}
//---------------------------------------------------------------------------//
Buffer::~Buffer()
{
SoundList sounds;
sounds.swap(m_sounds);
for (SoundList::const_iterator it = sounds.begin(); it != sounds.end(); ++it)
(*it)->resetBuffer();
if (m_buffer)
alCheck(alDeleteBuffers(1, &m_buffer));
}
//---------------------------------------------------------------------------//
bool Buffer::loadFromFile(const std::string& filename)
{
InputSoundFile file;
if (file.openFromFile(filename))
return initialize(file);
else
return false;
}
//---------------------------------------------------------------------------//
bool Buffer::loadFromMemory(const void* data, std::size_t sizeInBytes)
{
InputSoundFile file;
if (file.openFromMemory(data, sizeInBytes))
return initialize(file);
else
return false;
}
//---------------------------------------------------------------------------//
bool Buffer::loadFromStream(InputStream& stream)
{
InputSoundFile file;
if (file.openFromStream(stream))
return initialize(file);
else
return false;
}
//---------------------------------------------------------------------------//
bool Buffer::loadFromSamples(const std::int16_t* samples, std::uint64_t sampleCount, unsigned int channelCount, unsigned int sampleRate)
{
if (samples && sampleCount && channelCount && sampleRate)
{
m_samples.assign(samples, samples + sampleCount);
return update(channelCount, sampleRate);
}
else
{
be::utils::log::warn("Failed to load sound buffer from samples ( \
array: {}, count: {}, channels: {}, samplerate: {})",
*samples, sampleCount, channelCount, sampleRate);
//EMYL_WARN("Failed to load sound buffer from samples (array: %p, count: %llu, channels: %d, samplerate: %d)\n"
//, samples, sampleCount, channelCount, sampleRate);
//EMYL_WARN("Failed to load sound buffer from samples ("
//"array: %p, count: %d, channels: %d, samplerate: %d)\n"
//, samples, sampleCount, channelCount, sampleRate);
//EMYL_WARN("Failed to load sound buffer from samples (array: %p, count: %llu, channels: %d, samplerate: %d)\n"
// , samples, sampleCount, channelCount, sampleRate);
return false;
}
}
//---------------------------------------------------------------------------//
const std::int16_t* Buffer::getSamples() const
{
return m_samples.empty() ? nullptr : &m_samples[0];
}
//---------------------------------------------------------------------------//
std::uint64_t Buffer::getSampleCount() const
{
return m_samples.size();
}
//---------------------------------------------------------------------------//
unsigned int Buffer::getSampleRate() const
{
ALint sampleRate;
alCheck(alGetBufferi(m_buffer, AL_FREQUENCY, &sampleRate));
return sampleRate;
}
//---------------------------------------------------------------------------//
unsigned int Buffer::getChannelCount() const
{
ALint channelCount;
alCheck(alGetBufferi(m_buffer, AL_CHANNELS, &channelCount));
return channelCount;
}
//---------------------------------------------------------------------------//
ALfloat Buffer::getDuration() const
{
return m_duration;
}
//---------------------------------------------------------------------------//
Buffer& Buffer::operator =(const Buffer& right)
{
Buffer temp(right);
std::swap(m_samples, temp.m_samples);
std::swap(m_buffer, temp.m_buffer);
std::swap(m_duration, temp.m_duration);
std::swap(m_sounds, temp.m_sounds); // swap sounds too, so that they are detached when temp is destroyed
return *this;
}
//---------------------------------------------------------------------------//
bool Buffer::initialize(InputSoundFile& file)
{
// Retrieve the sound parameters
std::uint64_t sampleCount = file.getSampleCount();
unsigned int channelCount = file.getChannelCount();
unsigned int sampleRate = file.getSampleRate();
// Read the samples from the provided file
m_samples.resize(static_cast<std::size_t>(sampleCount));
if (file.read(&m_samples[0], sampleCount) == sampleCount)
{
// Update the internal buffer with the new samples
return update(channelCount, sampleRate);
}
else
{
return false;
}
}
//---------------------------------------------------------------------------//
bool Buffer::update(unsigned int channelCount, unsigned int sampleRate)
{
// Check parameters
if (!channelCount || !sampleRate || m_samples.empty())
return false;
// Find the good format according to the number of channels
ALenum format = internal::Device::getFormatFromChannelCount(channelCount);
// Check if the format is valid
if (format == 0)
{
be::utils::log::warn("Failed to open sound file from stream (cannot restart stream)");
//internal::EMYL_LOG("Failed to load sound buffer (unsupported number of channels: %d)\n"); // ,channelCount
return false;
}
// First make a copy of the list of sounds so we can reattach later
SoundList sounds(m_sounds);
// Detach the buffer from the sounds that use it (to avoid OpenAL errors)
for (SoundList::const_iterator it = sounds.begin(); it != sounds.end(); ++it)
(*it)->resetBuffer();
// Fill the buffer
ALsizei size = static_cast<ALsizei>(m_samples.size()) * sizeof(std::int16_t);
alCheck(alBufferData(m_buffer, format, &m_samples[0], size, sampleRate));
// Compute the duration
m_duration = static_cast<float>(m_samples.size()) / sampleRate / channelCount;
// Now reattach the buffer to the sounds that use it
for (SoundList::const_iterator it = sounds.begin(); it != sounds.end(); ++it)
(*it)->setBuffer(*this);
return true;
}
//---------------------------------------------------------------------------//
void Buffer::attachSound(Sound* sound) const
{
m_sounds.insert(sound);
}
//---------------------------------------------------------------------------//
void Buffer::detachSound(Sound* sound) const
{
m_sounds.erase(sound);
}
//---------------------------------------------------------------------------//
//-Stream--------------------------------------------------------------------//
//---------------------------------------------------------------------------//
Stream::Stream()
: m_thread()
, m_threadMutex()
, m_threadStartState(Stopped)
, m_isStreaming(false)
, m_buffers()
, m_channelCount(0)
, m_sampleRate(0)
, m_format(0)
, m_loop(false)
, m_samplesProcessed(0)
, m_endBuffers()
{
}
//---------------------------------------------------------------------------//
Stream::~Stream()
{
// Stop the sound if it was playing
// Request the thread to terminate
{
std::lock_guard<std::mutex> lock(m_threadMutex);
m_isStreaming = false;
}
// Wait for the thread to terminate
if(m_thread.joinable())
m_thread.join();
}
//---------------------------------------------------------------------------//
void Stream::initialize(unsigned int channelCount, unsigned int sampleRate)
{
m_channelCount = channelCount;
m_sampleRate = sampleRate;
// Deduce the format from the number of channels
m_format = internal::Device::getFormatFromChannelCount(channelCount);
// Check if the format is valid
if (m_format == 0)
{
m_channelCount = 0;
m_sampleRate = 0;
be::utils::log::warn("Unsupported number of channels ", m_channelCount);
//internal::EMYL_LOG("Unsupported number of channels (%d)\n"); //, m_channelCount
}
}
//---------------------------------------------------------------------------//
void Stream::play()
{
// Check if the sound parameters have been set
if (m_format == 0)
{
be::utils::log::warn("Failed to play audio stream: sound parameters have not been initialized (call initialize() first)");
//internal::EMYL_LOG("Failed to play audio stream: sound parameters have not been initialized (call initialize() first)\n");
return;
}
bool isStreaming = false;
State threadStartState = Stopped;
{
std::lock_guard<std::mutex> lock(m_threadMutex);
isStreaming = m_isStreaming;
threadStartState = m_threadStartState;
}
if (isStreaming && (threadStartState == Paused))
{
// If the sound is paused, resume it
std::lock_guard<std::mutex> lock(m_threadMutex);
m_threadStartState = Playing;
alCheck(alSourcePlay(m_source));
return;
}
else if (isStreaming && (threadStartState == Playing))
{
// If the sound is playing, stop it and continue as if it was stopped
stop();
}
// Move to the beginning
onSeek(0.f);
// Start updating the stream in a separate thread to avoid blocking the application
m_samplesProcessed = 0;
m_isStreaming = true;
m_threadStartState = Playing;
m_thread = std::thread(&Stream::streamData, this);
}
//---------------------------------------------------------------------------//
void Stream::pause()
{
// Handle pause() being called before the thread has started
{
std::lock_guard<std::mutex> lock(m_threadMutex);
if (!m_isStreaming)
return;
m_threadStartState = Paused;
}
alCheck(alSourcePause(m_source));
}
//---------------------------------------------------------------------------//
void Stream::stop()
{
// Request the thread to terminate
{
std::lock_guard<std::mutex> lock(m_threadMutex);
m_isStreaming = false;
}
// Wait for the thread to terminate
if(m_thread.joinable())
m_thread.join();
// Move to the beginning
onSeek(0.f);
// Reset the playing position
m_samplesProcessed = 0;
}
//---------------------------------------------------------------------------//
unsigned int Stream::getChannelCount() const
{
return m_channelCount;
}
//---------------------------------------------------------------------------//
unsigned int Stream::getSampleRate() const
{
return m_sampleRate;
}
//---------------------------------------------------------------------------//
Stream::State Stream::getState() const
{
State status = Source::getState();
// To compensate for the lag between play() and alSourceplay()
if (status == Stopped)
{
std::lock_guard<std::mutex> lock(m_threadMutex);
if (m_isStreaming)
status = m_threadStartState;
}
return status;
}
//---------------------------------------------------------------------------//
void Stream::setPlayingOffset(ALfloat timeOffset)
{
// Get old playing status
State oldState = getState();
// Stop the stream
stop();
// Let the derived class update the current position
onSeek(timeOffset);
// Restart streaming
m_samplesProcessed = static_cast<std::uint64_t>(timeOffset * m_sampleRate * m_channelCount);
if (oldState == Stopped)
return;
m_isStreaming = true;
m_threadStartState = oldState;
m_thread = std::thread(&Stream::streamData, this);
}
//---------------------------------------------------------------------------//
ALfloat Stream::getPlayingOffset() const
{
if (m_sampleRate && m_channelCount)
{
ALfloat secs = 0.f;
alCheck(alGetSourcef(m_source, AL_SEC_OFFSET, &secs));
return secs + static_cast<float>(m_samplesProcessed) / m_sampleRate / m_channelCount;
}
else
{
return 0.f;
}
}
//---------------------------------------------------------------------------//
void Stream::setLoop(bool loop)
{
m_loop = loop;
}
//---------------------------------------------------------------------------//
bool Stream::getLoop() const
{
return m_loop;
}
//---------------------------------------------------------------------------//
void Stream::streamData()
{
bool requestStop = false;
{
std::lock_guard<std::mutex> lock(m_threadMutex);
// Check if the thread was launched Stopped
if (m_threadStartState == Stopped)
{
m_isStreaming = false;
return;
}
}
// Create the buffers
alCheck(alGenBuffers(BufferCount, m_buffers));
for (int i = 0; i < BufferCount; ++i)
m_endBuffers[i] = false;
// Fill the queue
requestStop = fillQueue();
// Play the sound
alCheck(alSourcePlay(m_source));
{
std::lock_guard<std::mutex> lock(m_threadMutex);
// Check if the thread was launched Paused
if (m_threadStartState == Paused)
alCheck(alSourcePause(m_source));
}
for (;;)
{
{
std::lock_guard<std::mutex> lock(m_threadMutex);
if (!m_isStreaming)
break;
}
// The stream has been interrupted!
if (Source::getState() == Stopped)
{
if (!requestStop)
{
// Just continue
alCheck(alSourcePlay(m_source));
}
else
{
// End streaming
std::lock_guard<std::mutex> lock(m_threadMutex);
m_isStreaming = false;
}
}
// Get the number of buffers that have been processed (i.e. ready for reuse)
ALint nbProcessed = 0;
alCheck(alGetSourcei(m_source, AL_BUFFERS_PROCESSED, &nbProcessed));
while (nbProcessed--)
{
// Pop the first unused buffer from the queue
ALuint buffer;
alCheck(alSourceUnqueueBuffers(m_source, 1, &buffer));
// Find its number
unsigned int bufferNum = 0;
for (int i = 0; i < BufferCount; ++i)
if (m_buffers[i] == buffer)
{
bufferNum = i;
break;
}
// Retrieve its size and add it to the samples count
if (m_endBuffers[bufferNum])
{
// This was the last buffer: reset the sample count
m_samplesProcessed = 0;
m_endBuffers[bufferNum] = false;
}
else
{
ALint size, bits;
alCheck(alGetBufferi(buffer, AL_SIZE, &size));
alCheck(alGetBufferi(buffer, AL_BITS, &bits));
// Bits can be 0 if the format or parameters are corrupt, avoid division by zero
if (bits == 0)
{
be::utils::log::warn("Bits in sound stream are 0: make sure that the audio format is not corrupt " \
"and initialize() has been called correctly");
//internal::EMYL_LOG("Bits in sound stream are 0: make sure that the audio format is not corrupt "
// "and initialize() has been called correctly\n");
// Abort streaming (exit main loop)
std::lock_guard<std::mutex> lock(m_threadMutex);
m_isStreaming = false;
requestStop = true;
break;
}
else
{
m_samplesProcessed += size / (bits / 8);
}
}
// Fill it and push it back into the playing queue
if (!requestStop)
{
if (fillAndPushBuffer(bufferNum))
requestStop = true;
}
}
// Leave some time for the other threads if the stream is still playing
if (Source::getState() != Stopped)
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
// Stop the playback
alCheck(alSourceStop(m_source));
// Dequeue any buffer left in the queue
clearQueue();
// Delete the buffers
alCheck(alSourcei(m_source, AL_BUFFER, 0));
alCheck(alDeleteBuffers(BufferCount, m_buffers));
}
//---------------------------------------------------------------------------//
bool Stream::fillAndPushBuffer(unsigned int bufferNum)
{
bool requestStop = false;
// Acquire audio data
Chunk data = {NULL, 0};
if (!onGetData(data))
{
// Mark the buffer as the last one (so that we know when to reset the playing position)
m_endBuffers[bufferNum] = true;
// Check if the stream must loop or stop
if (m_loop)
{
// Return to the beginning of the stream source
onSeek(0.f);
// If we previously had no data, try to fill the buffer once again
if (!data.samples || (data.sampleCount == 0))
{
return fillAndPushBuffer(bufferNum);
}
}
else
{
// Not looping: request stop
requestStop = true;
}
}
// Fill the buffer if some data was returned
if (data.samples && data.sampleCount)
{
unsigned int buffer = m_buffers[bufferNum];
// Fill the buffer
ALsizei size = static_cast<ALsizei>(data.sampleCount) * sizeof(std::int16_t);
alCheck(alBufferData(buffer, m_format, data.samples, size, m_sampleRate));
// Push it into the sound queue
alCheck(alSourceQueueBuffers(m_source, 1, &buffer));
}
return requestStop;
}
//---------------------------------------------------------------------------//
bool Stream::fillQueue()
{
// Fill and enqueue all the available buffers
bool requestStop = false;
for (int i = 0; (i < BufferCount) && !requestStop; ++i)
{
if (fillAndPushBuffer(i))
requestStop = true;
}
return requestStop;
}
//---------------------------------------------------------------------------//
void Stream::clearQueue()
{
// Get the number of buffers still in the queue
ALint nbQueued;
alCheck(alGetSourcei(m_source, AL_BUFFERS_QUEUED, &nbQueued));
// Dequeue them all
ALuint buffer;
for (ALint i = 0; i < nbQueued; ++i)
alCheck(alSourceUnqueueBuffers(m_source, 1, &buffer));
}
//---------------------------------------------------------------------------//
//-Music---------------------------------------------------------------------//
//---------------------------------------------------------------------------//
Music::Music()
: m_file()
, m_duration()
{
}
//---------------------------------------------------------------------------//
Music::~Music()
{
// We must stop before destroying the file
stop();
}
//---------------------------------------------------------------------------//
bool Music::openFromFile(const std::string& filename)
{
// First stop the music if it was already running
stop();
// Open the underlying sound file
if (!m_file.openFromFile(filename))
return false;
// Perform common initializations
initialize();
return true;
}
//---------------------------------------------------------------------------//
bool Music::openFromMemory(const void* data, std::size_t sizeInBytes)
{
// First stop the music if it was already running
stop();
// Open the underlying sound file
if (!m_file.openFromMemory(data, sizeInBytes))
return false;
// Perform common initializations
initialize();
return true;
}
//---------------------------------------------------------------------------//
bool Music::openFromStream(InputStream& stream)
{
// First stop the music if it was already running
stop();
// Open the underlying sound file
if (!m_file.openFromStream(stream))
return false;
// Perform common initializations
initialize();
return true;
}
//---------------------------------------------------------------------------//
ALfloat Music::getDuration() const
{
return m_duration;
}
//---------------------------------------------------------------------------//
bool Music::onGetData(Stream::Chunk& data)
{
std::lock_guard<std::mutex> lock(m_mutex);
// Fill the chunk parameters
data.samples = &m_samples[0];
data.sampleCount = static_cast<std::size_t>(m_file.read(&m_samples[0], m_samples.size()));
// Check if we have reached the end of the audio file
return data.sampleCount == m_samples.size();
}
//---------------------------------------------------------------------------//
void Music::onSeek(ALfloat timeOffset)
{
std::lock_guard<std::mutex> lock(m_mutex);
m_file.seek(timeOffset);
}
//---------------------------------------------------------------------------//
void Music::initialize()
{
// Compute the music duration
m_duration = m_file.getDuration();
// Resize the internal buffer so that it can contain 1 second of audio samples
m_samples.resize(m_file.getSampleRate() * m_file.getChannelCount());
// Initialize the stream
Stream::initialize(m_file.getChannelCount(), m_file.getSampleRate());
}
//---------------------------------------------------------------------------//
//-SoundFileReaderWav--------------------------------------------------------//
//---------------------------------------------------------------------------//
class SoundFileReaderWav : public SoundFileReader
{
public:
static bool check(InputStream& stream);
public:
SoundFileReaderWav();
virtual bool open(InputStream& stream, Info& info);
virtual void seek(std::uint64_t sampleOffset);
virtual std::uint64_t read(std::int16_t* samples, std::uint64_t maxCount);
private:
bool parseHeader(Info& info);
InputStream* m_stream;
unsigned int m_bytesPerSample;
std::uint64_t m_dataStart;
};
namespace
{
// The following functions read integers as little endian and
// return them in the host byte order
bool decode(InputStream& stream, std::uint8_t& value)
{
return stream.read(&value, sizeof(value)) == sizeof(value);
}
bool decode(InputStream& stream, std::int16_t& value)
{
unsigned char bytes[sizeof(value)];
if (stream.read(bytes, sizeof(bytes)) != sizeof(bytes))
return false;
value = bytes[0] | (bytes[1] << 8);
return true;
}
bool decode(InputStream& stream, std::uint16_t& value)
{
unsigned char bytes[sizeof(value)];
if (stream.read(bytes, sizeof(bytes)) != sizeof(bytes))
return false;
value = bytes[0] | (bytes[1] << 8);
return true;
}
bool decode24bit(InputStream& stream, std::uint32_t& value)
{
unsigned char bytes[3];
if (stream.read(bytes, sizeof(bytes)) != sizeof(bytes))
return false;
value = bytes[0] | (bytes[1] << 8) | (bytes[2] << 16);
return true;
}
bool decode(InputStream& stream, std::uint32_t& value)
{
unsigned char bytes[sizeof(value)];
if (stream.read(bytes, sizeof(bytes)) != sizeof(bytes))
return false;
value = bytes[0] | (bytes[1] << 8) | (bytes[2] << 16) | (bytes[3] << 24);
return true;
}
const std::uint64_t mainChunkSize = 12;
}
//---------------------------------------------------------------------------//
bool SoundFileReaderWav::check(InputStream& stream)
{
char header[mainChunkSize];
if (stream.read(header, sizeof(header)) < static_cast<std::int64_t>(sizeof(header)))
return false;
return (header[0] == 'R') && (header[1] == 'I') && (header[2] == 'F') && (header[3] == 'F')
&& (header[8] == 'W') && (header[9] == 'A') && (header[10] == 'V') && (header[11] == 'E');
}
//---------------------------------------------------------------------------//
SoundFileReaderWav::SoundFileReaderWav()
: m_stream(NULL)
, m_bytesPerSample(0)
, m_dataStart(0)
{
}
//---------------------------------------------------------------------------//
bool SoundFileReaderWav::open(InputStream& stream, Info& info)
{
m_stream = &stream;
if (!parseHeader(info))
{
//EMYL_WARN("Failed to open WAV sound file (invalid or unsupported file)\n");
return false;
}
return true;
}
//---------------------------------------------------------------------------//
void SoundFileReaderWav::seek(std::uint64_t sampleOffset)
{
//EMYL_ASSERT(m_stream);
m_stream->seek(m_dataStart + sampleOffset * m_bytesPerSample);
}
//---------------------------------------------------------------------------//
std::uint64_t SoundFileReaderWav::read(std::int16_t* samples, std::uint64_t maxCount)
{
//EMYL_ASSERT(m_stream);
std::uint64_t count = 0;
while (count < maxCount)
{
switch (m_bytesPerSample)
{
case 1:
{
std::uint8_t sample = 0;
if (decode(*m_stream, sample))
*samples++ = (static_cast<std::int16_t>(sample) - 128) << 8;
else
return count;
break;
}
case 2:
{
std::int16_t sample = 0;
if (decode(*m_stream, sample))
*samples++ = sample;
else
return count;
break;
}
case 3:
{
std::uint32_t sample = 0;
if (decode24bit(*m_stream, sample))
*samples++ = sample >> 8;
else
return count;
break;
}
case 4:
{
std::uint32_t sample = 0;
if (decode(*m_stream, sample))
*samples++ = sample >> 16;
else
return count;
break;
}
default:
{
//EMYL_ASSERT(false);
return 0;
}
}
++count;
}
return count;
}
//---------------------------------------------------------------------------//
bool SoundFileReaderWav::parseHeader(Info& info)
{
//EMYL_ASSERT(m_stream);
// If we are here, it means that the first part of the header
// (the format) has already been checked
char mainChunk[mainChunkSize];
if (m_stream->read(mainChunk, sizeof(mainChunk)) != sizeof(mainChunk))
return false;
// Parse all the sub-chunks
bool dataChunkFound = false;
while (!dataChunkFound)
{
// Parse the sub-chunk id and size
char subChunkId[4];
if (m_stream->read(subChunkId, sizeof(subChunkId)) != sizeof(subChunkId))
return false;
std::uint32_t subChunkSize = 0;
if (!decode(*m_stream, subChunkSize))
return false;
// Check which chunk it is
if ((subChunkId[0] == 'f') && (subChunkId[1] == 'm') && (subChunkId[2] == 't') && (subChunkId[3] == ' '))
{
// "fmt" chunk
// Audio format
std::uint16_t format = 0;
if (!decode(*m_stream, format))
return false;
if (format != 1) // PCM
return false;
// Channel count
std::uint16_t channelCount = 0;
if (!decode(*m_stream, channelCount))
return false;
info.channelCount = channelCount;
// Sample rate
std::uint32_t sampleRate = 0;
if (!decode(*m_stream, sampleRate))
return false;
info.sampleRate = sampleRate;
// Byte rate
std::uint32_t byteRate = 0;
if (!decode(*m_stream, byteRate))
return false;
// Block align
std::uint16_t blockAlign = 0;
if (!decode(*m_stream, blockAlign))
return false;
// Bits per sample
std::uint16_t bitsPerSample = 0;
if (!decode(*m_stream, bitsPerSample))
return false;
if (bitsPerSample != 8 && bitsPerSample != 16 && bitsPerSample != 24 && bitsPerSample != 32)
{
be::utils::log::warn("Unsupported sample size: {} bit (Supported sample sizes are 8/16/24/32 bit)", bitsPerSample);
// internal::EMYL_LOG("Unsupported sample size: %d bit (Supported sample sizes are 8/16/24/32 bit)\n", bitsPerSample);
return false;
}
m_bytesPerSample = bitsPerSample / 8;
// Skip potential extra information (should not exist for PCM)
if (subChunkSize > 16)
{
if (m_stream->seek(m_stream->tell() + subChunkSize - 16) == -1)
return false;
}
}
else if ((subChunkId[0] == 'd') && (subChunkId[1] == 'a') && (subChunkId[2] == 't') && (subChunkId[3] == 'a'))
{
// "data" chunk
// Compute the total number of samples
info.sampleCount = subChunkSize / m_bytesPerSample;
// Store the starting position of samples in the file
m_dataStart = m_stream->tell();
dataChunkFound = true;
}
else
{
// unknown chunk, skip it
if (m_stream->seek(m_stream->tell() + subChunkSize) == -1)
return false;
}
}
return true;
}
//---------------------------------------------------------------------------//
SoundFileReaderRegistrer<SoundFileReaderWav> SoundFileReaderRegistrerWav;
//---------------------------------------------------------------------------//
//-SoundFileReaderOgg--------------------------------------------------------//
//---------------------------------------------------------------------------//
#include <vorbis/vorbisfile.h>
class SoundFileReaderOgg : public SoundFileReader
{
public:
static bool check(InputStream& stream);
public:
SoundFileReaderOgg();
~SoundFileReaderOgg();
virtual bool open(InputStream& stream, Info& info);
virtual void seek(std::uint64_t sampleOffset);
virtual std::uint64_t read(std::int16_t* samples, std::uint64_t maxCount);
private:
void close();
OggVorbis_File m_vorbis;
unsigned int m_channelCount;
};
namespace
{
inline size_t read(void* ptr, size_t size, size_t nmemb, void* data)
{
InputStream* stream = static_cast<InputStream*>(data);
return static_cast<std::size_t>(stream->read(ptr, size * nmemb));
}
inline int seek(void* data, ogg_int64_t offset, int whence)
{
InputStream* stream = static_cast<InputStream*>(data);
switch (whence)
{
case SEEK_SET:
break;
case SEEK_CUR:
offset += stream->tell();
break;
case SEEK_END:
offset = stream->getSize() - offset;
}
return static_cast<int>(stream->seek(offset));
}
inline long tell(void* data)
{
InputStream* stream = static_cast<InputStream*>(data);
return static_cast<long>(stream->tell());
}
static ov_callbacks callbacks = {&read, &seek, NULL, &tell};
}
//---------------------------------------------------------------------------//
bool SoundFileReaderOgg::check(InputStream& stream)
{
OggVorbis_File file;
if (ov_test_callbacks(&stream, &file, NULL, 0, callbacks) == 0)
{
ov_clear(&file);
return true;
}
else
return false;
}
//---------------------------------------------------------------------------//
SoundFileReaderOgg::SoundFileReaderOgg()
: m_vorbis ()
, m_channelCount(0)
{
m_vorbis.datasource = NULL;
}
//---------------------------------------------------------------------------//
SoundFileReaderOgg::~SoundFileReaderOgg()
{
close();
}
//---------------------------------------------------------------------------//
bool SoundFileReaderOgg::open(InputStream& stream, Info& info)
{
// Open the Vorbis stream
int status = ov_open_callbacks(&stream, &m_vorbis, NULL, 0, callbacks);
if (status < 0)
{
be::utils::log::warn("Failed to open Vorbis file for reading");
//internal::EMYL_LOG("Failed to open Vorbis file for reading\n");
return false;
}
// Retrieve the music attributes
vorbis_info* vorbisInfo = ov_info(&m_vorbis, -1);
info.channelCount = vorbisInfo->channels;
info.sampleRate = vorbisInfo->rate;
info.sampleCount = static_cast<std::size_t>(ov_pcm_total(&m_vorbis, -1) * vorbisInfo->channels);
// We must keep the channel count for the seek function
m_channelCount = info.channelCount;
return true;
}
//---------------------------------------------------------------------------//
void SoundFileReaderOgg::seek(std::uint64_t sampleOffset)
{
//EMYL_ASSERT(m_vorbis.datasource);
ov_pcm_seek(&m_vorbis, sampleOffset / m_channelCount);
}
//---------------------------------------------------------------------------//
std::uint64_t SoundFileReaderOgg::read(std::int16_t* samples, std::uint64_t maxCount)
{
// EMYL_ASSERT(m_vorbis.datasource);
// Try to read the requested number of samples, stop only on error or end of file
std::uint64_t count = 0;
while (count < maxCount)
{
int bytesToRead = static_cast<int>(maxCount - count) * sizeof(std::int16_t);
long bytesRead = ov_read(&m_vorbis, reinterpret_cast<char*>(samples), bytesToRead, 0, 2, 1, nullptr);
if (bytesRead > 0)
{
long samplesRead = bytesRead / sizeof(std::int16_t);
count += samplesRead;
samples += samplesRead;
}
else
{
// error or end of file
break;
}
}
return count;
}
//---------------------------------------------------------------------------//
void SoundFileReaderOgg::close()
{
if (m_vorbis.datasource)
{
ov_clear(&m_vorbis);
m_vorbis.datasource = NULL;
m_channelCount = 0;
}
}
//---------------------------------------------------------------------------//
SoundFileReaderRegistrer<SoundFileReaderOgg> SoundFileReaderRegistrerOgg;
} //namespace Emyl
|
#pragma once
#include "stdafx.h"
class BackGround
{
private:
int** pMapArr;
ege::PIMAGE blockImg;
ege::PIMAGE floorImg;
void initMap();
public:
BackGround();
~BackGround();
void reDraw();
};
|
/*
* VacuumPump.cpp
*
* Parent class for all throttle controllers
Copyright (c) 2018 Chris Young
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 "VacuumPump.h"
/*
* Constructor
*/
VacuumPump::VacuumPump() : Device() {
prefsHandler = new PrefHandler(VACUUM_PUMP);
commonName = "vacuum pump";
}
void VacuumPump::setup(){
TickHandler::getInstance()->detach(this);
Logger::info("add device: VACUUM PUMP (id:%X, %X)", VACUUM_PUMP, this);
Device::setup();
VacuumPumpConfiguration *config = (VacuumPumpConfiguration *) getConfiguration();
loadConfiguration();
TickHandler::getInstance()->attach(this, CFG_TICK_INTERVAL_VAC_PUMP);
}
/*
* Controls the main flow of throttle data acquisiton, validation and mapping to
* user defined behaviour.
*
* Get's called by the sub-class which is triggered by the tick handler
*/
void VacuumPump::handleTick() {
Device::handleTick();
VacuumPumpConfiguration *config = (VacuumPumpConfiguration *) getConfiguration();
uint16_t l = getLevel();
//Logger::info("vacuum voltage: %i mV", l);
if(l<config->light_off_threshold){ //if the vacuum level is lower than the light off level, then turn off the light
setOutput(config->vacLight,0);
}
else if(l>config->light_on_threshold){
setOutput(config->vacLight,1); //if the vacuum level is higher than the light on level, then turn on the light
}
}
DeviceType VacuumPump::getType() {
return (DEVICE_VACUUM_PUMP);
}
DeviceId VacuumPump::getId(){
return VACUUM_PUMP;
}
/*
* Returns the currently calculated brake vacuum level.
*/
uint16_t VacuumPump::getLevel() {
VacuumPumpConfiguration *config = (VacuumPumpConfiguration *) getConfiguration();
level = getAnalog(config->VacuumInPin);
return map(level, 0, 4096, (int32_t) 0, (int32_t) 5000);
}
/*
* Load the config parameters which are required by all throttles
*/
void VacuumPump::loadConfiguration() {
VacuumPumpConfiguration *config = (VacuumPumpConfiguration *) getConfiguration();
if (!config) {
config = new VacuumPumpConfiguration();
setConfiguration(config);
}
Device::loadConfiguration(); // call parent
if (prefsHandler->checksumValid()) { //checksum is good, read in the values stored in EEPROM
prefsHandler->read(EEBV_VACUUM_LIGHTON_THRESHOLD, &config->light_on_threshold);
prefsHandler->read(EEBV_VACUUM_LIGHTOFF_THRESHOLD, &config->light_off_threshold);
prefsHandler->read(EEBV_VACUUM_OUT, &config->vacLight);
prefsHandler->read(EEBV_VACUUM_IN, &config->VacuumInPin);
} else { //checksum invalid. Reinitialize values.
config->light_on_threshold = 65535; //light will not turn on by default
config->light_off_threshold = 65535;
config->VacuumInPin = 255; //not used by default
config->vacLight = 255; //not used by default
}
lont = config->light_on_threshold;
lofft = config->light_off_threshold;
adc_pin = config->VacuumInPin;
vac_out = config->vacLight;
}
/*
* Store the current configuration to EEPROM
*/
void VacuumPump::saveConfiguration() {
VacuumPumpConfiguration *config = (VacuumPumpConfiguration *) getConfiguration();
Device::saveConfiguration(); // call parent
prefsHandler->write(EEBV_VACUUM_LIGHTON_THRESHOLD, config->light_on_threshold);
prefsHandler->write(EEBV_VACUUM_LIGHTOFF_THRESHOLD, config->light_off_threshold);
prefsHandler->write(EEBV_VACUUM_OUT, config->vacLight);
prefsHandler->write(EEBV_VACUUM_IN, config->VacuumInPin);
prefsHandler->saveChecksum();
Logger::console("Vacuum pump configuration saved");
}
|
/*******************************************************************************
* Cristian Alexandrescu *
* 2163013577ba2bc237f22b3f4d006856 *
* 11a4bb2c77aca6a9927b85f259d9af10db791ce5cf884bb31e7f7a889d4fb385 *
* bc9a53289baf23d369484f5343ed5d6c *
*******************************************************************************/
/* Problem 1225 - Digit Counting */
#include <iostream>
#include <vector>
#include <numeric>
#include <algorithm>
using namespace std;
class NoDigits {
public:
NoDigits();
NoDigits(const NoDigits &roDigits);
NoDigits(const NoDigits &&roDigits);
NoDigits& operator = (const NoDigits &roDigits);
NoDigits& operator = (const NoDigits &&roDigits);
NoDigits operator + (const NoDigits &roDigits);
NoDigits& operator += (const NoDigits &roDigits);
unsigned int& operator [](std::size_t nIndex);
const unsigned int& operator [](std::size_t nIndex) const;
private:
vector<unsigned int> m_oVecDigits;
static const unsigned int NODIGITS = 10;
friend ostream& operator << (ostream &roStream, const NoDigits &roDigits);
};
NoDigits::NoDigits() : m_oVecDigits(NODIGITS) {
}
NoDigits::NoDigits(const NoDigits &roDigits) : m_oVecDigits(roDigits.m_oVecDigits) {
}
NoDigits::NoDigits(const NoDigits &&roDigits) : m_oVecDigits(move(roDigits.m_oVecDigits)) {
}
NoDigits& NoDigits::operator = (const NoDigits &roDigits) {
m_oVecDigits = roDigits.m_oVecDigits;
return *this;
}
NoDigits& NoDigits::operator = (const NoDigits &&roDigits) {
m_oVecDigits = move(roDigits.m_oVecDigits);
return *this;
}
NoDigits NoDigits::operator + (const NoDigits &roDigits) {
NoDigits oTemp(*this);
for (unsigned int nLoop = 0; nLoop < NODIGITS; nLoop++)
oTemp[nLoop] += roDigits[nLoop];
return oTemp;
}
NoDigits& NoDigits::operator += (const NoDigits &roDigits) {
for (unsigned int nLoop = 0; nLoop < NODIGITS; nLoop++)
m_oVecDigits[nLoop] += roDigits[nLoop];
return *this;
}
unsigned int& NoDigits::operator [](std::size_t nIndex) {
return m_oVecDigits[nIndex];
}
const unsigned int& NoDigits::operator [](std::size_t nIndex) const {
return m_oVecDigits[nIndex];
}
ostream& operator << (ostream &roStream, const NoDigits &roDigits) {
#ifdef COMPILER_SUPPORTS_RANGE_BASED_FOR_LOOP
bool bPrintSpace = false;
for (T &oElem : roDigits.m_oVecDigits) {
if (bPrintSpace)
roStream << " ";
else
bPrintSpace = true;
roStream << oElem;
}
#else
const vector<unsigned int> roVector = roDigits.m_oVecDigits;
roStream << *(roVector.begin());
for_each(roVector.begin() + 1, roVector.end(), [&roStream](unsigned int nElem) { roStream << " " << nElem; });
#endif
return roStream;
}
int main() {
const int MAX = 10001;
vector<NoDigits> oVecSol(1);
oVecSol.reserve(MAX);
for (unsigned int nLoop = 1; nLoop < 10; nLoop++) {
NoDigits oTemp;
oTemp[nLoop] = 1;
oVecSol.push_back(move(oTemp));
}
for (unsigned int nLoop = 10; nLoop < MAX; nLoop++) {
NoDigits oTemp(oVecSol[nLoop / 10]);
oTemp[nLoop % 10]++;
oVecSol.push_back(move(oTemp));
}
partial_sum(oVecSol.begin(), oVecSol.end(), oVecSol.begin());
unsigned int nNoCases;
for (cin >> nNoCases; nNoCases--; ) {
unsigned int nN;
cin >> nN;
cout << oVecSol[nN] << endl;
}
return 0;
}
|
// 快排
// Partition+Qsort
// Qsort:W(P+Q+Q),P切分产生两个区间,由于两个区间内的元素的最终位置不会越过该区间,所以递归排序即可
// Partition:选取元素,将其移动到合适的位置,使其左侧元素均小于它,右侧元素均大于等于它
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 5010;
// [two pointers]思想,从两端同时处理
// 该思想具体精髓在哪里还需要刷题
int Partition(int A[], int left, int right)
{
// 脑海里想象整个数组
// A[left]位置空出来
int temp = A[left];
while (left < right)
{
// 找到<temp的A[right]
while (left < right && A[right] >= temp)
right--;
// 填充到空出来的A[left]
// A[right]位置空出来
A[left] = A[right];
// 找到>=temp的A[left]
while (left < right && A[left] < temp)
left++;
// 填充到空出来的A[right]
// A[left]位置空出来
A[right] = A[left];
// 当已经完成时,left和right在切分点会相遇,做两次交换等于没有交换
}
// bug:遗漏该句
A[left] = temp;
return left;
}
void Qsort(int A[], int left, int right)
{
// 递归入口,while也可以,但是递归入口的判断条件写成if更符合理解
if (left < right)
{
int pos = Partition(A, left, right);
Qsort(A, left, pos - 1);
Qsort(A, pos + 1, right);
}
}
int main()
{
int n, A[MAXN];
scanf("%d", &n);
for (int i = 0; i < n; i++)
scanf("%d", &A[i]);
Qsort(A, 0, n - 1);
for (int i = 0; i < n; i++)
printf("%d\n", A[i]);
}
|
/*
* Copyright (c) 2009-2012 André Tupinambá (andrelrt@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.
*/
//-----------------------------------------------------------------------------
#include "distributedcl_internal.h"
#include "cl_utils.h"
#include "icd/icd_object_manager.h"
#include "composite/composite_context.h"
#include "composite/composite_sampler.h"
using dcl::icd::icd_object_manager;
using dcl::composite::composite_sampler;
using dcl::composite::composite_context;
//-----------------------------------------------------------------------------
extern "C" CL_API_ENTRY cl_sampler CL_API_CALL
clCreateSampler( cl_context context, cl_bool normalized_coords,
cl_addressing_mode addressing_mode, cl_filter_mode filter_mode,
cl_int* errcode_ret ) CL_API_SUFFIX__VERSION_1_0
{
if( (addressing_mode < CL_ADDRESS_NONE) ||
(addressing_mode > CL_ADDRESS_MIRRORED_REPEAT) ||
((filter_mode != CL_FILTER_NEAREST) && (filter_mode != CL_FILTER_LINEAR)) )
{
if( errcode_ret != NULL )
{
*errcode_ret = CL_INVALID_VALUE;
}
return NULL;
}
try
{
icd_object_manager& icd = icd_object_manager::get_instance();
composite_context* context_ptr =
icd.get_object_ptr< composite_context >( context );
composite_sampler* sampler_ptr = reinterpret_cast< composite_sampler* >(
context_ptr->create_sampler( normalized_coords, addressing_mode, filter_mode ) );
if( errcode_ret != NULL )
{
*errcode_ret = CL_SUCCESS;
}
return icd.get_cl_id< composite_sampler >( sampler_ptr );
}
catch( dcl::library_exception& ex )
{
if( errcode_ret != NULL )
{
*errcode_ret = ex.get_error();
}
return NULL;
}
catch( ... )
{
if( errcode_ret != NULL )
{
*errcode_ret = CL_INVALID_VALUE;
}
return NULL;
}
// Dummy
if( errcode_ret != NULL )
{
*errcode_ret = CL_INVALID_VALUE;
}
return NULL;
}
//-----------------------------------------------------------------------------
extern "C" CL_API_ENTRY cl_int CL_API_CALL
clRetainSampler( cl_sampler sampler ) CL_API_SUFFIX__VERSION_1_0
{
return retain_object< composite_sampler >( sampler );
}
//-----------------------------------------------------------------------------
extern "C" CL_API_ENTRY cl_int CL_API_CALL
clReleaseSampler( cl_sampler sampler ) CL_API_SUFFIX__VERSION_1_0
{
return release_object< composite_sampler >( sampler );
}
//-----------------------------------------------------------------------------
extern "C" CL_API_ENTRY cl_int CL_API_CALL
clGetSamplerInfo( cl_sampler sampler, cl_sampler_info param_name,
size_t param_value_size, void* param_value,
size_t* param_value_size_ret ) CL_API_SUFFIX__VERSION_1_0
{
return CL_INVALID_VALUE;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
|
/* vim:tabstop=4:expandtab:shiftwidth=4
*
* Idesk -- XImlib2Shadow.cpp
*
* Copyright (c) 2002, Chris (nikon) (nikon@sc.rr.com)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of the <ORGANIZATION> nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* (See the included file COPYING / BSD )
*/
#include "XImlib2Shadow.h"
#include "XIconWithShadow.h"
XImlib2Shadow::XImlib2Shadow(AbstractContainer * c, AbstractIcon * iParent,
AbstractConfig * con, AbstractIconConfig * iConfig)
: XImlib2Image(c, iParent, con, iConfig)
{
}
void XImlib2Shadow::refreshIcon()
{
XIconWithShadow * sIcon = dynamic_cast<XIconWithShadow *>(iconParent);
x = sIcon->getShadowX();
y = sIcon->getShadowY();
//don't need to call applyMouseOver stuff
XImlib2Image::repaint();
}
void XImlib2Shadow::configure()
{
XImlib2Image::configure();
DesktopIconConfig * dIconConfig =
dynamic_cast<DesktopIconConfig *>(iconConfig);
transparency = dIconConfig->getSnapShadowTrans();
if (transparency == -1 )
transparency = 200; //default value
imlib_context_set_image(image);
imlib_context_set_color_modifier(colorMod);
imlib_set_color_modifier_tables(mapNone, mapNone, mapNone,
defaultTransTable);
}
void XImlib2Shadow::moveWindow(int xCord, int yCord)
{
XDesktopContainer * xContainer =
dynamic_cast<XDesktopContainer *>(container);
XIcon * xIcon = dynamic_cast<XIcon *>(iconParent);
if (xCord >= 0 &&
yCord >= 0 &&
xCord < xContainer->widthOfScreen() &&
yCord < xContainer->heightOfScreen() )
{
x = xCord;
y = yCord;
XMoveWindow( xContainer->getDisplay() , window, x, y );
}
}
void XImlib2Shadow::renderShadowToImage(Pixmap &buffer, int fX, int fY)
{
XIconWithShadow * sIcon = dynamic_cast<XIconWithShadow *>(iconParent);
//sIcon->snapShadow();
x = sIcon->getShadowX();
y = sIcon->getShadowY();
int xCord = x - fX;
int yCord = y - fY;
imlib_context_set_image(image);
imlib_context_set_anti_alias(1); //smoother scaling
imlib_context_set_blend(1); //automatically blend image and background
imlib_context_set_drawable(buffer);
imlib_render_image_on_drawable(xCord, yCord);
}
|
#include<stdio.h>
#include<string.h>
int a[1000000];
int main()
{
int n, x;
scanf("%d%d",&n,&x);
for(int i = 0; i < n; i++)
{
scanf("%d",&a[i]);
}
if(a[0] >= x)
{
a[0] > x ? printf("-1 0") : printf("0 0");
return 0;
}
if(a[n-1] <= x)
{
a[n-1] < x ? printf("%d %d",n-1,n) : printf("%d %d",n-1,n-1);
return 0;
}
int left = 0,right = n;
int mid = left+(right-left)/2;
int l,r;
while(left < right)
{
if(right - left == 1)
{
printf("%d %d",left,right);
break;
}
if(a[mid] == x)
{
printf("%d %d",mid,mid);
break;
}
else if(a[mid] > x)
{
right = mid;
}
else if(a[mid] < x)
{
left = mid;
}
mid = left+(right-left)/2;
}
return 0;
}
|
#include "window_config.h"
LRESULT CALLBACK wndProc(HWND windowHandle, UINT message, WPARAM wParam, LPARAM lParam){
static HDC hardwareContext;
static HGLRC graphicContext;
int width;
int height;
if(message == WM_CREATE){
hardwareContext = GetDC(windowHandle);
globalHardwareContext = hardwareContext;
pixelFormatInit(hardwareContext);
graphicContext = wglCreateContext(hardwareContext);
wglMakeCurrent(hardwareContext, graphicContext);
return 0;
}
else if(message == WM_CLOSE){
wglMakeCurrent(hardwareContext, NULL); //disable context
wglDeleteContext(graphicContext);
PostQuitMessage(0);
return 0;
}
else if(message == WM_SIZE){
height = HIWORD(lParam);
width = LOWORD(lParam);
if(height == 0)
height = 1;
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45, (GLfloat)width/(GLfloat)height, 1, 1000);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
return 0;
}
return DefWindowProc(windowHandle, message, wParam, lParam);
}
bool windowClassInit(WNDCLASSEX* windowClassPtr, HINSTANCE hInstance){
windowClassPtr->cbSize = sizeof(WNDCLASSEX);
windowClassPtr->style = CS_HREDRAW | CS_VREDRAW;
windowClassPtr->lpfnWndProc = wndProc;
windowClassPtr->cbClsExtra = 0;
windowClassPtr->cbWndExtra = 0;
windowClassPtr->hInstance = hInstance;
windowClassPtr->hIcon = LoadIcon(NULL, IDI_APPLICATION);
windowClassPtr->hIconSm = LoadIcon(NULL, IDI_WINLOGO);
windowClassPtr->hCursor = LoadCursor(NULL, IDC_ARROW);
windowClassPtr->hbrBackground = NULL;
windowClassPtr->lpszMenuName = NULL;
windowClassPtr->lpszClassName = "MyClass";
return RegisterClassEx(windowClassPtr);
}
void pixelFormatInit(HDC hardwareContext){
int pixelFormat;
static PIXELFORMATDESCRIPTOR pixelDesc;
pixelDesc.nSize = sizeof(PIXELFORMATDESCRIPTOR);
pixelDesc.nVersion = 1;
pixelDesc.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER,
pixelDesc.iPixelType = PFD_TYPE_RGBA,
pixelDesc.cColorBits = 32;
pixelDesc.cRedBits = 0;
pixelDesc.cRedShift = 0;
pixelDesc.cGreenShift = 0;
pixelDesc.cBlueBits = 0;
pixelDesc.cBlueShift = 0;
pixelDesc.cAlphaBits = 0;
pixelDesc.cAlphaShift = 0;
pixelDesc.cAccumBits = 0;
pixelDesc.cAccumRedBits = 0;
pixelDesc.cAccumGreenBits = 0;
pixelDesc.cAccumBlueBits = 0;
pixelDesc.cAccumAlphaBits = 0;
pixelDesc.cDepthBits = 16;
pixelDesc.cStencilBits = 0;
pixelDesc.cAuxBuffers = 0;
pixelDesc.iLayerType = PFD_MAIN_PLANE;
pixelDesc.bReserved = 0;
pixelDesc.dwLayerMask = 0;
pixelDesc.dwVisibleMask = 0;
pixelDesc.dwDamageMask = 0;
pixelFormat = ChoosePixelFormat(hardwareContext, &pixelDesc);
SetPixelFormat(hardwareContext, pixelFormat, &pixelDesc);
}
void initFullScreen(RECT& windowRect, DWORD& dwStyle, DWORD& dwExStyle, int width, int height){
windowRect.left = 0;
windowRect.right = width;
windowRect.top = 0;
windowRect.bottom = height;
if(fullScreen){
DEVMODE screenSettings;
memset(&screenSettings, 0, sizeof(screenSettings));
screenSettings.dmSize = sizeof(screenSettings);
screenSettings.dmPelsWidth = width;
screenSettings.dmPelsHeight = height;
screenSettings.dmBitsPerPel = BITS;
screenSettings.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
if(ChangeDisplaySettings(&screenSettings, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL){
MessageBox(NULL, "Display mode failed", NULL, MB_OK);
fullScreen = false;
}
}
if(fullScreen){
dwExStyle = WS_EX_APPWINDOW;
dwStyle = WS_POPUP;
ShowCursor(false);
}
else{
dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;
dwStyle = WS_OVERLAPPEDWINDOW;
}
AdjustWindowRectEx(&windowRect, dwStyle, false, dwExStyle);
}
|
// MQ5 Gas Sensor
int sensor = 7;
int gasValue = A0; //D7
void setup() {
pinMode(sensor, INPUT);
Serial.begin(9600);
}
void loop() {
gasValue = analogRead(sensor);
Serial.print("MQ5 Value : ");
Serial.print(gasValue);
Serial.println("");
delay(1000);
}
|
//
// RenderTarget.cpp
// 3d technics
//
// Created by Mike on 1/12/15.
// Copyright (c) 2015 Mike. All rights reserved.
//
#include "RenderTarget.h"
FrameBuffer::FrameBuffer(void) : fbo(0) {
GL_DEBUG(glGenFramebuffers(1, &fbo));
GL_DEBUG(glBindFramebuffer(GL_FRAMEBUFFER, fbo));
}
FrameBuffer::~FrameBuffer(void) {
if (fbo) {
GL_DEBUG(glDeleteFramebuffers(1, &fbo));
}
}
void FrameBuffer::attach(unsigned int width, unsigned int height, GLint inner_format, GLenum format, GLenum pixel_type, GLenum target) {
Texture2D::Ptr texture = std::make_shared<Texture2D>(width, height, inner_format, format, pixel_type, false, nullptr);
GL_DEBUG(glFramebufferTexture2D(GL_FRAMEBUFFER, target, GL_TEXTURE_2D, texture->texture_name(), 0));
attachments[target] = texture;
}
bool FrameBuffer::complete() {
GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
if (status != GL_FRAMEBUFFER_COMPLETE) {
printf("FB error, status: 0x%x\n", status);
return false;
}
return true;
}
Texture2D::Ptr FrameBuffer::get_texture(GLenum target) {
auto attached_texture = attachments.find(target);
return attached_texture != attachments.end() ? attached_texture->second : nullptr;
}
void FrameBuffer::bind_buffer(GLenum target) {
GL_DEBUG(glBindFramebuffer(target, fbo));
}
void FrameBuffer::setup_draw_attachments(std::vector<GLenum> attachments) {
if (attachments.size() > 0) {
GL_DEBUG(glDrawBuffers((GLsizei)attachments.size(), attachments.data()));
}
}
void FrameBuffer::setup_draw_attachment(GLenum attachment) {
GL_DEBUG(glDrawBuffer(attachment));
}
void FrameBuffer::setup_read_attachment(GLenum attachment) {
GL_DEBUG(glReadBuffer(attachment));
}
void FrameBuffer::unbind() {
GL_DEBUG(glBindFramebuffer(GL_FRAMEBUFFER, 0));
}
void FrameBuffer::display_color_attachment(GLenum attachment, float x0, float y0, float x1, float y1) {
Texture2D::Ptr texture = get_texture(attachment);
if (texture) {
GL_DEBUG(glReadBuffer(attachment));
glm::vec2 size = texture->texture_size();
GL_DEBUG(glBlitFramebuffer(0, 0, size.x, size.y, x0, y0, x1, y1, GL_COLOR_BUFFER_BIT, GL_LINEAR));
}
}
|
// Copyright 2019 Google LLC
//
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree.
//
// Auto-generated file. Do not edit!
// Specification: test/f32-vsubc.yaml
// Generator: tools/generate-vbinary-test.py
#include <gtest/gtest.h>
#include <xnnpack/common.h>
#include <xnnpack/isa-checks.h>
#include <xnnpack/vbinary.h>
#include "vbinaryc-microkernel-tester.h"
#if XNN_ARCH_ARM || XNN_ARCH_ARM64
TEST(F32_VSUBC__NEON_X4, batch_eq_4) {
TEST_REQUIRES_ARM_NEON;
VBinOpCMicrokernelTester()
.batch_size(4)
.Test(xnn_f32_vsubc_ukernel__neon_x4, VBinOpCMicrokernelTester::OpType::SubC);
}
TEST(F32_VSUBC__NEON_X4, batch_div_4) {
TEST_REQUIRES_ARM_NEON;
for (size_t batch_size = 8; batch_size < 40; batch_size += 4) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.Test(xnn_f32_vsubc_ukernel__neon_x4, VBinOpCMicrokernelTester::OpType::SubC);
}
}
TEST(F32_VSUBC__NEON_X4, batch_lt_4) {
TEST_REQUIRES_ARM_NEON;
for (size_t batch_size = 1; batch_size < 4; batch_size++) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.Test(xnn_f32_vsubc_ukernel__neon_x4, VBinOpCMicrokernelTester::OpType::SubC);
}
}
TEST(F32_VSUBC__NEON_X4, batch_gt_4) {
TEST_REQUIRES_ARM_NEON;
for (size_t batch_size = 5; batch_size < 8; batch_size++) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.Test(xnn_f32_vsubc_ukernel__neon_x4, VBinOpCMicrokernelTester::OpType::SubC);
}
}
TEST(F32_VSUBC__NEON_X4, inplace) {
TEST_REQUIRES_ARM_NEON;
for (size_t batch_size = 1; batch_size <= 20; batch_size += 3) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.inplace(true)
.Test(xnn_f32_vsubc_ukernel__neon_x4, VBinOpCMicrokernelTester::OpType::SubC);
}
}
TEST(F32_VSUBC__NEON_X4, qmin) {
TEST_REQUIRES_ARM_NEON;
for (size_t batch_size = 1; batch_size <= 20; batch_size += 3) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.qmin(128)
.Test(xnn_f32_vsubc_ukernel__neon_x4, VBinOpCMicrokernelTester::OpType::SubC);
}
}
TEST(F32_VSUBC__NEON_X4, qmax) {
TEST_REQUIRES_ARM_NEON;
for (size_t batch_size = 1; batch_size <= 20; batch_size += 3) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.qmax(128)
.Test(xnn_f32_vsubc_ukernel__neon_x4, VBinOpCMicrokernelTester::OpType::SubC);
}
}
#endif // XNN_ARCH_ARM || XNN_ARCH_ARM64
#if XNN_ARCH_ARM || XNN_ARCH_ARM64
TEST(F32_VSUBC__NEON_X8, batch_eq_8) {
TEST_REQUIRES_ARM_NEON;
VBinOpCMicrokernelTester()
.batch_size(8)
.Test(xnn_f32_vsubc_ukernel__neon_x8, VBinOpCMicrokernelTester::OpType::SubC);
}
TEST(F32_VSUBC__NEON_X8, batch_div_8) {
TEST_REQUIRES_ARM_NEON;
for (size_t batch_size = 16; batch_size < 80; batch_size += 8) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.Test(xnn_f32_vsubc_ukernel__neon_x8, VBinOpCMicrokernelTester::OpType::SubC);
}
}
TEST(F32_VSUBC__NEON_X8, batch_lt_8) {
TEST_REQUIRES_ARM_NEON;
for (size_t batch_size = 1; batch_size < 8; batch_size++) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.Test(xnn_f32_vsubc_ukernel__neon_x8, VBinOpCMicrokernelTester::OpType::SubC);
}
}
TEST(F32_VSUBC__NEON_X8, batch_gt_8) {
TEST_REQUIRES_ARM_NEON;
for (size_t batch_size = 9; batch_size < 16; batch_size++) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.Test(xnn_f32_vsubc_ukernel__neon_x8, VBinOpCMicrokernelTester::OpType::SubC);
}
}
TEST(F32_VSUBC__NEON_X8, inplace) {
TEST_REQUIRES_ARM_NEON;
for (size_t batch_size = 1; batch_size <= 40; batch_size += 7) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.inplace(true)
.Test(xnn_f32_vsubc_ukernel__neon_x8, VBinOpCMicrokernelTester::OpType::SubC);
}
}
TEST(F32_VSUBC__NEON_X8, qmin) {
TEST_REQUIRES_ARM_NEON;
for (size_t batch_size = 1; batch_size <= 40; batch_size += 7) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.qmin(128)
.Test(xnn_f32_vsubc_ukernel__neon_x8, VBinOpCMicrokernelTester::OpType::SubC);
}
}
TEST(F32_VSUBC__NEON_X8, qmax) {
TEST_REQUIRES_ARM_NEON;
for (size_t batch_size = 1; batch_size <= 40; batch_size += 7) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.qmax(128)
.Test(xnn_f32_vsubc_ukernel__neon_x8, VBinOpCMicrokernelTester::OpType::SubC);
}
}
#endif // XNN_ARCH_ARM || XNN_ARCH_ARM64
#if XNN_ARCH_X86 || XNN_ARCH_X86_64
TEST(F32_VSUBC__SSE_X4, batch_eq_4) {
TEST_REQUIRES_X86_SSE;
VBinOpCMicrokernelTester()
.batch_size(4)
.Test(xnn_f32_vsubc_ukernel__sse_x4, VBinOpCMicrokernelTester::OpType::SubC);
}
TEST(F32_VSUBC__SSE_X4, batch_div_4) {
TEST_REQUIRES_X86_SSE;
for (size_t batch_size = 8; batch_size < 40; batch_size += 4) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.Test(xnn_f32_vsubc_ukernel__sse_x4, VBinOpCMicrokernelTester::OpType::SubC);
}
}
TEST(F32_VSUBC__SSE_X4, batch_lt_4) {
TEST_REQUIRES_X86_SSE;
for (size_t batch_size = 1; batch_size < 4; batch_size++) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.Test(xnn_f32_vsubc_ukernel__sse_x4, VBinOpCMicrokernelTester::OpType::SubC);
}
}
TEST(F32_VSUBC__SSE_X4, batch_gt_4) {
TEST_REQUIRES_X86_SSE;
for (size_t batch_size = 5; batch_size < 8; batch_size++) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.Test(xnn_f32_vsubc_ukernel__sse_x4, VBinOpCMicrokernelTester::OpType::SubC);
}
}
TEST(F32_VSUBC__SSE_X4, inplace) {
TEST_REQUIRES_X86_SSE;
for (size_t batch_size = 1; batch_size <= 20; batch_size += 3) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.inplace(true)
.Test(xnn_f32_vsubc_ukernel__sse_x4, VBinOpCMicrokernelTester::OpType::SubC);
}
}
TEST(F32_VSUBC__SSE_X4, qmin) {
TEST_REQUIRES_X86_SSE;
for (size_t batch_size = 1; batch_size <= 20; batch_size += 3) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.qmin(128)
.Test(xnn_f32_vsubc_ukernel__sse_x4, VBinOpCMicrokernelTester::OpType::SubC);
}
}
TEST(F32_VSUBC__SSE_X4, qmax) {
TEST_REQUIRES_X86_SSE;
for (size_t batch_size = 1; batch_size <= 20; batch_size += 3) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.qmax(128)
.Test(xnn_f32_vsubc_ukernel__sse_x4, VBinOpCMicrokernelTester::OpType::SubC);
}
}
#endif // XNN_ARCH_X86 || XNN_ARCH_X86_64
#if XNN_ARCH_X86 || XNN_ARCH_X86_64
TEST(F32_VSUBC__SSE_X8, batch_eq_8) {
TEST_REQUIRES_X86_SSE;
VBinOpCMicrokernelTester()
.batch_size(8)
.Test(xnn_f32_vsubc_ukernel__sse_x8, VBinOpCMicrokernelTester::OpType::SubC);
}
TEST(F32_VSUBC__SSE_X8, batch_div_8) {
TEST_REQUIRES_X86_SSE;
for (size_t batch_size = 16; batch_size < 80; batch_size += 8) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.Test(xnn_f32_vsubc_ukernel__sse_x8, VBinOpCMicrokernelTester::OpType::SubC);
}
}
TEST(F32_VSUBC__SSE_X8, batch_lt_8) {
TEST_REQUIRES_X86_SSE;
for (size_t batch_size = 1; batch_size < 8; batch_size++) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.Test(xnn_f32_vsubc_ukernel__sse_x8, VBinOpCMicrokernelTester::OpType::SubC);
}
}
TEST(F32_VSUBC__SSE_X8, batch_gt_8) {
TEST_REQUIRES_X86_SSE;
for (size_t batch_size = 9; batch_size < 16; batch_size++) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.Test(xnn_f32_vsubc_ukernel__sse_x8, VBinOpCMicrokernelTester::OpType::SubC);
}
}
TEST(F32_VSUBC__SSE_X8, inplace) {
TEST_REQUIRES_X86_SSE;
for (size_t batch_size = 1; batch_size <= 40; batch_size += 7) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.inplace(true)
.Test(xnn_f32_vsubc_ukernel__sse_x8, VBinOpCMicrokernelTester::OpType::SubC);
}
}
TEST(F32_VSUBC__SSE_X8, qmin) {
TEST_REQUIRES_X86_SSE;
for (size_t batch_size = 1; batch_size <= 40; batch_size += 7) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.qmin(128)
.Test(xnn_f32_vsubc_ukernel__sse_x8, VBinOpCMicrokernelTester::OpType::SubC);
}
}
TEST(F32_VSUBC__SSE_X8, qmax) {
TEST_REQUIRES_X86_SSE;
for (size_t batch_size = 1; batch_size <= 40; batch_size += 7) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.qmax(128)
.Test(xnn_f32_vsubc_ukernel__sse_x8, VBinOpCMicrokernelTester::OpType::SubC);
}
}
#endif // XNN_ARCH_X86 || XNN_ARCH_X86_64
#if XNN_ARCH_X86 || XNN_ARCH_X86_64
TEST(F32_VSUBC__AVX_X8, batch_eq_8) {
TEST_REQUIRES_X86_AVX;
VBinOpCMicrokernelTester()
.batch_size(8)
.Test(xnn_f32_vsubc_ukernel__avx_x8, VBinOpCMicrokernelTester::OpType::SubC);
}
TEST(F32_VSUBC__AVX_X8, batch_div_8) {
TEST_REQUIRES_X86_AVX;
for (size_t batch_size = 16; batch_size < 80; batch_size += 8) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.Test(xnn_f32_vsubc_ukernel__avx_x8, VBinOpCMicrokernelTester::OpType::SubC);
}
}
TEST(F32_VSUBC__AVX_X8, batch_lt_8) {
TEST_REQUIRES_X86_AVX;
for (size_t batch_size = 1; batch_size < 8; batch_size++) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.Test(xnn_f32_vsubc_ukernel__avx_x8, VBinOpCMicrokernelTester::OpType::SubC);
}
}
TEST(F32_VSUBC__AVX_X8, batch_gt_8) {
TEST_REQUIRES_X86_AVX;
for (size_t batch_size = 9; batch_size < 16; batch_size++) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.Test(xnn_f32_vsubc_ukernel__avx_x8, VBinOpCMicrokernelTester::OpType::SubC);
}
}
TEST(F32_VSUBC__AVX_X8, inplace) {
TEST_REQUIRES_X86_AVX;
for (size_t batch_size = 1; batch_size <= 40; batch_size += 7) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.inplace(true)
.Test(xnn_f32_vsubc_ukernel__avx_x8, VBinOpCMicrokernelTester::OpType::SubC);
}
}
TEST(F32_VSUBC__AVX_X8, qmin) {
TEST_REQUIRES_X86_AVX;
for (size_t batch_size = 1; batch_size <= 40; batch_size += 7) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.qmin(128)
.Test(xnn_f32_vsubc_ukernel__avx_x8, VBinOpCMicrokernelTester::OpType::SubC);
}
}
TEST(F32_VSUBC__AVX_X8, qmax) {
TEST_REQUIRES_X86_AVX;
for (size_t batch_size = 1; batch_size <= 40; batch_size += 7) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.qmax(128)
.Test(xnn_f32_vsubc_ukernel__avx_x8, VBinOpCMicrokernelTester::OpType::SubC);
}
}
#endif // XNN_ARCH_X86 || XNN_ARCH_X86_64
#if XNN_ARCH_X86 || XNN_ARCH_X86_64
TEST(F32_VSUBC__AVX_X16, batch_eq_16) {
TEST_REQUIRES_X86_AVX;
VBinOpCMicrokernelTester()
.batch_size(16)
.Test(xnn_f32_vsubc_ukernel__avx_x16, VBinOpCMicrokernelTester::OpType::SubC);
}
TEST(F32_VSUBC__AVX_X16, batch_div_16) {
TEST_REQUIRES_X86_AVX;
for (size_t batch_size = 32; batch_size < 160; batch_size += 16) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.Test(xnn_f32_vsubc_ukernel__avx_x16, VBinOpCMicrokernelTester::OpType::SubC);
}
}
TEST(F32_VSUBC__AVX_X16, batch_lt_16) {
TEST_REQUIRES_X86_AVX;
for (size_t batch_size = 1; batch_size < 16; batch_size++) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.Test(xnn_f32_vsubc_ukernel__avx_x16, VBinOpCMicrokernelTester::OpType::SubC);
}
}
TEST(F32_VSUBC__AVX_X16, batch_gt_16) {
TEST_REQUIRES_X86_AVX;
for (size_t batch_size = 17; batch_size < 32; batch_size++) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.Test(xnn_f32_vsubc_ukernel__avx_x16, VBinOpCMicrokernelTester::OpType::SubC);
}
}
TEST(F32_VSUBC__AVX_X16, inplace) {
TEST_REQUIRES_X86_AVX;
for (size_t batch_size = 1; batch_size <= 80; batch_size += 15) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.inplace(true)
.Test(xnn_f32_vsubc_ukernel__avx_x16, VBinOpCMicrokernelTester::OpType::SubC);
}
}
TEST(F32_VSUBC__AVX_X16, qmin) {
TEST_REQUIRES_X86_AVX;
for (size_t batch_size = 1; batch_size <= 80; batch_size += 15) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.qmin(128)
.Test(xnn_f32_vsubc_ukernel__avx_x16, VBinOpCMicrokernelTester::OpType::SubC);
}
}
TEST(F32_VSUBC__AVX_X16, qmax) {
TEST_REQUIRES_X86_AVX;
for (size_t batch_size = 1; batch_size <= 80; batch_size += 15) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.qmax(128)
.Test(xnn_f32_vsubc_ukernel__avx_x16, VBinOpCMicrokernelTester::OpType::SubC);
}
}
#endif // XNN_ARCH_X86 || XNN_ARCH_X86_64
#if XNN_ARCH_X86 || XNN_ARCH_X86_64
TEST(F32_VSUBC__AVX512F_X16, batch_eq_16) {
TEST_REQUIRES_X86_AVX512F;
VBinOpCMicrokernelTester()
.batch_size(16)
.Test(xnn_f32_vsubc_ukernel__avx512f_x16, VBinOpCMicrokernelTester::OpType::SubC);
}
TEST(F32_VSUBC__AVX512F_X16, batch_div_16) {
TEST_REQUIRES_X86_AVX512F;
for (size_t batch_size = 32; batch_size < 160; batch_size += 16) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.Test(xnn_f32_vsubc_ukernel__avx512f_x16, VBinOpCMicrokernelTester::OpType::SubC);
}
}
TEST(F32_VSUBC__AVX512F_X16, batch_lt_16) {
TEST_REQUIRES_X86_AVX512F;
for (size_t batch_size = 1; batch_size < 16; batch_size++) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.Test(xnn_f32_vsubc_ukernel__avx512f_x16, VBinOpCMicrokernelTester::OpType::SubC);
}
}
TEST(F32_VSUBC__AVX512F_X16, batch_gt_16) {
TEST_REQUIRES_X86_AVX512F;
for (size_t batch_size = 17; batch_size < 32; batch_size++) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.Test(xnn_f32_vsubc_ukernel__avx512f_x16, VBinOpCMicrokernelTester::OpType::SubC);
}
}
TEST(F32_VSUBC__AVX512F_X16, inplace) {
TEST_REQUIRES_X86_AVX512F;
for (size_t batch_size = 1; batch_size <= 80; batch_size += 15) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.inplace(true)
.Test(xnn_f32_vsubc_ukernel__avx512f_x16, VBinOpCMicrokernelTester::OpType::SubC);
}
}
TEST(F32_VSUBC__AVX512F_X16, qmin) {
TEST_REQUIRES_X86_AVX512F;
for (size_t batch_size = 1; batch_size <= 80; batch_size += 15) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.qmin(128)
.Test(xnn_f32_vsubc_ukernel__avx512f_x16, VBinOpCMicrokernelTester::OpType::SubC);
}
}
TEST(F32_VSUBC__AVX512F_X16, qmax) {
TEST_REQUIRES_X86_AVX512F;
for (size_t batch_size = 1; batch_size <= 80; batch_size += 15) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.qmax(128)
.Test(xnn_f32_vsubc_ukernel__avx512f_x16, VBinOpCMicrokernelTester::OpType::SubC);
}
}
#endif // XNN_ARCH_X86 || XNN_ARCH_X86_64
#if XNN_ARCH_X86 || XNN_ARCH_X86_64
TEST(F32_VSUBC__AVX512F_X32, batch_eq_32) {
TEST_REQUIRES_X86_AVX512F;
VBinOpCMicrokernelTester()
.batch_size(32)
.Test(xnn_f32_vsubc_ukernel__avx512f_x32, VBinOpCMicrokernelTester::OpType::SubC);
}
TEST(F32_VSUBC__AVX512F_X32, batch_div_32) {
TEST_REQUIRES_X86_AVX512F;
for (size_t batch_size = 64; batch_size < 320; batch_size += 32) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.Test(xnn_f32_vsubc_ukernel__avx512f_x32, VBinOpCMicrokernelTester::OpType::SubC);
}
}
TEST(F32_VSUBC__AVX512F_X32, batch_lt_32) {
TEST_REQUIRES_X86_AVX512F;
for (size_t batch_size = 1; batch_size < 32; batch_size++) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.Test(xnn_f32_vsubc_ukernel__avx512f_x32, VBinOpCMicrokernelTester::OpType::SubC);
}
}
TEST(F32_VSUBC__AVX512F_X32, batch_gt_32) {
TEST_REQUIRES_X86_AVX512F;
for (size_t batch_size = 33; batch_size < 64; batch_size++) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.Test(xnn_f32_vsubc_ukernel__avx512f_x32, VBinOpCMicrokernelTester::OpType::SubC);
}
}
TEST(F32_VSUBC__AVX512F_X32, inplace) {
TEST_REQUIRES_X86_AVX512F;
for (size_t batch_size = 1; batch_size <= 160; batch_size += 31) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.inplace(true)
.Test(xnn_f32_vsubc_ukernel__avx512f_x32, VBinOpCMicrokernelTester::OpType::SubC);
}
}
TEST(F32_VSUBC__AVX512F_X32, qmin) {
TEST_REQUIRES_X86_AVX512F;
for (size_t batch_size = 1; batch_size <= 160; batch_size += 31) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.qmin(128)
.Test(xnn_f32_vsubc_ukernel__avx512f_x32, VBinOpCMicrokernelTester::OpType::SubC);
}
}
TEST(F32_VSUBC__AVX512F_X32, qmax) {
TEST_REQUIRES_X86_AVX512F;
for (size_t batch_size = 1; batch_size <= 160; batch_size += 31) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.qmax(128)
.Test(xnn_f32_vsubc_ukernel__avx512f_x32, VBinOpCMicrokernelTester::OpType::SubC);
}
}
#endif // XNN_ARCH_X86 || XNN_ARCH_X86_64
#if !XNN_ARCH_ASMJS && !XNN_ARCH_WASM
TEST(F32_VSUBC__PSIMD_X4, batch_eq_4) {
TEST_REQUIRES_PSIMD;
VBinOpCMicrokernelTester()
.batch_size(4)
.Test(xnn_f32_vsubc_ukernel__psimd_x4, VBinOpCMicrokernelTester::OpType::SubC, VBinOpCMicrokernelTester::Variant::Scalar);
}
TEST(F32_VSUBC__PSIMD_X4, batch_div_4) {
TEST_REQUIRES_PSIMD;
for (size_t batch_size = 8; batch_size < 40; batch_size += 4) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.Test(xnn_f32_vsubc_ukernel__psimd_x4, VBinOpCMicrokernelTester::OpType::SubC, VBinOpCMicrokernelTester::Variant::Scalar);
}
}
TEST(F32_VSUBC__PSIMD_X4, batch_lt_4) {
TEST_REQUIRES_PSIMD;
for (size_t batch_size = 1; batch_size < 4; batch_size++) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.Test(xnn_f32_vsubc_ukernel__psimd_x4, VBinOpCMicrokernelTester::OpType::SubC, VBinOpCMicrokernelTester::Variant::Scalar);
}
}
TEST(F32_VSUBC__PSIMD_X4, batch_gt_4) {
TEST_REQUIRES_PSIMD;
for (size_t batch_size = 5; batch_size < 8; batch_size++) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.Test(xnn_f32_vsubc_ukernel__psimd_x4, VBinOpCMicrokernelTester::OpType::SubC, VBinOpCMicrokernelTester::Variant::Scalar);
}
}
TEST(F32_VSUBC__PSIMD_X4, inplace) {
TEST_REQUIRES_PSIMD;
for (size_t batch_size = 1; batch_size <= 20; batch_size += 3) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.inplace(true)
.Test(xnn_f32_vsubc_ukernel__psimd_x4, VBinOpCMicrokernelTester::OpType::SubC, VBinOpCMicrokernelTester::Variant::Scalar);
}
}
TEST(F32_VSUBC__PSIMD_X4, qmin) {
TEST_REQUIRES_PSIMD;
for (size_t batch_size = 1; batch_size <= 20; batch_size += 3) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.qmin(128)
.Test(xnn_f32_vsubc_ukernel__psimd_x4, VBinOpCMicrokernelTester::OpType::SubC, VBinOpCMicrokernelTester::Variant::Scalar);
}
}
TEST(F32_VSUBC__PSIMD_X4, qmax) {
TEST_REQUIRES_PSIMD;
for (size_t batch_size = 1; batch_size <= 20; batch_size += 3) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.qmax(128)
.Test(xnn_f32_vsubc_ukernel__psimd_x4, VBinOpCMicrokernelTester::OpType::SubC, VBinOpCMicrokernelTester::Variant::Scalar);
}
}
#endif // !XNN_ARCH_ASMJS && !XNN_ARCH_WASM
#if !XNN_ARCH_ASMJS && !XNN_ARCH_WASM
TEST(F32_VSUBC__PSIMD_X8, batch_eq_8) {
TEST_REQUIRES_PSIMD;
VBinOpCMicrokernelTester()
.batch_size(8)
.Test(xnn_f32_vsubc_ukernel__psimd_x8, VBinOpCMicrokernelTester::OpType::SubC, VBinOpCMicrokernelTester::Variant::Scalar);
}
TEST(F32_VSUBC__PSIMD_X8, batch_div_8) {
TEST_REQUIRES_PSIMD;
for (size_t batch_size = 16; batch_size < 80; batch_size += 8) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.Test(xnn_f32_vsubc_ukernel__psimd_x8, VBinOpCMicrokernelTester::OpType::SubC, VBinOpCMicrokernelTester::Variant::Scalar);
}
}
TEST(F32_VSUBC__PSIMD_X8, batch_lt_8) {
TEST_REQUIRES_PSIMD;
for (size_t batch_size = 1; batch_size < 8; batch_size++) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.Test(xnn_f32_vsubc_ukernel__psimd_x8, VBinOpCMicrokernelTester::OpType::SubC, VBinOpCMicrokernelTester::Variant::Scalar);
}
}
TEST(F32_VSUBC__PSIMD_X8, batch_gt_8) {
TEST_REQUIRES_PSIMD;
for (size_t batch_size = 9; batch_size < 16; batch_size++) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.Test(xnn_f32_vsubc_ukernel__psimd_x8, VBinOpCMicrokernelTester::OpType::SubC, VBinOpCMicrokernelTester::Variant::Scalar);
}
}
TEST(F32_VSUBC__PSIMD_X8, inplace) {
TEST_REQUIRES_PSIMD;
for (size_t batch_size = 1; batch_size <= 40; batch_size += 7) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.inplace(true)
.Test(xnn_f32_vsubc_ukernel__psimd_x8, VBinOpCMicrokernelTester::OpType::SubC, VBinOpCMicrokernelTester::Variant::Scalar);
}
}
TEST(F32_VSUBC__PSIMD_X8, qmin) {
TEST_REQUIRES_PSIMD;
for (size_t batch_size = 1; batch_size <= 40; batch_size += 7) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.qmin(128)
.Test(xnn_f32_vsubc_ukernel__psimd_x8, VBinOpCMicrokernelTester::OpType::SubC, VBinOpCMicrokernelTester::Variant::Scalar);
}
}
TEST(F32_VSUBC__PSIMD_X8, qmax) {
TEST_REQUIRES_PSIMD;
for (size_t batch_size = 1; batch_size <= 40; batch_size += 7) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.qmax(128)
.Test(xnn_f32_vsubc_ukernel__psimd_x8, VBinOpCMicrokernelTester::OpType::SubC, VBinOpCMicrokernelTester::Variant::Scalar);
}
}
#endif // !XNN_ARCH_ASMJS && !XNN_ARCH_WASM
#if XNN_ARCH_WASM
TEST(F32_VSUBC__WASM_X1, batch_eq_1) {
VBinOpCMicrokernelTester()
.batch_size(1)
.Test(xnn_f32_vsubc_ukernel__wasm_x1, VBinOpCMicrokernelTester::OpType::SubC, VBinOpCMicrokernelTester::Variant::Scalar);
}
TEST(F32_VSUBC__WASM_X1, batch_gt_1) {
for (size_t batch_size = 2; batch_size < 10; batch_size++) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.Test(xnn_f32_vsubc_ukernel__wasm_x1, VBinOpCMicrokernelTester::OpType::SubC, VBinOpCMicrokernelTester::Variant::Scalar);
}
}
TEST(F32_VSUBC__WASM_X1, inplace) {
for (size_t batch_size = 1; batch_size <= 5; batch_size += 1) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.inplace(true)
.Test(xnn_f32_vsubc_ukernel__wasm_x1, VBinOpCMicrokernelTester::OpType::SubC, VBinOpCMicrokernelTester::Variant::Scalar);
}
}
TEST(F32_VSUBC__WASM_X1, qmin) {
for (size_t batch_size = 1; batch_size <= 5; batch_size += 1) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.qmin(128)
.Test(xnn_f32_vsubc_ukernel__wasm_x1, VBinOpCMicrokernelTester::OpType::SubC, VBinOpCMicrokernelTester::Variant::Scalar);
}
}
TEST(F32_VSUBC__WASM_X1, qmax) {
for (size_t batch_size = 1; batch_size <= 5; batch_size += 1) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.qmax(128)
.Test(xnn_f32_vsubc_ukernel__wasm_x1, VBinOpCMicrokernelTester::OpType::SubC, VBinOpCMicrokernelTester::Variant::Scalar);
}
}
#endif // XNN_ARCH_WASM
#if XNN_ARCH_WASM
TEST(F32_VSUBC__WASM_X2, batch_eq_2) {
VBinOpCMicrokernelTester()
.batch_size(2)
.Test(xnn_f32_vsubc_ukernel__wasm_x2, VBinOpCMicrokernelTester::OpType::SubC, VBinOpCMicrokernelTester::Variant::Scalar);
}
TEST(F32_VSUBC__WASM_X2, batch_div_2) {
for (size_t batch_size = 4; batch_size < 20; batch_size += 2) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.Test(xnn_f32_vsubc_ukernel__wasm_x2, VBinOpCMicrokernelTester::OpType::SubC, VBinOpCMicrokernelTester::Variant::Scalar);
}
}
TEST(F32_VSUBC__WASM_X2, batch_lt_2) {
for (size_t batch_size = 1; batch_size < 2; batch_size++) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.Test(xnn_f32_vsubc_ukernel__wasm_x2, VBinOpCMicrokernelTester::OpType::SubC, VBinOpCMicrokernelTester::Variant::Scalar);
}
}
TEST(F32_VSUBC__WASM_X2, batch_gt_2) {
for (size_t batch_size = 3; batch_size < 4; batch_size++) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.Test(xnn_f32_vsubc_ukernel__wasm_x2, VBinOpCMicrokernelTester::OpType::SubC, VBinOpCMicrokernelTester::Variant::Scalar);
}
}
TEST(F32_VSUBC__WASM_X2, inplace) {
for (size_t batch_size = 1; batch_size <= 10; batch_size += 1) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.inplace(true)
.Test(xnn_f32_vsubc_ukernel__wasm_x2, VBinOpCMicrokernelTester::OpType::SubC, VBinOpCMicrokernelTester::Variant::Scalar);
}
}
TEST(F32_VSUBC__WASM_X2, qmin) {
for (size_t batch_size = 1; batch_size <= 10; batch_size += 1) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.qmin(128)
.Test(xnn_f32_vsubc_ukernel__wasm_x2, VBinOpCMicrokernelTester::OpType::SubC, VBinOpCMicrokernelTester::Variant::Scalar);
}
}
TEST(F32_VSUBC__WASM_X2, qmax) {
for (size_t batch_size = 1; batch_size <= 10; batch_size += 1) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.qmax(128)
.Test(xnn_f32_vsubc_ukernel__wasm_x2, VBinOpCMicrokernelTester::OpType::SubC, VBinOpCMicrokernelTester::Variant::Scalar);
}
}
#endif // XNN_ARCH_WASM
#if XNN_ARCH_WASM
TEST(F32_VSUBC__WASM_X4, batch_eq_4) {
VBinOpCMicrokernelTester()
.batch_size(4)
.Test(xnn_f32_vsubc_ukernel__wasm_x4, VBinOpCMicrokernelTester::OpType::SubC, VBinOpCMicrokernelTester::Variant::Scalar);
}
TEST(F32_VSUBC__WASM_X4, batch_div_4) {
for (size_t batch_size = 8; batch_size < 40; batch_size += 4) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.Test(xnn_f32_vsubc_ukernel__wasm_x4, VBinOpCMicrokernelTester::OpType::SubC, VBinOpCMicrokernelTester::Variant::Scalar);
}
}
TEST(F32_VSUBC__WASM_X4, batch_lt_4) {
for (size_t batch_size = 1; batch_size < 4; batch_size++) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.Test(xnn_f32_vsubc_ukernel__wasm_x4, VBinOpCMicrokernelTester::OpType::SubC, VBinOpCMicrokernelTester::Variant::Scalar);
}
}
TEST(F32_VSUBC__WASM_X4, batch_gt_4) {
for (size_t batch_size = 5; batch_size < 8; batch_size++) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.Test(xnn_f32_vsubc_ukernel__wasm_x4, VBinOpCMicrokernelTester::OpType::SubC, VBinOpCMicrokernelTester::Variant::Scalar);
}
}
TEST(F32_VSUBC__WASM_X4, inplace) {
for (size_t batch_size = 1; batch_size <= 20; batch_size += 3) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.inplace(true)
.Test(xnn_f32_vsubc_ukernel__wasm_x4, VBinOpCMicrokernelTester::OpType::SubC, VBinOpCMicrokernelTester::Variant::Scalar);
}
}
TEST(F32_VSUBC__WASM_X4, qmin) {
for (size_t batch_size = 1; batch_size <= 20; batch_size += 3) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.qmin(128)
.Test(xnn_f32_vsubc_ukernel__wasm_x4, VBinOpCMicrokernelTester::OpType::SubC, VBinOpCMicrokernelTester::Variant::Scalar);
}
}
TEST(F32_VSUBC__WASM_X4, qmax) {
for (size_t batch_size = 1; batch_size <= 20; batch_size += 3) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.qmax(128)
.Test(xnn_f32_vsubc_ukernel__wasm_x4, VBinOpCMicrokernelTester::OpType::SubC, VBinOpCMicrokernelTester::Variant::Scalar);
}
}
#endif // XNN_ARCH_WASM
TEST(F32_VSUBC__SCALAR_X1, batch_eq_1) {
VBinOpCMicrokernelTester()
.batch_size(1)
.Test(xnn_f32_vsubc_ukernel__scalar_x1, VBinOpCMicrokernelTester::OpType::SubC, VBinOpCMicrokernelTester::Variant::Scalar);
}
TEST(F32_VSUBC__SCALAR_X1, batch_gt_1) {
for (size_t batch_size = 2; batch_size < 10; batch_size++) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.Test(xnn_f32_vsubc_ukernel__scalar_x1, VBinOpCMicrokernelTester::OpType::SubC, VBinOpCMicrokernelTester::Variant::Scalar);
}
}
TEST(F32_VSUBC__SCALAR_X1, inplace) {
for (size_t batch_size = 1; batch_size <= 5; batch_size += 1) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.inplace(true)
.Test(xnn_f32_vsubc_ukernel__scalar_x1, VBinOpCMicrokernelTester::OpType::SubC, VBinOpCMicrokernelTester::Variant::Scalar);
}
}
TEST(F32_VSUBC__SCALAR_X1, qmin) {
for (size_t batch_size = 1; batch_size <= 5; batch_size += 1) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.qmin(128)
.Test(xnn_f32_vsubc_ukernel__scalar_x1, VBinOpCMicrokernelTester::OpType::SubC, VBinOpCMicrokernelTester::Variant::Scalar);
}
}
TEST(F32_VSUBC__SCALAR_X1, qmax) {
for (size_t batch_size = 1; batch_size <= 5; batch_size += 1) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.qmax(128)
.Test(xnn_f32_vsubc_ukernel__scalar_x1, VBinOpCMicrokernelTester::OpType::SubC, VBinOpCMicrokernelTester::Variant::Scalar);
}
}
TEST(F32_VSUBC__SCALAR_X2, batch_eq_2) {
VBinOpCMicrokernelTester()
.batch_size(2)
.Test(xnn_f32_vsubc_ukernel__scalar_x2, VBinOpCMicrokernelTester::OpType::SubC, VBinOpCMicrokernelTester::Variant::Scalar);
}
TEST(F32_VSUBC__SCALAR_X2, batch_div_2) {
for (size_t batch_size = 4; batch_size < 20; batch_size += 2) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.Test(xnn_f32_vsubc_ukernel__scalar_x2, VBinOpCMicrokernelTester::OpType::SubC, VBinOpCMicrokernelTester::Variant::Scalar);
}
}
TEST(F32_VSUBC__SCALAR_X2, batch_lt_2) {
for (size_t batch_size = 1; batch_size < 2; batch_size++) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.Test(xnn_f32_vsubc_ukernel__scalar_x2, VBinOpCMicrokernelTester::OpType::SubC, VBinOpCMicrokernelTester::Variant::Scalar);
}
}
TEST(F32_VSUBC__SCALAR_X2, batch_gt_2) {
for (size_t batch_size = 3; batch_size < 4; batch_size++) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.Test(xnn_f32_vsubc_ukernel__scalar_x2, VBinOpCMicrokernelTester::OpType::SubC, VBinOpCMicrokernelTester::Variant::Scalar);
}
}
TEST(F32_VSUBC__SCALAR_X2, inplace) {
for (size_t batch_size = 1; batch_size <= 10; batch_size += 1) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.inplace(true)
.Test(xnn_f32_vsubc_ukernel__scalar_x2, VBinOpCMicrokernelTester::OpType::SubC, VBinOpCMicrokernelTester::Variant::Scalar);
}
}
TEST(F32_VSUBC__SCALAR_X2, qmin) {
for (size_t batch_size = 1; batch_size <= 10; batch_size += 1) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.qmin(128)
.Test(xnn_f32_vsubc_ukernel__scalar_x2, VBinOpCMicrokernelTester::OpType::SubC, VBinOpCMicrokernelTester::Variant::Scalar);
}
}
TEST(F32_VSUBC__SCALAR_X2, qmax) {
for (size_t batch_size = 1; batch_size <= 10; batch_size += 1) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.qmax(128)
.Test(xnn_f32_vsubc_ukernel__scalar_x2, VBinOpCMicrokernelTester::OpType::SubC, VBinOpCMicrokernelTester::Variant::Scalar);
}
}
TEST(F32_VSUBC__SCALAR_X4, batch_eq_4) {
VBinOpCMicrokernelTester()
.batch_size(4)
.Test(xnn_f32_vsubc_ukernel__scalar_x4, VBinOpCMicrokernelTester::OpType::SubC, VBinOpCMicrokernelTester::Variant::Scalar);
}
TEST(F32_VSUBC__SCALAR_X4, batch_div_4) {
for (size_t batch_size = 8; batch_size < 40; batch_size += 4) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.Test(xnn_f32_vsubc_ukernel__scalar_x4, VBinOpCMicrokernelTester::OpType::SubC, VBinOpCMicrokernelTester::Variant::Scalar);
}
}
TEST(F32_VSUBC__SCALAR_X4, batch_lt_4) {
for (size_t batch_size = 1; batch_size < 4; batch_size++) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.Test(xnn_f32_vsubc_ukernel__scalar_x4, VBinOpCMicrokernelTester::OpType::SubC, VBinOpCMicrokernelTester::Variant::Scalar);
}
}
TEST(F32_VSUBC__SCALAR_X4, batch_gt_4) {
for (size_t batch_size = 5; batch_size < 8; batch_size++) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.Test(xnn_f32_vsubc_ukernel__scalar_x4, VBinOpCMicrokernelTester::OpType::SubC, VBinOpCMicrokernelTester::Variant::Scalar);
}
}
TEST(F32_VSUBC__SCALAR_X4, inplace) {
for (size_t batch_size = 1; batch_size <= 20; batch_size += 3) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.inplace(true)
.Test(xnn_f32_vsubc_ukernel__scalar_x4, VBinOpCMicrokernelTester::OpType::SubC, VBinOpCMicrokernelTester::Variant::Scalar);
}
}
TEST(F32_VSUBC__SCALAR_X4, qmin) {
for (size_t batch_size = 1; batch_size <= 20; batch_size += 3) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.qmin(128)
.Test(xnn_f32_vsubc_ukernel__scalar_x4, VBinOpCMicrokernelTester::OpType::SubC, VBinOpCMicrokernelTester::Variant::Scalar);
}
}
TEST(F32_VSUBC__SCALAR_X4, qmax) {
for (size_t batch_size = 1; batch_size <= 20; batch_size += 3) {
VBinOpCMicrokernelTester()
.batch_size(batch_size)
.qmax(128)
.Test(xnn_f32_vsubc_ukernel__scalar_x4, VBinOpCMicrokernelTester::OpType::SubC, VBinOpCMicrokernelTester::Variant::Scalar);
}
}
|
/*Sensor de Temperatura y Humedad DHT11<br>Instrucciones:
Recuerda descargar la libreria DHT para poder utilizar este sensor
Conectaremos el Sensor DHT11 a 5v y el pin de señal a la entrada digital 7
*/
#include "DHT.h"
#define DHTPIN 7
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);
void setup() {
Serial.begin(9600);
dht.begin();
}
void loop() {
int h = dht.readHumidity();// Lee la humedad
int t= dht.readTemperature();//Lee la temperatura
//////////////////////////////////////////////////Humedad
Serial.print("Humedad Relativa: ");
Serial.print(h);//Escribe la humedad
Serial.println(" %");
delay (2500);
///////////////////////////////////////////////////Temperatura
Serial.print("Temperatura: ");
Serial.print(t);//Escribe la temperatura
Serial.println(" C'");
delay (2500);
///////////////////////////////////////////////////
Serial.println("secate!!!");
delay (3000);
Serial.println ();
}
//Electrocrea.com
|
#ifndef ExN02PrimaryGeneratorAction_h
#define ExN02PrimaryGeneratorAction_h 1
#include "G4VUserPrimaryGeneratorAction.hh"
#include "globals.hh"
#include "G4ParticleGun.hh"
|
#include<bits/stdc++.h>
using namespace std;
#define mod 1000000007
int util(vector<vector<char> > &arr,int i,int j,vector<vector<int> > &dp){
int n=arr.size();
if(i<0 || j<0 || i>=n || j>=n) return 0;
if(arr[i][j]=='*') return dp[i][j]=0;
if(i==0 && j==0) return dp[i][j]=1;
if(dp[i][j]!=-1) return dp[i][j];
return dp[i][j]=(util(arr,i-1,j,dp)+util(arr,i,j-1,dp))%mod;
}
int main(){
int n;cin>>n;
vector<vector<char> > arr(n,vector<char>(n));
for(int i=0;i<n;i++) {
for(int j=0;j<n;j++){
cin>>arr[i][j];
}
}
vector<vector<int> > dp(n,vector<int>(n,-1));
cout<<util(arr,n-1,n-1,dp)<<endl;
}
|
#include<bits/stdc++.h>
using namespace std;
#define N 100000
int not_prime[101010];
vector<long long int> primes;
void crivo(){
memset(not_prime, 0, sizeof(not_prime));
for(int i = 2; i < N ; i++){
if(not_prime[i]) continue;
primes.push_back(i);
for(int k = i+i; k < N; k+=i){
not_prime[k] = 1;
}
}
}
vector<long long int> fatora(long long int x){
if(x == 1){
vector<long long int> v;
return v;
}
vector<long long int> fatores;
int i = 0;
while(primes[i] * primes[i] <= x){
if(x % primes[i] == 0){
fatores.push_back(primes[i]);
while(x % primes[i] == 0) x/= primes[i];
vector<long long int> outros = fatora(x);
for(auto it = outros.begin(); it != outros.end(); ++it){
fatores.push_back((*it));
}
return fatores;
}
i++;
}
fatores.push_back(x);
return fatores;
}
int main(){
crivo();
int t; scanf("%d", &t);
long long dif, bigPrime = primes[primes.size()-1];
while(t--){
printf("1 %lld\n", bigPrime);
fflush(stdout);
scanf("%lld", &dif);
if(dif == 0){
printf("2 %lld\n", bigPrime);
fflush(stdout);
char s[5];
scanf("%s", s);
if(strcmp(s, "No") == 0) exit(1);
}
else{
long long int aq = bigPrime*bigPrime - dif;
vector<long long int> possiveis = fatora(aq);
// for(auto ele: possiveis){
// printf("%lld ", ele);
// }printf("\n");
long long ans = -1;
int lo = 0, hi = possiveis.size()-1, mid;
while(lo <= hi){
mid = lo + (hi-lo)/2;
printf("1 %lld\n", possiveis[mid]);
fflush(stdout);
scanf("%lld", &dif);
if(dif == 0){
ans = possiveis[mid];
break;
}
if(dif == possiveis[mid]*possiveis[mid]){
lo = mid+1;
}
else{
hi = mid-1;
}
}
printf("2 %lld\n", ans);
fflush(stdout);
char s[5];
scanf("%s", s);
if(strcmp(s, "No") == 0) exit(1);
}
}
}
|
/* M. Gries 2016-05-16 */
/*
* Design Specification
* Based on ArduinoOTA/WebUpdater for OTA Uploads of any *.bin file the target application will be added here too
* an OTA uploader functionality still remains
* so another target application can be uploaded later on or an update of the following target application:
*
* Target Application: FADE
* source code copied from original Arduino examples 01.Basics/Fade.ino
*
*/
//INCLUDES
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
#include <ESP8266HTTPUpdateServer.h>
#include <TimeLib.h> //by Paul Stoffregen, not included in the Arduino IDE !!!
#include <Timezone.h> //by Jack Christensen, not included in the Arduino IDE !!!
//DECLARATIONS
const int ledPin = BUILTIN_LED; // the onboard LED
#define DBG_OUTPUT_PORT Serial
unsigned long previousMillis = 0;
const long interval = 1000;
volatile bool wasConnected = false;
bool isConnected(long timeOutSec) {
timeOutSec = timeOutSec * 1000;
int z = 0;
while (WiFi.status() != WL_CONNECTED) {
delay(200);
DBG_OUTPUT_PORT.print(".");
if (z == timeOutSec / 200) { return false; }
z++;
}
return true;
}
ESP8266WebServer httpServer(80);
ESP8266HTTPUpdateServer httpUpdater;
void build();
void wifi();
void ntp();
void ota();
void esp();
void fade();
void sendNTPpacket(IPAddress &address);
bool getNtpTime(char* ntpServerName);
void printTime(time_t t);
//UDP
WiFiUDP Udp;
unsigned int localPort = 123;
//NTP Server
char ntpServerName1[] = "ntp1.t-online.de";
char ntpServerName2[] = "time.nist.gov";
//Timezone
//Central European Time (Frankfurt, Paris)
TimeChangeRule CEST = { "CEST", Last, Sun, Mar, 2, 120 }; //Central European Summer Time
TimeChangeRule CET = { "CET ", Last, Sun, Oct, 3, 60 }; //Central European Standard Time
Timezone CE(CEST, CET);
TimeChangeRule *tcr; //pointer to the time change rule, use to get the TZ abbrev
time_t local;
//SETUP
void setup(void){
Serial.begin(74880); /* 2016-05-15 modified from 115200 to 74880*/
Serial.println("Setup: ");
Serial.println(" configuring Wifi, OTA, ESP, Application (Fade) ... ");
build();
wifi();
ota();
esp();
// Target Application (Fade) Setup:
pinMode(ledPin, OUTPUT); // initialize onboard LED as output
if (isConnected(30)) {
wasConnected = true;
DBG_OUTPUT_PORT.println(F("Starting UDP"));
Udp.begin(localPort);
DBG_OUTPUT_PORT.print(F("Local port: "));
DBG_OUTPUT_PORT.println(Udp.localPort());
DBG_OUTPUT_PORT.println(F("waiting for sync"));
}
Serial.println("Fade:");
Serial.println(" processing fading of built-in LED");
Serial.println(" application running ...");
}
//LOOP
void loop(void){
httpServer.handleClient();
// Target Application Loop:
fade();
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval) {
previousMillis = currentMillis;
if (!isConnected(10) && wasConnected) { delay(200); ESP.restart(); }
if (!getNtpTime(ntpServerName1)) { getNtpTime(ntpServerName2); }
local = CE.toLocal(now(), &tcr);
printTime(local);
}
}
|
#ifndef HTTPENDPOINTJSONSET_H
#define HTTPENDPOINTJSONSET_H
#include "httpendpoint.h"
#include "jsonconverter.h"
#include <functional>
template <typename T> class HttpEndpointJsonSet : public HttpEndpoint {
public:
using callback_t = std::function<void(T)>;
HttpEndpointJsonSet(const String &endpoint) : HttpEndpoint(endpoint) {}
virtual ~HttpEndpointJsonSet() {}
void setCallback(callback_t callback) { this->callback = callback; }
private:
callback_t callback;
protected:
virtual bool requestPost(HttpRequest &request,
HttpResponse &response) override {
if (!callback)
return false;
T value;
bool success = JsonConverter::fromJson<T>(request.getBody(), value);
if (!success) {
response.code = HTTP_STATUS_BAD_REQUEST;
response.sendString("Bad request");
return false;
}
callback(value);
response.code = HTTP_STATUS_OK;
return true;
}
};
#endif // HTTPENDPOINTJSONSET_H
|
#pragma once
#include "../../hlt/map.hpp"
#include "point.h"
#include "connection.h"
#include "../bot.h"
class Bot;
class IMap
{
public:
virtual void analyze (Bot const &) = 0;
virtual Point * get_point (unsigned x, unsigned y) = 0;
virtual std::vector<Connection> get_connections (Point const *) = 0;
};
|
#pragma once
#include "Types.hpp"
namespace engine
{
class Path;
class Config
{
public:
static Config& GetInstance();
Config() {}
~Config() {}
virtual Bool Initialize(const Path& configFile) = 0;
virtual Int32 GetInt32Value(const std::string& key) = 0;
virtual Uint32 GetUint32Value(const std::string& key) = 0;
virtual std::string GetStringValue(const std::string& key) = 0;
};
}
|
#include<iostream>
#define OJ 98
using namespace std;
int main()
{
#ifndef OJ
freopen("201709-1.txt","r",stdin);
#endif
int n;
cin>>n;
int num; //单买可以购买多少瓶
num=n/10;
int res=0;
int temp=0;
temp=num/5;
res+=temp*5;
res+=temp*2;
num-=temp*5;
temp=num/3;
res+= temp;
res+=temp*3;
num-=temp*3;
res+=num;
cout<<res;
#ifndef OJ
fclose(stdin);
#endif
return 0;
}
|
#include <tudocomp/meta/ast/Parser.hpp>
namespace tdc {
namespace meta {
namespace ast {
std::vector<Parser::preprocessor_t> Parser::s_preprocessors;
}}} //ns
|
//
// AtomFart.cpp
// Boids
//
// Created by chenyanjie on 4/7/15.
//
//
#include "AtomFart.h"
#include "../../scene/BattleLayer.h"
using namespace cocos2d;
AtomFart::AtomFart() {
}
AtomFart::~AtomFart() {
}
AtomFart* AtomFart::create( UnitNode* owner, const cocos2d::ValueMap& data, const cocos2d::ValueMap& params ) {
AtomFart* ret = new AtomFart();
if( ret && ret->init( owner, data, params ) ) {
ret->autorelease();
return ret;
}
else {
CC_SAFE_DELETE( ret );
return nullptr;
}
}
bool AtomFart::init( UnitNode* owner, const cocos2d::ValueMap& data, const cocos2d::ValueMap& params ) {
if( !SkillNode::init( owner ) ) {
return false;
}
int level = data.at( "level" ).asInt();
_damage = data.at( "damage" ).asValueVector().at( level - 1 ).asFloat();
_range = data.at( "range" ).asFloat();
_buff_damage = data.at( "buff_damage" ).asValueVector().at( level - 1 ).asFloat();
_buff_duration = data.at( "buff_duration" ).asValueVector().at( level - 1 ).asFloat();
return true;
}
void AtomFart::updateFrame( float delta ) {
}
void AtomFart::begin() {
std::string resource = "effects/human_king_skill_1";
std::string name = Utils::stringFormat( "%s_%d", SKILL_NAME_ATOM_FART, BulletNode::getNextBulletId() );
spine::SkeletonAnimation* skeleton = ArmatureManager::getInstance()->createArmature( resource );
skeleton->setScale( 1.5f );
UnitNodeSpineComponent* component = UnitNodeSpineComponent::create( skeleton, name, true );
Point dir = _owner->getUnitDirection();
Point fart_pos = _owner->getBonePos( "bone11" );
component->setAnimation( 0, "animation", false );
_owner->getBattleLayer()->addToEffectLayer( component, fart_pos, 0 );
ValueMap buff_data;
buff_data["duration"] = Value( _buff_duration );
buff_data["damage"] = Value( _buff_damage );
buff_data["buff_type"] = Value( BUFF_TYPE_POISON );
buff_data["buff_name"] = Value( "AtomFart" );
DamageCalculate* calculator = DamageCalculate::create( SKILL_NAME_ATOM_FART, _damage );
Vector<UnitNode*> candidates = _owner->getBattleLayer()->getAliveOpponentsInRange( _owner->getTargetCamp(), fart_pos, _range );
for( auto itr = candidates.begin(); itr != candidates.end(); ++itr ) {
UnitNode* unit = *itr;
PoisonBuff* buff = PoisonBuff::create( unit, buff_data );
unit->addBuff( buff->getBuffId(), buff );
ValueMap result = calculator->calculateDamageWithoutMiss( _owner->getTargetData(), unit->getTargetData() );
unit->takeDamage( result, _owner );
Point push_dir = unit->getPosition() - _owner->getPosition();
push_dir.normalize();
float push_distance = _range * 1.2f - unit->getPosition().distance( _owner->getPosition() );
unit->pushToward( push_dir, push_distance );
}
}
void AtomFart::end() {
}
|
#include <stdio.h>
#include <iostream>
#include <conio.h>
using namespace std;
main()
{
string queue[10];
int depan=0;
int belakang=0;
int pilihan, i;
string data;
do
{
menu:
cout<<"===================================="<<endl;
cout<<"| PROGRAM ARRAY OF QUEUE\t |"<<endl;
cout<<"===================================="<<endl;
cout<<"[1] Masukan Data |"<<endl;
cout<<"[2] Keluarkan / Hapus Data |"<<endl;
cout<<"[3] Lihat Data Antrian |"<<endl;
cout<<"[4] Exit Program |"<<endl;
cout<<"===================================="<<endl;
cout<<"Pilih Menu [1/2/3/4] : ";
cin>>pilihan;
switch (pilihan)
{
case 1: //enqueue
//apakah queue belum penuh?
if (belakang < 5 )
{
cout<<"Data Masuk = ";
cin>>data;
queue[belakang] = data;
belakang++;
getch();
if (belakang == 0)
depan = 0;
}
else
cout<<"Queue penuh! \n";
getch(); system("cls"); goto menu;
break;
case 2: //dequeue
//apakah queue belum kosong?
if (depan <= belakang)
{
cout<<"Data keluar = "<<queue[depan];
depan++;
getch();
}
else
cout<<"Queue kosong!\n";
getch(); system("cls");
break;
case 3:
cout<<endl;
cout<<"Tampilan Data QUEUE Yang Sudah Di Masukan "<<endl;
for(i=depan; i<=belakang-1; i++)
cout<<"\nDATA ANTRIAN QUEUE "<<" "<<queue[i]<<endl;
cout<<"\n";
getch(); system("cls"); goto menu;
break;
case 4:
cout<<"\nHELLO, THANK U FOR VISITING... ";
}
}
while (pilihan != 4);
getch();
}
|
#ifndef __FLIP_SLIDESHOW__
#define __FLIP_SLIDESHOW__
extern "C"{
#include <libavformat/avformat.h>
#include <libavcodec/avcodec.h>
}
#include <iostream>
namespace fliphw{
class SlideshowPimpl;
class Slideshow{
public:
Slideshow();
~Slideshow();
/**
* Appends the image, provided the specified stream is an image
* or video format. If the stream is not an image or video format,
* an exception will be thrown. If it is a video format, the first
* readable frame will be used.
*
* AVFormatContexts added here will be freed when this Slideshow is
* destroyed.
*
* @param image The image to append.
* @param imageStreamID The index into image->streams.
*/
void appendImage(AVFormatContext* image, int imageStreamID);
/**
* Sets the audio track for the slideshow.
* If audio->streams[audioStreamID] is not an audio format, an exception
* will be thrown.
*
* The AVStream set here will be cleaned up when this Slideshow
* is destroyed.
*
* @param audio An audio format AVStream, or null to indicate no audio track.
*/
void setAudio(AVFormatContext* audio, int audioStreamID);
/**
* Encodes the slideshow to the specified iostream, as long as at least
* one image has been provided.
*
* If no images have been added to this Slideshow, or another internal
* error occurs, an exception will be thrown.
*/
void encode(const char* outputFilename);
size_t getNumImages();
bool haveAudio();
private:
Slideshow(const Slideshow&);
SlideshowPimpl *const pImpl;
};
} //namespace fliphw
#endif //#ifndef __FLIP_SLIDESHOW__
|
//DEMO
//demo
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.