blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 4 201 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 7 100 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 260
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 11.4k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 17
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 80
values | src_encoding stringclasses 28
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 8 9.86M | extension stringclasses 52
values | content stringlengths 8 9.86M | authors listlengths 1 1 | author stringlengths 0 119 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4821a3b0f37f13050f6a5ce706d32c10341a7ee0 | 1d4a2faec0f4e5e9bb37ca6a4e83e7f27a568465 | /10721.cpp | a4d9bb869154dc2f98e386dd84a667fa33d46dce | [] | no_license | ronee12/Uva-Solutions | ed780b0028faea938a60b4440f058978abbe0acb | 85ab6c156f7532a1bb772cc55fea667488272559 | refs/heads/master | 2021-05-15T16:23:07.636866 | 2017-10-18T20:05:05 | 2017-10-18T20:05:05 | 107,455,889 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,303 | cpp | /**Bismillahir Rahmanir Rahim**/
#include <set>
#include <map>
#include <cmath>
#include <ctime>
#include <queue>
#include <stack>
#include <vector>
#include <string>
#include <cctype>
#include <cstdio>
#include <iomanip>
#include <sstream>
#include <cstdlib>
#include <cassert>
#include <climits>
#include <complex>
#include <numeric>
#include <valarray>
#include <iostream>
#include <memory.h>
#include <algorithm>
using namespace std;
#define inf 100000000
#define pb push_back
#define mp make_pair
#define eps 1e-9
#define nl printf("\n")
#define spc printf(" ")
#define sci(n) scanf("%ld",&n)
#define sc64(n) scanf("%I64d",&n)
#define scii(a,b) scanf("%ld %ld",&a,&b)
#define sc6464(a,b) scanf("%I64d %I64d",&a,&b)
#define scs(s) scanf("%s",s)
#define scss(a,b) scanf("%s %s",a,b)
#define scd(f) scanf("%lf",&f)
#define scdd(a,b) scanf("%lf %lf",&a,&b)
#define pfi(a) printf("%ld",a)
#define pf64(a) printf("%I64d",a)
#define pfii(a,b) printf("%ld %ld",a,b)
#define pf6464(a,b) printf("%I64d %I64d",a,b)
#define pfs(a) printf("%s",a)
#define pfss(a,b) printf("%s %s",a,b)
#define pfd(a) printf("%lf",a)
#define pfdd(a,b) printf("%lf %lf",a,b)
#define rep(i,n) for(int i(0),_n(n);i<_n;++i)
#define repl(i,n) for(int i=1;i<=n;i++)
#define repr(i,n) for(int i=n;i>=0;i--)
#define repi(i,a,b) for(int i(a),_b(b);i<=_b;++i)
#define repir(i,a,b) for(int i=a;i>=b;i--)
#define ff first
#define ss second
#define all(a) a.begin(),a.end()
#define mem(x,a) memset(x,a,sizeof(x))
#define repe(it,c) for(__typeof((c).begin()) it=(c).begin();it!=(c).end();++it)
int dx[]={0,0,1,-1,1,-1,1,-1},dy[]={1,-1,0,0,1,-1,-1,1};
typedef long long ll;
typedef long l;
typedef vector<int> vi;
typedef vector<long> vl;
typedef vector<long long> vll;
typedef vector<string> vs;
typedef vector<vector<int> > vvi;
inline void cn( long &n )//fast input function
{
n=0;
long ch=getchar();int sign=1;
while( ch < '0' || ch > '9' ){if(ch=='-')sign=-1; ch=getchar();}
while(ch >= '0' && ch <= '9')
n = (n<<3)+(n<<1) + ch-'0', ch=getchar();
n=n*sign;
}
template<class T> void cmin(T &a,T b){if(b<a) a=b;}
template<class T> void cmax(T &a,T b){if(b>a) a=b;}
template<class T> int len(const T&c){return (int)c.size();}
template<class T> int len(char c[]){return (int)strlen(c);}
string itos(long n){string s;while(n){s+=(n%10+48);n/=10;}reverse(all(s));return s;}
long stoi(string s){long n=0;rep(i,len(s))n=n*10+(s[i]-48);return n;}
//Polya-Burnside theory : (n^6+3n^4+12n^3+8n^2)/24
long n,m,k;
long long dp[51][51];
long long rec(int i,long val)
{
if(i==k)
{
if(val==n) return 1;
return 0;
}
if(val>n) return 0;
if(dp[i][val]!=-1) return dp[i][val];
long long ret=0;
repl(j,m)
{
ret+=rec(i+1,j+val);
}
return dp[i][val]=ret;
}
int main()
{
ios_base::sync_with_stdio(false);
//freopen("input.txt","r",stdin);
//freopen("output.txt","w",stdout);
while(cin>>n>>k>>m){
mem(dp,-1);
cout<<rec(0,0)<<endl;
}
return 0;
}
| [
"ron.mehedi@gmail.com"
] | ron.mehedi@gmail.com |
eb1e47faf45cc7f13bba621bc40a391ecc34ab7f | 3a395a51cab08e2cce0a00a417d2078ae3304645 | /Ex_3/ex_3_1.cpp | 18467b58a153fc80d493d351ae22c5ff1316d9b5 | [] | no_license | Salmanabdul786/Pds-2-Lab | 1321228263f0dc4d96e851d35c72823e4470c305 | 668e454a02c74f420111e647c8db9a68319a920a | refs/heads/master | 2020-03-24T15:00:27.415211 | 2018-07-29T15:27:57 | 2018-07-29T15:27:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 674 | cpp | #include<iostream>
using namespace std;
class Incre
{
public:
static int count_var;
static void countfun();
void display();
};
int Incre :: count_var; //static variables should be defined like this outside the class, otherwise it'll throw an error
void Incre :: countfun()
{
count_var++;
}
void Incre :: display()
{
cout << count_var;
}
int main()
{
Incre i;
Incre::countfun(); //Static functions are independent of the object of class.so it's ideal to call by scope resolution operator.
Incre::countfun();
Incre::countfun();
i.display(); //to show static variables can be accesed by normal functions also
}
| [
"noreply@github.com"
] | noreply@github.com |
83f14be87d2ef2bc3812904a3942acc455a42a72 | 7016222fb994b3c85c0c37489445e6b103f135f7 | /Octillery/Octillery/main.cpp | 15225aa8804af3d63d4b1159445a695c06f32325 | [] | no_license | Guadalupe-Moreno/Computacion_Grafica | 6dfb5c6bbe15b1628db0271f51844aeb9cf83286 | 490db42b0d2f63f687e05838b48b41d48d43ca98 | refs/heads/master | 2020-08-03T09:53:46.595094 | 2019-10-02T21:01:33 | 2019-10-02T21:01:33 | 211,708,123 | 0 | 0 | null | null | null | null | WINDOWS-1250 | C++ | false | false | 20,821 | cpp | /*
Modelo:
Emplenado texturisado y figuras 3D, modelar un pokemon pulpo
*/
#include <GL/glut.h>
#include "figuras.h"
#include "Textura_piel.c"
#include "Textura_bola.c"
#include "Textura_blanco.c"
#include "Textura_negro.c"
#include "Textura_piso.c"
#include "Textura_P1.c"
//variables para acumular traslación con teclas w,s (en z) a,d (en x) e,c (en y)
float transZ = -5.0f;
float transX = 0.0f;
float transY = 0.0f;
//variables para acumular rotación con flechas de dirección
float angleX = 0.0f;
float angleY = 0.0f;
//identificadores de textura
GLuint idTextura_piel;
GLuint idTextura_bola;
GLuint idTextura_blanco;
GLuint idTextura_negro;
GLuint idTextura_piso;
GLuint idTextura_P1;
//función para inicializar estados de gl
void inicializar(void)
{
glClearColor(0.831, 0.949, 0.988, 1);
glClearDepth(1.0f); // Configuramos Depth Buffer
glEnable(GL_DEPTH_TEST); // Habilitamos Depth Testing
glDepthFunc(GL_LEQUAL); // Tipo de Depth Testing a realizar
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
//cargaa textura piel
glGenTextures(1, &idTextura_piel);
glBindTexture(GL_TEXTURE_2D, idTextura_piel);
gluBuild2DMipmaps(GL_TEXTURE_2D,
Textura_piel.bytes_per_pixel, Textura_piel.width,
Textura_piel.height, GL_RGB, GL_UNSIGNED_BYTE,
Textura_piel.pixel_data);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
// En caso de no querer repetir las texturas, comentar estas
// dos líneas
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glEnable(GL_TEXTURE_2D);
//cargaa textura bola
glGenTextures(1, &idTextura_bola);
glBindTexture(GL_TEXTURE_2D, idTextura_bola);
gluBuild2DMipmaps(GL_TEXTURE_2D,
Textura_bola.bytes_per_pixel, Textura_bola.width,
Textura_bola.height, GL_RGB, GL_UNSIGNED_BYTE,
Textura_bola.pixel_data);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
// En caso de no querer repetir las texturas, comentar estas
// dos líneas
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glEnable(GL_TEXTURE_2D);
//cargaa textura blanco
glGenTextures(1, &idTextura_blanco);
glBindTexture(GL_TEXTURE_2D, idTextura_blanco);
gluBuild2DMipmaps(GL_TEXTURE_2D,
Textura_blanco.bytes_per_pixel, Textura_blanco.width,
Textura_blanco.height, GL_RGB, GL_UNSIGNED_BYTE,
Textura_blanco.pixel_data);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
// En caso de no querer repetir las texturas, comentar estas
// dos líneas
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glEnable(GL_TEXTURE_2D);
//cargaa textura negro
glGenTextures(1, &idTextura_negro);
glBindTexture(GL_TEXTURE_2D, idTextura_negro);
gluBuild2DMipmaps(GL_TEXTURE_2D,
Textura_negro.bytes_per_pixel, Textura_negro.width,
Textura_negro.height, GL_RGB, GL_UNSIGNED_BYTE,
Textura_negro.pixel_data);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
// En caso de no querer repetir las texturas, comentar estas
// dos líneas
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glEnable(GL_TEXTURE_2D);
//cargaa textura piso
glGenTextures(1, &idTextura_piso);
glBindTexture(GL_TEXTURE_2D, idTextura_piso);
gluBuild2DMipmaps(GL_TEXTURE_2D,
Textura_piso.bytes_per_pixel, Textura_piso.width,
Textura_piso.height, GL_RGB, GL_UNSIGNED_BYTE,
Textura_piso.pixel_data);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
// En caso de no querer repetir las texturas, comentar estas
// dos líneas
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glEnable(GL_TEXTURE_2D);
//cargaa textura pokebola
glGenTextures(1, &idTextura_P1);
glBindTexture(GL_TEXTURE_2D, idTextura_P1);
gluBuild2DMipmaps(GL_TEXTURE_2D,
Textura_P1.bytes_per_pixel, Textura_P1.width,
Textura_P1.height, GL_RGB, GL_UNSIGNED_BYTE,
Textura_P1.pixel_data);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
// En caso de no querer repetir las texturas, comentar estas
// dos líneas
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glEnable(GL_TEXTURE_2D);
}
void dibujar(void)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Limpiamos pantalla y Depth Buffer
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
//se debe recorrer hacia z negativo xq la cara de enfrente está mi espalda
//si no lo recorro lo suficiente las caras de los lados se verán largas
glTranslatef(transX, transY, transZ);
glRotatef(angleY, 0.0, 1.0, 0.0); //gira sobre y sentido horario
glRotatef(angleX, 1.0, 0.0, 0.0); //gira sobre x sentido antihorario
//dibujar cuerpo
//dibujar base
glPushMatrix();
glTranslatef(0.0f, -2.5f, 0.0f);
cilindro(0.75, 1.5, 50, idTextura_piel);
glPushMatrix();
glLoadIdentity();
glTranslatef(transX, transY, transZ);
glRotatef(angleY, 0.0, 1.0, 0.0);
glRotatef(angleX, 1.0, 0.0, 0.0);
glTranslatef(0.0f, -2.5f, 0.0f);
glScalef(2, 0.5, 2);
prisma2(idTextura_piso, idTextura_piso);
glPopMatrix();
glPushMatrix();
glLoadIdentity();
glTranslatef(transX, transY, transZ);
glRotatef(angleY, 0.0, 1.0, 0.0);
glRotatef(angleX, 1.0, 0.0, 0.0);
glTranslatef(0.0f, -3.0f, 0.0f);
glScalef(3, 0.5, 3);
prisma2(idTextura_piso, idTextura_piso);
glPopMatrix();
glPushMatrix();
glLoadIdentity();
glTranslatef(transX, transY, transZ);
glRotatef(angleY, 0.0, 1.0, 0.0);
glRotatef(angleX, 1.0, 0.0, 0.0);
glTranslatef(0.0f, -3.5f, 0.0f);
glScalef(4, 0.5, 4);
prisma2(idTextura_piso, idTextura_piso);
glPopMatrix();
glPopMatrix();
//dibujar bola inferior
glPushMatrix();
glTranslatef(0.0f, 0.5f, 0.0f);
esfera(2.0, 50, 50, idTextura_piel);
glPopMatrix();
//dibujar bola superior
glPushMatrix();
glTranslatef(0.0f, 1.5f, 0.0f);
esfera(2.0, 50, 50, idTextura_piel);
glPopMatrix();
//dibujar manchas amarillas
glPushMatrix();
glTranslatef(0.0f, 3.25f, 0.0f);
esfera(0.5, 50, 50, idTextura_bola);
glPopMatrix();
glPushMatrix();
glTranslatef(0.0f, 3.0f, 1.0f);
esfera(0.5, 50, 50, idTextura_bola);
glPopMatrix();
glPushMatrix();
glTranslatef(0.0f, 3.0f, -1.0f);
esfera(0.5, 50, 50, idTextura_bola);
glPopMatrix();
glPushMatrix();
glTranslatef(0.0f, 2.25f, -1.5f);
esfera(0.5, 50, 50, idTextura_bola);
glPopMatrix();
glPushMatrix();
glTranslatef(0.0f, 1.5f, -1.7f);
esfera(0.5, 50, 50, idTextura_bola);
glPopMatrix();
//dibujar cara
//nariz
glPushMatrix();
glTranslatef(0.0f, 2.0f, 1.5f);
glRotatef(90.0f, 1.0, 0.0, 0.0);
cono(1.5, 0.75, 10, idTextura_piel);
glPopMatrix();
glPushMatrix();
glTranslatef(0.0f, 2.0f, 2.0f);
glRotatef(90.0f, 1.0, 0.0, 0.0);
cilindro(0.5, 1.0, 50, idTextura_piel);
glPopMatrix();
glPushMatrix();
glTranslatef(0.0f, 2.0f, 2.75f);
esfera(0.3, 50, 50, idTextura_negro);
glPopMatrix();
//ojo izquierdo
glPushMatrix();
glTranslatef(-0.5f, 2.25f, 1.0f);
esfera(0.75, 50, 50, idTextura_blanco);
glPopMatrix();
glPushMatrix();
glTranslatef(-0.5f, 2.5f, 1.5f);
esfera(0.25, 50, 50, idTextura_negro);
glPopMatrix();
//ojo derecho
glPushMatrix();
glTranslatef(0.5f, 2.25f, 1.0f);
esfera(0.75, 50, 50, idTextura_blanco);
glPopMatrix();
glPushMatrix();
glTranslatef(0.5f, 2.5f, 1.5f);
esfera(0.25, 50, 50, idTextura_negro);
glPopMatrix();
//dibujar tentaculos
//tentaculo izquierdo
glPushMatrix();
glTranslatef(-1.5f, 0.0f, 0.0f);
glRotatef(120.0f, 0.0, 0.0, 1.0);
cilindro(0.75, 1.0, 50, idTextura_piel);
glPushMatrix();
glLoadIdentity();
glTranslatef(transX, transY, transZ);
glRotatef(angleY, 0.0, 1.0, 0.0);
glRotatef(angleX, 1.0, 0.0, 0.0);
glTranslatef(-1.75f, 0.5f, 0.0f);
esfera(0.5, 50, 50, idTextura_bola);
glPopMatrix();
glPushMatrix();
glLoadIdentity();
glTranslatef(transX, transY, transZ);
glRotatef(angleY, 0.0, 1.0, 0.0);
glRotatef(angleX, 1.0, 0.0, 0.0);
glTranslatef(-2.5f, -0.5f, 0.0f);
esfera(0.75, 50, 50, idTextura_bola);
glRotatef(90.0f, 0.0, 0.0, 1.0);
cilindro(0.70, 2.0, 50, idTextura_piel);
glPopMatrix();
glPushMatrix();
glLoadIdentity();
glTranslatef(transX, transY, transZ);
glRotatef(angleY, 0.0, 1.0, 0.0);
glRotatef(angleX, 1.0, 0.0, 0.0);
glTranslatef(-4.5f, -0.5f, 0.0f);
esfera(0.75, 50, 50, idTextura_bola);
glPushMatrix();
glTranslatef(0.0f, 0.1f, 0.0f);
glRotatef(45.0f, 0.0, 0.0, 1.0);
cilindro(0.60, 1.0, 50, idTextura_piel);
glPopMatrix();
glPopMatrix();
glPushMatrix();
glLoadIdentity();
glTranslatef(transX, transY, transZ);
glRotatef(angleY, 0.0, 1.0, 0.0);
glRotatef(angleX, 1.0, 0.0, 0.0);
glTranslatef(-5.3f, 0.85f, 0.0f);
esfera(1.0, 50, 50, idTextura_P1);
glPopMatrix();
glPopMatrix();
//tentaculo atras izquierdo
glPushMatrix();
glTranslatef(-1.0f, -0.5f, -2.0f);
glRotatef(30.0f, 0.0, 1.0, 0.0);
glRotatef(55.0f, 1.0, 0.0, 0.0);
cilindro(0.75, 1.0, 50, idTextura_piel);
glPushMatrix();
glLoadIdentity();
glTranslatef(transX, transY, transZ);
glRotatef(angleY, 0.0, 1.0, 0.0);
glRotatef(angleX, 1.0, 0.0, 0.0);
glTranslatef(-1.0f, 0.5f, -1.5f);
esfera(0.5, 50, 50, idTextura_bola);
glPopMatrix();
glPushMatrix();
glLoadIdentity();
glTranslatef(transX, transY, transZ);
glRotatef(angleY, 0.0, 1.0, 0.0);
glRotatef(angleX, 1.0, 0.0, 0.0);
glTranslatef(-1.0f, -0.60f, -2.2f);
esfera(0.80, 50, 50, idTextura_bola);
glPushMatrix();
glTranslatef(-1.0f, -0.1f, -2.0f);
glRotatef(30.0f, 0.0, 1.0, 0.0);
glRotatef(90.0f, 1.0, 0.0, 0.0);
cilindro(0.70, 2.0, 50, idTextura_piel);
glPopMatrix();
glPushMatrix();
glLoadIdentity();
glTranslatef(transX, transY, transZ);
glRotatef(angleY, 0.0, 1.0, 0.0);
glRotatef(angleX, 1.0, 0.0, 0.0);
glTranslatef(-1.9f, -0.70f, -4.0f);
esfera(0.75, 50, 50, idTextura_bola);
glPushMatrix();
glTranslatef(0.0f, 0.1f, 0.0f);
glRotatef(30.0f, 0.0, 1.0, 0.0);
glRotatef(315.0f, 1.0, 0.0, 0.0);
cilindro(0.60, 1.0, 50, idTextura_piel);
glPopMatrix();
glPopMatrix();
glPushMatrix();
glLoadIdentity();
glTranslatef(transX, transY, transZ);
glRotatef(angleY, 0.0, 1.0, 0.0);
glRotatef(angleX, 1.0, 0.0, 0.0);
glTranslatef(-2.5f, 0.70f, -5.0f);
esfera(1.0, 50, 50, idTextura_P1);
glPopMatrix();
glPopMatrix();
glPopMatrix();
//tentaculo atras derecho
glPushMatrix();
glTranslatef(1.0f, -0.5f, -2.0f);
glRotatef(330.0f, 0.0, 1.0, 0.0);
glRotatef(55.0f, 1.0, 0.0, 0.0);
cilindro(0.75, 1.0, 50, idTextura_piel);
glPushMatrix();
glLoadIdentity();
glTranslatef(transX, transY, transZ);
glRotatef(angleY, 0.0, 1.0, 0.0);
glRotatef(angleX, 1.0, 0.0, 0.0);
glTranslatef(1.0f, 0.5f, -1.5f);
esfera(0.5, 50, 50, idTextura_bola);
glPopMatrix();
glPushMatrix();
glLoadIdentity();
glTranslatef(transX, transY, transZ);
glRotatef(angleY, 0.0, 1.0, 0.0);
glRotatef(angleX, 1.0, 0.0, 0.0);
glTranslatef(1.0f, -0.60f, -2.2f);
esfera(0.80, 50, 50, idTextura_bola);
glPushMatrix();
glTranslatef(1.0f, -0.1f, -2.0f);
glRotatef(330.0f, 0.0, 1.0, 0.0);
glRotatef(90.0f, 1.0, 0.0, 0.0);
cilindro(0.70, 2.0, 50, idTextura_piel);
glPopMatrix();
glPushMatrix();
glLoadIdentity();
glTranslatef(transX, transY, transZ);
glRotatef(angleY, 0.0, 1.0, 0.0);
glRotatef(angleX, 1.0, 0.0, 0.0);
glTranslatef(1.9f, -0.70f, -4.0f);
esfera(0.75, 50, 50, idTextura_bola);
glPushMatrix();
glTranslatef(0.0f, 0.1f, 0.0f);
glRotatef(330.0f, 0.0, 1.0, 0.0);
glRotatef(315.0f, 1.0, 0.0, 0.0);
cilindro(0.60, 1.0, 50, idTextura_piel);
glPopMatrix();
glPopMatrix();
glPushMatrix();
glLoadIdentity();
glTranslatef(transX, transY, transZ);
glRotatef(angleY, 0.0, 1.0, 0.0);
glRotatef(angleX, 1.0, 0.0, 0.0);
glTranslatef(2.5f, 0.70f, -5.0f);
esfera(1.0, 50, 50, idTextura_P1);
glPopMatrix();
glPopMatrix();
glPopMatrix();
//tentaculo derecho
glPushMatrix();
glTranslatef(1.5f, 0.0f, 0.0f);
glRotatef(240.0f, 0.0, 0.0, 1.0);
cilindro(0.75, 1.0, 50, idTextura_piel);
glPushMatrix();
glLoadIdentity();
glTranslatef(transX, transY, transZ);
glRotatef(angleY, 0.0, 1.0, 0.0);
glRotatef(angleX, 1.0, 0.0, 0.0);
glTranslatef(1.75f, 0.5f, 0.0f);
esfera(0.5, 50, 50, idTextura_bola);
glPopMatrix();
glPushMatrix();
glLoadIdentity();
glTranslatef(transX, transY, transZ);
glRotatef(angleY, 0.0, 1.0, 0.0);
glRotatef(angleX, 1.0, 0.0, 0.0);
glTranslatef(4.5f, -0.5f, 0.0f);
glRotatef(90.0f, 0.0, 0.0, 1.0);
cilindro(0.70, 2.0, 50, idTextura_piel);
glPushMatrix();
glLoadIdentity();
glTranslatef(transX, transY, transZ);
glRotatef(angleY, 0.0, 1.0, 0.0);
glRotatef(angleX, 1.0, 0.0, 0.0);
glTranslatef(2.5f, -0.5f, 0.0f);
esfera(0.75, 50, 50, idTextura_bola);
glPopMatrix();
glPushMatrix();
glLoadIdentity();
glTranslatef(transX, transY, transZ);
glRotatef(angleY, 0.0, 1.0, 0.0);
glRotatef(angleX, 1.0, 0.0, 0.0);
glTranslatef(4.5f, -0.5f, 0.0f);
esfera(0.75, 50, 50, idTextura_bola);
glPushMatrix();
glTranslatef(0.0f, -0.1f, 0.0f);
glRotatef(315.0f, 0.0, 0.0, 1.0);
cilindro(0.60, 1.0, 50, idTextura_piel);
glPopMatrix();
glPopMatrix();
glPushMatrix();
glLoadIdentity();
glTranslatef(transX, transY, transZ);
glRotatef(angleY, 0.0, 1.0, 0.0);
glRotatef(angleX, 1.0, 0.0, 0.0);
glTranslatef(5.0f, 0.5f, 0.0f);
esfera(1.0, 50, 50, idTextura_P1);
glPopMatrix();
glPopMatrix();
glPopMatrix();
//tentaculo enfrente izquierdo
glPushMatrix();
glTranslatef(-0.7f, 0.0f, 1.5f);
glRotatef(330.0f, 0.0, 1.0, 0.0);
glRotatef(120.0f, 1.0, 0.0, 0.0);
cilindro(0.75, 1.0, 50, idTextura_piel);
glPushMatrix();
glLoadIdentity();
glTranslatef(transX, transY, transZ);
glRotatef(angleY, 0.0, 1.0, 0.0);
glRotatef(angleX, 1.0, 0.0, 0.0);
glTranslatef(-0.95f, 0.5f, 1.5f);
esfera(0.5, 50, 50, idTextura_bola);
glPopMatrix();
glPushMatrix();
glLoadIdentity();
glTranslatef(transX, transY, transZ);
glRotatef(angleY, 0.0, 1.0, 0.0);
glRotatef(angleX, 1.0, 0.0, 0.0);
glTranslatef(1.2f, -0.5f, 2.2f);
esfera(0.80, 50, 50, idTextura_bola);
glPushMatrix();
glTranslatef(0.0f, -0.1f, 0.0f);
glRotatef(30.0f, 0.0, 1.0, 0.0);
glRotatef(90.0f, 1.0, 0.0, 0.0);
cilindro(0.70, 2.0, 50, idTextura_piel);
glPopMatrix();
glPushMatrix();
glLoadIdentity();
glTranslatef(transX, transY, transZ);
glRotatef(angleY, 0.0, 1.0, 0.0);
glRotatef(angleX, 1.0, 0.0, 0.0);
glTranslatef(-2.35f, -0.5f, 4.25f);
esfera(0.75, 50, 50, idTextura_bola);
glPushMatrix();
glTranslatef(0.0f, -0.1f, 0.0f);
glRotatef(330.0f, 0.0, 1.0, 0.0);
glRotatef(45.0f, 1.0, 0.0, 0.0);
cilindro(0.60, 1.0, 50, idTextura_piel);
glPopMatrix();
glPopMatrix();
glPushMatrix();
glLoadIdentity();
glTranslatef(transX, transY, transZ);
glRotatef(angleY, 0.0, 1.0, 0.0);
glRotatef(angleX, 1.0, 0.0, 0.0);
glTranslatef(-2.50f, 0.5f, 4.7f);
esfera(1.0, 50, 50, idTextura_P1);
glPopMatrix();
glPopMatrix();
glPopMatrix();
//tentaculo enfrente derecho
glPushMatrix();
glTranslatef(0.7f, 0.0f, 1.5f);
glRotatef(30.0f, 0.0, 1.0, 0.0);
glRotatef(120.0f, 1.0, 0.0, 0.0);
cilindro(0.75, 1.0, 50, idTextura_piel);
glPushMatrix();
glLoadIdentity();
glTranslatef(transX, transY, transZ);
glRotatef(angleY, 0.0, 1.0, 0.0);
glRotatef(angleX, 1.0, 0.0, 0.0);
glTranslatef(0.95f, 0.5f, 1.5f);
esfera(0.5, 50, 50, idTextura_bola);
glPopMatrix();
glPushMatrix();
glLoadIdentity();
glTranslatef(transX, transY, transZ);
glRotatef(angleY, 0.0, 1.0, 0.0);
glRotatef(angleX, 1.0, 0.0, 0.0);
glTranslatef(-1.2f, -0.5f, 2.2f);
esfera(0.80, 50, 50, idTextura_bola);
glPushMatrix();
glTranslatef(0.0f, -0.1f, 0.0f);
glRotatef(330.0f, 0.0, 1.0, 0.0);
glRotatef(90.0f, 1.0, 0.0, 0.0);
cilindro(0.70, 2.0, 50, idTextura_piel);
glPopMatrix();
glPushMatrix();
glLoadIdentity();
glTranslatef(transX, transY, transZ);
glRotatef(angleY, 0.0, 1.0, 0.0);
glRotatef(angleX, 1.0, 0.0, 0.0);
glTranslatef(2.35f, -0.5f, 4.25f);
esfera(0.75, 50, 50, idTextura_bola);
glPushMatrix();
glTranslatef(0.0f, -0.1f, 0.0f);
glRotatef(30.0f, 0.0, 1.0, 0.0);
glRotatef(45.0f, 1.0, 0.0, 0.0);
cilindro(0.60, 1.0, 50, idTextura_piel);
glPopMatrix();
glPopMatrix();
glPushMatrix();
glLoadIdentity();
glTranslatef(transX, transY, transZ);
glRotatef(angleY, 0.0, 1.0, 0.0);
glRotatef(angleX, 1.0, 0.0, 0.0);
glTranslatef(2.50f, 0.5f, 4.7f);
esfera(1.0, 50, 50, idTextura_P1);
glPopMatrix();
glPopMatrix();
glPopMatrix();
/*
glTranslatef(-1.875f, -0.80f, 0.0f);
glRotatef(120.0f, 0.0, 0.0, 1.0);
cono(3, 0.75, 10, idTextura_piel);
*/
glFlush();
}
void remodelar(int width, int height) // Creamos funcion Reshape
{
if (height == 0) // Prevenir division entre cero
{
height = 1;
}
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION); // Seleccionamos Projection Matrix
glLoadIdentity();
// Tipo de Vista
//glFrustum(-5, 5, -5, 5, 0.1, 50.0);
glFrustum(-0.1, 0.1, -0.1, 0.1, 0.1, 50.0);
glutPostRedisplay();
}
void teclado(unsigned char key, int x, int y)
{
switch (key) {
case 'w': case 'W': //acerca al objeto con traslación en z pos
transZ += 0.2f;
break;
case 's': case 'S': //aleja al objeto con traslación en z neg
transZ -= 0.2f;
break;
case 'a': case 'A': //traslada objeto hacia la derecha en x pos
transX += 0.2f;
break;
case 'd': case 'D': //traslada objeto hacia la izquierda en x neg
transX -= 0.2f;
break;
case 'e': case 'E': //traslada objeto hacia arriba en y pos
transY += 0.2f;
break;
case 'c': case 'C': //traslada objeto hacia abajo en y neg
transY -= 0.2f;
break;
case 27: //Si presiona tecla ESC (ASCII 27) sale
exit(0);
break;
default: //Si es cualquier otra tecla no hace nada
break;
}
glutPostRedisplay();
}
void teclasFlechas(int tecla, int x, int y) // Funcion para manejo de teclas especiales (arrow keys)
{
switch (tecla) {
case GLUT_KEY_UP: //gira sobre x sentido antihorario, valor positivo
angleX += 2.0f;
break;
case GLUT_KEY_DOWN: //gira sobre x sentido horario, valor negativo
angleX -= 2.0f;
break;
case GLUT_KEY_LEFT: //gira sobre y sentido antihorario, valor positivo
angleY += 2.0f;
break;
case GLUT_KEY_RIGHT: //gira sobre y sentido horario, valor negativo
angleY -= 2.0f;
break;
default:
break;
}
glutPostRedisplay();
}
int main(int argc, char* argv[])
{
//inicializa GLUT con el sistema de ventanas pasando los argumentos del main
glutInit(&argc, argv);
//Buffer simple para dibujar
//Colores RGB y alpha
//Buffer de profundidad
glutInitDisplayMode(GLUT_RGBA | GLUT_SINGLE | GLUT_DEPTH);
//Define ventana de 500 pixeles de ancho por 500 de alto
glutInitWindowSize(600, 600);
//Posiciona la ventana de izquierda a derecha 50 pixeles y de arriba a abajo 25
glutInitWindowPosition(400, 100);
//Crea y abre la ventana y recibe el nombre que va en su barra de título
glutCreateWindow(argv[1]);
//Llamada a función propia para inicializar estados de opengl
inicializar();
//Llamada a la función a ser dibujada y redibujada
glutDisplayFunc(dibujar);
glutReshapeFunc(remodelar);
//Lamada a función que maneja eventos del teclado
glutKeyboardFunc(teclado);
glutSpecialFunc(teclasFlechas);
//Llamada a función que cede el control a GLUT y procesa eventos de ventana, ratón
glutMainLoop();
//termina la ejecución devolviendo cero
return 0;
} | [
"ing.guadalupe.moreno@gmail.com"
] | ing.guadalupe.moreno@gmail.com |
5f49d3e774936f1dea6af733995cb5c7433c4983 | d8c3c255e867c02887b4b214064de6c1d91d03ca | /src/MatrixWriter.cpp | 8a98a410134dd57a2a63ed17277fd3b5db910248 | [] | no_license | kevinatrix15/system-solver-test | ba2cac46516144bc71f178160c6835c4e4ff5cba | f0e39806620c049c3a52ad16548405c77197f6ae | refs/heads/master | 2021-01-12T02:39:52.479149 | 2017-01-10T15:18:20 | 2017-01-10T15:18:20 | 78,084,954 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,547 | cpp | /**
* @file MatrixWriter.cpp
* @brief Implementation of the MatrixWriter class.
* @author Kevin Briggs <kevin.briggs@3dsim.com>
* Copyright 2017, 3DSIM LLC
* @version 1
* @date 2017-01-03
*/
#include <cassert>
#include <fstream>
#include <string>
#include "MatrixWriter.h"
namespace CODETEST
{
/******************************************************************************
* CONSTRUCTORS / DESTRUCTORS **************************************************
******************************************************************************/
MatrixWriter::MatrixWriter(const std::string& filename)
: m_filename(filename)
{
assert(!m_filename.empty());
// do nothing
}
/******************************************************************************
* PUBLIC METHODS **************************************************************
******************************************************************************/
void MatrixWriter::write(const size_t numRows,
const size_t numCols,
const std::vector<double>& vals)
{
std::fstream outFile(m_filename, std::fstream::out | std::fstream::trunc);
if (!outFile.is_open()) {
throw std::runtime_error("Failed to open file: " + m_filename);
}
// write out the header of matrix dimensions
outFile << numRows << " " << numCols << std::endl;
for (size_t row=0; row < numRows; ++row) {
for (size_t col=0; col < numCols; ++col) {
const size_t idx = col + row*numCols;
outFile << vals[idx] << " ";
}
outFile << std::endl;
}
}
} // namespace CODETEST
| [
"kevin.briggs@3dsim.com"
] | kevin.briggs@3dsim.com |
76a688a84ba007d5a66eb9d472dea1909104972b | fd4644b2b988f62b14d5e20ef565b70b92cfb0a5 | /kgl/src/obj.cpp | 4cc59bd84152f6cb76b742d827df7e3a67ebeebb | [] | no_license | jhk2/glsandbox | 63d64fb324f44d312bb91a99d5f04150a6669b54 | ad442f029bac361133484b51d53ab3a833e23a2d | refs/heads/master | 2020-04-28T00:31:39.280049 | 2014-07-18T20:00:36 | 2014-07-18T20:00:36 | 5,698,311 | 6 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 21,833 | cpp | #include "obj.h"
#include <stdio.h>
#include <assert.h>
#include "shader.h"
#include "matrixstack.h"
Obj::Obj(const char *filename) : currentcombo_(0), min_(), max_()
{
loadFile(filename);
}
Obj::~Obj()
{
for (std::map<std::string, std::pair<ObjMesh *, ObjMaterial *>>::iterator iter = meshes_.begin(); iter != meshes_.end(); iter++) {
delete iter->second.first;
}
for (std::map<std::string, ObjMaterial *>::iterator iter = materials_.begin(); iter != materials_.end(); iter++) {
delete iter->second;
}
for (std::map<std::string, Texture *>::iterator iter = textures_.begin(); iter != textures_.end(); iter++) {
delete iter->second;
}
}
void Obj::draw(const Shader &shader) const
{
// assume that if more than one shader stage needs the uniforms they will be bound to the same pipeline object
//~ printf("drawing obj\n"); fflush(stdout);
// go through all of the sub meshes in the map
for (std::map<std::string, std::pair<ObjMesh *, ObjMaterial *>>::const_iterator iter = meshes_.begin(); iter != meshes_.end(); iter++) {
//~ printf("drawing submesh %s\n", iter->first.c_str()); fflush(stdout);
//~ printf("get material\n"); fflush(stdout);
ObjMaterial &curmat = *(iter->second.second);
/*
// set material parameters as uniform values
//~ printf("get uniform locations\n"); fflush(stdout);
GLint Ns, Ni, Tr, Tf, illum, Ka, Kd, Ks, Ke, map_Ka, map_Kd, map_Ks;
Ns = shader.getUniformLocation("Ns");
Ni = shader.getUniformLocation("Ni");
Tr = shader.getUniformLocation("Tr");
Tf = shader.getUniformLocation("Tf");
illum = shader.getUniformLocation("illum");
Ka = shader.getUniformLocation("Ka");
Kd = shader.getUniformLocation("Kd");
Ks = shader.getUniformLocation("Ks");
Ke = shader.getUniformLocation("Ke");
map_Ka = shader.getUniformLocation("map_Ka");
map_Kd = shader.getUniformLocation("map_Kd");
map_Ks = shader.getUniformLocation("map_Ks");
//~ printf("set uniform values\n"); fflush(stdout);
shader.use();
if (Ns != -1) {
glUniform1f(Ns, curmat.Ns);
}
if (Ni != -1) {
glUniform1f(Ni, curmat.Ni);
}
if (Tr != -1) {
glUniform1f(Tr, curmat.Tr);
}
if (Tf != -1) {
glUniform3fv(Tf, 1, &curmat.Tf.x);
}
if (illum != -1) {
glUniform1ui(illum, curmat.illum);
}
if (Ka != -1) {
glUniform3fv(Ka, 1, &curmat.Ka.x);
}
if (Kd != -1) {
glUniform3fv(Kd, 1, &curmat.Kd.x);
}
if (Ks != -1) {
glUniform3fv(Ks, 1, &curmat.Ks.x);
}
if (Ke != -1) {
glUniform3fv(Ke, 1, &curmat.Ke.x);
}
if (map_Ka != -1) {
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, curmat.map_Ka->getID());
glUniform1i(map_Ka, 0);
}
if (map_Kd != -1) {
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, curmat.map_Kd->getID());
glUniform1i(map_Kd, 1);
}
if (map_Ks != -1) {
glActiveTexture(GL_TEXTURE2);
glBindTexture(GL_TEXTURE_2D, curmat.map_Ks->getID());
glUniform1i(map_Ks, 2);
}
*/
// Bind uniform buffer with material parameters
GLuint blockIndex = shader.getUniformBlockIndex("ObjMaterial");
if (blockIndex != -1) {
glBindBufferBase(GL_UNIFORM_BUFFER, blockIndex, curmat.ubo);
}
GLint map_Ka, map_Kd, map_Ks;
map_Ka = shader.getUniformLocation("map_Ka");
map_Kd = shader.getUniformLocation("map_Kd");
map_Ks = shader.getUniformLocation("map_Ks");
// bind textures to pre-determined locations
if (map_Ka != -1) {
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, curmat.map_Ka->getID());
glUniform1i(map_Ka, 0);
}
if (map_Kd != -1) {
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, curmat.map_Kd->getID());
glUniform1i(map_Kd, 1);
}
if (map_Ks != -1) {
glActiveTexture(GL_TEXTURE2);
glBindTexture(GL_TEXTURE_2D, curmat.map_Ks->getID());
glUniform1i(map_Ks, 2);
}
//~ glActiveTexture(GL_TEXTURE0);
//~ glBindTexture(GL_TEXTURE_2D, curmat.map_Ka->getID());
//~ glActiveTexture(GL_TEXTURE1);
//~ glBindTexture(GL_TEXTURE_2D, curmat.map_Kd->getID());
//~ glActiveTexture(GL_TEXTURE2);
//~ glBindTexture(GL_TEXTURE_2D, curmat.map_Ks->getID());
// draw the actual mesh
ObjMesh &curmesh = *(iter->second.first);
curmesh.draw();
glActiveTexture(GL_TEXTURE2);
glBindTexture(GL_TEXTURE_2D, 0);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, 0);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, 0);
if (blockIndex != -1) {
glBindBufferBase(GL_UNIFORM_BUFFER, blockIndex, 0);
}
}
}
void Obj::getBounds(fl3 &min, fl3 &max)
{
min = min_;
max = max_;
}
bool Obj::loadFile(const char *filename)
{
//printf("trying to load obj file %s\n", filename); fflush(stdout);
FILE *pFile = fopen(filename, "r");
if(!pFile) {
printf("failed to open obj file %s\n", filename); fflush(stdout);
return false;
}
char line[1024] = "";
char buf[512] = "";
ObjMaterial *currentmat = 0;
std::string meshname = "";
// map for storing v/t/n triples versus index buffer
std::map<int3, unsigned int> triples;
fpos_t lastread;
fgetpos(pFile, &lastread);
while (fscanf(pFile, "%s", buf) > 0) {
if (strcmp(buf, "mtllib") == 0) {
// need to load the material file if we have not already
fscanf(pFile, "%s", buf);
std::string mtlfile (buf);
if (mtlfiles_.find(mtlfile) == mtlfiles_.end()) {
// add the path to the obj file to the name
std::string fullpath (filename);
size_t slashindex = fullpath.find_last_of("/");
if (slashindex != std::string::npos) {
mtlfile = fullpath.substr(0, slashindex + 1) + mtlfile;
}
// insert a new material
loadMaterials(mtlfile.c_str());
} else {
printf("found undefined mtlfile %s, which is bad, but continuing\n", buf); fflush(stdout);
}
} else if (strcmp(buf, "usemtl") == 0) {
fscanf(pFile, "%s", buf);
std::string mtlfile (buf);
currentmat = materials_[mtlfile];
assert(currentmat != 0);
} else if (strcmp(buf, "g") == 0) {
fscanf(pFile, "%s", buf);
//printf("loading submesh %s\n", buf); fflush(stdout);
meshname = buf;
} else if (strcmp(buf, "v") == 0) {
fl3 v;
fscanf(pFile, "%f %f %f", &v.x, &v.y, &v.z);
// update min/max
min_.x = min(min_.x, v.x);
min_.y = min(min_.y, v.y);
min_.z = min(min_.z, v.z);
max_.x = max(max_.x, v.x);
max_.y = max(max_.y, v.y);
max_.z = max(max_.z, v.z);
verts_.push_back(v);
} else if (strcmp(buf, "vt") == 0) {
fl3 t;
fscanf(pFile, "%f %f %f", &t.x, &t.y, &t.z);
texs_.push_back(t);
} else if (strcmp(buf, "vn") == 0) {
fl3 n;
fscanf(pFile, "%f %f %f", &n.x, &n.y, &n.z);
norms_.push_back(n);
} else if (strcmp(buf, "f") == 0) {
// move it back to before the f
fsetpos(pFile, &lastread);
// we make the assumption that all faces for a particular mesh are consecutively located in the file
// get the face indices
ObjMesh *currentmesh = 0;
if (texs_.size() == 0 && norms_.size() == 0) {
// we only have positions
//printf("create new PMesh\n"); fflush(stdout);
currentmesh = createPMesh(pFile);
} else if (texs_.size() == 0) {
// we have positions and normals
//printf("we've read %u verts and %u normals\n", verts_.size(), norms_.size()); fflush(stdout);
//printf("create new PNMesh\n"); fflush(stdout);
currentmesh = createPNMesh(pFile);
} else if (norms_.size() == 0) {
// we have positions and texcoords
//printf("create new PTMesh\n"); fflush(stdout);
currentmesh = createPTMesh(pFile);
} else {
// we have all 3
//printf("create new PTNMesh\n"); fflush(stdout);
currentmesh = createPTNMesh(pFile);
}
// put it in the map
if(meshname.length() == 0) {
meshname = "default";
}
if(meshes_.find(meshname) == meshes_.end()) {
//printf("inserting new mesh with name %s\n", meshname.c_str()); fflush(stdout);
meshes_[meshname] = std::pair<ObjMesh*,ObjMaterial*>(currentmesh, currentmat);
} else {
printf("tried to insert mesh which already existed with name %s\n", meshname.c_str()); fflush(stdout);
}
}
fgetpos(pFile, &lastread);
}
// clear temporary stuff
verts_.clear();
texs_.clear();
norms_.clear();
inds_.clear();
mtlfiles_.clear();
combos_.clear();
return true;
}
bool Obj::loadMaterials(const char *filename)
{
//printf("trying to load mtl file %s\n", filename); fflush(stdout);
FILE *pFile = fopen(filename, "r");
if(!pFile) {
printf("couldn't open mtlfile %s\n", filename); fflush(stdout);
return false;
}
// get the directory
std::string fullpath (filename);
size_t slashindex = fullpath.find_last_of("/");
std::string directory = "";
if (slashindex != std::string::npos) {
directory = fullpath.substr(0, slashindex + 1);
}
ObjMaterial *currentmat = 0;
char buf[512] = "";
while (fscanf(pFile, "%s", buf) > 0) {
//printf("buf contents %s\n", buf); fflush(stdout);
if (strcmp(buf, "newmtl") == 0) {
fscanf(pFile, "%s", buf);
ObjMaterial *newmat = new ObjMaterial();
newmat->name = std::string(buf);
materials_[newmat->name] = newmat;
currentmat = newmat;
} else if (strcmp(buf, "Ns") == 0) {
float val;
fscanf(pFile, "%f", &val);
currentmat->ublock.Ns = val;
} else if (strcmp(buf, "Ni") == 0) {
float val;
fscanf(pFile, "%f", &val);
currentmat->ublock.Ni = val;
} else if (strcmp(buf, "d") == 0 || strcmp(buf, "Tr") == 0) {
float val;
fscanf(pFile, "%f", &val);
// for d/tf, might have another value already so take the max
currentmat->ublock.d = max(currentmat->ublock.d, val);
} else if (strcmp(buf, "illum") == 0) {
unsigned int val;
fscanf(pFile, "%u", &val);
currentmat->ublock.illum = val;
} else if (strcmp(buf, "Ka") == 0) {
fl3 val;
fscanf(pFile, "%f %f %f", &val.x, &val.y, &val.z);
currentmat->ublock.Ka = val;
} else if (strcmp(buf, "Kd") == 0) {
fl3 val;
fscanf(pFile, "%f %f %f", &val.x, &val.y, &val.z);
currentmat->ublock.Kd = val;
} else if (strcmp(buf, "Ks") == 0) {
fl3 val;
fscanf(pFile, "%f %f %f", &val.x, &val.y, &val.z);
currentmat->ublock.Ks = val;
} else if (strcmp(buf, "Ke") == 0) {
fl3 val;
fscanf(pFile, "%f %f %f", &val.x, &val.y, &val.z);
currentmat->ublock.Ke = val;
} else if (strcmp(buf, "map_Ka") == 0) {
fscanf(pFile, "%s", buf);
std::string texpath (buf);
std::string fulltexpath = directory + texpath;
if (textures_.find(texpath) == textures_.end()) {
// insert a new texture
textures_[texpath] = new Texture(fulltexpath.c_str());
}
currentmat->map_Ka = textures_[texpath];
} else if (strcmp(buf, "map_Kd") == 0) {
fscanf(pFile, "%s", buf);
std::string texpath (buf);
std::string fulltexpath = directory + buf;
if (textures_.find(texpath) == textures_.end()) {
// insert a new texture
textures_[texpath] = new Texture(fulltexpath.c_str());
}
currentmat->map_Kd = textures_[texpath];
} else if (strcmp(buf, "map_Ks") == 0) {
fscanf(pFile, "%s", buf);
std::string texpath (buf);
std::string fulltexpath = directory + buf;
if (textures_.find(texpath) == textures_.end()) {
// insert a new texture
textures_[texpath] = new Texture(fulltexpath.c_str());
}
currentmat->map_Ks = textures_[texpath];
}
}
for (std::map<std::string, ObjMaterial *>::iterator it = materials_.begin(); it != materials_.end(); it++) {
ObjMaterial *mat = it->second;
// make a uniform buffer for these properties
GLuint &ubo = mat->ubo;
glGenBuffers(1, &ubo);
glBindBuffer(GL_UNIFORM_BUFFER, ubo);
glBufferData(GL_UNIFORM_BUFFER, sizeof(ObjMaterial::ObjUniformBlock), ¤tmat->ublock, GL_STATIC_READ);
glBindBuffer(GL_UNIFORM_BUFFER, 0);
}
return true;
}
Obj::ObjMesh* Obj::createPTNMesh(FILE *file)
{
//~ printf("creating ptn mesh\n"); fflush(stdout);
unsigned int read = 0;
InterleavedMesh<PTNvert, GLuint> *mesh = new InterleavedMesh<PTNvert, GLuint>(GL_TRIANGLES);
currentcombo_ = 0;
combos_.clear();
// 3 vertex attributes with 3 floats each
mesh->addAttrib(0, AttributeInfoSpec<GLfloat>(3)).addAttrib(1, AttributeInfoSpec<GLfloat>(3)).addAttrib(2, AttributeInfoSpec<GLfloat>(3));
fpos_t lastpos;
char buf[512] = "";
fgetpos(file, &lastpos);
while (fscanf(file, "%s", buf) > 0) {
if (strcmp(buf, "f") != 0) {
// we hit something other than "f"
//~ printf("hit a non f character %s after %u faces\n", buf, read); fflush(stdout);
fsetpos(file, &lastpos);
break;
} else {
// read the face
int3 v[3];
fscanf(file, "%u/%u/%u %u/%u/%u %u/%u/%u", &v[0].x, &v[0].y, &v[0].z, &v[1].x, &v[1].y, &v[1].z, &v[2].x, &v[2].y, &v[2].z);
// check if each of them is contained
PTNvert vert;
for (int i = 0; i < 3; i++) {
int3 &cur = v[i];
if (combos_.find(cur) == combos_.end()) {
//~ printf("making new vertex entry for combo %u/%u/%u index %u\n", cur.x, cur.y, cur.z, currentcombo_); fflush(stdout);
combos_[cur] = currentcombo_;
//inds_.push_back(currentcombo_);
mesh->addInd(currentcombo_);
currentcombo_++;
vert.pos_ = verts_[cur.x - 1];
vert.tex_ = texs_[cur.y - 1];
vert.norm_ = norms_[cur.z - 1];
//~ printf("adding new vertex combo index %u pos %f,%f,%f (%u) tex %f,%f,%f (%u)\n", currentcombo_, vert.pos_.x, vert.pos_.y, vert.pos_.z, cur.x-1, vert.tex_.x, vert.tex_.y, vert.tex_.z, cur.y-1); fflush(stdout);
mesh->addVert(vert);
} else {
//~ printf("found existing entry for combo %u/%u/%u index %u\n", cur.x, cur.y, cur.z, combos_[cur]); fflush(stdout);
//inds_.push_back(combos_[cur]);
mesh->addInd(combos_[cur]);
}
}
read++;
}
fgetpos(file, &lastpos);
}
mesh->finalize();
// we've read all the faces, so make the mesh
return new ObjMesh(mesh);
}
Obj::ObjMesh* Obj::createPTMesh(FILE *file)
{
unsigned int read = 0;
currentcombo_ = 0;
combos_.clear();
InterleavedMesh<PTvert, GLuint> *mesh = new InterleavedMesh<PTvert, GLuint>(GL_TRIANGLES);
// 2 vertex attributes with 3 floats each
mesh->addAttrib(0, AttributeInfoSpec<GLfloat>(3)).addAttrib(1, AttributeInfoSpec<GLfloat>(3));
fpos_t lastpos;
char buf[512] = "";
fgetpos(file, &lastpos);
while (fscanf(file, "%s", buf) > 0) {
//~ printf("buf contents: %s\n", buf); fflush(stdout);
if (strcmp(buf, "f") != 0) {
// we hit something other than "f"
//~ printf("hit something other than f: %s\n", buf); fflush(stdout);
fsetpos(file, &lastpos);
break;
} else {
// read the face
int3 v[3];
unsigned int scanned = fscanf(file, "%u/%u %u/%u %u/%u", &v[0].x, &v[0].y, &v[1].x, &v[1].y, &v[2].x, &v[2].y);
//~ if(scanned != 6) {
//~ printf("scanned less than 6 items: %u/%u %u/%u %u/%u\n", v[0].x, v[0].y, v[1].x, v[1].y, v[2].x, v[2].y);
//~ fflush(stdout);
//~ }
// check if each of them is contained
PTvert vert;
for (int i = 0; i < 3; i++) {
int3 &cur = v[i];
if (combos_.find(cur) == combos_.end()) {
combos_[cur] = currentcombo_;
//inds_.push_back(currentcombo_);
mesh->addInd(currentcombo_);
currentcombo_++;
vert.pos_ = verts_[cur.x - 1];
vert.tex_ = texs_[cur.y - 1];
mesh->addVert(vert);
} else {
//inds_.push_back(combos_[cur]);
mesh->addInd(combos_[cur]);
}
}
read++;
}
fgetpos(file, &lastpos);
}
//~ printf("read %u faces\n", read); fflush(stdout);
mesh->finalize();
// we've read all the faces, so make the mesh
return new ObjMesh(mesh);
}
Obj::ObjMesh* Obj::createPNMesh(FILE *file)
{
currentcombo_ = 0;
combos_.clear();
//printf("creating pn mesh\n"); fflush(stdout);
InterleavedMesh<PNvert, GLuint> *mesh = new InterleavedMesh<PNvert, GLuint>(GL_TRIANGLES);
// 2 vertex attributes with 3 floats each
mesh->addAttrib(0, AttributeInfoSpec<GLfloat>(3)).addAttrib(2, AttributeInfoSpec<GLfloat>(3));
fpos_t lastpos;
char buf[512] = "";
fgetpos(file, &lastpos);
unsigned int faces = 0;
while (fscanf(file, "%s", buf) > 0) {
if (strcmp(buf, "f") != 0) {
// we hit something other than "f"
//printf("hit something other than f, ending mesh\n"); fflush(stdout);
fsetpos(file, &lastpos);
break;
} else {
// read the face
int3 v[3];
fscanf(file, "%u//%u %u//%u %u//%u", &v[0].x, &v[0].y, &v[1].x, &v[1].y, &v[2].x, &v[2].y);
// check if each of them is contained
PNvert vert;
for (int i = 0; i < 3; i++) {
int3 &cur = v[i];
if (combos_.find(cur) == combos_.end()) {
combos_[cur] = currentcombo_;
//inds_.push_back(currentcombo_);
mesh->addInd(currentcombo_);
currentcombo_++;
vert.pos_ = verts_[cur.x - 1];
vert.norm_ = norms_[cur.y - 1];
mesh->addVert(vert);
} else {
//inds_.push_back(combos_[cur]);
mesh->addInd(combos_[cur]);
}
}
faces++;
}
fgetpos(file, &lastpos);
}
//printf("read %u faces\n", faces); fflush(stdout);
mesh->finalize();
// we've read all the faces, so make the mesh
return new ObjMesh(mesh);
}
Obj::ObjMesh* Obj::createPMesh(FILE *file)
{
currentcombo_ = 0;
combos_.clear();
InterleavedMesh<fl3, GLuint> *mesh = new InterleavedMesh<fl3, GLuint>(GL_TRIANGLES);
// 2 vertex attributes with 3 floats each
mesh->addAttrib(0, AttributeInfoSpec<GLfloat>(3));
fpos_t lastpos;
char buf[512] = "";
fgetpos(file, &lastpos);
while (fscanf(file, "%s", buf) > 0) {
if (strcmp(buf, "f") != 0) {
// we hit something other than "f"
fsetpos(file, &lastpos);
break;
} else {
// read the face
int3 v[3];
fscanf(file, "%u/%u %u/%u %u/%u", &v[0].x, &v[1].x, &v[2].x);
// check if each of them is contained
fl3 vert;
for (int i = 0; i < 3; i++) {
int3 &cur = v[i];
if (combos_.find(cur) == combos_.end()) {
combos_[cur] = currentcombo_;
//inds_.push_back(currentcombo_);
mesh->addInd(currentcombo_);
currentcombo_++;
vert = verts_[cur.x - 1];
mesh->addVert(vert);
} else {
//inds_.push_back(combos_[cur]);
mesh->addInd(combos_[cur]);
}
}
}
fgetpos(file, &lastpos);
}
mesh->finalize();
// we've read all the faces, so make the mesh
return new ObjMesh(mesh);
}
| [
"krazyklutzykorean@gmail.com"
] | krazyklutzykorean@gmail.com |
b957f945cc14bce5c0b3bf697c4d2eecd3ca92a7 | d7b3865f1669739ca2487f65b4af24ec0087f8cf | /cxx/apply_optional.cpp | d859fd30a7f0a0f88a1bbfc2dd77f6614761866a | [] | no_license | agutikov/stuff | 78bee46eacfb67da4ce445dd5b7bd90924aad7de | 41ab186219440de6acfa537758dcfd66c35d320d | refs/heads/master | 2023-01-21T13:27:35.569670 | 2023-01-10T04:07:26 | 2023-01-10T04:07:26 | 8,577,077 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,281 | cpp | #include <iostream>
#include <optional>
struct Trace
{
Trace() { std::cout << " ctor" << std::endl; }
~Trace() { std::cout << " dtor" << std::endl; }
Trace(const Trace&) { std::cout << " copy ctor" << std::endl; }
Trace& operator=(const Trace&) { std::cout << " copy operator=" << std::endl; return *this; }
Trace(Trace&&) { std::cout << " move ctor" << std::endl; }
Trace& operator=(Trace&&) { std::cout << " move operator=" << std::endl; return *this; }
void foo() const { std::cout << " foo const" << std::endl; }
void bar() { std::cout << " bar" << std::endl; }
};
void Foo(const Trace& t)
{
t.foo();
}
void Bar(Trace& t)
{
t.bar();
}
int Baz(Trace& t)
{
return 123;
}
typedef void(*void_trace_f)(Trace& t);
template <typename T, void_trace_f f>
void optional_apply(std::optional<T>& v)
{
if (v.has_value()) {
f(v.value());
}
}
typedef void(*void_const_trace_f)(const Trace& t);
template <typename T, void_const_trace_f f>
void optional_apply(const std::optional<T>& v)
{
if (v.has_value()) {
f(v.value());
}
}
int main()
{
std::optional<Trace> t1(std::in_place);
optional_apply<Trace, Bar>(t1);
optional_apply<Trace, Foo>(t1);
return 0;
}
| [
"gutikoff@gmail.com"
] | gutikoff@gmail.com |
86f64f9263bd7c290cd06e421df38d5d07bacb15 | 3bf91b10c47d677ac6caf121eeb4d1ead8d2b561 | /src/helium/device/mpc23017.h | 11e6c7d292de9a597a81e52b5997bda641598bd9 | [] | no_license | fabiodl/helium | 8d9dea1e433973632199ea10a5bf54b6a3741afe | fe8f58eb55e033c596d66e377dc808c46ca0dfce | refs/heads/master | 2020-12-06T15:09:29.227558 | 2020-03-10T07:48:28 | 2020-03-10T07:48:28 | 67,750,827 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,504 | h | #ifndef HE_MPC23017
#define HE_MPC23017
#include <stdint.h>
namespace helium{
template <typename I2C>
class MPC23017{
public:
enum AddrTable{
DEVICEADDR=0x20, //start address,
};
enum Name{
A,B
};
enum Direction{IN,OUT,ALLIN=0,ALLOUT=0xFF};
MPC23017(I2C& pi2c);
void setDirection(uint16_t dir);
void setDirection(Name p,unsigned char mask);
void setDirection(Name p,int bit,bool value);
void setOutput(uint16_t dir);
void setOutput(Name p,unsigned char val);
void setOutput(Name p,int bit,bool x);
void setPullup(uint16_t dir);
void setPullup(Name p,unsigned char val);
void setPullup(Name p,int bit,bool x);
uint16_t read();
unsigned char read(Name p);
bool read(Name p,int bit);
private:
typedef unsigned char Cache[2];
void setRegister(Cache& c,unsigned char regbase,uint16_t val);
void setRegister(Cache& c,unsigned char regbase,unsigned char offset,unsigned char val);
void setRegister(Cache& c,unsigned char regbase,unsigned char offset,unsigned char bit,bool val);
I2C& i2c;
Cache ddr,port,pullup;
class paired{
public:
enum Regs{
IODIRA,
IODIRB,
IPOLA,
IPOLB,
GPINTENA,
GPINTENB,
DEFVALA,
DEFVALB,
INTCONA,
INTCONB,
IOCON,
IOCON2,
GPPUA,
GPPUB,
INTFA,
INTFB,
INTCAPA,
INTCAPB,
GPIOA,
GPIOB,
OLATA,
OLATB,
};
};
};
}
#include "mpc23017.hpp"
#endif
| [
"fabiodl@gmail.com"
] | fabiodl@gmail.com |
0d0a6c28b08ceb2d280f5373d884b25ac368e9d3 | aecf4944523b50424831f8af3debef67e3163b97 | /net.ssa/xr_3da/xrGame/movement_manager_game.cpp | 62bd05cfcd22491feb9b3ad853d913ddb01df6d2 | [] | no_license | xrLil-Batya/gitxray | bc8c905444e40c4da5d77f69d03b41d5b9cec378 | 58aaa5185f7a682b8cf5f5f376a2e5b6ca16fed4 | refs/heads/main | 2023-03-31T07:43:57.500002 | 2020-12-12T21:12:25 | 2020-12-12T21:12:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,979 | cpp | ////////////////////////////////////////////////////////////////////////////
// Module : movement_manager_game.cpp
// Created : 03.12.2003
// Modified : 03.12.2003
// Author : Dmitriy Iassenev
// Description : Movement manager for game paths
////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "movement_manager.h"
#include "alife_simulator.h"
#include "alife_graph_registry.h"
#include "alife_level_registry.h"
#include "profiler.h"
#include "game_location_selector.h"
#include "game_path_manager.h"
#include "level_location_selector.h"
#include "level_path_manager.h"
#include "detail_path_manager.h"
#include "ai_object_location.h"
#include "custommonster.h"
#include "level_path_builder.h"
#include "detail_path_builder.h"
#include "mt_config.h"
void CMovementManager::process_game_path()
{
START_PROFILE ("Build Path/Process Game Path");
if (m_path_state != ePathStateTeleport) {
if (!level_path().actual() && (m_path_state > ePathStateBuildLevelPath))
m_path_state = ePathStateBuildLevelPath;
if (!game_path().actual() && (m_path_state > ePathStateBuildGamePath))
m_path_state = ePathStateBuildGamePath;
}
switch (m_path_state) {
case ePathStateSelectGameVertex : {
game_selector().select_location(object().ai_location().game_vertex_id(),game_path().m_dest_vertex_id);
if (game_selector().failed())
break;
m_path_state = ePathStateBuildGamePath;
// if (time_over())
// break;
}
case ePathStateBuildGamePath : {
game_path().build_path(object().ai_location().game_vertex_id(),game_dest_vertex_id());
if (game_path().failed()) {
Msg ("! Cannot build GAME path! (object %s)",*object().cName());
Msg ("! CURRENT LEVEL : %s",*Level().name());
Fvector temp = ai().game_graph().vertex(object().ai_location().game_vertex_id())->level_point();
Msg ("! CURRENT game point position : [%f][%f][%f]",VPUSH(temp));
const GameGraph::CVertex *vertex = ai().game_graph().vertex(game_dest_vertex_id());
Msg ("! TARGET LEVEL : %s",*ai().game_graph().header().level(vertex->level_id()).name());
temp = vertex->level_point();
Msg ("! TARGET game point position : [%f][%f][%f]",VPUSH(temp));
const u8 *target_vertex_type = ai().game_graph().vertex(game_dest_vertex_id())->vertex_type();
Msg (
"! Target point mask [%d][%d][%d][%d]",
target_vertex_type[0],
target_vertex_type[1],
target_vertex_type[2],
target_vertex_type[3]
);
Msg ("! Object masks (%d) :",m_location_manager->vertex_types().size());
typedef GameGraph::TERRAIN_VECTOR::const_iterator const_iterator;
const_iterator I = m_location_manager->vertex_types().begin();
const_iterator E = m_location_manager->vertex_types().end();
for ( ; I != E; ++I)
Msg ("! [%d][%d][%d][%d]",(*I).tMask[0],(*I).tMask[1],(*I).tMask[2],(*I).tMask[3]);
break;
}
m_path_state = ePathStateContinueGamePath;
// if (time_over())
// break;
}
case ePathStateContinueGamePath : {
game_path().select_intermediate_vertex();
if (ai().game_graph().vertex(object().ai_location().game_vertex_id())->level_id() != ai().game_graph().vertex(game_path().intermediate_vertex_id())->level_id()) {
m_path_state = ePathStateTeleport;
VERIFY (ai().get_alife());
VERIFY (ai().alife().graph().level().level_id() == ai().game_graph().vertex(object().ai_location().game_vertex_id())->level_id());
teleport (game_path().intermediate_vertex_id());
break;
}
m_path_state = ePathStateBuildLevelPath;
// if (time_over())
// break;
}
case ePathStateBuildLevelPath : {
VERIFY (
ai().game_graph().vertex(object().ai_location().game_vertex_id())->level_id()
==
ai().game_graph().vertex(game_path().intermediate_vertex_id())->level_id()
);
u32 dest_level_vertex_id = ai().game_graph().vertex(
game_path().intermediate_vertex_id()
)->level_vertex_id();
if (!accessible(dest_level_vertex_id)) {
Fvector dest_pos;
dest_level_vertex_id = restrictions().accessible_nearest(
ai().level_graph().vertex_position(dest_level_vertex_id),
dest_pos
);
}
if (can_use_distributed_compuations(mtLevelPath)) {
level_path_builder().setup(
object().ai_location().level_vertex_id(),
dest_level_vertex_id
);
break;
}
level_path().build_path(
object().ai_location().level_vertex_id(),
dest_level_vertex_id
);
if (level_path().failed()) {
m_path_state = ePathStateBuildLevelPath;
break;
}
m_path_state = ePathStateContinueLevelPath;
break;
}
case ePathStateContinueLevelPath : {
VERIFY (!level_path().failed());
level_path().select_intermediate_vertex();
m_path_state = ePathStateBuildDetailPath;
// if (time_over())
// break;
}
case ePathStateBuildDetailPath : {
detail().set_state_patrol_path(true);
detail().set_start_position(object().Position());
detail().set_start_direction(Fvector().setHP(-m_body.current.yaw,0));
detail().set_dest_position(
ai().level_graph().vertex_position(
level_path().intermediate_vertex_id()
)
);
if (can_use_distributed_compuations(mtDetailPath)) {
detail_path_builder().setup(
level_path().path(),
level_path().intermediate_index()
);
break;
}
detail().build_path(
level_path().path(),
level_path().intermediate_index()
);
on_build_path ();
if (detail().failed()) {
m_path_state = ePathStateBuildLevelPath;
break;
}
m_path_state = ePathStatePathVerification;
break;
}
case ePathStatePathVerification : {
if (!game_selector().actual(object().ai_location().game_vertex_id(),path_completed()))
m_path_state = ePathStateSelectGameVertex;
else
if (!game_path().actual())
m_path_state = ePathStateBuildGamePath;
else
if (!level_path().actual())
m_path_state = ePathStateBuildLevelPath;
else
if (!detail().actual())
m_path_state = ePathStateBuildLevelPath;
else
if (detail().completed(object().Position(),!detail().state_patrol_path())) {
m_path_state = ePathStateContinueLevelPath;
if (level_path().completed()) {
m_path_state = ePathStateContinueGamePath;
if (game_path().completed())
m_path_state = ePathStatePathCompleted;
}
}
break;
}
case ePathStatePathCompleted : {
if (!game_selector().actual(object().ai_location().game_vertex_id(),path_completed()))
m_path_state = ePathStateSelectGameVertex;
break;
}
case ePathStateTeleport : {
break;
}
default : NODEFAULT;
}
STOP_PROFILE
}
| [
"admin@localhost"
] | admin@localhost |
20f1040e993b9176e8d70b11ea977d36de1023c0 | 60a1cada7a89823dca25937367eeeea86c189864 | /Private_inheritance.cpp | b46d25a7acf201f669cb3403a7fd7e93674f52dc | [] | no_license | errorr404/OOPS-Concept | 666bc414a3da8a884607ea5640983f642a1e22d6 | d898732e6942030723ce8897b34c70179253ca2d | refs/heads/master | 2020-03-28T05:10:06.883410 | 2018-09-13T01:55:26 | 2018-09-13T01:55:26 | 147,760,035 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 639 | cpp | #include<bits/stdc++.h>
using namespace std;
class Person{
protected:
string name;
public:
void setName(string iname){
name=iname;
}
};
class Student : private Person{
// all the members of the base class is available here as a private member.
public:
void display(){
cout<<name<<endl;
}
void studentsetname(string iname){
setName(iname);
}
};
class Gstudent: public Student {
// name is not assessble here bcz it is private in class Student
public:
void setGstudentName(string iname){
studentsetname(iname);
}
};
int main(){
Gstudent dixit;
dixit.setGstudentName("Dixit");
dixit.display();
}
| [
"dkbishwash@gmail.com"
] | dkbishwash@gmail.com |
6496411ad3415c30eef7ea12dd6af9d770750bff | b72356a44c0229b492027094c83356240a228792 | /Vivado_HLS/HLS/mpc_pso/solution1/syn/systemc/Compult_mul_31s_10ns_41_3.h | 7376e4fc880471cc6a7a8d2ed23645b9d5f25559 | [] | no_license | jlumeiqin/ETC_ECU | e953e5990d13cfed756e8067042a820d759540b9 | fc65963e634372bf688bf9eff9402ed1c62c99a9 | refs/heads/master | 2021-01-21T19:45:36.190239 | 2015-11-05T01:54:49 | 2015-11-05T01:54:49 | 45,520,228 | 3 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,215 | h | // ==============================================================
// File generated by Vivado(TM) HLS - High-Level Synthesis from C, C++ and SystemC
// Version: 2014.4
// Copyright (C) 2014 Xilinx Inc. All rights reserved.
//
// ==============================================================
#ifndef __Compult_mul_31s_10ns_41_3__HH__
#define __Compult_mul_31s_10ns_41_3__HH__
#include "ACMP_mul_su.h"
#include <systemc>
template<
int ID,
int NUM_STAGE,
int din0_WIDTH,
int din1_WIDTH,
int dout_WIDTH>
SC_MODULE(Compult_mul_31s_10ns_41_3) {
sc_core::sc_in_clk clk;
sc_core::sc_in<sc_dt::sc_logic> reset;
sc_core::sc_in<sc_dt::sc_logic> ce;
sc_core::sc_in< sc_dt::sc_lv<din0_WIDTH> > din0;
sc_core::sc_in< sc_dt::sc_lv<din1_WIDTH> > din1;
sc_core::sc_out< sc_dt::sc_lv<dout_WIDTH> > dout;
ACMP_mul_su<ID, 3, din0_WIDTH, din1_WIDTH, dout_WIDTH> ACMP_mul_su_U;
SC_CTOR(Compult_mul_31s_10ns_41_3): ACMP_mul_su_U ("ACMP_mul_su_U") {
ACMP_mul_su_U.clk(clk);
ACMP_mul_su_U.reset(reset);
ACMP_mul_su_U.ce(ce);
ACMP_mul_su_U.din0(din0);
ACMP_mul_su_U.din1(din1);
ACMP_mul_su_U.dout(dout);
}
};
#endif //
| [
"hgzxmeiqin123@126.com"
] | hgzxmeiqin123@126.com |
e89ab44d4f0532f20d429a0152ae45ab9a9cb42e | 22e4b712bc42fbb7cb4ac6b1a41897e77d65e563 | /carArduino_2017_1212.ino | 82d960ffd1eced63e51345c517c7b7db8a655e19 | [] | no_license | bioasura/plant7688 | dea98d333530c25ec2b153a44ecfdbf57d426b97 | 39328952eb95efb15d8e1e13328fdd64dcefdf7f | refs/heads/master | 2021-05-14T08:27:44.462793 | 2018-01-04T19:17:33 | 2018-01-04T19:17:33 | 116,297,453 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,355 | ino | #include <Digital_Light_ISL29035.h>
#include <Digital_Light_TSL2561.h>
#include <SoftwareSerial.h>
#include <Wire.h>
#include <Arduino.h>
#include "SHT31.h"
SHT31 sht31 = SHT31();
SoftwareSerial SSerial(11,12);
//const int PinEN = 12;
//const int PinOUT = 11;
//const int PinEN = 12;
//const int PinOUT = 11;
int enabled = 0; //sensor detection flag
int current_state = 0;
int state = 0; //momentary state value
int count = 0; //state change count
int countxx=0;
long currentMilli = 0;
int trigPin = 12; //Trig Pin
int echoPin = 11; //Echo Pin
long duration, cm, inches;
long pmcf10 = 0;
long pmcf25 = 0;
long pmcf100 = 0;
long pmat10 = 0;
long pmat25 = 0;
long pmat100 = 0;
String fpmcf010;
String fpmcf025;
String fpmcf100;
String fpmat010;
String fpmat025;
String fpmat100;
String powerCMD = "";
// the setup function runs once when you press reset or power the board
void setup() {
// enable();
// currentMilli = millis();
SSerial.begin(9600);
Serial.begin(9600);
Serial1.begin(9600);
Wire.begin();
TSL2561.init();
sht31.begin();
/*
pinMode(13, OUTPUT);
pinMode(21, INPUT);
pinMode(6,OUTPUT);
pinMode(trigPin, OUTPUT); //Define inputs and outputs
pinMode(echoPin, INPUT);
pinMode(17, OUTPUT);
pinMode(20, OUTPUT);
*/
delay(100);
}
void getUltraSound() {
digitalWrite(trigPin, LOW);
delayMicroseconds(5);
digitalWrite(trigPin, HIGH); // 蝯� Trig 擃雿���� 10敺桃��
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
pinMode(echoPin, INPUT); // 霈���� echo ��雿�
duration = pulseIn(echoPin, HIGH); // ��擃雿�����
cm = (duration/2) / 29.1; // 撠������ cm ��� inch
inches = (duration/2) / 74;
Serial.print("Distance : ");
Serial.print(inches);
Serial.print("in, ");
Serial.print(cm);
Serial.print("cm");
Serial.println();
Serial1.print("Distance : ");
Serial1.print(inches);
Serial1.print("in, ");
Serial1.print(cm);
Serial1.print("cm");
Serial1.println();
delay(250);
}
// the loop function runs over and over again forever
void loop() {
// digitalWrite(6,HIGH);
getPMS5003();
/* if(digitalRead(PinOUT) != current_state)
{
count++;
delay(1);
current_state = -(current_state - 1); //changes current_state from 0 to 1, and vice-versa
}
*/
/*
if(millis()-currentMilli > 500) //prints the "speed" every half a second
{
print_speed();
}
*/
/*
digitalWrite(2,HIGH);
digitalWrite(3,LOW);
digitalWrite(4,HIGH);
digitalWrite(5,LOW);
*/
/*
digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level)
delay(100); // wait for a second
digitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage LOW
delay(100); // wait for a second
*/
// Serial1.println ("This is a test: "+(String)count+"x");
// Serial1.println ("Command "+(String)count+"x");
// Serial1.println ();
getCommand();
// if (count%10==0){
// Serial.println ("Command: "+(String)count);
// }
countxx++;
// delay(100);
}
void getCommand() {
int count=0;
int c = Serial1.read();
if ((c == 10) || (c == 13)) {
powerCMD.trim();
// Serial1.println ("Arduino Receive CMD:\t" + powerCMD);
Serial.println (powerCMD + "\t" + count);
String devid = getValue(powerCMD, '\t', 0);
String pstate = getValue(powerCMD, '\t', 1);
String npin = getValue(powerCMD, '\t', 2);
powerCMD = "";
devid.trim();
String sensors = getValue(powerCMD, '\t', 0);
Serial.println ("devid:"+devid);
Serial.println ("pstate:"+pstate);
Serial.println ("npin:"+npin);
if (devid == "setPower") {
setPower(pstate, npin);
}
if (devid == "getPMS5003") {
Serial1.println ("PM "+fpmcf010 + " " + fpmcf025 + " "+fpmcf100+" x");
/*
Serial.println ("PMCF010: " + fpmcf010 + " PMCF025: " + fpmcf025 + " PMCF100: " + fpmcf100 + " PMAT010: " + fpmat010 + " PMAT025: " + fpmat025 + " PMAT100: " + fpmat100+" x");
Serial.flush();
Serial1.println ("PMCF010: " + fpmcf010 + " PMCF025: " + fpmcf025 + " PMCF100: " + fpmcf100 + " PMAT010: " + fpmat010 + " PMAT025: " + fpmat025 + " PMAT100: " + fpmat100+" x");
Serial1.flush();
*/
}
if (devid == "getSHT31") {
getSHT31();
}
if (devid == "getLight") {
getLight();
}
if (devid == "getUltraSound") {
getUltraSound();
}
}
if (c != -1) {
powerCMD = powerCMD + (char)c;
}
}
void setPower(String pstate, String npin) {
// Serial1.println ("Arduino receive setPower:\t"+pstate+"\t"+npin+"x");
int common=0;
int countxx=0;
while (countxx<npin.length()) {
if (npin.charAt(count)==',') {
common++;
}
countxx++;
}
Serial.println ("setPower common:"+common);
Serial.println ("setPower common:\t"+(String)common+"\tXXXX");
// Serial1.println ();
int i=0;
for (i=0;i<common;i++) {
String npinC = getValue(npin, ',', i);
String pstateC=getValue(pstate,',',i);
Serial.println ("!!!!!!!!!!!!!!!!!!!! set nPin: "+npinC+"\tpstateC: "+pstateC);
int npinX = npinC.toInt();
int pstateX=pstateC.toInt();
Serial.println ("npinX:"+(String)npinX);
Serial.println ("pstateX:"+(String)pstateX);
pinMode (npinX, OUTPUT);
// delay(1000);
// digitalWrite (npinX, pstateX);
digitalWrite (npinX, pstateX);
}
/*
int npinC = npin.toInt();
int pstateC = pstate.toInt();
pinMode (npinC, OUTPUT);
digitalWrite (npinC, pstateC);
*/
delay(100);
}
String getValue(String data, char separator, int index)
{
int found = 0;
int strIndex[] = {0, -1};
int maxIndex = data.length() - 1;
for (int i = 0; i <= maxIndex && found <= index; i++) {
if (data.charAt(i) == separator || i == maxIndex) {
found++;
strIndex[0] = strIndex[1] + 1;
strIndex[1] = (i == maxIndex) ? i + 1 : i;
}
}
return found > index ? data.substring(strIndex[0], strIndex[1]) : "";
}
void getPMS5003() {
SSerial.begin(9600);
delay(100);
unsigned char cs;
unsigned char high;
while (SSerial.available()) {
cs = SSerial.read();
if ((countxx == 0 && cs != 0x42) || (countxx == 1 && cs != 0x4d)) {
Serial.println("check failed");
break;
}
if (countxx > 15) {
break;
}
else if (countxx == 4 || countxx == 6 || countxx == 8 || countxx == 10 || countxx == 12 || countxx == 14) high = cs;
else if (countxx == 5) {
pmcf10 = 256 * high + cs;
}
else if (countxx == 7) {
pmcf25 = 256 * high + cs;
}
else if (countxx == 9) {
pmcf100 = 256 * high + cs;
}
else if (countxx == 11) {
pmat10 = 256 * high + cs;
}
else if (countxx == 13) {
pmat25 = 256 * high + cs;
}
else if (countxx == 15) {
pmat100 = 256 * high + cs;
}
countxx++;
}
fpmcf010 = String(pmcf10);
fpmcf025 = String(pmcf25);
fpmcf100 = String(pmcf100);
fpmat010 = String(pmat10);
fpmat025 = String(pmat25);
fpmat100 = String(pmat100);
// Serial.println ("\tPMCF010: " + fpmcf010 + " PMCF025: " + fpmcf025 + " PMCF100: " + fpmcf100 + " PMAT010: " + fpmat010 + " PMAT025: " + fpmat025 + " PMAT100: " + fpmat100);
// Serial.flush();
// if (countxx%10==0) {
// Serial1.println ("PMCF010 " + fpmcf010 + " PMCF025 " + fpmcf025 + " PMCF100 " + fpmcf100 + " PMAT010: " + fpmat010 + " PMAT025: " + fpmat025 + " PMAT100: " + fpmat100+" x");
// delay(100);
// Serial1.println ("PM "+fpmcf010 + " " + fpmcf025 + " "+fpmcf100+" x");
// Serial1.flush();
delay(100);
// }
}
void getSHT31() {
float temp = sht31.getTemperature();
float hum = sht31.getHumidity();
Serial.print("Temp = ");
Serial.print(temp);
Serial.println(" C");
Serial.print("Hum = ");
Serial.print(hum);
Serial.println("%");
Serial.println();
delay(1000);
Serial1.print("Temp = ");
Serial1.print(temp);
Serial1.println(" C");
Serial1.print("Hum = ");
Serial1.print(hum);
Serial1.println(" %x");
// Serial1.println();
delay(1000);
}
void getLight() {
Serial.print("The Light value is: ");
Serial.println(TSL2561.readVisibleLux());
Serial1.print ("The Light value is: ");
Serial1.println((String)TSL2561.readVisibleLux()+" x");
delay(1000);
}
/*
void enable()
{
//To start the sensor reading, enable pin EN (pin 9) with HIGH signal
//To make sure it's a clean HIGH signal, give small LOW signal before
pinMode(PinOUT, INPUT);
pinMode(PinEN, OUTPUT);
digitalWrite(PinEN,LOW);
delayMicroseconds(5);
digitalWrite(PinEN, HIGH);
wait();
}
void disable() //function not used in this program
{
pinMode(PinEN, OUTPUT);
digitalWrite(PinEN, LOW);
}
void wait() //waits for the sensor to return a state = 1
{
while(digitalRead(PinOUT) != 1)
{
digitalRead(PinOUT);
}
current_state = 1;
Serial.println("Sensor enabled!");
}
void print_speed()
{
Serial.print("Speed: ");
Serial.print(count*2);
Serial.println(" Changes/s");
currentMilli = millis();
count = 0;
}
*/
| [
"root@shengan-xubuntu-15.10"
] | root@shengan-xubuntu-15.10 |
f627212f0a836dc940d2a6a0beac0533cc04c6fc | bff9ee7f0b96ac71e609a50c4b81375768541aab | /deps/src/cmake-3.9.3/Source/cmNinjaLinkLineComputer.h | 13f05a83867d523bbfa1eccd9d364238731fac9e | [
"BSD-3-Clause"
] | permissive | rohitativy/turicreate | d7850f848b7ccac80e57e8042dafefc8b949b12b | 1c31ee2d008a1e9eba029bafef6036151510f1ec | refs/heads/master | 2020-03-10T02:38:23.052555 | 2018-04-11T02:20:16 | 2018-04-11T02:20:16 | 129,141,488 | 1 | 0 | BSD-3-Clause | 2018-04-11T19:06:32 | 2018-04-11T19:06:31 | null | UTF-8 | C++ | false | false | 815 | h | /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
file Copyright.txt or https://cmake.org/licensing for details. */
#ifndef cmNinjaLinkLineComputer_h
#define cmNinjaLinkLineComputer_h
#include "cmConfigure.h"
#include <string>
#include "cmLinkLineComputer.h"
class cmGlobalNinjaGenerator;
class cmOutputConverter;
class cmStateDirectory;
class cmNinjaLinkLineComputer : public cmLinkLineComputer
{
CM_DISABLE_COPY(cmNinjaLinkLineComputer)
public:
cmNinjaLinkLineComputer(cmOutputConverter* outputConverter,
cmStateDirectory const& stateDir,
cmGlobalNinjaGenerator const* gg);
std::string ConvertToLinkReference(std::string const& input) const
CM_OVERRIDE;
private:
cmGlobalNinjaGenerator const* GG;
};
#endif
| [
"znation@apple.com"
] | znation@apple.com |
6e0608729eb42f97a7318808c07a8e51ccb2cf2e | f73ac48568176e36928985993d23ceade0bbc8d4 | /main.cpp | 8b1199010d8896518b3e2a2497928fdd7919a4a3 | [
"Apache-2.0"
] | permissive | GameHackingAcademy/Wyrmsun_Macrobot | 46c11413c5890bb1e9ef8c5b796a9070018e640a | 2b185943ead7fd8bb32f26d4fb4c4559989d5e88 | refs/heads/master | 2023-08-30T02:40:05.616000 | 2021-11-16T03:41:02 | 2021-11-16T03:41:02 | 398,588,341 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,671 | cpp | /*
A hack for Wyrmsun that will automatically create worker units out of the currently selected structure when a player's gold is over 3000.
It accomplishes this by filling the current unit buffer with worker data and then calling the create unit function in the game.
After injecting this hack, go in game and recruit a worker. Then select a structure as you collect gold.
You will notice workers being queued automatically.
Due to the way Wyrmsun handles recruitment, it is possible to create units out of whatever is selected, including other units.
The technique and offsets used are discussed here: https://gamehacking.academy/lesson/41
*/
#include <Windows.h>
HANDLE wyrmsun_base;
DWORD* base;
DWORD* unitbase;
DWORD recruit_unit_ret_address;
DWORD recruit_unit_call_address;
unsigned char unitdata[0x110];
bool init = false;
DWORD gameloop_ret_address;
DWORD gameloop_call_address;
DWORD *gold_base, *gold;
// The recruit unit codecave hooks the game's recruit unit function
// It's main job is to copy a valid buffer of data for a worker unit
// instead of having to reverse the structure
__declspec(naked) void recruit_unit_codecave() {
__asm {
pushad
mov base, ecx
}
unitbase = (DWORD*)(*base);
memcpy(unitdata, unitbase, 0x110);
init = true;
_asm {
popad
push ecx
mov ecx, esi
call recruit_unit_call_address
jmp recruit_unit_ret_address
}
}
// In the main game loop, our codecave will check the current player's gold
// If it is over 3000, and we have a valid worker buffer, call the recruit unit function
// with worker data.
__declspec(naked) void gameloop_codecave() {
__asm {
pushad
}
gold_base = (DWORD*)((DWORD)wyrmsun_base + 0x0061A504);
gold = (DWORD*)(*gold_base + 0x78);
gold = (DWORD*)(*gold + 4);
gold = (DWORD*)(*gold + 8);
gold = (DWORD*)(*gold + 4);
gold = (DWORD*)(*gold);
gold = (DWORD*)(*gold + 0x14);
if (init && *gold > 3000) {
memcpy(unitbase, unitdata, 0x110);
__asm {
mov ecx, base
push ecx
call recruit_unit_call_address
}
}
__asm {
popad
call gameloop_call_address
jmp gameloop_ret_address
}
}
// When our DLL is attached, unprotect the memory at the code we wish to write at
// Then set the first opcode to E9, or jump
// Caculate the location using the formula: new_location - original_location+5
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) {
DWORD old_protect;
if (fdwReason == DLL_PROCESS_ATTACH) {
// Since Wyrmsun loads code dynamically, we need to calculate offsets based of the base address of the main module
wyrmsun_base = GetModuleHandle(L"wyrmsun.exe");
unsigned char* hook_location = (unsigned char*)((DWORD)wyrmsun_base + 0x223471);
recruit_unit_ret_address = (DWORD)hook_location + 8;
recruit_unit_call_address = (DWORD)wyrmsun_base + 0x2CF7;
VirtualProtect((void*)hook_location, 8, PAGE_EXECUTE_READWRITE, &old_protect);
*hook_location = 0xE9;
*(DWORD*)(hook_location + 1) = (DWORD)&recruit_unit_codecave - ((DWORD)hook_location + 5);
*(hook_location + 5) = 0x90;
*(hook_location + 6) = 0x90;
*(hook_location + 7) = 0x90;
hook_location = (unsigned char*)((DWORD)wyrmsun_base + 0x385D34);
gameloop_ret_address = (DWORD)hook_location + 5;
gameloop_call_address = (DWORD)wyrmsun_base + 0xDBCA;
VirtualProtect((void*)hook_location, 5, PAGE_EXECUTE_READWRITE, &old_protect);
*hook_location = 0xE9;
*(DWORD*)(hook_location + 1) = (DWORD)&gameloop_codecave - ((DWORD)hook_location + 5);
}
return true;
}
| [
"noreply@github.com"
] | noreply@github.com |
2a6a92f5a695f46331cc801b26fe1a5140a52680 | a40526018769ef99523d37229d8c813d41867f48 | /1041.cpp | e463ecb6432e2591eaf4daea0b2b50983b750292 | [] | no_license | npkhanhh/shopee | 9d992e70081a997698179f2bcee9da8aa21b9176 | 1ff2730a0559b5771baca9bdbc432d37f3393437 | refs/heads/master | 2023-03-04T13:21:19.810110 | 2021-02-18T13:19:25 | 2021-02-18T13:19:25 | 333,385,865 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,315 | cpp | #include <iostream>
#include <vector>
#include <assert.h>
#include <string>
#include <map>
using namespace std;
class Solution {
public:
bool isRobotBounded(string instructions) {
int count_g=0, count_l=0, count_r = 0;
int x=0, y=0;
int face = 0;
for (int i = 0; i<instructions.length(); ++i) {
if (instructions[i] == 'G') {
count_g += 1;
if (face == 0) {
y += 1;
} else if (face == 1) {
x += 1;
} else if (face == 2) {
y -= 1;
} else {
x -= 1;
}
} else if (instructions[i] == 'L') {
count_l += 1;
face -= 1;
if (face < 0) {
face += 4;
}
} else {
count_r += 1;
face += 1;
face = face % 4;
}
}
if (x==0 &&y==0 && face==0){
return true;
}
if (abs(count_l - count_r) % 4 == 0 && count_g > 0) {
return false;
}
return true;
}
};
int main() {
Solution s;
bool b;
cout << b << endl;
int a;
cout << a << endl;
return 0;
}
| [
"npkhanh93@gmail.com"
] | npkhanh93@gmail.com |
77c49d9fea50ceb9fd8456c4c313f2bda11031dd | d71147e42d2ca53d0137b6f113661d57d452256a | /uicontroller.h | 9bc15912a868efa90893d1495956270001166adc | [] | no_license | Kuttuna/QML-C- | 9190b54b2b306be1ff3c06cf9cdcb1db82aa048e | 5f27588be83c4ac8c35de97723e7f396446e0cc7 | refs/heads/master | 2020-04-13T13:26:46.047795 | 2018-12-27T01:10:15 | 2018-12-27T01:10:15 | 163,230,749 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 318 | h | #ifndef UICONTROLLER_H
#define UICONTROLLER_H
#include <QObject>
class UiController : public QObject
{
Q_OBJECT
public:
explicit UiController(QObject *parent = nullptr);
Q_INVOKABLE int increase(int value);
Q_INVOKABLE int decrease(int value);
signals:
public slots:
};
#endif // UICONTROLLER_H
| [
"serttunahan@hotmail.com"
] | serttunahan@hotmail.com |
1f5a9020490fd3a474067f530b38a9e4bc6cbdf9 | 7c187350a4f6ecac9651fa0bb41ce75ef683b308 | /AEngine/src/Graphics/Shader.cpp | bee3abaffa6502b13edea66fdb4654786d33009c | [
"Unlicense"
] | permissive | Garciaj007/AEngine | 263040f5bf9bf0a78cf9e08d4e09e7e7bf177e4a | 1a64fc116efab3864b7c535bc8bd03e8aab4bb61 | refs/heads/master | 2020-07-21T14:01:56.884163 | 2020-02-18T05:30:39 | 2020-02-18T05:30:39 | 206,889,293 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 2,512 | cpp | #include <Core/AEpch.h>
#include "Core/Utils.h"
#include "Core/Logger.h"
#include "ShaderHandler.h"
std::unique_ptr<ShaderHandler> ShaderHandler::instance(nullptr);
std::map<const char*, GLuint> ShaderHandler::programs = std::map<const char*, GLuint>();
ShaderHandler* ShaderHandler::GetInstance() {
if (!instance) instance = std::unique_ptr<ShaderHandler>(new ShaderHandler());
return instance.get();
}
ShaderHandler::~ShaderHandler()
{
//if (!programs.empty()){
// for (const auto& entry : programs) glDeleteProgram(entry.second);
// programs.clear();
//}
}
GLuint ShaderHandler::GetShaderProgram(const char* shaderName)
{
if (programs.find(shaderName) != programs.end()) {
return programs.at(shaderName);
}
return 0;
}
void ShaderHandler::CreateProgram(const char* shaderName, const char* vertFilePath, const char* fragFilePath)
{
auto vShaderCode = Utils::ReadTextFile(vertFilePath);
auto fShaderCode = Utils::ReadTextFile(fragFilePath);
const auto vertShaderId = CreateShader(GL_VERTEX_SHADER, vShaderCode, shaderName);
const auto fragShaderId = CreateShader(GL_FRAGMENT_SHADER, fShaderCode, shaderName);
GLint linkResult;
const auto programId = glCreateProgram();
glAttachShader(programId, vertShaderId);
glAttachShader(programId, fragShaderId);
glLinkProgram(programId);
glGetProgramiv(programId, GL_LINK_STATUS, &linkResult);
if (!linkResult)
{
char log[512];
glGetProgramInfoLog(programId, 512, nullptr, &log[0]);
LOG_ERROR("Error linking ShaderHandler Program: " + std::string(shaderName) + ". Error: \n" + log, __FILE__, __LINE__);
}
programs.emplace(std::make_pair(shaderName, programId));
glDeleteShader(vertShaderId);
glDeleteShader(fragShaderId);
}
GLuint ShaderHandler::CreateShader(const GLenum shaderType, std::string& shaderSource, const char* shaderName)
{
auto compileResult = 0;
const auto shader = glCreateShader(shaderType);
const auto shaderCode = shaderSource.c_str();
glShaderSource(shader, 1, &shaderCode, nullptr);
glCompileShader(shader);
glGetShaderiv(shader, GL_COMPILE_STATUS, &compileResult);
if (!compileResult)
{
auto logLength = 0;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &logLength);
std::vector<char> shaderLog(logLength);
glGetShaderInfoLog(shader, logLength, nullptr, &shaderLog[0]);
const std::string logString(shaderLog.begin(), shaderLog.end());
LOG_ERROR("Error compiling shader " + std::string(shaderName) + ". Error: \n" + logString, __FILE__, __LINE__);
return 0;
}
return shader;
}
| [
"jurielgarcia2010@gmail.com"
] | jurielgarcia2010@gmail.com |
fe518cb38f0a68439ac8888fe9eaa70d924c38ef | c02e6a950d0bf2ee8c875c70ad707df8b074bb8e | /build/Android/Preview/bimcast/app/src/main/include/Fuse.Drawing.Polygon.h | 3c4523e8ffa2c2d0abcd64d81b73aa1eec6b7175 | [] | no_license | BIMCast/bimcast-landing-ui | 38c51ad5f997348f8c97051386552509ff4e3faf | a9c7ff963d32d625dfb0237a8a5d1933c7009516 | refs/heads/master | 2021-05-03T10:51:50.705052 | 2016-10-04T12:18:22 | 2016-10-04T12:18:22 | 69,959,209 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,420 | h | // This file was generated based on C:\ProgramData\Uno\Packages\Fuse.Drawing.Polygons\0.35.12\$.uno.
// WARNING: Changes might be lost if you edit this file directly.
#pragma once
#include <Uno.Object.h>
namespace g{namespace Fuse{namespace Drawing{namespace Tesselation{struct Face;}}}}
namespace g{namespace Fuse{namespace Drawing{struct Cache;}}}
namespace g{namespace Fuse{namespace Drawing{struct Contour;}}}
namespace g{namespace Fuse{namespace Drawing{struct Polygon;}}}
namespace g{namespace Fuse{namespace Drawing{struct PolygonDrawable;}}}
namespace g{namespace Uno{namespace Content{namespace Models{struct ModelMesh;}}}}
namespace g{namespace Uno{namespace Geometry{struct Triangle2D;}}}
namespace g{namespace Uno{struct Float2;}}
namespace g{
namespace Fuse{
namespace Drawing{
// public partial sealed class Polygon :161
// {
uType* Polygon_typeof();
void Polygon__ctor__fn(Polygon* __this, uArray* contours);
void Polygon__ctor_1_fn(Polygon* __this, uObject* contours);
void Polygon__ctor_2_fn(Polygon* __this, uDelegate* windingRule, uArray* contours);
void Polygon__ctor_3_fn(Polygon* __this, uDelegate* windingRule, uObject* contours);
void Polygon__get_Contours_fn(Polygon* __this, uObject** __retval);
void Polygon__CreateTriangle_fn(Polygon* __this, ::g::Fuse::Drawing::Tesselation::Face* face, ::g::Uno::Geometry::Triangle2D** __retval);
void Polygon__Extrude_fn(Polygon* __this, float* depth, float* smoothingThreshold, ::g::Uno::Content::Models::ModelMesh** __retval);
void Polygon__GetBoundaryContours_fn(Polygon* __this, uObject** __retval);
void Polygon__GetFillTriangles_fn(Polygon* __this, uObject** __retval);
void Polygon__GetTriangleVertices_fn(Polygon* __this, uArray** __retval);
void Polygon__get_IsDegenerate_fn(Polygon* __this, bool* __retval);
void Polygon__New1_fn(uArray* contours, Polygon** __retval);
void Polygon__New2_fn(uObject* contours, Polygon** __retval);
void Polygon__New3_fn(uDelegate* windingRule, uArray* contours, Polygon** __retval);
void Polygon__New4_fn(uDelegate* windingRule, uObject* contours, Polygon** __retval);
void Polygon__Stroke_fn(Polygon* __this, float* Width, float* Offset, int* StartCap, int* EndCap, Polygon** __retval);
void Polygon__Triangulate_fn(Polygon* __this, uObject** __retval);
void Polygon__get_WindingRule_fn(Polygon* __this, uDelegate** __retval);
struct Polygon : uObject
{
uStrong<uArray*> _boundaryContours;
uStrong< ::g::Fuse::Drawing::Cache*> _contours;
uStrong<uDelegate*> _windingRule;
void ctor_(uArray* contours);
void ctor_1(uObject* contours);
void ctor_2(uDelegate* windingRule, uArray* contours);
void ctor_3(uDelegate* windingRule, uObject* contours);
uObject* Contours();
::g::Uno::Geometry::Triangle2D* CreateTriangle(::g::Fuse::Drawing::Tesselation::Face* face);
::g::Uno::Content::Models::ModelMesh* Extrude(float depth, float smoothingThreshold);
uObject* GetBoundaryContours();
uObject* GetFillTriangles();
uArray* GetTriangleVertices();
bool IsDegenerate();
Polygon* Stroke(float Width, float Offset, int StartCap, int EndCap);
uObject* Triangulate();
uDelegate* WindingRule();
static Polygon* New1(uArray* contours);
static Polygon* New2(uObject* contours);
static Polygon* New3(uDelegate* windingRule, uArray* contours);
static Polygon* New4(uDelegate* windingRule, uObject* contours);
};
// }
}}} // ::g::Fuse::Drawing
| [
"mabu@itechhub.co.za"
] | mabu@itechhub.co.za |
ba910a0d9e614e557192ea2bb53762a50d786a89 | 8d16b45007096e0342c7e43a4155b5d6dc916b62 | /Algorithm/61-120/112_Path_Sum.cpp | 5aaefea7df0d66a8e2c38a0b9c2ac512d0f32f16 | [] | no_license | FuzeT/LeetCode | f39b4830f76071b70129953353750de6870f0676 | 32d7876f4a182a8f279fe7d8e55a2560c808c399 | refs/heads/master | 2021-01-18T01:27:05.925990 | 2015-08-28T02:56:15 | 2015-08-28T02:56:15 | 33,971,620 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 897 | cpp | #include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <algorithm>
#include <map>
#include <stack>
#include <queue>
#include <unordered_map>
#include <set>
#include <math.h>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
struct ReturnPair{
int depth;
bool balance;
ReturnPair(int x) : depth(x), balance(true){}
ReturnPair(bool f) : depth(0), balance(f){};
};
class Solution {
public:
bool hasPathSum(TreeNode* root, long long sum) {
if (root == NULL) return false;
if (root->left == NULL && root->right == NULL && root->val == sum) return true;
long long new_sum = sum - root->val;
return(hasPathSum(root->left, new_sum) || hasPathSum(root->right, new_sum));
}
}; | [
"tcf8661@hotmail.com"
] | tcf8661@hotmail.com |
85d5281cdce4b099fd99611764c22aedda65bb15 | ffd583a7ae88ba510e02f8f5141506ec6d2071fd | /src/logging.h | 4fa9adf43992d4a43dd38b80651f5370c7bab8dc | [
"MIT"
] | permissive | Coleganet/Clearcore-Project | 37f90a797c8098c76f538f30125ce797fba9ebba | e1878cdff32ad14509c0950edf4cd428883e966b | refs/heads/master | 2023-03-31T15:11:33.061970 | 2021-04-06T00:16:21 | 2021-04-06T00:16:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,880 | h | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2018 The Bitcoin developers
// Copyright (c) 2015-2020 The PIVX developers
// Copyright (c) 2020 The CLEARCOIN developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
/**
* Server/client environment: argument handling, config file parsing,
* logging, thread wrappers
*/
#ifndef BITCOIN_LOGGING_H
#define BITCOIN_LOGGING_H
#include "fs.h"
#include "tinyformat.h"
#include <atomic>
#include <cstdint>
#include <list>
#include <mutex>
#include <vector>
static const bool DEFAULT_LOGTIMEMICROS = false;
static const bool DEFAULT_LOGIPS = false;
static const bool DEFAULT_LOGTIMESTAMPS = true;
extern const char * const DEFAULT_DEBUGLOGFILE;
extern bool fLogIPs;
struct CLogCategoryActive
{
std::string category;
bool active;
};
namespace BCLog {
enum LogFlags : uint32_t {
NONE = 0,
NET = (1 << 0),
TOR = (1 << 1),
MEMPOOL = (1 << 2),
HTTP = (1 << 3),
BENCH = (1 << 4),
ZMQ = (1 << 5),
DB = (1 << 6),
RPC = (1 << 7),
ESTIMATEFEE = (1 << 8),
ADDRMAN = (1 << 9),
SELECTCOINS = (1 << 10),
REINDEX = (1 << 11),
CMPCTBLOCK = (1 << 12),
RAND = (1 << 13),
PRUNE = (1 << 14),
PROXY = (1 << 15),
MEMPOOLREJ = (1 << 16),
LIBEVENT = (1 << 17),
COINDB = (1 << 18),
QT = (1 << 19),
LEVELDB = (1 << 20),
STAKING = (1 << 21),
MASTERNODE = (1 << 22),
MNBUDGET = (1 << 23),
MNPING = (1 << 24),
LEGACYZC = (1 << 25),
ALL = ~(uint32_t)0,
};
class Logger
{
private:
FILE* m_fileout = nullptr;
std::mutex m_file_mutex;
std::list<std::string> m_msgs_before_open;
/**
* m_started_new_line is a state variable that will suppress printing of
* the timestamp when multiple calls are made that don't end in a
* newline.
*/
std::atomic_bool m_started_new_line{true};
/** Log categories bitfield. */
std::atomic<uint32_t> m_categories{0};
std::string LogTimestampStr(const std::string& str);
public:
bool m_print_to_console = false;
bool m_print_to_file = false;
bool m_log_timestamps = DEFAULT_LOGTIMESTAMPS;
bool m_log_time_micros = DEFAULT_LOGTIMEMICROS;
fs::path m_file_path;
std::atomic<bool> m_reopen_file{false};
/** Send a string to the log output */
int LogPrintStr(const std::string &str);
/** Returns whether logs will be written to any output */
bool Enabled() const { return m_print_to_console || m_print_to_file; }
bool OpenDebugLog();
void ShrinkDebugFile();
uint32_t GetCategoryMask() const { return m_categories.load(); }
void EnableCategory(LogFlags flag);
bool EnableCategory(const std::string& str);
void DisableCategory(LogFlags flag);
bool DisableCategory(const std::string& str);
bool WillLogCategory(LogFlags category) const;
bool DefaultShrinkDebugFile() const;
};
} // namespace BCLog
extern BCLog::Logger* const g_logger;
/** Return true if log accepts specified category */
static inline bool LogAcceptCategory(BCLog::LogFlags category)
{
return g_logger->WillLogCategory(category);
}
/** Returns a string with the supported log categories */
std::string ListLogCategories();
/** Returns a vector of the active log categories. */
std::vector<CLogCategoryActive> ListActiveLogCategories();
/** Return true if str parses as a log category and set the flag */
bool GetLogCategory(BCLog::LogFlags& flag, const std::string& str);
/** Get format string from VA_ARGS for error reporting */
template<typename... Args> std::string FormatStringFromLogArgs(const char *fmt, const Args&... args) { return fmt; }
// Be conservative when using LogPrintf/error or other things which
// unconditionally log to debug.log! It should not be the case that an inbound
// peer can fill up a user's disk with debug.log entries.
#define LogPrintf(...) do { \
if(g_logger->Enabled()) { \
std::string _log_msg_; /* Unlikely name to avoid shadowing variables */ \
try { \
_log_msg_ = tfm::format(__VA_ARGS__); \
} catch (tinyformat::format_error &e) { \
/* Original format string will have newline so don't add one here */ \
_log_msg_ = "Error \"" + std::string(e.what()) + \
"\" while formatting log message: " + \
FormatStringFromLogArgs(__VA_ARGS__); \
} \
g_logger->LogPrintStr(_log_msg_); \
} \
} while(0)
#define LogPrint(category, ...) do { \
if (LogAcceptCategory((category))) { \
LogPrintf(__VA_ARGS__); \
} \
} while(0)
#endif // BITCOIN_LOGGING_H
| [
"noreply@github.com"
] | noreply@github.com |
2f09bae44e051f380e50b7be219471ebdca21d9c | ca7a34691d1a933c893836289395edc34dbb30cb | /backend-microservices/presenceservice/src/main.cpp | cc4db2687daec8d51ff515d86a125ecaf01d1232 | [] | no_license | bhameyie/special-bassoon | f1b40da1e4b1ec9bedb78a8b40ff21e3c323e848 | 62482d381d665443764c60f972691593df4cbcf7 | refs/heads/main | 2023-03-20T22:55:46.629887 | 2021-03-10T13:41:59 | 2021-03-10T13:41:59 | 327,182,651 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 229 | cpp | #include "service_runner.cpp"
#include "presence_recorder_service.cpp"
int main() {
//UpdateUserConnectionRequest req;
ServiceRunner runner("0.0.0.0:50051");
auto server = runner.Run();
server->Wait();
return 0;
}
| [
"muzzled.coder@gmail.com"
] | muzzled.coder@gmail.com |
88b85e9e4089b0ff6dbdf39701aa93fa3678a3b2 | afd207e6e47887067e04d2aa2f903fbfbaf39d18 | /CellGraph.h | c42ea52100672cd6a9f0f46d8f86d58e28b01cc9 | [] | no_license | algo-88team/Hidato | f87e988d536ae7c9759fa54f81d9efd5aafa13a9 | 6bfe5ea7660434d39c4bf69e75f7c436dbbf73d1 | refs/heads/master | 2020-04-07T16:34:57.838026 | 2018-12-17T13:40:48 | 2018-12-17T13:40:48 | 158,534,481 | 0 | 0 | null | 2018-12-17T10:57:05 | 2018-11-21T10:59:01 | C++ | UTF-8 | C++ | false | false | 1,184 | h | //
// Created by thdtj on 2018-12-10.
//
#ifndef HIDATO_CELLGRAPH_H
#define HIDATO_CELLGRAPH_H
#include <vector>
#include <set>
#include <map>
#include "Puzzle.h"
#include "Cell.h"
class CellGraph {
public:
CellGraph() : width(0), height(0), map(nullptr) {}
CellGraph(const Puzzle &puzzle);
CellGraph(const CellGraph &cg);
virtual ~CellGraph();
Cell **operator[](int i) const;
Cell **operator[](int i);
Cell *operator[](const Point &p) const;
Cell *&operator[](const Point &p);
CellGraph &operator=(const CellGraph &cg);
Cell *getRandCell(int n) const;
Cell *getNextRandCell() const;
int getRemaindersSetSize();
void eraseRemainder(int n, Cell *pCell);
void eraseRemainders(int n);
void eraseCell(Cell *pCell);
void checkNeighbor(const Cell &c);
bool checkMapping();
bool is_candidatesEmpty();
bool is_remaindersEmpty();
bool is_finished();
Cell *find_onlyCandidate();
Cell *find_onlyRemainder();
private:
int width;
int height;
Cell ***map;
std::vector<Cell *> cells;
std::map<int, std::set<Cell *>> remaindersSet;
};
#endif //HIDATO_CELLGRAPH_H
| [
"thdtjddb@naver.com"
] | thdtjddb@naver.com |
b030ed446e314313f0eb9d367749b404f0633662 | 6935e02bb7a75778cc01cd07fc18b32d46aea177 | /ConcurrencyRuntime/parallel_for.cpp | 63246a80ffc8b3fa49e65fd94b9f6c038b8848c6 | [] | no_license | turingcompl33t/windows-internals | 6bc207faf70cf614985e97c5e2660fe3028a9654 | eba1bc5401b7b57b58d1a966e7dbc633b8e3f87c | refs/heads/master | 2022-12-03T20:20:43.730808 | 2020-08-18T17:28:04 | 2020-08-18T17:28:04 | 217,789,884 | 57 | 19 | null | null | null | null | UTF-8 | C++ | false | false | 400 | cpp | // parallel_for.cpp
// Demonstration of PPL parallel_for algorithm.
#include <windows.h>
#include <ppl.h>
#include <cstdio>
#include <vector>
using namespace concurrency;
int wmain()
{
for (int i = 0; i < 10; ++i)
{
printf("%d ", i);
}
printf("\n");
// rewritten version of the above, except executed in parallel
concurrency::parallel_for(0, 10, [](int i)
{
printf("%d ", i);
});
} | [
"kdotterrer@gmail.com"
] | kdotterrer@gmail.com |
40098e3ebdef081d08975f1ea36195863514cd2a | bb35a689812fc097e5ca6ca6d00509d1a664efb7 | /DeepMimicCore/sim/SimCharBuilder.h | 51287174343ec11b135e42f2c42ce4f64584b2ab | [
"MIT"
] | permissive | rangsansith/DeepMimic | 9461013c414aac48f1e2e79d1bf19b677af4834e | cc226a2363310683fe8e6753b7fdc75fed1918bd | refs/heads/master | 2020-04-04T15:40:35.425215 | 2018-10-21T15:21:25 | 2018-10-21T15:21:25 | 156,047,284 | 1 | 0 | MIT | 2018-11-04T03:53:36 | 2018-11-04T03:53:36 | null | UTF-8 | C++ | false | false | 341 | h | #pragma once
#include "sim/SimCharacter.h"
class cSimCharBuilder
{
public:
enum eCharType
{
eCharNone,
cCharGeneral,
eCharMax
};
static void CreateCharacter(eCharType char_type, std::shared_ptr<cSimCharacter>& out_char);
static void ParseCharType(const std::string& char_type_str, eCharType& out_char_type);
protected:
};
| [
"jasonpeng142@hotmail.com"
] | jasonpeng142@hotmail.com |
58fce7c65817dc143684b223634fdb108ab51f24 | e6bf17b3e658ae3684a3875f2db79fb7ae04b8b8 | /Infoarena/viteza2.cpp | 5b37bc8cfaef055b95c2035b6b4a64a7ac626639 | [] | no_license | stefdasca/CompetitiveProgramming | 8e16dc50e33b309c8802b99da57b46ee98ae0619 | 0dbabcc5fe75177f61d232d475b99e4dbd751502 | refs/heads/master | 2023-07-26T15:05:30.898850 | 2023-07-09T08:47:52 | 2023-07-09T08:47:52 | 150,778,979 | 37 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 1,003 | cpp | /// #bettercoderthanshebeautiful
#include<bits/stdc++.h>
#define fi first
#define se second
using namespace std;
ifstream f("viteza2.in");
ofstream g("viteza2.out");
int n,m;
struct pr
{
int a,b,c;
};
pr v[5002];
bool cmp(pr a, pr b)
{
return a.a<b.a;
}
int d[1002][1002];
int main()
{
f>>n>>m;
for(int i=1;i<=m;++i)
f>>v[i].b>>v[i].c>>v[i].a;
sort(v+1,v+m+1,cmp);
for(int i=1;i<=n;++i)
for(int j=1;j<=n;++j)
d[i][j]=2e9;
for(int i=1;i<=n;++i)
d[i][i]=0;
for(int i=1;i<=m;i++)
{
int cost=v[i].a,a=v[i].b,b=v[i].c;
for(int k=1;k<=n;k++)
{
d[k][b]=min(d[k][b],d[k][a]+cost);
d[k][a]=min(d[k][a],d[k][b]+cost);
}
}
for(int i=1;i<=n;++i)
{
for(int j=1;j<=n;++j)
if(d[i][j]==2e9)
g<<-1<<" ";
else
g<<d[i][j]<<" ";
g<<'\n';
}
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
2d7fb708f9510d1bdf18b8379855a022da7e2887 | fc88b5b3b79a0aa38b8af735aa0d7323c285e0fc | /light/service.cpp | 242d22b158ae3a4878705a91103b7724992b488c | [] | no_license | Sohamlad7/android_device_motorola_cedric | d345a8c46b526739b98de0ded3deaff1b602a306 | a350d1f506327b2670900d9df8b3be299085e80a | refs/heads/lineage-17.1 | 2021-01-20T02:57:36.732997 | 2019-03-14T13:30:13 | 2020-07-05T06:17:13 | 92,758,063 | 50 | 99 | null | 2020-07-05T06:18:42 | 2017-05-29T16:45:37 | C++ | UTF-8 | C++ | false | false | 1,390 | cpp | /*
* Copyright 2017 The LineageOS Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#define LOG_TAG "android.hardware.light@2.0-service.cedric"
#include <hidl/HidlTransportSupport.h>
#include "Light.h"
using android::hardware::configureRpcThreadpool;
using android::hardware::joinRpcThreadpool;
using android::hardware::light::V2_0::ILight;
using android::hardware::light::V2_0::implementation::Light;
using android::OK;
using android::sp;
using android::status_t;
int main() {
android::sp<ILight> service = new Light();
configureRpcThreadpool(1, true);
status_t status = service->registerAsService();
if (status != OK) {
ALOGE("Cannot register Light HAL service.");
return 1;
}
ALOGI("Light HAL service ready.");
joinRpcThreadpool();
ALOGI("Light HAL service failed to join thread pool.");
return 1;
}
| [
"sohamlad7@gmail.com"
] | sohamlad7@gmail.com |
b6069430bca1ca7b4360f04f9088985b05c26517 | 0359df3b29e30caf5399a4ce77eb70feef8120aa | /tests/unittests/unittests.cpp | e834c13c9e3b296dc447a76d5b8b5ccbfcce415a | [
"BSD-2-Clause"
] | permissive | teragonaudio/readerwriterqueue | 6fa1bd25f03f48ea245b2583f836b5d00ecb9848 | 5a221632234fe6738ccbc95499a05cb998a1bf1d | refs/heads/master | 2021-01-20T23:17:48.300422 | 2015-04-01T00:32:42 | 2015-04-01T00:32:42 | 13,518,309 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,898 | cpp | // ©2013-2015 Cameron Desrochers
// Unit tests for moodycamel::ReaderWriterQueue
#include <cstdio>
#include <cstdio>
#include <cstring>
#include <string>
#include "minitest.h"
#include "../common/simplethread.h"
#include "../../readerwriterqueue.h"
using namespace moodycamel;
// *NOT* thread-safe
struct Foo
{
Foo() : copied(false) { id = _id()++; }
Foo(Foo const& other) : id(other.id), copied(true) { }
~Foo()
{
if (copied) return;
if (id != _last_destroyed_id() + 1) {
_destroyed_in_order() = false;
}
_last_destroyed_id() = id;
++_destroy_count();
}
static void reset() { _destroy_count() = 0; _id() = 0; _destroyed_in_order() = true; _last_destroyed_id() = -1; }
static int destroy_count() { return _destroy_count(); }
static bool destroyed_in_order() { return _destroyed_in_order(); }
private:
static int& _destroy_count() { static int c = 0; return c; }
static int& _id() { static int i = 0; return i; }
static bool& _destroyed_in_order() { static bool d = true; return d; }
static int& _last_destroyed_id() { static int i = -1; return i; }
int id;
bool copied;
};
class ReaderWriterQueueTests : public TestClass<ReaderWriterQueueTests>
{
public:
ReaderWriterQueueTests()
{
REGISTER_TEST(create_empty_queue);
REGISTER_TEST(enqueue_one);
REGISTER_TEST(enqueue_many);
REGISTER_TEST(nonempty_destroy);
REGISTER_TEST(try_enqueue);
REGISTER_TEST(try_dequeue);
REGISTER_TEST(peek);
REGISTER_TEST(pop);
REGISTER_TEST(size_approx);
REGISTER_TEST(threaded);
}
bool create_empty_queue()
{
{
ReaderWriterQueue<int> q;
}
{
ReaderWriterQueue<int> q(1234);
}
return true;
}
bool enqueue_one()
{
int item;
{
item = 0;
ReaderWriterQueue<int> q(1);
q.enqueue(12345);
ASSERT_OR_FAIL(q.try_dequeue(item));
ASSERT_OR_FAIL(item == 12345);
}
{
item = 0;
ReaderWriterQueue<int> q(1);
ASSERT_OR_FAIL(q.try_enqueue(12345));
ASSERT_OR_FAIL(q.try_dequeue(item));
ASSERT_OR_FAIL(item == 12345);
}
return true;
}
bool enqueue_many()
{
int item = -1;
{
ReaderWriterQueue<int> q(100);
for (int i = 0; i != 100; ++i) {
q.enqueue(i);
}
for (int i = 0; i != 100; ++i) {
ASSERT_OR_FAIL(q.try_dequeue(item));
ASSERT_OR_FAIL(item == i);
}
}
{
ReaderWriterQueue<int> q(100);
for (int i = 0; i != 1200; ++i) {
q.enqueue(i);
}
for (int i = 0; i != 1200; ++i) {
ASSERT_OR_FAIL(q.try_dequeue(item));
ASSERT_OR_FAIL(item == i);
}
}
return true;
}
bool nonempty_destroy()
{
Foo item;
// Some elements at beginning
Foo::reset();
{
ReaderWriterQueue<Foo> q(31);
for (int i = 0; i != 10; ++i) {
q.enqueue(Foo());
}
}
ASSERT_OR_FAIL(Foo::destroy_count() == 10);
ASSERT_OR_FAIL(Foo::destroyed_in_order());
// Entire block
Foo::reset();
{
ReaderWriterQueue<Foo> q(31);
for (int i = 0; i != 31; ++i) {
q.enqueue(Foo());
}
}
ASSERT_OR_FAIL(Foo::destroy_count() == 31);
ASSERT_OR_FAIL(Foo::destroyed_in_order());
// Multiple blocks
Foo::reset();
{
ReaderWriterQueue<Foo> q(31);
for (int i = 0; i != 94; ++i) {
q.enqueue(Foo());
}
}
ASSERT_OR_FAIL(Foo::destroy_count() == 94);
ASSERT_OR_FAIL(Foo::destroyed_in_order());
// Some elements in another block
Foo::reset();
{
ReaderWriterQueue<Foo> q(31);
for (int i = 0; i != 42; ++i) {
q.enqueue(Foo());
}
for (int i = 0; i != 31; ++i) {
ASSERT_OR_FAIL(q.try_dequeue(item));
}
}
ASSERT_OR_FAIL(Foo::destroy_count() == 42);
ASSERT_OR_FAIL(Foo::destroyed_in_order());
// Some elements in multiple blocks
Foo::reset();
{
ReaderWriterQueue<Foo> q(31);
for (int i = 0; i != 123; ++i) {
q.enqueue(Foo());
}
for (int i = 0; i != 25; ++i) {
ASSERT_OR_FAIL(q.try_dequeue(item));
}
for (int i = 0; i != 47; ++i) {
q.enqueue(Foo());
}
for (int i = 0; i != 140; ++i) {
ASSERT_OR_FAIL(q.try_dequeue(item));
}
for (int i = 0; i != 230; ++i) {
q.enqueue(Foo());
}
for (int i = 0; i != 130; ++i) {
ASSERT_OR_FAIL(q.try_dequeue(item));
}
for (int i = 0; i != 100; ++i) {
q.enqueue(Foo());
}
}
ASSERT_OR_FAIL(Foo::destroy_count() == 500);
ASSERT_OR_FAIL(Foo::destroyed_in_order());
return true;
}
bool try_enqueue()
{
ReaderWriterQueue<int> q(31);
int item;
int size = 0;
for (int i = 0; i < 10000; ++i) {
if ((rand() & 1) == 1) {
bool result = q.try_enqueue(i);
if (size == 31) {
ASSERT_OR_FAIL(!result);
}
else {
ASSERT_OR_FAIL(result);
++size;
}
}
else {
bool result = q.try_dequeue(item);
if (size == 0) {
ASSERT_OR_FAIL(!result);
}
else {
ASSERT_OR_FAIL(result);
--size;
}
}
}
return true;
}
bool try_dequeue()
{
int item;
{
ReaderWriterQueue<int> q(1);
ASSERT_OR_FAIL(!q.try_dequeue(item));
}
{
ReaderWriterQueue<int, 2> q(10);
ASSERT_OR_FAIL(!q.try_dequeue(item));
}
return true;
}
bool threaded()
{
weak_atomic<int> result;
result = 1;
ReaderWriterQueue<int> q(100);
SimpleThread reader([&]() {
int item;
int prevItem = -1;
for (int i = 0; i != 1000000; ++i) {
if (q.try_dequeue(item)) {
if (item <= prevItem) {
result = 0;
}
prevItem = item;
}
}
});
SimpleThread writer([&]() {
for (int i = 0; i != 1000000; ++i) {
if (((i >> 7) & 1) == 0) {
q.enqueue(i);
}
else {
q.try_enqueue(i);
}
}
});
writer.join();
reader.join();
return result.load() == 1 ? true : false;
}
bool peek()
{
weak_atomic<int> result;
result = 1;
ReaderWriterQueue<int> q(100);
SimpleThread reader([&]() {
int item;
int prevItem = -1;
int* peeked;
for (int i = 0; i != 100000; ++i) {
peeked = q.peek();
if (peeked != nullptr) {
if (q.try_dequeue(item)) {
if (item <= prevItem || item != *peeked) {
result = 0;
}
prevItem = item;
}
else {
result = 0;
}
}
}
});
SimpleThread writer([&]() {
for (int i = 0; i != 100000; ++i) {
if (((i >> 7) & 1) == 0) {
q.enqueue(i);
}
else {
q.try_enqueue(i);
}
}
});
writer.join();
reader.join();
return result.load() == 1 ? true : false;
}
bool pop()
{
weak_atomic<int> result;
result = 1;
ReaderWriterQueue<int> q(100);
SimpleThread reader([&]() {
int item;
int prevItem = -1;
int* peeked;
for (int i = 0; i != 100000; ++i) {
peeked = q.peek();
if (peeked != nullptr) {
item = *peeked;
if (q.pop()) {
if (item <= prevItem) {
result = 0;
}
prevItem = item;
}
else {
result = 0;
}
}
}
});
SimpleThread writer([&]() {
for (int i = 0; i != 100000; ++i) {
if (((i >> 7) & 1) == 0) {
q.enqueue(i);
}
else {
q.try_enqueue(i);
}
}
});
writer.join();
reader.join();
return result.load() == 1 ? true : false;
}
bool size_approx()
{
weak_atomic<int> result;
weak_atomic<int> front;
weak_atomic<int> tail;
result = 1;
front = 0;
tail = 0;
ReaderWriterQueue<int> q(10);
SimpleThread reader([&]() {
int item;
for (int i = 0; i != 100000; ++i) {
if (q.try_dequeue(item)) {
fence(memory_order_release);
front = front.load() + 1;
}
int size = (int)q.size_approx();
fence(memory_order_acquire);
int tail_ = tail.load();
int front_ = front.load();
if (size > tail_ - front_ || size < 0) {
result = 0;
}
}
});
SimpleThread writer([&]() {
for (int i = 0; i != 100000; ++i) {
tail = tail.load() + 1;
fence(memory_order_release);
q.enqueue(i);
int tail_ = tail.load();
int front_ = front.load();
fence(memory_order_acquire);
int size = (int)q.size_approx();
if (size > tail_ - front_ || size < 0) {
result = 0;
}
}
});
writer.join();
reader.join();
return result.load() == 1 ? true : false;
}
};
void printTests(ReaderWriterQueueTests const& tests)
{
std::printf(" Supported tests are:\n");
std::vector<std::string> names;
tests.getAllTestNames(names);
for (auto it = names.cbegin(); it != names.cend(); ++it) {
std::printf(" %s\n", it->c_str());
}
}
// Basic test harness
int main(int argc, char** argv)
{
bool disablePrompt = false;
std::vector<std::string> selectedTests;
// Disable buffering (so that when run in, e.g., Sublime Text, the output appears as it is written)
std::setvbuf(stdout, nullptr, _IONBF, 0);
// Isolate the executable name
std::string progName = argv[0];
auto slash = progName.find_last_of("/\\");
if (slash != std::string::npos) {
progName = progName.substr(slash + 1);
}
ReaderWriterQueueTests tests;
// Parse command line options
if (argc == 1) {
std::printf("Running all unit tests for moodycamel::ReaderWriterQueue.\n(Run %s --help for other options.)\n\n", progName.c_str());
}
else {
bool printHelp = false;
bool printedTests = false;
bool error = false;
for (int i = 1; i < argc; ++i) {
if (std::strcmp(argv[i], "--help") == 0) {
printHelp = true;
}
else if (std::strcmp(argv[i], "--disable-prompt") == 0) {
disablePrompt = true;
}
else if (std::strcmp(argv[i], "--run") == 0) {
if (i + 1 == argc || argv[i + 1][0] == '-') {
std::printf("Expected test name argument for --run option.\n");
if (!printedTests) {
printTests(tests);
printedTests = true;
}
error = true;
continue;
}
if (!tests.validateTestName(argv[++i])) {
std::printf("Unrecognized test '%s'.\n", argv[i]);
if (!printedTests) {
printTests(tests);
printedTests = true;
}
error = true;
continue;
}
selectedTests.push_back(argv[i]);
}
else {
std::printf("Unrecognized option '%s'.\n", argv[i]);
error = true;
}
}
if (error || printHelp) {
if (error) {
std::printf("\n");
}
std::printf("%s\n Description: Runs unit tests for moodycamel::ReaderWriterQueue\n", progName.c_str());
std::printf(" --help Prints this help blurb\n");
std::printf(" --run test Runs only the specified test(s)\n");
std::printf(" --disable-prompt Disables prompt before exit when the tests finish\n");
return error ? -1 : 0;
}
}
int exitCode = 0;
bool result;
if (selectedTests.size() > 0) {
result = tests.run(selectedTests);
}
else {
result = tests.run();
}
if (result) {
std::printf("All %stests passed.\n", (selectedTests.size() > 0 ? "selected " : ""));
}
else {
std::printf("Test(s) failed!\n");
exitCode = 2;
}
if (!disablePrompt) {
std::printf("Press ENTER to exit.\n");
getchar();
}
return exitCode;
}
| [
"cameron@moodycamel.com"
] | cameron@moodycamel.com |
b7f5c9cb84ea315a8a01cc31a4a2b909ad8c7230 | 756a0308bfd15f098270b5621b83caef5683cb28 | /examples/example.cpp | 29b5c340499a3ef4622b544a65cb2a5cd7dbc633 | [
"MIT"
] | permissive | mrnul/GNeural-Nets | a80d53c2448d5deea1a58295d007573bcbd689f3 | 2d9a97121af93e5b540a6d0f52d7eb078955016d | refs/heads/master | 2023-03-19T02:09:43.814528 | 2021-03-13T12:36:43 | 2021-03-13T12:36:43 | 266,313,139 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,640 | cpp | #include <iostream>
#include "GNeuralNetwork.h"
#include "GAGNN.h"
using std::cout;
using std::endl;
using std::cin;
int main()
{
//XOR inputs
const vector<vector<float>> input = { {1,0}, {1,1}, {0,1}, {0,0} };
//{1,0} = True
//{0,1} = False
const vector<vector<float>> output = { {1,0}, {0,1}, {1,0}, {0,1} };
// 2 input nodes, one hidden layer with 2 nodes, 2 output nodes
const vector<int> topology = { 2 , 2 , 2 };
GAGNNParams Params;
Params.MutationCoeff = 0.5f;
Params.MutationProb = 0.2f;
Params.ParentCount = 2;
//Create a population of 50 networks of which 10 are the elites.
//Create 1000 random floats ~N(0, 1.0)
//Run in one worker thread
GAGNN Test(GNeuralNetwork(topology), 50, 10, 1000, 1);
//A variable to store the best network
NetworkWithInfo res;
cout.precision(3);
while (res.Network.Info.Error > 0.01f)
{
Test.CalcNextGeneration(Params, input, output);
res = Test.GetBest();
cout << res.Network.Info.Error << "\t|->\t"\
<< res.Network.Info.Accuracy << "\t" << res.ExInfo.Generation << "\t" << res.Network.Info.NumberOfWeights << "\t"\
<< endl;
// kill some in order to introduce some variance
Test.KillEliteAtRandom(0.1f);
}
cout << "Max weight:" << res.Network.MaxWeightValue() << "\n"\
<< "Min weight:" << res.Network.MinWeightValue() << "\n"\
<< endl;
//For each input print the calculated output
for (int i = 0; i < input.size(); i++)
{
res.Network.Feed(input[i]);
cout << GetOutputString(input[i]) << " --> " << res.Network.GetOutputString() << endl;
}
cout << "Done" << endl;
cin.get();
}
| [
"noreply@github.com"
] | noreply@github.com |
b8d3ee37ad5a6ffeb91e51cafd42f89028f832c9 | db96b049c8e27f723fcb2f3a99291e631f1a1801 | /src/dbapi/driver/public.cpp | cd791e0f5ccb129a5290ae37c8d09013a2a07262 | [] | no_license | Watch-Later/ncbi-cxx-toolkit-public | 1c3a2502b21c7c5cee2c20c39e37861351bd2c05 | 39eede0aea59742ca4d346a6411b709a8566b269 | refs/heads/master | 2023-08-15T14:54:41.973806 | 2021-10-04T04:03:02 | 2021-10-04T04:03:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 32,888 | cpp | /* $Id$
* ===========================================================================
*
* PUBLIC DOMAIN NOTICE
* National Center for Biotechnology Information
*
* This software/database is a "United States Government Work" under the
* terms of the United States Copyright Act. It was written as part of
* the author's official duties as a United States Government employee and
* thus cannot be copyrighted. This software/database is freely available
* to the public for use. The National Library of Medicine and the U.S.
* Government have not placed any restriction on its use or reproduction.
*
* Although all reasonable efforts have been taken to ensure the accuracy
* and reliability of the software and data, the NLM and the U.S.
* Government do not and cannot warrant the performance or results that
* may be obtained by using this software or data. The NLM and the U.S.
* Government disclaim all warranties, express or implied, including
* warranties of performance, merchantability or fitness for any particular
* purpose.
*
* Please cite the author in any work or product based on this material.
*
* ===========================================================================
*
* Author: Vladimir Soussov
*
* File Description: Data Server public interfaces
*
*/
#include <ncbi_pch.hpp>
#include <dbapi/driver/public.hpp>
#include <dbapi/driver/impl/dbapi_impl_result.hpp>
#include <dbapi/driver/impl/dbapi_impl_cmd.hpp>
#include <dbapi/driver/impl/dbapi_impl_connection.hpp>
#include <dbapi/error_codes.hpp>
#ifdef NCBI_OS_MSWIN
# include <winsock2.h>
#elif !defined(NCBI_OS_SOLARIS)
# include <sys/fcntl.h>
# include <sys/types.h>
# include <sys/socket.h>
#endif
#define NCBI_USE_ERRCODE_X Dbapi_DataServer
BEGIN_NCBI_SCOPE
#ifdef _DEBUG
static void s_TraceParams(const CDBParams& params,
const CDiagCompileInfo& info) {
if (dynamic_cast<const impl::CCachedRowInfo*>(¶ms)) {
return;
}
for (unsigned int i = 0, n = params.GetNum(); i < n; ++i) {
const CDB_Object* obj = params.GetValue(i);
const string& name = params.GetName(i);
string value = obj ? obj->GetLogString() : string("(null)");
if (name.empty()) { // insertion, typically bulk
CNcbiDiag(info, eDiag_Trace).GetRef()
<< "Column #" << (i + 1) << " = " << value
<< Endm;
} else {
CNcbiDiag(info, eDiag_Trace).GetRef()
<< "Parameter #" << (i + 1) << " (" << name << ") = " << value
<< Endm;
}
}
}
// Cite caller.
# define TRACE_PARAMS(params) s_TraceParams(params, DIAG_COMPILE_INFO)
#else
# define TRACE_PARAMS(params) ((void)0)
#endif
////////////////////////////////////////////////////////////////////////////
// CDBParamVariant::
//
inline
unsigned int ConvertI2UI(int value)
{
CHECK_DRIVER_ERROR( (value < 0), "Negative parameter's position not allowed.", 200001 );
return static_cast<unsigned int>(value);
}
CDBParamVariant::CDBParamVariant(int pos)
: m_IsPositional(true)
, m_Pos(ConvertI2UI(pos))
{
}
CDBParamVariant::CDBParamVariant(unsigned int pos)
: m_IsPositional(true)
, m_Pos(pos)
{
}
CDBParamVariant::CDBParamVariant(const char* name)
: m_IsPositional(false)
, m_Pos(0)
, m_Name(MakeName(name, m_Format))
{
}
CDBParamVariant::CDBParamVariant(const string& name)
: m_IsPositional(false)
, m_Pos(0)
, m_Name(MakeName(name, m_Format))
{
}
CDBParamVariant::~CDBParamVariant(void)
{
}
// Not finished yet ...
string
CDBParamVariant::GetName(CDBParamVariant::ENameFormat format) const
{
if (format != GetFormat()) {
switch (format) {
case ePlainName:
return MakePlainName(m_Name);
case eQMarkName: // '...WHERE name=?'
return "?";
case eNumericName: // '...WHERE name=:1'
case eNamedName: // '...WHERE name=:name'
return ':' + MakePlainName(m_Name);
case eFormatName: // ANSI C printf format codes, e.g. '...WHERE name=%s'
return '%' + MakePlainName(m_Name);
case eSQLServerName: // '...WHERE name=@name'
return '@' + MakePlainName(m_Name);
}
}
return m_Name;
}
CTempString CDBParamVariant::MakeName(const CTempString& name,
CDBParamVariant::ENameFormat& format)
{
// Do not make copy of name to process it ...
CTempString new_name;
CTempString::const_iterator begin_str = NULL, c = name.data();
format = ePlainName;
for (; c != NULL && c != name.end(); ++c) {
char ch = *c;
if (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r') {
if (begin_str == NULL) {
// Remove whitespace ...
continue;
} else {
// Look forward for non-space characters.
bool space_chars_only = true;
for (const char* tc = c; tc != NULL && *tc != '\0'; ++tc) {
char tch = *tc;
if (tch == ' ' || tch == '\t' || tch == '\n' || tch == '\r') {
continue;
} else {
space_chars_only = false;
break;
}
}
if (space_chars_only) {
// Remove trailing whitespace ...
break;
}
}
}
// Check for leading symbol ...
if (begin_str == NULL) {
begin_str = c;
switch (ch) {
case '?' :
format = eQMarkName;
break;
case ':' :
if (*(c + 1)) {
if (isdigit(*(c + 1))) {
format = eNumericName;
} else {
format = eNamedName;
}
} else {
DATABASE_DRIVER_ERROR("Invalid parameter format: "
+ string(name), 1);
}
break;
case '@' :
format = eSQLServerName;
break;
case '%' :
format = eFormatName;
break;
case '$' :
// !!!!
format = eFormatName;
break;
}
}
}
if (begin_str != NULL) {
new_name.assign(begin_str, c - begin_str);
}
return new_name;
}
string CDBParamVariant::MakePlainName(const CTempString& name)
{
// Do not make copy of name to process it ...
CTempString plain_name;
CTempString::const_iterator begin_str = NULL, c = name.data();
for (; c != NULL && c != name.end(); ++c) {
char ch = *c;
if (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r') {
if (begin_str == NULL) {
// Remove whitespaces ...
continue;
} else {
// Look forward for non-space characters.
bool space_chars_only = true;
for (const char* tc = c; tc != NULL && *tc != '\0'; ++tc) {
char tch = *tc;
if (tch == ' ' || tch == '\t' || tch == '\n' || tch == '\r') {
continue;
} else {
space_chars_only = false;
break;
}
}
if (space_chars_only) {
// Remove trailing whitespace ...
break;
}
}
}
// Check for leading symbol ...
if (begin_str == NULL) {
begin_str = c;
if (ch == ':' || ch == '@' || ch == '$' || ch == '%') {
// Skip leading symbol ...
++begin_str;
}
}
}
if (begin_str != NULL) {
plain_name.assign(begin_str, c - begin_str);
}
return plain_name;
}
////////////////////////////////////////////////////////////////////////////
// CCDB_Connection::
//
CDB_Connection::CDB_Connection(impl::CConnection* c)
: m_ConnImpl(c), m_HasTransaction(false)
{
CHECK_DRIVER_ERROR( !c, "No valid connection provided", 200001 );
m_ConnImpl->AttachTo(this);
m_ConnImpl->SetResultProcessor(0); // to clean up the result processor if any
}
bool CDB_Connection::IsAlive()
{
if (m_ConnImpl == NULL || !m_ConnImpl->IsAlive()) {
return false;
} else {
return x_IsAlive();
}
}
bool CDB_Connection::x_IsAlive()
{
// Try to confirm that the network connection hasn't closed.
// (Done only when no separate network library is necessary.)
// XXX - consider caching GetLowLevelHandle result, or at least
// availability.
#ifndef NCBI_OS_SOLARIS
try {
I_ConnectionExtra::TSockHandle s = m_ConnImpl->GetLowLevelHandle();
char c;
# ifdef NCBI_OS_UNIX
// On Windows, the non-blocking flag is write-only(!); leave it
// alone, since only the ftds driver implements
// GetLowLevelHandle, and FreeTDS normally enables non-blocking
// mode itself. (It does so on Unix too, but explicitly
// restoring settings is still best practice.)
int orig_flags = fcntl(s, F_GETFL, 0);
fcntl(s, F_SETFL, orig_flags | O_NONBLOCK);
# endif
int n = recv(s, &c, 1, MSG_PEEK);
# ifdef NCBI_OS_UNIX
if ((orig_flags & O_NONBLOCK) != O_NONBLOCK) {
fcntl(s, F_SETFL, orig_flags);
}
# endif
if (n > 0) {
return true; // open, with unread data available
} else if (n == 0) {
return false; // closed
} else {
# ifdef NCBI_OS_MSWIN
return WSAGetLastError() == WSAEWOULDBLOCK;
# else
switch (errno) {
case EAGAIN:
# if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN
case EWOULDBLOCK:
# endif
return true; // open, but no data immediately available
default:
return false; // something else is wrong
}
# endif
}
} catch (CDB_Exception&) { // Presumably unimplemented
return true;
}
#endif
return true;
}
#define CHECK_CONNECTION( conn ) \
CHECK_DRIVER_WARNING( !conn, "Connection has been closed", 200002 )
CDB_LangCmd* CDB_Connection::LangCmd(const string& lang_query)
{
CHECK_CONNECTION(m_ConnImpl);
_TRACE("Sending SQL: " << lang_query);
return m_ConnImpl->LangCmd(lang_query);
}
CDB_RPCCmd* CDB_Connection::RPC(const string& rpc_name)
{
CHECK_CONNECTION(m_ConnImpl);
// _TRACE-d in CDB_RPCCmd::Send, which performs the actual I/O.
return m_ConnImpl->RPC(rpc_name);
}
CDB_BCPInCmd* CDB_Connection::BCPIn(const string& table_name)
{
CHECK_CONNECTION(m_ConnImpl);
_TRACE("Performing bulk insertion into " << table_name);
return m_ConnImpl->BCPIn(table_name);
}
CDB_CursorCmd* CDB_Connection::Cursor(const string& cursor_name,
const string& query,
unsigned int batch_size)
{
CHECK_CONNECTION(m_ConnImpl);
_TRACE("Opening cursor for " << query);
return m_ConnImpl->Cursor(cursor_name, query, batch_size);
}
CDB_SendDataCmd* CDB_Connection::SendDataCmd(I_BlobDescriptor& desc,
size_t data_size,
bool log_it,
bool dump_results)
{
CHECK_CONNECTION(m_ConnImpl);
_TRACE("Sending " << data_size << " byte(s) of data");
return m_ConnImpl->SendDataCmd(desc, data_size, log_it, dump_results);
}
bool CDB_Connection::SendData(I_BlobDescriptor& desc, CDB_Stream& lob,
bool log_it)
{
CHECK_CONNECTION(m_ConnImpl);
_TRACE("Sending " << lob.Size() << " byte(s) of data");
return m_ConnImpl->SendData(desc, lob, log_it);
}
void CDB_Connection::SetDatabaseName(const string& name)
{
if (name.empty()) {
return;
}
CHECK_CONNECTION(m_ConnImpl);
_TRACE("Now using database " << name);
m_ConnImpl->SetDatabaseName(name);
}
bool CDB_Connection::Refresh()
{
CHECK_CONNECTION(m_ConnImpl);
return m_ConnImpl->Refresh() && x_IsAlive();
}
const string& CDB_Connection::ServerName() const
{
CHECK_CONNECTION(m_ConnImpl);
return m_ConnImpl->ServerName();
}
Uint4 CDB_Connection::Host() const
{
CHECK_CONNECTION(m_ConnImpl);
return m_ConnImpl->Host();
}
Uint2 CDB_Connection::Port() const
{
CHECK_CONNECTION(m_ConnImpl);
return m_ConnImpl->Port();
}
const string& CDB_Connection::UserName() const
{
CHECK_CONNECTION(m_ConnImpl);
return m_ConnImpl->UserName();
}
const string& CDB_Connection::Password() const
{
CHECK_CONNECTION(m_ConnImpl);
return m_ConnImpl->Password();
}
const string& CDB_Connection::DatabaseName() const
{
CHECK_CONNECTION(m_ConnImpl);
return m_ConnImpl->GetDatabaseName();
}
I_DriverContext::TConnectionMode CDB_Connection::ConnectMode() const
{
CHECK_CONNECTION(m_ConnImpl);
return m_ConnImpl->ConnectMode();
}
bool CDB_Connection::IsReusable() const
{
CHECK_CONNECTION(m_ConnImpl);
return m_ConnImpl->IsReusable();
}
unsigned int CDB_Connection::GetReuseCount() const
{
CHECK_CONNECTION(m_ConnImpl);
return m_ConnImpl->GetReuseCount();
}
const string& CDB_Connection::PoolName() const
{
CHECK_CONNECTION(m_ConnImpl);
return m_ConnImpl->PoolName();
}
I_DriverContext* CDB_Connection::Context() const
{
CHECK_CONNECTION(m_ConnImpl);
return m_ConnImpl->Context();
}
void CDB_Connection::PushMsgHandler(CDB_UserHandler* h,
EOwnership ownership)
{
CHECK_CONNECTION(m_ConnImpl);
m_ConnImpl->PushMsgHandler(h, ownership);
}
void CDB_Connection::PopMsgHandler(CDB_UserHandler* h)
{
CHECK_CONNECTION(m_ConnImpl);
m_ConnImpl->PopMsgHandler(h);
}
CDB_ResultProcessor*
CDB_Connection::SetResultProcessor(CDB_ResultProcessor* rp)
{
return m_ConnImpl? m_ConnImpl->SetResultProcessor(rp) : NULL;
}
CDB_Connection::~CDB_Connection()
{
try {
if ( m_ConnImpl ) {
Close();
}
}
NCBI_CATCH_ALL_X( 2, NCBI_CURRENT_FUNCTION )
}
bool CDB_Connection::Abort()
{
CHECK_CONNECTION(m_ConnImpl);
if (m_ConnImpl->Abort()) {
Close();
return true;
}
return false;
}
bool CDB_Connection::Close(void)
{
CHECK_CONNECTION(m_ConnImpl);
try {
if (m_ConnImpl->IsReusable() && m_ConnImpl->IsAlive() && x_IsAlive()
&& m_ConnImpl->GetServerType() != CDBConnParams::eSybaseOpenServer) {
unique_ptr<CDB_LangCmd> lcmd(LangCmd("IF @@TRANCOUNT > 0 ROLLBACK"));
lcmd->Send();
lcmd->DumpResults();
}
} catch (CDB_Exception&) {
}
m_ConnImpl->Release();
m_ConnImpl = NULL;
return true;
}
void CDB_Connection::SetTimeout(size_t nof_secs)
{
CHECK_CONNECTION(m_ConnImpl);
m_ConnImpl->SetTimeout(nof_secs);
}
void CDB_Connection::SetCancelTimeout(size_t nof_secs)
{
CHECK_CONNECTION(m_ConnImpl);
m_ConnImpl->SetCancelTimeout(nof_secs);
}
size_t CDB_Connection::GetTimeout(void) const
{
CHECK_CONNECTION(m_ConnImpl);
return m_ConnImpl->GetTimeout();
}
size_t CDB_Connection::GetCancelTimeout(void) const
{
CHECK_CONNECTION(m_ConnImpl);
return m_ConnImpl->GetCancelTimeout();
}
I_ConnectionExtra& CDB_Connection::GetExtraFeatures(void)
{
CHECK_CONNECTION(m_ConnImpl);
return *m_ConnImpl;
}
string CDB_Connection::GetDriverName(void) const
{
CHECK_CONNECTION(m_ConnImpl);
return m_ConnImpl->GetDriverName();
}
void CDB_Connection::FinishOpening(void)
{
CHECK_CONNECTION(m_ConnImpl);
m_ConnImpl->FinishOpening();
}
////////////////////////////////////////////////////////////////////////////
// CDB_Result::
//
CDB_Result::CDB_Result(impl::CResult* r) :
m_ResImpl(r)
{
CHECK_DRIVER_ERROR( !m_ResImpl, "No valid result provided", 200004 );
m_ResImpl->AttachTo(this);
}
#define CHECK_RESULT( res ) \
CHECK_DRIVER_WARNING( !res, "This result is not available anymore", 200003 )
EDB_ResType CDB_Result::ResultType() const
{
CHECK_RESULT( GetIResultPtr() );
return GetIResult().ResultType();
}
const CDBParams& CDB_Result::GetDefineParams(void) const
{
CHECK_RESULT( GetIResultPtr() );
return GetIResult().GetDefineParams();
}
unsigned int CDB_Result::NofItems() const
{
CHECK_RESULT( GetIResultPtr() );
return GetIResult().GetDefineParams().GetNum();
}
const char*
CDB_Result::ItemName(unsigned int item_num) const
{
CHECK_RESULT( GetIResultPtr() );
const string& name = GetIResult().GetDefineParams().GetName(item_num);
if (!name.empty()) {
return name.c_str();
}
return NULL;
}
size_t CDB_Result::ItemMaxSize(unsigned int item_num) const
{
CHECK_RESULT( GetIResultPtr() );
return GetIResult().GetDefineParams().GetMaxSize(item_num);
}
EDB_Type CDB_Result::ItemDataType(unsigned int item_num) const
{
CHECK_RESULT( GetIResultPtr() );
return GetIResult().GetDefineParams().GetDataType(item_num);
}
bool CDB_Result::Fetch()
{
// An exception should be thrown from this place. We cannot omit this exception
// because it is expected by ftds driver in CursorResult::Fetch.
CHECK_RESULT( GetIResultPtr() );
// if ( !GetIResultPtr() ) {
// return false;
// }
return GetIResult().Fetch();
}
int CDB_Result::CurrentItemNo() const
{
CHECK_RESULT( GetIResultPtr() );
return GetIResult().CurrentItemNo();
}
int CDB_Result::GetColumnNum(void) const
{
CHECK_RESULT( GetIResultPtr() );
return GetIResult().GetColumnNum();
}
CDB_Object* CDB_Result::GetItem(CDB_Object* item_buf, EGetItem policy)
{
CHECK_RESULT( GetIResultPtr() );
return GetIResult().GetItem(item_buf, policy);
}
size_t CDB_Result::ReadItem(void* buffer, size_t buffer_size, bool* is_null)
{
CHECK_RESULT( GetIResultPtr() );
return GetIResult().ReadItem(buffer, buffer_size, is_null);
}
I_BlobDescriptor* CDB_Result::GetBlobDescriptor()
{
CHECK_RESULT( GetIResultPtr() );
return GetIResult().GetBlobDescriptor();
}
bool CDB_Result::SkipItem()
{
CHECK_RESULT( GetIResultPtr() );
return GetIResult().SkipItem();
}
CDB_Result::~CDB_Result()
{
try {
if ( GetIResultPtr() ) {
GetIResult().Release();
}
}
NCBI_CATCH_ALL_X( 3, NCBI_CURRENT_FUNCTION )
}
////////////////////////////////////////////////////////////////////////////
// CDB_LangCmd::
//
CDB_LangCmd::CDB_LangCmd(impl::CBaseCmd* c)
{
CHECK_DRIVER_ERROR( !c, "No valid command provided", 200004 );
m_CmdImpl = c;
m_CmdImpl->AttachTo(this);
}
#define CHECK_COMMAND( cmd ) \
CHECK_DRIVER_WARNING( !cmd, "This command cannot be used anymore", 200005 )
bool CDB_LangCmd::More(const string& query_text)
{
CHECK_COMMAND( m_CmdImpl );
return m_CmdImpl->More(query_text);
}
CDBParams& CDB_LangCmd::GetBindParams(void)
{
CHECK_COMMAND( m_CmdImpl );
return m_CmdImpl->GetBindParams();
}
CDBParams& CDB_LangCmd::GetDefineParams(void)
{
CHECK_COMMAND( m_CmdImpl );
return m_CmdImpl->GetDefineParams();
}
bool CDB_LangCmd::Send()
{
CHECK_COMMAND( m_CmdImpl );
TRACE_PARAMS(m_CmdImpl->GetBindParams());
m_CmdImpl->SaveInParams();
return m_CmdImpl->Send();
}
bool CDB_LangCmd::WasSent() const
{
CHECK_COMMAND( m_CmdImpl );
return m_CmdImpl->WasSent();
}
bool CDB_LangCmd::Cancel()
{
CHECK_COMMAND( m_CmdImpl );
return m_CmdImpl->Cancel();
}
bool CDB_LangCmd::WasCanceled() const
{
CHECK_COMMAND( m_CmdImpl );
return m_CmdImpl->WasCanceled();
}
CDB_Result* CDB_LangCmd::Result()
{
CHECK_COMMAND( m_CmdImpl );
return m_CmdImpl->Result();
}
bool CDB_LangCmd::HasMoreResults() const
{
CHECK_COMMAND( m_CmdImpl );
return m_CmdImpl->HasMoreResults();
}
bool CDB_LangCmd::HasFailed() const
{
CHECK_COMMAND( m_CmdImpl );
return m_CmdImpl->HasFailed();
}
int CDB_LangCmd::RowCount() const
{
CHECK_COMMAND( m_CmdImpl );
return m_CmdImpl->RowCount();
}
void CDB_LangCmd::DumpResults()
{
CHECK_COMMAND( m_CmdImpl );
m_CmdImpl->DumpResults();
}
CDB_LangCmd::~CDB_LangCmd()
{
try {
if ( m_CmdImpl ) {
m_CmdImpl->Release();
}
}
NCBI_CATCH_ALL_X( 4, NCBI_CURRENT_FUNCTION )
}
/////////////////////////////////////////////////////////////////////////////
// CDB_RPCCmd::
//
CDB_RPCCmd::CDB_RPCCmd(impl::CBaseCmd* c)
{
CHECK_DRIVER_ERROR( !c, "No valid command provided", 200006 );
m_CmdImpl = c;
m_CmdImpl->AttachTo(this);
}
CDBParams& CDB_RPCCmd::GetBindParams(void)
{
CHECK_COMMAND( m_CmdImpl );
return m_CmdImpl->GetBindParams();
}
CDBParams& CDB_RPCCmd::GetDefineParams(void)
{
CHECK_COMMAND( m_CmdImpl );
return m_CmdImpl->GetDefineParams();
}
bool CDB_RPCCmd::Send()
{
CHECK_COMMAND( m_CmdImpl );
_TRACE("Calling remote procedure " << GetProcName());
TRACE_PARAMS(m_CmdImpl->GetBindParams());
m_CmdImpl->SaveInParams();
return m_CmdImpl->Send();
}
bool CDB_RPCCmd::WasSent() const
{
CHECK_COMMAND( m_CmdImpl );
return m_CmdImpl->WasSent();
}
bool CDB_RPCCmd::Cancel()
{
CHECK_COMMAND( m_CmdImpl );
return m_CmdImpl->Cancel();
}
bool CDB_RPCCmd::WasCanceled() const
{
CHECK_COMMAND( m_CmdImpl );
return m_CmdImpl->WasCanceled();
}
CDB_Result* CDB_RPCCmd::Result()
{
CHECK_COMMAND( m_CmdImpl );
return m_CmdImpl->Result();
}
bool CDB_RPCCmd::HasMoreResults() const
{
CHECK_COMMAND( m_CmdImpl );
return m_CmdImpl->HasMoreResults();
}
bool CDB_RPCCmd::HasFailed() const
{
CHECK_COMMAND( m_CmdImpl );
return m_CmdImpl->HasFailed();
}
int CDB_RPCCmd::RowCount() const
{
CHECK_COMMAND( m_CmdImpl );
return m_CmdImpl->RowCount();
}
void CDB_RPCCmd::DumpResults()
{
CHECK_COMMAND( m_CmdImpl );
m_CmdImpl->DumpResults();
}
void CDB_RPCCmd::SetRecompile(bool recompile)
{
CHECK_COMMAND( m_CmdImpl );
m_CmdImpl->SetRecompile(recompile);
}
const string& CDB_RPCCmd::GetProcName(void) const
{
CHECK_COMMAND( m_CmdImpl );
return m_CmdImpl->GetQuery();
}
CDB_RPCCmd::~CDB_RPCCmd()
{
try {
if ( m_CmdImpl ) {
m_CmdImpl->Release();
}
}
NCBI_CATCH_ALL_X( 5, NCBI_CURRENT_FUNCTION )
}
////////////////////////////////////////////////////////////////////////////
// CDB_BCPInCmd::
//
CDB_BCPInCmd::CDB_BCPInCmd(impl::CBaseCmd* c)
{
CHECK_DRIVER_ERROR( !c, "No valid command provided", 200007 );
m_CmdImpl = c;
m_CmdImpl->AttachTo(this);
}
void CDB_BCPInCmd::SetHints(CTempString hints)
{
CHECK_COMMAND( m_CmdImpl );
m_CmdImpl->SetHints(hints);
}
void CDB_BCPInCmd::AddHint(EBCP_Hints hint, unsigned int value /* = 0 */)
{
CHECK_COMMAND( m_CmdImpl );
m_CmdImpl->AddHint(hint, value);
}
void CDB_BCPInCmd::AddOrderHint(CTempString columns)
{
CHECK_COMMAND( m_CmdImpl );
m_CmdImpl->AddOrderHint(columns);
}
CDBParams& CDB_BCPInCmd::GetBindParams(void)
{
CHECK_COMMAND( m_CmdImpl );
return m_CmdImpl->GetBindParams();
}
bool CDB_BCPInCmd::Bind(unsigned int column_num, CDB_Object* value)
{
GetBindParams().Bind(column_num, value);
return true;
}
bool CDB_BCPInCmd::SendRow()
{
CHECK_COMMAND( m_CmdImpl );
if (m_CmdImpl->m_RowsSent++ == 0) {
TRACE_PARAMS(m_CmdImpl->GetBindParams());
} else if (m_CmdImpl->m_AtStartOfBatch) {
m_CmdImpl->m_RowsSentAtBatchStart = m_CmdImpl->m_RowsSent - 1;
}
m_CmdImpl->m_AtStartOfBatch = false;
m_CmdImpl->SaveInParams();
return m_CmdImpl->Send();
}
bool CDB_BCPInCmd::Cancel()
{
CHECK_COMMAND( m_CmdImpl );
return m_CmdImpl->Cancel();
}
bool CDB_BCPInCmd::CompleteBatch()
{
CHECK_COMMAND( m_CmdImpl );
if (m_CmdImpl->m_BatchesSent++ == 0 && m_CmdImpl->m_RowsSent > 1) {
_TRACE("Sent a batch of " << m_CmdImpl->GetRowsInCurrentBatch()
<< " rows");
}
m_CmdImpl->m_AtStartOfBatch = true;
return m_CmdImpl->CommitBCPTrans();
}
bool CDB_BCPInCmd::CompleteBCP()
{
CHECK_COMMAND( m_CmdImpl );
if (m_CmdImpl->m_BatchesSent > 1) {
_TRACE("Sent " << m_CmdImpl->m_RowsSent << " rows, in "
<< m_CmdImpl->m_BatchesSent << " batches");
}
return m_CmdImpl->EndBCP();
}
CDB_BCPInCmd::~CDB_BCPInCmd()
{
try {
if ( m_CmdImpl ) {
m_CmdImpl->Release();
}
}
NCBI_CATCH_ALL_X( 6, NCBI_CURRENT_FUNCTION )
}
/////////////////////////////////////////////////////////////////////////////
// CDB_CursorCmd::
//
CDB_CursorCmd::CDB_CursorCmd(impl::CBaseCmd* c)
{
CHECK_DRIVER_ERROR( !c, "No valid command provided", 200006 );
m_CmdImpl = c;
m_CmdImpl->AttachTo(this);
}
CDBParams& CDB_CursorCmd::GetBindParams(void)
{
CHECK_COMMAND( m_CmdImpl );
return m_CmdImpl->GetBindParams();
}
CDBParams& CDB_CursorCmd::GetDefineParams(void)
{
CHECK_COMMAND( m_CmdImpl );
return m_CmdImpl->GetDefineParams();
}
CDB_Result* CDB_CursorCmd::Open()
{
CHECK_COMMAND( m_CmdImpl );
TRACE_PARAMS(m_CmdImpl->GetBindParams());
return m_CmdImpl->OpenCursor();
}
bool CDB_CursorCmd::Update(const string& table_name, const string& upd_query)
{
CHECK_COMMAND( m_CmdImpl );
m_CmdImpl->SaveInParams();
return m_CmdImpl->Update(table_name, upd_query);
}
bool CDB_CursorCmd::UpdateBlob(unsigned int item_num, CDB_Stream& data,
bool log_it)
{
CHECK_COMMAND( m_CmdImpl );
return m_CmdImpl->UpdateBlob(item_num, data, log_it);
}
CDB_SendDataCmd* CDB_CursorCmd::SendDataCmd(unsigned int item_num,
size_t size,
bool log_it,
bool dump_results)
{
CHECK_COMMAND( m_CmdImpl );
return m_CmdImpl->SendDataCmd(item_num, size, log_it, dump_results);
}
bool CDB_CursorCmd::Delete(const string& table_name)
{
CHECK_COMMAND( m_CmdImpl );
return m_CmdImpl->Delete(table_name);
}
int CDB_CursorCmd::RowCount() const
{
CHECK_COMMAND( m_CmdImpl );
return m_CmdImpl->RowCount();
}
bool CDB_CursorCmd::Close()
{
CHECK_COMMAND( m_CmdImpl );
return m_CmdImpl->CloseCursor();
}
CDB_CursorCmd::~CDB_CursorCmd()
{
try {
if ( m_CmdImpl ) {
m_CmdImpl->Release();
}
}
NCBI_CATCH_ALL_X( 7, NCBI_CURRENT_FUNCTION )
}
/////////////////////////////////////////////////////////////////////////////
// CDB_SendDataCmd::
//
CDB_SendDataCmd::CDB_SendDataCmd(impl::CSendDataCmd* c)
{
CHECK_DRIVER_ERROR( !c, "No valid command provided", 200006 );
m_CmdImpl = c;
m_CmdImpl->AttachTo(this);
}
size_t CDB_SendDataCmd::SendChunk(const void* pChunk, size_t nofBytes)
{
CHECK_DRIVER_WARNING( !m_CmdImpl, "This command cannot be used anymore", 200005 );
return m_CmdImpl->SendChunk(pChunk, nofBytes);
}
bool CDB_SendDataCmd::Cancel(void)
{
CHECK_DRIVER_WARNING( !m_CmdImpl, "This command cannot be used anymore", 200005 );
return m_CmdImpl->Cancel();
}
CDB_Result* CDB_SendDataCmd::Result()
{
CHECK_COMMAND( m_CmdImpl );
return m_CmdImpl->Result();
}
bool CDB_SendDataCmd::HasMoreResults() const
{
CHECK_COMMAND( m_CmdImpl );
return m_CmdImpl->HasMoreResults();
}
void CDB_SendDataCmd::DumpResults()
{
CHECK_COMMAND( m_CmdImpl );
m_CmdImpl->DumpResults();
}
CDB_SendDataCmd::~CDB_SendDataCmd()
{
try {
if ( m_CmdImpl ) {
m_CmdImpl->Release();
}
}
NCBI_CATCH_ALL_X( 8, NCBI_CURRENT_FUNCTION )
}
/////////////////////////////////////////////////////////////////////////////
// CDB_BlobDescriptor::
//
CDB_BlobDescriptor::CDB_BlobDescriptor(const string& table_name,
const string& column_name,
const string& search_conditions,
ETDescriptorType column_type,
ETriState has_legacy_type)
: m_TableName(table_name)
, m_ColumnName(column_name)
, m_SearchConditions(search_conditions)
, m_ColumnType(column_type)
, m_HasLegacyType(has_legacy_type)
{
}
CDB_BlobDescriptor::~CDB_BlobDescriptor()
{
}
int CDB_BlobDescriptor::DescriptorType() const
{
return 0;
}
/////////////////////////////////////////////////////////////////////////////
// CDB_ResultProcessor::
//
CDB_ResultProcessor::CDB_ResultProcessor(CDB_Connection* c) :
m_Con(NULL),
m_Prev(NULL),
m_Next(NULL)
{
SetConn(c);
}
void CDB_ResultProcessor::ProcessResult(CDB_Result& res)
{
while (res.Fetch()) // fetch and forget
continue;
}
CDB_ResultProcessor::~CDB_ResultProcessor()
{
try {
if ( m_Con ) {
m_Con->SetResultProcessor(m_Prev);
}
if(m_Prev) {
m_Prev->m_Next = m_Next;
}
if(m_Next) {
m_Next->m_Prev = m_Prev;
}
}
NCBI_CATCH_ALL_X( 9, NCBI_CURRENT_FUNCTION )
}
void CDB_ResultProcessor::SetConn(CDB_Connection* c)
{
// Clear previously used connection ...
if ( m_Con ) {
m_Con->SetResultProcessor(NULL);
}
m_Con = c;
if ( m_Con ) {
_ASSERT(m_Prev == NULL);
m_Prev = m_Con->SetResultProcessor(this);
if (m_Prev) {
_ASSERT(m_Prev->m_Next == NULL);
m_Prev->m_Next = this;
}
}
}
void CDB_ResultProcessor::ReleaseConn(void)
{
m_Con = NULL;
}
////////////////////////////////////////////////////////////////////////////////
CAutoTrans::CAutoTrans(const CSubject& subject)
: m_Abort(true)
, m_Conn(subject.m_Connection)
, m_TranCount(0)
{
BeginTransaction();
m_TranCount = GetTranCount();
if (m_TranCount > 1) {
m_SavepointName = "ncbi_dbapi_txn_"
+ NStr::NumericToString(reinterpret_cast<intptr_t>(this), 0, 16);
unique_ptr<CDB_LangCmd> auto_stmt
(m_Conn.LangCmd("SAVE TRANSACTION " + m_SavepointName));
auto_stmt->Send();
auto_stmt->DumpResults();
}
}
CAutoTrans::~CAutoTrans(void)
{
try
{
const int curr_TranCount = GetTranCount();
if (curr_TranCount >= m_TranCount) {
if (curr_TranCount > m_TranCount) {
// A nested transaction is started and not finished yet ...
ERR_POST_X(1, Warning << "A nested transaction was started and "
"it is not finished yet.");
}
// Assume that we are on the same level of transaction nesting.
if(m_Abort) {
Rollback();
} else {
Commit();
}
}
m_Conn.m_HasTransaction = (curr_TranCount <= 1);
// Skip commit/rollback if this transaction was previously
// explicitly finished ...
}
NCBI_CATCH_ALL_X( 10, NCBI_CURRENT_FUNCTION )
}
void
CAutoTrans::BeginTransaction(void)
{
m_Conn.m_HasTransaction = true;
unique_ptr<CDB_LangCmd> auto_stmt(m_Conn.LangCmd("BEGIN TRANSACTION"));
auto_stmt->Send();
auto_stmt->DumpResults();
}
void
CAutoTrans::Commit(void)
{
unique_ptr<CDB_LangCmd> auto_stmt(m_Conn.LangCmd("COMMIT"));
auto_stmt->Send();
auto_stmt->DumpResults();
}
void
CAutoTrans::Rollback(void)
{
unique_ptr<CDB_LangCmd> auto_stmt
(m_Conn.LangCmd("ROLLBACK TRANSACTION " + m_SavepointName));
auto_stmt->Send();
auto_stmt->DumpResults();
if (m_SavepointName.empty()) {
_ASSERT(m_TranCount == 1);
} else {
// Formally unwind via an empty commit, as a rollback would
// also cancel outer transactions.
Commit();
}
}
int
CAutoTrans::GetTranCount(void)
{
int result = 0;
unique_ptr<CDB_LangCmd> auto_stmt(m_Conn.LangCmd("SELECT @@trancount as tc"));
if (auto_stmt->Send()) {
while(auto_stmt->HasMoreResults()) {
unique_ptr<CDB_Result> rs(auto_stmt->Result());
if (rs.get() == NULL) {
continue;
}
if (rs->ResultType() != eDB_RowResult) {
continue;
}
if (rs->Fetch()) {
CDB_Int tran_count;
rs->GetItem(&tran_count);
result = tran_count.Value();
}
while(rs->Fetch()) {
}
}
}
return result;
}
END_NCBI_SCOPE
| [
"ludwigf@78c7ea69-d796-4a43-9a09-de51944f1b03"
] | ludwigf@78c7ea69-d796-4a43-9a09-de51944f1b03 |
eb741f89bac9a219d1289fafae21c9b1ef8f8dc4 | 8885ce9cd0555d24f554c8646558226430c6e71c | /AI_DijkstrasSearch/PathAgent.h | 0ab121ffc9ae8fa8a8b154a7a5d53bc08df732c1 | [] | no_license | AcademyOfInteractiveEntertainment/AIEYear1Samples | ee6f852451ffe401a032c3db494de937109790a5 | 8a67da68cf5e373be9f2972b0b6aaaf0ebd51452 | refs/heads/master | 2023-07-05T04:14:52.271023 | 2022-07-07T04:08:01 | 2022-07-07T04:08:01 | 250,116,725 | 7 | 24 | null | 2023-07-06T18:10:31 | 2020-03-25T23:43:47 | HTML | UTF-8 | C++ | false | false | 372 | h | #pragma once
#include "raylib.h"
#include "pathfinding.h"
#include <vector>
namespace pathfinding
{
class PathAgent
{
public:
Vector2 position;
std::vector<Node*> path;
int currentIndex;
Node* currentNode;
float speed;
void SetNode(Node* node);
void Update(float deltaTime);
void GoToNode(Node* node);
void Draw();
};
}
| [
"drmike@fundamentzero.com"
] | drmike@fundamentzero.com |
fcb7cf005c52cd9408c1e698c30711bab670b6d9 | 047600ca8efa01dd308f4549793db97e6ddcec20 | /Src/HLSDK/vgui_controls/BuildFactoryHelper.cpp | b5bd43619c8553e231a358c8feec2e3e8f0ba6a9 | [] | no_license | crskycode/Mind-Team | cbb9e98322701a5d437fc9823dd4c296a132330f | ceab21c20b0b51a2652c02c04eb7ae353b82ffd0 | refs/heads/main | 2023-03-16T10:34:31.812155 | 2021-03-02T02:23:40 | 2021-03-02T02:23:40 | 343,616,799 | 6 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,523 | cpp | //========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose: Helper for the CHudElement class to add themselves to the list of hud elements
//
// $NoKeywords: $
//=============================================================================//
#include "vgui/IVGui.h"
#include "vgui_controls/MessageMap.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
using namespace vgui;
// Start with empty list
CBuildFactoryHelper *CBuildFactoryHelper::m_sHelpers = NULL;
//-----------------------------------------------------------------------------
// Purpose: Constructs a panel factory
// Input : pfnCreate - fn Ptr to a function which generates a panel
//-----------------------------------------------------------------------------
CBuildFactoryHelper::CBuildFactoryHelper( char const *className, PANELCREATEFUNC func )
{
// Make this fatal
if ( HasFactory( className ) )
{
Error( "CBuildFactoryHelper: Factory for '%s' already exists!!!!\n", className );
}
//List is empty, or element belongs at front, insert here
m_pNext = m_sHelpers;
m_sHelpers = this;
Assert( func );
m_CreateFunc = func;
Assert( className );
m_pClassName = className;
}
//-----------------------------------------------------------------------------
// Purpose: Returns next object in list
// Output : CBuildFactoryHelper
//-----------------------------------------------------------------------------
CBuildFactoryHelper *CBuildFactoryHelper::GetNext( void )
{
return m_pNext;
}
char const *CBuildFactoryHelper::GetClassName() const
{
return m_pClassName;
}
vgui::Panel *CBuildFactoryHelper::CreatePanel()
{
if ( !m_CreateFunc )
return NULL;
return ( *m_CreateFunc )();
}
// private static meethod
bool CBuildFactoryHelper::HasFactory( char const *className )
{
CBuildFactoryHelper *p = m_sHelpers;
while ( p )
{
if ( !Q_stricmp( className, p->GetClassName() ) )
return true;
p = p->GetNext();
}
return false;
}
// static method
vgui::Panel *CBuildFactoryHelper::InstancePanel( char const *className )
{
CBuildFactoryHelper *p = m_sHelpers;
while ( p )
{
if ( !Q_stricmp( className, p->GetClassName() ) )
return p->CreatePanel();
p = p->GetNext();
}
return NULL;
}
// static method
void CBuildFactoryHelper::GetFactoryNames( CUtlVector< char const * >& list )
{
list.RemoveAll();
CBuildFactoryHelper *p = m_sHelpers;
while ( p )
{
list.AddToTail( p->GetClassName() );
p = p->GetNext();
}
}
| [
"crskycode@hotmail.com"
] | crskycode@hotmail.com |
cec930c840aa9ea2fef05efda619ee5aaf222231 | 04208e69e7cf235d5299fa57d84afc74562b6d0a | /A89_zhubo/mainwindow - 副本.cpp | 66ccc5e56316c0f12dd09904f6b260c7f5e12870 | [] | no_license | QPKJEDL/deskgame | d09ccc20e3049853d9d7f87096d326138a4b9cd5 | 3043b56f6c669247b7998b3e75d926d53f07f0da | refs/heads/master | 2022-12-03T07:44:02.928771 | 2020-08-12T07:14:00 | 2020-08-12T07:14:00 | 271,161,577 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 34,985 | cpp | #include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QKeyEvent>
#include <QDebug>
#include <QTimer>
#include <QDateTime>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QUrl>
#include <QByteArray>
#include <QGraphicsOpacityEffect>
#include <vector>
using namespace std;
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
// , m_edit_string("")
, m_edit_last("")
{
ui->setupUi(this);
//ui->lineEdit->setFocus();
ui->lineEdit->setStyleSheet("background:transparent;border-width:0;border-style:outset");
timer_focus = new QTimer(this);
connect(timer_focus, SIGNAL(timeout()), this, SLOT(update()));
ui->button_locate->setFocus();
timer_opacity = new QTimer(this);
timer_date = new QTimer(this);
//connect(timer_opacity, SIGNAL(timeout()), this, SLOT(on_timeout()));
//timer_opacity->start(10);
m_graphiceffect = new QGraphicsOpacityEffect;
m_light = false;
n_graphiceffect = new QGraphicsOpacityEffect;
connect(ui->pu_start, SIGNAL(clicked()), this, SLOT(pu_start()));
connect(ui->pu_stop, SIGNAL(clicked()), this, SLOT(pu_stop()));
connect(timer_opacity, SIGNAL(timeout()), this, SLOT(on_timeout()));
connect(ui->button_locate,SIGNAL(clicked()),this,SLOT(pu_locate()));
connect(ui->lineEdit_2,SIGNAL(returnPressed()),this,SLOT(line_finish()));
connect(ui->button_summit,SIGNAL(clicked()),this,SLOT(on_summit()));
connect(timer_date,SIGNAL(timeout()),this,SLOT(update_date()));
timer_date->start(200);
connect(ui->pu_exit,SIGNAL(clicked()),this,SLOT(on_exit()));
connect(ui->button_useless,SIGNAL(clicked()),this,SLOT(on_useless()));
//M 连接所有按钮的按下和松开的槽函数
connect(ui->button_useless,SIGNAL(pressed()),this,SLOT(useless_pressed()));
connect(ui->button_useless,SIGNAL(released()),this,SLOT(useless_released()));
connect(ui->button_locate,SIGNAL(pressed()),this,SLOT(locate_pressed()));
connect(ui->button_locate,SIGNAL(released()),this,SLOT(locate_released()));
connect(ui->button_summit,SIGNAL(pressed()),this,SLOT(summit_pressed()));
connect(ui->button_summit,SIGNAL(released()),this,SLOT(summit_released()));
connect(ui->pu_stop,SIGNAL(pressed()),this,SLOT(stop_pressed()));
connect(ui->pu_stop,SIGNAL(released()),this,SLOT(stop_released()));
connect(ui->xue_change,SIGNAL(pressed()),this,SLOT(change_pressed()));
connect(ui->xue_change,SIGNAL(released()),this,SLOT(change_released()));
connect(ui->pu_start,SIGNAL(pressed()),this,SLOT(start_pressed()));
connect(ui->pu_start,SIGNAL(released()),this,SLOT(start_released()));
//M 开始按钮
connect(ui->pu_start,SIGNAL(clicked()),this,SLOT(on_start()));
//M 倒计时计数器
timer_Countdown = new QTimer(this);
count_down = 15;
connect(timer_Countdown,SIGNAL(timeout()),this,SLOT(on_count_down()));
QNetworkAccessManager *accessManager = new QNetworkAccessManager(this);
connect(accessManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(finishedSlot(QNetworkReply*)));
QNetworkRequest request;m_edit_last = QString("");
request.setUrl(QUrl("http://192.168.0.106:8210/lh_desk_ini"));
//get
//accessManager->get(request);
QByteArray postData;
postData.append("username=admin&password=123456");
//post
QNetworkReply* reply = accessManager->post(request, postData);
//M
//闲家一
head = new players;
head->num = 0;
head->data[0].label = ui->one_one_pic;
head->data[1].label = ui->one_two_pic;
head->data[2].label = ui->one_three_pic;
head->data[3].label = ui->one_four_pic;
head->data[4].label = ui->one_five_pic;
//闲家二
players *er = new players;
er->num = 1;
er->data[0].label = ui->two_one_pic;
er->data[1].label = ui->two_two_pic;
er->data[2].label = ui->two_three_pic;
er->data[3].label = ui->two_four_pic;
er->data[4].label = ui->two_four_pic_2;//?
head->next = er;
//闲家三
players *san = new players;
san->num = 2;
san->data[0].label = ui->three_one_pic;
san->data[1].label = ui->three_two_pic;
san->data[2].label = ui->three_three_pic;
san->data[3].label = ui->three_four_pic;
san->data[4].label = ui->three_five_pic;
er->next = san;
//庄家
players *zhuang = new players;
zhuang->num = 3;
zhuang->data[0].label = ui->zhuang_one_pic;
zhuang->data[1].label = ui->zhuang_two_pic;
zhuang->data[2].label = ui->zhuang_three_pic;
zhuang->data[3].label = ui->zhuang_four_pic;
zhuang->data[4].label = ui->zhuang_five_pic;
san->next = zhuang;
zhuang->next = head;
//M
//初始化结果列表,80 个QLabel
quarter = 0;
//第一局
FOURLABELS *labels_one = new FOURLABELS;
labels_one->zhuang = ui->zhuang_one;
labels_one->one = ui->one_one;
labels_one->two = ui->two_one;
labels_one->three = ui->three_one;
this->result_list.append(labels_one);
//
FOURLABELS *labels_two = new FOURLABELS;
labels_two->zhuang = ui->zhuang_two;
labels_two->one = ui->one_two;
labels_two->two = ui->two_two;
labels_two->three = ui->three_two;
this->result_list.append(labels_two);
//
FOURLABELS *labels_three = new FOURLABELS;
labels_three->zhuang = ui->zhuang_three;
labels_three->one = ui->one_three;
labels_three->two = ui->two_three;
labels_three->three = ui->three_three;
this->result_list.append(labels_three);
//
FOURLABELS *labels_four = new FOURLABELS;
labels_four->zhuang = ui->zhuang_four;
labels_four->one = ui->one_four;
labels_four->two = ui->two_four;
labels_four->three = ui->three_four;
this->result_list.append(labels_four);
//
FOURLABELS *labels_five = new FOURLABELS;
labels_five->zhuang = ui->zhuang_five;
labels_five->one = ui->one_five;
labels_five->two = ui->two_five;
labels_five->three = ui->three_five;
this->result_list.append(labels_five);
//
FOURLABELS *labels_six = new FOURLABELS;
labels_six->zhuang = ui->zhuang_six;
labels_six->one = ui->one_six;
labels_six->two = ui->two_six;
labels_six->three = ui->three_six;
this->result_list.append(labels_six);
//
FOURLABELS *labels_seven = new FOURLABELS;
labels_seven->zhuang = ui->zhuang_seven;
labels_seven->one = ui->one_seven;
labels_seven->two = ui->two_seven;
labels_seven->three = ui->three_seven;
this->result_list.append(labels_seven);
//
FOURLABELS *labels_eight = new FOURLABELS;
labels_eight->zhuang = ui->zhuang_eight;
labels_eight->one = ui->one_eight;
labels_eight->two = ui->two_eight;
labels_eight->three = ui->three_eight;
this->result_list.append(labels_eight);
//
FOURLABELS *labels_nine = new FOURLABELS;
labels_nine->zhuang = ui->zhuang_nine;
labels_nine->one = ui->one_nine;
labels_nine->two = ui->two_nine;
labels_nine->three = ui->three_nine;
this->result_list.append(labels_nine);
//
FOURLABELS *labels_ten = new FOURLABELS;
labels_ten->zhuang = ui->zhuang_ten;
labels_ten->one = ui->one_ten;
labels_ten->two = ui->two_ten;
labels_ten->three = ui->three_ten;
this->result_list.append(labels_ten);
//第十一局
FOURLABELS *labels_eleven = new FOURLABELS;
labels_eleven->zhuang = ui->zhuang_ele;
labels_eleven->one = ui->one_ele;
labels_eleven->two = ui->two_ele;
labels_eleven->three = ui->three_ele;
this->result_list.append(labels_eleven);
//
FOURLABELS *labels_twe = new FOURLABELS;
labels_twe->zhuang = ui->zhuang_twe;
labels_twe->one = ui->one_twe;
labels_twe->two = ui->two_twe;
labels_twe->three = ui->three_twe;
this->result_list.append(labels_twe);
//
FOURLABELS *labels_thr = new FOURLABELS;
labels_thr->zhuang = ui->zhuang_thr;
labels_thr->one = ui->one_thr;
labels_thr->two = ui->two_thr;
labels_thr->three = ui->three_thr;
this->result_list.append(labels_thr);
//
FOURLABELS *labels_fourteen = new FOURLABELS;
labels_fourteen->zhuang = ui->zhuang_fourteen;
labels_fourteen->one = ui->one_fourteen;
labels_fourteen->two = ui->two_fourteen;
labels_fourteen->three = ui->three_fourteen;
this->result_list.append(labels_fourteen);
//
FOURLABELS *labels_fif = new FOURLABELS;
labels_fif->zhuang = ui->zhuang_fif;
labels_fif->one = ui->one_fif;
labels_fif->two = ui->two_fif;
labels_fif->three = ui->three_fif;
this->result_list.append(labels_fif);
//
FOURLABELS *labels_sixteen = new FOURLABELS;
labels_sixteen->zhuang = ui->zhuang_sixteen;
labels_sixteen->one = ui->one_sixteen;
labels_sixteen->two = ui->two_sixteen;
labels_sixteen->three = ui->three_sixteen;
this->result_list.append(labels_sixteen);
//
FOURLABELS *labels_seventeen = new FOURLABELS;
labels_seventeen->zhuang = ui->zhuang_seventeen;
labels_seventeen->one = ui->one_seventeen;
labels_seventeen->two = ui->two_seventeen;
labels_seventeen->three = ui->three_seventeen;
this->result_list.append(labels_seventeen);
//
FOURLABELS *labels_eighteen = new FOURLABELS;
labels_eighteen->zhuang = ui->zhuang_eighteen;
labels_eighteen->one = ui->one_eighteen;
labels_eighteen->two = ui->two_eighteen;
labels_eighteen->three = ui->three_eighteen;
this->result_list.append(labels_eighteen);
//
FOURLABELS *labels_ninteen = new FOURLABELS;
labels_ninteen->zhuang = ui->zhuang_ninteen;
labels_ninteen->one = ui->one_ninteen;
labels_ninteen->two = ui->two_ninteen;
labels_ninteen->three = ui->three_ninteen;
this->result_list.append(labels_ninteen);
//
FOURLABELS *labels_twt = new FOURLABELS;
labels_twt->zhuang = ui->zhuang_twt;
labels_twt->one = ui->one_twt;
labels_twt->two = ui->two_twt;
labels_twt->three = ui->three_twt;
this->result_list.append(labels_twt);
//M
ui->lineEdit_2->setVisible(false);
}
//判断是否是炸弹12,五花牛11
int FiveBull(CARD player[]){
//炸弹判断
int shuLiang[5] = {0};
int count = 0,c = 0;
for(int i = 0;i < 5;i++){
for(int j = 0;j < 5;j++){
if(player[i].face == player[j].face){
shuLiang[i]++;
if(c < shuLiang[i]){
c = shuLiang[i];
//炸弹
if(c == 4){
return 12;
}
}
}
}
if(player[i].hua){
count++;
//五花牛
if(count == 5){
return 11;
}
}
}
return -1;
}
//牛几 ,10 为 牛 10
int BullCount(CARD player[]){
for(int one = 0;one <= 2;one++){
for(int two = one + 1;two <= 3;two++){
for(int three = two + 1;three <= 4;three++){
if((player[one].num + player[two].num + player[three].num) % 10 == 0){
vector<int> vec = {0,1,2,3,4};
vec.erase(vec.begin() + one);
vec.erase(vec.begin() + two - 1);
vec.erase(vec.begin() + three - 2);
int m = (player[vec[0]].num + player[vec[1]].num) % 10;
if(m == 0){
return 10;
}
return m;
}
}
}
}
return -1;
}
//该函数的作用是将 face 转换成 点数
int dianShu(string str){
string Cards[] = {"A","2","3","4","5","6","7","8","9","10","J","Q","K"};
for(int i = 0;i < 13;i++){
if(Cards[i] == str){
return i + 1;
}
}
return 0;
}
//按理说排序以后就不必寻找最大点数的牌了,因为player[4]
void paixu(CARD player[]){
for(int i = 0;i < 4;i++){
for(int j = 0;j < 4-i;j++){
//先判断下一个牌的值是否大于这个牌的值
if(dianShu(player[j].face) > dianShu(player[j + 1].face)){
CARD temp = player[j];
player[j] = player[j + 1];
player[j + 1] = temp;
}
//如果上面的if语句执行了,则说明值不一样,那么下面这个if不会成立
if(dianShu(player[j].face) == dianShu(player[j + 1].face) && player[j].color > player[j + 1].color){
CARD temp = player[j];
player[j] = player[j + 1];
player[j + 1] = temp;
}
}
}
}
PAIRESULT PaiXing(CARD player[]){
paixu(player);
PAIRESULT r;
r.biggest = player[4];//由于paixu() 函数已经将最大的牌放到最后一个了,所以直接获取就行
r.paiXing = FiveBull(player);
if(r.paiXing == -1){
r.paiXing = BullCount(player);
}
if(r.paiXing == -1){
r.paiXing = dianShu(r.biggest.face) - 14;//用于后面比较牌型
}
return r;
}
void MainWindow::locate(){
for(int j = 2;j <= location;j++){
head = head->next;
}
}
//1 2 3 4 1 2 3 4
void MainWindow::flash()
{
}
string PaiXingToStr(int paixing){
if(paixing < 0){
return "无牛";
}
else if(paixing > 0 && paixing < 10){
return "牛 " + to_string(paixing);
}
else{
switch (paixing) {
case(10):
return "牛牛";
break;
case(11):
return "五花牛";
break;
case(12):
return "炸弹";
break;
}
}
return "不可能";
}
void MainWindow::wait(CARD card){
head->data[number.num].hua = card.hua;
head->data[number.num].num = card.num;
head->data[number.num].face = card.face;
head->data[number.num].color = card.color;
if(number.num == 4){
switch (head->num) {
case(0):
ui->xian1_result->setText(QString::fromStdString(PaiXingToStr(PaiXing(head->data).paiXing)));
break;
case(1):
ui->xian2_result->setText(QString::fromStdString(PaiXingToStr(PaiXing(head->data).paiXing)));
break;
case(2):
ui->xian3_result->setText(QString::fromStdString(PaiXingToStr(PaiXing(head->data).paiXing)));
break;
case(3):
ui->zhuang_result->setText(QString::fromStdString(PaiXingToStr(PaiXing(head->data).paiXing)));
break;
}
}
head = head->next;
number.increase();
if(number.num == 5){
// 提交按钮启用
ui->button_summit->setEnabled(true);
ui->button_summit->setFocus();
summit_released();
//M
timer_focus->stop();
n_graphiceffect->setOpacity(1);
label_name->setGraphicsEffect(n_graphiceffect);
if(location % 4 == 0){
label_name->setStyleSheet("color: rgb(255, 0, 0)");
}
else{
label_name->setStyleSheet("color: rgb(255, 255, 255)");
}
}
}
MainWindow::~MainWindow()
{
delete ui;
}
string intToFace(int str){
vector<string> Cards = {"A","2","3","4","5","6","7","8","9","10","J","Q","K"};
return Cards[str - 1];
}
CARD strToCard(string str){
string color = str.substr(0,1);
string face = str.substr(1,2);
CARD card;
card.color = stoi(color);
card.num = stoi(face) > 10 ? 10 : stoi(face);
card.hua = stoi(face) > 10 ? true : false;
card.face = intToFace(stoi(face));
return card;
}
void MainWindow::keyPressEvent(QKeyEvent *keyValue)
{
if(keyValue->key() == 16777220)//enter
{
QString str = ui->lineEdit->text();
if (m_edit_last != str) {
//发送数据
m_edit_last = str;
if(number.num == 5){
return;
}
if(m_edit_last.size() == 3){
head->data[number.num].label->setStyleSheet("image: url(:/image/pukepai/" + str +".png)");
wait(strToCard(m_edit_last.toStdString()));
}
}
//M
ui->lineEdit->setText(QString(""));
}
}
//若前者大,则返回true,否则返回false
bool Bigger(PAIRESULT player_1,PAIRESULT player_2){
if(player_1.paiXing > player_2.paiXing){
return true;
}
if(player_1.paiXing == player_2.paiXing){
if(dianShu(player_1.biggest.face) > dianShu(player_2.biggest.face)){
return true;
}
if(dianShu(player_1.biggest.face) == dianShu(player_2.biggest.face)){
return player_1.biggest.color > player_2.biggest.color ? true : false;
}
return false;
}
return false;
}
QString PaixingToResult(int i){
if(i < 0){
return "N";
}
if(i == 10){
return "B";
}
if(i > 0){
return QString::fromStdString(to_string(i));
}
return QString("");
}
void MainWindow::result(){
PAIRESULT zhuang;
PAIRESULT vec[3] = {};
QString result = "";
for(int i = 0;i < 4;i++){
PAIRESULT result = PaiXing(head->data);
if(head->num == 3){
zhuang = result;
}
else{
vec[head->num] = result;
}
head = head->next;
}
//所有牌型收集完毕,开始比较
//庄家结果
if(quarter <= 19){
result_list[quarter]->zhuang->setText(PaixingToResult(zhuang.paiXing));
}
else{
for(int q = 0;q < 19;q++){
result_list[q]->zhuang->setText(result_list[q+1]->zhuang->text());
result_list[q]->zhuang->setStyleSheet(result_list[q]->zhuang->styleSheet());
}
result_list[19]->zhuang->setText(PaixingToResult(zhuang.paiXing));
result_list[19]->zhuang->setStyleSheet("image: url(:/image/red.png)");
}
for(int i = 0;i < 3;i++){
if(!Bigger(zhuang,vec[i])){
switch (i) {
case(0):{
//闲家1 赢
result += "闲家1 ";
int j = stoi(ui->one_win_times->text().toStdString());
ui->one_win_times->setText(QString::fromStdString(to_string(j+1)));
if(quarter <= 19){
result_list[quarter]->one->setText(PaixingToResult(vec[i].paiXing));
result_list[quarter]->one->setStyleSheet("image: url(:/image/blue.png)");
}
else{
for(int q = 0;q < 19;q++){
result_list[q]->one->setText(result_list[q+1]->one->text());
result_list[q]->one->setStyleSheet(result_list[q+1]->one->styleSheet());
}
result_list[19]->one->setText(PaixingToResult(vec[i].paiXing));
result_list[19]->one->setStyleSheet("image: url(:/image/blue.png)");
}
break;
}
case(1):{
//闲家2 赢
result += "闲家2 ";
int j = stoi(ui->two_win_times->text().toStdString());
ui->two_win_times->setText(QString::fromStdString(to_string(j+1)));
if(quarter <= 19){
result_list[quarter]->two->setText(PaixingToResult(vec[i].paiXing));
result_list[quarter]->two->setStyleSheet("image: url(:/image/blue.png)");
}
else{
for(int q = 0;q < 19;q++){
result_list[q]->two->setText(result_list[q+1]->two->text());
result_list[q]->two->setStyleSheet(result_list[q+1]->two->styleSheet());
}
result_list[19]->two->setText(PaixingToResult(vec[i].paiXing));
result_list[19]->two->setStyleSheet("image: url(:/image/blue.png)");
}
break;
}
case(2):{
//闲家3 赢
result += "闲家3 ";
int j = stoi(ui->three_win_times->text().toStdString());
ui->three_win_times->setText(QString::fromStdString(to_string(j+1)));
if(quarter <= 19){
result_list[quarter]->three->setText(PaixingToResult(vec[i].paiXing));
result_list[quarter]->three->setStyleSheet("image: url(:/image/blue.png)");
}
else{
for(int q = 0;q < 19;q++){
result_list[q]->three->setText(result_list[q+1]->three->text());
result_list[q]->three->setStyleSheet(result_list[q+1]->three->styleSheet());
}
result_list[19]->three->setText(PaixingToResult(vec[i].paiXing));
result_list[19]->three->setStyleSheet("image: url(:/image/blue.png)");
}
break;
}
}
}
else{
switch (i) {
case(0):{
//闲家1 输
if(quarter <= 19){
result_list[quarter]->one->setText(PaixingToResult(vec[i].paiXing));
result_list[quarter]->one->setStyleSheet("image: url(:/image/gray.png)");
}
else{
for(int q = 0;q < 19;q++){
result_list[q]->one->setText(result_list[q+1]->one->text());
result_list[q]->one->setStyleSheet(result_list[q+1]->one->styleSheet());
}
result_list[19]->one->setText(PaixingToResult(vec[i].paiXing));
result_list[19]->one->setStyleSheet("image: url(:/image/gray.png)");
}
break;
}
case(1):{
//闲家2 输
if(quarter <= 19){
result_list[quarter]->two->setText(PaixingToResult(vec[i].paiXing));
result_list[quarter]->two->setStyleSheet("image: url(:/image/gray.png)");
}
else{
for(int q = 0;q < 19;q++){
result_list[q]->two->setText(result_list[q+1]->two->text());
result_list[q]->two->setStyleSheet(result_list[q+1]->two->styleSheet());
}
result_list[19]->two->setText(PaixingToResult(vec[i].paiXing));
result_list[19]->two->setStyleSheet("image: url(:/image/gray.png)");
}
break;
}
case(2):{
//闲家3 输
if(quarter <= 19){
result_list[quarter]->three->setText(PaixingToResult(vec[i].paiXing));
result_list[quarter]->three->setStyleSheet("image: url(:/image/gray.png)");
}
else{
for(int q = 0;q < 19;q++){
result_list[q]->three->setText(result_list[q+1]->three->text());
result_list[q]->three->setStyleSheet(result_list[q+1]->three->styleSheet());
}
result_list[19]->three->setText(PaixingToResult(vec[i].paiXing));
result_list[19]->three->setStyleSheet("image: url(:/image/gray.png)");
}
break;
}
}
}
}
if(result == ""){
ui->pu_result->setText(QString("庄赢"));
ui->who_win->setText("庄赢");
}
else{
ui->pu_result->setText(result);
ui->who_win->setText(result);
}
quarter++;
}
void MainWindow::update()
{
ui->lineEdit->setFocus();
}
void MainWindow::update_date(){
ui->label_date->setText(QDateTime::currentDateTime().toString("yyyy-MM-dd dddd hh:mm:ss"));
}
void MainWindow::on_timeout()
{
qreal i = m_graphiceffect->opacity();
if(number.num == 5){
i = 1;
m_graphiceffect->setOpacity(i);
head->data[4].label->setGraphicsEffect(m_graphiceffect);
timer_opacity->stop();
return;
}
head->data[number.num].label->setStyleSheet("border-radius:5px;background-color: rgb(255, 0, 0)");
if (i < 0.1)
this->m_light = true;
if (i == 1)
this->m_light = false;
if (!m_light)
i -= 0.05;
else
i += 0.05;
m_graphiceffect->setOpacity(i);
head->data[number.num].label->setGraphicsEffect(m_graphiceffect);
n_graphiceffect->setOpacity(i);
label_name->setGraphicsEffect(n_graphiceffect);
}
void MainWindow::pu_start()
{
}
void MainWindow::pu_stop()
{
}
void MainWindow::pu_locate()
{
//timer_focus->stop();//应该stop了两遍
ui->lineEdit_2->setText("");
ui->lineEdit_2->setVisible(true);
// 禁用定位按钮,把按钮变成灰色
ui->button_locate->setEnabled(false);
ui->button_locate->setStyleSheet("border-radius:5px; \
color: rgb(0, 255, 0); \
background-color: rgb(125, 125, 125); \
color: rgb(255, 255, 255);");
}
void MainWindow::LabelPaixu(players *head){
//闲家一
head->data[0].label = ui->one_one_pic;
head->data[1].label = ui->one_two_pic;
head->data[2].label = ui->one_three_pic;
head->data[3].label = ui->one_four_pic;
head->data[4].label = ui->one_five_pic;
head = head->next;
//闲家二
head->data[0].label = ui->two_one_pic;
head->data[1].label = ui->two_two_pic;
head->data[2].label = ui->two_three_pic;
head->data[3].label = ui->two_four_pic;
head->data[4].label = ui->two_four_pic_2;//?
head = head->next;
//闲家三
head->data[0].label = ui->three_one_pic;
head->data[1].label = ui->three_two_pic;
head->data[2].label = ui->three_three_pic;
head->data[3].label = ui->three_four_pic;
head->data[4].label = ui->three_five_pic;
head = head->next;
//庄家
head->data[0].label = ui->zhuang_one_pic;
head->data[1].label = ui->zhuang_two_pic;
head->data[2].label = ui->zhuang_three_pic;
head->data[3].label = ui->zhuang_four_pic;
head->data[4].label = ui->zhuang_five_pic;
head = head->next;
}
void MainWindow::line_finish()
{
bool ok = false;
location = ui->lineEdit_2->text().toInt(&ok);
if(!ok || location < 2 || location > 12){
//提示
return;
}
ui->lineEdit->setFocus();
timer_focus->start(200);
QString str = ui->lineEdit_2->text();
ui->label_locate->setText(str);
ui->lineEdit_2->setVisible(false);
locate();
timer_opacity->start(10);
ui->button_locate->setEnabled(false);
// 废除按钮启用,恢复颜色;
ui->button_useless->setEnabled(true);
useless_released();
// 名字开始闪烁
switch (location % 4) {
case(0):
//庄家
ui->label_zhuang->setStyleSheet("color: rgb(200, 140, 0)");
label_name = ui->label_zhuang;
break;
case(1):
ui->label_xian1->setStyleSheet("color: rgb(200, 140, 0)");
label_name = ui->label_xian1;
break;
case(2):
ui->label_xian2->setStyleSheet("color: rgb(200, 140, 0)");
label_name = ui->label_xian2;
break;
case(3):
ui->label_xian3->setStyleSheet("color: rgb(200, 140, 0)");
label_name = ui->label_xian3;
break;
}
//显示停止下注
ui->opration_show->setText("停止下注");
}
void update_result_labels(int ){
}
void MainWindow::on_summit()
{
timer_opacity->stop();
//遍历清空节点
players *node = head;
do{
for(int i = 0;i < 5;i++){
node->data[i].label->setStyleSheet("background-color: rgb(0, 32, 57)");
}
node = node->next;
}while(node != head);
//head 归位
for(int i = location % 4 + 3; i % 4 != 0;i++){
head = head->next;
}
number.man = 0;
number.num = 0;
ui->button_locate->setFocus();
ui->button_locate->setEnabled(true);
ui->button_summit->setEnabled(false);
//牌型清空
ui->xian1_result->setText(QString(""));
ui->xian2_result->setText(QString(""));
ui->xian3_result->setText(QString(""));
ui->zhuang_result->setText(QString(""));
result();
LabelPaixu(head);
m_edit_last = QString("");
//显示已完结
ui->opration_show->setText(QString("已完结"));
//增加铺次
int i = stoi(ui->pu_times->text().toStdString());
ui->pu_times->setText(QString::fromStdString(to_string(i + 1)));
//清空定位
ui->label_locate->setText(QString(""));
}
void MainWindow::finishedSlot(QNetworkReply* reply)
{
if (reply->error() == QNetworkReply::NoError)
{
QByteArray bytes = reply->readAll();
qDebug() << bytes;
}
else
{
qDebug() << "finishedSlot errors here";
qDebug( "found error .... code: %d\n", (int)reply->error());
qDebug() << reply->errorString();
}
reply->deleteLater();
}
void MainWindow::on_exit(){
ui->pu_start->setDown(true);
this->close();
}
void MainWindow::on_useless(){
//停止闪烁
timer_opacity->stop();
//恢复透明度
if(number.num < 5){
m_graphiceffect->setOpacity(1);
head->data[number.num].label->setGraphicsEffect(m_graphiceffect);
}
if(location % 4 == 0){
label_name->setStyleSheet("color: rgb(255, 0, 0)");
}
else{
label_name->setStyleSheet("color: rgb(255, 255, 255)");
}
n_graphiceffect->setOpacity(1);
label_name->setGraphicsEffect(n_graphiceffect);
//遍历清空节点
players *node = head;
do{
for(int i = 0;i < 5;i++){
node->data[i].label->setStyleSheet("background-color: rgb(0, 32, 57)");
}
node = node->next;
}while(node != head);
//head 归位
for(int i = location % 4 + 3; i % 4 != 0;i++){
head = head->next;
}
number.man = 0;
number.num = 0;
ui->button_locate->setFocus();
ui->button_locate->setEnabled(true);
ui->button_summit->setEnabled(false);
// 牌型清空
ui->xian1_result->setText(QString(""));
ui->xian2_result->setText(QString(""));
ui->xian3_result->setText(QString(""));
ui->zhuang_result->setText(QString(""));
LabelPaixu(head);
m_edit_last = QString("");
// 作废按钮禁用,颜色变灰
ui->button_useless->setEnabled(false);
ui->button_useless->setStyleSheet("border-radius:5px; \
color: rgb(0, 255, 0); \
background-color: rgb(125, 125, 125); \
color: rgb(255, 255, 255);");
}
void MainWindow::useless_pressed()
{
ui->button_useless->setStyleSheet("border-radius:5px; \
color: rgb(0, 255, 0); \
background-color: rgb(0, 0, 200); \
color: rgb(255, 255, 255);");
}
void MainWindow::useless_released()
{
ui->button_useless->setStyleSheet("border-radius:5px; \
color: rgb(0, 255, 0); \
background-color: rgb(0, 0, 255); \
color: rgb(255, 255, 255);");
}
void MainWindow::locate_pressed()
{
ui->button_locate->setStyleSheet("border-radius:5px; \
border-color: qlineargradient(spread:pad, x1:0, y1:0, x2:0, y2:1, stop:0 rgba(0, 0, 0, 255), stop:0.33 rgba(0, 0, 0, 255), stop:0.34 rgba(255, 30, 30, 255), stop:0.66 rgba(255, 0, 0, 255), stop:0.67 rgba(255, 255, 0, 255), stop:1 rgba(255, 255, 0, 255)); \
background-color: rgb(200, 0, 0); \
color: rgb(255, 255, 255);");
}
void MainWindow::locate_released()
{
ui->button_locate->setStyleSheet("border-radius:5px; \
border-color: qlineargradient(spread:pad, x1:0, y1:0, x2:0, y2:1, stop:0 rgba(0, 0, 0, 255), stop:0.33 rgba(0, 0, 0, 255), stop:0.34 rgba(255, 30, 30, 255), stop:0.66 rgba(255, 0, 0, 255), stop:0.67 rgba(255, 255, 0, 255), stop:1 rgba(255, 255, 0, 255)); \
background-color: rgb(255, 0, 0); \
color: rgb(255, 255, 255);");
}
void MainWindow::summit_pressed()
{
ui->button_summit->setStyleSheet("border-radius:5px; \
background-color: rgb(0, 120, 200); \
color: rgb(255, 255, 255);");
}
void MainWindow::summit_released()
{
ui->button_summit->setStyleSheet("border-radius:5px; \
background-color: rgb(0, 170, 255); \
color: rgb(255, 255, 255);");
}
void MainWindow::exit_pressed()
{
ui->pu_exit->setStyleSheet("border-radius:5px; \
background-color: rgb(0, 120, 200); \
color: rgb(255, 255, 255);");
}
void MainWindow::exit_released()
{
ui->pu_exit->setStyleSheet("border-radius:5px; \
background-color: rgb(0, 170, 255); \
color: rgb(255, 255, 255);");
}
void MainWindow::stop_pressed()
{
ui->pu_stop->setStyleSheet("border-radius:5px; \
background-color: rgb(0, 120, 200); \
color: rgb(255, 255, 255);");
}
void MainWindow::stop_released()
{
ui->pu_stop->setStyleSheet("border-radius:5px; \
background-color: rgb(0, 170, 255); \
color: rgb(255, 255, 255);");
}
void MainWindow::change_pressed()
{
ui->xue_change->setStyleSheet("border-radius:5px; \
background-color: rgb(0, 120, 200); \
color: rgb(255, 255, 255);");
}
void MainWindow::change_released()
{
ui->xue_change->setStyleSheet("border-radius:5px; \
background-color: rgb(0, 170, 255); \
color: rgb(255, 255, 255);");
}
void MainWindow::start_pressed()
{
ui->pu_start->setStyleSheet("border-radius:5px; \
background-color: rgb(0, 120, 200); \
color: rgb(255, 255, 255);");
}
void MainWindow::start_released()
{
ui->pu_start->setStyleSheet("border-radius:5px; \
background-color: rgb(0, 170, 255); \
color: rgb(255, 255, 255);");
}
void MainWindow::on_start()
{
// 禁用开始按钮
ui->pu_start->setEnabled(false);
ui->pu_start->setStyleSheet("border-radius:5px; \
border-color: qlineargradient(spread:pad, x1:0, y1:0, x2:0, y2:1, stop:0 rgba(0, 0, 0, 255), stop:0.33 rgba(0, 0, 0, 255), stop:0.34 rgba(255, 30, 30, 255), stop:0.66 rgba(255, 0, 0, 255), stop:0.67 rgba(255, 255, 0, 255), stop:1 rgba(255, 255, 0, 255)); \
color: rgb(255, 255, 255); \
background-color: rgb(125, 125, 125);");
timer_Countdown->start(1000);
}
void MainWindow::on_count_down()
{
qDebug() << count_down;
ui->who_win->setText(QString::fromStdString(to_string(count_down)));
if(count_down-- == 0){
timer_Countdown->stop();
ui->who_win->setText(QString(""));
ui->button_locate->setEnabled(true);
locate_released();
}
}
| [
"1598411165@qq.com"
] | 1598411165@qq.com |
76af7c987d323f60e99c3ece335e35425febdbc9 | 13d8e21ba6ac6cdc4e1914cdedb990c1b97a7541 | /c++/pbbslib/random_shuffle.h | 64ab17566819a622d571b11d55622c5368945e94 | [
"MIT"
] | permissive | mengshanfeng/PAM | 8a3ee0ab70939412ab3f6263f9a54d0aaa36fc89 | e4e3d47fd3f997ea4d65b8ea6f811e219d1cb4f6 | refs/heads/master | 2020-05-26T17:47:48.046072 | 2019-03-12T03:02:16 | 2019-03-12T03:02:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,569 | h | // This code is part of the Problem Based Benchmark Suite (PBBS)
// Copyright (c) 2010-2016 Guy Blelloch and the PBBS team
//
// 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.
#pragma once
#include <math.h>
#include <stdio.h>
#include <cstdint>
#include "utilities.h"
#include "random.h"
#include "counting_sort.h"
namespace pbbs {
template <typename Seq>
void seq_random_shuffle(Seq A, random r = default_random) {
size_t n = A.size();
// the Knuth shuffle
if (n < 2) return;
for (size_t i=n-1; i > 0; i--)
std::swap(A[i],A[r.ith_rand(i)%(i+1)]);
}
template <typename Seq>
void random_shuffle(Seq A, random r = default_random) {
size_t n = A.size();
if (n < SEQ_THRESHOLD) {
seq_random_shuffle(A);
return;
}
size_t bits = 10;
if (n < (1 << 27))
bits = (log2_up(n) - 7)/2;
else bits = (log2_up(n) - 17);
size_t num_buckets = (1<<bits);
size_t mask = num_buckets - 1;
auto rand_pos = [&] (size_t i) -> size_t {
return r.ith_rand(i) & mask;};
auto get_pos = make_sequence<size_t>(n, rand_pos);
// first randomly sorts based on random values [0,num_buckets)
sequence<size_t> bucket_offsets = count_sort(A, A, get_pos, num_buckets);
// now sequentially randomly shuffle within each bucket
auto bucket_f = [&] (size_t i) {
size_t start = bucket_offsets[i];
size_t end = bucket_offsets[i+1];
seq_random_shuffle(A.slice(start,end), r.fork(i));
};
parallel_for(0, num_buckets, bucket_f, 1);
}
}
| [
"syhlalala@gmail.com"
] | syhlalala@gmail.com |
05e8da80586be7daabbd34372c7e7ad450fc6fb8 | e97c316f64f827082e5c0c995fc08e943ddecad4 | /job/Job.cpp | c8cf0932086ee8765545838ad79deada5b89dfde | [] | no_license | AndreasHK/opcuaTestTool | af37d43da7f1ff00af4bf8dbd786f2f3cd6cbef9 | 86194aba3b20af06ef733039102876e3bf2eb65a | refs/heads/master | 2022-10-10T11:27:13.978631 | 2020-06-13T09:21:22 | 2020-06-13T09:21:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,116 | cpp | #include "Job.h"
#include "Task.h"
#include <chrono>
#include <fstream>
#include <iostream>
#include <nlohmann/json.hpp>
#include "Client.h"
namespace tt {
void Job::addTask(std::unique_ptr<Task> task)
{
tasks.emplace_back(std::move(task));
}
const std::vector<std::unique_ptr<Task>>& Job::getTasks()
{
return tasks;
}
void RepetiveJob::execute(TestClient* client)
{
if(client->getConnectionState()!=Client::ConnectionState::CONNECTED)
{
std::cout << "could not connect to server, abort job" << std::endl;
status = JobStatus::ABORTED;
return;
}
for (const auto& t : tasks)
{
if(!t->prepare(client))
{
status = JobStatus::ABORTED;
std::cout << "prepare failed, abort job" << std::endl;
return;
}
}
auto start = std::chrono::steady_clock::now();
status = JobStatus::RUNNING;
for (auto i = 0u; i < iterations; i++)
{
for (const auto& t : tasks)
{
if(!t->execute(client))
{
status = JobStatus::ABORTED;
std::cout << "execute failed, abort job" << std::endl;
return;
}
}
}
status = JobStatus::FINISHED;
auto end = std::chrono::steady_clock::now();
std::chrono::duration<double, std::milli> duration;
duration = end - start;
totalRuntime_ms = duration.count();
runtimePerIteration_ms = totalRuntime_ms / static_cast<double>(iterations);
}
const std::string& Job::getServerUri() const
{
return serverUri;
}
void Job::addResult(const std::string& inputFile, const std::string& outputFile)
{
using nlohmann::json;
std::ifstream ifs1{ inputFile };
auto j = json::parse(ifs1);
auto result = json{ { "totalRuntime_ms", totalRuntime_ms }, { "runtimePerIteration_ms", runtimePerIteration_ms } };
if(status!= JobStatus::FINISHED)
{
result["statusCode"] = "Error";
}
else
{
result["statusCode"] = "Ok";
}
nlohmann::json output;
output["result"] = result;
output["request"] = j;
std::ofstream out(outputFile);
out << output;
out.close();
}
} // namespace tt
| [
"matkonnerth@gmail.com"
] | matkonnerth@gmail.com |
9f4ce8ae23f33e54d8dd4369b8368a3925b0b204 | f5fe0f0f9a7e32a4eaf4f7ddd3d50d3efc09139a | /Tiny Wonders/Up the Garden Path.ino | 7c3000cdfb96b8813337ecf8deaab5c08938b2f7 | [] | no_license | yolabs007/Piwars2021 | 9aa9fcb3e55a880c3bc63df33015a0659f46787b | c9257c445d3706289d8a013e3cf76ffe3fac4843 | refs/heads/main | 2023-06-02T03:09:23.945099 | 2021-06-20T12:27:15 | 2021-06-20T12:27:15 | 373,027,023 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,324 | ino | #include <AFMotor.h>
// Change these below Pins to connected pins of IR sensor
#define lefts A1
#define rights A5
AF_DCMotor motor1(1, MOTOR12_8KHZ); // Here right side motor is connected to M1
AF_DCMotor motor2(2, MOTOR12_8KHZ); // Here left side motor is connected to M4
void setup() {
pinMode(lefts,INPUT);
pinMode(rights,INPUT);
Serial.begin(9600);
}
void loop(){
//printing values of the sensors to the serial monitor
Serial.println(digitalRead(lefts));
Serial.println(digitalRead(rights));
//line detected by both
if(digitalRead(lefts)==0 && digitalRead(rights)==0){
//FORWARD
motor1.run(FORWARD);
motor1.setSpeed(100);
motor2.run(FORWARD);
motor2.setSpeed(100);
}
//line detected by left sensor
else if(digitalRead(lefts)==0 && digitalRead(rights)==1){
//turn left
motor1.run(FORWARD);
motor1.setSpeed(125);
motor2.run(BACKWARD);
motor2.setSpeed(100);
}
//line detected by right sensor
else if(digitalRead(lefts)==1 && digitalRead(rights)==0){;
//turn left
motor1.run(BACKWARD);
motor1.setSpeed(100);
motor2.run(FORWARD);
motor2.setSpeed(125);
}
//line detected by none
else if(digitalRead(lefts)==1 && digitalRead(rights)==1){
//stop
motor1.run(RELEASE);
motor2.run(RELEASE);
}
}
| [
"noreply@github.com"
] | noreply@github.com |
0eecad15832c63d666c5913c7dd5fccdf409f155 | 5095bbe94f3af8dc3b14a331519cfee887f4c07e | /FarmWeb/Source/tools/ServerController.h | fdd9b98a7129601c4c21224d120a1e001b171406 | [] | no_license | sativa/apsim_development | efc2b584459b43c89e841abf93830db8d523b07a | a90ffef3b4ed8a7d0cce1c169c65364be6e93797 | refs/heads/master | 2020-12-24T06:53:59.364336 | 2008-09-17T05:31:07 | 2008-09-17T05:31:07 | 64,154,433 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 996 | h | //---------------------------------------------------------------------------
#ifndef ServerControllerH
#define ServerControllerH
//---------------------------------------------------------------------------
#include <Classes.hpp>
#include <IWServerControllerBase.hpp>
#include <IWApplication.hpp>
#include <IWInit.hpp>
#include "UserSessionUnit.h"
//---------------------------------------------------------------------------
class TIWServerController : public TIWServerControllerBase
{
__published: // IDE-managed Components
void __fastcall IWServerControllerBaseNewSession(
TIWApplication *ASession, TIWBaseForm *&VMainForm);
private: // User declarations
public: // User declarations
__fastcall TIWServerController(TComponent* Owner);
};
//---------------------------------------------------------------------------
extern PACKAGE TIWServerController *IWServerController;
//---------------------------------------------------------------------------
#endif
| [
"hol353@8bb03f63-af10-0410-889a-a89e84ef1bc8"
] | hol353@8bb03f63-af10-0410-889a-a89e84ef1bc8 |
82f2085cef5f131ad73c425255fffa68e66f09c5 | a5f35d0dfaddb561d3595c534b6b47f304dbb63d | /Source/BansheeEngine/GUI/BsGUIButton.h | db74872ab4441dfc094372fc6c7f31f229b8f874 | [] | no_license | danielkrupinski/BansheeEngine | 3ff835e59c909853684d4985bd21bcfa2ac86f75 | ae820eb3c37b75f2998ddeaf7b35837ceb1bbc5e | refs/heads/master | 2021-05-12T08:30:30.564763 | 2018-01-27T12:55:25 | 2018-01-27T12:55:25 | 117,285,819 | 1 | 0 | null | 2018-01-12T20:38:41 | 2018-01-12T20:38:41 | null | UTF-8 | C++ | false | false | 3,206 | h | //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
//**************** Copyright (c) 2016 Marko Pintera (marko.pintera@gmail.com). All rights reserved. **********************//
#pragma once
#include "BsPrerequisites.h"
#include "GUI/BsGUIButtonBase.h"
#include "GUI/BsGUIContent.h"
namespace bs
{
/** @addtogroup GUI
* @{
*/
/** GUI button that can be clicked. Has normal, hover and active states with an optional label. */
class BS_EXPORT GUIButton : public GUIButtonBase
{
public:
/**
* Returns type name of the GUI element used for finding GUI element styles.
*/
static const String& getGUITypeName();
/**
* Creates a new button with the specified label.
*
* @param[in] text Label to display on the button.
* @param[in] styleName Optional style to use for the element. Style will be retrieved from GUISkin of the
* GUIWidget the element is used on. If not specified default button style is used.
*/
static GUIButton* create(const HString& text, const String& styleName = StringUtil::BLANK);
/**
* Creates a new button with the specified label.
*
* @param[in] text Label to display on the button.
* @param[in] options Options that allow you to control how is the element positioned and sized.
* This will override any similar options set by style.
* @param[in] styleName Optional style to use for the element. Style will be retrieved from GUISkin of the
* GUIWidget the element is used on. If not specified default button style is used.
*/
static GUIButton* create(const HString& text, const GUIOptions& options, const String& styleName = StringUtil::BLANK);
/**
* Creates a new button with the specified label.
*
* @param[in] content Content to display on a button. May include a label, image and a tooltip.
* @param[in] styleName Optional style to use for the element. Style will be retrieved from GUISkin of the
* GUIWidget the element is used on. If not specified default button style is used.
*/
static GUIButton* create(const GUIContent& content, const String& styleName = StringUtil::BLANK);
/**
* Creates a new button with the specified label.
*
* @param[in] content Content to display on a button. May include a label, image and a tooltip.
* @param[in] options Options that allow you to control how is the element positioned and sized. This will
* override any similar options set by style.
* @param[in] styleName Optional style to use for the element. Style will be retrieved from GUISkin of the
* GUIWidget the element is used on. If not specified default button style is used.
*/
static GUIButton* create(const GUIContent& content, const GUIOptions& options, const String& styleName = StringUtil::BLANK);
public: // ***** INTERNAL ******
/** @name Internal
* @{
*/
/** @copydoc GUIElement::_getElementType */
ElementType _getElementType() const override { return ElementType::Button; }
/** @} */
private:
GUIButton(const String& styleName, const GUIContent& content, const GUIDimensions& dimensions);
};
/** @} */
} | [
"bearishsun@gmail.com"
] | bearishsun@gmail.com |
b9125585de6e1833d3e3581fcbbfcdb1445f8311 | ed6c9903832748003a9208112be9c3db184954dc | /doc/Programs/ParallelizationMPI/vectormatrixclass.cpp | b608779ae82f5093bb703ecfcadee9ec8b70ff8e | [
"CC0-1.0"
] | permissive | CompPhysics/ComputationalPhysics2 | ece24a2b16d7ed391c759765e228ddb484408757 | 73b364a3fc7df6e23e43876f1d5b6305a9f893cf | refs/heads/gh-pages | 2023-08-31T05:09:39.554926 | 2023-05-07T01:51:00 | 2023-05-07T01:51:00 | 28,933,001 | 128 | 65 | CC0-1.0 | 2022-03-03T21:50:27 | 2015-01-07T20:38:21 | null | UTF-8 | C++ | false | false | 13,875 | cpp |
#include "vectormatrixclass.h"
Point::Point(int dim){
dimension = dim;
data = new double[dimension];
for(int i=0;i<dimension;i++)
data[i] = 0.0;
}
Point::Point(const Point &v){
dimension = v.Dimension();
data = new double[dimension];
for(int i=0;i<dimension;i++)
data[i] = v.data[i];
}
Point::~Point(){
dimension = 0;
delete[] data;
data = NULL;
}
int Point::Dimension() const{
return(dimension);
}
double Point::operator()(const int i) const{
if(i>=0 && i<dimension)
return data[i];
cerr << "Point::Invalid index " << i << " for Point of dimension " << dimension << endl;
return(0);
}
double& Point::operator()(const int i){
if(i>=0 && i<dimension)
return data[i];
cerr << "Point::Invalid index " << i << " for Point of dimension " << dimension << endl;
return(data[0]);
}
Point& Point::operator=(const Point &v) {
dimension = v.Dimension();
for(int i=0;i<dimension;i++)
data[i] = v.data[i];
return *this;
};
void Point::Print() const{
cout << endl;
cout << "[ ";
if(dimension>0)
cout << data[0];
for(int i=1;i<dimension;i++)
cout << "; " << data[i];
cout << " ]" << endl;
}
Vector::Vector(){
dimension = 0;
data = NULL;
}
Vector::Vector(int dim){
dimension = dim;
data = new double[dimension];
for(int i=0;i<dimension;i++)
data[i] = 0.0;
}
Vector::Vector(const Vector &v){
dimension = v.Dimension();
data = new double[dimension];
for(int i=0;i<dimension;i++)
data[i] = v.data[i];
}
Vector::Vector(int col, const Matrix &A){
dimension = A.Rows();
data = new double[dimension];
for(int i=0;i<A.Rows();i++)
data[i] = A(i,col);
}
Vector::~Vector(){
dimension = 0;
delete[] data;
data = NULL;
}
void Vector::Initialize(int dim){
if(dimension!=0)
delete[] data;
dimension = dim;
data = new double[dimension];
for(int i=0;i<dimension;i++)
data[i] = 0.0;
}
int Vector::Dimension() const{
return(dimension);
}
double Vector::operator()(const int i) const{
if(i>=0 && i<dimension)
return data[i];
cerr << "Vector::Invalid index " << i << " for Vector of dimension " << dimension << endl;
return(0);
}
double& Vector::operator()(const int i){
if(i>=0 && i<dimension)
return data[i];
cerr << "Vector::Invalid index " << i << " for Vector of dimension " << dimension << endl;
return(data[0]);
}
Vector& Vector::operator=(const Vector &v) {
dimension = v.Dimension();
for(int i=0;i<dimension;i++)
data[i] = v.data[i];
return *this;
};
void Vector::Print() const{
cout << endl;
cout << "[ ";
if(dimension>0)
cout << data[0];
for(int i=1;i<dimension;i++)
cout << "; " << data[i];
cout << " ]" << endl;
}
double Vector::Norm_l1(){
double sum = 0.0;
for(int i=0;i<dimension;i++)
sum += fabs(data[i]);
return(sum);
}
double Vector::Norm_l2(){
double sum = 0.0;
for(int i=0;i<dimension;i++)
sum += data[i]*data[i];
return(sqrt(sum));
}
void Vector::Normalize(){
double tmp = 1.0/Norm_l2();
for(int i=0;i<dimension;i++)
data[i] = data[i]*tmp;
}
double Vector::Norm_linf(){
double maxval = 0.0,tmp;
for(int i=0;i<dimension;i++){
tmp = fabs(data[i]);
maxval = (maxval > tmp)?maxval:tmp;
}
return(maxval);
}
double Vector::MaxMod(){
double maxm = -1.0e+10;
for(int i=0; i<dimension; i++)
maxm = (maxm > fabs(data[i]))?maxm:fabs(data[i]);
return maxm;
}
double Vector::ElementofMaxMod(){
return(data[MaxModindex()]);
}
int Vector::MaxModindex(){
double maxm = -1.0e+10;
int maxmindex = 0;
for(int i=0; i<dimension; i++){
if(maxm<fabs(data[i])){
maxm = fabs(data[i]);
maxmindex = i;
}
}
return maxmindex;
}
void Vector::Initialize(double a){
for(int i=0; i<dimension; i++)
data[i] = a;
}
void Vector::Initialize(double *v){
for(int i=0; i<dimension; i++)
data[i] = v[i];
}
Matrix::Matrix(int dim){
rows = dim;
columns = dim;
data = new double*[rows];
for(int i=0;i<rows;i++){
data[i] = new double[columns];
for(int j=0;j<columns;j++)
data[i][j] = 0.0;
}
}
Matrix::Matrix(int rows1, int columns1){
rows = rows1;
columns = columns1;
data = new double*[rows];
for(int i=0;i<rows;i++){
data[i] = new double[columns];
for(int j=0;j<columns;j++)
data[i][j] = 0.0;
}
}
Matrix::Matrix(const Matrix& m){
rows = m.rows;
columns = m.columns;
data = new double*[rows];
for(int i=0;i<rows;i++){
data[i] = new double[columns];
for(int j=0; j<columns; j++)
data[i][j] = m.data[i][j];
}
}
Matrix::Matrix(int num_Vectors, const Vector * q){
rows = q[0].Dimension();
columns = num_Vectors;
data = new double*[rows];
for(int i=0;i<rows;i++){
data[i] = new double[columns];
for(int j=0; j<columns; j++)
data[i][j] = q[j](i);
}
}
Matrix::Matrix(int rows1, int columns1, double **rowptrs){
rows = rows1;
columns = columns1;
data = new double*[rows];
for(int i=0;i<rows;i++)
data[i] = rowptrs[i];
}
Matrix::~Matrix(){
for(int i=0;i<rows;i++)
delete[] data[i];
rows = 0;
columns = 0;
delete[] data;
}
int Matrix::Rows() const{
return(rows);
}
int Matrix::Columns() const{
return(columns);
}
double **Matrix::GetPointer(){
return(data);
}
void Matrix::GetColumn(int col, Vector &x){
x.Initialize(0.0);
for(int i=0;i<rows;i++)
x(i) = data[i][col];
}
void Matrix::GetColumn(int col, Vector &x, int rowoffset){
x.Initialize(0.0);
for(int i=0;i<rows-rowoffset;i++)
x(i) = data[i+rowoffset][col];
}
void Matrix::PutColumn(int col, const Vector &x){
for(int i=0;i<rows;i++)
data[i][col] = x(i);
}
double Matrix::Norm_linf(){
double maxval = 0.0,sum;
for(int i=0;i<rows;i++){
sum = 0.0;
for(int j=0;j<columns;j++)
sum += fabs(data[i][j]);
maxval = (maxval > sum)?maxval:sum;
}
return(maxval);
}
double Matrix::Norm_l1(){
double maxval = 0.0,sum;
for(int j=0;j<columns;j++){
sum = 0.0;
for(int i=0;i<rows;i++)
sum += fabs(data[i][j]);
maxval = (maxval > sum)?maxval:sum;
}
return(maxval);
}
Matrix& Matrix::operator=(const Matrix &m){
if( (rows == m.rows) && (columns == m.columns)){
for(int i=0; i<rows; i++)
for(int j=0;j<columns;j++){
data[i][j] = m.data[i][j];
}
}
else
cerr << "Matrix Error: Cannot equate matrices of different sizes\n";
return *this;
}
double Matrix::operator()(const int i, const int j) const {
if( (i>=0) && (j>=0) && (i<rows) && (j<columns))
return(data[i][j]);
else
cerr << "Matrix Error: Invalid Matrix indices (" << i << "," << j <<
"), for Matrix of size " << rows << " X " << columns << endl;
return((double)0);
}
double& Matrix::operator()(const int i, const int j) {
if( (i>=0) && (j>=0) && (i<rows) && (j<columns))
return(data[i][j]);
else
cerr << "Matrix Error: Invalid Matrix indices (" << i << "," << j <<
"), for Matrix of size " << rows << " X " << columns << endl;;
return(data[0][0]);
}
void Matrix::Print() const{
cout << endl;
cout << "[ ";
for(int i=0;i<rows;i++){
cout << data[i][0];
for(int j=1;j<columns;j++)
cout << " " << data[i][j];
if(i!=(rows-1))
cout << ";\n";
}
cout << " ]" << endl;
}
double Matrix::MaxModInRow(int row){
double maxv = -1.0e+10;
for(int i=0;i<columns;i++)
maxv = (fabs(data[row][i])>maxv)?fabs(data[row][i]):maxv;
return maxv;
}
double Matrix::MaxModInRow(int row, int starting_column){
double maxv = -1.0e+10;
for(int i=starting_column;i<columns;i++)
maxv = (fabs(data[row][i])>maxv)?fabs(data[row][i]):maxv;
return maxv;
}
int Matrix::MaxModInRowindex(int row){
int maxvindex = 0;
double maxv = -1.0e+10;
for(int i=0;i<columns;i++){
if(maxv < fabs(data[row][i])){
maxv = fabs(data[row][i]);
maxvindex = i;
}
}
return maxvindex;
}
int Matrix::MaxModInRowindex(int row, int starting_column){
int maxvindex = 0;
double maxv = -1.0e+10;
for(int i=starting_column;i<columns;i++){
if(maxv < fabs(data[row][i])){
maxv = fabs(data[row][i]);
maxvindex = i;
}
}
return maxvindex;
}
double Matrix::MaxModInColumn(int column){
double maxv = -1.0e+10;
for(int i=0;i<rows;i++)
maxv = (fabs(data[i][column])>maxv)?fabs(data[i][column]):maxv;
return maxv;
}
double Matrix::MaxModInColumn(int column, int starting_row){
double maxv = -1.0e+10;
for(int i=starting_row;i<rows;i++)
maxv = (fabs(data[i][column])>maxv)?fabs(data[i][column]):maxv;
return maxv;
}
int Matrix::MaxModInColumnindex(int column){
int maxvindex = 0;
double maxv = -1.0e+10;
for(int i=0;i<rows;i++){
if(maxv < fabs(data[i][column])){
maxv = fabs(data[i][column]);
maxvindex = i;
}
}
return maxvindex;
}
int Matrix::MaxModInColumnindex(int column, int starting_column){
int maxvindex = 0;
double maxv = -1.0e+10;
for(int i=starting_column;i<rows;i++){
if(maxv < fabs(data[i][column])){
maxv = fabs(data[i][column]);
maxvindex = i;
}
}
return maxvindex;
}
void Matrix::RowSwap(int row1, int row2){
double * tmp = data[row1];
data[row1] = data[row2];
data[row2] = tmp;
}
/****************************************************************/
/* Operator Definitions */
/****************************************************************/
Vector operator-(const Vector& v){
Vector x(v.Dimension());
for(int i=0;i<v.Dimension();i++)
x(i) = -v(i);
return x;
}
Vector operator+(const Vector& v1, const Vector& v2){
int min_dim = min_dimension(v1,v2);
Vector x(min_dim);
for(int i=0;i<min_dim;i++)
x(i) = v1(i) + v2(i);
return x;
}
Vector operator-(const Vector& v1, const Vector& v2){
int min_dim = min_dimension(v1,v2);
Vector x(min_dim);
for(int i=0;i<min_dim;i++)
x(i) = v1(i) - v2(i);
return x;
}
Vector operator/(const Vector& v, const double s) {
Vector x(v.Dimension());
for(int i=0;i<v.Dimension();i++)
x(i) = v(i)/s;
return x;
}
Vector operator*(const double s, const Vector &v) {
Vector x(v.Dimension());
for(int i=0;i<v.Dimension();i++)
x(i) = s*v(i);
return x;
}
Vector operator*(const Vector& v, const double s) {
Vector x(v.Dimension());
for(int i=0;i<v.Dimension();i++)
x(i) = s*v(i);
return x;
}
Vector operator*(const Matrix& A, const Vector& x){
int rows = A.Rows(), columns = A.Columns();
int dim = x.Dimension();
Vector b(dim);
if(columns != dim){
cerr << "Invalid dimensions given in matrix-vector multiply" << endl;
return(b);
}
for(int i=0;i<rows;i++){
b(i) = 0.0;
for(int j=0;j<columns;j++){
b(i) += A(i,j)*x(j);
}
}
return b;
}
/****************************************************************/
/* Function Definitions */
/****************************************************************/
int min_dimension(const Vector& v1, const Vector& v2){
int min_dim = (v1.Dimension()<v2.Dimension())?v1.Dimension():v2.Dimension();
return(min_dim);
}
double dot(const Vector& u, const Vector& v){
double sum = 0.0;
int min_dim = min_dimension(u,v);
for(int i=0;i<min_dim;i++)
sum += u(i)*v(i);
return sum;
}
double dot(int N, const Vector& u, const Vector& v){
double sum = 0.0;
for(int i=0;i<N;i++)
sum += u(i)*v(i);
return sum;
}
double dot(int N, double *a, double *b){
double sum = 0.0;
for(int i=0;i<N;i++)
sum += a[i]*b[i];
return sum;
}
/*******************************/
/* Log base 2 of a number */
/*******************************/
double log2(double x){
return(log(x)/log(2.0));
}
void Swap(double &a, double &b){
double tmp = a;
a = b;
b = tmp;
}
double Sign(double x){
double xs;
xs = (x>=0.0)?1.0:-1.0;
return xs;
}
//GammaF function valid for x integer, or x (integer+0.5)
double GammaF(double x){
double gamma = 1.0;
if (x == -0.5)
gamma = -2.0*sqrt(M_PI);
else if (!x) return gamma;
else if ((x-(int)x) == 0.5){
int n = (int) x;
double tmp = x;
gamma = sqrt(M_PI);
while(n--){
tmp -= 1.0;
gamma *= tmp;
}
}
else if ((x-(int)x) == 0.0){
int n = (int) x;
double tmp = x;
while(--n){
tmp -= 1.0;
gamma *= tmp;
}
}
return gamma;
}
int Factorial(int n){
int value=1;
for(int i=n;i>0;i--)
value = value*i;
return value;
}
double ** CreateMatrix(int m, int n){
double ** mat;
mat = new double*[m];
for(int i=0;i<m;i++){
mat[i] = new double[n];
for(int j=0;j<m;j++)
mat[i][j] = 0.0;
}
return mat;
}
int ** ICreateMatrix(int m, int n){
int ** mat;
mat = new int*[m];
for(int i=0;i<m;i++){
mat[i] = new int[n];
for(int j=0;j<m;j++)
mat[i][j] = 0;
}
return mat;
}
void DestroyMatrix(double ** mat, int m, int n){
for(int i=0;i<m;i++)
delete[] mat[i];
delete[] mat;
}
void IDestroyMatrix(int ** mat, int m, int n){
for(int i=0;i<m;i++)
delete[] mat[i];
delete[] mat;
}
| [
"morten.hjorth-jensen@fys.uio.no"
] | morten.hjorth-jensen@fys.uio.no |
9c7ec1eb5630dd5f749ee62f645a6c29511abad3 | 634120df190b6262fccf699ac02538360fd9012d | /Develop/Server/GameServerOck/main/GCmdHandler_Palette.cpp | 68577fa341ae22169eaa3fb8cfb3ba4e97651b05 | [] | no_license | ktj007/Raiderz_Public | c906830cca5c644be384e68da205ee8abeb31369 | a71421614ef5711740d154c961cbb3ba2a03f266 | refs/heads/master | 2021-06-08T03:37:10.065320 | 2016-11-28T07:50:57 | 2016-11-28T07:50:57 | 74,959,309 | 6 | 4 | null | 2016-11-28T09:53:49 | 2016-11-28T09:53:49 | null | UTF-8 | C++ | false | false | 3,690 | cpp | #include "StdAfx.h"
#include "GCmdHandler_Palette.h"
#include "CCommandTable.h"
#include "GPaletteSystem.h"
#include "GPlayerObjectManager.h"
#include "GGlobal.h"
GCmdHandler_Palette::GCmdHandler_Palette(MCommandCommunicator* pCC) : MCommandHandler(pCC)
{
SetCmdHandler(MC_PALETTE_SELECT_REQ, OnRequestSelect);
SetCmdHandler(MC_PALETTE_SET_PRIMARY_REQ, OnRequestSetPrimary);
SetCmdHandler(MC_PALETTE_SET_SECONDARY_REQ, OnRequestSetSecondary);
SetCmdHandler(MC_PALETTE_PUTUP_REQ, OnRequestPutUp);
SetCmdHandler(MC_PALETTE_PUTDOWN_REQ, OnRequestPutDown);
SetCmdHandler(MC_PALETTE_CHANGE_REQ, OnRequestChange);
}
MCommandResult GCmdHandler_Palette::OnRequestSelect(MCommand* pCmd, MCommandHandler* pHandler)
{
GEntityPlayer* pPlayer = gmgr.pPlayerObjectManager->GetEntityInWorld(pCmd->GetSenderUID());
if (NULL == pPlayer) return CR_FALSE;
PALETTE_NUM nNum;
if (pCmd->GetParameter(&nNum, 0, MPT_UCHAR)==false) return CR_FALSE;
gsys.pPaletteSystem->Select(pPlayer, nNum);
return CR_TRUE;
}
MCommandResult GCmdHandler_Palette::OnRequestSetPrimary(MCommand* pCmd, MCommandHandler* pHandler)
{
GEntityPlayer* pPlayer = gmgr.pPlayerObjectManager->GetEntityInWorld(pCmd->GetSenderUID());
if (NULL == pPlayer) return CR_FALSE;
PALETTE_NUM nNum;
if (pCmd->GetParameter(&nNum, 0, MPT_UCHAR)==false) return CR_FALSE;
gsys.pPaletteSystem->SetPrimary(pPlayer, nNum);
return CR_TRUE;
}
MCommandResult GCmdHandler_Palette::OnRequestSetSecondary(MCommand* pCmd, MCommandHandler* pHandler)
{
GEntityPlayer* pPlayer = gmgr.pPlayerObjectManager->GetEntityInWorld(pCmd->GetSenderUID());
if (NULL == pPlayer) return CR_FALSE;
PALETTE_NUM nNum;
if (pCmd->GetParameter(&nNum, 0, MPT_UCHAR)==false) return CR_FALSE;
gsys.pPaletteSystem->SetSecondary(pPlayer, nNum);
return CR_TRUE;
}
MCommandResult GCmdHandler_Palette::OnRequestPutUp(MCommand* pCmd, MCommandHandler* pHandler)
{
GEntityPlayer* pPlayer = gmgr.pPlayerObjectManager->GetEntityInWorld(pCmd->GetSenderUID());
if (NULL == pPlayer) return CR_FALSE;
PALETTE_NUM nNum;
PALETTE_SLOT nSlot;
PALETTE_ITEM_TYPE nType;
int nItemIDorTalentID;
if (pCmd->GetParameter(&nNum, 0, MPT_UCHAR)==false) return CR_FALSE;
if (pCmd->GetParameter(&nSlot, 1, MPT_UCHAR)==false) return CR_FALSE;
if (pCmd->GetParameter(&nType, 2, MPT_UCHAR)==false) return CR_FALSE;
if (pCmd->GetParameter(&nItemIDorTalentID, 3, MPT_INT)==false) return CR_FALSE;
gsys.pPaletteSystem->PutUp(pPlayer, nNum, nSlot, nType, nItemIDorTalentID);
return CR_TRUE;
}
MCommandResult GCmdHandler_Palette::OnRequestPutDown(MCommand* pCmd, MCommandHandler* pHandler)
{
GEntityPlayer* pPlayer = gmgr.pPlayerObjectManager->GetEntityInWorld(pCmd->GetSenderUID());
if (NULL == pPlayer) return CR_FALSE;
PALETTE_NUM nNum;
PALETTE_SLOT nSlot;
if (pCmd->GetParameter(&nNum, 0, MPT_UCHAR)==false) return CR_FALSE;
if (pCmd->GetParameter(&nSlot, 1, MPT_UCHAR)==false) return CR_FALSE;
gsys.pPaletteSystem->PutDown(pPlayer, nNum, nSlot);
return CR_TRUE;
}
MCommandResult GCmdHandler_Palette::OnRequestChange(MCommand* pCmd, MCommandHandler* pHandler)
{
GEntityPlayer* pPlayer = gmgr.pPlayerObjectManager->GetEntityInWorld(pCmd->GetSenderUID());
if (NULL == pPlayer) return CR_FALSE;
PALETTE_NUM nNum1;
PALETTE_SLOT nSlot1;
PALETTE_NUM nNum2;
PALETTE_SLOT nSlot2;
if (pCmd->GetParameter(&nNum1, 0, MPT_UCHAR)==false) return CR_FALSE;
if (pCmd->GetParameter(&nSlot1, 1, MPT_UCHAR)==false) return CR_FALSE;
if (pCmd->GetParameter(&nNum2, 2, MPT_UCHAR)==false) return CR_FALSE;
if (pCmd->GetParameter(&nSlot2, 3, MPT_UCHAR)==false) return CR_FALSE;
gsys.pPaletteSystem->Change(pPlayer, nNum1, nSlot1, nNum2, nSlot2);
return CR_TRUE;
} | [
"espause0703@gmail.com"
] | espause0703@gmail.com |
0bddbcf3e7e20993f734b4e378e47dbf5d44ee36 | 184af138d1d0e947c6fe97671f1fe826e285428c | /gst/libraries/chain/webassembly/wabt.cpp | 1c3a091c3d468d7f125510e91d18e67f82935603 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause",
"Apache-2.0"
] | permissive | gstchain/gstio | 11463cf6a5708438f07a8a6e9e02dcb40ac9560a | 8c8379e64881a6704dff02ffe9d3b5a5ea38e418 | refs/heads/master | 2023-05-23T04:04:29.723351 | 2021-06-15T02:07:43 | 2021-06-15T02:07:43 | 281,070,404 | 0 | 3 | null | 2021-06-15T02:07:44 | 2020-07-20T09:16:28 | C++ | UTF-8 | C++ | false | false | 4,844 | cpp | #include <gstio/chain/webassembly/wabt.hpp>
#include <gstio/chain/apply_context.hpp>
#include <gstio/chain/wasm_gstio_constraints.hpp>
//wabt includes
#include <src/interp.h>
#include <src/binary-reader-interp.h>
#include <src/error-formatter.h>
namespace gstio { namespace chain { namespace webassembly { namespace wabt_runtime {
//yep 🤮
static wabt_apply_instance_vars* static_wabt_vars;
using namespace wabt;
using namespace wabt::interp;
namespace wasm_constraints = gstio::chain::wasm_constraints;
class wabt_instantiated_module : public wasm_instantiated_module_interface {
public:
wabt_instantiated_module(std::unique_ptr<interp::Environment> e, std::vector<uint8_t> initial_mem, interp::DefinedModule* mod) :
_env(move(e)), _instatiated_module(mod), _initial_memory(initial_mem),
_executor(_env.get(), nullptr, Thread::Options(64*1024,
wasm_constraints::maximum_call_depth+2))
{
for(Index i = 0; i < _env->GetGlobalCount(); ++i) {
if(_env->GetGlobal(i)->mutable_ == false)
continue;
_initial_globals.emplace_back(_env->GetGlobal(i), _env->GetGlobal(i)->typed_value);
}
if(_env->GetMemoryCount())
_initial_memory_configuration = _env->GetMemory(0)->page_limits;
}
void apply(apply_context& context) override {
//reset mutable globals
for(const auto& mg : _initial_globals)
mg.first->typed_value = mg.second;
wabt_apply_instance_vars this_run_vars{nullptr, context};
static_wabt_vars = &this_run_vars;
//reset memory to inital size & copy back in initial data
if(_env->GetMemoryCount()) {
Memory* memory = this_run_vars.memory = _env->GetMemory(0);
memory->page_limits = _initial_memory_configuration;
memory->data.resize(_initial_memory_configuration.initial * WABT_PAGE_SIZE);
memset(memory->data.data(), 0, memory->data.size());
memcpy(memory->data.data(), _initial_memory.data(), _initial_memory.size());
}
_params[0].set_i64(uint64_t(context.receiver));
_params[1].set_i64(uint64_t(context.act.account));
_params[2].set_i64(uint64_t(context.act.name));
ExecResult res = _executor.RunStartFunction(_instatiated_module);
GST_ASSERT( res.result == interp::Result::Ok, wasm_execution_error, "wabt start function failure (${s})", ("s", ResultToString(res.result)) );
res = _executor.RunExportByName(_instatiated_module, "apply", _params);
GST_ASSERT( res.result == interp::Result::Ok, wasm_execution_error, "wabt execution failure (${s})", ("s", ResultToString(res.result)) );
}
private:
std::unique_ptr<interp::Environment> _env;
DefinedModule* _instatiated_module; //this is owned by the Environment
std::vector<uint8_t> _initial_memory;
TypedValues _params{3, TypedValue(Type::I64)};
std::vector<std::pair<Global*, TypedValue>> _initial_globals;
Limits _initial_memory_configuration;
Executor _executor;
};
wabt_runtime::wabt_runtime() {}
std::unique_ptr<wasm_instantiated_module_interface> wabt_runtime::instantiate_module(const char* code_bytes, size_t code_size, std::vector<uint8_t> initial_memory) {
std::unique_ptr<interp::Environment> env = std::make_unique<interp::Environment>();
for(auto it = intrinsic_registrator::get_map().begin() ; it != intrinsic_registrator::get_map().end(); ++it) {
interp::HostModule* host_module = env->AppendHostModule(it->first);
for(auto itf = it->second.begin(); itf != it->second.end(); ++itf) {
host_module->AppendFuncExport(itf->first, itf->second.sig, [fn=itf->second.func](const auto* f, const auto* fs, const auto& args, auto& res) {
TypedValue ret = fn(*static_wabt_vars, args);
if(ret.type != Type::Void)
res[0] = ret;
return interp::Result::Ok;
});
}
}
interp::DefinedModule* instantiated_module = nullptr;
wabt::Errors errors;
wabt::Result res = ReadBinaryInterp(env.get(), code_bytes, code_size, read_binary_options, &errors, &instantiated_module);
GST_ASSERT( Succeeded(res), wasm_execution_error, "Error building wabt interp: ${e}", ("e", wabt::FormatErrorsToString(errors, Location::Type::Binary)) );
return std::make_unique<wabt_instantiated_module>(std::move(env), initial_memory, instantiated_module);
}
void wabt_runtime::immediately_exit_currently_running_module() {
throw wasm_exit();
}
}}}}
| [
"gst1019@hotmail.com"
] | gst1019@hotmail.com |
a6626ac5330fd39684ce7d97e8033b580b99f3a0 | 656243ae84ca3a2280cc9cc3aad95afca8e10565 | /Code/CryEngine/CryScriptSystem/ScriptBindings/ScriptBinding.h | 6dcad09043166a670cc531160e647600e9a4b6b9 | [] | no_license | NightOwlsEntertainment/PetBox_A_Journey_to_Conquer_Elementary_Algebra | 914ff61bb210862401acb4d3a2eb19d323b00548 | 8383c5c1162d02310f460a1359f04891e5e85bff | refs/heads/master | 2021-01-22T09:48:55.961703 | 2015-11-11T11:26:27 | 2015-11-11T11:26:27 | 45,846,131 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,202 | h | ////////////////////////////////////////////////////////////////////////////
//
// Crytek Engine Source File.
// Copyright (C), Crytek Studios, 2001-2004.
// -------------------------------------------------------------------------
// File name: ScriptBinding.h
// Version: v1.00
// Created: 9/7/2004 by Timur.
// Compilers: Visual Studio.NET 2003
// Description:
// -------------------------------------------------------------------------
// History:
//
////////////////////////////////////////////////////////////////////////////
#ifndef __ScriptBinding_h__
#define __ScriptBinding_h__
#pragma once
class CScriptableBase;
//////////////////////////////////////////////////////////////////////////
class CScriptBindings
{
public:
CScriptBindings();
virtual ~CScriptBindings();
void Init( ISystem *pSystem,IScriptSystem *pSS );
void Done();
void LoadScriptedSurfaceTypes( const char *sFolder,bool bReload );
virtual void GetMemoryStatistics(ICrySizer *pSizer) const;
private:
std::vector<std::unique_ptr<CScriptableBase> > m_binds;
class CScriptSurfaceTypesLoader *m_pScriptSurfaceTypes;
};
#endif // __ScriptBinding_h__
| [
"jonathan.v.mendoza@gmail.com"
] | jonathan.v.mendoza@gmail.com |
6acefed61a752eee83d60922df3d3dd6928b9574 | 7ab3757bde602ebe0b2f9e49d7e1d5f672ee150a | /easyeditor/include/ee/ObjSelectionSet.h | a4c4d291a1f837ba202c8e30de274ed9e9d02f19 | [
"MIT"
] | permissive | brucelevis/easyeditor | 310dc05084b06de48067acd7ef5d6882fd5b7bba | d0bb660a491c7d990b0dae5b6fa4188d793444d9 | refs/heads/master | 2021-01-16T18:36:37.012604 | 2016-08-11T11:25:20 | 2016-08-11T11:25:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 415 | h | #ifndef _EASYEDITOR_OBJ_SELECTION_SET_H_
#define _EASYEDITOR_OBJ_SELECTION_SET_H_
#include "SelectionSet.h"
namespace ee
{
template<class T>
class ObjSelectionSet : public SelectionSet<T>
{
public:
virtual ~ObjSelectionSet();
virtual void Clear();
virtual void Add(T* item);
virtual void Remove(T* item);
}; // ObjSelectionSet
}
#include "ObjSelectionSet.inl"
#endif // _EASYEDITOR_OBJ_SELECTION_SET_H_ | [
"zhuguang@ejoy.com"
] | zhuguang@ejoy.com |
4d40b4c4b7d7163d8c97a265dfe7175a8aebd601 | 3007e411b14e6b285052c58c2e4848a99751387e | /Source/Classes/AppDelegate.cpp | 5138e1599c45f0480efb711a845ffe4a99af667b | [] | no_license | Hatch-ST/DoubleShip | 3d2fd8412ebbc630d2453b817a7404c7f344b292 | 31a26843e3becfc4bf0d78eb2c8e886f01eaec1b | refs/heads/master | 2021-01-20T22:28:21.469851 | 2015-04-20T10:15:22 | 2015-04-20T10:15:22 | 34,250,048 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,444 | cpp | #include "AppDelegate.h"
#include "TitleScene.h"
#include "GameMainScene.h"
USING_NS_CC;
AppDelegate::AppDelegate() {
}
AppDelegate::~AppDelegate()
{
}
bool AppDelegate::applicationDidFinishLaunching() {
// initialize director
CCDirector* pDirector = CCDirector::sharedDirector();
CCEGLView* pEGLView = CCEGLView::sharedOpenGLView();
pDirector->setOpenGLView(pEGLView);
// turn on display FPS
pDirector->setDisplayStats(false);
// set FPS. the default value is 1.0/60 if you don't call this
pDirector->setAnimationInterval(1.0 / 60);
CCEGLView::sharedOpenGLView()->setDesignResolutionSize(960, 540, kResolutionExactFit);
// create a scene. it's an autorelease object
CCScene *pScene = Title::scene();
// run
pDirector->runWithScene(pScene);
return true;
}
// This function will be called when the app is inactive. When comes a phone call,it's be invoked too
void AppDelegate::applicationDidEnterBackground() {
CCDirector::sharedDirector()->stopAnimation();
// if you use SimpleAudioEngine, it must be pause
// SimpleAudioEngine::sharedEngine()->pauseBackgroundMusic();
}
// this function will be called when the app is active again
void AppDelegate::applicationWillEnterForeground() {
CCDirector::sharedDirector()->startAnimation();
// if you use SimpleAudioEngine, it must resume here
// SimpleAudioEngine::sharedEngine()->resumeBackgroundMusic();
}
| [
"satoru-tk819@rb4.so-net.ne.jp"
] | satoru-tk819@rb4.so-net.ne.jp |
4aead3e9bc5ae60fa1e3bb5477da8151e03238d3 | 1a29bb587dcf09dac045320bf55974682a355fa3 | /test/testcase/pch.h | 7ef511c283934a444d39d0a8e2684e709cad3378 | [] | no_license | lcksfa/cmake_duilib | 272026833aaf6108c5527a7a73545cb476f74a08 | 50184bd216d34a880ed900c4fca0c0afc32cd90e | refs/heads/master | 2021-07-17T10:40:08.219072 | 2020-06-07T13:56:59 | 2020-06-07T13:56:59 | 159,792,859 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 22 | h | #include "catch.hpp"
| [
"yousaid820@163.com"
] | yousaid820@163.com |
eb1166f1c1ad16856be9bf55b588df0f2449ca21 | 3276ea06f50529fbe6552c263210ae887189f180 | /Source/Controls/GuiBasicControls.cpp | 842e371a6b2dda4150a080d7c3fa6de7a152a0d7 | [] | no_license | delta1766/GacUI | ee3246e4c58ef88c735b134cf887334b00df9bb1 | be4381701f1e38db72707c99ff9e0006aef008ec | refs/heads/master | 2021-08-24T13:34:44.173411 | 2017-12-10T02:04:20 | 2017-12-10T02:04:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,363 | cpp | #include "GuiBasicControls.h"
#include "GuiApplication.h"
#include "Templates/GuiThemeStyleFactory.h"
namespace vl
{
namespace presentation
{
namespace controls
{
using namespace elements;
using namespace compositions;
using namespace collections;
using namespace reflection::description;
/***********************************************************************
GuiControl
***********************************************************************/
void GuiControl::BeforeControlTemplateUninstalled()
{
}
void GuiControl::AfterControlTemplateInstalled(bool initialize)
{
controlTemplateObject->SetText(text);
controlTemplateObject->SetFont(font);
controlTemplateObject->SetVisuallyEnabled(isVisuallyEnabled);
controlTemplateObject->SetFocusableComposition(focusableComposition);
}
void GuiControl::CheckAndStoreControlTemplate(templates::GuiControlTemplate* value)
{
controlTemplateObject = value;
}
void GuiControl::EnsureControlTemplateExists()
{
if (!controlTemplateObject)
{
RebuildControlTemplate();
}
}
void GuiControl::RebuildControlTemplate()
{
bool initialize = controlTemplateObject == nullptr;
if (controlTemplateObject)
{
BeforeControlTemplateUninstalled();
containerComposition->GetParent()->RemoveChild(containerComposition);
boundsComposition->AddChild(containerComposition);
SafeDeleteComposition(controlTemplateObject);
controlTemplateObject = nullptr;
}
if (controlTemplate)
{
CheckAndStoreControlTemplate(controlTemplate({}));
}
else
{
CheckAndStoreControlTemplate(theme::GetCurrentTheme()->CreateStyle(controlThemeName)({}));
}
if (controlTemplateObject)
{
controlTemplateObject->SetAlignmentToParent(Margin(0, 0, 0, 0));
containerComposition->GetParent()->RemoveChild(containerComposition);
boundsComposition->AddChild(controlTemplateObject);
controlTemplateObject->GetContainerComposition()->AddChild(containerComposition);
AfterControlTemplateInstalled(initialize);
}
}
void GuiControl::OnChildInserted(GuiControl* control)
{
GuiControl* oldParent=control->parent;
children.Add(control);
control->parent=this;
control->OnParentChanged(oldParent, control->parent);
control->UpdateVisuallyEnabled();
}
void GuiControl::OnChildRemoved(GuiControl* control)
{
GuiControl* oldParent=control->parent;
control->parent=0;
children.Remove(control);
control->OnParentChanged(oldParent, control->parent);
}
void GuiControl::OnParentChanged(GuiControl* oldParent, GuiControl* newParent)
{
OnParentLineChanged();
}
void GuiControl::OnParentLineChanged()
{
for(vint i=0;i<children.Count();i++)
{
children[i]->OnParentLineChanged();
}
}
void GuiControl::OnRenderTargetChanged(elements::IGuiGraphicsRenderTarget* renderTarget)
{
RenderTargetChanged.Execute(GetNotifyEventArguments());
}
void GuiControl::OnBeforeReleaseGraphicsHost()
{
for(vint i=0;i<children.Count();i++)
{
children[i]->OnBeforeReleaseGraphicsHost();
}
}
void GuiControl::UpdateVisuallyEnabled()
{
bool newValue = isEnabled && (parent == 0 ? true : parent->GetVisuallyEnabled());
if (isVisuallyEnabled != newValue)
{
isVisuallyEnabled = newValue;
if (controlTemplateObject)
{
controlTemplateObject->SetVisuallyEnabled(isVisuallyEnabled);
}
VisuallyEnabledChanged.Execute(GetNotifyEventArguments());
for (vint i = 0; i < children.Count(); i++)
{
children[i]->UpdateVisuallyEnabled();
}
}
}
void GuiControl::SetFocusableComposition(compositions::GuiGraphicsComposition* value)
{
if (focusableComposition != value)
{
focusableComposition = value;
if (controlTemplateObject)
{
controlTemplateObject->SetFocusableComposition(focusableComposition);
}
}
}
bool GuiControl::IsAltEnabled()
{
GuiControl* control = this;
while (control)
{
if (!control->GetVisible() || !control->GetEnabled())
{
return false;
}
control = control->GetParent();
}
return true;
}
bool GuiControl::IsAltAvailable()
{
return focusableComposition != 0 && alt != L"";
}
compositions::GuiGraphicsComposition* GuiControl::GetAltComposition()
{
return boundsComposition;
}
compositions::IGuiAltActionHost* GuiControl::GetActivatingAltHost()
{
return activatingAltHost;
}
void GuiControl::OnActiveAlt()
{
SetFocus();
}
bool GuiControl::SharedPtrDestructorProc(DescriptableObject* obj, bool forceDisposing)
{
GuiControl* value=dynamic_cast<GuiControl*>(obj);
if(value->GetBoundsComposition()->GetParent())
{
if (!forceDisposing) return false;
}
SafeDeleteControl(value);
return true;
}
GuiControl::GuiControl(theme::ThemeName themeName)
:controlThemeName(themeName)
{
{
boundsComposition = new GuiBoundsComposition;
boundsComposition->SetAssociatedControl(this);
boundsComposition->SetMinSizeLimitation(GuiGraphicsComposition::LimitToElementAndChildren);
containerComposition = new GuiBoundsComposition;
containerComposition->SetTransparentToMouse(true);
containerComposition->SetMinSizeLimitation(GuiGraphicsComposition::LimitToElementAndChildren);
containerComposition->SetAlignmentToParent(Margin(0, 0, 0, 0));
boundsComposition->AddChild(containerComposition);
}
{
ControlTemplateChanged.SetAssociatedComposition(boundsComposition);
RenderTargetChanged.SetAssociatedComposition(boundsComposition);
VisibleChanged.SetAssociatedComposition(boundsComposition);
EnabledChanged.SetAssociatedComposition(boundsComposition);
VisuallyEnabledChanged.SetAssociatedComposition(boundsComposition);
AltChanged.SetAssociatedComposition(boundsComposition);
TextChanged.SetAssociatedComposition(boundsComposition);
FontChanged.SetAssociatedComposition(boundsComposition);
}
font = GetCurrentController()->ResourceService()->GetDefaultFont();
sharedPtrDestructorProc = &GuiControl::SharedPtrDestructorProc;
}
GuiControl::~GuiControl()
{
// prevent a root bounds composition from notifying its dead controls
if (!parent)
{
NotifyFinalizeInstance(boundsComposition);
}
if (tooltipControl)
{
// the only legal parent is the GuiApplication::sharedTooltipWindow
if (tooltipControl->GetBoundsComposition()->GetParent())
{
tooltipControl->GetBoundsComposition()->GetParent()->RemoveChild(tooltipControl->GetBoundsComposition());
}
delete tooltipControl;
}
for (vint i = 0; i < children.Count(); i++)
{
delete children[i];
}
children.Clear();
// let the root control of a control tree delete the whole composition tree
if (!parent)
{
delete boundsComposition;
}
}
compositions::GuiEventArgs GuiControl::GetNotifyEventArguments()
{
return GuiEventArgs(boundsComposition);
}
GuiControl::ControlTemplatePropertyType GuiControl::GetControlTemplate()
{
return controlTemplate;
}
void GuiControl::SetControlTemplate(const ControlTemplatePropertyType& value)
{
controlTemplate = value;
RebuildControlTemplate();
ControlTemplateChanged.Execute(GetNotifyEventArguments());
}
templates::GuiControlTemplate* GuiControl::GetControlTemplateObject()
{
EnsureControlTemplateExists();
return controlTemplateObject;
}
compositions::GuiBoundsComposition* GuiControl::GetBoundsComposition()
{
EnsureControlTemplateExists();
return boundsComposition;
}
compositions::GuiGraphicsComposition* GuiControl::GetContainerComposition()
{
EnsureControlTemplateExists();
return containerComposition;
}
compositions::GuiGraphicsComposition* GuiControl::GetFocusableComposition()
{
EnsureControlTemplateExists();
return focusableComposition;
}
GuiControl* GuiControl::GetParent()
{
return parent;
}
vint GuiControl::GetChildrenCount()
{
return children.Count();
}
GuiControl* GuiControl::GetChild(vint index)
{
return children[index];
}
bool GuiControl::AddChild(GuiControl* control)
{
return GetContainerComposition()->AddChild(control->GetBoundsComposition());
}
bool GuiControl::HasChild(GuiControl* control)
{
return children.Contains(control);
}
GuiControlHost* GuiControl::GetRelatedControlHost()
{
return parent?parent->GetRelatedControlHost():0;
}
bool GuiControl::GetVisuallyEnabled()
{
return isVisuallyEnabled;
}
bool GuiControl::GetEnabled()
{
return isEnabled;
}
void GuiControl::SetEnabled(bool value)
{
if(isEnabled!=value)
{
isEnabled=value;
EnabledChanged.Execute(GetNotifyEventArguments());
UpdateVisuallyEnabled();
}
}
bool GuiControl::GetVisible()
{
return isVisible;
}
void GuiControl::SetVisible(bool value)
{
boundsComposition->SetVisible(value);
if(isVisible!=value)
{
isVisible=value;
VisibleChanged.Execute(GetNotifyEventArguments());
}
}
const WString& GuiControl::GetAlt()
{
return alt;
}
bool GuiControl::SetAlt(const WString& value)
{
if (!IGuiAltAction::IsLegalAlt(value)) return false;
if (alt != value)
{
alt = value;
AltChanged.Execute(GetNotifyEventArguments());
}
return true;
}
void GuiControl::SetActivatingAltHost(compositions::IGuiAltActionHost* host)
{
activatingAltHost = host;
}
const WString& GuiControl::GetText()
{
return text;
}
void GuiControl::SetText(const WString& value)
{
if (text != value)
{
text = value;
if (controlTemplateObject)
{
controlTemplateObject->SetText(text);
}
TextChanged.Execute(GetNotifyEventArguments());
}
}
const FontProperties& GuiControl::GetFont()
{
return font;
}
void GuiControl::SetFont(const FontProperties& value)
{
if (font != value)
{
font = value;
if (controlTemplateObject)
{
controlTemplateObject->SetFont(font);
}
FontChanged.Execute(GetNotifyEventArguments());
}
}
void GuiControl::SetFocus()
{
if(focusableComposition)
{
GuiGraphicsHost* host=focusableComposition->GetRelatedGraphicsHost();
if(host)
{
host->SetFocus(focusableComposition);
}
}
}
description::Value GuiControl::GetTag()
{
return tag;
}
void GuiControl::SetTag(const description::Value& value)
{
tag=value;
}
GuiControl* GuiControl::GetTooltipControl()
{
return tooltipControl;
}
GuiControl* GuiControl::SetTooltipControl(GuiControl* value)
{
GuiControl* oldTooltipControl=tooltipControl;
tooltipControl=value;
return oldTooltipControl;
}
vint GuiControl::GetTooltipWidth()
{
return tooltipWidth;
}
void GuiControl::SetTooltipWidth(vint value)
{
tooltipWidth=value;
}
bool GuiControl::DisplayTooltip(Point location)
{
if(!tooltipControl) return false;
GetApplication()->ShowTooltip(this, tooltipControl, tooltipWidth, location);
return true;
}
void GuiControl::CloseTooltip()
{
if(GetApplication()->GetTooltipOwner()==this)
{
GetApplication()->CloseTooltip();
}
}
IDescriptable* GuiControl::QueryService(const WString& identifier)
{
if (identifier == IGuiAltAction::Identifier)
{
return (IGuiAltAction*)this;
}
else if (identifier == IGuiAltActionContainer::Identifier)
{
return 0;
}
else if(parent)
{
return parent->QueryService(identifier);
}
else
{
return 0;
}
}
/***********************************************************************
GuiCustomControl
***********************************************************************/
GuiCustomControl::GuiCustomControl(theme::ThemeName themeName)
:GuiControl(themeName)
{
}
GuiCustomControl::~GuiCustomControl()
{
FinalizeAggregation();
FinalizeInstanceRecursively(this);
}
}
}
} | [
"vczh@163.com"
] | vczh@163.com |
9744856c73a3a628e70fe77ce743b3522ab070b2 | bbeaadef08cccb872c9a1bb32ebac7335d196318 | /Fontes/Estudo/TFormEdtAlternativa.cpp | b1cf90d8702692fae1dc244aa72daddead0c4d8c | [] | no_license | danilodesouzapereira/plataformasinap_exportaopendss | d0e529b493f280aefe91b37e893359a373557ef8 | c624e9e078dce4b9bcc8e5b03dd4d9ea71c29b3f | refs/heads/master | 2023-03-20T20:37:21.948550 | 2021-03-12T17:53:12 | 2021-03-12T17:53:12 | 347,150,304 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 1,828 | cpp | // ---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop
#include "TFormEdtAlternativa.h"
#include "..\Planejamento\VTAlternativa.h"
#include "..\..\DLL_Inc\Funcao.h"
// ---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
// ---------------------------------------------------------------------------
__fastcall TFormEdtAlternativa::TFormEdtAlternativa(TComponent* Owner, VTAlternativa *alternativa)
: TForm(Owner)
{
//salva ponteiro
this->alternativa = alternativa;
//preenche dados existentes
EditCodigo->Text = alternativa->Codigo;
RichEditJustif->Text = alternativa->Justificativa;
}
// ---------------------------------------------------------------------------
__fastcall TFormEdtAlternativa::~TFormEdtAlternativa(void)
{
// nada a fazer
}
// ---------------------------------------------------------------------------
void __fastcall TFormEdtAlternativa::ActionCancelaExecute(TObject *Sender)
{
// fecha o form
ModalResult = mrCancel;
}
// ---------------------------------------------------------------------------
void __fastcall TFormEdtAlternativa::ActionConfirmaExecute(TObject *Sender)
{
// valida entrada de dado
if ((Trim(EditCodigo->Text)).IsEmpty())
{
Aviso("Preencha a identificação da alternativa");
return;
}
int length = (Trim(RichEditJustif->Text)).Length();
if (length > 4000)
{
Aviso("A justificativa está com " + IntToStr(length) + " caracteres e não pode ultrapassar 4000 caracteres");
return;
}
//preenche dados
alternativa->Codigo = EditCodigo->Text;
alternativa->Justificativa = RichEditJustif->Text;
// fecha o form
ModalResult = mrOk;
}
// ---------------------------------------------------------------------------
// eof
| [
"danilopereira@usp.br"
] | danilopereira@usp.br |
dddc6aadf3aab3a0fe97c9874f25459d0b57ab05 | 9d24bfcbde3ebd1c410c35404bd6a06c37694048 | /Shared.h | 45150bec185cd4f284bbd5d36d85a444216f0414 | [] | no_license | typcn/biliquery_db | 4fedfb7e714093e6047b944e09bd0b0ea3144b60 | 575c7df4593747e6c60908788b1ac1bbdb8950b8 | refs/heads/master | 2021-09-24T12:12:18.881607 | 2018-10-09T20:46:08 | 2018-10-09T20:46:08 | 109,018,519 | 23 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 2,229 | h | #ifndef shared_hpp
#define shared_hpp
#include <unordered_map>
class Hasher
{
public:
size_t operator() (uint32_t key) const
{
return key;
}
};
typedef std::unordered_multimap<uint32_t, uint32_t, Hasher> DirectMap;
const uint8_t hexmap[] =
{
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // !"#$%&'
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ()*+,-./
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, // 01234567
0x08, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // 89:;<=>?
0x00, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x00, // @ABCDEFG
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // HIJKLMNO
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // PQRSTUVW
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // XYZ[\]^_
0x00, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x00, // `abcdefg
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // hijklmno
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // pqrstuvw
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // xyz{|}~.
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // ........
};
#endif
| [
"admin@typcn.com"
] | admin@typcn.com |
56db24b9efad2c437df98edfe5bac98ae11a4cd2 | 6889db3d20e89307be1c3c3bd532a255efe29cc3 | /Assignment3/Client/include/ConnectionHandler.h | a2c2d4f0131e82bb2c999bd7d113dc1e171eefbf | [] | no_license | noatshuva/System-Programming | 72587f82aae8c67d03246a18ac8ecbb99761d738 | 328ba5b9124a9763a554bc4a7d7178aad9cfd17e | refs/heads/master | 2022-12-17T17:05:22.028059 | 2020-09-02T17:17:34 | 2020-09-02T17:17:34 | 292,345,859 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,849 | h | #ifndef CONNECTION_HANDLER__
#define CONNECTION_HANDLER__
#include <string>
#include <iostream>
#include <boost/asio.hpp>
#include "DataBase.h"
using boost::asio::ip::tcp;
class ConnectionHandler {
private:
const std::string host_;
const short port_;
boost::asio::io_service io_service_; // Provides core I/O functionality
tcp::socket socket_;
bool isTerminate;
public:
ConnectionHandler(std::string host, short port);
virtual ~ConnectionHandler();
// Connect to the remote machine
bool connect();
// Read a fixed number of bytes from the server - blocking.
// Returns false in case the connection is closed before bytesToRead bytes can be read.
bool getBytes(char bytes[], unsigned int bytesToRead);
// Send a fixed number of bytes from the client - blocking.
// Returns false in case the connection is closed before all the data is sent.
bool sendBytes(const char bytes[], int bytesToWrite);
// Read an ascii line from the server
// Returns false in case connection closed before a newline can be read.
bool getLine(std::string& line);
// Send an ascii line from the server
// Returns false in case connection closed before all the data is sent.
bool sendLine(std::string& line);
// Get Ascii data from the server until the delimiter character
// Returns false in case connection closed before null can be read.
bool getFrameAscii(std::string& frame, char delimiter);
// Send a message to the remote host.
// Returns false in case connection is closed before all the data is sent.
bool sendFrameAscii(const std::string& frame, char delimiter);
// Close down the connection properly.
void close();
bool shouldTerminate();
void terminate();
}; //class ConnectionHandler
#endif | [
"noa.tshuva3@gmail.com"
] | noa.tshuva3@gmail.com |
76658f0ca268680d222e1785c47795f265d77d5c | eea7adb1221e39e949e9f13b92805f1f63c61696 | /leetcode-01/cpp/leetcode/258. add-digits.cpp | 7b3d076c7a08bf502f3290367eee9cd3b3c1de3e | [] | no_license | zhangchunbao515/leetcode | 4fb7e5ac67a51679f5ba89eed56cd21f53cd736d | d191d3724f6f4b84a66d0917d16fbfc58205d948 | refs/heads/master | 2020-08-02T21:39:05.798311 | 2019-09-28T14:44:14 | 2019-09-28T14:44:14 | 211,514,370 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 168 | cpp | #include "public.h"
//8ms, 80.94%
//O(1)时间复杂度, 那么就是数学题
class Solution {
public:
int addDigits(int num) {
return ((num - 1) % 9) + 1;
}
};
| [
"zhangchunbao515@163.com"
] | zhangchunbao515@163.com |
beba373c713da6646cbf59bd6263099fd4b5c3b0 | 35b929181f587c81ad507c24103d172d004ee911 | /SrcLib/core/fwAtomsPatch/src/fwAtomsPatch/patcher/registry/detail.cpp | 05117851b2ef9554d8e10883cf9784080c6ce8d8 | [] | no_license | hamalawy/fw4spl | 7853aa46ed5f96660123e88d2ba8b0465bd3f58d | 680376662bf3fad54b9616d1e9d4c043d9d990df | refs/heads/master | 2021-01-10T11:33:53.571504 | 2015-07-23T08:01:59 | 2015-07-23T08:01:59 | 50,699,438 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 704 | cpp | /* ***** BEGIN LICENSE BLOCK *****
* FW4SPL - Copyright (C) IRCAD, 2009-2013.
* Distributed under the terms of the GNU Lesser General Public License (LGPL) as
* published by the Free Software Foundation.
* ****** END LICENSE BLOCK ****** */
#include <fwCore/util/LazyInstantiator.hpp>
#include "fwAtomsPatch/patcher/registry/detail.hpp"
namespace fwAtomsPatch
{
namespace patcher
{
namespace registry
{
struct FwDataRegistryInstantiatorTag {} ;
SPTR(Type) get()
{
typedef ::fwCore::util::LazyInstantiator< Type, FwDataRegistryInstantiatorTag > InstantiatorType;
return InstantiatorType::getInstance();
}
} // namespace registry
} // namespace patcher
} // namespace fwAtomsPatch
| [
"fbridault@IRCAD.FR"
] | fbridault@IRCAD.FR |
10f9a4bc5347d4ae8ddd34c5cbd79225ead0bdb6 | c2c73e1a8544366db75a64b8d15995c184e8efb1 | /src/psim/simulations/single_attitude_orbit.cpp | 1e70afb75cccc94bfdc7cc10f009fd7d279a4039 | [
"MIT"
] | permissive | pathfinder-for-autonomous-navigation/psim | 86be0b23f0ddb4289dcc708bfaccc482ce6aff22 | 073f7f67f8ce2102dab65d7e68f56abbacc2d098 | refs/heads/master | 2022-03-01T19:34:45.975219 | 2022-01-11T04:07:20 | 2022-01-11T04:07:20 | 206,230,836 | 5 | 10 | MIT | 2022-01-10T01:21:01 | 2019-09-04T04:25:18 | C++ | UTF-8 | C++ | false | false | 1,830 | cpp | //
// MIT License
//
// Copyright (c) 2020 Pathfinder for Autonomous Navigation (PAN)
//
// 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.
//
/** @file psim/simulations/single_attitude_orbit.cpp
* @author Kyle Krol
*/
#include <psim/simulations/single_attitude_orbit.hpp>
#include <psim/sensors/satellite_sensors.hpp>
#include <psim/truth/earth.hpp>
#include <psim/truth/satellite_truth.hpp>
#include <psim/truth/time.hpp>
namespace psim {
SingleAttitudeOrbitGnc::SingleAttitudeOrbitGnc(
RandomsGenerator &randoms, Configuration const &config)
: ModelList(randoms) {
// Truth model
add<Time>(randoms, config);
add<EarthGnc>(randoms, config);
add<SatelliteTruthGnc>(randoms, config, "leader");
// Sensors model
add<SatelliteSensors>(randoms, config, "leader");
}
} // namespace psim
| [
"noreply@github.com"
] | noreply@github.com |
f9bcf8e4dfa2d779a763b43179792ecf9f9de979 | c770d6f12c38047379f016f0a1fe0a7ccf3ba51e | /Simulation/1_3_3.cpp | 8bf887527eb9da624a8917ba725f87a574c26c3c | [] | no_license | irvanda/Traffic-intersection-modeling | de063fa4e16965deface4741d15aa5fe05083864 | cd3fde87ee20ae703584b21b92e39490502af8a1 | refs/heads/master | 2020-05-23T14:34:34.962057 | 2019-05-15T10:54:15 | 2019-05-15T10:54:15 | 186,807,117 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,428 | cpp | //----- Include files ----------------------------------------------------------
#include <iostream> // Needed for cout
#include <stdlib.h> // Needed for exit() and rand()
#include <math.h> // Needed for log()
#include <fstream> // Needed for I/O file
#include <algorithm> // Needed for max
using namespace std;
//----- Constants --------------------------------------------------------------
#define SIM_TIME 8.64e4 // Simulation time
#define GREEN 20000 // green light interval time
#define RED 60000 // red light interval time
#define ARR_TIME 3.00 // Mean time between arrivals in seconds
#define SERV_TIME 3.00 // Mean service time in seconds
//----- Function prototypes ----------------------------------------------------
double rand_val(int seed); // RNG for unif(0,1)
double exponential(double x); // Generate exponential RV with mean x
//===== Main program ===========================================================
int main(void)
{
ofstream output;
ofstream output3;
output.open ("output_debugging_1_3_3.txt");
output3.open ("output_1_3_3.txt");
cout << "Simulation time = " << SIM_TIME << endl;
cout << "Mean time between arrivals = " << ARR_TIME << endl;
cout << "Mean service time = " << SERV_TIME << endl;
cout << "Counter time for green = " << GREEN/1000 << endl;
cout << "Counter time for red = " << RED/1000 << endl;
output3 << " Simulation time = " << SIM_TIME << endl;
output3 << " Mean time = " << ARR_TIME << endl;
output3 << " Mean service time = " << SERV_TIME << endl;
output3 << "Counter time for green = " << GREEN/1000 << endl;
output3 << "Counter time for red = " << RED/1000 << endl;
double w_tot = 0.0, l_tot = 0.0;
int c_tot = 0;
unsigned int Max = 0;
double end_time = SIM_TIME; // Total time to simulate
double Ta = ARR_TIME; // Mean time between arrivals
double Ts = SERV_TIME; // Mean service time
double sim_time = 0.0; // Simulation time
double t1 = 0.0; // Time for next event #1 (arrival)
double t2 = SIM_TIME; // Time for next event #2 (departure)
unsigned int n = 0; // Number of customers in the system
unsigned int c = 0; // Number of service completions
double s = 0.0; // Area of number of customers in system
double tn = sim_time; // Variable for "last event time"
double l; // Mean number in the query server
double w; // Mean waiting time
double TL_red; // Traffic Light interval time for red light
double TL_green; // Traffic Light interval time for green light
bool green = true; // light condition
// Seed the RNG
int seed = (rand()%100 + time(NULL))%100;
rand_val(seed);
//initialize Traffic Light Timing
srand(seed);
int roll = rand()%10;
cout << "Roll = " << roll << endl;
if (roll >5)
{
green = false;
TL_red = double(rand()%RED)/1000;
TL_green = 20.00;
cout << endl << "pertama RED dengan waktu sisa " << TL_red << " s" << endl;
}
else
{
TL_green = double(rand()%GREEN)/1000;
TL_red = 60.00;
cout << endl << "pertama GREEN dengan waktu sisa " << TL_green << " s" << endl;
}
output << "===================================================================" << endl;
output << "debugging: " << endl << endl;
// Main simulation loop
while (sim_time < end_time)
{
if (green)
{
if (t1 < t2) // *** Event #1 (arrival) ***
{
sim_time = t1;
TL_green -= (sim_time - tn); // Update green time counter
s = s + n * (sim_time - tn); // Update area under "s" curve
n++;
Max = max(n, Max);
tn = sim_time; // tn = "last event time" for next event
output << "t1 = " << t1 << ", TL_green = " << TL_green << \
", n = " << n << ", sim_time = " << sim_time << endl;
t1 = sim_time + exponential(Ta);
if (n == 1)
t2 = sim_time + exponential(Ts);
if (TL_green < 0)
{
green = false;
TL_red += TL_green;
TL_green = 20.00;
}
}
else // *** Event #2 (departure) ***
{
sim_time = t2;
TL_green -= (sim_time - tn); // update red time counter
s = s + n * (sim_time - tn); // Update area under "s" curve
n--;
tn = sim_time; // tn = "last event time" for next event
c++; // Increment number of completions
output << "t2 = " << t2 << ", TL_green = " << TL_green << \
", n = " << n << ", C = " << c << ", sim_time = " << sim_time << endl;
if (n > 0)
t2 = sim_time + exponential(Ts);
else
t2 = SIM_TIME;
if (TL_green < (t2 - sim_time) && t2 != SIM_TIME)
{
if( t1 > (sim_time + TL_green))
{
green = false;
TL_red += TL_green -(min(t1,t2)-sim_time);
TL_green = 20.00;
}
}
}
}
else
{ //only arrival event occurs
sim_time = t1;
TL_red -= (sim_time - tn); // Update green time counter
s = s + n * (sim_time - tn); // Update area under "s" curve
n++;
tn = sim_time; // tn = "last event time" for next event
output << "t1 = " << t1 << ", TL_red = " << TL_red << \
", n = " << n << ", sim_time = " << sim_time << endl;
t1 = sim_time + exponential(Ta);
if (TL_red < (t1-sim_time))
{
green = true;
t2=sim_time+TL_red;
TL_red = 60.00;
}
}
}
// End of simulation
// Compute outputs
l = s / sim_time; // Compute mean number in system
w = s / c; // Compute mean time spent in the system
/*w_tot += w; I'm gonna use this later
l_tot += l;
c_tot += c;*/
cout << " Numb. of Completion Mean Numb. in System Mean System Time" << endl;
output << "Numb. of Completion Mean Numb. in System Mean System Time" << endl;
// Output results
cout << "Numb. of completion = " << c << endl << "Mean Numb. in system = " << l << endl << \
"Mean Response Time = " << w << endl;
output3 << "Numb. of completion = " << c << endl << "Mean Numb. in system = " << l << endl << \
"Mean Response Time = " << w << endl;
cout << "Max number in queue= " << Max << endl;
output3 << "Max number in queue= " << Max << endl;
output.close();
output3.close();
return(0);
}
//=========================================================================
//= Multiplicative LCG for generating uniform(0.0, 1.0) random numbers =
//= - x_n = 7^5*x_(n-1)mod(2^31 - 1) =
//= - With x seeded to 1 the 10000th x value should be 1043618065 =
//= - From R. Jain, "The Art of Computer Systems Performance Analysis," =
//= John Wiley & Sons, 1991. (Page 443, Figure 26.2) =
//= - Seed the RNG if seed > 0, return a unif(0,1) if seed == 0 =
//=========================================================================
double rand_val(int seed)
{
const long a = 16807; // Multiplier
const long m = 2147483647; // Modulus
const long q = 127773; // m div a
const long r = 2836; // m mod a
static long x; // Random int value (seed is set to 1)
long x_div_q; // x divided by q
long x_mod_q; // x modulo q
long x_new; // New x value
// Seed the RNG
if (seed != 0) x = seed;
// RNG using integer arithmetic
x_div_q = x / q;
x_mod_q = x % q;
x_new = (a * x_mod_q) - (r * x_div_q);
if (x_new > 0)
x = x_new;
else
x = x_new + m;
// Return a random value between 0.0 and 1.0
return((double) x / m);
}
//==============================================================================
//= Function to generate exponentially distributed RVs using inverse method =
//= - Input: x (mean value of distribution) =
//= - Output: Returns with exponential RV =
//==============================================================================
double exponential(double x)
{
double z; // Uniform random number from 0 to 1
// Pull a uniform RV (0 < z < 1)
do
{
z = rand_val(0);
}
while ((z == 0) || (z == 1));
return(-x * log(z));
}
| [
"noreply@github.com"
] | noreply@github.com |
d75ea5cb14819b8ecdef8e2f93bd0c8ee8c1d662 | 0272f2e67a09432d22e4f382125723777c27044d | /design-examples/trws/systemc/trws_acc.h | 9c437be286c65f3d818bb8724510e60181f4c277 | [
"BSD-3-Clause"
] | permissive | intel/rapid-design-methods-for-developing-hardware-accelerators | 027545835fef8daac9d43e731c09b9873fabb989 | 9a0afe216626b6d345b436ee4dce71511e8275f4 | refs/heads/master | 2023-05-27T13:25:30.640965 | 2023-01-07T00:07:05 | 2023-01-07T00:07:05 | 76,606,002 | 94 | 19 | BSD-3-Clause | 2019-06-01T20:30:48 | 2016-12-16T00:03:48 | C++ | UTF-8 | C++ | false | false | 9,589 | h | // See LICENSE for license details.
/*[[[cog
import cog
from cog_acctempl import *
from dut_params import *
]]]*/
//[[[end]]] (checksum: d41d8cd98f00b204e9800998ecf8427e)
/*[[[cog
cog.outl("#ifndef __%s_ACC_H__" % dut.nm.upper())
cog.outl("#define __%s_ACC_H__" % dut.nm.upper())
]]]*/
#ifndef __TRWS_ACC_H__
#define __TRWS_ACC_H__
//[[[end]]] (checksum: 1df28a537af2a31b305bbd09860812ef)
#include "accelerator_interface.h"
#include "accelerator_template.h"
/*[[[cog
cog.outl("class %s_acc : public accelerator_interface<Config> {" % dut.nm)
]]]*/
class trws_acc : public accelerator_interface<Config> {
//[[[end]]] (checksum: 12f2cfddf8abcddf35e1591211255dab)
public:
// load/store units
/*[[[cog
for p in dut.inps:
cog.outl("typedef %s %sLoadParams;" % (p.loadUnitType(), p.nm))
for p in dut.outs:
cog.outl("typedef %s %sStoreParams;" % (p.storeUnitType(),p.nm))
for p in dut.inps:
cog.outl("AccIn<%sLoadParams> %s_mem_in;" % (p.nm,p.nm))
for p in dut.outs:
cog.outl("AccOut<%sStoreParams> %s_mem_out;" % (p.nm,p.nm))
]]]*/
typedef LoadUnitParams< UCacheLine, __gi_Slots__, 1 << 28, 1> giLoadParams;
typedef LoadUnitParams< CacheLine, __wi_Slots__, 1 << 28, 1> wiLoadParams;
typedef LoadUnitParams< UCacheLine, __mi_Slots__, 1 << 28, 1> miLoadParams;
typedef LoadUnitParams< Pair, __inp_Slots__, 1 << 28, 1> inpLoadParams;
typedef StoreUnitParams< UCacheLine> moStoreParams;
AccIn<giLoadParams> gi_mem_in;
AccIn<wiLoadParams> wi_mem_in;
AccIn<miLoadParams> mi_mem_in;
AccIn<inpLoadParams> inp_mem_in;
AccOut<moStoreParams> mo_mem_out;
//[[[end]]] (checksum: 34cb1a117ceb1c75900177faa5b8ef37)
/*[[[cog
cog.outl("MemArbiter<%d, SplMemWriteReqType, SplMemWriteRespType> wr_arbiter;" % (len(dut.outs),))
cog.outl("MemArbiter<%d, SplMemReadReqType, SplMemReadRespType> rd_arbiter;" % (len(dut.inps),))
]]]*/
MemArbiter<1, SplMemWriteReqType, SplMemWriteRespType> wr_arbiter;
MemArbiter<4, SplMemReadReqType, SplMemReadRespType> rd_arbiter;
//[[[end]]] (checksum: 1545520f9420c3ef512dca31ff5d4477)
// main compute block
/*[[[cog
cog.outl("%s_hls dut;" % dut.nm)
]]]*/
trws_hls dut;
//[[[end]]] (checksum: c43ec93c8afec58733eed673805b151d)
// channels to connect components above
sc_signal<bool> wr_arb_idle, rd_arb_idle, acc_done, overall_done;
/*[[[cog
for p in dut.inps:
cog.outl("AccIn<%sLoadParams>::ChannelToArbiter %s_mem_in_arb_ch;" % (p.nm,p.nm))
for p in dut.outs:
cog.outl("AccOut<%sStoreParams >::ChannelToArbiter %s_mem_out_arb_ch;" % (p.nm,p.nm))
for p in dut.inps:
cog.outl("ga::tlm_fifo<%s > %s;" % (p.reqTy(),p.reqNm()))
cog.outl("ga::tlm_fifo<%s > %s;" % (p.respTy(),p.respNm()))
for p in dut.outs:
cog.outl("ga::tlm_fifo<%s > %s;" % (p.reqTy(),p.reqNm()))
cog.outl("ga::tlm_fifo<%s > %s;" % (p.dataTy(),p.dataNm()))
]]]*/
AccIn<giLoadParams>::ChannelToArbiter gi_mem_in_arb_ch;
AccIn<wiLoadParams>::ChannelToArbiter wi_mem_in_arb_ch;
AccIn<miLoadParams>::ChannelToArbiter mi_mem_in_arb_ch;
AccIn<inpLoadParams>::ChannelToArbiter inp_mem_in_arb_ch;
AccOut<moStoreParams >::ChannelToArbiter mo_mem_out_arb_ch;
ga::tlm_fifo<MemTypedReadReqType<UCacheLine> > giReq;
ga::tlm_fifo<MemTypedReadRespType<UCacheLine> > giResp;
ga::tlm_fifo<MemTypedReadReqType<CacheLine> > wiReq;
ga::tlm_fifo<MemTypedReadRespType<CacheLine> > wiResp;
ga::tlm_fifo<MemTypedReadReqType<UCacheLine> > miReq;
ga::tlm_fifo<MemTypedReadRespType<UCacheLine> > miResp;
ga::tlm_fifo<MemTypedReadReqType<Pair> > inpReq;
ga::tlm_fifo<MemTypedReadRespType<Pair> > inpResp;
ga::tlm_fifo<MemTypedWriteReqType<UCacheLine> > moReq;
ga::tlm_fifo<MemTypedWriteDataType<UCacheLine> > moData;
//[[[end]]] (checksum: 58cf76df2eeb598b0c46f08ae8c023ee)
//
SimpleGate<3, GATE_AND> and_gate;
IdleMonitor<8> idle_monitor;
/*[[[cog
cog.outl("SC_HAS_PROCESS(%s_acc);" % dut.nm)
]]]*/
SC_HAS_PROCESS(trws_acc);
//[[[end]]] (checksum: 06e71829e12da9700609157456e357f0)
/*[[[cog
cog.outl("""%s_acc(sc_module_name name = sc_gen_unique_name("%s_acc")) :""" % (dut.nm,dut.nm))
]]]*/
trws_acc(sc_module_name name = sc_gen_unique_name("trws_acc")) :
//[[[end]]] (checksum: ca1b44b1ddeafec1120d09c16dcce335)
accelerator_interface<Config>(name)
/*[[[cog
for p in dut.inps:
cog.outl(""", %s_mem_in("%s_mem_in")""" % (p.nm,p.nm))
for p in dut.outs:
cog.outl(""", %s_mem_out("%s_mem_out")""" % (p.nm,p.nm))
]]]*/
, gi_mem_in("gi_mem_in")
, wi_mem_in("wi_mem_in")
, mi_mem_in("mi_mem_in")
, inp_mem_in("inp_mem_in")
, mo_mem_out("mo_mem_out")
//[[[end]]] (checksum: 4dc4b12c7cc9bbbf3f772643d5db7d01)
, dut("dut")
, wr_arb_idle("wr_arb_idle")
, rd_arb_idle("rd_arb_idle")
, acc_done("acc_done")
, overall_done("overall_done")
/*[[[cog
for p in dut.inps:
cog.outl(""", %s("%s")""" % (p.reqNm(),p.reqNm()))
cog.outl(""", %s("%s")""" % (p.respNm(),p.respNm()))
for p in dut.outs:
cog.outl(""", %s("%s")""" % (p.reqNm(),p.reqNm()))
cog.outl(""", %s("%s")""" % (p.dataNm(),p.dataNm()))
]]]*/
, giReq("giReq")
, giResp("giResp")
, wiReq("wiReq")
, wiResp("wiResp")
, miReq("miReq")
, miResp("miResp")
, inpReq("inpReq")
, inpResp("inpResp")
, moReq("moReq")
, moData("moData")
//[[[end]]] (checksum: c11a3b1f02f5035cd5f42644e0d80a41)
, idle_monitor("idle_monitor")
{
/*[[[cog
for idx,p in enumerate(dut.inps):
cog.outl("%s_mem_in_arb_ch.bindArbiter<%d>(rd_arbiter,%d,%s_mem_in);" % (p.nm,len(dut.inps),idx,p.nm))
for idx,p in enumerate(dut.outs):
cog.outl("%s_mem_out_arb_ch.bindArbiter<%d>(wr_arbiter,%d,%s_mem_out);" % (p.nm,len(dut.outs),idx,p.nm))
]]]*/
gi_mem_in_arb_ch.bindArbiter<4>(rd_arbiter,0,gi_mem_in);
wi_mem_in_arb_ch.bindArbiter<4>(rd_arbiter,1,wi_mem_in);
mi_mem_in_arb_ch.bindArbiter<4>(rd_arbiter,2,mi_mem_in);
inp_mem_in_arb_ch.bindArbiter<4>(rd_arbiter,3,inp_mem_in);
mo_mem_out_arb_ch.bindArbiter<1>(wr_arbiter,0,mo_mem_out);
//[[[end]]] (checksum: 9ce01dc5c66951b8ee2bb26d33b4b523)
rd_arbiter.clk(clk);
rd_arbiter.rst(rst);
wr_arbiter.clk(clk);
wr_arbiter.rst(rst);
/*[[[cog
for p in dut.inps:
cog.outl("%s_mem_in.clk(clk);" % (p.nm,))
cog.outl("%s_mem_in.rst(rst);" % (p.nm,))
for p in dut.outs:
cog.outl("%s_mem_out.clk(clk);" % (p.nm,))
cog.outl("%s_mem_out.rst(rst);" % (p.nm,))
]]]*/
gi_mem_in.clk(clk);
gi_mem_in.rst(rst);
wi_mem_in.clk(clk);
wi_mem_in.rst(rst);
mi_mem_in.clk(clk);
mi_mem_in.rst(rst);
inp_mem_in.clk(clk);
inp_mem_in.rst(rst);
mo_mem_out.clk(clk);
mo_mem_out.rst(rst);
//[[[end]]] (checksum: 43c2094e1752505c8d0e9e774628216a)
idle_monitor.clk(clk);
idle_monitor.rst(rst);
dut.clk(clk);
dut.rst(rst);
dut.start(start);
dut.config(config);
/*[[[cog
for p in dut.inps:
cog.outl("dut.%s(%s);" % (p.reqNmK(),p.reqNm()))
cog.outl("%s_mem_in.acc_req_in(%s);" % (p.nm,p.reqNm()))
cog.outl("")
cog.outl("dut.%s(%s);" % (p.respNmK(),p.respNm()))
cog.outl("%s_mem_in.acc_resp_out(%s);" % (p.nm,p.respNm()))
cog.outl("")
for p in dut.outs:
cog.outl("dut.%s(%s);" % (p.reqNmK(),p.reqNm()))
cog.outl("%s_mem_out.acc_req_in(%s);" % (p.nm,p.reqNm()))
cog.outl("")
cog.outl("dut.%s(%s);" % (p.dataNmK(),p.dataNm()))
cog.outl("%s_mem_out.acc_data_in(%s);" % (p.nm,p.dataNm()))
cog.outl("")
]]]*/
dut.giReqOut(giReq);
gi_mem_in.acc_req_in(giReq);
dut.giRespIn(giResp);
gi_mem_in.acc_resp_out(giResp);
dut.wiReqOut(wiReq);
wi_mem_in.acc_req_in(wiReq);
dut.wiRespIn(wiResp);
wi_mem_in.acc_resp_out(wiResp);
dut.miReqOut(miReq);
mi_mem_in.acc_req_in(miReq);
dut.miRespIn(miResp);
mi_mem_in.acc_resp_out(miResp);
dut.inpReqOut(inpReq);
inp_mem_in.acc_req_in(inpReq);
dut.inpRespIn(inpResp);
inp_mem_in.acc_resp_out(inpResp);
dut.moReqOut(moReq);
mo_mem_out.acc_req_in(moReq);
dut.moDataOut(moData);
mo_mem_out.acc_data_in(moData);
//[[[end]]] (checksum: 1bf71aedcdd2c57919c523212d62bcf7)
rd_arbiter.out_req_fifo(spl_rd_req);
rd_arbiter.in_resp_fifo(spl_rd_resp);
wr_arbiter.out_req_fifo(spl_wr_req);
wr_arbiter.in_resp_fifo(spl_wr_resp);
// idle/done ANDing
wr_arbiter.idle(wr_arb_idle);
and_gate.ins[0](wr_arb_idle);
rd_arbiter.idle(rd_arb_idle);
and_gate.ins[1](rd_arb_idle);
dut.done(acc_done);
and_gate.ins[2](acc_done);
and_gate.out(overall_done);
idle_monitor.in_idle(overall_done);
idle_monitor.out_idle(done);
}
};
#endif
| [
"steven.m.burns@intel.com"
] | steven.m.burns@intel.com |
838e41f2f0880d12f11d96227307da2991799c58 | b9ab0973a86955a0ac264d03e764934db4d88025 | /src/Game.cpp | 277820a7e2ddda249e1c80530472dab445e3ff21 | [] | no_license | swarzzy/factory-game | b7ef7d76b8b34e1adb7cc4c1e7ba3666cb0daa50 | 8229ce1cd5025a9ea6c79fd837795b6ebf4505de | refs/heads/master | 2022-12-11T03:16:49.346513 | 2020-07-05T16:15:36 | 2020-07-05T16:15:36 | 262,098,096 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 38,853 | cpp | #include "Game.h"
#include "Platform.h"
#include "DebugOverlay.h"
#include "Resource.h"
#include "entities/Player.h"
#include "entities/Container.h"
#include "entities/Pipe.h"
#include "entities/Pickup.h"
#include "entities/Belt.h"
#include "entities/Extractor.h"
#include "entities/Projectile.h"
#include "EntityTraits.h"
#include "SaveAndLoad.h"
#include "Globals.h"
#include <stdlib.h>
ItemUseResult GrenadeUse(ItemID id, Entity* user) {
ItemUseResult result {};
result.destroyAfterUse = true;
if (user->type == EntityType::Player) {
auto player = (Player*)user;
auto throwDir = player->lookDir;
auto throwPos = WorldPos::Offset(player->p, V3(0.0f, player->height - 0.2f, 0.0f));
auto grenade = CreateProjectile(throwPos);
if (grenade) {
result.used = true;
grenade->velocity += throwDir * 100.0f;
}
}
return result;
}
void RegisterBuiltInEntities(Context* context) {
auto entityInfo = &context->entityInfo;
{ // Traits
auto belt = EntityInfoRegisterTrait(entityInfo);
assert(belt->id == (u32)Trait::Belt);
belt->name = "Belt";
auto itemExchange = EntityInfoRegisterTrait(entityInfo);
assert(itemExchange->id == (u32)Trait::ItemExchange);
itemExchange->name = "Item exchange";
auto handUsable = EntityInfoRegisterTrait(entityInfo);
assert(handUsable->id == (u32)Trait::HandUsable);
handUsable->name = "Hand usable";
}
{ // Entities
auto container = EntityInfoRegisterEntity<Container>(entityInfo, EntityKind::Block);
assert(container->typeID == (u32)EntityType::Container);
container->Create = CreateContainerEntity;
container->name = "Container";
container->DropPickup = ContainerDropPickup;
container->Behavior = ContainerUpdateAndRender;
container->UpdateAndRenderUI = ContainerUpdateAndRenderUI;
container->Delete = DeleteContainer;
container->Serialize = ContainerSerialize;
container->Deserialize = ContainerDeserialize;
container->hasUI = true;
REGISTER_ENTITY_TRAIT(container, Container, itemExchangeTrait, Trait::ItemExchange);
auto pipe = EntityInfoRegisterEntity<Pipe>(entityInfo, EntityKind::Block);
assert(pipe->typeID == (u32)EntityType::Pipe);
pipe->Create = CreatePipeEntity;
pipe->name = "Pipe";
pipe->DropPickup = PipeDropPickup;
pipe->Behavior = PipeUpdateAndRender;
pipe->UpdateAndRenderUI = PipeUpdateAndRenderUI;
pipe->Serialize = PipeSerialize;
pipe->Deserialize = PipeDeserialize;
auto belt = EntityInfoRegisterEntity<Belt>(entityInfo, EntityKind::Block);
assert(belt->typeID == (u32)EntityType::Belt);
belt->Create = CreateBelt;
belt->name = "Belt";
belt->DropPickup = BeltDropPickup;
belt->Behavior = BeltBehavior;
belt->Serialize = BeltSerialize;
belt->Deserialize = BeltDeserialize;
REGISTER_ENTITY_TRAIT(belt, Belt, belt, Trait::Belt);
auto extractor = EntityInfoRegisterEntity<Extractor>(entityInfo, EntityKind::Block);
assert(extractor->typeID == (u32)EntityType::Extractor);
extractor->Create = CreateExtractor;
extractor->name = "Extractor";
extractor->DropPickup = ExtractorDropPickup;
extractor->Behavior = ExtractorBehavior;
extractor->UpdateAndRenderUI = ExtractorUpdateAndRenderUI;
extractor->Serialize = ExtractorSerialize;
extractor->Deserialize = ExtractorDeserialize;
REGISTER_ENTITY_TRAIT(extractor, Extractor, itemExchangeTrait, Trait::ItemExchange);
//REGISTER_ENTITY_TRAIT(extractor, Extractor, testTrait, Trait::Test);
// TODO: Remove
auto barrel = EntityInfoRegisterEntity<u32>(entityInfo, EntityKind::Block);
assert(barrel->typeID == (u32)EntityType::Barrel);
barrel->name = "Barrel";
// TODO: remove
auto tank = EntityInfoRegisterEntity<u32>(entityInfo, EntityKind::Block);
assert(tank->typeID == (u32)EntityType::Tank);
tank->name = "Tank";
auto pickup = EntityInfoRegisterEntity<Pickup>(entityInfo, EntityKind::Spatial);
assert(pickup->typeID == (u32)EntityType::Pickup);
pickup->Create = CreatePickupEntity;
pickup->name = "Pickup";
pickup->Behavior = PickupUpdateAndRender;
pickup->Serialize = SerializePickup;
pickup->Deserialize = DeserializePickup;
auto projectile = EntityInfoRegisterEntity<Projectile>(entityInfo, EntityKind::Spatial);
assert(projectile->typeID == (u32)EntityType::Projectile);
projectile->Create = CreateProjectileEntity;
projectile->name = "Projectile";
projectile->Behavior = ProjectileUpdateAndRender;
projectile->CollisionResponse = ProjectileCollisionResponse;
auto player = EntityInfoRegisterEntity<Player>(entityInfo, EntityKind::Spatial);
assert(player->typeID == (u32)EntityType::Player);
player->Create = CreatePlayerEntity;
player->name = "Player";
player->ProcessOverlap = PlayerProcessOverlap;
player->Behavior = PlayerUpdateAndRender;
player->UpdateAndRenderUI = PlayerUpdateAndRenderUI;
player->hasUI = true;
player->Delete = DeletePlayer;
assert(entityInfo->entityTable.count == ((u32)EntityType::_Count - 1));
}
{ // Items
auto container = EntityInfoRegisterItem(entityInfo);
assert(container->id == (u32)Item::Container);
container->name = "Container";
container->convertsToBlock = false;
container->associatedEntityTypeID = (u32)EntityType::Container;
container->mesh = context->containerMesh;
container->material = &context->containerMaterial;
container->icon = &context->containerIcon;
auto stone = EntityInfoRegisterItem(entityInfo);
assert(stone->id == (u32)Item::Stone);
stone->name = "Stone";
stone->convertsToBlock = true;
stone->associatedBlock = BlockValue::Stone;
stone->material = &context->stoneMaterial;
stone->icon = &context->stoneDiffuse;
auto grass = EntityInfoRegisterItem(entityInfo);
assert(grass->id == (u32)Item::Grass);
grass->name = "Grass";
grass->convertsToBlock = true;
grass->associatedBlock = BlockValue::Grass;
grass->material = &context->grassMaterial;
grass->icon = &context->grassDiffuse;
auto coalOre = EntityInfoRegisterItem(entityInfo);
assert(coalOre->id == (u32)Item::CoalOre);
coalOre->name = "Coal ore";
coalOre->convertsToBlock = true;
coalOre->associatedBlock = BlockValue::CoalOre;
coalOre->mesh = context->coalOreMesh;
coalOre->material = &context->coalOreMaterial;
coalOre->icon = &context->coalIcon;
coalOre->beltAlign = 0.4f;
coalOre->beltScale = 0.5f;
auto pipe = EntityInfoRegisterItem(entityInfo);
assert(pipe->id == (u32)Item::Pipe);
pipe->name = "Pipe";
pipe->convertsToBlock = false;
pipe->associatedEntityTypeID = (u32)EntityType::Pipe;
pipe->mesh = context->pipeStraightMesh;
pipe->material = &context->pipeMaterial;
pipe->beltScale = 0.35f;
pipe->icon = &context->pipeIcon;
auto belt = EntityInfoRegisterItem(entityInfo);
assert(belt->id == (u32)Item::Belt);
belt->name = "Belt";
belt->convertsToBlock = false;
belt->associatedEntityTypeID = (u32)EntityType::Belt;
belt->mesh = context->beltStraightMesh;
belt->material = &context->beltMaterial;
belt->icon = &context->beltIcon;
auto extractor = EntityInfoRegisterItem(entityInfo);
assert(extractor->id == (u32)Item::Extractor);
extractor->name = "Extractor";
extractor->convertsToBlock = false;
extractor->associatedEntityTypeID = (u32)EntityType::Extractor;
extractor->mesh = context->extractorMesh;
extractor->material = &context->extractorMaterial;
extractor->icon = &context->extractorIcon;
auto barrel = EntityInfoRegisterItem(entityInfo);
assert(barrel->id == (u32)Item::Barrel);
barrel->name = "Barrel";
barrel->convertsToBlock = false;
barrel->associatedEntityTypeID = (u32)EntityType::Barrel;
auto tank = EntityInfoRegisterItem(entityInfo);
assert(tank->id == (u32)Item::Tank);
tank->name = "Tank";
tank->convertsToBlock = false;
tank->associatedEntityTypeID = (u32)EntityType::Tank;
auto water = EntityInfoRegisterItem(entityInfo);
assert(water->id == (u32)Item::Water);
water->name = "Water";
water->convertsToBlock = true;
water->associatedBlock = BlockValue::Water;
water->material = &context->waterMaterial;
auto coalOreBlock = EntityInfoRegisterItem(entityInfo);
assert(coalOreBlock->id == (u32)Item::CoalOreBlock);
coalOreBlock->name = "CoalOreBlock";
coalOreBlock->convertsToBlock = true;
coalOreBlock->associatedBlock = BlockValue::CoalOre;
coalOreBlock->material = &context->coalOreBlockMaterial;
coalOreBlock->icon = &context->coalOreBlockDiffuse;
auto grenade = EntityInfoRegisterItem(entityInfo);
assert(grenade->id == (u32)Item::Grenade);
grenade->name = "Grenade";
grenade->convertsToBlock = false;
//grenade->associatedEntityTypeID = (u32)EntityType::Grenade;
grenade->mesh = context->grenadeMesh;
grenade->material = &context->grenadeMaterial;
grenade->icon = &context->grenadeIcon;
grenade->Use = GrenadeUse;
assert(entityInfo->itemTable.count == ((u32)Item::_Count - 1));
}
{ // Blocks
auto stone = EntityInfoRegisterBlock(entityInfo);
assert(stone->id == (u32)BlockValue::Stone);
stone->name = "Stone";
stone->associatedItem = (ItemID)Item::Stone;
auto grass = EntityInfoRegisterBlock(entityInfo);
assert(grass->id == (u32)BlockValue::Grass);
grass->name = "Grass";
grass->associatedItem = (ItemID)Item::Grass;
auto coalOre = EntityInfoRegisterBlock(entityInfo);
assert(coalOre->id == (u32)BlockValue::CoalOre);
coalOre->name = "Coal ore";
coalOre->DropPickup = CoalOreDropPickup;
coalOre->associatedItem = (ItemID)Item::CoalOre;
auto water = EntityInfoRegisterBlock(entityInfo);
assert(water->id == (u32)BlockValue::Water);
water->name = "Water";
water->associatedItem = (ItemID)Item::Water;
assert(entityInfo->blockTable.count == ((u32)BlockValue::_Count - 1));
}
}
void FluxInit(Context* context) {
log_print("Chunk size %llu\n", sizeof(Chunk));
context->hdrMap = LoadCubemapHDR("../res/desert_sky/nz.hdr", "../res/desert_sky/ny.hdr", "../res/desert_sky/pz.hdr", "../res/desert_sky/nx.hdr", "../res/desert_sky/px.hdr", "../res/desert_sky/py.hdr");
UploadToGPU(&context->hdrMap);
context->irradanceMap = MakeEmptyCubemap(64, 64, TextureFormat::RGB16F, TextureFilter::Bilinear, TextureWrapMode::ClampToEdge, false);
UploadToGPU(&context->irradanceMap);
context->enviromentMap = MakeEmptyCubemap(256, 256, TextureFormat::RGB16F, TextureFilter::Trilinear, TextureWrapMode::ClampToEdge, true);
UploadToGPU(&context->enviromentMap);
context->renderGroup.drawSkybox = true;
context->renderGroup.skyboxHandle = context->enviromentMap.gpuHandle;
context->renderGroup.irradanceMapHandle = context->irradanceMap.gpuHandle;
context->renderGroup.envMapHandle = context->enviromentMap.gpuHandle;
GenIrradanceMap(context->renderer, &context->irradanceMap, context->hdrMap.gpuHandle);
GenEnvPrefiliteredMap(context->renderer, &context->enviromentMap, context->hdrMap.gpuHandle, 6);
auto gameWorld = &context->gameWorld;
InitWorld(&context->gameWorld, context, &context->chunkMesher, 293847, Globals::DebugWorldName);
auto stone = ResourceLoaderLoadImage("../res/tile_stone.png", DynamicRange::LDR, true, 3, PlatformAlloc, GlobalLogger, GlobalLoggerData);
SetBlockTexture(context->renderer, BlockValue::Stone, stone->bits);
auto grass = ResourceLoaderLoadImage("../res/tile_grass.png", DynamicRange::LDR, true, 3, PlatformAlloc, GlobalLogger, GlobalLoggerData);
SetBlockTexture(context->renderer, BlockValue::Grass, grass->bits);
auto coalOre = ResourceLoaderLoadImage("../res/tile_coal_ore.png", DynamicRange::LDR, true, 3, PlatformAlloc, GlobalLogger, GlobalLoggerData);
SetBlockTexture(context->renderer, BlockValue::CoalOre, coalOre->bits);
auto water = ResourceLoaderLoadImage("../res/tile_water.png", DynamicRange::LDR, true, 3, PlatformAlloc, GlobalLogger, GlobalLoggerData);
SetBlockTexture(context->renderer, BlockValue::Water, water->bits);
context->coalIcon = LoadTextureFromFile("../res/coal_icon.png", TextureFormat::SRGB8, TextureWrapMode::Default, TextureFilter::None, DynamicRange::LDR);
assert(context->coalIcon.base);
UploadToGPU(&context->coalIcon);
context->containerIcon = LoadTextureFromFile("../res/chest_icon.png", TextureFormat::SRGB8, TextureWrapMode::Default, TextureFilter::None, DynamicRange::LDR);
assert(context->containerIcon.base);
UploadToGPU(&context->containerIcon);
context->beltIcon = LoadTextureFromFile("../res/belt_icon.png", TextureFormat::SRGB8, TextureWrapMode::Default, TextureFilter::None, DynamicRange::LDR);
assert(context->beltIcon.base);
UploadToGPU(&context->beltIcon);
context->extractorIcon = LoadTextureFromFile("../res/extractor_icon.png", TextureFormat::SRGB8, TextureWrapMode::Default, TextureFilter::None, DynamicRange::LDR);
assert(context->extractorIcon.base);
UploadToGPU(&context->extractorIcon);
context->pipeIcon = LoadTextureFromFile("../res/pipe_icon.png", TextureFormat::SRGB8, TextureWrapMode::Default, TextureFilter::None, DynamicRange::LDR);
assert(context->pipeIcon.base);
UploadToGPU(&context->pipeIcon);
context->grenadeIcon = LoadTextureFromFile("../res/grenade_icon.png", TextureFormat::SRGB8, TextureWrapMode::Default, TextureFilter::None, DynamicRange::LDR);
assert(context->grenadeIcon.base);
UploadToGPU(&context->grenadeIcon);
context->cubeMesh = LoadMeshFlux("../res/cube.mesh");
assert(context->cubeMesh);
UploadToGPU(context->cubeMesh);
context->coalOreMesh = LoadMeshFlux("../res/coal_ore/coal_ore.mesh");
assert(context->coalOreMesh);
UploadToGPU(context->coalOreMesh);
context->containerMesh = LoadMeshFlux("../res/container/container.mesh");
assert(context->containerMesh);
UploadToGPU(context->containerMesh);
context->pipeStraightMesh = LoadMeshFlux("../res/pipesss/pipe_straight.mesh");
assert(context->pipeStraightMesh);
UploadToGPU(context->pipeStraightMesh);
context->pipeTurnMesh = LoadMeshFlux("../res/pipesss/pipe_turn.mesh");
assert(context->pipeTurnMesh);
UploadToGPU(context->pipeTurnMesh);
context->pipeTeeMesh = LoadMeshFlux("../res/pipesss/pipe_Tee.mesh");
assert(context->pipeTeeMesh);
UploadToGPU(context->pipeTeeMesh);
context->pipeCrossMesh = LoadMeshFlux("../res/pipesss/pipe_cross.mesh");
assert(context->pipeCrossMesh);
UploadToGPU(context->pipeCrossMesh);
context->barrelMesh = LoadMeshFlux("../res/barrel/barrel.mesh");
assert(context->barrelMesh);
UploadToGPU(context->barrelMesh);
context->beltStraightMesh = LoadMeshFlux("../res/belt/belt_straight.mesh");
assert(context->beltStraightMesh);
UploadToGPU(context->beltStraightMesh);
context->extractorMesh = LoadMeshFlux("../res/extractor/extractor.mesh");
assert(context->extractorMesh);
UploadToGPU(context->extractorMesh);
context->grenadeMesh = LoadMeshFlux("../res/grenade/grenade.mesh");
assert(context->grenadeMesh);
UploadToGPU(context->grenadeMesh);
context->playerMaterial.workflow = Material::Workflow::PBR;
context->playerMaterial.pbr.albedoValue = V3(0.8f, 0.0f, 0.0f);
context->playerMaterial.pbr.roughnessValue = 0.7f;
context->coalOreMaterial.workflow = Material::Workflow::PBR;
context->coalOreMaterial.pbr.albedoValue = V3(0.0f, 0.0f, 0.0f);
context->coalOreMaterial.pbr.roughnessValue = 0.95f;
context->containerAlbedo = LoadTextureFromFile("../res/container/albedo_1024.png", TextureFormat::SRGB8, TextureWrapMode::Default, TextureFilter::Default, DynamicRange::LDR);
assert(context->containerAlbedo.base);
UploadToGPU(&context->containerAlbedo);
context->containerMetallic = LoadTextureFromFile("../res/container/metallic_1024.png", TextureFormat::R8, TextureWrapMode::Default, TextureFilter::Default, DynamicRange::LDR);
assert(context->containerMetallic.base);
UploadToGPU(&context->containerMetallic);
context->containerNormal = LoadTextureFromFile("../res/container/normal_1024.png", TextureFormat::RGB8, TextureWrapMode::Default, TextureFilter::Default, DynamicRange::LDR);
assert(context->containerNormal.base);
UploadToGPU(&context->containerNormal);
context->containerAO = LoadTextureFromFile("../res/container/AO_1024.png", TextureFormat::RGB8, TextureWrapMode::Default, TextureFilter::Default, DynamicRange::LDR);
assert(context->containerAO.base);
UploadToGPU(&context->containerAO);
context->containerMaterial.workflow = Material::Workflow::PBR;
context->containerMaterial.pbr.useAlbedoMap = true;
context->containerMaterial.pbr.useMetallicMap = true;
context->containerMaterial.pbr.useNormalMap = true;
context->containerMaterial.pbr.useAOMap = true;
context->containerMaterial.pbr.normalFormat = NormalFormat::DirectX;
context->containerMaterial.pbr.albedoMap = &context->containerAlbedo;
context->containerMaterial.pbr.roughnessValue = 0.35f;
context->containerMaterial.pbr.metallicMap = &context->containerMetallic;
context->containerMaterial.pbr.normalMap = &context->containerNormal;
context->containerMaterial.pbr.AOMap = &context->containerAO;
context->pipeAlbedo = LoadTextureFromFile("../res/pipesss/textures/albedo.png", TextureFormat::SRGB8, TextureWrapMode::Default, TextureFilter::Default, DynamicRange::LDR);
assert(context->pipeAlbedo.base);
UploadToGPU(&context->pipeAlbedo);
context->pipeRoughness = LoadTextureFromFile("../res/pipesss/textures/roughness.png", TextureFormat::R8, TextureWrapMode::Default, TextureFilter::Default, DynamicRange::LDR);
assert(context->pipeRoughness.base);
UploadToGPU(&context->pipeRoughness);
context->pipeMetallic = LoadTextureFromFile("../res/pipesss/textures/metallic.png", TextureFormat::R8, TextureWrapMode::Default, TextureFilter::Default, DynamicRange::LDR);
assert(context->pipeMetallic.base);
UploadToGPU(&context->pipeMetallic);
context->pipeNormal = LoadTextureFromFile("../res/pipesss/textures/normal.png", TextureFormat::RGB8, TextureWrapMode::Default, TextureFilter::Default, DynamicRange::LDR);
assert(context->pipeNormal.base);
UploadToGPU(&context->pipeNormal);
context->pipeAO = LoadTextureFromFile("../res/pipesss/textures/AO.png", TextureFormat::RGB8, TextureWrapMode::Default, TextureFilter::Default, DynamicRange::LDR);
assert(context->pipeAO.base);
UploadToGPU(&context->pipeAO);
context->pipeMaterial.workflow = Material::Workflow::PBR;
context->pipeMaterial.pbr.useAlbedoMap = true;
context->pipeMaterial.pbr.useMetallicMap = true;
context->pipeMaterial.pbr.useRoughnessMap = true;
context->pipeMaterial.pbr.useNormalMap = true;
context->pipeMaterial.pbr.useAOMap = true;
context->pipeMaterial.pbr.normalFormat = NormalFormat::DirectX;
context->pipeMaterial.pbr.albedoMap = &context->pipeAlbedo;
context->pipeMaterial.pbr.roughnessMap = &context->pipeRoughness;
context->pipeMaterial.pbr.metallicMap = &context->pipeMetallic;
context->pipeMaterial.pbr.normalMap = &context->pipeNormal;
context->pipeMaterial.pbr.AOMap = &context->pipeAO;
context->barrelAlbedo = LoadTextureFromFile("../res/barrel/albedo.png", TextureFormat::SRGB8, TextureWrapMode::Default, TextureFilter::Default, DynamicRange::LDR);
assert(context->barrelAlbedo.base);
UploadToGPU(&context->barrelAlbedo);
context->barrelRoughness = LoadTextureFromFile("../res/barrel/roughness.png", TextureFormat::R8, TextureWrapMode::Default, TextureFilter::Default, DynamicRange::LDR);
assert(context->barrelRoughness.base);
UploadToGPU(&context->barrelRoughness);
context->barrelNormal = LoadTextureFromFile("../res/barrel/normal.png", TextureFormat::RGB8, TextureWrapMode::Default, TextureFilter::Default, DynamicRange::LDR);
assert(context->barrelNormal.base);
UploadToGPU(&context->barrelNormal);
context->barrelAO = LoadTextureFromFile("../res/barrel/AO.png", TextureFormat::RGB8, TextureWrapMode::Default, TextureFilter::Default, DynamicRange::LDR);
assert(context->barrelAO.base);
UploadToGPU(&context->barrelAO);
context->barrelMaterial.workflow = Material::Workflow::PBR;
context->barrelMaterial.pbr.useAlbedoMap = true;
context->barrelMaterial.pbr.useRoughnessMap = true;
context->barrelMaterial.pbr.useNormalMap = true;
context->barrelMaterial.pbr.useAOMap = true;
context->barrelMaterial.pbr.normalFormat = NormalFormat::DirectX;
context->barrelMaterial.pbr.albedoMap = &context->barrelAlbedo;
context->barrelMaterial.pbr.roughnessMap = &context->barrelRoughness;
context->barrelMaterial.pbr.metallicValue = 0.0f;
context->barrelMaterial.pbr.normalMap = &context->barrelNormal;
context->barrelMaterial.pbr.AOMap = &context->barrelAO;
context->beltDiffuse = LoadTextureFromFile("../res/belt/diffuse.png", TextureFormat::SRGB8, TextureWrapMode::Default, TextureFilter::Default, DynamicRange::LDR);
assert(context->beltDiffuse.base);
UploadToGPU(&context->beltDiffuse);
context->beltMaterial.workflow = Material::Workflow::PBR;
context->beltMaterial.pbr.useAlbedoMap = true;
context->beltMaterial.pbr.albedoMap = &context->beltDiffuse;
context->beltMaterial.pbr.roughnessValue = 1.0f;
context->beltMaterial.pbr.metallicValue = 0.0f;
context->extractorDiffuse = LoadTextureFromFile("../res/extractor/diffuse.png", TextureFormat::SRGB8, TextureWrapMode::Default, TextureFilter::Default, DynamicRange::LDR);
assert(context->extractorDiffuse.base);
UploadToGPU(&context->extractorDiffuse);
context->extractorMaterial.workflow = Material::Workflow::PBR;
context->extractorMaterial.pbr.useAlbedoMap = true;
context->extractorMaterial.pbr.albedoMap = &context->extractorDiffuse;
context->extractorMaterial.pbr.roughnessValue = 1.0f;
context->extractorMaterial.pbr.metallicValue = 0.0f;
context->stoneDiffuse = LoadTextureFromFile("../res/tile_stone.png", TextureFormat::SRGB8, TextureWrapMode::Default, TextureFilter::Default, DynamicRange::LDR);
assert(context->stoneDiffuse.base);
UploadToGPU(&context->stoneDiffuse);
context->stoneMaterial.workflow = Material::Workflow::PBR;
context->stoneMaterial.pbr.useAlbedoMap = true;
context->stoneMaterial.pbr.albedoMap = &context->stoneDiffuse;
context->stoneMaterial.pbr.roughnessValue = 1.0f;
context->stoneMaterial.pbr.metallicValue = 0.0f;
context->grassDiffuse = LoadTextureFromFile("../res/tile_grass.png", TextureFormat::SRGB8, TextureWrapMode::Default, TextureFilter::Default, DynamicRange::LDR);
assert(context->grassDiffuse.base);
UploadToGPU(&context->grassDiffuse);
context->grassMaterial.workflow = Material::Workflow::PBR;
context->grassMaterial.pbr.useAlbedoMap = true;
context->grassMaterial.pbr.albedoMap = &context->grassDiffuse;
context->grassMaterial.pbr.roughnessValue = 1.0f;
context->grassMaterial.pbr.metallicValue = 0.0f;
context->coalOreBlockDiffuse = LoadTextureFromFile("../res/tile_coal_ore.png", TextureFormat::SRGB8, TextureWrapMode::Default, TextureFilter::Default, DynamicRange::LDR);
assert(context->coalOreBlockDiffuse.base);
UploadToGPU(&context->coalOreBlockDiffuse);
context->coalOreBlockMaterial.workflow = Material::Workflow::PBR;
context->coalOreBlockMaterial.pbr.useAlbedoMap = true;
context->coalOreBlockMaterial.pbr.albedoMap = &context->coalOreBlockDiffuse;
context->coalOreBlockMaterial.pbr.roughnessValue = 1.0f;
context->coalOreBlockMaterial.pbr.metallicValue = 0.0f;
context->waterDiffuse = LoadTextureFromFile("../res/tile_water.png", TextureFormat::SRGB8, TextureWrapMode::Default, TextureFilter::Default, DynamicRange::LDR);
assert(context->waterDiffuse.base);
UploadToGPU(&context->waterDiffuse);
context->waterMaterial.workflow = Material::Workflow::PBR;
context->waterMaterial.pbr.useAlbedoMap = true;
context->waterMaterial.pbr.albedoMap = &context->waterDiffuse;
context->waterMaterial.pbr.roughnessValue = 1.0f;
context->waterMaterial.pbr.metallicValue = 0.0f;
context->grenadeAlbedo = LoadTextureFromFile("../res/grenade/textures_256/albedo.png", TextureFormat::SRGB8, TextureWrapMode::Default, TextureFilter::Default, DynamicRange::LDR);
assert(context->grenadeAlbedo.base);
UploadToGPU(&context->grenadeAlbedo);
context->grenadeRoughness = LoadTextureFromFile("../res/grenade/textures_256/roughness.png", TextureFormat::R8, TextureWrapMode::Default, TextureFilter::Default, DynamicRange::LDR);
assert(context->grenadeRoughness.base);
UploadToGPU(&context->grenadeRoughness);
context->grenadeMetallic = LoadTextureFromFile("../res/grenade/textures_256/metallic.png", TextureFormat::R8, TextureWrapMode::Default, TextureFilter::Default, DynamicRange::LDR);
assert(context->grenadeMetallic.base);
UploadToGPU(&context->grenadeMetallic);
context->grenadeNormal = LoadTextureFromFile("../res/grenade/textures_256/normal.png", TextureFormat::RGB8, TextureWrapMode::Default, TextureFilter::Default, DynamicRange::LDR);
assert(context->grenadeNormal.base);
UploadToGPU(&context->grenadeNormal);
context->grenadeAO = LoadTextureFromFile("../res/grenade/textures_256/AO.png", TextureFormat::RGB8, TextureWrapMode::Default, TextureFilter::Default, DynamicRange::LDR);
assert(context->grenadeAO.base);
UploadToGPU(&context->grenadeAO);
context->grenadeMaterial.workflow = Material::Workflow::PBR;
context->grenadeMaterial.pbr.useAlbedoMap = true;
context->grenadeMaterial.pbr.useRoughnessMap = true;
context->grenadeMaterial.pbr.useMetallicMap = true;
context->grenadeMaterial.pbr.useNormalMap = true;
context->grenadeMaterial.pbr.useAOMap = true;
context->grenadeMaterial.pbr.normalFormat = NormalFormat::DirectX;
context->grenadeMaterial.pbr.albedoMap = &context->grenadeAlbedo;
context->grenadeMaterial.pbr.roughnessMap = &context->grenadeRoughness;
context->grenadeMaterial.pbr.metallicMap = &context->grenadeMetallic;
context->grenadeMaterial.pbr.normalMap = &context->grenadeNormal;
context->grenadeMaterial.pbr.AOMap = &context->grenadeAO;
EntityInfoInit(&context->entityInfo);
RegisterBuiltInEntities(context);
context->camera.targetWorldPosition = WorldPos::Make(IV3(0, 15, 0));
MoveRegion(&gameWorld->chunkPool.playerRegion, WorldPos::ToChunk(context->camera.targetWorldPosition.block).chunk);
#if 0
Entity* container = CreateContainerEntity(gameWorld, WorldPos::Make(0, 16, 0));
Entity* pipe = CreatePipeEntity(gameWorld, WorldPos::Make(2, 16, 0));
//Entity* barrel = CreateBarrel(context, gameWorld, IV3(4, 16, 0));
#endif
UIInit(&context->ui);
context->camera.mode = CameraMode::Gameplay;
PlatformSetInputMode(InputMode::FreeCursor);
context->camera.inputMode = GameInputMode::Game;
PlatformSetSaveThreadWork(SaveThreadWork, nullptr, 3000);
}
void FluxReload(Context* context) {
}
void FluxUpdate(Context* context) {
auto world = &context->gameWorld;
while (!world->playerID) {
auto player = (Player*)CreatePlayerEntity(world, WorldPos::Make(0, 30, 0));
if (player) {
player->camera = &context->camera;
world->playerID = player->id;
EntityInventoryPushItem(player->toolbelt, Item::Pipe, 128);
EntityInventoryPushItem(player->toolbelt, Item::Belt, 128);
EntityInventoryPushItem(player->toolbelt, Item::CoalOre, 128);
EntityInventoryPushItem(player->toolbelt, Item::Container, 128);
EntityInventoryPushItem(player->toolbelt, Item::Stone, 128);
EntityInventoryPushItem(player->toolbelt, Item::Extractor, 128);
EntityInventoryPushItem(player->toolbelt, Item::Grenade, 128);
}
UpdateChunks(&world->chunkPool);
return;
}
auto player = static_cast<Player*>(GetEntity(&context->gameWorld, context->gameWorld.playerID));
assert(player);
auto renderer = context->renderer;
auto camera = &context->camera;
if (KeyPressed(Key::F5)) {
auto saved = SaveWorld(world);
if (saved) {
log_print("[Game] World %s was saved\n", world->name);
} else {
log_print("[Game] Failed to save world %s\n", world->name);
}
}
if(KeyPressed(Key::Tilde)) {
context->consoleEnabled = !context->consoleEnabled;
if (context->consoleEnabled) {
camera->inputMode = GameInputMode::UI;
context->console.justOpened = true;
} else {
// TODO: check if inventory wants to capture input
camera->inputMode = GameInputMode::Game;
}
}
if (camera->inputMode == GameInputMode::InGameUI || camera->inputMode == GameInputMode::UI) {
PlatformSetInputMode(InputMode::FreeCursor);
} else {
PlatformSetInputMode(InputMode::CaptureCursor);
}
if (context->consoleEnabled) {
DrawConsole(&context->console);
}
i32 rendererSampleCount = GetRenderSampleCount(renderer);
DEBUG_OVERLAY_SLIDER(rendererSampleCount, 0, GetRenderMaxSampleCount(renderer));
if (rendererSampleCount != GetRenderSampleCount(renderer)) {
ChangeRenderResolution(renderer, GetRenderResolution(renderer), rendererSampleCount);
}
auto renderRes = GetRenderResolution(renderer);
if (renderRes.x != GetPlatform()->windowWidth ||
renderRes.y != GetPlatform()->windowHeight) {
ChangeRenderResolution(renderer, UV2(GetPlatform()->windowWidth, GetPlatform()->windowHeight), GetRenderSampleCount(renderer));
}
auto ui = &context->ui;
auto debugUI = &context->debugUI;
if (KeyPressed(Key::F1)) {
Globals::ShowDebugOverlay = !Globals::ShowDebugOverlay;
}
if (KeyPressed(Key::F2)) {
DebugUIToggleChunkTool(debugUI);
}
if (KeyPressed(Key::F3)) {
DebugUITogglePerfCounters(debugUI);
}
if (KeyPressed(Key::E)) {
if (UIHasOpen(ui)) {
UICloseAll(ui);
} else {
UIOpenForEntity(ui, context->gameWorld.playerID);
}
}
if (KeyPressed(Key::Escape)) {
UICloseAll(ui);
}
UIUpdateAndRender(ui);
Update(&context->camera, player, 1.0f / 60.0f);
glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
DrawDebugPerformanceCounters();
auto group = &context->renderGroup;
group->camera = &context->camera;
DirectionalLight light = {};
light.dir = Normalize(V3(0.3f, -1.0f, -0.95f));
light.from = V3(4.0f, 200.0f, 0.0f);
light.ambient = V3(0.3f);
light.diffuse = V3(1.0f);
light.specular = V3(1.0f);
RenderCommandSetDirLight lightCommand = { light };
Push(group, &lightCommand);
UpdateChunkEntities(&world->chunkPool, group, camera);
UpdateChunks(&world->chunkPool);
DrawChunks(&world->chunkPool, group, camera);
if (camera->inputMode == GameInputMode::Game) {
// TODO: Raycast
v3 ro = camera->position;
v3 rd = camera->mouseRay;
f32 dist = 10.0f;
iv3 roWorld = WorldPos::Offset(camera->targetWorldPosition, ro).block;
iv3 rdWorld = WorldPos::Offset(camera->targetWorldPosition, ro + rd * dist).block;
iv3 min = IV3(Min(roWorld.x, rdWorld.x), Min(roWorld.y, rdWorld.y), Min(roWorld.z, rdWorld.z)) - IV3(1);
iv3 max = IV3(Max(roWorld.x, rdWorld.x), Max(roWorld.y, rdWorld.y), Max(roWorld.z, rdWorld.z)) + IV3(1);
f32 tMin = F32::Max;
iv3 hitBlock = GameWorld::InvalidPos;
EntityID hitEntity = EntityID {0};
v3 hitNormal;
iv3 hitNormalInt;
for (i32 z = min.z; z < max.z; z++) {
for (i32 y = min.y; y < max.y; y++) {
for (i32 x = min.x; x < max.x; x++) {
auto block = GetBlock(&context->gameWorld, x, y, z);
if ((u32)(block.value) || block.entity) {
WorldPos voxelWorldP = WorldPos::Make(x, y, z);
v3 voxelRelP = WorldPos::Relative(camera->targetWorldPosition, voxelWorldP);
BBoxAligned voxelAABB;
voxelAABB.min = voxelRelP - V3(Globals::BlockHalfDim);
voxelAABB.max = voxelRelP + V3(Globals::BlockHalfDim);
//DrawAlignedBoxOutline(group, voxelAABB.min, voxelAABB.max, V3(0.0f, 1.0f, 0.0f), 2.0f);
auto intersection = Intersect(voxelAABB, ro, rd, 0.0f, dist); // TODO: Raycast distance
if (intersection.hit && intersection.t < tMin) {
tMin = intersection.t;
hitBlock = voxelWorldP.block;
hitNormal = intersection.normal;
hitNormalInt = intersection.iNormal;
if (block.entity) {
hitEntity = block.entity->id;
}
}
}
}
}
}
player->selectedBlock = hitBlock;
player->selectedEntity = hitEntity;
if (hitEntity != 0) {
if (KeyPressed(Key::R)) {
auto entity = GetEntity(&context->gameWorld, hitEntity);
if (entity) {
auto info = GetEntityInfo(entity->type);
EntityRotateData data {};
data.direction = EntityRotateData::Direction::CW;
info->Behavior(entity, EntityBehaviorInvoke::Rotate, &data);
}
}
Entity* entity = GetEntity(&context->gameWorld, hitEntity); {
if (entity) {
UIDrawEntityInfo(&context->ui, entity);
}
}
} else if (hitBlock.x != GameWorld::InvalidCoord) {
auto block = GetBlockValue(&context->gameWorld, hitBlock);
if (block != BlockValue::Empty) {
UIDrawBlockInfo(&context->ui, hitBlock);
}
}
bool buildBlock = false;
bool useItem = true;
if (hitBlock.x != GameWorld::InvalidCoord) {
if (MouseButtonPressed(MouseButton::Left)) {
ConvertBlockToPickup(&context->gameWorld, hitBlock);
}
if (MouseButtonPressed(MouseButton::Right)) {
buildBlock = true;
if (hitEntity != 0) {
auto entity = GetEntity(&context->gameWorld, hitEntity);
if (entity) {
auto info = GetEntityInfo(entity->type);
if (info->hasUI) {
if (UIOpenForEntity(&context->ui, hitEntity)) {
UIOpenForEntity(ui, context->gameWorld.playerID);
buildBlock = false;
useItem = false;
}
}
}
}
}
if (buildBlock) {
auto blockToBuild = player->toolbelt->slots[player->toolbeltSelectIndex].item;
if (blockToBuild != Item::None) {
auto info = GetItemInfo(blockToBuild);
if (!info->Use) {
// TODO: Check is item exist in inventory before build?
auto result = BuildBlock(context, &context->gameWorld, hitBlock + hitNormalInt, blockToBuild);
useItem = false;
if (!Globals::CreativeModeEnabled) {
if (result) {
EntityInventoryPopItem(player->toolbelt, player->toolbeltSelectIndex);
}
}
}
//assert(result);
}
}
iv3 selectedBlockPos = player->selectedBlock;
v3 minP = WorldPos::Relative(camera->targetWorldPosition, WorldPos::Make(selectedBlockPos));
v3 maxP = WorldPos::Relative(camera->targetWorldPosition, WorldPos::Make(selectedBlockPos));
minP -= V3(Globals::BlockHalfDim);
maxP += V3(Globals::BlockHalfDim);
DrawAlignedBoxOutline(group, minP, maxP, V3(0.0f, 0.0f, 1.0f), 2.0f);
}
if (useItem && MouseButtonPressed(MouseButton::Right)) {
auto item = player->toolbelt->slots[player->toolbeltSelectIndex].item;
auto info = GetItemInfo(item);
if (info->Use) {
auto result = info->Use((ItemID)item, player);
if (result.used && result.destroyAfterUse) {
EntityInventoryPopItem(player->toolbelt, player->toolbeltSelectIndex);
}
}
}
}
ForEach(&context->gameWorld.entitiesToMove, [&](auto it) {
auto entity = *it;
assert(entity);
UpdateEntityResidence(&context->gameWorld, entity);
});
FlatArrayClear(&context->gameWorld.entitiesToMove);
ForEach(&context->gameWorld.entitiesToDelete, [&](Entity** it) {
auto entity = *it;
assert(entity);
assert(entity->deleted);
DeleteEntity(world, entity);
});
BucketArrayClear(&context->gameWorld.entitiesToDelete);
Begin(renderer, group);
ShadowPass(renderer, group);
MainPass(renderer, group);
End(renderer);
UpdateDebugProfiler(&context->debugProfiler);
DebugUIUpdateAndRender(debugUI);
// Alpha
//ImGui::PopStyleVar();
}
void FluxRender(Context* context) {}
| [
"hbr.tzuf@yandex.ru"
] | hbr.tzuf@yandex.ru |
a8a2f4480334ec1942c06301edbd5be8a3c63b74 | 1762699cd6ba24ce329eb10ccb67ddcabddd37d0 | /src/TicTacToe.cpp | 0b3d0a38b0cdd2a8960916d93e9d333f721ee39a | [] | no_license | LightFelicis/TicTacToe | 66cf1b0c9df19a374bc58c26ddaa1e2b0b429aa4 | 1662a42966a45d81aa5af71ccebc42a6dcf226ff | refs/heads/master | 2020-07-22T06:48:23.668900 | 2019-09-08T21:59:40 | 2019-09-08T21:59:40 | 207,107,041 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 235 | cpp | // Alicja Kluczek
#pragma execution_character_set( "utf-8" )
#include <iostream>
#include "GameView.h"
#include "Board.h"
#include "Logic.h"
int main()
{
while (true) {
Logic GAME = Logic();
GAME.Start();
}
}
| [
"alicja2602@gmail.com"
] | alicja2602@gmail.com |
3ce3c8a9315faaf42c7138665ca73a7cdb42dc7f | 6d760556cbfade17db9b990dda17658d81a81a55 | /src/libs/netcomm/socket/datagram.h | b9b671f88c6fabd3734f8110e719c245eaa65efe | [] | no_license | sj/fawkresrobotics-fawkes-copy | 8e247a5d2ed76d14aeb06c9a439ee35cf194b025 | 1854db8cafa1718bc636631162c76d15b6894c5b | refs/heads/master | 2020-03-31T13:05:51.779358 | 2018-10-09T11:45:37 | 2018-10-09T11:45:37 | 152,241,372 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,349 | h |
/***************************************************************************
* datagram.h - Fawkes datagram socket (UDP)
*
* Created: Mon Nov 13 19:06:24 2006
* Copyright 2006 Tim Niemueller [www.niemueller.de]
*
****************************************************************************/
/* 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. A runtime exception applies to
* this software (see LICENSE.GPL_WRE file mentioned below for details).
*
* 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 Library General Public License for more details.
*
* Read the full text in the LICENSE.GPL_WRE file in the doc directory.
*/
#ifndef __NETCOMM_SOCKET_DATAGRAM_H_
#define __NETCOMM_SOCKET_DATAGRAM_H_
#include <netcomm/socket/socket.h>
namespace fawkes {
class DatagramSocket : public Socket
{
public:
DatagramSocket(AddrType addr_type, float timeout = 0.f);
DatagramSocket(DatagramSocket &s);
virtual Socket * clone();
};
} // end namespace fawkes
#endif
| [
"github@s.traiectum.net"
] | github@s.traiectum.net |
36431503a36d11400f76bf478409fae67e172652 | 95b0bdd785ee0f62692996891e1d6c8d07621af5 | /JeVousSouhaiteUneBonneJournée/main.cpp | e01c1b8171ab314ff9368eefa88a19b825c2b19a | [] | no_license | benoittachet/globalGameJam2017 | d3bed406725ea6a45c7c811543a74f7f2e90151e | 92a9545418ae636347350a5b6d31cdf017a5dd64 | refs/heads/master | 2021-06-10T10:11:04.286563 | 2017-01-22T15:30:40 | 2017-01-22T15:30:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,383 | cpp | #include "Display.h"
#include <thread>
#include <SFML/Graphics.hpp>
#include "main.h"
globalData *data;
globalData::globalData()
{
sf::Music *a = new sf::Music;
exitProgram = false;
redraw = true;
_texture = new sf::Texture();
_backGround = new sf::Sprite();
_window = new sf::RenderWindow();
_tileset = new sf::Texture();
_wall = new sf::Sprite();
_floor = new sf::Sprite();
_players = new std::vector<Player*>;
sf::Music *p1 = new sf::Music;
sf::Music *p2 = new sf::Music;
sf::Music *p3 = new sf::Music;
sf::Music *p4 = new sf::Music;
_music.push_back(p1);
_music.push_back(p2);
_music.push_back(p3);
_music.push_back(p4);
_texture->loadFromFile("src/background.png");
_tileset->loadFromFile("src/tileset.png");
_backGround->setTexture(*_texture, true);
_wall->setTexture(*_tileset, true);
_floor->setTexture(*_tileset, true);
_wall->setTextureRect(sf::IntRect(64, 0, 64, 64));
_floor->setTextureRect(sf::IntRect(0, 0, 64, 64));
_window->create(sf::VideoMode(1280, 720), "GLOBAL");
_backGround->setScale((float)_window->getSize().x / _texture->getSize().x, (float)_window->getSize().y / _texture->getSize().y);
}
globalData::~globalData()
{
delete _texture;
delete _tileset;
delete _window;
delete _backGround;
delete _wall;
delete _floor;
delete _players;
}
sf::Music *globalData::getMusicStream(int i)
{
return (_music.at(i));
}
bool globalData::getExit()
{
return this->exitProgram;
}
void globalData::setExit(bool b)
{
this->exitProgram = b;
}
bool globalData::getRedraw()
{
return (redraw);
}
void globalData::setRedraw(bool b)
{
this->redraw = b;
}
sf::Texture *globalData::getTexture()
{
return this->_texture;
}
void globalData::setTexture(sf::Texture *t)
{
this->_texture = t;
}
sf::RenderWindow *globalData::getWindow()
{
return this->_window;
}
void globalData::setWindow(sf::RenderWindow *w)
{
_window = w;
}
sf::Sprite *globalData::getBackGround()
{
return _backGround;
}
void globalData::setBackGround(sf::Sprite *b)
{
_backGround = b;
}
std::vector<Player*> *globalData::getPlayers()
{
return _players;
}
Player *globalData::getPlayer(int i)
{
return _players->at(i);
}
Labyrinth *globalData::getLabyrinth()
{
return (this->laby);
}
void globalData::setLabyrinth(Labyrinth *lab)
{
this->laby = lab;
std::vector<std::vector<int>> labData = lab->getData();
std::vector<sf::Sprite> *actualLine;
actualLine = new std::vector<sf::Sprite>;
for (unsigned int i = 0; i < labData.size(); i++)
{
for (unsigned int j = 0; j < labData[i].size(); j++)
{
if (labData[i][j] == 0)
actualLine->push_back(*this->_floor);
else
actualLine->push_back(*this->_wall);
(*actualLine)[j].setPosition(sf::Vector2f((float)(64.0 * j), (float)(64.0 * i)));
}
this->spritesVector.push_back(*actualLine);
actualLine->clear();
}
}
std::vector<std::vector<sf::Sprite>>globalData::getSpritesVector()
{
return (this->spritesVector);
}
int main()
{
data = new globalData();
Labyrinth laby("src/testLabyrinth/mapTest2.txt");
Player p1(0);
Player p2(1);
Player p3(2);
Player p4(3);
data->setLabyrinth(&laby);
std::thread t1(&Player::start, &p1);
std::thread t2(&Player::start, &p2);
std::thread t3(&Player::start, &p3);
std::thread t4(&Player::start, &p4);
data->getWindow()->setActive(true);
drawInWindow();
delete data;
return 0;
} | [
"jimmy.djabali@epitech.eu"
] | jimmy.djabali@epitech.eu |
2ffc7fcb151de079cacbffaebef2637f9fb93c31 | 79115b8e7a8631e81edb4074ce5e945fca7f6ac1 | /TheWay/Private/AI/BTTasks/BTTask_TurnToTarget.cpp | 36ab1be45af4d516a474a63f6f415c3a927e1a0e | [] | no_license | SeongTaek/TheWay | f1a2c093669ac1a4caed4da1a85ebdcf40cb7a5d | 23ad2cf418147bf94c5791a468edd4a456279022 | refs/heads/main | 2023-04-19T10:12:07.990662 | 2021-05-12T05:18:24 | 2021-05-12T05:18:24 | 336,471,787 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,586 | cpp | // Fill out your copyright notice in the Description page of Project Settings.
#include "AI/BTTasks/BTTask_TurnToTarget.h"
#include "Character/BaseCharacter.h"
#include "Controller/BaseAIController.h"
#include "Utility/CreataekUtility.h"
#include "BehaviorTree/BlackboardComponent.h"
#include "GameFramework/CharacterMovementComponent.h"
FString UBTTask_TurnToTarget::GetStaticDescription() const
{
return FString::Printf(TEXT("목표물(%s)을 향해 회전합니다."), *BBKeyTarget.SelectedKeyName.ToString());
}
UBTTask_TurnToTarget::UBTTask_TurnToTarget()
{
NodeName = TEXT("목표물 바라보기");
bNotifyTick = true;
bNotifyTaskFinished = true;
}
EBTNodeResult::Type UBTTask_TurnToTarget::ExecuteTask(UBehaviorTreeComponent& OwnerComp, uint8* NodeMemory)
{
EBTNodeResult::Type Result = Super::ExecuteTask(OwnerComp, NodeMemory);
auto Character = Cast<ABaseCharacter>(OwnerComp.GetAIOwner()->GetPawn());
if (Character == nullptr)
{
return EBTNodeResult::Failed;
}
auto Target = Cast<ABaseCharacter>(OwnerComp.GetBlackboardComponent()->GetValueAsObject(BBKeyTarget.SelectedKeyName));
if (Target == nullptr)
{
return EBTNodeResult::Failed;
}
Character->GetCharacterMovement()->bUseControllerDesiredRotation = false;
return EBTNodeResult::InProgress;
}
void UBTTask_TurnToTarget::TickTask(UBehaviorTreeComponent& OwnerComp, uint8* NodeMemory, float DeltaSeconds)
{
Super::TickTask(OwnerComp, NodeMemory, DeltaSeconds);
auto Character = Cast<ABaseCharacter>(OwnerComp.GetAIOwner()->GetPawn());
ReturnIfNull(Character);
auto Target = Cast<ABaseCharacter>(OwnerComp.GetBlackboardComponent()->GetValueAsObject(BBKeyTarget.SelectedKeyName));
ReturnIfNull(Target);
FVector Direction = Target->GetActorLocation() - Character->GetActorLocation();
Direction.Normalize();
FRotator CharacterRotator = Character->GetActorRotation();
FRotator NewLookAt = FRotationMatrix::MakeFromX(Direction).Rotator();
NewLookAt.Pitch = 0.0f;
NewLookAt.Roll = 0.0f;
Character->SetActorRotation(FMath::RInterpTo(CharacterRotator, NewLookAt, DeltaSeconds, 10.0f));
if (FMath::Abs(CharacterRotator.Yaw - NewLookAt.Yaw) <= 1.0f)
{
FinishLatentTask(OwnerComp, EBTNodeResult::Succeeded);
}
}
void UBTTask_TurnToTarget::OnTaskFinished(UBehaviorTreeComponent& OwnerComp, uint8* NodeMemory, EBTNodeResult::Type TaskResult)
{
Super::OnTaskFinished(OwnerComp, NodeMemory, TaskResult);
auto Character = Cast<ABaseCharacter>(OwnerComp.GetAIOwner()->GetPawn());
ReturnIfNull(Character);
Character->GetCharacterMovement()->bUseControllerDesiredRotation = true;
}
| [
"gora2033@gmail.com"
] | gora2033@gmail.com |
bd4281e4f981ce53909182a7de4a381346b98358 | 50fe3d91065b9252f05c803bed129055a7d073ce | /busplan/line.cpp | bc7b9576c2daf5267c5a7c8895862123e464413c | [
"MIT"
] | permissive | gonmator/busplan | d4affadfc8b78881a0c7d7950d30e29cd3f13afc | 5845b63b16741dd0472cbba1ba028bdfdcfe0e3f | refs/heads/master | 2021-01-02T08:14:12.314732 | 2015-06-08T09:33:20 | 2015-06-08T09:33:20 | 33,974,158 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,165 | cpp | #include <algorithm>
#include "line.hpp"
StopSet Line::getStopSet() const {
StopSet rv;
for (const auto& routep: routes_) {
const auto& rstops = routep.second.stops();
rv.insert(rstops.cbegin(), rstops.cend());
}
return rv;
}
StepsRoutes Line::getForwardStepsRoutes() const {
StepsRoutes rv;
for (const auto& routep: routes_) {
rv.emplace_back(routep.first, std::move(routep.second.getForwardSteps()));
}
return rv;
}
StepsRoutes Line::getBackwardStepsRoutes() const {
StepsRoutes rv;
for (const auto& routep: routes_) {
rv.emplace_back(routep.first, std::move(routep.second.getBackwardSteps()));
}
return rv;
}
TimeLine Line::getStopTimes(Day day, const Stop& stop) const {
TimeLine rv;
for (const auto& routep: routes_) {
try {
auto tl = routep.second.getStopTimes(day, stop);
rv.insert(rv.end(), tl.cbegin(), tl.cend());
} catch (std::out_of_range&) {
// ignore, it is ok.
}
}
std::stable_sort(rv.begin(), rv.end());
rv.erase(std::unique(rv.begin(), rv.end()), rv.end());
return rv;
}
| [
"gonmator@gmail.com"
] | gonmator@gmail.com |
e8e0dfaef90d9d71ed09c4dfd73e614a3236a580 | bd97ffed36b0fa501694c2255fb1d96a4f1f2d1f | /123 Best Time to Buy and Sell Stock III/best_time_to_buy_sell_stock_3.cpp | e6144dfdef76c441489e425398f58aaa6671f3dc | [] | no_license | evanyz/leetcode | ea4c13a9ff1a8c1e78f04cd3ec8514dd92eefbfe | ae8fd5d8fe6370ae64b25e2ad340822ecee9f755 | refs/heads/master | 2020-12-31T03:16:45.525575 | 2015-12-19T07:13:22 | 2015-12-19T07:13:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 881 | cpp | /*
* LeetCode Submissions by Xinyu Chen
* Best Time to Buy and Sell Stock III
* https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/
* Runtime: 12 ms
*/
class Solution {
public:
int maxProfit(vector<int>& prices) {
int len = prices.size(), profit = INT_MIN;
if (len < 2) return 0;
int buy = prices[0], sell = prices[len - 1];
vector<int> left(len, 0);
vector<int> right(len, 0);
for (int i = 1; i < len; i++) {
buy = min(buy, prices[i]);
left[i] = max(left[i - 1], prices[i] - buy);
}
for (int j = len - 2; j >= 0; j--) {
sell = max(sell, prices[j]);
right[j] = max(right[j + 1], sell - prices[j]);
}
for (int k = 0; k < len; k++) {
profit = max(profit, left[k] + right[k]);
}
return profit;
}
}; | [
"collectchen@gmail.com"
] | collectchen@gmail.com |
8ace77d54e23f9259a6a011b40115f05a02ed050 | 49490401c78efd229fa59546cd0143855218a174 | /reconstructTree.cpp | 1327781a820460dce038bd3429f0a1ccaf969742 | [] | no_license | ssripadham/CodingInterview | 1ecddb60c14507b6951cb905f147300f39fe453f | c008f5ff40d2bb7e7e2e39742d0393c74a809243 | refs/heads/master | 2021-07-04T06:08:01.639330 | 2021-06-03T01:47:48 | 2021-06-03T01:47:48 | 44,039,228 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,188 | cpp | struct node {
int data;
struct node* left;
struct node* right;
};
void inOrder(struct node* root){
if (root == null) return;
inOrder(root->left);
cout<<root->data;
inOrder(root->right);
}
struct node* newNode(int data){
struct node* newNode = (struct node*) malloc(sizeof(struct node));
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
struct node* reconstructTree(vector<int>& pre, int preStart, int preEnd,
vector<int>& in, int inStart, int inEnd){
if (preStart > preEnd) return null;
if (preStart == preEnd) {
return newNode(pre[preStart]);
}
int rootIndex = 0;
for (int i = inStart; i <= inEnd; ++i){
if (in[i] = pre[preStart]) {
rootIndex = i;
break;
}
}
//1 2 3 4 5 r = 2
int numLeftTree = rootIndex - instart;
int numRightTree = inEnd - rootIndex;
struct node* root = newNode(inStart[rootIndex]);
root->left = reconstructTree(pre, preStart+1, preStart+numLeftTree,
in, inStart, inStart+numLeftTree-1);
root->right = reconstructTree(pre, preStart+1+numLeftTree+1, preEnd,
in, inStart+numLeftTree+1, inEnd);
return root;
} | [
"noreply@github.com"
] | noreply@github.com |
aa3313f2ab76cbd448a358671e07d4df31dd170a | 9d27be29a1f5823a939432394b7bef5770adf46f | /Common/src/DoubleBuffer.cpp | fbfefbf06782aada7611b1b77d2e25670ddee33d | [] | no_license | wilbert-alberts/PiControl | 16471deaf13c5092ef2bf343bfb8e223a451693c | 81e5e0b0d6c5305af6d4600942cd961c67e592bd | refs/heads/master | 2020-05-02T14:02:12.228616 | 2014-10-14T19:32:13 | 2014-10-14T19:32:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,248 | cpp | /*
* DoubleBufferImp.cpp
*
* Created on: Jun 13, 2013
* Author: wilbert
*/
#include "DoubleBuffer.h"
#include <iostream>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <semaphore.h>
#include <cassert>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <system_error>
static const char* DB_MEM_ID = "/mem.DB.pages";
static const char* DB_LOCK0_ID = "/DB.lock0";
static const char* DB_LOCK1_ID = "/DB.lock1";
DoubleBuffer* DoubleBuffer::instance = 0;
DoubleBuffer::DoubleBuffer() {}
DoubleBuffer::~DoubleBuffer() {}
DoubleBuffer* DoubleBuffer::getInstance()
{
if (instance==0) {
instance = new DoubleBuffer();
}
return instance;
}
void DoubleBuffer::initSemaphores() {
pageHandles[0].sem = sem_open(DB_LOCK0_ID, O_CREAT, S_IRUSR | S_IWUSR, 1);
if (pageHandles[0].sem == SEM_FAILED ) {
throw std::system_error(errno, std::system_category(), "unable to create semaphore");
}
pageHandles[1].sem = sem_open(DB_LOCK1_ID, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR, 1);
if (pageHandles[1].sem == SEM_FAILED ) {
throw std::system_error(errno, std::system_category(),"unable to create semaphore");
}
}
void DoubleBuffer::create(int size) {
shmfd = shm_open(DB_MEM_ID, O_RDWR | O_CREAT, S_IRUSR|S_IWUSR);
if (shmfd == -1) {
throw std::system_error(errno, std::system_category(),"unable to create shared memory");
}
int memSize = (size+sizeof(DoubleBufferPage))*2;
if (ftruncate(shmfd, memSize)==-1) {
throw std::system_error(errno, std::system_category(),"unable to set length of shared memory");
}
pageHandles[0].page = static_cast<DoubleBufferPage*>(mmap(0, memSize, PROT_READ|PROT_WRITE, MAP_SHARED, shmfd, 0));
memset(pageHandles[0].page, 0, memSize);
if (pageHandles[0].page == MAP_FAILED) {
throw std::system_error(errno, std::system_category(), "unable to map shared memory");
}
char* p1 = (char*)(pageHandles[0].page);
pageHandles[1].page = (DoubleBufferPage*)(p1+size+sizeof(DoubleBufferPage));
pageHandles[0].page->pagesize = size;
pageHandles[1].page->pagesize = size;
created=true;
initSemaphores();
}
void DoubleBuffer::connect() {
shmfd = shm_open(DB_MEM_ID, O_RDWR, S_IRUSR|S_IWUSR);
if (shmfd == -1) {
throw std::system_error(errno, std::system_category(), "unable to create shared memory");
}
// mmap in order to retrieve actual size
pageHandles[0].page = static_cast<DoubleBufferPage*>(mmap(0, sizeof(DoubleBufferPage), PROT_READ|PROT_WRITE, MAP_SHARED, shmfd, 0));
int memsize = (pageHandles[0].page->pagesize+sizeof(DoubleBufferPage))*2;
if (munmap(pageHandles[0].page, sizeof(DoubleBufferPage))<0)
throw std::system_error(errno, std::system_category(), "unable to unmap shared memory");
// mmap again with correct size.
pageHandles[0].page = static_cast<DoubleBufferPage*>(mmap(0, memsize, PROT_READ|PROT_WRITE, MAP_SHARED, shmfd, 0));
if (pageHandles[0].page == MAP_FAILED) {
throw std::system_error(errno, std::system_category(), "unable to remap shared memory with correct size.");
}
char* p1 = (char*)(pageHandles[0].page);
int size = pageHandles[0].page->pagesize;
pageHandles[1].page = (DoubleBufferPage*)(p1+size+sizeof(DoubleBufferPage));
created=true;
initSemaphores();
}
int DoubleBuffer::size() {
assert(created);
assert(pageHandles[0].page->pagesize==pageHandles[1].page->pagesize);
return pageHandles[0].page->pagesize;
}
void DoubleBuffer::lock(int page) {
int r = sem_wait(pageHandles[page].sem);
if (r == -1) {
throw std::system_error(errno, std::system_category(),"unable to lock DoubleBuffer semaphore");
}
pageHandles[page].locked = true;
}
void DoubleBuffer::lockAny() {
int idx;
if (buffer == pageHandles[0].page) {
// Start with try to lock page 1
idx = 1;
}
else {
// Start with try to lock page 1
idx = 0;
}
while (1) {
int r;
r = sem_trywait(pageHandles[idx].sem);
if (r==0) {
pageHandles[idx].locked=true;
buffer=pageHandles[idx].page;
//std::cout << "l" << idx << std::endl;
return;
}
// Try to lock the other page.
idx = 1-idx;
}
}
void DoubleBuffer::lock() {
assert(created);
lockAny();
return;
}
void DoubleBuffer::lockOther() {
assert(created);
int other = (buffer == pageHandles[0].page) ? 1: 0;
lock(other);
}
void DoubleBuffer::unlock(int page) {
pageHandles[page].locked = false;
int r = sem_post(pageHandles[page].sem);
if (r == -1) {
throw std::system_error(errno, std::system_category());
}
}
void DoubleBuffer::unlock() {
assert(created);
int page = (buffer == pageHandles[0].page) ? 0: 1;
unlock(page);
}
void DoubleBuffer::unlockOther() {
assert(created);
int page = (buffer == pageHandles[0].page) ? 1: 0;
unlock(page);
}
void* DoubleBuffer::get() {
assert(created);
int page = (buffer == pageHandles[0].page) ? 0: 1;
if (!pageHandles[page].locked)
throw std::runtime_error("error: No buffer locked");
return buffer->mem;
}
void* DoubleBuffer::getOther() {
assert(created);
int other = (buffer == pageHandles[0].page) ? 1: 0;
if (!pageHandles[other].locked)
throw std::runtime_error("error: No buffer locked");
return pageHandles[other].page->mem;
}
void DoubleBuffer::copyFrom() {
char* src;
char* dst;
int other;
if (!(pageHandles[0].locked || pageHandles[1].locked))
throw std::runtime_error("error: No buffer locked");
other = (buffer==pageHandles[0].page) ? 1 : 0;
lock(other);
src= (char*)(pageHandles[other].page->mem);
dst= (char*)(pageHandles[1-other].page->mem);
memcpy (dst, src, pageHandles[1-other].page->pagesize);
unlock(other);
}
void DoubleBuffer::copyTo() {
char* src;
char* dst;
int other;
if (!(pageHandles[0].locked || pageHandles[1].locked))
throw std::runtime_error("error: No buffer locked");
other = (buffer==pageHandles[0].page) ? 1 : 0;
lock(other);
src= (char*)(pageHandles[1-other].page->mem);
dst= (char*)(pageHandles[other].page->mem);
memcpy (dst, src, pageHandles[1-other].page->pagesize);
unlock(other);
}
DoubleBufferLock::DoubleBufferLock()
: db(DoubleBuffer::getInstance())
{
db->connect();
db->lock();
}
DoubleBufferLock::~DoubleBufferLock() {
db->unlock();
}
| [
"wilbert.alberts@gmail.com"
] | wilbert.alberts@gmail.com |
4eb867985b383d461b81a801657d43ac6d99bc6b | f5b0098ea0fb7230dcbdf41d943601df0916567c | /dali/utils/scoring_utils.cpp | f6044aaccf5a686d7bba8aabc05929b291962b06 | [
"MIT"
] | permissive | byzhang/Dali | 98db397b85fcc9ae33e0b5dde74a7138ac53a2e4 | 54a45c240f706ef40b0fa0e2911f6c92cdb5f5ad | refs/heads/master | 2021-01-17T11:04:35.779415 | 2016-08-03T00:52:37 | 2016-08-03T00:52:37 | 52,980,381 | 0 | 0 | null | 2016-03-02T17:00:07 | 2016-03-02T17:00:06 | null | UTF-8 | C++ | false | false | 3,603 | cpp | #include "dali/utils/scoring_utils.h"
using std::vector;
using std::string;
namespace utils {
ConfusionMatrix::ConfusionMatrix(int classes, const vector<string>& _names) : names(_names), totals(classes) {
for (int i = 0; i < classes;++i) {
grid.emplace_back(classes);
}
}
void ConfusionMatrix::classified_a_when_b(int a, int b) {
// update the misclassification:
grid[b][a] += 1;
// update the stakes:
totals[b] += 1;
};
void ConfusionMatrix::report() const {
std::cout << "\nConfusion Matrix\n\t";
for (auto & name : names) {
std::cout << name << "\t";
}
std::cout << "\n";
auto names_ptr = names.begin();
auto totals_ptr = totals.begin();
for (auto& category : grid) {
std::cout << *names_ptr << "\t";
for (auto & el : category) {
std::cout << std::fixed
<< std::setw(4)
<< std::setprecision(2)
<< std::setfill(' ')
<< ((*totals_ptr) > 0 ? (100.0 * ((double) el / (double)(*totals_ptr))) : 0.0)
<< "%\t";
}
std::cout << "\n";
names_ptr++;
totals_ptr++;
}
}
Accuracy& Accuracy::true_positive(const int& _tp) {
tp = _tp;
return *this;
}
Accuracy& Accuracy::true_negative(const int& _tn) {
tn = _tn;
return *this;
}
Accuracy& Accuracy::false_positive(const int& _fp) {
fp = _fp;
return *this;
}
Accuracy& Accuracy::false_negative(const int& _fn) {
fn = _fn;
return *this;
}
int Accuracy::true_positive() const {
return tp;
}
int Accuracy::true_negative() const {
return tn;
}
int Accuracy::false_positive() const {
return fp;
}
int Accuracy::false_negative() const {
return fn;
}
double Accuracy::precision() const {
return (double) tp / ((double)(tp + fp));
}
double Accuracy::recall() const {
return (double) tp / ((double)(tp + fn));
}
double Accuracy::F1() const {
auto P = precision();
auto R = recall();
return (2.0 * P * R) / (P + R);
}
template<typename T>
double pearson_correlation(const std::vector<T>& x, const std::vector<T>& y) {
utils::assert2(y.size() == x.size(), "Not an equal number of abscissa and ordinates.");
double avg_x = 0;
int total = x.size();
for (auto& datapoint : x) avg_x += datapoint;
avg_x /= total;
double avg_y = 0;
for (auto& prediction : y) avg_y += prediction;
avg_y /= total;
double xdiff = 0;
double ydiff = 0;
double xdiff_square = 0;
double ydiff_square = 0;
double diffprod = 0;
for (int example_idx = 0; example_idx < total; example_idx++) {
xdiff = x[example_idx] - avg_x;
ydiff = y[example_idx] - avg_y;
diffprod += xdiff * ydiff;
xdiff_square += xdiff * xdiff;
ydiff_square += ydiff * ydiff;
}
if (xdiff_square == 0 || ydiff_square == 0) return 0.0;
return diffprod / std::sqrt(xdiff_square * ydiff_square);
}
template double pearson_correlation(const std::vector<float>& x, const std::vector<float>& y);
template double pearson_correlation(const std::vector<double>& x, const std::vector<double>& y);
}
| [
"jonathanraiman@gmail.com"
] | jonathanraiman@gmail.com |
ade20620b4a7ed8760bcbaeade6afafa19d06d2c | f677b66ab73de6bf146eec7a14612b92950c0900 | /examples/state-elimination-nfa/ex2/output.re | 1f23a5673d8c7009962c622388d8a6637ef77bc6 | [
"MIT"
] | permissive | jonathanvdc/automata-generator | d85796fb3d68aadfadd92757a90c2cc1b64fbd2e | 0104f6019c4ef316aecc1aa82243d53e6e3b77f6 | refs/heads/master | 2021-03-12T23:18:44.381178 | 2015-08-04T15:33:53 | 2015-08-04T15:33:53 | 39,786,728 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 21 | re | (o+t(o+t)+to(o+t))*to | [
"jonathan.vdc@outlook.com"
] | jonathan.vdc@outlook.com |
dc83831fb2209f8bd0b634dca36056d9c062d061 | aa2a3a583f7583b70c391d0ea19f37b0fbe6c189 | /C++_primer/3_string/3-5.cpp | d8b299a260f19e80cf0a7a424fe5c904b7c40ac9 | [] | no_license | mayongjian1992/C-_primer_lerning | d4f89e196adfacdfebc634fadaa89aebb7c5308e | cec6fd521563141a44a23ac0c1282a0fe9578363 | refs/heads/master | 2020-04-11T20:14:03.114891 | 2019-02-27T06:30:37 | 2019-02-27T06:30:37 | 162,064,240 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 514 | cpp | /*************************************************************************
> File Name: 3-5.cpp
> Author:micheal.ma
> Mail: micheal.ma@powervision.me
> Created Time: 2018年12月19日 星期三 15时03分33秒
************************************************************************/
#include<iostream>
#include <string>
using namespace std;
int main()
{
string total, s1;
while(cin >> s1 )
{
total=total+s1;
total=total + " ";
}
cout << total<<endl;
return 0;
}
| [
"micheal.ma@powervision.me"
] | micheal.ma@powervision.me |
e9a5ceb91d6241b334f414c7f1cc65a0efee25df | 7cc4bd5ce79fcbaa5fa2a58558aa05f89df0f7a4 | /attic/library - Copy/ports/gf-port-adapters.hpp | c36576f2451c4abf3ef0efab41d5ae6eea16a249 | [] | no_license | wovo/godafoss-c- | 5bde98b077bfd3a2bb0cbe9057abf5b7b0c3ebf4 | 77be6d2661be47af6b6591a944c169021ee71020 | refs/heads/master | 2023-03-17T07:17:15.014692 | 2021-03-27T10:16:18 | 2021-03-27T10:16:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,738 | hpp | // ==========================================================================
//
// gf-port-adapters.hpp
//
// ==========================================================================
//
// This file is part the https://www.github.com/godafoss
// free C++ library for close-to-the-hardware programming.
//
// Copyright Wouter van Ooijen 2019
//
// Distributed under the Boost Software License, Version 1.0.
// (See the accompanying LICENSE_1_0.txt in the root directory of this
// library, or a copy at http://www.boost.org/LICENSE_1_0.txt)
//
// ==========================================================================
// ==========================================================================
//
// concepts
//
// ==========================================================================
template< typename T >
concept can_port_in_out =
is_port_in_out< T >
|| is_port_oc< T >;
template< typename T >
concept can_port_out =
is_port_out< T >
|| is_port_in_out< T >
|| is_port_oc< T >;
template< typename T >
concept can_port_in =
is_port_in< T >
|| is_port_in_out< T >
|| is_port_oc< T >;
template< typename T >
concept can_port_oc =
// a port_in_out is NOT acceptable
is_port_oc< T >;
/*
template< typename T, typename... D >
using _first = T;
template< typename... T >
concept _can_port_out_first =
is_port_out< _first< T > >
|| is_port_in_out< _first< T > >
|| is_port_oc< _first< T > >;
*/
// ==========================================================================
//
// fallbacks
//
// A port can be constructed from another port
// (implemented in this file),
// or from a list of pins (implemented in port-from-pins).
//
// ==========================================================================
template< typename... Ts >
requires
can_pin_in_out_list< Ts...>
|| ( ( sizeof...( Ts ) == 1 ) && ( can_port_in_out< Ts > && ... ) )
struct port_in_out;
template< typename... Ts >
requires
can_pin_out_list< Ts...>
|| ( ( sizeof...( Ts ) == 1 ) && ( can_port_out< Ts > && ... ) )
struct port_out;
template< typename... Ts >
requires
can_pin_in_list< Ts...>
|| ( ( sizeof...( Ts ) == 1 ) && ( can_port_in< Ts > && ... ) )
struct port_in;
template< typename... Ts >
requires
can_pin_oc_list< Ts...>
|| ( ( sizeof...( Ts ) == 1 ) && ( can_port_oc< Ts > && ... ) )
struct port_oc;
// ==========================================================================
//
// adapters
//
// ==========================================================================
template< is_port_in_out T >
struct port_in_out< T > :
be_port_in_out< T::n_pins >,
box_inherit_init< T >,
box_inherit_direction< T >,
box_inherit_write< T >,
box_inherit_read< T >
{};
/* wovo
template< is_port_oc T >
struct pin_in_out< T > :
be_pin_out,
box_init< T >,
box_write< T >,
box_read< T >
{
static GODAFOSS_INLINE void direction_set_input(){
// make all pins high, which is effectively input
T::write( ~0 );
}
static GODAFOSS_INLINE void direction_set_output(){}
static GODAFOSS_INLINE void direction_set_flush(){
T::flush();
}
};
*/
// ==========================================================================
template< is_port_in_out T >
struct port_out< T > :
be_port_out< T::n_pins >,
box_inherit_init< T >,
box_inherit_write< T >
{
static GODAFOSS_INLINE void init(){
T::init();
direct< T >::direction_set_output();
}
};
template< is_port_out T >
struct port_out< T > :
be_port_out< T::n_pins >,
box_inherit_init< T >,
box_inherit_write< T >
{};
template< is_port_oc T >
struct port_out< T > :
be_port_out< T::n_pins >,
box_inherit_init< T >,
box_inherit_write< T >
{};
// ==========================================================================
template< is_port_in_out T >
struct port_in< T > :
be_port_in< T::n_pins >,
box_inherit_init< T >,
box_inherit_read< T >
{
static GODAFOSS_INLINE void init(){
T::init();
direct< T >::direction_set_input();
}
};
template< is_port_in T >
struct port_in< T > :
be_port_in< T::n_pins >,
box_inherit_init< T >,
box_inherit_read< T >
{};
template< is_port_oc T >
struct port_in< T > :
be_port_in< T::n_pins >,
box_inherit_init< T >,
box_inherit_read< T >
{
static GODAFOSS_INLINE void init(){
T::init();
direct< invert< T >>::write( 0 );
}
};
// ==========================================================================
template< is_port_oc T >
struct port_oc< T > :
be_port_oc< T::n_pins >,
box_inherit_init< T >,
box_inherit_write< T >,
box_inherit_read< T >
{};
| [
"wouter@voti.nl"
] | wouter@voti.nl |
6035e13cf4b910bbe9e13067198a0891286e4f7d | b22588340d7925b614a735bbbde1b351ad657ffc | /athena/DetectorDescription/Identifier/Identifier/HWIdentifier.h | 548e58b23477de3e9b1c97e90ee816ec1d18cecc | [] | no_license | rushioda/PIXELVALID_athena | 90befe12042c1249cbb3655dde1428bb9b9a42ce | 22df23187ef85e9c3120122c8375ea0e7d8ea440 | refs/heads/master | 2020-12-14T22:01:15.365949 | 2020-01-19T03:59:35 | 2020-01-19T03:59:35 | 234,836,993 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,232 | h | /*
Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
*/
//<doc><file> $Id: HWIdentifier.h,v 1.3 2004-02-24 13:52:15 schaffer Exp $
//<version> $Name: not supported by cvs2svn $
#ifndef IDENTIFIER_HWIDENTIFIER_H
# define IDENTIFIER_HWIDENTIFIER_H
#include "Identifier/Identifier.h"
class HWIdentifier : public Identifier {
public:
/// Default constructor
HWIdentifier ();
/// Constructor from value_type
explicit HWIdentifier(value_type value);
/// Constructor from Identifier
explicit HWIdentifier(const Identifier& old);
/// Constructor from Identifier32 value_type (unsigned int)
explicit HWIdentifier(Identifier32::value_type value);
explicit HWIdentifier(int value);
};
inline HWIdentifier::HWIdentifier()
: Identifier::Identifier()
{}
inline HWIdentifier::HWIdentifier(value_type value)
: Identifier::Identifier(value)
{}
inline HWIdentifier::HWIdentifier(const Identifier& old)
: Identifier::Identifier(old)
{}
inline HWIdentifier::HWIdentifier(Identifier32::value_type value)
: Identifier::Identifier(value)
{}
inline HWIdentifier::HWIdentifier(int value)
: Identifier::Identifier(value)
{}
#endif // IDENTIFIER_HWIDENTIFIER_H
| [
"rushioda@lxplus754.cern.ch"
] | rushioda@lxplus754.cern.ch |
7556cc4c754e2305a8655a3426ac822a63a85ab0 | 763159c1308c14447b389209244645c7b638ccb5 | /sstd_botan/mingw_gcc/build/include/botan/emsa.h | cd424e64c9fdcfa0ee777db0449c0f29af3a43d5 | [] | no_license | 15831944/sstd_library | 9f53791df831724b02f7e86988fbd9a3c146e6b6 | 10c2ec1db09417c6d3217a37462db5bbf1a6fa5c | refs/heads/master | 2022-03-09T06:50:09.977767 | 2019-07-20T03:10:51 | 2019-07-20T03:10:51 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,180 | h | /*
* EMSA Classes
* (C) 1999-2007 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#ifndef BOTAN_PUBKEY_EMSA_H_
#define BOTAN_PUBKEY_EMSA_H_
#include <botan/secmem.h>
#include <botan/alg_id.h>
#include <string>
namespace Botan {
class Private_Key;
class RandomNumberGenerator;
/**
* EMSA, from IEEE 1363s Encoding Method for Signatures, Appendix
*
* Any way of encoding/padding signatures
*/
class BOTAN_PUBLIC_API(2,0) EMSA
{
public:
virtual ~EMSA() = default;
/**
* Add more data to the signature computation
* @param input some data
* @param length length of input in bytes
*/
virtual void update(const uint8_t input[], size_t length) = 0;
/**
* @return raw hash
*/
virtual secure_vector<uint8_t> raw_data() = 0;
/**
* Return the encoding of a message
* @param msg the result of raw_data()
* @param output_bits the desired output bit size
* @param rng a random number generator
* @return encoded signature
*/
virtual secure_vector<uint8_t> encoding_of(const secure_vector<uint8_t>& msg,
size_t output_bits,
RandomNumberGenerator& rng) = 0;
/**
* Verify the encoding
* @param coded the received (coded) message representative
* @param raw the computed (local, uncoded) message representative
* @param key_bits the size of the key in bits
* @return true if coded is a valid encoding of raw, otherwise false
*/
virtual bool verify(const secure_vector<uint8_t>& coded,
const secure_vector<uint8_t>& raw,
size_t key_bits) = 0;
/**
* Prepare sig_algo for use in choose_sig_format for x509 certs
*
* @param key used for checking compatibility with the encoding scheme
* @param cert_hash_name is checked to equal the hash for the encoding
* @return algorithm identifier to signatures created using this key,
* padding method and hash.
*/
virtual AlgorithmIdentifier config_for_x509(const Private_Key& key,
const std::string& cert_hash_name) const;
/**
* @return a new object representing the same encoding method as *this
*/
virtual EMSA* clone() = 0;
/**
* @return the SCAN name of the encoding/padding scheme
*/
virtual std::string name() const = 0;
};
/**
* Factory method for EMSA (message-encoding methods for signatures
* with appendix) objects
* @param algo_spec the name of the EMSA to create
* @return pointer to newly allocated object of that type
*/
BOTAN_PUBLIC_API(2,0) EMSA* get_emsa(const std::string& algo_spec);
/**
* Returns the hash function used in the given EMSA scheme
* If the hash function is not specified or not understood,
* returns "SHA-512"
* @param algo_spec the name of the EMSA
* @return hash function used in the given EMSA scheme
*/
BOTAN_PUBLIC_API(2,0) std::string hash_for_emsa(const std::string& algo_spec);
}
#endif
| [
"zhaixueqiang@hotmail.com"
] | zhaixueqiang@hotmail.com |
c187903a43d7a6348b25839b398890ae4c64d993 | 4352b5c9e6719d762e6a80e7a7799630d819bca3 | /tutorials/eulerVortex.twitch/eulerVortex.cyclic.twitch.test.test/processor1/3.3/rho | 2804a9c87554ff06a83d5540edc3e82bc0cbcd41 | [] | no_license | dashqua/epicProject | d6214b57c545110d08ad053e68bc095f1d4dc725 | 54afca50a61c20c541ef43e3d96408ef72f0bcbc | refs/heads/master | 2022-02-28T17:20:20.291864 | 2019-10-28T13:33:16 | 2019-10-28T13:33:16 | 184,294,390 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 45,287 | /*--------------------------------*- C++ -*----------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration | Website: https://openfoam.org
\\ / A nd | Version: 6
\\/ M anipulation |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class volScalarField;
location "3.3";
object rho;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [1 -3 0 0 0 0 0];
internalField nonuniform List<scalar>
5625
(
1.44904
1.43977
1.42875
1.41676
1.40446
1.39239
1.38092
1.37019
1.36016
1.35072
1.34169
1.33277
1.32358
1.31386
1.30363
1.2931
1.2824
1.27178
1.26195
1.25376
1.24763
1.24386
1.24297
1.24543
1.25098
1.25868
1.26767
1.27757
1.28817
1.29898
1.30946
1.31944
1.32909
1.33868
1.34828
1.35797
1.36801
1.37889
1.391
1.40435
1.41834
1.43182
1.44336
1.45166
1.45591
1.45603
1.45261
1.4467
1.43948
1.43199
1.42498
1.4189
1.41391
1.41001
1.40706
1.4049
1.40336
1.40229
1.40156
1.40106
1.40073
1.4005
1.40035
1.40025
1.40018
1.40013
1.40009
1.40007
1.40005
1.40004
1.40003
1.40002
1.40001
1.40001
1.40001
1.45206
1.44387
1.43373
1.42239
1.41053
1.39869
1.38733
1.37666
1.36676
1.35764
1.34915
1.341
1.33295
1.32487
1.31672
1.30846
1.3001
1.29199
1.28465
1.2785
1.27378
1.27088
1.27027
1.27207
1.27593
1.2812
1.28752
1.2948
1.30289
1.31136
1.31981
1.32821
1.33677
1.34563
1.35478
1.36423
1.37425
1.38522
1.39742
1.41066
1.42419
1.43679
1.44706
1.45385
1.45658
1.45539
1.45102
1.44457
1.43718
1.4298
1.42306
1.41732
1.41268
1.40908
1.40638
1.40443
1.40304
1.40208
1.40142
1.40097
1.40067
1.40047
1.40033
1.40023
1.40017
1.40012
1.40009
1.40006
1.40005
1.40003
1.40003
1.40002
1.40001
1.40001
1.40001
1.45474
1.44779
1.43865
1.42808
1.41677
1.40529
1.39409
1.38349
1.37367
1.3647
1.35648
1.34883
1.34163
1.33476
1.32805
1.32136
1.31481
1.30868
1.30318
1.29847
1.29484
1.29264
1.29212
1.29321
1.29564
1.29912
1.30358
1.30905
1.31537
1.32217
1.3292
1.33655
1.34439
1.35278
1.36163
1.37095
1.38099
1.39205
1.40425
1.41724
1.43013
1.44163
1.45044
1.4556
1.45677
1.45429
1.44906
1.44218
1.43472
1.42752
1.42111
1.41574
1.41145
1.40817
1.40573
1.40397
1.40273
1.40187
1.40128
1.40088
1.40061
1.40043
1.40031
1.40022
1.40016
1.40012
1.40009
1.40006
1.40005
1.40003
1.40003
1.40002
1.40001
1.40001
1.40001
1.45693
1.45138
1.44339
1.43373
1.4231
1.41209
1.40117
1.3907
1.38094
1.37201
1.36389
1.35653
1.34985
1.3437
1.33787
1.33231
1.32714
1.32241
1.31811
1.31441
1.31161
1.30989
1.30928
1.30976
1.31119
1.31352
1.3168
1.3211
1.32623
1.33189
1.33801
1.34471
1.35213
1.36022
1.36889
1.37814
1.38821
1.39932
1.41142
1.42398
1.43599
1.44617
1.45335
1.45678
1.45638
1.45271
1.44673
1.43954
1.43212
1.42519
1.41915
1.41418
1.41026
1.40729
1.4051
1.40353
1.40243
1.40167
1.40115
1.4008
1.40056
1.4004
1.40029
1.40021
1.40015
1.40011
1.40008
1.40006
1.40004
1.40003
1.40002
1.40002
1.40001
1.40001
1.40001
1.45852
1.45448
1.44781
1.43923
1.42941
1.41899
1.40846
1.39822
1.38856
1.37964
1.37155
1.3643
1.35786
1.35204
1.34673
1.34193
1.33764
1.33373
1.33018
1.32724
1.32503
1.32355
1.32282
1.3229
1.32377
1.32547
1.32809
1.33167
1.33603
1.34098
1.34656
1.35291
1.36011
1.36803
1.37658
1.3858
1.39588
1.40696
1.4188
1.43071
1.4416
1.45025
1.45564
1.45729
1.45539
1.45063
1.44406
1.4367
1.42943
1.42283
1.41721
1.41266
1.40912
1.40645
1.40451
1.40312
1.40215
1.40149
1.40103
1.40072
1.40051
1.40036
1.40026
1.40019
1.40014
1.4001
1.40008
1.40006
1.40004
1.40003
1.40002
1.40002
1.40001
1.40001
1.40001
1.45936
1.45696
1.45177
1.44441
1.43557
1.42589
1.41588
1.40597
1.39648
1.38762
1.37953
1.37231
1.36589
1.36018
1.35514
1.35076
1.34689
1.3434
1.34037
1.33794
1.33607
1.3347
1.33392
1.33384
1.33448
1.33589
1.33818
1.34135
1.34526
1.34981
1.35513
1.36133
1.36842
1.37625
1.38471
1.39389
1.40395
1.41486
1.42624
1.43725
1.44676
1.45366
1.45716
1.45705
1.45374
1.44807
1.44107
1.4337
1.42669
1.42049
1.41532
1.4112
1.40803
1.40567
1.40395
1.40274
1.4019
1.40131
1.40092
1.40065
1.40046
1.40033
1.40024
1.40018
1.40013
1.4001
1.40007
1.40005
1.40004
1.40003
1.40002
1.40002
1.40001
1.40001
1.40001
1.45934
1.45866
1.45507
1.44911
1.44143
1.43265
1.42329
1.41384
1.40462
1.3959
1.38786
1.38062
1.37415
1.36844
1.3635
1.35924
1.3555
1.35224
1.34955
1.34738
1.34563
1.34434
1.34364
1.34359
1.34417
1.3455
1.34766
1.35062
1.35428
1.35867
1.36391
1.37009
1.37712
1.38485
1.39323
1.40235
1.41228
1.42286
1.43354
1.44337
1.45126
1.45624
1.4578
1.45601
1.45146
1.44508
1.43784
1.4306
1.42394
1.4182
1.4135
1.40981
1.407
1.40493
1.40344
1.40239
1.40166
1.40115
1.40081
1.40058
1.40042
1.4003
1.40022
1.40016
1.40012
1.40009
1.40007
1.40005
1.40004
1.40003
1.40002
1.40002
1.40001
1.40001
1.40001
1.45837
1.45943
1.45755
1.45315
1.4468
1.43908
1.43055
1.4217
1.41288
1.40441
1.39649
1.38925
1.38273
1.377
1.37203
1.36773
1.364
1.36087
1.3583
1.3562
1.35452
1.35335
1.35279
1.35281
1.35343
1.35479
1.35694
1.35982
1.3634
1.36777
1.37304
1.37922
1.38619
1.39381
1.40209
1.41108
1.42074
1.43077
1.44046
1.44882
1.45486
1.45782
1.45748
1.45415
1.44858
1.44171
1.43443
1.42745
1.42124
1.416
1.41178
1.40851
1.40605
1.40426
1.40297
1.40206
1.40144
1.40101
1.40072
1.40051
1.40037
1.40027
1.4002
1.40015
1.40011
1.40008
1.40006
1.40005
1.40003
1.40003
1.40002
1.40001
1.40001
1.40001
1.40001
1.45641
1.45915
1.45905
1.45633
1.45146
1.445
1.43748
1.42939
1.42112
1.41302
1.40532
1.39817
1.39167
1.38591
1.38087
1.37648
1.37272
1.36961
1.36705
1.36495
1.36335
1.36232
1.36187
1.36197
1.36268
1.36412
1.36631
1.3692
1.3728
1.37721
1.38254
1.3887
1.39558
1.40306
1.41116
1.4199
1.42911
1.43832
1.44671
1.45334
1.45735
1.45827
1.45615
1.4515
1.44517
1.43805
1.43091
1.42433
1.41862
1.41391
1.41018
1.40732
1.40519
1.40364
1.40254
1.40177
1.40124
1.40088
1.40063
1.40045
1.40033
1.40025
1.40018
1.40014
1.4001
1.40008
1.40006
1.40004
1.40003
1.40002
1.40002
1.40001
1.40001
1.40001
1.40001
1.45344
1.45774
1.45941
1.45846
1.45523
1.45019
1.44386
1.43671
1.42917
1.42158
1.41422
1.40727
1.40088
1.39514
1.39005
1.38561
1.38183
1.37867
1.37607
1.37398
1.37247
1.37155
1.37117
1.37134
1.37216
1.37371
1.37596
1.37888
1.38254
1.38703
1.39238
1.39847
1.40519
1.41246
1.4203
1.42862
1.43712
1.4452
1.452
1.45667
1.45857
1.45752
1.45383
1.44816
1.44134
1.43421
1.42738
1.42129
1.41613
1.41196
1.40869
1.40622
1.4044
1.40309
1.40216
1.40151
1.40107
1.40076
1.40055
1.4004
1.4003
1.40022
1.40017
1.40013
1.40009
1.40007
1.40005
1.40004
1.40003
1.40002
1.40002
1.40001
1.40001
1.40001
1.40001
1.44957
1.45518
1.45852
1.45937
1.45788
1.45442
1.44944
1.44342
1.43678
1.42989
1.42301
1.4164
1.41024
1.40461
1.39955
1.39511
1.39133
1.38814
1.38551
1.38345
1.382
1.38113
1.38079
1.38106
1.38201
1.38364
1.38594
1.3889
1.39263
1.39716
1.40245
1.40839
1.41487
1.42185
1.42927
1.43695
1.44445
1.45108
1.45601
1.45858
1.4584
1.45559
1.45061
1.44423
1.43723
1.4303
1.42392
1.41839
1.41381
1.41016
1.40735
1.40525
1.4037
1.4026
1.40182
1.40128
1.40091
1.40066
1.40048
1.40035
1.40026
1.4002
1.40015
1.40011
1.40009
1.40006
1.40005
1.40004
1.40003
1.40002
1.40002
1.40001
1.40001
1.40001
1.40001
1.44494
1.45153
1.45632
1.45891
1.45922
1.45745
1.45399
1.44928
1.44372
1.43768
1.43148
1.42537
1.41956
1.41415
1.40922
1.40488
1.40113
1.39795
1.39534
1.39333
1.39193
1.39108
1.39081
1.39117
1.3922
1.39389
1.39622
1.39921
1.40296
1.40745
1.4126
1.41829
1.42443
1.43097
1.43778
1.44455
1.45072
1.4556
1.45848
1.45893
1.45684
1.45254
1.44665
1.4399
1.43297
1.42643
1.42061
1.41568
1.41168
1.40854
1.40615
1.40438
1.40309
1.40217
1.40153
1.40108
1.40077
1.40056
1.40041
1.40031
1.40023
1.40018
1.40013
1.4001
1.40008
1.40006
1.40004
1.40003
1.40003
1.40002
1.40001
1.40001
1.40001
1.40001
1.40001
1.43978
1.44693
1.45288
1.45701
1.45907
1.45907
1.45727
1.45401
1.44971
1.44471
1.43936
1.43392
1.42858
1.42353
1.41888
1.41472
1.41107
1.40796
1.40543
1.4035
1.40214
1.40133
1.40112
1.40156
1.40265
1.40435
1.40667
1.40967
1.41337
1.41772
1.42261
1.42793
1.4336
1.43952
1.44545
1.45099
1.45553
1.45845
1.45923
1.45768
1.45397
1.44857
1.44213
1.43533
1.42872
1.42271
1.41751
1.4132
1.40976
1.4071
1.40509
1.40361
1.40255
1.4018
1.40127
1.40091
1.40066
1.40048
1.40036
1.40027
1.4002
1.40016
1.40012
1.40009
1.40007
1.40005
1.40004
1.40003
1.40002
1.40002
1.40001
1.40001
1.40001
1.40001
1.40001
1.43442
1.44167
1.44832
1.45369
1.45733
1.45908
1.459
1.45736
1.45447
1.45069
1.44635
1.44172
1.43704
1.4325
1.42825
1.42438
1.42094
1.41799
1.41559
1.41375
1.41244
1.41171
1.41158
1.41207
1.41315
1.41483
1.41712
1.42005
1.4236
1.42769
1.43219
1.437
1.44203
1.44709
1.45186
1.45586
1.45854
1.4594
1.45818
1.45492
1.44998
1.44389
1.43729
1.43072
1.4246
1.41921
1.41467
1.41097
1.40806
1.40583
1.40417
1.40296
1.40209
1.40148
1.40105
1.40076
1.40055
1.40041
1.40031
1.40023
1.40018
1.40014
1.40011
1.40008
1.40006
1.40005
1.40004
1.40003
1.40002
1.40002
1.40001
1.40001
1.40001
1.40001
1.40001
1.42914
1.43608
1.44296
1.44914
1.45405
1.45737
1.459
1.45903
1.45769
1.45528
1.45213
1.4485
1.44464
1.44077
1.43703
1.43356
1.43044
1.42775
1.42554
1.42383
1.42263
1.42198
1.42191
1.42242
1.42348
1.42509
1.42729
1.43006
1.43334
1.43702
1.44099
1.44514
1.4493
1.45323
1.45655
1.45879
1.4595
1.45839
1.45544
1.45087
1.44514
1.43879
1.43235
1.42623
1.42074
1.41602
1.41212
1.409
1.40657
1.40474
1.40338
1.4024
1.4017
1.40121
1.40087
1.40063
1.40046
1.40035
1.40026
1.4002
1.40016
1.40012
1.40009
1.40007
1.40005
1.40004
1.40003
1.40002
1.40002
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.42418
1.43052
1.43718
1.44367
1.44942
1.454
1.45714
1.4588
1.45907
1.45817
1.45635
1.45388
1.451
1.44795
1.44487
1.44193
1.43925
1.43691
1.43495
1.43341
1.43236
1.43183
1.43181
1.43231
1.43331
1.43482
1.43684
1.43932
1.44219
1.44532
1.44859
1.45186
1.45491
1.45746
1.45912
1.4595
1.45834
1.45554
1.45127
1.44587
1.4398
1.43355
1.42752
1.422
1.41719
1.41315
1.40987
1.40728
1.40529
1.4038
1.40271
1.40192
1.40137
1.40098
1.40071
1.40052
1.40039
1.40029
1.40022
1.40017
1.40014
1.4001
1.40008
1.40006
1.40005
1.40004
1.40003
1.40002
1.40002
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.4197
1.42527
1.43139
1.43772
1.44381
1.4492
1.45353
1.45662
1.45842
1.45905
1.45865
1.45747
1.45573
1.45363
1.45137
1.4491
1.44696
1.44504
1.44341
1.44215
1.44128
1.44086
1.44087
1.44132
1.44222
1.44356
1.44531
1.44738
1.44968
1.45209
1.45448
1.45666
1.4584
1.4594
1.45934
1.45798
1.45522
1.45116
1.44605
1.44028
1.43428
1.42841
1.42297
1.41815
1.41404
1.41064
1.40793
1.40582
1.40421
1.40302
1.40215
1.40153
1.40109
1.40079
1.40057
1.40043
1.40032
1.40025
1.40019
1.40015
1.40012
1.40009
1.40007
1.40005
1.40004
1.40003
1.40003
1.40002
1.40002
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.4158
1.42052
1.42591
1.43174
1.43769
1.44338
1.44846
1.45262
1.45573
1.45776
1.45877
1.45893
1.4584
1.45739
1.45607
1.45459
1.4531
1.4517
1.45049
1.44953
1.44889
1.44858
1.44862
1.44901
1.44975
1.45082
1.45217
1.45369
1.45529
1.45683
1.45817
1.45911
1.45943
1.45887
1.45724
1.45444
1.45051
1.44567
1.44021
1.4345
1.42886
1.42357
1.41882
1.41472
1.41128
1.40849
1.40628
1.40459
1.40331
1.40237
1.40169
1.4012
1.40087
1.40063
1.40046
1.40035
1.40027
1.40021
1.40016
1.40013
1.4001
1.40008
1.40006
1.40005
1.40004
1.40003
1.40002
1.40002
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.41249
1.41639
1.42096
1.42608
1.43156
1.43711
1.44243
1.44721
1.45123
1.45439
1.45664
1.45806
1.45876
1.45886
1.45854
1.45793
1.45718
1.45639
1.45565
1.45506
1.45465
1.45446
1.45451
1.4548
1.45533
1.45605
1.45688
1.45775
1.45853
1.4591
1.45931
1.45898
1.45794
1.45601
1.45313
1.44931
1.44472
1.43959
1.4342
1.42886
1.42379
1.41919
1.41516
1.41174
1.40893
1.40667
1.40491
1.40357
1.40257
1.40184
1.40131
1.40094
1.40068
1.4005
1.40037
1.40028
1.40022
1.40017
1.40014
1.40011
1.40009
1.40007
1.40005
1.40004
1.40003
1.40003
1.40002
1.40002
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40973
1.41289
1.41666
1.42099
1.4258
1.43088
1.43601
1.44093
1.44542
1.44931
1.45249
1.45494
1.45671
1.45786
1.45851
1.45879
1.4588
1.45865
1.45843
1.45822
1.45806
1.45799
1.45804
1.4582
1.45845
1.45875
1.45901
1.45916
1.45909
1.45868
1.45782
1.45635
1.45418
1.45123
1.44753
1.44319
1.4384
1.43339
1.42838
1.42361
1.41923
1.41534
1.412
1.40922
1.40695
1.40517
1.40378
1.40274
1.40197
1.40141
1.40101
1.40073
1.40053
1.4004
1.4003
1.40023
1.40018
1.40014
1.40011
1.40009
1.40007
1.40006
1.40005
1.40004
1.40003
1.40002
1.40002
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40749
1.41
1.41303
1.4166
1.42065
1.42508
1.42972
1.43439
1.43892
1.4431
1.4468
1.44994
1.45251
1.45451
1.456
1.45707
1.45779
1.45825
1.45853
1.45869
1.45877
1.45882
1.45885
1.45886
1.45881
1.45867
1.45837
1.45783
1.45698
1.45572
1.45396
1.45163
1.44868
1.44515
1.44109
1.43667
1.43206
1.42745
1.42302
1.41892
1.41524
1.41204
1.40934
1.40712
1.40534
1.40394
1.40287
1.40207
1.40149
1.40107
1.40077
1.40056
1.40041
1.40031
1.40024
1.40019
1.40015
1.40012
1.4001
1.40008
1.40006
1.40005
1.40004
1.40003
1.40002
1.40002
1.40002
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.4057
1.40766
1.41006
1.41292
1.41623
1.41993
1.42394
1.42812
1.43234
1.43642
1.44025
1.4437
1.44671
1.44926
1.45136
1.45304
1.45433
1.45529
1.45599
1.45647
1.45677
1.45691
1.45691
1.45677
1.45645
1.45592
1.45513
1.45403
1.45257
1.45068
1.44832
1.44548
1.44217
1.43845
1.43443
1.43026
1.42608
1.42205
1.41828
1.41486
1.41186
1.40929
1.40715
1.40541
1.40403
1.40296
1.40215
1.40154
1.40111
1.40079
1.40058
1.40042
1.40032
1.40024
1.40019
1.40015
1.40012
1.4001
1.40008
1.40006
1.40005
1.40004
1.40003
1.40003
1.40002
1.40002
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40429
1.4058
1.40766
1.40991
1.41255
1.41556
1.41888
1.42245
1.42616
1.42988
1.4335
1.43691
1.44004
1.44283
1.44524
1.44726
1.44892
1.45024
1.45123
1.45195
1.4524
1.45261
1.45258
1.45231
1.45178
1.45096
1.44983
1.44836
1.44652
1.44429
1.44166
1.43865
1.43532
1.43175
1.42805
1.42434
1.42073
1.41733
1.41422
1.41146
1.40906
1.40704
1.40538
1.40404
1.40299
1.40218
1.40158
1.40113
1.40081
1.40059
1.40043
1.40032
1.40024
1.40019
1.40015
1.40012
1.4001
1.40008
1.40007
1.40005
1.40004
1.40004
1.40003
1.40002
1.40002
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40319
1.40434
1.40577
1.40751
1.40957
1.41195
1.41463
1.41756
1.42066
1.42388
1.4271
1.43023
1.4332
1.43593
1.43838
1.44052
1.44233
1.44381
1.44496
1.4458
1.44634
1.44659
1.44653
1.44618
1.44552
1.44455
1.44325
1.44161
1.43963
1.43731
1.43468
1.43179
1.42871
1.4255
1.42227
1.41911
1.41611
1.41334
1.41085
1.40867
1.4068
1.40524
1.40397
1.40296
1.40218
1.40158
1.40114
1.40082
1.40059
1.40043
1.40031
1.40024
1.40018
1.40015
1.40012
1.4001
1.40008
1.40007
1.40005
1.40004
1.40004
1.40003
1.40002
1.40002
1.40002
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40235
1.40322
1.4043
1.40562
1.4072
1.40905
1.41115
1.41349
1.41601
1.41866
1.42138
1.4241
1.42673
1.42922
1.43151
1.43355
1.43533
1.43681
1.43799
1.43885
1.43941
1.43965
1.43959
1.43921
1.43852
1.4375
1.43617
1.43454
1.43262
1.43043
1.42801
1.42541
1.42271
1.41997
1.41727
1.41469
1.41227
1.41007
1.40812
1.40643
1.405
1.40382
1.40288
1.40213
1.40155
1.40112
1.4008
1.40058
1.40042
1.4003
1.40023
1.40018
1.40014
1.40011
1.40009
1.40008
1.40006
1.40005
1.40005
1.40004
1.40003
1.40003
1.40002
1.40002
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40172
1.40237
1.40318
1.40417
1.40536
1.40677
1.40839
1.4102
1.41219
1.41431
1.41652
1.41877
1.42099
1.42312
1.42513
1.42696
1.42856
1.42992
1.43102
1.43184
1.43237
1.43259
1.43252
1.43215
1.43148
1.43052
1.42929
1.42778
1.42604
1.4241
1.422
1.41979
1.41753
1.41528
1.41311
1.41105
1.40915
1.40745
1.40596
1.40468
1.40361
1.40274
1.40204
1.4015
1.40108
1.40078
1.40055
1.4004
1.40029
1.40021
1.40016
1.40013
1.4001
1.40009
1.40007
1.40006
1.40005
1.40004
1.40004
1.40003
1.40003
1.40002
1.40002
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40126
1.40173
1.40233
1.40306
1.40396
1.40501
1.40623
1.40761
1.40914
1.4108
1.41254
1.41433
1.41613
1.41788
1.41955
1.42109
1.42247
1.42365
1.4246
1.42532
1.42578
1.42597
1.4259
1.42556
1.42496
1.42412
1.42303
1.42173
1.42024
1.41861
1.41686
1.41506
1.41323
1.41145
1.40974
1.40814
1.40669
1.4054
1.40428
1.40333
1.40254
1.40191
1.40141
1.40102
1.40073
1.40052
1.40037
1.40027
1.40019
1.40015
1.40011
1.40009
1.40008
1.40006
1.40006
1.40005
1.40004
1.40004
1.40003
1.40003
1.40002
1.40002
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40091
1.40126
1.4017
1.40224
1.40289
1.40367
1.40458
1.40562
1.40677
1.40803
1.40936
1.41075
1.41216
1.41355
1.41489
1.41613
1.41726
1.41823
1.41902
1.41961
1.41999
1.42015
1.42008
1.41979
1.41928
1.41856
1.41765
1.41657
1.41535
1.41403
1.41263
1.4112
1.40977
1.40839
1.40708
1.40587
1.40478
1.40383
1.403
1.40231
1.40175
1.4013
1.40094
1.40068
1.40048
1.40034
1.40024
1.40017
1.40013
1.4001
1.40008
1.40006
1.40006
1.40005
1.40004
1.40004
1.40003
1.40003
1.40003
1.40002
1.40002
1.40002
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40067
1.40092
1.40123
1.40163
1.4021
1.40268
1.40334
1.4041
1.40496
1.40589
1.4069
1.40795
1.40903
1.41009
1.41113
1.4121
1.41298
1.41375
1.41437
1.41484
1.41514
1.41526
1.4152
1.41496
1.41454
1.41395
1.41322
1.41235
1.41139
1.41034
1.40925
1.40815
1.40706
1.40602
1.40504
1.40414
1.40334
1.40265
1.40205
1.40156
1.40116
1.40085
1.40061
1.40043
1.4003
1.40021
1.40015
1.4001
1.40008
1.40006
1.40005
1.40005
1.40004
1.40004
1.40003
1.40003
1.40003
1.40002
1.40002
1.40002
1.40002
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40049
1.40067
1.4009
1.40118
1.40152
1.40194
1.40242
1.40298
1.4036
1.40429
1.40503
1.4058
1.4066
1.4074
1.40819
1.40892
1.40959
1.41017
1.41065
1.41101
1.41123
1.41132
1.41126
1.41106
1.41072
1.41026
1.40968
1.40901
1.40827
1.40747
1.40664
1.40581
1.40499
1.40422
1.4035
1.40285
1.40227
1.40177
1.40136
1.40102
1.40074
1.40053
1.40037
1.40026
1.40017
1.40012
1.40008
1.40006
1.40005
1.40004
1.40003
1.40003
1.40003
1.40003
1.40003
1.40002
1.40002
1.40002
1.40002
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40036
1.40049
1.40066
1.40086
1.40111
1.4014
1.40175
1.40215
1.4026
1.40309
1.40362
1.40419
1.40478
1.40536
1.40593
1.40647
1.40697
1.4074
1.40776
1.40801
1.40818
1.40823
1.40818
1.40802
1.40775
1.40739
1.40695
1.40643
1.40587
1.40527
1.40465
1.40404
1.40345
1.40288
1.40237
1.4019
1.4015
1.40115
1.40086
1.40063
1.40045
1.40031
1.40021
1.40014
1.40009
1.40006
1.40004
1.40003
1.40002
1.40002
1.40002
1.40002
1.40002
1.40002
1.40002
1.40002
1.40002
1.40002
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40027
1.40037
1.40049
1.40063
1.4008
1.40101
1.40126
1.40154
1.40186
1.40222
1.4026
1.403
1.40341
1.40384
1.40425
1.40464
1.40499
1.4053
1.40555
1.40574
1.40585
1.40588
1.40583
1.4057
1.4055
1.40522
1.40488
1.4045
1.40408
1.40364
1.40319
1.40274
1.40231
1.40191
1.40155
1.40123
1.40095
1.40071
1.40052
1.40036
1.40025
1.40016
1.4001
1.40006
1.40003
1.40002
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40002
1.40002
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40021
1.40027
1.40036
1.40047
1.40059
1.40074
1.40091
1.40111
1.40133
1.40158
1.40185
1.40213
1.40243
1.40272
1.40301
1.40328
1.40353
1.40375
1.40392
1.40404
1.40411
1.40413
1.40408
1.40397
1.40382
1.40361
1.40336
1.40308
1.40277
1.40245
1.40212
1.40181
1.40151
1.40123
1.40097
1.40075
1.40056
1.40041
1.40028
1.40019
1.40011
1.40006
1.40003
1.40001
1.4
1.39999
1.39999
1.4
1.4
1.4
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40016
1.40021
1.40028
1.40035
1.40044
1.40054
1.40066
1.4008
1.40096
1.40113
1.40131
1.40151
1.40171
1.40192
1.40211
1.4023
1.40247
1.40261
1.40273
1.40281
1.40285
1.40285
1.40281
1.40272
1.4026
1.40244
1.40226
1.40205
1.40183
1.4016
1.40137
1.40115
1.40094
1.40075
1.40058
1.40043
1.40031
1.40021
1.40013
1.40007
1.40003
1.4
1.39999
1.39998
1.39998
1.39998
1.39998
1.39999
1.39999
1.4
1.4
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.4
1.4
1.40001
1.40013
1.40016
1.40021
1.40026
1.40033
1.4004
1.40049
1.40058
1.40069
1.40081
1.40094
1.40107
1.4012
1.40134
1.40148
1.4016
1.40171
1.4018
1.40188
1.40192
1.40194
1.40193
1.40189
1.40183
1.40173
1.40162
1.40148
1.40133
1.40117
1.40101
1.40085
1.4007
1.40055
1.40043
1.40031
1.40022
1.40014
1.40008
1.40004
1.4
1.39998
1.39997
1.39996
1.39996
1.39997
1.39997
1.39998
1.39999
1.39999
1.4
1.4
1.4
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.4001
1.40013
1.40016
1.4002
1.40025
1.4003
1.40036
1.40043
1.4005
1.40058
1.40067
1.40076
1.40085
1.40094
1.40102
1.40111
1.40118
1.40123
1.40127
1.4013
1.4013
1.40129
1.40126
1.4012
1.40113
1.40104
1.40094
1.40084
1.40072
1.40061
1.4005
1.4004
1.4003
1.40022
1.40015
1.40008
1.40004
1.4
1.39998
1.39996
1.39995
1.39995
1.39995
1.39996
1.39996
1.39997
1.39998
1.39999
1.39999
1.39999
1.4
1.4
1.4
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.4
1.4
1.4
1.40001
1.40008
1.40011
1.40013
1.40016
1.40019
1.40023
1.40027
1.40032
1.40037
1.40043
1.40048
1.40054
1.4006
1.40066
1.40071
1.40076
1.4008
1.40084
1.40086
1.40087
1.40087
1.40085
1.40082
1.40077
1.40072
1.40065
1.40058
1.4005
1.40043
1.40035
1.40027
1.4002
1.40014
1.40009
1.40004
1.40001
1.39998
1.39996
1.39995
1.39994
1.39994
1.39994
1.39995
1.39996
1.39996
1.39997
1.39998
1.39999
1.39999
1.4
1.4
1.4
1.4
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40006
1.40008
1.40011
1.40013
1.40015
1.40018
1.40021
1.40024
1.40028
1.40032
1.40035
1.40039
1.40043
1.40047
1.4005
1.40053
1.40055
1.40057
1.40058
1.40058
1.40057
1.40055
1.40052
1.40049
1.40044
1.4004
1.40034
1.40029
1.40023
1.40018
1.40013
1.40008
1.40004
1.40001
1.39998
1.39996
1.39995
1.39994
1.39993
1.39994
1.39994
1.39995
1.39995
1.39996
1.39997
1.39998
1.39998
1.39999
1.39999
1.4
1.4
1.4
1.4
1.4
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.4
1.4
1.4
1.4
1.40001
1.40006
1.40007
1.40008
1.4001
1.40012
1.40014
1.40016
1.40019
1.40021
1.40023
1.40026
1.40029
1.40031
1.40033
1.40035
1.40037
1.40038
1.40039
1.40039
1.40038
1.40037
1.40035
1.40033
1.4003
1.40027
1.40023
1.40019
1.40015
1.40011
1.40007
1.40004
1.40001
1.39999
1.39997
1.39995
1.39994
1.39993
1.39993
1.39993
1.39994
1.39994
1.39995
1.39996
1.39996
1.39997
1.39998
1.39998
1.39999
1.39999
1.4
1.4
1.4
1.4
1.4
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.4
1.4
1.4
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40004
1.40006
1.40007
1.40008
1.40009
1.40011
1.40013
1.40014
1.40016
1.40018
1.4002
1.40021
1.40023
1.40024
1.40025
1.40026
1.40026
1.40027
1.40026
1.40025
1.40024
1.40022
1.4002
1.40018
1.40015
1.40012
1.4001
1.40007
1.40004
1.40002
1.39999
1.39997
1.39996
1.39995
1.39994
1.39993
1.39993
1.39993
1.39994
1.39994
1.39995
1.39996
1.39996
1.39997
1.39998
1.39998
1.39999
1.39999
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.4
1.4
1.4
1.4
1.40001
1.40004
1.40004
1.40005
1.40007
1.40008
1.40009
1.4001
1.40011
1.40013
1.40014
1.40015
1.40016
1.40017
1.40018
1.40018
1.40018
1.40018
1.40018
1.40017
1.40017
1.40016
1.40014
1.40012
1.4001
1.40008
1.40006
1.40004
1.40002
1.4
1.39998
1.39997
1.39996
1.39995
1.39994
1.39994
1.39993
1.39994
1.39994
1.39994
1.39995
1.39996
1.39996
1.39997
1.39997
1.39998
1.39999
1.39999
1.39999
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.40001
1.40001
1.40001
1.40001
1.40001
1.4
1.4
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40003
1.40004
1.40004
1.40005
1.40006
1.40007
1.40008
1.40009
1.4001
1.40011
1.40012
1.40012
1.40013
1.40013
1.40013
1.40013
1.40013
1.40013
1.40012
1.40011
1.4001
1.40009
1.40007
1.40006
1.40004
1.40003
1.40001
1.4
1.39998
1.39997
1.39996
1.39995
1.39995
1.39994
1.39994
1.39994
1.39994
1.39995
1.39995
1.39996
1.39996
1.39997
1.39998
1.39998
1.39999
1.39999
1.39999
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.4
1.4
1.4
1.40001
1.40001
1.40002
1.40003
1.40004
1.40004
1.40005
1.40005
1.40006
1.40007
1.40008
1.40008
1.40009
1.40009
1.4001
1.4001
1.4001
1.4001
1.4001
1.40009
1.40008
1.40008
1.40007
1.40005
1.40004
1.40003
1.40002
1.40001
1.39999
1.39998
1.39997
1.39996
1.39996
1.39995
1.39995
1.39995
1.39995
1.39995
1.39995
1.39996
1.39996
1.39997
1.39997
1.39998
1.39998
1.39998
1.39999
1.39999
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.40001
1.40001
1.4
1.4
1.4
1.4
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40002
1.40002
1.40003
1.40003
1.40004
1.40004
1.40005
1.40006
1.40006
1.40006
1.40007
1.40007
1.40007
1.40007
1.40008
1.40007
1.40007
1.40007
1.40006
1.40005
1.40005
1.40004
1.40003
1.40001
1.4
1.4
1.39999
1.39998
1.39997
1.39997
1.39996
1.39996
1.39996
1.39996
1.39996
1.39996
1.39996
1.39996
1.39997
1.39997
1.39998
1.39998
1.39999
1.39999
1.39999
1.39999
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.40001
1.40001
1.40001
1.40001
1.4
1.4
1.4
1.4
1.4
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40002
1.40002
1.40002
1.40003
1.40003
1.40004
1.40004
1.40004
1.40005
1.40005
1.40005
1.40006
1.40006
1.40006
1.40006
1.40006
1.40005
1.40005
1.40004
1.40004
1.40003
1.40002
1.40002
1.40001
1.4
1.39999
1.39998
1.39998
1.39997
1.39997
1.39997
1.39996
1.39996
1.39996
1.39997
1.39997
1.39997
1.39997
1.39998
1.39998
1.39998
1.39999
1.39999
1.39999
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40002
1.40002
1.40002
1.40002
1.40003
1.40003
1.40003
1.40004
1.40004
1.40004
1.40004
1.40004
1.40004
1.40005
1.40005
1.40004
1.40004
1.40004
1.40003
1.40003
1.40002
1.40002
1.40001
1.4
1.4
1.39999
1.39999
1.39998
1.39998
1.39998
1.39997
1.39997
1.39997
1.39997
1.39997
1.39997
1.39998
1.39998
1.39998
1.39999
1.39999
1.39999
1.39999
1.39999
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40002
1.40002
1.40002
1.40002
1.40003
1.40003
1.40003
1.40003
1.40003
1.40004
1.40004
1.40003
1.40003
1.40003
1.40003
1.40003
1.40002
1.40002
1.40002
1.40001
1.40001
1.4
1.4
1.39999
1.39999
1.39999
1.39998
1.39998
1.39998
1.39998
1.39998
1.39998
1.39998
1.39998
1.39998
1.39999
1.39999
1.39999
1.39999
1.39999
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40002
1.40002
1.40002
1.40002
1.40002
1.40002
1.40003
1.40003
1.40003
1.40003
1.40003
1.40003
1.40003
1.40002
1.40002
1.40002
1.40002
1.40001
1.40001
1.40001
1.4
1.4
1.4
1.39999
1.39999
1.39999
1.39999
1.39998
1.39998
1.39998
1.39998
1.39999
1.39999
1.39999
1.39999
1.39999
1.39999
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.40001
1.4
1.4
1.4
1.4
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40002
1.40002
1.40002
1.40002
1.40002
1.40002
1.40002
1.40002
1.40002
1.40002
1.40002
1.40002
1.40002
1.40001
1.40001
1.40001
1.4
1.4
1.4
1.4
1.39999
1.39999
1.39999
1.39999
1.39999
1.39999
1.39999
1.39999
1.39999
1.39999
1.39999
1.39999
1.39999
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.40001
1.40001
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40002
1.40002
1.40002
1.40002
1.40002
1.40002
1.40002
1.40002
1.40002
1.40001
1.40001
1.40001
1.40001
1.40001
1.4
1.4
1.4
1.4
1.4
1.4
1.39999
1.39999
1.39999
1.39999
1.39999
1.39999
1.39999
1.39999
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.40001
1.4
1.4
1.4
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.40001
1.40001
1.4
1.4
1.4
1.4
1.4
1.4
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.40001
1.40001
1.40001
1.40001
1.4
1.4
1.40001
1.40001
1.40001
1.40001
1.4
1.4
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.40001
1.40001
1.4
1.4
1.4
1.4
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.4
1.4
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.40001
1.40001
1.4
1.4
1.4
1.4
1.40001
1.40001
1.40001
1.40001
1.4
1.4
1.4
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.4
1.4
1.4
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.4
1.4
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.4
1.4
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.40001
1.40001
1.40001
1.40001
1.4
1.4
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.4
1.4
1.4
1.4
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.4
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.4
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.4
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.4
1.4
1.4
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.4
1.40001
1.40001
1.40001
1.40001
1.40001
1.4
1.4
1.4
1.40001
1.40001
1.4
1.4
1.40001
1.40001
1.40001
1.4
1.4
1.40001
1.40001
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.40001
1.40001
1.40001
1.40001
1.4
1.4
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.4
1.4
1.4
1.4
1.4
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.4
1.40001
1.40001
1.4
1.40001
1.4
1.4
1.4
1.40001
1.40001
1.4
1.40001
1.40001
1.40001
1.40001
1.4
1.40001
1.40001
1.40001
1.40001
1.4
1.4
1.4
1.40001
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.40001
1.40001
1.40001
1.40001
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.40001
1.40001
1.40001
1.40001
1.4
1.4
1.4
1.4
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.4
1.4
1.40001
1.40001
1.40001
1.40001
1.40001
1.4
1.4
1.4
1.40001
1.40001
1.40001
1.4
1.4
1.4
1.40001
1.4
1.4
1.4
1.40001
1.40001
1.4
1.4
1.4
1.4
1.40001
1.40001
1.4
1.4
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.4
1.4
1.4
1.40001
1.40001
1.4
1.40001
1.40001
1.40001
1.40001
1.40001
1.4
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.4
1.4
1.4
1.4
1.4
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.4
1.4
1.4
1.4
1.40001
1.4
1.40001
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.4
1.4
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.4
1.4
1.4
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.4
1.4
1.4
1.40001
1.40001
1.40001
1.40001
1.40001
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.40001
1.40001
1.40001
1.40001
1.4
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.4
1.4
1.4
1.4
1.4
1.40001
1.40001
1.4
1.4
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.4
1.4
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.4
1.4
1.4
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.4
1.4
1.4
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.4
1.4
1.4
1.4
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.4
1.4
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.4
1.4
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.4
1.4
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.39999
1.39999
1.39999
1.39999
1.39999
1.39999
1.4
1.4
1.4
1.4
1.4
1.4
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40002
1.40002
1.40002
1.40002
1.40002
1.40002
1.40002
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.4
1.4
1.4
1.4
1.4
1.4
1.39999
1.39999
1.39999
1.39999
1.39999
1.39999
1.39999
1.39999
1.39999
1.39999
1.39999
1.4
1.4
1.4
1.4
1.40001
1.40001
1.40001
1.40001
1.40002
1.40002
1.40002
1.40002
1.40002
1.40002
1.40002
1.40002
1.40002
1.40002
1.40002
1.40002
1.40002
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.4
1.4
1.4
1.4
1.39999
1.39999
1.39999
1.39999
1.39999
1.39999
1.39999
1.39999
1.39999
1.39999
1.39999
1.39999
1.39999
1.39999
1.4
1.4
1.4
1.40001
1.40001
1.40001
1.40002
1.40002
1.40002
1.40002
1.40002
1.40003
1.40003
1.40003
1.40003
1.40002
1.40002
1.40002
1.40002
1.40002
1.40002
1.40002
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.4
1.4
1.4
1.39999
1.39999
1.39999
1.39999
1.39999
1.39998
1.39998
1.39998
1.39998
1.39998
1.39998
1.39998
1.39999
1.39999
1.39999
1.4
1.4
1.4
1.40001
1.40001
1.40002
1.40002
1.40002
1.40003
1.40003
1.40003
1.40003
1.40003
1.40003
1.40003
1.40003
1.40003
1.40003
1.40003
1.40002
1.40002
1.40002
1.40002
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.4
1.39999
1.39999
1.39999
1.39999
1.39998
1.39998
1.39998
1.39998
1.39998
1.39998
1.39998
1.39998
1.39998
1.39998
1.39998
1.39999
1.39999
1.4
1.4
1.40001
1.40001
1.40002
1.40002
1.40003
1.40003
1.40004
1.40004
1.40004
1.40004
1.40004
1.40004
1.40004
1.40004
1.40004
1.40003
1.40003
1.40003
1.40003
1.40002
1.40002
1.40002
1.40002
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
)
;
boundaryField
{
emptyPatches_empt
{
type empty;
}
top_cyc
{
type cyclic;
}
bottom_cyc
{
type cyclic;
}
inlet_cyc
{
type cyclic;
}
outlet_cyc
{
type cyclic;
}
procBoundary1to0
{
type processor;
value nonuniform List<scalar>
75
(
1.45574
1.45746
1.4587
1.45935
1.45932
1.4585
1.45684
1.45433
1.451
1.44694
1.44231
1.43732
1.43223
1.42729
1.42268
1.41854
1.41492
1.41184
1.40927
1.40717
1.40547
1.40414
1.40308
1.40229
1.40168
1.40122
1.40089
1.40065
1.40047
1.40035
1.40026
1.4002
1.40015
1.40012
1.4001
1.40008
1.40006
1.40005
1.40005
1.40003
1.40004
1.40002
1.40002
1.40002
1.40002
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.4
1.40001
1.40001
1.4
1.40001
1.40001
1.40001
1.4
1.40001
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
1.4
)
;
}
procBoundary1to0throughoutlet_cyc
{
type processorCyclic;
value nonuniform List<scalar>
75
(
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.4
1.40001
1.4
1.40001
1.4
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
)
;
}
procBoundary1to3
{
type processor;
value nonuniform List<scalar>
75
(
1.4458
1.43557
1.4238
1.41128
1.39868
1.38646
1.3749
1.36405
1.35377
1.34384
1.33404
1.32402
1.31335
1.3016
1.28868
1.27503
1.26116
1.2474
1.23446
1.22361
1.21567
1.21089
1.20968
1.21274
1.2201
1.2307
1.24316
1.25661
1.27061
1.28457
1.2978
1.30995
1.32117
1.3318
1.34207
1.35212
1.36227
1.37307
1.38505
1.3984
1.41267
1.42684
1.43947
1.44913
1.45483
1.45626
1.45384
1.44856
1.4416
1.43408
1.42685
1.42046
1.41515
1.41094
1.40774
1.40538
1.40369
1.40251
1.4017
1.40115
1.40078
1.40054
1.40037
1.40026
1.40018
1.40013
1.40009
1.40007
1.40005
1.40004
1.40003
1.40002
1.40002
1.40001
1.40001
)
;
}
procBoundary1to3throughbottom_cyc
{
type processorCyclic;
value nonuniform List<scalar>
75
(
1.39999
1.39999
1.39999
1.39999
1.39998
1.39998
1.39998
1.39997
1.39997
1.39997
1.39997
1.39997
1.39997
1.39997
1.39998
1.39998
1.39999
1.39999
1.4
1.4
1.40001
1.40002
1.40003
1.40003
1.40004
1.40004
1.40005
1.40005
1.40005
1.40005
1.40005
1.40005
1.40005
1.40005
1.40005
1.40004
1.40004
1.40004
1.40003
1.40003
1.40003
1.40002
1.40002
1.40002
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
1.40001
)
;
}
}
// ************************************************************************* //
| [
"tdg@debian"
] | tdg@debian | |
8391764250bb746a115c29f2751e4c8424986290 | 6aeccfb60568a360d2d143e0271f0def40747d73 | /sandbox/libs/outfmt/example/format-options.cpp | 5d5c60a35e91a955fab8f6978259f022132fcee3 | [] | no_license | ttyang/sandbox | 1066b324a13813cb1113beca75cdaf518e952276 | e1d6fde18ced644bb63e231829b2fe0664e51fac | refs/heads/trunk | 2021-01-19T17:17:47.452557 | 2013-06-07T14:19:55 | 2013-06-07T14:19:55 | 13,488,698 | 1 | 3 | null | 2023-03-20T11:52:19 | 2013-10-11T03:08:51 | C++ | UTF-8 | C++ | false | false | 4,290 | cpp | // (C) Copyright 2003-2004: Reece H. Dunn
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <iostream> // std::cout
#include <string> // std::string
#include <algorithm> // std::generate
#include <stdlib.h> // rand
#include <string.h> // strlen
#include <boost/outfmt/formatob.hpp>
#include <boost/outfmt/stl/vector.hpp>
#include <boost/outfmt/stl/list.hpp>
int main()
{
// std::vector
std::vector< int > v( 10 );
std::generate( v.begin(), v.end(), ::rand );
// std::list
std::list< char > l;
l.push_back( 'A' );
l.push_back( 'B' );
l.push_back( 'C' );
// std::string and arrays
const char * str = "Jeanette Biedermann";
std::string s = "Warum bist du nicht da?";
int i[ 4 ] = { 3, 6, 9, 12 };
// examples
std::cout << "vector< int > = "
<< boost::io::formatob( v ).format( "( ", " )" )
<< '\n';
// [results]: vector< int > = ( 41, 18467, 6334, 26500, 19169, 15724, 11478, 29358, 26962, 24464 )
std::cout << "vector< int > = "
<< boost::io::formatob( v ).format( " | " )
<< '\n';
// [results]: vector< int > = [ 41 | 18467 | 6334 | 26500 | 19169 | 15724 | 11478 | 29358 | 26962 | 24464 ]
std::cout << "int[ 4 ] = "
<< boost::io::formatob
(
boost::io::range( i, i + 4 ),
boost::io::rangefmt().format( " ; " )
)
<< '\n';
// [results]: int[ 4 ] = [ 3 ; 6 ; 9 ; 12 ]
std::cout << "int[ 4 ] = "
<< boost::io::formatob
(
boost::io::range( i, i + 4 ),
boost::io::rangefmt()
).format( " ; " )
<< '\n';
// [results]: int[ 4 ] = [ 3 ; 6 ; 9 ; 12 ]
std::cout << "int[ 4 ] = "
<< boost::io::formatob( boost::io::range( i, i + 4 )).format( " ; " )
<< '\n';
// [results]: int[ 4 ] = [ 3 ; 6 ; 9 ; 12 ]
std::cout << "char * = "
<< boost::io::formatob( boost::io::range( str, str + ::strlen( str )))
.format( "[", "]", "; " )
<< '\n';
// [results]: char * = [J; e; a; n; e; t; t; e; ; B; i; e; d; e; r; m; a; n; n]
std::cout << "std::string = "
<< boost::io::formatob( s, boost::io::containerfmt()).format( "", "", "|" )
<< '\n';
// [results]: std::string = W|a|r|u|m| |b|i|s|t| |d|u| |n|i|c|h|t| |d|a|?
std::cout << '\n' << "sub-list:" << '\n' << '\n';
std::cout << "std::string = "
<< boost::io::formatobex< char >
(
boost::io::range( s.begin() + 6, s.end())
)
.format( '"', '"', '-' )
<< '\n';
// [results]: std::string = "b-i-s-t- -d-u- -n-i-c-h-t- -d-a-?"
std::cout << '\n' << "advanced formatting:" << '\n' << '\n';
std::cout << "std::string = "
<< boost::io::formatob( s, boost::io::containerfmt()).format( "<: ", " :>", " " )
<< '\n';
// [results]: std::string = <: W a r u m b i s t d u n i c h t d a ? :>
std::cout << "std::string = "
<< boost::io::formatob
(
s,
boost::io::containerfmt
(
boost::io::wrappedfmt().format( "'", "'" ) // :-)
)
).format( "{ ", " }" )
<< '\n';
// [results]: std::string = { 'W', 'a', 'r', 'u', 'm', ' ', 'b', 'i', 's', 't', ' ', 'd', 'u', ' ', 'n', 'i', 'c', 'h', 't', ' ', 'd', 'a', '?' }
std::cout << "int[ 4 ] = "
<< boost::io::formatob( boost::io::range( i, i + 4 )).format( " -:- " )
<< '\n';
// [results]: int[ 4 ] = [ 3 -:- 6 -:- 9 -:- 12 ]
std::cout << "int[ 4 ] = "
<< boost::io::formatob( boost::io::range( i, i + 4 ))
.format( " -\n- " ).format( "\n- ", " -" )
<< '\n';
/* [results]:
int[ 4 ] =
- 3 -
- 6 -
- 9 -
- 12 -
*/
return( 0 );
}
| [
"msclrhd@hotmail.com"
] | msclrhd@hotmail.com |
84d23b81924611d7b12b4d7ccab5173f6b7a00b1 | ae9822bc1d6c4861cf7b137ff7122c6108fe01ea | /src/examples/matio_matrix_example.cpp | 6c367acecca7ccee614687c17ba5aeb75c000224 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | Nicogene/yarp-telemetry | dea07c0a16c26fc728bb189af858849c199cf80e | c6b9222e9733d549b251f50d0b317b4fdc3729e0 | refs/heads/master | 2023-02-27T23:10:24.270559 | 2021-02-09T11:30:30 | 2021-02-09T11:30:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,353 | cpp | #include <vector>
#include <matioCpp/matioCpp.h>
using namespace std;
int main(int argc, char *argv[])
{
matioCpp::File file = matioCpp::File::Create("test_int.mat");
matioCpp::File file_double = matioCpp::File::Create("test_double.mat");
matioCpp::File file_3d = matioCpp::File::Create("test_3d.mat");
// Create a matio matrix of ints 2x2 (from vector)
vector<int> in = {2, 4, 7, 10};
matioCpp::MultiDimensionalArray<int> out("test", {2,2}, in.data());
// Create a matio matrix of ints 2x2x2 (from vector)
vector<int> in_3d = {2, 4, 7, 9, 10, 13, 21, 24};
matioCpp::MultiDimensionalArray<int> out_3d("test", {2,2,2}, in_3d.data());
// create a matio matrix of doubles
vector<double> in_double = {2.0, 4.0, 6.0, 8.0};
matioCpp::MultiDimensionalArray<double> out_double("test", {2,2}, in_double.data());
// adding another 2x2 matrix to an existing matrix
out_double.resize({2, 2, 2}); // clears previous data
out_double({0,0,0}) = in_double[0];
out_double({0,1,0}) = in_double[1];
out_double({0,0,1}) = in_double[2];
out_double({0,1,1}) = in_double[3];
out_double({1,0,0}) = 40.0;
out_double({1,1,0}) = 50.0;
out_double({1,0,1}) = 60.0;
out_double({1,1,1}) = 70.0;
// {#vectors_vectors, #vectors, #element}
file.write(out);
file_double.write(out_double);
file_3d.write(out_3d);
return 0;
}
| [
"alexandre.antunes@plymouth.ac.uk"
] | alexandre.antunes@plymouth.ac.uk |
82c583cedb37927282bced9110c367c355c04a69 | a69e96cabcd4ade5c4bb6f18f13b7b518d91915c | /test/unit_test.cc | 30a98cf465cfcafdc2b6de67ca50fdaf5a8c1708 | [] | no_license | hangyu0100/pplp | d71dd6be606e51990868bd9467da8b43c5d2180e | ef22f75db15709f7db4f684269f662e5a77d4587 | refs/heads/master | 2023-02-17T09:32:05.962507 | 2021-01-13T11:48:50 | 2021-01-13T11:48:50 | 259,145,304 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,764 | cc | #include <iostream>
#include <random>
#include "pplp_polyhedron.h"
#include "pplp_ioInterface.h"
#include "pplp_tbbParallel.h"
using namespace PPLP ;
bool TestConstructor() {
int consNum = 3 ;
int variNum = 3 ;
int eqConsNum = 1 ;
Matrix ineqCoeff(consNum, variNum+1) ;
ineqCoeff << 3, 0, -1, 12,
-1, 0, -3, 7,
-1, 0, 2, -4 ;
Matrix eqCoeff(eqConsNum, variNum+1) ;
eqCoeff << 0, 1, 0, 2 ;
RMatrix ineqCoeffR(consNum, variNum+1) ;
RMatrix eqCoeffR(eqConsNum, variNum+1) ;
for (int i = 0; i < consNum; ++ i) {
for (int j = 0; j < variNum+1; ++ j) {
ineqCoeffR.at(i,j) = (int)round(ineqCoeff(i,j)) ;
}
}
for (int i = 0; i < eqConsNum; ++ i) {
for (int j = 0; j < variNum+1; ++ j) {
eqCoeffR.at(i,j) = (int)eqCoeff(i,j) ;
}
}
Polyhedron poly1 ;
assert(poly1.get_constraint_num() == 0) ;
assert(poly1.get_eq_constraint_num() == 0) ;
assert(poly1.get_variable_num() == 0) ;
assert( poly1.IsTop() ) ;
poly1.SetSize(consNum, variNum, eqConsNum) ;
assert(poly1.get_constraint_num() == 3) ;
assert(poly1.get_eq_constraint_num() == 1) ;
assert(poly1.get_variable_num() == 3) ;
for (int i = 0; i < consNum; ++ i) {
for (int j = 0; j < variNum; ++ j) {
poly1.SetCoef( i, j, ineqCoeff(i,j) ) ;
}
poly1.SetConstant( i, ineqCoeff(i,variNum) ) ;
}
for (int i = 0; i < eqConsNum; ++ i) {
for (int j = 0; j < variNum; ++ j) {
poly1.SetEqCoef( i, j, eqCoeff(i,j) ) ;
}
poly1.SetEqConstant( i, eqCoeff(i,variNum) ) ;
}
Polyhedron poly4(consNum, variNum, eqConsNum) ;
for (int i = 0; i < consNum; ++ i) {
for (int j = 0; j < variNum; ++ j) {
poly4.SetCoef( i, j, ineqCoeff(i,j) ) ;
}
poly4.SetConstant( i, ineqCoeff(i,variNum) ) ;
}
for (int i = 0; i < eqConsNum; ++ i) {
for (int j = 0; j < variNum; ++ j) {
poly4.SetEqCoef( i, j, eqCoeff(i,j) ) ;
}
poly4.SetEqConstant( i, eqCoeff(i,variNum) ) ;
}
assert( poly1.get_coefficients() == poly4.get_coefficients() && poly1.get_constants() == poly4.get_constants() ) ;
assert( poly1.get_eq_coefficients() == poly4.get_eq_coefficients() && poly1.get_eq_constants() == poly4.get_eq_constants() ) ;
assert( poly1.get_coefficients() == poly4.get_coefficients() && poly1.get_constants() == poly4.get_constants() ) ;
assert( poly1.get_eq_coefficients() == poly4.get_eq_coefficients() && poly1.get_eq_constants() == poly4.get_eq_constants() ) ;
Polyhedron poly2(3, 3, 1) ;
assert(poly2.get_constraint_num() == 3) ;
assert(poly2.get_eq_constraint_num() == 1) ;
assert(poly2.get_variable_num() == 3) ;
poly2.set_coefficients( ineqCoeff.block(0, 0, consNum, variNum) ) ;
poly2.set_constants( ineqCoeff.col(variNum).transpose() ) ;
poly2.set_eq_coefficients( eqCoeff.block(0, 0, eqConsNum, variNum) ) ;
poly2.set_eq_constants( eqCoeff.col(variNum).transpose() ) ;
Polyhedron poly3( ineqCoeffR, std::vector<int>(), eqCoeffR, std::vector<int>() ) ;
assert( poly1.get_coefficients() == poly2.get_coefficients() && poly1.get_constants() == poly2.get_constants() ) ;
assert( poly1.get_eq_coefficients() == poly2.get_eq_coefficients() && poly1.get_eq_constants() == poly2.get_eq_constants() ) ;
assert( poly1.get_coefficients() == poly3.get_coefficients() && poly1.get_constants() == poly3.get_constants() ) ;
assert( poly1.get_eq_coefficients() == poly3.get_eq_coefficients() && poly1.get_eq_constants() == poly3.get_eq_constants() ) ;
poly2.Init() ;
poly2.set_coefficients( ineqCoeff.block(0, 0, consNum, variNum) ) ;
poly2.set_constants( ineqCoeff.col(variNum).transpose() ) ;
poly2.set_eq_coefficients( eqCoeff.block(0, 0, eqConsNum, variNum) ) ;
poly2.set_eq_constants( eqCoeff.col(variNum).transpose() ) ;
assert( poly1.get_coefficients() == poly2.get_coefficients() && poly1.get_constants() == poly2.get_constants() ) ;
assert( poly1.get_eq_coefficients() == poly2.get_eq_coefficients() && poly1.get_eq_constants() == poly2.get_eq_constants() ) ;
return true ;
}
bool TestEquality() {
Polyhedron poly1(2, 3, 1) ;
Polyhedron poly2(2, 3, 1) ;
poly1.SetCoef(0, 1, 2) ;
poly1.SetCoef(0, 2, 1) ;
poly1.SetConstant(0, -1) ;
poly2.SetCoef(1, 1, 2) ;
poly2.SetCoef(1, 2, 1) ;
poly2.SetConstant(1, -1) ;
poly1.SetCoef(1, 0, -1) ;
poly1.SetCoef(1, 2, 3) ;
poly1.SetConstant(1, 2) ;
poly2.SetCoef(0, 0, -1) ;
poly2.SetCoef(0, 2, 3) ;
poly2.SetConstant(0, 2) ;
poly1.SetEqCoef(0, 0, 1) ;
poly1.SetEqCoef(0, 1, 2) ;
poly1.SetEqCoef(0, 2, -2) ;
poly1.SetEqConstant(0, -1) ;
poly2.SetEqCoef(0, 0, 1) ;
poly2.SetEqCoef(0, 1, 2) ;
poly2.SetEqCoef(0, 2, -2) ;
poly2.SetEqConstant(0, -1) ;
return poly1.IsEqualTo(poly2) ;
}
bool TestSubPoly() {
int consNum = 4 ;
int variNum = 3 ;
int eqConsNum = 4 ;
Polyhedron poly(consNum, variNum, eqConsNum) ;
srand( time(NULL) ) ;
std::random_device rd ;
std::mt19937 gen(rd()) ;
std::uniform_int_distribution<> dis(-10, 10) ;
int coeff ;
for (int i = 0; i < consNum; ++ i) {
for (int j = 0; j < variNum; ++ j) {
coeff = dis(gen) ;
poly.SetCoef(i, j, coeff) ;
}
coeff = dis(gen) ;
poly.SetConstant(i, coeff) ;
}
for (int i = 0; i < eqConsNum; ++ i) {
for (int j = 0; j < variNum; ++ j) {
coeff = dis(gen) ;
poly.SetEqCoef(i, j, coeff) ;
}
coeff = dis(gen) ;
poly.SetEqConstant(i, coeff) ;
}
std::vector<int> idx1 ;
idx1.push_back(1) ;
idx1.push_back(2) ;
Polyhedron sub1 = poly.GetSubPoly(idx1) ;
assert( sub1.get_constraint_num() == (int)idx1.size() ) ;
for (unsigned i = 0; i < idx1.size(); ++ i) {
for (int j = 0; j < variNum; ++ j) {
assert( sub1.GetCoef(i, j) == poly.GetCoef(idx1[i], j) ) ;
}
assert( sub1.GetConstant(i) == poly.GetConstant( idx1[i] ) ) ;
}
for (int i = 0; i < eqConsNum; ++ i) {
for (int j = 0; j < variNum; ++ j) {
assert( sub1.GetEqCoef(i, j) == poly.GetEqCoef(i, j) ) ;
}
assert( sub1.GetEqConstant(i) == poly.GetEqConstant(i) ) ;
}
std::vector<int> idx2 ;
idx2.push_back(0) ;
idx2.push_back(3) ;
Polyhedron sub2 = poly.GetSubPoly(std::vector<int>(), idx2) ;
assert( sub2.get_eq_constraint_num() == (int)idx2.size() ) ;
for (int i = 0; i < consNum; ++ i) {
for (int j = 0; j < variNum; ++ j) {
assert( sub2.GetCoef(i, j) == poly.GetCoef(i, j) ) ;
}
assert( sub2.GetConstant(i) == poly.GetConstant(i) ) ;
}
for (unsigned i = 0; i < idx2.size(); ++ i) {
for (int j = 0; j < variNum; ++ j) {
assert( sub2.GetEqCoef(i, j) == poly.GetEqCoef(idx2[i], j) ) ;
}
assert( sub2.GetEqConstant(i) == poly.GetEqConstant( idx2[i] ) ) ;
}
Polyhedron sub3 = poly.GetSubPoly(idx1, idx2) ;
assert( sub3.get_constraint_num() == (int)idx1.size() ) ;
assert( sub3.get_eq_constraint_num() == (int)idx2.size() ) ;
for (unsigned i = 0; i < idx1.size(); ++ i) {
for (int j = 0; j < variNum; ++ j) {
assert( sub3.GetCoef(i, j) == poly.GetCoef(idx1[i], j) ) ;
}
assert( sub3.GetConstant(i) == poly.GetConstant( idx1[i] ) ) ;
}
for (unsigned i = 0; i < idx2.size(); ++ i) {
for (int j = 0; j < variNum; ++ j) {
assert( sub3.GetEqCoef(i, j) == poly.GetEqCoef(idx2[i], j) ) ;
}
assert( sub3.GetEqConstant(i) == poly.GetEqConstant( idx2[i] ) ) ;
}
return true ;
}
bool TestIo() {
int consNum = 3 ;
int variNum = 3 ;
int eqConsNum = 1 ;
IoInterface ioInter ;
std::vector<Polyhedron> polyVec = ioInter.LoadPolyhedra("./testfiles/test.poly") ;
assert( ioInter.get_cons_num() == consNum+eqConsNum) ;
assert( ioInter.get_vari_num() == variNum) ;
Polyhedron poly = polyVec[0] ;
Matrix ineqCoeff(consNum, variNum+1) ;
ineqCoeff << 3, 0, -1, 12,
-1, 0, -3, 7,
-1, 0, 2, -4 ;
Matrix eqCoeff(eqConsNum, variNum+1) ;
eqCoeff << 0, 1, 0, 2 ;
assert( poly.get_coefficients() == ineqCoeff.block(0, 0, consNum, variNum) ) ;
assert( poly.get_constants() == ineqCoeff.col(variNum).transpose() ) ;
assert( poly.get_eq_coefficients() == eqCoeff.block(0, 0, eqConsNum, variNum) ) ;
assert( poly.get_eq_constants() == eqCoeff.col(variNum).transpose() ) ;
return true ;
}
bool TestGaussian() {
RMatrix matrix(4, 5) ;
matrix.at(0,0) = 2 ;
matrix.at(0,1) = 3 ;
matrix.at(0,2) = -2 ;
matrix.at(0,3) = 1 ;
matrix.at(0,4) = 2 ;
matrix.at(1,0) = 3 ;
matrix.at(1,1) = -2 ;
matrix.at(1,2) = 4 ;
matrix.at(1,3) = -1 ;
matrix.at(1,4) = 3 ;
matrix.at(2,0) = 10 ;
matrix.at(2,1) = 15 ;
matrix.at(2,2) = -10 ;
matrix.at(2,3) = 5 ;
matrix.at(2,4) = 10 ;
matrix.at(3,0) = -1 ;
matrix.at(3,1) = -4 ;
matrix.at(3,2) = 2 ;
matrix.at(3,3) = 3 ;
matrix.at(3,4) = 1 ;
ReducedMatrix reduced = Tool::GaussianElimination(matrix) ;
assert(reduced.succeed) ;
int consNum = reduced.rowIdx.size() ;
int variNum = reduced.colIdx.size() ;
for (int j = 0; j < variNum+1; ++ j) {
assert( reduced.matrix.at(2,j).is_zero() ) ;
}
int rowIdx ;
RMatrix rm(consNum, variNum+1) ;
for (int i = 0; i < consNum; ++ i) {
for (int j = 0; j < variNum+1; ++ j) {
rowIdx = reduced.rowIdx[i] ;
rm.at(i,j) = reduced.matrix.at(rowIdx, j) ;
}
}
for (int i = 0; i < consNum; ++ i) {
assert( rm.at(i,i).is_one() ) ;
}
matrix.at(2,4) = 9 ;
ReducedMatrix reduced2 = Tool::GaussianElimination(matrix) ;
assert( ! reduced2.succeed) ;
return true ;
}
bool TestGaussianFloat() {
Matrix matrix(4, 5) ;
matrix << 2, 3, -2, 1, 2,
3, -2, 4, -1, 3,
10, 15, -10, 5, 10,
-1, -4, 2, 3, 1 ;
ReducedMatrixFloat reduced = Tool::GaussianEliminationFloat(matrix) ;
assert(reduced.succeed) ;
int consNum = reduced.rowIdx.size() ;
int variNum = reduced.colIdx.size() ;
for (int j = 0; j < variNum+1; ++ j) {
assert(reduced.matrix(2,j) == 0) ;
}
int rowIdx ;
Matrix rm(consNum, variNum+1) ;
for (int i = 0; i < consNum; ++ i) {
for (int j = 0; j < variNum+1; ++ j) {
rowIdx = reduced.rowIdx[i] ;
rm(i,j) = reduced.matrix(rowIdx, j) ;
}
}
for (int i = 0; i < consNum; ++ i) {
assert(rm(i,i) == 1) ;
}
matrix(2,4) = 9 ;
ReducedMatrixFloat reduced2 = Tool::GaussianEliminationFloat(matrix) ;
assert( ! reduced2.succeed) ;
matrix(2,4) = 10 ;
matrix.row(2) = matrix.row(2) / 3 ;
ReducedMatrixFloat reduced3 = Tool::GaussianEliminationFloat(matrix) ;
assert(reduced3.succeed) ;
return true ;
}
bool TestSubsEq() {
int consNum = 3 ;
int variNum = 3 ;
int eqConsNum = 3 ;
Matrix ineqCoeff(consNum, variNum+1) ;
ineqCoeff << 3, 2, -1, 12,
-1, 1, -3, 7,
-3, -1, 1, -7 ;
Matrix eqCoeff(eqConsNum, variNum+1) ;
eqCoeff << 0, 1, 0, 2,
0, 2, 3, -2,
0, 6, 9, -6 ;
Polyhedron poly(consNum, variNum, eqConsNum) ;
poly.set_coefficients( ineqCoeff.block(0, 0, consNum, variNum) ) ;
poly.set_constants( ineqCoeff.col(variNum).transpose() ) ;
poly.set_eq_coefficients( eqCoeff.block(0, 0, eqConsNum, variNum) ) ;
poly.set_eq_constants( eqCoeff.col(variNum).transpose() ) ;
Polyhedron poly2 = poly ;
ReducedMatrix redMatrixR = poly.SubsEqConsR() ;
ReducedMatrixFloat redMatrixF = poly2.SubsEqConsF() ;
assert(poly.GetEqCoef(0,1) == 1) ;
assert(poly.GetEqCoef(1,2) == 1) ;
assert( poly.get_eq_coefficients() == poly2.get_eq_coefficients() ) ;
assert( poly.get_eq_constants() == poly2.get_eq_constants() ) ;
assert( poly.get_eq_constraint_num() == poly2.get_eq_constraint_num() ) ;
poly.SubsIneqConsR(redMatrixR) ;
poly2.SubsIneqConsF(redMatrixF) ;
assert( poly.get_eq_coefficients() == poly2.get_eq_coefficients() ) ;
assert( poly.get_eq_constants() == poly2.get_eq_constants() ) ;
assert( poly.get_coefficients() == poly2.get_coefficients() ) ;
assert( poly.get_constants() == poly2.get_constants() ) ;
return true ;
}
bool TestMiniIneqOnly() {
int consNum = 5 ;
int variNum = 3 ;
Matrix ineqCoeff(consNum, variNum+1) ;
ineqCoeff << -21, -33, -39, 30,
-168, -174, -67, 261,
-273, -357, -311, 429,
-21, -15, 10, 31,
-168, -156, -18, 289 ;
Polyhedron poly(consNum, variNum) ;
poly.set_coefficients( ineqCoeff.block(0, 0, consNum, variNum) ) ;
poly.set_constants( ineqCoeff.col(variNum).transpose() ) ;
poly.Minimize() ;
std::vector<int> activeIdx = poly.GetActiveIdx() ;
assert(activeIdx[0] == 0) ;
assert(activeIdx[1] == 3) ;
return true ;
}
bool TestMinimize() {
int consNum = 5 ;
int eqConsNum = 2 ;
int variNum = 5 ;
Matrix ineqCoeff(consNum, variNum+1) ;
ineqCoeff << 12, -11, -21, -33, -39, 30,
21, -3, -168, -174, -67, 261,
-5, 10, -273, -357, -311, 429,
-21, 10, -21, -15, 10, 31,
-3, 21, -168, -156, -18, 289 ;
Polyhedron poly(consNum, variNum, eqConsNum) ;
Matrix eqCoeff(eqConsNum, variNum+1) ;
eqCoeff << 1, 0, 0, 0, 0, 0,
0, 1, 0, 0, 0, 0 ;
poly.set_coefficients( ineqCoeff.block(0, 0, consNum, variNum) ) ;
poly.set_constants( ineqCoeff.col(variNum).transpose() ) ;
poly.set_eq_coefficients( eqCoeff.block(0, 0, eqConsNum, variNum) ) ;
poly.set_eq_constants( eqCoeff.col(variNum).transpose() ) ;
poly.Minimize() ;
std::vector<int> activeIdx = poly.GetActiveIdx() ;
assert(activeIdx[0] == 0) ;
assert(activeIdx[1] == 3) ;
return true ;
}
bool TestConstructorProj() {
int consNum = 3, variNum = 2 ;
Polyhedron poly(consNum, variNum) ;
Matrix coeff(consNum, variNum) ;
Vector constant(consNum) ;
coeff << -3, 1,
-1, -2,
4, 1 ;
constant << -1, -5, 13 ;
poly.set_coefficients( std::move(coeff) ) ;
poly.set_constants( std::move(constant) ) ;
TbbParallel tbb(poly) ;
// the second parameter 0 enforces the algo choose a start task point
// this is for test
tbb.PlpParallel(1, 0) ;
// the result should be x>=1, x<=5
RMatrix res( tbb.GetOptimalMatrix() ) ;
RNumber ratio1( -res.at(0,2) / res.at(0,1) ) ;
RNumber ratio2( -res.at(1,2) / res.at(1,1) ) ;
RNumber five, zero ;
five.set_integer(5) ;
zero.set_zero() ;
if ( ratio1.is_one() ) {
assert(ratio2 == five) ;
assert(res.at(0,1) > zero) ;
assert(res.at(0,2) < zero) ;
assert(res.at(1,1) < zero) ;
assert(res.at(1,2) > zero) ;
}
else if ( ratio2.is_one() ) {
assert(ratio1 == five) ;
assert(res.at(1,1) > zero) ;
assert(res.at(1,2) < zero) ;
assert(res.at(0,1) < zero) ;
assert(res.at(0,2) > zero) ;
}
else {
return false ;
}
return true ;
}
int main (int argc, char* argv[]) {
// constructor of polyhedron
assert( TestConstructor() ) ;
std::cout << "Test constructor: OK" << std::endl ;
// equality of polyhedra
assert( TestEquality() ) ;
std::cout << "Test polyhedra equality: OK" << std::endl ;
// subpoly
assert( TestSubPoly() ) ;
std::cout << "Test subpoly: OK" << std::endl ;
// io
//assert( TestIo() ) ;
//std::cout << "Test io: OK" << std::endl ;
// minimization
// Gaussian
assert( TestGaussian() ) ;
std::cout << "Test Gaussian: OK" << std::endl ;
// Gaussian float
assert( TestGaussianFloat() ) ;
std::cout << "Test GaussianFloat: OK" << std::endl ;
// Equalities
assert( TestSubsEq() ) ;
std::cout << "Test substitute equalities: OK" << std::endl ;
// raytracing
// TODO maybe refine this part
assert( TestMiniIneqOnly() ) ;
std::cout << "Test minimization with inequalities only: OK" << std::endl ;
assert( TestMinimize() ) ;
std::cout << "Test minimization with inequalities and equalities: OK" << std::endl ;
// projection inequalities
assert( TestConstructorProj() ) ;
std::cout << "Test constructor of projection: OK" << std::endl ;
return 0 ;
}
| [
"hang.yu0100@gmail.com"
] | hang.yu0100@gmail.com |
2beb11212818c15006d7026bff69551b1c71646f | be0282afa8dd436619c71d6118c9db455eaf1a29 | /Intermediate/Build/Win64/Design3D/Inc/ClothingSystemRuntimeInterface/ClothingSimulationInteractor.gen.cpp | 26fe5324e683d8c1c49760265531b59635b78811 | [] | no_license | Quant2017/Design3D | 0f915580b222af40ab911021cceef5c26375d7f9 | 94a22386be4aa37aa0f546354cc62958820a4bf6 | refs/heads/master | 2022-04-23T10:44:12.398772 | 2020-04-22T01:02:39 | 2020-04-22T01:02:39 | 262,966,755 | 1 | 0 | null | 2020-05-11T07:12:37 | 2020-05-11T07:12:36 | null | UTF-8 | C++ | false | false | 8,231 | cpp | // Copyright 1998-2019 Epic Games, Inc. All Rights Reserved.
/*===========================================================================
Generated code exported from UnrealHeaderTool.
DO NOT modify this manually! Edit the corresponding .h files instead!
===========================================================================*/
#include "UObject/GeneratedCppIncludes.h"
#include "ClothingSystemRuntimeInterface/Public/ClothingSimulationInteractor.h"
#ifdef _MSC_VER
#pragma warning (push)
#pragma warning (disable : 4883)
#endif
PRAGMA_DISABLE_DEPRECATION_WARNINGS
void EmptyLinkFunctionForGeneratedCodeClothingSimulationInteractor() {}
// Cross Module References
CLOTHINGSYSTEMRUNTIMEINTERFACE_API UClass* Z_Construct_UClass_UClothingSimulationInteractor_NoRegister();
CLOTHINGSYSTEMRUNTIMEINTERFACE_API UClass* Z_Construct_UClass_UClothingSimulationInteractor();
COREUOBJECT_API UClass* Z_Construct_UClass_UObject();
UPackage* Z_Construct_UPackage__Script_ClothingSystemRuntimeInterface();
CLOTHINGSYSTEMRUNTIMEINTERFACE_API UFunction* Z_Construct_UFunction_UClothingSimulationInteractor_ClothConfigUpdated();
CLOTHINGSYSTEMRUNTIMEINTERFACE_API UFunction* Z_Construct_UFunction_UClothingSimulationInteractor_PhysicsAssetUpdated();
// End Cross Module References
void UClothingSimulationInteractor::StaticRegisterNativesUClothingSimulationInteractor()
{
UClass* Class = UClothingSimulationInteractor::StaticClass();
static const FNameNativePtrPair Funcs[] = {
{ "ClothConfigUpdated", &UClothingSimulationInteractor::execClothConfigUpdated },
{ "PhysicsAssetUpdated", &UClothingSimulationInteractor::execPhysicsAssetUpdated },
};
FNativeFunctionRegistrar::RegisterFunctions(Class, Funcs, ARRAY_COUNT(Funcs));
}
struct Z_Construct_UFunction_UClothingSimulationInteractor_ClothConfigUpdated_Statics
{
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[];
#endif
static const UE4CodeGen_Private::FFunctionParams FuncParams;
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UClothingSimulationInteractor_ClothConfigUpdated_Statics::Function_MetaDataParams[] = {
{ "Category", "ClothingSimulation" },
{ "ModuleRelativePath", "Public/ClothingSimulationInteractor.h" },
{ "ToolTip", "Called to update the cloth config without restarting the simulation" },
};
#endif
const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_UClothingSimulationInteractor_ClothConfigUpdated_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UClothingSimulationInteractor, nullptr, "ClothConfigUpdated", 0, nullptr, 0, RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x04020400, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UClothingSimulationInteractor_ClothConfigUpdated_Statics::Function_MetaDataParams, ARRAY_COUNT(Z_Construct_UFunction_UClothingSimulationInteractor_ClothConfigUpdated_Statics::Function_MetaDataParams)) };
UFunction* Z_Construct_UFunction_UClothingSimulationInteractor_ClothConfigUpdated()
{
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UClothingSimulationInteractor_ClothConfigUpdated_Statics::FuncParams);
}
return ReturnFunction;
}
struct Z_Construct_UFunction_UClothingSimulationInteractor_PhysicsAssetUpdated_Statics
{
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[];
#endif
static const UE4CodeGen_Private::FFunctionParams FuncParams;
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UClothingSimulationInteractor_PhysicsAssetUpdated_Statics::Function_MetaDataParams[] = {
{ "Category", "ClothingSimulation" },
{ "ModuleRelativePath", "Public/ClothingSimulationInteractor.h" },
{ "ToolTip", "Called to update collision status without restarting the simulation" },
};
#endif
const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_UClothingSimulationInteractor_PhysicsAssetUpdated_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UClothingSimulationInteractor, nullptr, "PhysicsAssetUpdated", 0, nullptr, 0, RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x04020400, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UClothingSimulationInteractor_PhysicsAssetUpdated_Statics::Function_MetaDataParams, ARRAY_COUNT(Z_Construct_UFunction_UClothingSimulationInteractor_PhysicsAssetUpdated_Statics::Function_MetaDataParams)) };
UFunction* Z_Construct_UFunction_UClothingSimulationInteractor_PhysicsAssetUpdated()
{
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UClothingSimulationInteractor_PhysicsAssetUpdated_Statics::FuncParams);
}
return ReturnFunction;
}
UClass* Z_Construct_UClass_UClothingSimulationInteractor_NoRegister()
{
return UClothingSimulationInteractor::StaticClass();
}
struct Z_Construct_UClass_UClothingSimulationInteractor_Statics
{
static UObject* (*const DependentSingletons[])();
static const FClassFunctionLinkInfo FuncInfo[];
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Class_MetaDataParams[];
#endif
static const FCppClassTypeInfoStatic StaticCppClassTypeInfo;
static const UE4CodeGen_Private::FClassParams ClassParams;
};
UObject* (*const Z_Construct_UClass_UClothingSimulationInteractor_Statics::DependentSingletons[])() = {
(UObject* (*)())Z_Construct_UClass_UObject,
(UObject* (*)())Z_Construct_UPackage__Script_ClothingSystemRuntimeInterface,
};
const FClassFunctionLinkInfo Z_Construct_UClass_UClothingSimulationInteractor_Statics::FuncInfo[] = {
{ &Z_Construct_UFunction_UClothingSimulationInteractor_ClothConfigUpdated, "ClothConfigUpdated" }, // 3308417843
{ &Z_Construct_UFunction_UClothingSimulationInteractor_PhysicsAssetUpdated, "PhysicsAssetUpdated" }, // 400585641
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UClothingSimulationInteractor_Statics::Class_MetaDataParams[] = {
{ "IncludePath", "ClothingSimulationInteractor.h" },
{ "ModuleRelativePath", "Public/ClothingSimulationInteractor.h" },
{ "ToolTip", "If a clothing simulation is able to be interacted with at runtime then a derived\ninteractor should be created, and at least the basic API implemented for that\nsimulation.\nOnly write to the simulation and context during the call to Sync, as that is\nguaranteed to be a safe place to access this data." },
};
#endif
const FCppClassTypeInfoStatic Z_Construct_UClass_UClothingSimulationInteractor_Statics::StaticCppClassTypeInfo = {
TCppClassTypeTraits<UClothingSimulationInteractor>::IsAbstract,
};
const UE4CodeGen_Private::FClassParams Z_Construct_UClass_UClothingSimulationInteractor_Statics::ClassParams = {
&UClothingSimulationInteractor::StaticClass,
nullptr,
&StaticCppClassTypeInfo,
DependentSingletons,
FuncInfo,
nullptr,
nullptr,
ARRAY_COUNT(DependentSingletons),
ARRAY_COUNT(FuncInfo),
0,
0,
0x001000A1u,
METADATA_PARAMS(Z_Construct_UClass_UClothingSimulationInteractor_Statics::Class_MetaDataParams, ARRAY_COUNT(Z_Construct_UClass_UClothingSimulationInteractor_Statics::Class_MetaDataParams))
};
UClass* Z_Construct_UClass_UClothingSimulationInteractor()
{
static UClass* OuterClass = nullptr;
if (!OuterClass)
{
UE4CodeGen_Private::ConstructUClass(OuterClass, Z_Construct_UClass_UClothingSimulationInteractor_Statics::ClassParams);
}
return OuterClass;
}
IMPLEMENT_CLASS(UClothingSimulationInteractor, 701231955);
template<> CLOTHINGSYSTEMRUNTIMEINTERFACE_API UClass* StaticClass<UClothingSimulationInteractor>()
{
return UClothingSimulationInteractor::StaticClass();
}
static FCompiledInDefer Z_CompiledInDefer_UClass_UClothingSimulationInteractor(Z_Construct_UClass_UClothingSimulationInteractor, &UClothingSimulationInteractor::StaticClass, TEXT("/Script/ClothingSystemRuntimeInterface"), TEXT("UClothingSimulationInteractor"), false, nullptr, nullptr, nullptr);
DEFINE_VTABLE_PTR_HELPER_CTOR(UClothingSimulationInteractor);
PRAGMA_ENABLE_DEPRECATION_WARNINGS
#ifdef _MSC_VER
#pragma warning (pop)
#endif
| [
"Snake_Jenny@126.com"
] | Snake_Jenny@126.com |
320d773deca72cf6db768b6d678bf2a54a86aa40 | ce262ae496ab3eeebfcbb337da86d34eb689c07b | /SETools/SEManagedFramework/AssemblyInfo.cpp | e2875a11791810b0026b9db2311fe75a0a26e879 | [] | no_license | pizibing/swingengine | d8d9208c00ec2944817e1aab51287a3c38103bea | e7109d7b3e28c4421c173712eaf872771550669e | refs/heads/master | 2021-01-16T18:29:10.689858 | 2011-06-23T04:27:46 | 2011-06-23T04:27:46 | 33,969,301 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,412 | cpp | // Swing Engine Version 1 Source Code
// Most of techniques in the engine are mainly based on David Eberly's
// Wild Magic 4 open-source code.The author of Swing Engine learned a lot
// from Eberly's experience of architecture and algorithm.
// Several sub-systems are totally new,and others are re-implimented or
// re-organized based on Wild Magic 4's sub-systems.
// Copyright (c) 2007-2010. All Rights Reserved
//
// Eberly's permission:
// Geometric Tools, Inc.
// http://www.geometrictools.com
// Copyright (c) 1998-2006. All Rights Reserved
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation; either version 2.1 of the License, or (at
// your option) any later version. The license is available for reading at
// the location:
// http://www.gnu.org/copyleft/lgpl.html
#include "SEManagedFrameworkPCH.h"
using namespace System::Reflection;
using namespace System::Runtime::CompilerServices;
//
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
//
[assembly:AssemblyTitleAttribute("")];
[assembly:AssemblyDescriptionAttribute("")];
[assembly:AssemblyConfigurationAttribute("")];
[assembly:AssemblyCompanyAttribute("")];
[assembly:AssemblyProductAttribute("")];
[assembly:AssemblyCopyrightAttribute("")];
[assembly:AssemblyTrademarkAttribute("")];
[assembly:AssemblyCultureAttribute("")];
// Public types are CLS-compliant unless otherwise stated.
[assembly:CLSCompliantAttribute(true)];
//
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the value or you can default the Revision and
// Build Numbers
// by using the '*' as shown below:
[assembly:AssemblyVersionAttribute("1.0.*")];
//
// In order to sign your assembly you must specify a key to use. Refer to the
// Microsoft .NET Framework documentation for more information on assembly
// signing.
//
// Use the attributes below to control which key is used for signing.
//
// Notes:
// (*) If no key is specified, the assembly is not signed.
// (*) KeyName refers to a key that has been installed in the Crypto Service
// Provider (CSP) on your machine. KeyFile refers to a file which
// contains
// a key.
// (*) If the KeyFile and the KeyName values are both specified, the
// following processing occurs:
// (1) If the KeyName can be found in the CSP, that key is used.
// (2) If the KeyName does not exist and the KeyFile does exist, the key
// in the KeyFile is installed into the CSP and used.
// (*) In order to create a KeyFile, you can use the sn.exe (Strong Name)
// utility.
// When specifying the KeyFile, the location of the KeyFile should be
// relative to the project directory.
// (*) Delay Signing is an advanced option - see the Microsoft .NET Framework
// documentation for more information on this.
//
[assembly:AssemblyDelaySignAttribute(false)];
[assembly:AssemblyKeyFileAttribute("")];
[assembly:AssemblyKeyNameAttribute("")];
| [
"hide106@163.com@876e9856-8d94-11de-b760-4d83c623b0ac"
] | hide106@163.com@876e9856-8d94-11de-b760-4d83c623b0ac |
44f41026306d7957b6730a297e55d2dfcac9f2ae | 824393d3a158860c66a31cdd50ba07972859912e | /bzoj2594.cc | 58788edf32f072d9ccb35b926c7d5e3554200050 | [] | no_license | gcgeng/My-Code | 3cc661640e411aec9545a400fcbfbabda4d3a567 | fb41fecc65b0a79a2154e6a70d659010bc3aa17d | refs/heads/master | 2023-08-31T01:52:56.441414 | 2017-05-13T15:14:02 | 2017-05-13T15:14:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,498 | cc | #include <algorithm>
#include <cctype>
#include <cstdio>
#include <cstring>
#include <iostream>
const int maxv = 1500005;
int read() {
int x = 0, f = 1;
char ch = getchar();
while (!isdigit(ch)) {
if (ch == '-')
f = -1;
ch = getchar();
}
while (isdigit(ch)) {
x = x * 10 + ch - '0';
ch = getchar();
}
return x * f;
}
struct data {
int from, to, dat, br, id;
data(int x = 0, int y = 0, int z = 0, int i = 0, int j = 0)
: from(x), to(y), dat(z), br(i), id(j) {}
bool operator<(const data b) const {
return this->from < b.from || ((this->from == b.from) && (this->to < b.to));
}
} a[1000005];
struct req {
int opt, x, y, id, ans;
req(int x = 0, int y = 0, int z = 0, int k = 0, int fuck = 0) {
this->opt = x;
this->x = y;
this->y = z;
this->id = k;
this->ans = fuck;
}
} q[100005];
bool cmp(data a, data b) { return a.dat < b.dat; }
bool cmp2(data a, data b) { return a.id < b.id; }
int n, m, qaq, f[maxv], max[maxv], val[maxv], tot, maxnum[maxv];
int fa[maxv], ch[maxv][2];
bool rev[maxv];
int bisearch(int u, int v) {
int l = 1, r = m;
while (l <= r) {
int mid = (l + r) >> 1;
if (a[mid].from < u || (a[mid].from == u && a[mid].to < v))
l = mid + 1;
else if (a[mid].from == u && a[mid].to == v)
return mid;
else
r = mid - 1;
}
return -1;
}
bool isroot(int x) { return ch[fa[x]][0] != x && ch[fa[x]][1] != x; }
void pushdown(int k) {
if (rev[k]) {
rev[k] ^= 1;
rev[ch[k][0]] ^= 1;
rev[ch[k][1]] ^= 1;
std::swap(ch[k][0], ch[k][1]);
}
}
void update(int x) {
maxnum[x] = x;
int l = maxnum[ch[x][0]], r = maxnum[ch[x][1]];
if (val[l] > val[maxnum[x]])
maxnum[x] = l;
if (val[r] > val[maxnum[x]])
maxnum[x] = r;
max[x] = val[maxnum[x]];
}
void zig(int x) {
int y = fa[x], z = fa[y], l = (ch[y][1] == x), r = l ^ 1;
if (!isroot(y))
ch[z][ch[z][1] == y] = x;
fa[ch[y][l] = ch[x][r]] = y;
fa[ch[x][r] = y] = x;
fa[x] = z;
update(y);
update(x);
}
void splay(int x) {
int s[maxv], top = 0;
s[++top] = x;
for (int i = x; !isroot(i); i = fa[i])
s[++top] = fa[i];
while (top)
pushdown(s[top--]);
for (int y; !isroot(x); zig(x)) {
if (!isroot(y = fa[x])) {
zig((ch[fa[y]][0] == y) == (ch[y][0] == x) ? y : x);
}
}
update(x);
}
void access(int x) {
for (int t = 0; x; t = x, x = fa[x]) {
splay(x);
ch[x][1] = t;
update(x);
}
}
void makeroot(int x) {
access(x);
splay(x);
rev[x] ^= 1;
}
void split(int x, int y) {
makeroot(y);
access(x);
splay(x);
}
void link(int x, int y) {
makeroot(x);
fa[x] = y;
}
void cut(int x, int y) {
makeroot(x);
access(y);
splay(y);
ch[y][0] = fa[x] = 0;
}
void init() {
memset(val, 0, sizeof(val));
n = read();
m = read();
qaq = read();
for (int i = 1; i <= n; i++)
f[i] = i;
for (int i = 1; i <= m; i++) {
int x = read(), y = read(), z = read();
if (x > y)
std::swap(x, y);
a[i] = data(x, y, z);
}
std::sort(a + 1, a + 1 + m, cmp);
for (int i = 1; i <= m; i++) {
a[i].id = i;
val[n + i] = a[i].dat;
maxnum[n + i] = n + i;
}
std::sort(a + 1, a + 1 + m);
for (int i = 1; i <= qaq; i++) {
int x = read(), y = read(), z = read();
q[i] = req(x, y, z);
if (x == 2) {
if (q[i].x > q[i].y)
std::swap(q[i].x, q[i].y);
int t = bisearch(q[i].x, q[i].y);
a[t].br = 1;
q[i].id = a[t].id;
}
}
}
int find(int x) { return f[x] == x ? x : f[x] = find(f[x]); }
void kruskal() {
std::sort(a + 1, a + m + 1, cmp2);
tot = 0;
for (int i = 1; i <= m; i++) {
if (!a[i].br) {
int u = a[i].from, v = a[i].to, x = find(u), y = find(v);
if (x != y) {
f[x] = y;
link(u, i + n);
link(v, i + n);
tot++;
if (tot == n - 1)
break;
}
}
}
}
void solve() {
for (int i = qaq; i >= 1; i--) {
int op = q[i].opt, x = q[i].x, y = q[i].y;
if (op == 1) {
split(x, y);
q[i].ans = val[maxnum[x]];
}
if (op == 2) {
int k = q[i].id;
split(x, y);
int t = maxnum[x];
if (a[k].dat < val[t]) {
cut(a[t - n].from, t);
cut(a[t - n].to, t);
link(x, k + n);
link(y, k + n);
}
}
}
for (int i = 1; i <= qaq; i++) {
if (q[i].opt == 1)
printf("%d\n", q[i].ans);
}
}
int main() {
#ifndef ONLINE_JUDGE
freopen("input", "r", stdin);
#endif
init();
kruskal();
solve();
return 0;
}
| [
"unrealgengchen@gmail.com"
] | unrealgengchen@gmail.com |
ef4ffc3119ca8677deecf355d02b37ad511fb630 | c4faeb593157c6d464e3b6c5d63f1502c15d0c99 | /src/D.cpp | 6363f77eb61bf8429c741685759aaef871cb60d8 | [] | no_license | paulodellanzo/tallerdeprogramacionuba | ae13f4bad8e4ae4c3230e7c665657b89c9646047 | f742d285378448fd8cd2f7789705de8af6e7b153 | refs/heads/master | 2021-01-25T10:06:26.164327 | 2010-11-25T02:25:30 | 2010-11-25T02:25:30 | 32,342,666 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,163 | cpp | #include "D.h"
D::D() {
// TODO Auto-generated constructor stub
}
list<string>* D::realizarOperacion(list<char*>* operandos, Jugador * jugador){
list<string>* respuesta = new list<string>();
list<string>::iterator it=respuesta->begin();
char * apuesta;
if(strcmp(operandos->front(),"Poso")==0){
operandos->pop_front();
apuesta=operandos->front();
operandos->pop_front();
}else{
it=respuesta->begin();
it=respuesta->insert(it,"Error");
it++;
it=respuesta->insert(it,"V");
it++;
it=respuesta->insert(it,"Falta ingresar apuesta");
return respuesta;
}
int apuestaInt=atoi(apuesta);
if(apuestaInt==0){
jugador->dejarDeJugar();
cout<<"Dejo de jugar"<<endl;
}
int apuestaAux=0 - apuestaInt;
jugador->modificarPlataEn(apuestaAux);
apuestaInt+=jugador->getUltimaApuesta() + 1;
jugador->setUltimaApuesta(apuestaInt);
ostringstream sstream;
sstream << apuestaInt;
string apuestaString = sstream.str();
it=respuesta->begin();
it=respuesta->insert(it,"Correcto");
it++;
it=respuesta->insert(it,"Poso");
it++;
it=respuesta->insert(it,apuestaString);
return respuesta;
}
D::~D() {
// TODO Auto-generated destructor stub
}
| [
"tatoqac@gmail.com@7e5a14ec-3cf2-37fe-fe1e-88608d0336ab"
] | tatoqac@gmail.com@7e5a14ec-3cf2-37fe-fe1e-88608d0336ab |
45ee990589672df4dc0d80d14b2e106368f926c2 | 986959b15d763745518085bdb5106daeb4e0b41d | /Volume - 5 (500 - 572)/500 - Print “Hello”.cpp | 0a989b56a5926161c71e704ddcea7e82e622a742 | [] | no_license | Md-Sabbir-Ahmed/Outsbook | a19d314b481d5f2e57478c98b0fe50d08781310c | e3b2c54517de3badff96f96d99d1592db7286513 | refs/heads/master | 2022-11-07T06:43:37.955730 | 2020-06-26T20:32:03 | 2020-06-26T20:32:03 | 267,264,610 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 235 | cpp | #include<bits/stdc++.h>
using namespace std;
int main()
{
int n;
while(cin>>n)
{
int c=0;
for(int i=1;i<=n;i++){
c++;
cout<<"Line "<<c<<": hello\n";
}
}
return 0;
}
| [
"sabbir106706@gmail.com"
] | sabbir106706@gmail.com |
2fe6b6bfeb39660c9a1ad063c2e50e93d609e751 | 7b4ce7c1411fb2a3b0ab088d89bf93ed97b1905d | /dep/scintilla/scintilla-3.21.0/lexers/LexSTTXT.cxx | dd2fe5465e4bd1ecc7117ab5e646bebd4485f8ba | [
"LicenseRef-scancode-scintilla",
"MIT"
] | permissive | gitahead/gitahead | 9fb86aee4df2e60fb1ff5bec615e3f6876b70049 | 81df5b468fc3ebd148320d894e561fb097324b88 | refs/heads/master | 2023-08-15T01:20:34.055687 | 2022-05-24T21:03:38 | 2022-05-24T21:03:38 | 159,882,575 | 1,894 | 318 | MIT | 2022-04-06T18:37:07 | 2018-11-30T21:52:34 | C++ | UTF-8 | C++ | false | false | 11,010 | cxx | // Scintilla source code edit control
/** @file LexSTTXT.cxx
** Lexer for Structured Text language.
** Written by Pavel Bulochkin
**/
// The License.txt file describes the conditions under which this software may be distributed.
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <stdarg.h>
#include <assert.h>
#include <ctype.h>
#include "ILexer.h"
#include "Scintilla.h"
#include "SciLexer.h"
#include "WordList.h"
#include "LexAccessor.h"
#include "Accessor.h"
#include "StyleContext.h"
#include "CharacterSet.h"
#include "LexerModule.h"
using namespace Scintilla;
static void ClassifySTTXTWord(WordList *keywordlists[], StyleContext &sc)
{
char s[256] = { 0 };
sc.GetCurrentLowered(s, sizeof(s));
if ((*keywordlists[0]).InList(s)) {
sc.ChangeState(SCE_STTXT_KEYWORD);
}
else if ((*keywordlists[1]).InList(s)) {
sc.ChangeState(SCE_STTXT_TYPE);
}
else if ((*keywordlists[2]).InList(s)) {
sc.ChangeState(SCE_STTXT_FUNCTION);
}
else if ((*keywordlists[3]).InList(s)) {
sc.ChangeState(SCE_STTXT_FB);
}
else if ((*keywordlists[4]).InList(s)) {
sc.ChangeState(SCE_STTXT_VARS);
}
else if ((*keywordlists[5]).InList(s)) {
sc.ChangeState(SCE_STTXT_PRAGMAS);
}
sc.SetState(SCE_STTXT_DEFAULT);
}
static void ColouriseSTTXTDoc (Sci_PositionU startPos, Sci_Position length, int initStyle,
WordList *keywordlists[], Accessor &styler)
{
StyleContext sc(startPos, length, initStyle, styler);
CharacterSet setWord(CharacterSet::setAlphaNum, "_", 0x80, true);
CharacterSet setWordStart(CharacterSet::setAlpha, "_", 0x80, true);
CharacterSet setNumber(CharacterSet::setDigits, "_.eE");
CharacterSet setHexNumber(CharacterSet::setDigits, "_abcdefABCDEF");
CharacterSet setOperator(CharacterSet::setNone,",.+-*/:;<=>[]()%&");
CharacterSet setDataTime(CharacterSet::setDigits,"_.-:dmshDMSH");
for ( ; sc.More() ; sc.Forward())
{
if(sc.atLineStart && sc.state != SCE_STTXT_COMMENT)
sc.SetState(SCE_STTXT_DEFAULT);
switch(sc.state)
{
case SCE_STTXT_NUMBER: {
if(!setNumber.Contains(sc.ch))
sc.SetState(SCE_STTXT_DEFAULT);
break;
}
case SCE_STTXT_HEXNUMBER: {
if (setHexNumber.Contains(sc.ch))
continue;
else if(setDataTime.Contains(sc.ch))
sc.ChangeState(SCE_STTXT_DATETIME);
else if(setWord.Contains(sc.ch))
sc.ChangeState(SCE_STTXT_DEFAULT);
else
sc.SetState(SCE_STTXT_DEFAULT);
break;
}
case SCE_STTXT_DATETIME: {
if (setDataTime.Contains(sc.ch))
continue;
else if(setWord.Contains(sc.ch))
sc.ChangeState(SCE_STTXT_DEFAULT);
else
sc.SetState(SCE_STTXT_DEFAULT);
break;
}
case SCE_STTXT_OPERATOR: {
sc.SetState(SCE_STTXT_DEFAULT);
break;
}
case SCE_STTXT_PRAGMA: {
if (sc.ch == '}')
sc.ForwardSetState(SCE_STTXT_DEFAULT);
break;
}
case SCE_STTXT_COMMENTLINE: {
if (sc.atLineStart)
sc.SetState(SCE_STTXT_DEFAULT);
break;
}
case SCE_STTXT_COMMENT: {
if(sc.Match('*',')'))
{
sc.Forward();
sc.ForwardSetState(SCE_STTXT_DEFAULT);
}
break;
}
case SCE_STTXT_STRING1: {
if(sc.atLineEnd)
sc.SetState(SCE_STTXT_STRINGEOL);
else if(sc.ch == '\'' && sc.chPrev != '$')
sc.ForwardSetState(SCE_STTXT_DEFAULT);
break;
}
case SCE_STTXT_STRING2: {
if (sc.atLineEnd)
sc.SetState(SCE_STTXT_STRINGEOL);
else if(sc.ch == '\"' && sc.chPrev != '$')
sc.ForwardSetState(SCE_STTXT_DEFAULT);
break;
}
case SCE_STTXT_STRINGEOL: {
if(sc.atLineStart)
sc.SetState(SCE_STTXT_DEFAULT);
break;
}
case SCE_STTXT_CHARACTER: {
if(setHexNumber.Contains(sc.ch))
sc.SetState(SCE_STTXT_HEXNUMBER);
else if(setDataTime.Contains(sc.ch))
sc.SetState(SCE_STTXT_DATETIME);
else sc.SetState(SCE_STTXT_DEFAULT);
break;
}
case SCE_STTXT_IDENTIFIER: {
if(!setWord.Contains(sc.ch))
ClassifySTTXTWord(keywordlists, sc);
break;
}
}
if(sc.state == SCE_STTXT_DEFAULT)
{
if(IsADigit(sc.ch))
sc.SetState(SCE_STTXT_NUMBER);
else if (setWordStart.Contains(sc.ch))
sc.SetState(SCE_STTXT_IDENTIFIER);
else if (sc.Match('/', '/'))
sc.SetState(SCE_STTXT_COMMENTLINE);
else if(sc.Match('(', '*'))
sc.SetState(SCE_STTXT_COMMENT);
else if (sc.ch == '{')
sc.SetState(SCE_STTXT_PRAGMA);
else if (sc.ch == '\'')
sc.SetState(SCE_STTXT_STRING1);
else if (sc.ch == '\"')
sc.SetState(SCE_STTXT_STRING2);
else if(sc.ch == '#')
sc.SetState(SCE_STTXT_CHARACTER);
else if (setOperator.Contains(sc.ch))
sc.SetState(SCE_STTXT_OPERATOR);
}
}
if (sc.state == SCE_STTXT_IDENTIFIER && setWord.Contains(sc.chPrev))
ClassifySTTXTWord(keywordlists, sc);
sc.Complete();
}
static const char * const STTXTWordListDesc[] = {
"Keywords",
"Types",
"Functions",
"FB",
"Local_Var",
"Local_Pragma",
0
};
static bool IsCommentLine(Sci_Position line, Accessor &styler, bool type)
{
Sci_Position pos = styler.LineStart(line);
Sci_Position eolPos = styler.LineStart(line + 1) - 1;
for (Sci_Position i = pos; i < eolPos; i++)
{
char ch = styler[i];
char chNext = styler.SafeGetCharAt(i + 1);
int style = styler.StyleAt(i);
if(type) {
if (ch == '/' && chNext == '/' && style == SCE_STTXT_COMMENTLINE)
return true;
}
else if (ch == '(' && chNext == '*' && style == SCE_STTXT_COMMENT)
break;
if (!IsASpaceOrTab(ch))
return false;
}
for (Sci_Position i = eolPos-2; i>pos; i--)
{
char ch = styler[i];
char chPrev = styler.SafeGetCharAt(i-1);
int style = styler.StyleAt(i);
if(ch == ')' && chPrev == '*' && style == SCE_STTXT_COMMENT)
return true;
if(!IsASpaceOrTab(ch))
return false;
}
return false;
}
static bool IsPragmaLine(Sci_Position line, Accessor &styler)
{
Sci_Position pos = styler.LineStart(line);
Sci_Position eolPos = styler.LineStart(line+1) - 1;
for (Sci_Position i = pos ; i < eolPos ; i++)
{
char ch = styler[i];
int style = styler.StyleAt(i);
if(ch == '{' && style == SCE_STTXT_PRAGMA)
return true;
else if (!IsASpaceOrTab(ch))
return false;
}
return false;
}
static void GetRangeUpper(Sci_PositionU start,Sci_PositionU end,Accessor &styler,char *s,Sci_PositionU len)
{
Sci_PositionU i = 0;
while ((i < end - start + 1) && (i < len-1)) {
s[i] = static_cast<char>(toupper(styler[start + i]));
i++;
}
s[i] = '\0';
}
static void ClassifySTTXTWordFoldPoint(int &levelCurrent,Sci_PositionU lastStart,
Sci_PositionU currentPos, Accessor &styler)
{
char s[256];
GetRangeUpper(lastStart, currentPos, styler, s, sizeof(s));
// See Table C.2 - Keywords
if (!strcmp(s, "ACTION") ||
!strcmp(s, "CASE") ||
!strcmp(s, "CONFIGURATION") ||
!strcmp(s, "FOR") ||
!strcmp(s, "FUNCTION") ||
!strcmp(s, "FUNCTION_BLOCK") ||
!strcmp(s, "IF") ||
!strcmp(s, "INITIAL_STEP") ||
!strcmp(s, "REPEAT") ||
!strcmp(s, "RESOURCE") ||
!strcmp(s, "STEP") ||
!strcmp(s, "STRUCT") ||
!strcmp(s, "TRANSITION") ||
!strcmp(s, "TYPE") ||
!strcmp(s, "VAR") ||
!strcmp(s, "VAR_INPUT") ||
!strcmp(s, "VAR_OUTPUT") ||
!strcmp(s, "VAR_IN_OUT") ||
!strcmp(s, "VAR_TEMP") ||
!strcmp(s, "VAR_EXTERNAL") ||
!strcmp(s, "VAR_ACCESS") ||
!strcmp(s, "VAR_CONFIG") ||
!strcmp(s, "VAR_GLOBAL") ||
!strcmp(s, "WHILE"))
{
levelCurrent++;
}
else if (!strcmp(s, "END_ACTION") ||
!strcmp(s, "END_CASE") ||
!strcmp(s, "END_CONFIGURATION") ||
!strcmp(s, "END_FOR") ||
!strcmp(s, "END_FUNCTION") ||
!strcmp(s, "END_FUNCTION_BLOCK") ||
!strcmp(s, "END_IF") ||
!strcmp(s, "END_REPEAT") ||
!strcmp(s, "END_RESOURCE") ||
!strcmp(s, "END_STEP") ||
!strcmp(s, "END_STRUCT") ||
!strcmp(s, "END_TRANSITION") ||
!strcmp(s, "END_TYPE") ||
!strcmp(s, "END_VAR") ||
!strcmp(s, "END_WHILE"))
{
levelCurrent--;
if (levelCurrent < SC_FOLDLEVELBASE) {
levelCurrent = SC_FOLDLEVELBASE;
}
}
}
static void FoldSTTXTDoc(Sci_PositionU startPos, Sci_Position length, int initStyle, WordList *[],Accessor &styler)
{
bool foldComment = styler.GetPropertyInt("fold.comment") != 0;
bool foldPreprocessor = styler.GetPropertyInt("fold.preprocessor") != 0;
bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
Sci_PositionU endPos = startPos + length;
int visibleChars = 0;
Sci_Position lineCurrent = styler.GetLine(startPos);
int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
int levelCurrent = levelPrev;
char chNext = styler[startPos];
int styleNext = styler.StyleAt(startPos);
int style = initStyle;
Sci_Position lastStart = 0;
CharacterSet setWord(CharacterSet::setAlphaNum, "_", 0x80, true);
for (Sci_PositionU i = startPos; i < endPos; i++)
{
char ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
int stylePrev = style;
style = styleNext;
styleNext = styler.StyleAt(i + 1);
bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n');
if (foldComment && style == SCE_STTXT_COMMENT) {
if(stylePrev != SCE_STTXT_COMMENT)
levelCurrent++;
else if(styleNext != SCE_STTXT_COMMENT && !atEOL)
levelCurrent--;
}
if ( foldComment && atEOL && ( IsCommentLine(lineCurrent, styler,false)
|| IsCommentLine(lineCurrent,styler,true))) {
if(!IsCommentLine(lineCurrent-1, styler,true) && IsCommentLine(lineCurrent+1, styler,true))
levelCurrent++;
if (IsCommentLine(lineCurrent-1, styler,true) && !IsCommentLine(lineCurrent+1, styler,true))
levelCurrent--;
if (!IsCommentLine(lineCurrent-1, styler,false) && IsCommentLine(lineCurrent+1, styler,false))
levelCurrent++;
if (IsCommentLine(lineCurrent-1, styler,false) && !IsCommentLine(lineCurrent+1, styler,false))
levelCurrent--;
}
if(foldPreprocessor && atEOL && IsPragmaLine(lineCurrent, styler)) {
if(!IsPragmaLine(lineCurrent-1, styler) && IsPragmaLine(lineCurrent+1, styler ))
levelCurrent++;
else if(IsPragmaLine(lineCurrent-1, styler) && !IsPragmaLine(lineCurrent+1, styler))
levelCurrent--;
}
if (stylePrev != SCE_STTXT_KEYWORD && style == SCE_STTXT_KEYWORD) {
lastStart = i;
}
if(stylePrev == SCE_STTXT_KEYWORD) {
if(setWord.Contains(ch) && !setWord.Contains(chNext))
ClassifySTTXTWordFoldPoint(levelCurrent,lastStart, i, styler);
}
if (!IsASpace(ch)) {
visibleChars++;
}
if (atEOL) {
int lev = levelPrev;
if (visibleChars == 0 && foldCompact)
lev |= SC_FOLDLEVELWHITEFLAG;
if ((levelCurrent > levelPrev) && (visibleChars > 0))
lev |= SC_FOLDLEVELHEADERFLAG;
if (lev != styler.LevelAt(lineCurrent))
styler.SetLevel(lineCurrent, lev);
lineCurrent++;
levelPrev = levelCurrent;
visibleChars = 0;
}
// If we didn't reach the EOL in previous loop, store line level and whitespace information.
// The rest will be filled in later...
int lev = levelPrev;
if (visibleChars == 0 && foldCompact)
lev |= SC_FOLDLEVELWHITEFLAG;
styler.SetLevel(lineCurrent, lev);
}
}
LexerModule lmSTTXT(SCLEX_STTXT, ColouriseSTTXTDoc, "fcST", FoldSTTXTDoc, STTXTWordListDesc);
| [
"jason@scitools.com"
] | jason@scitools.com |
7e66f9c98cc4bae1c48c3ccf2a27611b93d026d8 | ac55debd36644e7e57888783fe3a716d7a30db15 | /1. C++学习第一阶段/7. 指针/5. 指针和数组.cpp | 22ab9a790f8c21f3b860c1eefbee9db39841992a | [] | no_license | Kerry-yu/Cpp_Learn | abe234062d74afc8b7d2d681fd25341fe9282726 | 574973e61433bd0f3f541ec58b545dc9bb954c43 | refs/heads/main | 2023-08-27T18:42:38.918104 | 2021-11-13T08:39:47 | 2021-11-13T08:39:47 | 395,538,092 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 599 | cpp | #include<iostream>
using namespace std;
int main() {
//指针和数组
//利用指针访问数组中的元素
int arr[10] = { 1,2,3,4,5,6,7,8,9,10 };
cout << "第一个元素为:" << arr[0] << endl;
int* p = arr;//arr(数组名)就是数组的首地址
cout << "利用指针访问第一个元素: " << *p << endl;
p++;//指针向后偏移四个字节
cout << "利用指针访问第二个元素: " << *p << endl;
//利用指针遍历数组
cout << "利用指针遍历数组" << endl;
int* p2 = arr;
for (int i = 0; i < 10; i++)
{
cout << *p2 << endl;
p2++;
}
return 0;
}
| [
"2413800399@qq.com"
] | 2413800399@qq.com |
c626d3c2742c40b5950f65f92f191cdbfe91db17 | 20f6693bed8e559b32b5b649f7393908964932de | /SDK/DBDGameplayPresenter_functions.cpp | cba77a17259a643942ecaf29f693aaa2b68a83b6 | [] | no_license | xnf4o/DBD_SDK_502 | 9e0e210490e2f7b9bc9b021f48972e252d66f0c7 | c7da68275286e53b9a24d6b8afbb6e932fc93407 | refs/heads/main | 2023-05-31T18:55:45.805581 | 2021-07-01T14:23:54 | 2021-07-01T14:23:54 | 382,058,835 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 18,221 | cpp | // Name: dbd, Version: 502
#include "../pch.h"
/*!!DEFINE!!*/
/*!!HELPER_DEF!!*/
/*!!HELPER_INC!!*/
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
namespace CG
{
//---------------------------------------------------------------------------
// Functions
//---------------------------------------------------------------------------
// Function DBDGameplayPresenter.SurvivorStatusComponent.OnValidatedInteractionStarted
// (Final, Native, Private)
void USurvivorStatusComponent::OnValidatedInteractionStarted()
{
static UFunction* fn = nullptr;
if (!fn)
fn =
UObject::FindObject<UFunction>("Function DBDGameplayPresenter.SurvivorStatusComponent.OnValidatedInteractionStarted");
USurvivorStatusComponent_OnValidatedInteractionStarted_Params params;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function DBDGameplayPresenter.SurvivorStatusComponent.OnValidatedInteractionEnded
// (Final, Native, Private)
void USurvivorStatusComponent::OnValidatedInteractionEnded()
{
static UFunction* fn = nullptr;
if (!fn)
fn =
UObject::FindObject<UFunction>("Function DBDGameplayPresenter.SurvivorStatusComponent.OnValidatedInteractionEnded");
USurvivorStatusComponent_OnValidatedInteractionEnded_Params params;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function DBDGameplayPresenter.SurvivorStatusComponent.OnSuvivorDamaged
// (Final, Native, Private)
// Parameters:
// DeadByDaylight_ECamperDamageState oldDamageState (ConstParm, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// DeadByDaylight_ECamperDamageState newDamageState (ConstParm, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void USurvivorStatusComponent::OnSuvivorDamaged(DeadByDaylight_ECamperDamageState oldDamageState, DeadByDaylight_ECamperDamageState newDamageState)
{
static UFunction* fn = nullptr;
if (!fn)
fn =
UObject::FindObject<UFunction>("Function DBDGameplayPresenter.SurvivorStatusComponent.OnSuvivorDamaged");
USurvivorStatusComponent_OnSuvivorDamaged_Params params;
params.oldDamageState = oldDamageState;
params.newDamageState = newDamageState;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function DBDGameplayPresenter.SurvivorStatusComponent.OnSurivorStatusChange
// (Event, Public, BlueprintEvent)
void USurvivorStatusComponent::OnSurivorStatusChange()
{
static UFunction* fn = nullptr;
if (!fn)
fn =
UObject::FindObject<UFunction>("Function DBDGameplayPresenter.SurvivorStatusComponent.OnSurivorStatusChange");
USurvivorStatusComponent_OnSurivorStatusChange_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function DBDGameplayPresenter.SurvivorStatusComponent.OnRunningAndMovementChanged
// (Final, Native, Private)
// Parameters:
// bool isRunningAndMoving (ConstParm, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void USurvivorStatusComponent::OnRunningAndMovementChanged(bool isRunningAndMoving)
{
static UFunction* fn = nullptr;
if (!fn)
fn =
UObject::FindObject<UFunction>("Function DBDGameplayPresenter.SurvivorStatusComponent.OnRunningAndMovementChanged");
USurvivorStatusComponent_OnRunningAndMovementChanged_Params params;
params.isRunningAndMoving = isRunningAndMoving;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function DBDGameplayPresenter.SurvivorStatusComponent.OnPlayerImmobilizeStateChanged
// (Final, Native, Private)
// Parameters:
// DeadByDaylight_ECamperImmobilizeState oldImmobilizeState (ConstParm, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// DeadByDaylight_ECamperImmobilizeState newImmobilizeState (ConstParm, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void USurvivorStatusComponent::OnPlayerImmobilizeStateChanged(DeadByDaylight_ECamperImmobilizeState oldImmobilizeState, DeadByDaylight_ECamperImmobilizeState newImmobilizeState)
{
static UFunction* fn = nullptr;
if (!fn)
fn =
UObject::FindObject<UFunction>("Function DBDGameplayPresenter.SurvivorStatusComponent.OnPlayerImmobilizeStateChanged");
USurvivorStatusComponent_OnPlayerImmobilizeStateChanged_Params params;
params.oldImmobilizeState = oldImmobilizeState;
params.newImmobilizeState = newImmobilizeState;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function DBDGameplayPresenter.SurvivorStatusComponent.OnHookedStateChanged
// (Final, Native, Private)
void USurvivorStatusComponent::OnHookedStateChanged()
{
static UFunction* fn = nullptr;
if (!fn)
fn =
UObject::FindObject<UFunction>("Function DBDGameplayPresenter.SurvivorStatusComponent.OnHookedStateChanged");
USurvivorStatusComponent_OnHookedStateChanged_Params params;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function DBDGameplayPresenter.SurvivorStatusComponent.OnGuidedStateChanged
// (Final, Native, Private)
void USurvivorStatusComponent::OnGuidedStateChanged()
{
static UFunction* fn = nullptr;
if (!fn)
fn =
UObject::FindObject<UFunction>("Function DBDGameplayPresenter.SurvivorStatusComponent.OnGuidedStateChanged");
USurvivorStatusComponent_OnGuidedStateChanged_Params params;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function DBDGameplayPresenter.SurvivorStatusComponent.OnCrouchChanged
// (Final, Native, Private)
// Parameters:
// bool IsCrouched (ConstParm, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void USurvivorStatusComponent::OnCrouchChanged(bool IsCrouched)
{
static UFunction* fn = nullptr;
if (!fn)
fn =
UObject::FindObject<UFunction>("Function DBDGameplayPresenter.SurvivorStatusComponent.OnCrouchChanged");
USurvivorStatusComponent_OnCrouchChanged_Params params;
params.IsCrouched = IsCrouched;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function DBDGameplayPresenter.SurvivorStatusComponent.IsSleeping
// (Final, Native, Public, BlueprintCallable, BlueprintPure, Const)
// Parameters:
// bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
bool USurvivorStatusComponent::IsSleeping()
{
static UFunction* fn = nullptr;
if (!fn)
fn =
UObject::FindObject<UFunction>("Function DBDGameplayPresenter.SurvivorStatusComponent.IsSleeping");
USurvivorStatusComponent_IsSleeping_Params params;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function DBDGameplayPresenter.SurvivorStatusComponent.IsRunning
// (Final, Native, Public, BlueprintCallable, BlueprintPure, Const)
// Parameters:
// bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
bool USurvivorStatusComponent::IsRunning()
{
static UFunction* fn = nullptr;
if (!fn)
fn =
UObject::FindObject<UFunction>("Function DBDGameplayPresenter.SurvivorStatusComponent.IsRunning");
USurvivorStatusComponent_IsRunning_Params params;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function DBDGameplayPresenter.SurvivorStatusComponent.IsInjured
// (Final, Native, Public, BlueprintCallable, BlueprintPure, Const)
// Parameters:
// bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
bool USurvivorStatusComponent::IsInjured()
{
static UFunction* fn = nullptr;
if (!fn)
fn =
UObject::FindObject<UFunction>("Function DBDGameplayPresenter.SurvivorStatusComponent.IsInjured");
USurvivorStatusComponent_IsInjured_Params params;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function DBDGameplayPresenter.SurvivorStatusComponent.IsHooked
// (Final, Native, Public, BlueprintCallable, BlueprintPure, Const)
// Parameters:
// bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
bool USurvivorStatusComponent::IsHooked()
{
static UFunction* fn = nullptr;
if (!fn)
fn =
UObject::FindObject<UFunction>("Function DBDGameplayPresenter.SurvivorStatusComponent.IsHooked");
USurvivorStatusComponent_IsHooked_Params params;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function DBDGameplayPresenter.SurvivorStatusComponent.IsHiding
// (Final, Native, Public, BlueprintCallable, BlueprintPure, Const)
// Parameters:
// bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
bool USurvivorStatusComponent::IsHiding()
{
static UFunction* fn = nullptr;
if (!fn)
fn =
UObject::FindObject<UFunction>("Function DBDGameplayPresenter.SurvivorStatusComponent.IsHiding");
USurvivorStatusComponent_IsHiding_Params params;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function DBDGameplayPresenter.SurvivorStatusComponent.IsHealing
// (Final, Native, Public, BlueprintCallable, BlueprintPure, Const)
// Parameters:
// bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
bool USurvivorStatusComponent::IsHealing()
{
static UFunction* fn = nullptr;
if (!fn)
fn =
UObject::FindObject<UFunction>("Function DBDGameplayPresenter.SurvivorStatusComponent.IsHealing");
USurvivorStatusComponent_IsHealing_Params params;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function DBDGameplayPresenter.SurvivorStatusComponent.IsHarpooned
// (Final, Native, Public, BlueprintCallable, BlueprintPure, Const)
// Parameters:
// bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
bool USurvivorStatusComponent::IsHarpooned()
{
static UFunction* fn = nullptr;
if (!fn)
fn =
UObject::FindObject<UFunction>("Function DBDGameplayPresenter.SurvivorStatusComponent.IsHarpooned");
USurvivorStatusComponent_IsHarpooned_Params params;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function DBDGameplayPresenter.SurvivorStatusComponent.IsGettingStrangled
// (Final, Native, Public, BlueprintCallable, BlueprintPure, Const)
// Parameters:
// bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
bool USurvivorStatusComponent::IsGettingStrangled()
{
static UFunction* fn = nullptr;
if (!fn)
fn =
UObject::FindObject<UFunction>("Function DBDGameplayPresenter.SurvivorStatusComponent.IsGettingStrangled");
USurvivorStatusComponent_IsGettingStrangled_Params params;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function DBDGameplayPresenter.SurvivorStatusComponent.IsGettingSacrificed
// (Final, Native, Public, BlueprintCallable, BlueprintPure, Const)
// Parameters:
// bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
bool USurvivorStatusComponent::IsGettingSacrificed()
{
static UFunction* fn = nullptr;
if (!fn)
fn =
UObject::FindObject<UFunction>("Function DBDGameplayPresenter.SurvivorStatusComponent.IsGettingSacrificed");
USurvivorStatusComponent_IsGettingSacrificed_Params params;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function DBDGameplayPresenter.SurvivorStatusComponent.IsDying
// (Final, Native, Public, BlueprintCallable, BlueprintPure, Const)
// Parameters:
// bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
bool USurvivorStatusComponent::IsDying()
{
static UFunction* fn = nullptr;
if (!fn)
fn =
UObject::FindObject<UFunction>("Function DBDGameplayPresenter.SurvivorStatusComponent.IsDying");
USurvivorStatusComponent_IsDying_Params params;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function DBDGameplayPresenter.SurvivorStatusComponent.isDead
// (Final, Native, Public, BlueprintCallable, BlueprintPure, Const)
// Parameters:
// bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
bool USurvivorStatusComponent::isDead()
{
static UFunction* fn = nullptr;
if (!fn)
fn =
UObject::FindObject<UFunction>("Function DBDGameplayPresenter.SurvivorStatusComponent.isDead");
USurvivorStatusComponent_isDead_Params params;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function DBDGameplayPresenter.SurvivorStatusComponent.IsCrouching
// (Final, Native, Public, BlueprintCallable, BlueprintPure, Const)
// Parameters:
// bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
bool USurvivorStatusComponent::IsCrouching()
{
static UFunction* fn = nullptr;
if (!fn)
fn =
UObject::FindObject<UFunction>("Function DBDGameplayPresenter.SurvivorStatusComponent.IsCrouching");
USurvivorStatusComponent_IsCrouching_Params params;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function DBDGameplayPresenter.SurvivorStatusComponent.IsCaptured
// (Final, Native, Public, BlueprintCallable, BlueprintPure, Const)
// Parameters:
// bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
bool USurvivorStatusComponent::IsCaptured()
{
static UFunction* fn = nullptr;
if (!fn)
fn =
UObject::FindObject<UFunction>("Function DBDGameplayPresenter.SurvivorStatusComponent.IsCaptured");
USurvivorStatusComponent_IsCaptured_Params params;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function DBDGameplayPresenter.SurvivorStatusComponent.GetMovementSpeed
// (Final, Native, Public, HasOutParms, BlueprintCallable, BlueprintPure, Const)
// Parameters:
// float currentMovementSpeed (Parm, OutParm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// float percentMovementSpeed (Parm, OutParm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// float maximumMovementSpeed (Parm, OutParm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void USurvivorStatusComponent::GetMovementSpeed(float* currentMovementSpeed, float* percentMovementSpeed, float* maximumMovementSpeed)
{
static UFunction* fn = nullptr;
if (!fn)
fn =
UObject::FindObject<UFunction>("Function DBDGameplayPresenter.SurvivorStatusComponent.GetMovementSpeed");
USurvivorStatusComponent_GetMovementSpeed_Params params;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
if (currentMovementSpeed != nullptr)
*currentMovementSpeed = params.currentMovementSpeed;
if (percentMovementSpeed != nullptr)
*percentMovementSpeed = params.percentMovementSpeed;
if (maximumMovementSpeed != nullptr)
*maximumMovementSpeed = params.maximumMovementSpeed;
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"xnf4o@inbox.ru"
] | xnf4o@inbox.ru |
8a0f9d21c5d3e44992c6695baff1fd18f8d81a28 | ee92d1a196cf5c8b6ddf57307b71a571bb86503f | /2D-Game basics/StartState.cpp | c712713f781ba7f8924520fabe22b754929f6985 | [] | no_license | FreeSirenety/2D-Game-basics | aa21a740f531b6858a69982cb5c0a061286ced66 | 799270ca8755537625dbc7d8246c39f1a5556305 | refs/heads/master | 2021-01-25T08:49:22.969859 | 2014-10-01T16:02:00 | 2014-10-01T16:02:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 341 | cpp | #include "StartState.h"
#include <iostream>
StartState::StartState(SpriteManager *p_xSpriteManager) : State(p_xSpriteManager)
{
}
void StartState::Enter()
{
std::cout << "Entering Start State" << std::endl;
}
void StartState::Update(float p_fDeltaTime)
{
}
void StartState::Exit()
{
std::cout << "Exiting Start State" << std::endl;
} | [
"revilo.tlob@gmail.com"
] | revilo.tlob@gmail.com |
d838d809c87f68692eacf4dcb18441fe94cf13ee | 6eab01a42d97d1cf21dbf97341a8d2ed270e80b2 | /Demo/13/13.12/Source.cpp | f4d430cad5f8e31f6e32d84bb69fe6ddfccc6f78 | [] | no_license | TomSms/VSEngine2 | 30f5d4020bb7dddc3568a21a92c6c5bc6f354dc6 | b2bf9a4fae8fb4e028f1cedc3b2886999c1d27be | refs/heads/master | 2020-03-07T21:13:08.966023 | 2018-03-16T02:24:21 | 2018-03-16T02:24:21 | 127,720,662 | 0 | 1 | null | 2018-04-02T07:26:21 | 2018-04-02T07:26:21 | null | GB18030 | C++ | false | false | 8,399 | cpp | //这个Demo演示地形CLOD,加载了一个高程图作为地形。按W可以切换线框模式。
#include <VSApplication.h>
#include <VSEngineInput.h>
#include <VSCameraActor.h>
#include <VSWorld.h>
#include <VS1stCameraController.h>
#include "VSStaticActor.h"
#include "VSLightActor.h"
#include "VSSkyLight.h"
#include "VSViewFamily.h"
#include "VSTimer.h"
#include "VSSceneManager.h"
#include "VSTerrainActor.h"
#include "VSCLodTerrainNode.h"
using namespace VSEngine2;
class VSDemoWindowsApplication : public VSWindowApplication
{
DLCARE_APPLICATION(VSDemoWindowsApplication);
public:
VSDemoWindowsApplication();
~VSDemoWindowsApplication();
virtual bool PreInitial();
virtual bool OnInitial();
virtual bool OnTerminal();
virtual bool PostUpdate();
virtual bool PreUpdate();
virtual bool OnDraw();
virtual void OnMove(int xPos, int yPos);
virtual void OnReSize(int iWidth, int iHeight);
virtual void OnKeyDown(unsigned int uiKey);
virtual void OnKeyUp(unsigned int uiKey);
virtual void OnLButtonDown(int xPos, int yPos);
virtual void OnLButtonUp(int xPos, int yPos);
virtual void OnRButtonDown(int xPos, int yPos);
virtual void OnRButtonUp(int xPos, int yPos);
virtual void OnMButtonDown(int xPos, int yPos);
virtual void OnMButtonUp(int xPos, int yPos);
virtual void OnMouseMove(int xPos, int yPos);
virtual void OnMouseWheel(int xPos, int yPos, int zDet);
protected:
VSCameraActor* m_pCameraActor;
VS1stCameraController* m_p1stCameraController;
VSSceneMap * m_pTestMap;
bool m_bLMouseDowning;
int m_iDetMouseX;
int m_iDetMouseY;
int m_iLastMouseX;
int m_iLastMouseY;
bool m_bWireSwith;
VSRasterizerStatePtr m_pWireFrameStateEnable;
};
IMPLEMENT_APPLICATION(VSDemoWindowsApplication);
VSDemoWindowsApplication::VSDemoWindowsApplication()
{
m_bWireSwith = true;
}
VSDemoWindowsApplication::~VSDemoWindowsApplication()
{
}
bool VSDemoWindowsApplication::PreInitial()
{
VSWindowApplication::PreInitial();
m_uiInputAPIType = VSEngineInput::IAT_WINDOWS;
//m_uiInputAPIType = VSEngineInput::IAT_DX;
VSResourceManager::ms_bUpdateThread = false;
VSResourceManager::ms_bRenderThread = false;
m_bLMouseDowning = false;
m_iDetMouseX = 0;
m_iDetMouseY = 0;
m_iLastMouseX = 0;
m_iLastMouseY = 0;
m_pWireFrameStateEnable = NULL;
VSEngineFlag::EnableCLODMesh = false;
return true;
}
bool VSDemoWindowsApplication::OnInitial()
{
VSWindowApplication::OnInitial();
m_p1stCameraController = VSObject::GetInstance<VS1stCameraController>();
m_pCameraActor = (VSCameraActor *)VSWorld::ms_pWorld->CreateActor<VSCameraActor>();
m_pCameraActor->GetTypeNode()->AddController(m_p1stCameraController);
VSVector3 CameraPos(0.0f, 300.0f, 0.0f);
VSVector3 CameraDir(0.0f, 0.0f, 1.0f);
m_pCameraActor->GetTypeNode()->CreateFromLookDir(CameraPos, CameraDir);
m_pCameraActor->GetTypeNode()->SetPerspectiveFov(AngleToRadian(90.0f), (m_uiScreenWidth * 1.0f) / (m_uiScreenHeight), 1.0f, 80000.0f);
m_pTestMap = VSWorld::ms_pWorld->CreateScene(_T("Test"));
VSWorld::ms_pWorld->CreateActor(_T("NewMonsterLOD0.STMODEL"), VSVector3(0, 0, 500), VSMatrix3X3::ms_Identity, VSVector3::ms_One, m_pTestMap);
VSCLodTerrainActor * pTerrainActor = (VSCLodTerrainActor *)VSWorld::ms_pWorld->CreateActor<VSCLodTerrainActor>(VSVector3(-1300.0f, -2000.0f, -1300.0f), VSMatrix3X3::ms_Identity, VSVector3::ms_One, m_pTestMap);
pTerrainActor->GetTypeNode()->SetTerrainNodeType(VSCLodTerrainNode::TNT_QUAD);
pTerrainActor->GetTypeNode()->SetCLODScale(3.0f);
pTerrainActor->GetTypeNode()->CreateTarrainFromHeightMap(_T("heightdate.raw"),6,10.0f);
VSSkyLightActor * pSkyLightActor = (VSSkyLightActor *)VSWorld::ms_pWorld->CreateActor<VSSkyLightActor>(VSVector3::ms_Zero, VSMatrix3X3::ms_Identity, VSVector3::ms_One, m_pTestMap);
pSkyLightActor->GetTypeNode()->m_DownColor = VSColorRGBA(1.0f, 1.0f, 1.0f, 1.0f);
pSkyLightActor->GetTypeNode()->m_UpColor = VSColorRGBA(1.0f, 0.0f, 0.0f, 1.0f);
m_pTestMap->GetScene()->Build();
VSArray<VSString> SceneMap;
SceneMap.AddElement(_T("Main"));
SceneMap.AddElement(_T("Test"));
VSWorld::ms_pWorld->AttachWindowViewFamilyToCamera(m_pCameraActor, VSWindowViewFamily::VT_WINDOW_NORMAL,
_T("WindowUse"), SceneMap, VSForwordEffectSceneRenderMethod::ms_Type.GetName().GetBuffer());
VSRasterizerDesc WireLessDesc;
WireLessDesc.m_bWireEnable = true;
m_pWireFrameStateEnable = VSResourceManager::CreateRasterizerState(WireLessDesc);
VSViewFamily * pViewFamily = VSSceneManager::ms_pSceneManager->GetViewFamily(_T("WindowUse"));
VSSceneRenderMethod * pRM = pViewFamily->m_pSceneRenderMethod;
if (m_bWireSwith)
{
VSRenderState RenderState;
RenderState.SetRasterizerState(m_pWireFrameStateEnable);
pRM->SetUseState(RenderState, VSRenderState::IF_WIRE_ENABLE);
}
else
{
pRM->ClearUseState();
}
return true;
}
bool VSDemoWindowsApplication::OnTerminal()
{
VSWindowApplication::OnTerminal();
m_pWireFrameStateEnable = NULL;
return true;
}
bool VSDemoWindowsApplication::PostUpdate()
{
VSWindowApplication::PostUpdate();
if (m_bLMouseDowning)
{
m_p1stCameraController->m_RotXDelta = ((m_iDetMouseY)* 1.0f) * 0.001f/*VSTimer::ms_pTimer->GetDetTime() * 0.5f*/;
m_p1stCameraController->m_RotYDelta = ((m_iDetMouseX)* 1.0f) * 0.001f/*VSTimer::ms_pTimer->GetDetTime() * 0.5f*/;
m_iDetMouseX = 0;
m_iDetMouseY = 0;
}
else
{
m_p1stCameraController->m_RotXDelta = 0.0f;
m_p1stCameraController->m_RotYDelta = 0.0f;
}
return true;
}
bool VSDemoWindowsApplication::PreUpdate()
{
VSWindowApplication::PreUpdate();
return true;
}
bool VSDemoWindowsApplication::OnDraw()
{
VSWindowApplication::OnDraw();
return true;
}
void VSDemoWindowsApplication::OnMove(int xPos, int yPos)
{
}
void VSDemoWindowsApplication::OnReSize(int iWidth, int iHeight)
{
}
void VSDemoWindowsApplication::OnKeyDown(unsigned int uiKey)
{
VSApplication::OnKeyDown(uiKey);
if (uiKey == VSEngineInput::BK_UP)
{
m_p1stCameraController->m_MoveZDelta = 1.0f;
}
else if (uiKey == VSEngineInput::BK_DOWN)
{
m_p1stCameraController->m_MoveZDelta = -1.0f;
}
else if (uiKey == VSEngineInput::BK_LEFT)
{
m_p1stCameraController->m_MoveXDelta = -1.0f;
}
else if (uiKey == VSEngineInput::BK_RIGHT)
{
m_p1stCameraController->m_MoveXDelta = 1.0f;
}
else if (uiKey == VSEngineInput::BK_W)
{
m_bWireSwith = !m_bWireSwith;
VSViewFamily * pViewFamily = VSSceneManager::ms_pSceneManager->GetViewFamily(_T("WindowUse"));
VSSceneRenderMethod * pRM = pViewFamily->m_pSceneRenderMethod;
if (m_bWireSwith)
{
VSRenderState RenderState;
RenderState.SetRasterizerState(m_pWireFrameStateEnable);
pRM->SetUseState(RenderState, VSRenderState::IF_WIRE_ENABLE);
}
else
{
pRM->ClearUseState();
}
}
}
void VSDemoWindowsApplication::OnKeyUp(unsigned int uiKey)
{
VSApplication::OnKeyUp(uiKey);
if (uiKey == VSEngineInput::BK_UP)
{
m_p1stCameraController->m_MoveZDelta = 0.0f;
}
else if (uiKey == VSEngineInput::BK_DOWN)
{
m_p1stCameraController->m_MoveZDelta = 0.0f;
}
else if (uiKey == VSEngineInput::BK_LEFT)
{
m_p1stCameraController->m_MoveXDelta = 0.0f;
}
else if (uiKey == VSEngineInput::BK_RIGHT)
{
m_p1stCameraController->m_MoveXDelta = 0.0f;
}
}
void VSDemoWindowsApplication::OnLButtonDown(int xPos, int yPos)
{
VSWindowApplication::OnLButtonDown(xPos, yPos);
m_bLMouseDowning = true;
m_iLastMouseX = xPos;
m_iLastMouseY = yPos;
m_iDetMouseX = 0;
m_iDetMouseY = 0;
}
void VSDemoWindowsApplication::OnLButtonUp(int xPos, int yPos)
{
VSWindowApplication::OnLButtonUp(xPos, yPos);
m_bLMouseDowning = false;
}
void VSDemoWindowsApplication::OnRButtonDown(int xPos, int yPos)
{
VSWindowApplication::OnRButtonDown(xPos, yPos);
}
void VSDemoWindowsApplication::OnRButtonUp(int xPos, int yPos)
{
VSWindowApplication::OnRButtonUp(xPos, yPos);
}
void VSDemoWindowsApplication::OnMButtonDown(int xPos, int yPos)
{
VSWindowApplication::OnMButtonDown(xPos, yPos);
}
void VSDemoWindowsApplication::OnMButtonUp(int xPos, int yPos)
{
VSWindowApplication::OnMButtonUp(xPos, yPos);
}
void VSDemoWindowsApplication::OnMouseMove(int xPos, int yPos)
{
VSWindowApplication::OnMouseMove(xPos, yPos);
if (m_bLMouseDowning)
{
m_iDetMouseX = xPos - m_iLastMouseX;
m_iDetMouseY = yPos - m_iLastMouseY;
m_iLastMouseX = xPos;
m_iLastMouseY = yPos;
}
}
void VSDemoWindowsApplication::OnMouseWheel(int xPos, int yPos, int zDet)
{
VSWindowApplication::OnMouseWheel(xPos, yPos, zDet);
}
| [
"azhecheng@tencent.com"
] | azhecheng@tencent.com |
854cae12b3a95b08d379be4fc01d1510ce650ef2 | 5465db204e2169cae700f6873d49109fbf32b100 | /Parser.h | 9b1fc0d37102606876dbe5450b6d294e474bf1b6 | [] | no_license | reeWorlds/ResolutionMethod | 8bb4157261427ac548e503c8b55295879be50784 | d6dfafbe281b76bde548790dced5c99786ed27c6 | refs/heads/master | 2020-11-24T15:49:28.041120 | 2019-12-15T17:52:31 | 2019-12-15T17:52:31 | 228,226,432 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 625 | h | #pragma once
#include <string>
#include <vector>
#include "Formula.h"
#include "Variable.h"
#include "Negation.h"
#include "Conjunction.h"
#include "Disjunction.h"
class Parser
{
static int isPredicateSymbol(char value);
static int isSpecialSymbol(char value);
static int isCorrect0_1_2Formula(std::string);
static int getFormulaIndex(std::string& formula, int start);
static std::string intToString(int number);
static Formula* parseFormula(std::string formula);
public:
static std::vector<Formula*> parseInput(std::string input);
static int isCorrectFormula(std::string formula);
}; | [
"noreply@github.com"
] | noreply@github.com |
b9846b4470a2099a6af343fa196b55e10020ab1d | afe2f9f53a1e2bc0a48cd965dcddc3341c9e5c56 | /Sources/CZ3/math/lp/lp_api.h | 2a4e5058d4f60de01cb3ce0a482af0b55d5b346b | [
"MIT"
] | permissive | LuizZak/swift-z3 | 2b9e039148c44bf76c38f1468c96c3930dc7ed2c | 5c5d85e2d9e6b727486d872fbd8e6fa8eceeaf72 | refs/heads/master | 2023-05-25T06:24:41.617541 | 2023-05-16T12:41:37 | 2023-05-16T12:41:37 | 238,067,756 | 8 | 4 | MIT | 2023-05-12T17:46:57 | 2020-02-03T21:41:37 | C++ | UTF-8 | C++ | false | false | 4,373 | h | /*++
Copyright (c) 2017 Microsoft Corporation
Author:
Lev Nachmanson (levnach)
Nikolaj Bjorner (nbjorner)
--*/
#pragma once
#include "util/inf_rational.h"
#include "util/optional.h"
namespace lp_api {
typedef int bool_var;
typedef int theory_var;
enum bound_kind { lower_t, upper_t };
inline std::ostream& operator<<(std::ostream& out, bound_kind const& k) {
switch (k) {
case lower_t: return out << "<=";
case upper_t: return out << ">=";
}
return out;
}
template<typename Literal>
class bound {
Literal m_bv;
theory_var m_var;
lp::lpvar m_vi;
bool m_is_int;
rational m_value;
bound_kind m_bound_kind;
lp::constraint_index m_constraints[2];
public:
bound(Literal bv, theory_var v, lp::lpvar vi, bool is_int, rational const& val, bound_kind k, lp::constraint_index ct, lp::constraint_index cf) :
m_bv(bv),
m_var(v),
m_vi(vi),
m_is_int(is_int),
m_value(val),
m_bound_kind(k) {
m_constraints[0] = cf;
m_constraints[1] = ct;
}
virtual ~bound() = default;
theory_var get_var() const { return m_var; }
lp::tv tv() const { return lp::tv::raw(m_vi); }
Literal get_lit() const { return m_bv; }
bound_kind get_bound_kind() const { return m_bound_kind; }
bool is_int() const { return m_is_int; }
rational const& get_value() const { return m_value; }
lp::constraint_index get_constraint(bool b) const { return m_constraints[b]; }
inf_rational get_value(bool is_true) const {
if (is_true != get_lit().sign())
return inf_rational(m_value); // v >= value or v <= value
if (m_is_int) {
SASSERT(m_value.is_int());
rational const& offset = (m_bound_kind == lower_t) ? rational::minus_one() : rational::one();
return inf_rational(m_value + offset); // v <= value - 1 or v >= value + 1
}
else {
return inf_rational(m_value, m_bound_kind != lower_t); // v <= value - epsilon or v >= value + epsilon
}
}
virtual std::ostream& display(std::ostream& out) const {
return out << m_value << " " << get_bound_kind() << " v" << get_var();
}
};
template<typename Literal>
inline std::ostream& operator<<(std::ostream& out, bound<Literal> const& b) {
return b.display(out);
}
typedef optional<inf_rational> opt_inf_rational;
struct stats {
unsigned m_assert_lower;
unsigned m_assert_upper;
unsigned m_bounds_propagations;
unsigned m_num_iterations;
unsigned m_num_iterations_with_no_progress;
unsigned m_need_to_solve_inf;
unsigned m_fixed_eqs;
unsigned m_conflicts;
unsigned m_bound_propagations1;
unsigned m_bound_propagations2;
unsigned m_assert_diseq;
unsigned m_assert_eq;
unsigned m_gomory_cuts;
unsigned m_assume_eqs;
unsigned m_branch;
stats() { reset(); }
void reset() {
memset(this, 0, sizeof(*this));
}
void collect_statistics(statistics& st) const {
st.update("arith-lower", m_assert_lower);
st.update("arith-upper", m_assert_upper);
st.update("arith-propagations", m_bounds_propagations);
st.update("arith-iterations", m_num_iterations);
st.update("arith-pivots", m_need_to_solve_inf);
st.update("arith-plateau-iterations", m_num_iterations_with_no_progress);
st.update("arith-fixed-eqs", m_fixed_eqs);
st.update("arith-conflicts", m_conflicts);
st.update("arith-bound-propagations-lp", m_bound_propagations1);
st.update("arith-bound-propagations-cheap", m_bound_propagations2);
st.update("arith-diseq", m_assert_diseq);
st.update("arith-eq", m_assert_eq);
st.update("arith-gomory-cuts", m_gomory_cuts);
st.update("arith-assume-eqs", m_assume_eqs);
st.update("arith-branch", m_branch);
}
};
}
| [
"luizinho_mack@yahoo.com.br"
] | luizinho_mack@yahoo.com.br |
5d4f166af270a57dc7feb1cbd7f35374ed5ef5f1 | 928a5ef4bffbedd6eb039442a776b398fb69d43e | /sim_bp.cc | 049a37ae7f29ab90948b98539057c06031880a87 | [] | no_license | Shreyas097/Branch-Prediction-Simulator | 42cf7a25ffb0717028a3df4b4e21eb2ae5e91455 | 366d9063a58dcdd82aab86896f07ee6110c990e8 | refs/heads/master | 2020-04-07T06:18:21.200431 | 2018-11-18T21:52:28 | 2018-11-18T21:52:28 | 158,129,907 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,804 | cc | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "sim_bp.h"
/* argc holds the number of command line arguments
argv[] holds the commands themselves
Example:-
sim bimodal 6 gcc_trace.txt
argc = 4
argv[0] = "sim"
argv[1] = "bimodal"
argv[2] = "6"
... and so on
*/
int main (int argc, char* argv[])
{
FILE *FP; // File handler
char *trace_file; // Variable that holds trace file name;
bp_params params; // look at sim_bp.h header file for the the definition of struct bp_params
char outcome; // Variable holds branch outcome
unsigned long int addr; // Variable holds the address read from input file
if (!(argc == 4 || argc == 5 || argc == 7))
{
printf("Error: Wrong number of inputs:%d\n", argc-1);
exit(EXIT_FAILURE);
}
params.bp_name = argv[1];
// strtoul() converts char* to unsigned long. It is included in <stdlib.h>
if(strcmp(params.bp_name, "bimodal") == 0) // Bimodal
{
if(argc != 4)
{
printf("Error: %s wrong number of inputs:%d\n", params.bp_name, argc-1);
exit(EXIT_FAILURE);
}
params.M2 = strtoul(argv[2], NULL, 10);
trace_file = argv[3];
printf("COMMAND\n%s %s %lu %s\n", argv[0], params.bp_name, params.M2, trace_file);
bp_type = bimodal;
M2 = params.M2;
b_table_size = pow(2,params.M2);
b_table = (int *)malloc((b_table_size)*sizeof(int));
for(int i = 0; i<b_table_size; i++)
{
b_table[i] = 2;
}
}
else if(strcmp(params.bp_name, "gshare") == 0) // Gshare
{
if(argc != 5)
{
printf("Error: %s wrong number of inputs:%d\n", params.bp_name, argc-1);
exit(EXIT_FAILURE);
}
params.M1 = strtoul(argv[2], NULL, 10);
params.N = strtoul(argv[3], NULL, 10);
trace_file = argv[4];
printf("COMMAND\n%s %s %lu %lu %s\n", argv[0], params.bp_name, params.M1, params.N, trace_file);
bp_type = gshare;
M1 = params.M1;
N = params.N;
g_table_size = pow(2,params.M1);
g_table = (int *)malloc((g_table_size)*sizeof(int));
for(int i = 0; i<g_table_size; i++)
{
g_table[i] = 2;
}
bhr = 0;
}
else if(strcmp(params.bp_name, "hybrid") == 0) // Hybrid
{
if(argc != 7)
{
printf("Error: %s wrong number of inputs:%d\n", params.bp_name, argc-1);
exit(EXIT_FAILURE);
}
params.K = strtoul(argv[2], NULL, 10);
params.M1 = strtoul(argv[3], NULL, 10);
params.N = strtoul(argv[4], NULL, 10);
params.M2 = strtoul(argv[5], NULL, 10);
trace_file = argv[6];
printf("COMMAND\n%s %s %lu %lu %lu %lu %s\n", argv[0], params.bp_name, params.K, params.M1, params.N, params.M2, trace_file);
bp_type = hybrid;
M2 = params.M2;
M1 = params.M1;
N = params.N;
K = params.K;
b_table_size = pow(2,params.M2);
b_table = (int *)malloc((b_table_size)*sizeof(int));
for(int i = 0; i<b_table_size; i++)
{
b_table[i] = 2;
}
g_table_size = pow(2,params.M1);
g_table = (int *)malloc((g_table_size)*sizeof(int));
for(int i = 0; i<g_table_size; i++)
{
g_table[i] = 2;
}
bhr = 0;
c_table_size = pow(2,params.K);
c_table = (int *)malloc((c_table_size)*sizeof(int));
for(int i = 0; i<c_table_size; i++)
{
c_table[i] = 1;
}
}
else
{
printf("Error: Wrong branch predictor name:%s\n", params.bp_name);
exit(EXIT_FAILURE);
}
// Open trace_file in read mode
FP = fopen(trace_file, "r");
if(FP == NULL)
{
// Throw error and exit if fopen() failed
printf("Error: Unable to open file %s\n", trace_file);
exit(EXIT_FAILURE);
}
char str[2];
while(fscanf(FP, "%lx %s", &addr, str) != EOF)
{
total++;
outcome = str[0];
if(outcome == 't')
original_prediction = taken;
else if(outcome == 'n')
original_prediction = not_taken;
pc_addr = addr >> 2;
sprintf(address, "%lx", pc_addr);
binary = change_to_binary(address);
if(bp_type == bimodal)
{
b_index = get_b_index(M2); //Getting index
b_predict = do_predict(b_table,b_index); // Making prediction
update_index(b_table,b_index,original_prediction,b_predict); // Updating index
}
else if(bp_type == gshare)
{
g_index = get_g_index(M1,N); //Getting index
g_predict = do_predict(g_table,g_index); // Making prediction
update_index(g_table,g_index,original_prediction,g_predict); // Updating index
bhr_place_original = (original_prediction<<(N-1));
bhr = (bhr_place_original)|(bhr>>1); // Updating BHR
}
else if(bp_type == hybrid)
{
// Getting chooser table index
c_index = get_c_index(K);
// Getting Bimodal table index
b_index = get_b_index(M2);
b_predict = do_predict(b_table,b_index);
// Getting Gshare table index
g_index = get_g_index(M1,N);
g_predict = do_predict(g_table,g_index);
if(c_table[c_index]>=2)
update_index(g_table,g_index,original_prediction,g_predict);
else
update_index(b_table,b_index,original_prediction,b_predict);
if((original_prediction==g_predict)&&(original_prediction!=b_predict))
{
if(c_table[c_index]<3)
c_table[c_index]++;
}
else if((original_prediction!=g_predict)&&(original_prediction==b_predict))
{
if(c_table[c_index]>0)
c_table[c_index]--;
}
bhr_place_original = (original_prediction<<(N-1));
bhr = (bhr_place_original)|(bhr>>1); // Updating BHR
}
}
float tot,mp;
char percent_symbol = '%';
tot = total;
mp = mis_predict;
printf("OUTPUT");
printf("\n number of predictions: %d", total);
printf("\n number of mispredictions: %d", mis_predict);
printf("\n misprediction rate: %.2f", mp/tot*100);
printf("%c",percent_symbol);
if(bp_type == bimodal)
{
printf("\nFINAL BIMODAL CONTENTS");
for(int i = 0; i<b_table_size; i++)
printf("\n %d\t%d", i, b_table[i]);
printf("\n");
}
else if(bp_type == gshare)
{
printf("\nFINAL GSHARE CONTENTS");
for(int i = 0; i<g_table_size; i++)
printf("\n %d\t%d", i, g_table[i]);
printf("\n");
}
else if(bp_type == hybrid)
{
printf("\nFINAL CHOOSER CONTENTS");
for(int i = 0; i<c_table_size; i++)
printf("\n %d\t%d", i, c_table[i]);
printf("\nFINAL GSHARE CONTENTS");
for(int i = 0; i<g_table_size; i++)
printf("\n %d\t%d", i, g_table[i]);
printf("\nFINAL BIMODAL CONTENTS");
for(int i = 0; i<b_table_size; i++)
printf("\n %d\t%d", i, b_table[i]);
printf("\n");
}
return 0;
}
// Converting hex to binary
char *change_to_binary(char address[])
{
char *binary = (char *)malloc(sizeof(char) * 10000);
unsigned long int i;
for(i=0; i < strlen(address); ++i)
{
if (address[i] == '0')
strcat(binary, "0000");
else if (address[i] == '1')
strcat(binary, "0001");
else if (address[i] == '2')
strcat(binary, "0010");
else if (address[i] == '3')
strcat(binary, "0011");
else if (address[i] == '4')
strcat(binary, "0100");
else if (address[i] == '5')
strcat(binary, "0101");
else if (address[i] == '6')
strcat(binary, "0110");
else if (address[i] == '7')
strcat(binary, "0111");
else if (address[i] == '8')
strcat(binary, "1000");
else if (address[i] == '9')
strcat(binary, "1001");
else if (address[i] == 'a' || address[i] == 'A')
strcat(binary, "1010");
else if (address[i] == 'b' || address[i] == 'B')
strcat(binary, "1011");
else if (address[i] == 'c' || address[i] == 'C')
strcat(binary, "1100");
else if (address[i] == 'd' || address[i] == 'D')
strcat(binary, "1101");
else if (address[i] == 'e' || address[i] == 'E')
strcat(binary, "1110");
else if (address[i] == 'f' || address[i] == 'F')
strcat(binary, "1111");
}
return binary;
}
// Getting Bimodal index
unsigned long int get_b_index(unsigned long int M2)
{
char *index = (char *)malloc(sizeof(char) * M2);
char temp[M2];
int k = 0;
for(unsigned long int i = strlen(binary)-M2; i < strlen(binary); i++)
{
temp[k] = binary[i];
++k;
}
char temp1[M2];
int j = 0;
for(unsigned long int i = 0; i < M2; i++)
{
temp1[j] = temp[j];
++j;
}
strcat(index,temp1);
unsigned long int b_index = strtoul(index,NULL,2);
return b_index;
}
// Getting Gshare index
unsigned long int get_g_index(unsigned long int M1, unsigned long int N)
{
unsigned long int g_index;
int diff = M1-N;
int m1_bits = pow(2,M1) - 1;
int n_bits = pow(2,N) - 1;
int diff_bits = pow(2,diff) - 1;
int m1 = (pc_addr & m1_bits);
int n = (bhr & n_bits);
int m1_n = (m1 & diff_bits);
int temp1 = (m1>>diff) ^ n;
int temp2 = temp1<<diff;
g_index = temp2|m1_n;
// printf("\n Gshare Index = %lx", g_index);
return g_index;
}
// Getting Hybrid index
unsigned long int get_c_index(unsigned long int K)
{
char *index = (char *)malloc(sizeof(char) * K);
char temp[K];
int k = 0;
for(unsigned long int i = strlen(binary)-K; i < strlen(binary); i++)
{
temp[k] = binary[i];
++k;
}
strcat(index,temp);
unsigned long int c_index = strtoul(index,NULL,2);
return c_index;
}
// Perform prediction
int do_predict(int *table, unsigned long int index)
{
int prediction;
if(table[index] >= 2)
prediction = taken;
else
prediction = not_taken;
return prediction;
}
// Updating Index
void update_index(int *table, unsigned long int index, int original, int prediction)
{
if(prediction != original)
mis_predict++;
if(original == taken)
{
if(table[index] < 3)
table[index]++;
}
else if(original == not_taken)
{
if(table[index] > 0)
table[index]--;
}
} | [
"noreply@github.com"
] | noreply@github.com |
23156d73d14a38f59f41b2e4548f77f06d5d8731 | 5579f660876acca08d681a039fcfac4bb625f5d7 | /infovis/tree/xml_tree.hpp | 8c8b2ce0c538de8168c54718c73967825cf09b4d | [
"MIT"
] | permissive | jdfekete/millionvis | e278d267cb6a2bf2d29f616ea5378d528c4e4d2c | 01dab6a40ebdb3eef751b638171805665f4ee68f | refs/heads/master | 2020-05-30T07:11:59.739040 | 2016-09-24T15:30:07 | 2016-09-24T15:30:07 | 69,087,119 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,424 | hpp | /* -*- C++ -*-
*
* Copyright (C) 2016 Jean-Daniel Fekete
*
* This file is part of MillionVis.
*
* 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.
*/
#ifndef INFOVIS_TREE_XML_TREE_HPP
#define INFOVIS_TREE_XML_TREE_HPP
#include <infovis/tree/tree.hpp>
namespace infovis {
unsigned xml_tree(const std::string& filename, tree& t);
} // namespace infovis
#endif // INFOVIS_TREE_XML_TREE_HPP
| [
"Jean-Daniel.Fekete@inria.fr"
] | Jean-Daniel.Fekete@inria.fr |
1f86ddb03688fbc17ac2869a6b90d8cc40dbd791 | 924fadc4a724be2d77eaaf906af6613cad71b0a1 | /Servidor/Final/ServerTerminalRU/alunoserver.cpp | c647bf23c3d35f7decacf1e552353cdc44950b5c | [] | no_license | EEL7323/slash_n | 58fb2725d99142a7f8f2669a32297291a8738a8e | a8ac280ae4da4e6ee656d86ab1887b4b6f5d73e6 | refs/heads/master | 2021-01-20T03:02:15.136178 | 2017-07-05T15:15:05 | 2017-07-05T15:15:05 | 89,488,172 | 0 | 2 | null | 2017-07-05T15:15:06 | 2017-04-26T14:07:08 | C++ | UTF-8 | C++ | false | false | 186 | cpp | #include "alunoserver.h"
AlunoServer::AlunoServer()
{
}
void AlunoServer::setSenha(QString senha)
{
senhaApp = senha;
}
QString AlunoServer::getSenha()
{
return senhaApp;
}
| [
"robertophi@gmail.com"
] | robertophi@gmail.com |
7bc7e717c397fb157218b376aea79ae89707ce28 | df818e3f9b73ee4477718856e5bd1fd99f2e4a9b | /ws/snake/IXSnakeProtocol.cpp | 138612e38db0d61d0fe5bc129207d11155a4f973 | [
"BSD-3-Clause"
] | permissive | tiwariashish86/IXWebSocket | 66fdcdd298603f80b7b1bde6005232eff8275fad | 761b6b70bd8004817293c80897d61dbb9ac01040 | refs/heads/master | 2020-05-21T02:19:47.490980 | 2019-05-09T22:05:01 | 2019-05-09T22:05:01 | 185,875,746 | 2 | 0 | BSD-3-Clause | 2019-05-09T21:43:42 | 2019-05-09T21:43:41 | null | UTF-8 | C++ | false | false | 9,034 | cpp | /*
* IXSnakeProtocol.cpp
* Author: Benjamin Sergeant
* Copyright (c) 2019 Machine Zone, Inc. All rights reserved.
*/
#include "IXSnakeProtocol.h"
#include <ixwebsocket/IXWebSocket.h>
#include <ixcrypto/IXHMac.h>
#include "IXSnakeConnectionState.h"
#include "IXAppConfig.h"
#include "nlohmann/json.hpp"
#include <sstream>
namespace snake
{
void handleError(
const std::string& action,
std::shared_ptr<ix::WebSocket> ws,
nlohmann::json pdu,
const std::string& errMsg)
{
std::string actionError(action);
actionError += "/error";
nlohmann::json response = {
{"action", actionError},
{"id", pdu.value("id", 1)},
{"body", {
{"reason", errMsg}
}}
};
ws->sendText(response.dump());
}
void handleHandshake(
std::shared_ptr<SnakeConnectionState> state,
std::shared_ptr<ix::WebSocket> ws,
const nlohmann::json& pdu)
{
std::string role = pdu["body"]["data"]["role"];
state->setNonce(generateNonce());
state->setRole(role);
nlohmann::json response = {
{"action", "auth/handshake/ok"},
{"id", pdu.value("id", 1)},
{"body", {
{"data", {
{"nonce", state->getNonce()},
{"connection_id", state->getId()}
}},
}}
};
auto serializedResponse = response.dump();
std::cout << "response = " << serializedResponse << std::endl;
ws->sendText(serializedResponse);
}
void handleAuth(
std::shared_ptr<SnakeConnectionState> state,
std::shared_ptr<ix::WebSocket> ws,
const AppConfig& appConfig,
const nlohmann::json& pdu)
{
auto secret = getRoleSecret(appConfig, state->appkey(), state->role());
std::cout << "secret = " << secret << std::endl;
if (secret.empty())
{
nlohmann::json response = {
{"action", "auth/authenticate/error"},
{"id", pdu.value("id", 1)},
{"body", {
{"error", "authentication_failed"},
{"reason", "invalid secret"}
}}
};
ws->sendText(response.dump());
return;
}
auto nonce = state->getNonce();
auto serverHash = ix::hmac(nonce, secret);
std::string clientHash = pdu["body"]["credentials"]["hash"];
if (appConfig.verbose)
{
std::cout << serverHash << std::endl;
std::cout << clientHash << std::endl;
}
if (serverHash != clientHash)
{
nlohmann::json response = {
{"action", "auth/authenticate/error"},
{"id", pdu.value("id", 1)},
{"body", {
{"error", "authentication_failed"},
{"reason", "invalid hash"}
}}
};
ws->sendText(response.dump());
return;
}
nlohmann::json response = {
{"action", "auth/authenticate/ok"},
{"id", pdu.value("id", 1)},
{"body", {}}
};
ws->sendText(response.dump());
}
void handlePublish(
std::shared_ptr<SnakeConnectionState> state,
std::shared_ptr<ix::WebSocket> ws,
const nlohmann::json& pdu)
{
std::vector<std::string> channels;
auto body = pdu["body"];
if (body.find("channels") != body.end())
{
for (auto&& channel : body["channels"])
{
channels.push_back(channel);
}
}
else if (body.find("channel") != body.end())
{
channels.push_back(body["channel"]);
}
else
{
std::stringstream ss;
ss << "Missing channels or channel field in publish data";
handleError("rtm/publish", ws, pdu, ss.str());
return;
}
for (auto&& channel : channels)
{
std::stringstream ss;
ss << state->appkey()
<< "::"
<< channel;
std::string errMsg;
if (!state->redisClient().publish(ss.str(), pdu.dump(), errMsg))
{
std::stringstream ss;
ss << "Cannot publish to redis host " << errMsg;
handleError("rtm/publish", ws, pdu, ss.str());
return;
}
}
}
//
// FIXME: this is not cancellable. We should be able to cancel the redis subscription
//
void handleRedisSubscription(
std::shared_ptr<SnakeConnectionState> state,
std::shared_ptr<ix::WebSocket> ws,
const AppConfig& appConfig,
const nlohmann::json& pdu)
{
std::string channel = pdu["body"]["channel"];
std::string subscriptionId = channel;
std::stringstream ss;
ss << state->appkey()
<< "::"
<< channel;
std::string appChannel(ss.str());
ix::RedisClient redisClient;
int port = appConfig.redisPort;
auto urls = appConfig.redisHosts;
std::string hostname(urls[0]);
// Connect to redis first
if (!redisClient.connect(hostname, port))
{
std::stringstream ss;
ss << "Cannot connect to redis host " << hostname << ":" << port;
handleError("rtm/subscribe", ws, pdu, ss.str());
return;
}
std::cout << "Connected to redis host " << hostname << ":" << port << std::endl;
// Now authenticate, if needed
if (!appConfig.redisPassword.empty())
{
std::string authResponse;
if (!redisClient.auth(appConfig.redisPassword, authResponse))
{
std::stringstream ss;
ss << "Cannot authenticated to redis";
handleError("rtm/subscribe", ws, pdu, ss.str());
return;
}
std::cout << "Auth response: " << authResponse << ":" << port << std::endl;
}
int id = 0;
auto callback = [ws, &id, &subscriptionId](const std::string& messageStr)
{
auto msg = nlohmann::json::parse(messageStr);
nlohmann::json response = {
{"action", "rtm/subscription/data"},
{"id", id++},
{"body", {
{"subscription_id", subscriptionId},
{"messages", {{msg}}}
}}
};
ws->sendText(response.dump());
};
auto responseCallback = [ws, pdu, &subscriptionId](const std::string& redisResponse)
{
std::cout << "Redis subscribe response: " << redisResponse << std::endl;
// Success
nlohmann::json response = {
{"action", "rtm/subscribe/ok"},
{"id", pdu.value("id", 1)},
{"body", {
{"subscription_id", subscriptionId}
}}
};
ws->sendText(response.dump());
};
std::cerr << "Subscribing to " << appChannel << "..." << std::endl;
if (!redisClient.subscribe(appChannel, responseCallback, callback))
{
std::stringstream ss;
ss << "Error subscribing to channel " << appChannel;
handleError("rtm/subscribe", ws, pdu, ss.str());
return;
}
}
void handleSubscribe(
std::shared_ptr<SnakeConnectionState> state,
std::shared_ptr<ix::WebSocket> ws,
const AppConfig& appConfig,
const nlohmann::json& pdu)
{
state->fut = std::async(std::launch::async,
handleRedisSubscription,
state,
ws,
appConfig,
pdu);
}
void processCobraMessage(
std::shared_ptr<SnakeConnectionState> state,
std::shared_ptr<ix::WebSocket> ws,
const AppConfig& appConfig,
const std::string& str)
{
auto pdu = nlohmann::json::parse(str);
std::cout << "Got " << str << std::endl;
auto action = pdu["action"];
std::cout << "action = " << action << std::endl;
if (action == "auth/handshake")
{
handleHandshake(state, ws, pdu);
}
else if (action == "auth/authenticate")
{
handleAuth(state, ws, appConfig, pdu);
}
else if (action == "rtm/publish")
{
handlePublish(state, ws, pdu);
}
else if (action == "rtm/subscribe")
{
handleSubscribe(state, ws, appConfig, pdu);
}
else
{
std::cerr << "Unhandled action: " << action << std::endl;
}
}
}
| [
"bsergean@gmail.com"
] | bsergean@gmail.com |
f72ee2847b5e068f55f34b6dc6cdf88b88134da8 | 48298469e7d828ab1aa54a419701c23afeeadce1 | /Client/Client/WXCore/Core/WXXMLParser.cpp | 64867b0bff49d84472ba8fdeb13162856fd99965 | [] | no_license | brock7/TianLong | c39fccb3fd2aa0ad42c9c4183d67a843ab2ce9c2 | 8142f9ccb118e76a5cd0a8b168bcf25e58e0be8b | refs/heads/master | 2021-01-10T14:19:19.850859 | 2016-02-20T13:58:55 | 2016-02-20T13:58:55 | 52,155,393 | 5 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 206 | cpp | #include "WXXMLParser.h"
namespace WX
{
XMLParser::XMLParser(void)
{
}
//-----------------------------------------------------------------------
XMLParser::~XMLParser()
{
}
}
| [
"xiaowave@gmail.com"
] | xiaowave@gmail.com |
431cc59a1614e818fdd5e37749538d5bddcd7fc6 | 7ce2a1d5ee504a670186cd408afd03c7a7ab3632 | /ReactorFramework/src/SockConnector.h | 04a74f17b7cb13eb9027e41ebadfdc9de9a2ecbb | [] | no_license | lcstar726/WebServer | 8e594f5705a56e29daf24f45d63e5798376bedf2 | b57f8c4eb32c6a7dd86bd13e358865bd89e82ba6 | refs/heads/master | 2020-03-09T23:41:15.537861 | 2018-04-11T09:02:52 | 2018-04-11T09:02:52 | 129,063,755 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,858 | h | #ifndef __SOCK_CONNECTOR_H__
#define __SOCK_CONNECTOR_H__
#include "InetAddress.h"
#include "SockStream.h"
class SockConnector
{
public:
SockConnector( void );
SockConnector( SockStream &soStreamNew
, const BaseAddress &addrRemote
, const TimeValue *timeout = NULL
, const BaseAddress &addrLocal = BaseAddress::addrAny
, bool bReuseAddr = false
, int iFlags = 0
, int iPerms = 0
, int iProtocol = 0 );
~SockConnector( void );
int Connect( SockStream &soStreamNew
, const BaseAddress &addrRemote
, const TimeValue *timeout = NULL
, const BaseAddress &addrLocal = BaseAddress::addrAny
, bool bReuseAddr = false
, int iFlags = 0
, int iPerms = 0
, int iProtocol = 0 );
typedef InetAddress PeerAddress;
typedef SockStream PeerStream;
protected:
int HandleTimedConnect( HANDLE handle, const TimeValue *timeout, bool bIsTLI = false );
int Complete( SockStream &soStreamNew
, BaseAddress *addrRemote = NULL
, const TimeValue *timeout = NULL );
int SharedOpen( SockStream &soStreamNew
, int iProtocolFamily
, int iProtocol
, bool bReuseAddr );
int SharedConnectStart( SockStream &soStreamNew
, const TimeValue *timeout
, const BaseAddress &addrLocal );
int SharedConnectFinish( SockStream &soStreamNew
, const TimeValue *timeout
, int iResult );
};
inline SockConnector::SockConnector( void ) {}
inline SockConnector::~SockConnector( void ) {}
#endif
| [
"noreply@github.com"
] | noreply@github.com |
e630a1d7045be5593265cbcde6ebb37815a1e99f | b1a2bacb8f275e2ccaa5c53b311ee24e6bb520aa | /p908_smallest_range_1.cpp | 9aa8b58293b53ed877aa43723c1484514b15b849 | [] | no_license | angtylook/happycpp | 0eb8a8bf0f190369dafd0190e144da7b633bc7ef | c24d6b7991a62f95354bf750bdc9cb55c4657f2b | refs/heads/master | 2021-11-17T20:49:46.100409 | 2021-08-15T09:00:41 | 2021-08-15T09:00:41 | 139,601,988 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 825 | cpp | #include <iostream>
#include <vector>
class Solution {
public:
int smallestRangeI(std::vector<int>& A, int K) {
int smallest = A.front();
int biggest = A.front();
for (auto a : A) {
if (smallest > a) {
smallest = a;
}
if (biggest < a) {
biggest = a;
}
}
smallest += K;
biggest -= K;
if (biggest > smallest) {
return biggest - smallest;
}
return 0;
}
};
int main() {
Solution sol;
std::vector t1{1};
std::vector t2{0, 10};
std::vector t3{1, 3, 6};
std::cout << sol.smallestRangeI(t1, 0) << std::endl;
std::cout << sol.smallestRangeI(t2, 2) << std::endl;
std::cout << sol.smallestRangeI(t3, 3) << std::endl;
return 0;
}
| [
"lookto2008@gmail.com"
] | lookto2008@gmail.com |
afa0ba2d298aec276aa69cbec7762c35f657b3e9 | 02a015427a02881ec725670d4fb9ef7cfd48e2a7 | /Project 1 - Platformer game engine/Source/2DPlatformer/2DPlatformer/MapController.h | 2a45d5ec5ed856fd88cb9813c242c55060881856 | [] | no_license | njustesen/game-engines-itu | fd997cd552722f0aa08f52462525623cc1c786da | ee7b99dae5ca7b25081f1ba3c853707076b6f921 | refs/heads/master | 2021-01-24T11:22:53.801500 | 2016-10-07T07:39:52 | 2016-10-07T07:39:52 | 70,225,047 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 715 | h | #include "GameObject.h"
#include "SDL.h"
#include "Level.h"
#include <string>
#include "SDL_image.h"
#include <vector>
using namespace std;
#pragma once
class MapController
{
private:
Level * level;
Sprite *background;
SDL_Surface* tileset[100];
int intFromString(string s);
int charX;
int charY;
vector<GameObject*> * monsters;
void loadTileset();
public:
int getCharX();
int getCharY();
vector<GameObject*> * getMonsters();
Level *getLevel();
SDL_Surface *getTileImage(int tile);
SDL_Surface *loadTileImage(int tile);
Sprite *getBackground();
void loadLevel(string levelName);
MapController(void);
MapController(string levelName);
~MapController(void);
};
| [
"noju@Nielss-MacBook-Pro.local"
] | noju@Nielss-MacBook-Pro.local |
35a8be27702a59abe340d22424d9af20701171e5 | 61ea765b944c245840a3544d60663b045ec571e0 | /dataTypes.cpp | 578420d4ff417158a965a80128d364bc7f3db12d | [] | no_license | mcdylanb/hackerRankSB | e574909a9f8385f5bac0e19d31d054ca3d970d0c | dea3ec4c3e647f57517061f20d1a37787f968aef | refs/heads/master | 2022-11-22T05:02:19.088365 | 2020-07-23T13:35:50 | 2020-07-23T13:35:50 | 281,425,557 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 867 | cpp | /*
* =====================================================================================
*
* Filename: dataTypes.cpp
*
* Description: Basic Data Types sandbox
*
* Version: 1.0
* Created: 07/19/2020 10:08:41 AM
* Revision: none
* Compiler: gcc
*
* Author: Dylan Balagtas,
* Organization:
*
* =====================================================================================
*/
#include <stdlib.h>
#include <iostream>
#include <cstdio>
using namespace std;
int main() {
// Complete the code.
int number;
long longNumber;
char varChar;
float varFloat;
double varDouble;
scanf("%d %ld %c %f %lf", &number, &longNumber, &varChar, &varFloat, &varDouble);
printf("%d \n%ld \n%c \n%0.3f \n%0.9lf\n", number, longNumber, varChar, varFloat, varDouble);
return 0;
}
| [
"dylansatgalab@gmail.com"
] | dylansatgalab@gmail.com |
5b11965fdff8d234beefcc6f9ecd1497d38d29fe | d6a1186bd313d81593514c4f544f4774593c3fed | /arrays/multi_arrays.cpp | f79c9c6b59408d9da717082321de1585a44ef3e3 | [] | no_license | jadenpadua/cpp | 6cb834f7a0e085593612e02477c969ef132b6a66 | a5f71c03e00bd165865b62490fc4e7b8935ec99e | refs/heads/master | 2023-02-09T13:39:59.485311 | 2021-01-03T06:57:39 | 2021-01-03T06:57:39 | 326,347,435 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 413 | cpp | #include <iostream>
using namespace std;
int main() {
string animals[2][3] = {
{"fox", "dog", "cat"},
{"mouse", "squirell", "parrot"}
};
for(int i = 0; i < sizeof(animals)/ sizeof(animals[0]); i++) {
for(int j = 0; j < sizeof(animals[0]) / sizeof(string); j++) {
cout << animals[i][j] << " " << flush;
}
cout << endl;
}
return 0;
} | [
"jadenpadua@Jadens-MacBook-Pro.local"
] | jadenpadua@Jadens-MacBook-Pro.local |
7e4744cab4b22850910d93ba8328129cdde995fc | 4bd57b8501d4326ecc06c1d1ea499935e1668d95 | /MASH-dev/SeanWu/uganda-ibm/pf-pdg/PDG.cpp | fea4113a07cfdd6d990860ada6cfd2acf5fe01f7 | [] | no_license | aucarter/MASH-Main | 0a97eac24df1f7e6c4e01ceb4778088b2f00c194 | d4ea6e89a9f00aa6327bed4762cba66298bb6027 | refs/heads/master | 2020-12-07T09:05:52.814249 | 2019-12-12T19:53:24 | 2019-12-12T19:53:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,631 | cpp | /* ################################################################################
#
# Testing PDG (simple standalone c++ conversion)
# Based on the R code in John Henry's dev folder
#
################################################################################ */
#include "PDG.h"
/* PDG requires a multivariate hypergeometric random number, which we adapt the algorithm from Agner Fog here (cite him!) */
// destination: array to fill the drawn "balls"
// source: number of "balls" in each "urn"
// n: number of draws to take
// k: number of "urns"
void rmhyper(int* destination, int const* source, int n, int k){
int sum, x, y;
size_t i;
if(n < 0 || k < 0){Rcpp::stop("Invalid parameters of distribution");}
// total number of "balls"
for(i = 0, sum = 0; i < k; i++){
y = source[i];
if(y < 0){Rcpp::stop("Cannot have a negative number of balls in an urn");}
sum += y;
}
if(n > sum){Rcpp::stop("Distribution undefined for n > sum");}
for(i=0; i<k-1; i++){
// generate ouput by calling rhyper k-1 times
y = source[i];
x = (int)R::rhyper((double)y,(double)sum-y,(double)n);
n -= x;
sum -= y;
destination[i] = x;
}
// get the last one
destination[i] = n;
};
/* ################################################################################
# PDG static members
################################################################################ */
size_t PDG_human::global_ixH = 0;
size_t PDG_human::pfAges = 27;
double PDG_human::pfdr = 0.75;
double PDG_human::gdk = std::log10(0.7);
double PDG_human::pgm = 1.184;
double PDG_human::pgb = -2.004;
double PDG_human::gm = 1.652;
double PDG_human::gb = 1.662;
std::vector<double> PDG_human::Ptmax = {0.,5.210246,4.573131,4.373306,4.218014,4.079337,4.157638,3.805582,3.821811,3.827757,3.467524,3.740757,3.349316,3.732802,3.652580,3.231724,2.567026,2.283804,2.929233,1.962211,2.944931,1.851258,2.193125,2.309303,1.564271,3.205746,2.719204,1.915100};
std::vector<double> PDG_human::Ptshape = {0.,4.639315,2.275418,2.258965,2.311616,2.474827,3.176543,2.943449,3.419812,4.387235,2.755179,5.014499,4.114957,8.849801,6.918817,4.470316,3.726024,4.332549,4.547252,1.829113,5.378781,1.581417,1.094105,1.000000,1.030259,2.641712,2.991721,5.007464};
std::vector<double> PDG_human::Ptrate = {0.,4.008275,1.539217,1.612759,1.756409,1.907544,2.034369,1.949314,2.043045,2.571400,1.800733,2.482635,2.385546,3.573325,3.135033,2.244577,2.825106,3.004125,2.390421,2.198324,2.916877,1.992531,1.051514,1.572928,1.460975,1.294750,2.077740,2.618999};
double PDG_human::pfpatency = 1. - std::exp(-0.1385);
double PDG_human::pgv = 0.2704;
// Immunity
double PDG_human::immHalf = 3.5246;
double PDG_human::immSlope = 3.038;
double PDG_human::immThresh = 0.;
double PDG_human::immP = 0.;
// Health
double PDG_human::feverHalf = 3.5246;
double PDG_human::feverSlope = 3.038;
double PDG_human::feverMax = .8835;
// Infectivity
double PDG_human::TEHalf = 2.3038;
double PDG_human::TESlope = 3.5524;
double PDG_human::TEMax = .4242;
// Diagnostics - Light Microscopy
double PDG_human::LMHalf = 2.;
double PDG_human::LMSlope = 3.;
double PDG_human::LMMax = 0.9;
double PDG_human::LMMin = 0.05;
// special functions
double PDG_human::sigmoid(const double x, const double xhalf, const double b){
return std::pow((x/xhalf),b) / (std::pow((x/xhalf),b) + 1.);
};
double PDG_human::sigmoidexp(const double x, const double xhalf, const double b){
return std::exp(x*b)/(std::exp(x*b)+std::exp(xhalf*b));
};
/* ################################################################################
# PDG constructor & destructor
################################################################################ */
// constructor & destructor
PDG_human::PDG_human(const double age_, const bool sex_) :
ixH(global_ixH),
age(age_),
sex(sex_),
Pf(pfAges,0),
Pt(NAN), Gt(NAN),
MOI(0),
Imm(0.), immCounter(0),
pFever(0.),
TE(0.)
{
global_ixH++;
};
PDG_human::~PDG_human() = default;
/* ################################################################################
# PDG infection dynamics
################################################################################ */
// infection methods
void PDG_human::begin_infection(size_t nInfections){
Pf[0] += nInfections;
MOI = std::accumulate(Pf.begin(),Pf.end(),0);
};
void PDG_human::clear_infections(){
std::fill(Pf.begin(),Pf.end(),0);
Pt = 0.;
Gt = 0.;
};
// update functions
void PDG_human::update_PDG(){
// gametocytes: depend on lagged Pf
update_Gt();
// update Pf, Pt, MOI, TE
age_infections();
update_Pt();
update_MOI();
update_TE();
update_pFever();
// update_age(dt)
};
void PDG_human::age_infections(){
// attrition of infections at final age category
if(Pf.back() > 0){
Pf.back() -= (int)R::rbinom((double)Pf.back(), pfdr);
}
// some proportion of patent infections move into subpatent phase; each independent
int nPf = std::accumulate(Pf.begin(),Pf.end(),0);
// we want to only move them into subpatency AFTER the intrinsic incubation period & first fortnight of infection
if( ((MOI - Pf.back() - Pf.front()) > 0) && (nPf > 0) ){
// number of patent cohorts to 'terminate'
int term = R::rbinom((double)MOI-Pf.back(),pfpatency);
if(term > 0){
// only do the sampling if we need to)
if(nPf > 1){
// sample the cohorts that are being removed
std::vector<int> subs(pfAges,0);
rmhyper(subs.data(),Pf.data(),term,pfAges);
// remove the newly subpatent infections
for(size_t i=0; i<pfAges; i++){
Pf[i] -= subs[i];
}
// add the subpatent infections to the oldest age group
Pf.back() += std::accumulate(subs.begin(),subs.end(),0);
// if we can we'd prefer to avoid sampling the multivariate hypergeom dist
} else {
std::fill(Pf.begin(),Pf.end(),0);
Pf.back() = 1;
}
}
}
// shift all cohorts to the next age group
for(int i=pfAges-1; i>=0; i--){
if(i == pfAges-1){
Pf[i] += Pf[i-1];
} else if(i == 0){
Pf[i] = 0;
} else {
Pf[i] = Pf[i-1];
}
}
};
// update parasite densities
void PDG_human::update_Pt(){
if(MOI > 0){
Pt = 0.;
// pull from all of the age-specific distributions, sum to get total Pt; limit tails of distn
for(size_t k=0; k<pfAges; k++){
if(Pf[k] > 0){
double sum = 0.;
for(size_t pf=0; pf<Pf[k]; pf++){
sum += std::pow(10,(Ptmax[k] - R::rgamma(Ptshape[k], 1./Ptrate[k])));
}
Pt = std::log10(std::pow(10,Pt) + sum);
}
}
// include immune effect (this is just a stub, here we just discount Pt by at most 99 percent)
Pt = std::log10((1.-.99*Imm) * std::pow(10,Pt));
} else {
Pt = NAN;
}
};
// update gametocyte densities
void PDG_human::update_Gt(){
int nPf = std::accumulate(Pf.begin(),Pf.end(),0);
if(nPf > 0){
// skip computations if Pt is NaN (if the infection just happened, no merozoites yet)
if(isnan(Pt)){
Gt = NAN;
// use power law to translate from Pt to Gt; add unbiased noise due to uncertainty in P2G fit
} else {
Gt = (pgm * Pt) + pgb;
if(((Gt*gm) + gb) > 0.){
Gt += R::rnorm(0,std::sqrt(pgv));
} else {
Gt = NAN;
}
}
} else {
Gt += gdk;
}
};
// update multiplicity of infection
void PDG_human::update_MOI(){
// add total active infections in each age category
MOI = std::accumulate(Pf.begin(),Pf.end(),0);
};
void PDG_human::update_Imm(){
// count up at random rate proportional to Pt, down by geometric if below
// be sure to ensure nonnegative-definiteness of counters
if(isnan(Pt) || Pt < immThresh){
immCounter = std::max(immCounter - 1, 0);
} else {
immCounter = std::max(immCounter + (int)R::rgeom(immP),0);
}
// sigmoidal conversion of counter to immune effect
Imm = sigmoid((double)immCounter, immHalf, immSlope);
};
// scaled sigmoid signal; Gametocytes assumed to encode TE
void PDG_human::update_TE(){
if(isnan(Gt)){
TE = 0.;
} else {
TE = TEMax * sigmoidexp(Gt, TEHalf, TESlope);
}
};
void PDG_human::update_pFever(){
if(isnan(Pt)){
pFever = 0.;
} else {
pFever = feverMax * sigmoidexp(Pt, feverHalf, feverSlope);
}
};
// void PDG_human::upate_age(const double dt);
// diagnostics
/* light microscopy */
bool PDG_human::diagnostic_LM(){
double p = 0.;
if(!isnan(Pt) && (Pt > 0.)){
p = (LMMax-LMMin) * sigmoidexp(Pt,LMHalf,LMSlope) + LMMin;
}
bool res = false;
if(R::runif(0.,1.) < p){
res = true;
}
return res;
};
| [
"slwu89@berkeley.edu"
] | slwu89@berkeley.edu |
a97402295ed91eb7d02d219eb96d91d32c8222b2 | 3c4c3f231f44e848e8e1a9ad4a1d7bd82e44750a | /StratifyAPI/code/calc-Base64/src/main.cpp | d60606a64336118d8d103312279ca6e2f65e7aef | [] | no_license | StratifyLabs/StratifyDocsCode | 5e9b4e72ff8ea1989e91a3b1fde38bd94c5edd74 | e76e210c78c865637526da63cb0072e0a7b83678 | refs/heads/master | 2020-07-26T02:18:05.028930 | 2019-09-15T21:04:51 | 2019-09-15T21:04:51 | 208,500,970 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,438 | cpp |
#include <cstdio>
//md2code:include
#include <sapi/calc.hpp>
#include <sapi/var.hpp>
#include <sapi/fs.hpp>
int main(int argc, char * argv[]){
{
//md2code:main
Data data_to_encode(arg::Size(128));
data_to_encode.fill<u8>(32);
String encoded_string = Base64::encode(
arg::SourceData(data_to_encode)
);
//You can then decode the data using this code snippet:
Data original_data = Base64::decode(
arg::Base64EncodedString(encoded_string)
);
if( original_data == data_to_encode ){
printf("It works!\n");
}
}
{
//md2code:main
String encoded_string;
//assign base64 encoded string
Data raw_data;
raw_data = Base64::decode(encoded_string);
}
{
//md2code:main
Data raw_data(arg::Size(64)); //raw binary data that needs to be encoded
raw_data.fill<u8>(0xaa);
String result = Base64::encode(arg::SourceData(raw_data));
printf("Encoded string is '%s'\n", result.cstring());
}
{
//md2code:main
File source;
File destination;
source.open(
arg::FilePath("/home/raw_data.dat"),
OpenFlags::read_only()
);
destination.create(
arg::DestinationFilePath("/home/base64_encoded.txt"),
arg::IsOverwrite(true)
);
Base64::encode(
arg::SourceFile(source),
arg::DestinationFile(destination)
);
}
return 0;
}
| [
"tyler.w.gilbert@gmail.com"
] | tyler.w.gilbert@gmail.com |
c73d4b86f47818abfc4819d64b5118ecf7930db2 | 5a93e465b3a2ec5e5b549db1bd6ecc4f0f78ffdf | /Key.h | eb6fcc8e16691b70a3cfbfb834d195587bba9865 | [] | no_license | vladkeel/DataStructures_HW1 | e85b8bb7d85ba4a758c4c0a27bc79f4b8fe78855 | b5982c7748d552c94bae4211a95337073ae6549d | refs/heads/master | 2021-01-10T01:32:48.680290 | 2015-12-02T15:48:17 | 2015-12-02T15:48:17 | 46,812,248 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 649 | h | /*
* Key.h
*
* Created on: Nov 30, 2015
* Author: mac
*/
#ifndef KEY_H_
#define KEY_H_
class Key{
int levelNum;
int pokemonID;
public:
Key():levelNum(0), pokemonID(0){};
Key(int level, int pokemon) : levelNum(level), pokemonID(pokemon){};
bool operator==(const Key& k){
return (levelNum==k.levelNum)&&(pokemonID==k.pokemonID);
}
bool operator<(const Key& k) const{
if(levelNum>k.levelNum)
return true;
else if(levelNum==k.levelNum)
return pokemonID < k.pokemonID ? true : false;
return false;
}
int getLevel() const{
return levelNum;
}
int getPokemon() const{
return pokemonID;
}
};
#endif /* KEY_H_ */
| [
"Vlad Keel"
] | Vlad Keel |
c948ccf5c04871f9ba7edb56d9222d00e5f2b5ed | 3b74241704f1317aef4e54ce66494a4787b0b8c0 | /AtCoder/ABC254/D.cpp | 37f796bdd905d5f94db0b799f5350ce7f80848f0 | [
"CC0-1.0"
] | permissive | arlechann/atcoder | 990a5c3367de23dd79359906fd5119496aad6eee | a62fa2324005201d518b800a5372e855903952de | refs/heads/master | 2023-09-01T12:49:34.034329 | 2023-08-26T17:20:36 | 2023-08-26T17:20:36 | 211,708,577 | 0 | 0 | CC0-1.0 | 2022-06-06T21:49:11 | 2019-09-29T18:37:00 | Rust | UTF-8 | C++ | false | false | 4,567 | cpp | #include <algorithm>
#include <cassert>
#include <climits>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <functional>
#include <iomanip>
#include <iostream>
#include <limits>
#include <list>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <sstream>
#include <string>
#include <tuple>
#include <type_traits>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
#define REP(i, n) for(int i = 0, i##_MACRO = (n); i < i##_MACRO; i++)
#define RREP(i, n) for(int i = (n)-1; i >= 0; i--)
#define RANGE(i, a, b) for(int i = (a), i##_MACRO = (b); i < i##_MACRO; i++)
#define RRANGE(i, a, b) for(int i = (b)-1, i##_MACRO = (a); i >= i##_MACRO; i--)
#define EACH(e, a) for(auto&& e : a)
#define ALL(a) std::begin(a), std::end(a)
#define RALL(a) std::rbegin(a), std::rend(a)
#define FILL(a, n) memset((a), n, sizeof(a))
#define FILLZ(a) FILL(a, 0)
#define CAST(x, t) (static_cast<t>(x))
#define PRECISION(x) std::fixed << std::setprecision(x)
using namespace std;
using ll = long long;
using VI = vector<int>;
using VI2D = vector<vector<int>>;
using VLL = vector<long long>;
using VLL2D = vector<vector<long long>>;
constexpr int INF = 2e9;
constexpr long long INFLL = 2e18;
constexpr double EPS = 1e-10;
constexpr double PI = acos(-1.0);
template <typename T, std::size_t N>
struct make_vector_type {
using type =
typename std::vector<typename make_vector_type<T, (N - 1)>::type>;
};
template <typename T>
struct make_vector_type<T, 0> {
using type = typename std::vector<T>;
};
template <typename T, size_t N>
auto make_vector_impl(const std::vector<std::size_t>& ls, T init_value) {
if constexpr(N == 0) {
return std::vector<T>(ls[N], init_value);
} else {
return typename make_vector_type<T, N>::type(
ls[N], make_vector_impl<T, (N - 1)>(ls, init_value));
}
}
template <typename T, std::size_t N>
auto make_vector(const std::size_t (&ls)[N], T init_value) {
std::vector<std::size_t> dimensions(N);
for(int i = 0; i < N; i++) {
dimensions[N - i - 1] = ls[i];
}
return make_vector_impl<T, N - 1>(dimensions, init_value);
}
template <typename T>
std::vector<T> make_vector(std::size_t size, T init_value) {
return std::vector<T>(size, init_value);
}
template <typename T>
constexpr int sign(T x) {
return x < 0 ? -1 : x > 0 ? 1 : 0;
}
template <>
constexpr int sign(double x) {
return x < -EPS ? -1 : x > EPS ? 1 : 0;
}
template <typename T>
constexpr bool chmax(T& m, T x) {
if(m >= x) {
return false;
}
m = x;
return true;
}
template <typename T>
constexpr bool chmin(T& m, T x) {
if(m <= x) {
return false;
}
m = x;
return true;
}
template <typename T>
constexpr T square(T x) {
return x * x;
}
template <typename T>
constexpr T pow(T a, int n) {
T ret = 1;
while(n != 0) {
if(n % 2) {
ret *= a;
}
a *= a;
n /= 2;
}
return ret;
}
template <typename T>
constexpr T div_ceil(T a, T b) {
assert(b != 0);
if(a < 0 && b < 0) {
a = -a;
b = -b;
}
if(a >= 0 && b > 0) {
return (a + b - 1) / b;
}
return a / b;
}
template <typename T>
constexpr T div_floor(T a, T b) {
assert(b != 0);
if(a < 0 && b < 0) {
a = -a;
b = -b;
}
if(a >= 0 && b > 0) {
return a / b;
}
assert(false);
}
template <typename T>
constexpr bool is_power_of_two(T n) {
if constexpr(n == std::numeric_limits<T>::min()) {
return true;
}
return (n & (n - 1)) == 0;
}
constexpr std::size_t next_power_of_two(std::size_t n) {
if((n & (n - 1)) == 0) {
return n;
}
std::size_t ret = 1;
while(n != 0) {
ret <<= 1;
n >>= 1;
}
return ret;
}
template <typename T>
constexpr T next_multiple_of(T a, T b) {
return div_ceil(a, b) * b;
}
template <typename T>
constexpr bool is_mul_overflow(T a, T b) {
if(a >= 0 && b >= 0) {
return a > std::numeric_limits<T>::max() / b;
}
if(a <= 0 && b < 0) {
return a < div_ceil(std::numeric_limits<T>::max(), b);
}
if(a < 0) {
return a > std::numeric_limits<T>::min() / b;
}
if(b < 0) {
return a < div_ceil(std::numeric_limits<T>::max(), b);
}
}
template <typename T>
constexpr T diff(T a, T b) {
return max(a, b) - min(a, b);
}
/**
* _ _ _ ____
* (_)_ __ | |_ _ __ ___ __ _(_)_ __ / /\ \ _
* | | '_ \| __| | '_ ` _ \ / _` | | '_ \| | | (_)
* | | | | | |_ | | | | | | (_| | | | | | | | |_
* |_|_| |_|\__| |_| |_| |_|\__,_|_|_| |_| | | ( )
* \_\/_/|/
*/
int main() {
ll n;
cin >> n;
ll result = 0;
for(ll i = 1; i <= n; i++) {
ll sq = i * i;
}
cout << result << endl;
return 0;
}
| [
"dragnov3728@gmail.com"
] | dragnov3728@gmail.com |
7c2c1ab3736f944609568fd6c76ec24d3a2cf55b | 75406b949add5ba30f4e802d14326140e05825cb | /test.cpp | 879cbcfeb53c64ac60bf0fc0993b74209e7584cd | [] | no_license | gaopeng1965/AlgoTest | 9f4e2abe41c41784893897e06cde192a885f7697 | a339dabde8a25bc202da011405cb31f058d10327 | refs/heads/main | 2023-08-19T09:12:06.597785 | 2021-10-04T08:48:36 | 2021-10-04T08:48:36 | 390,428,357 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,225 | cpp | /*
#include <iostream>
#include <thread>
#include <mutex>
#include <unistd.h>
#include <chrono>
#include <algorithm>
#include <sys/syscall.h>
#include <condition_variable>
#include <future>
#include <string>
#include <vector>
using std::string;
using std::cout;
using std::endl;
using std::vector;
using std::thread;
//std::mutex mtx;
//std::condition_variable cv;
//bool ready = false;
#if 0
string DoTimeCostWork(int nId)
{
std::this_thread::sleep_for(std::chrono::seconds(nId));
return "www";
}
int main()
{
std::future<std::string> fut = std::async(DoTimeCostWork, 3);
// 每100毫秒轮询查看任务执行进度
std::chrono::milliseconds tSpan(200);
while (fut.wait_for(tSpan) != std::future_status::ready)
{
cout << "......" << endl;
}
cout << "exec complete:" << fut.get() << endl;
return 0;
}
#endif
#if 0
void printId(int id){
std::unique_lock<std::mutex> lck(mtx);
cv.wait(lck,[]{return ready;});//[&]???
cout<<"Thread : "<<id<<endl;
}
void go(){
std::unique_lock<std::mutex> lck(mtx);
ready = true;
cv.notify_all();
}
void foo(){
std::this_thread::sleep_for(std::chrono::seconds(1));
cout<<std::this_thread::get_id()<<endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
}
void bar(){
std::this_thread::sleep_for(std::chrono::seconds(1));
cout<<std::this_thread::get_id()<<endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
}
int main(){
// thread t[10];
// for (int i = 0; i < 10; ++i) {
// t[i] = thread(printId,i);
// }
// cout << "10 threads ready to race...\n";
// go();
//
// for (auto& i:t) {
// i.join();
// }
// auto f =[]()->void{
// if (ready)
// cout<<"true\n";
// else
// cout<<"false\n";
// };
// f();
cout<<getpid()<<endl;
cout<<std::this_thread::get_id()<<endl;
std::thread t1(foo);
std::thread t2(bar);
std::cout << "thread 1 id: " << t1.get_id() << std::endl;
std::cout << "thread 2 id: " << t2.get_id() << std::endl;
std::swap(t1, t2);
std::cout << "after std::swap(t1, t2):" << std::endl;
std::cout << "thread 1 id: " << t1.get_id() << std::endl;
std::cout << "thread 2 id: " << t2.get_id() << std::endl;
t1.swap(t2);
std::cout << "after t1.swap(t2):" << std::endl;
std::cout << "thread 1 id: " << t1.get_id() << std::endl;
std::cout << "thread 2 id: " << t2.get_id() << std::endl;
t1.join();
t2.join();
return 0;
}
#endif
#if 0
template<typename T>
void print(T& t){
cout << "lvalue" << endl;
}
template<typename T>
void print(T&& t){
cout << "rvalue" << endl;
}
template<typename T>
void TestForward(T && v){
print(v);
print(std::forward<T>(v));
print(std::move(v));
}
int main(){
TestForward(1);
int x = 1;
TestForward(x);
TestForward(std::forward<int>(x));
return 0;
}
#endif
#if 0
#include <boost/asio.hpp>
#include <boost/asio/steady_timer.hpp>
using namespace boost::asio;
using namespace boost::asio::ip;
io_service io;
tcp::resolver resolv(io);
tcp::socket tcp_socket(io);
std::array<char, 4096> bytes;
void read_handler(const boost::system::error_code &ec, std::size_t bytes_transferred)
{
if (!ec)
{
std::cout.write(bytes.data(), bytes_transferred);
tcp_socket.async_read_some(buffer(bytes), read_handler);
}
}
void connect_handler(const boost::system::error_code &ec)
{
if (!ec)
{
std::string r =
"GET / HTTP/1.1\r\nHost: theboostcpplibraries.com\r\n\r\n";
write(tcp_socket, buffer(r));
tcp_socket.async_read_some(buffer(bytes), read_handler);
}
}
//void print(const boost::system::error_code&){
// cout<<"hhhhhhhh"<<endl;
//}
void resolve_handler(const boost::system::error_code &ec, tcp::resolver::iterator it)
{
if (!ec)
tcp_socket.async_connect(*it, connect_handler);
}
int main_1()
{
// steady_timer t1(io, std::chrono::seconds(2));
// t1.async_wait([](const boost::system::error_code &e){
// cout<<"2 sec\n";
// });
// steady_timer t2(io, std::chrono::seconds(2));
// t2.async_wait([](const boost::system::error_code &e){
// cout<<"2 sec\n";
// });
//
// thread thread1([&io]{io.run();});
// thread thread2([&io]{io.run();});
// thread1.join();
// thread2.join();
tcp::resolver::query q("theboostcpplibraries.com","80");
resolv.async_resolve(q,resolve_handler);
io.run();
return 0;
}
#endif
#include "FooBar.h"
#if 0
int main(){
FooBar f(2);
FooBar f2(3);
// thread t1 = f.createThread1();
// thread t2 = f.createThread2();
thread t1 = thread(&FooBar::foo,&f2,[]{
cout<<"foo";
});
thread t2 = thread(&FooBar::bar,&f2,[]{
cout<<"bar";
});
t1.join();
t2.join();
return 0;
}
#endif
//#include <algorithm>
//class Solution {
//public:
// void getLeastNumbers(vector<int>& arr, int k) {
// if (arr.size()==0){
// cout<<"vector are null"<<endl;
// }else if(arr.size()<=k){
// return;
// } else{
// std::sort(arr.begin(),arr.end());
// arr.erase(arr.begin()+k,arr.end());
// }
// }
//};
#if 0
int main(){
// vector<int> arr{3,2,1};
// Solution s;
// s.getLeastNumbers(arr,2);
// std::for_each(arr.begin(),arr.end(),[](int x){
// cout<<x<<" ";
// });
using namespace pugi;
xml_document doc;
if (!doc.load_file("/root/ShareDir/DRM/test/gen1.xml")) return -1;
// string l2d = doc.child("task")
string node = doc.child("task").child("inputlist").child("input").attribute("description").value();
cout<<node<<endl;
xml_node input_node = doc.child("task").child("inputlist").child("input");
for (; input_node; input_node = input_node.next_sibling()) {
cout<<input_node.attribute("description").value()<<endl;
}
// xml_node tools = doc.child("Profile").child("Tools");
//
// //[code_traverse_base_basic
// for (xml_node tool = tools.first_child(); tool; tool = tool.next_sibling())
// {
// std::cout << "Tool:";
//
// for (xml_attribute attr = tool.first_attribute(); attr; attr = attr.next_attribute())
// {
// string tmp1 = attr.name();
// string tmp2 = attr.value();
// std::cout << " " << tmp1 << "=" << tmp2;
// }
//
// std::cout << std::endl;
// }
// using namespace pugi;
// xml_document doc;
// xml_parse_result result = doc.load_file("/root/ShareDir/DRM/smr/smr3.5/xml/tree.xml");//parse解析,无错误则返回1
// cout << result.description() << endl;//也可以把1描述出来,No error
// if (!result) return -1; //推荐直接写 if (!doc.load_file("tree.xml")) return -1;
//
// cout << doc.child("mesh").attribute("name").value() << endl; //节点mesh的属性name的值
// cout << doc.first_child().child_value() << endl;
// cout << doc.child("mesh").child("node").attribute("attr1").value() << endl; //节点mesh的节点node的属性attr1的值
// return 0;
//
// doc.print(cout); //展示文档内容
}
#endif
#include <boost/filesystem.hpp>
#include <boost/xpressive/xpressive.hpp>
#include <sstream>
//int main_0(){
// using namespace boost::filesystem;
// using namespace boost::xpressive;
//// string s = "/root/ShareDir/DRM/smr/smr3.5/L2D/H2B_OPER_SMR_L2D_SG_20200305T155827_20200305T165140_036_0079_01.h5";
//// path p(s);
//// cout<<p.filename()<<endl;
// string tmp = "/root/ShareDir/DRM/smr/smr3.5/L2D/H2B_OPER_SMR_L2D_SG_20200305T155827_20200305T165140_036_0079_01.h5";
// string s = path(tmp).filename().string();
// sregex reg = sregex::compile("_(\\d{8})T\\d{0,6}_(\\d{8})T\\d*");
// smatch what;
// if(regex_search(s,what,reg)){
// string time1 = what[1];
// string time2 = what[2];
// if(time1 == time2)
// cout<<time1<<"="<<time2<<endl;
// else
// cout<<time1<<" "<<time2<<endl;
// } else
// cout<<"not match."<<endl;
//}
string TupperLower(const string &strName, bool bLower)
{
string strResult;
if (bLower)
{
std::transform(strName.begin(), strName.end(), back_inserter(strResult), ::tolower);
}
else
{
std::transform(strName.begin(), strName.end(), back_inserter(strResult), ::toupper);
}
return strResult;
}
int main_s(){
#if 0
using std::stringstream;
string s = " This is life! ";
auto t1 = std::chrono::high_resolution_clock::now();
string tmp,ans;
stringstream ss(s);
while(ss>>tmp){
ans=" "+tmp+ans;
}
if(ans!="")
ans.erase(ans.begin());
auto t2 = std::chrono::high_resolution_clock::now();
// 整型结果
// auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(t2-t1);
std::chrono::duration<double,std::milli> duration = t2-t1;
cout<<ans<<endl;
cout<<duration.count()<<" ms"<<endl;
string ddd = "This is an example";
ddd.erase(ddd.find(' '));
cout<<ddd<<endl;
#endif
// using std::shared_ptr;
// using std::make_shared;
//
// auto a = make_shared<FooBar>(5);
}
*/
| [
"754205163@qq.com"
] | 754205163@qq.com |
b157c1c20d284b4361bcbbc4d8775baf06a83f36 | 2f20ab7ee2aa0d99862a6e72d987f5a23e0245be | /barectf_lttng_lib/freertos_platform/barectf_platform.cpp | 06a55dc21920c323ecc4a8d1ee04bb259a316e3e | [] | no_license | khoitd1997/small_program | 64713cdebb72ff6c3638832331031cdbd4b643b0 | 97c17101c364b934a4a3e18004ecb0fc54d78506 | refs/heads/master | 2022-03-17T17:15:50.114201 | 2022-02-25T16:46:25 | 2022-02-25T16:46:25 | 199,195,955 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,261 | cpp | /*
* Copyright (c) 2015 EfficiOS Inc. and Linux Foundation
* Copyright (c) 2015-2020 Philippe Proulx <pproulx@efficios.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 <stdexcept>
#include "barectf.h"
#include "barectf_platform.h"
#include "barectf_utils.h"
bool BarectfUserTrace::isStatedumpDone = false;
bool BarectfKernelTrace::init(uint8_t* bufAddr, const unsigned int bufSize) {
BarectfBaseTrace::init(bufAddr, bufSize);
barectf_init(&streamCtx, traceBuffer, bufSize, barectfCallback, this);
openPacket();
return true;
}
void BarectfKernelTrace::finish(bool* isEmpty) {
if (isEmpty) { *isEmpty = barectf_packet_is_empty(&streamCtx); }
closePacket();
}
void BarectfKernelTrace::openPacket() {
barectf_kernel_stream_open_packet(&streamCtx, getCurrCpu());
}
void BarectfKernelTrace::closePacket() {
if (barectf_packet_is_open(&streamCtx) && !barectf_packet_is_empty(&streamCtx)) {
barectf_kernel_stream_close_packet(&streamCtx);
}
}
void BarectfKernelTrace::openPacketCallback(void* const data) {
BarectfKernelTrace* kernelTrace = static_cast<BarectfKernelTrace*>(data);
kernelTrace->openPacket();
}
void BarectfKernelTrace::closePacketCallback(void* const data) {
BarectfKernelTrace* kernelTrace = static_cast<BarectfKernelTrace*>(data);
kernelTrace->closePacket();
}
int BarectfKernelTrace::isBackendFullCallback(void* const data) {
(void)(data);
return 0;
}
bool BarectfUserTrace::init(uint8_t* bufAddr, const unsigned int bufSize) {
BarectfBaseTrace::init(bufAddr, bufSize);
barectf_init(&streamCtx, traceBuffer, bufSize, barectfCallback, this);
openPacket();
doBasicStatedump();
return true;
}
void BarectfUserTrace::finish(bool* isEmpty) {
if (isEmpty) { *isEmpty = barectf_packet_is_empty(&streamCtx); }
closePacket();
}
void BarectfUserTrace::openPacket() { barectf_user_stream_open_packet(&streamCtx, getCurrCpu()); }
void BarectfUserTrace::closePacket() {
if (barectf_packet_is_open(&streamCtx) && !barectf_packet_is_empty(&streamCtx)) {
barectf_user_stream_close_packet(&streamCtx);
}
}
void BarectfUserTrace::openPacketCallback(void* const data) {
BarectfUserTrace* userTrace = static_cast<BarectfUserTrace*>(data);
userTrace->openPacket();
}
void BarectfUserTrace::closePacketCallback(void* const data) {
BarectfUserTrace* userTrace = static_cast<BarectfUserTrace*>(data);
userTrace->closePacket();
}
int BarectfUserTrace::isBackendFullCallback(void* const data) { return 0; }
void BarectfUserTrace::doBasicStatedump() {
// we only want one statedump ever, so make sure only one guy ever does it
FreeRTOSCriticalSectionGuard lock{};
if (isStatedumpDone) { return; }
BarectfThreadInfo threadInfo;
getCurrThreadInfo(threadInfo);
barectf_user_stream_trace_lttng_ust_statedump_start(
&streamCtx, FreeRtosFixedPid, threadInfo.tid, threadInfo.name);
barectf_user_stream_trace_lttng_ust_statedump_procname(
&streamCtx, FreeRtosFixedPid, threadInfo.tid, threadInfo.name, threadInfo.name);
BarectfExeInfo exeInfo{};
barectfGetCurrExeInfo(exeInfo);
if (exeInfo.name.empty()) {
throw std::runtime_error("barectfGetCurrExeInfo didn't set info properly");
}
barectf_user_stream_trace_lttng_ust_statedump_bin_info(&streamCtx,
FreeRtosFixedPid,
threadInfo.tid,
threadInfo.name,
(uintptr_t)(exeInfo.baseAddr),
exeInfo.memSize,
exeInfo.name.c_str(),
exeInfo.isPositionIndependent ? 1 : 0,
false,
false);
barectf_user_stream_trace_lttng_ust_statedump_end(
&streamCtx, FreeRtosFixedPid, threadInfo.tid, threadInfo.name);
isStatedumpDone = true;
} | [
"khoidinhtrinh@gmail.com"
] | khoidinhtrinh@gmail.com |
bacec80e7af93051f0bee51995d3ae403d34395d | a6cabe4236778f411d9a850d2435a2a24e87de85 | /MameBake3DLib/CPP/Model_20160419_1.cpp | 00c38dad69a564fdbb3456bea897bb6ba8480c6b | [] | no_license | lvjunsetup/MameBake3D | 27e447246467e39dc49ae96109a5706359c39c62 | af5e869e8a204aa356f0b061f31ed03fbccb74f3 | refs/heads/master | 2021-09-29T01:44:08.612094 | 2018-11-22T13:24:05 | 2018-11-22T13:24:05 | null | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 165,324 | cpp | #include "stdafx.h"
//#include <stdafx.h>
#include <stdio.h>
#include <stdarg.h>
#include <math.h>
#include <string.h>
#include <wchar.h>
#include <ctype.h>
#include <malloc.h>
#include <memory.h>
#include <windows.h>
#include <crtdbg.h>
#include <Model.h>
#include <polymesh3.h>
#include <polymesh4.h>
#include <ExtLine.h>
#include <GetMaterial.h>
#include <mqofile.h>
#include <mqomaterial.h>
#include <mqoobject.h>
#include <Bone.h>
#include <mqoface.h>
#define DBGH
#include <dbg.h>
#include <DXUT.h>
#include <DXUTcamera.h>
#include <DXUTgui.h>
#include <DXUTsettingsdlg.h>
#include <SDKmisc.h>
#include <DispObj.h>
//#include <InfScope.h>
#include <MySprite.h>
#include <MotionPoint.h>
#include <quaternion.h>
#include <VecMath.h>
#include <Collision.h>
#include <EngName.h>
#include <RigidElem.h>
#include <string>
#include <fbxsdk.h>
#include <fbxsdk/scene/shading/fbxlayeredtexture.h>
//#include <fbxsdk/scene/shading/fbxtexture.h>
//#include <fbxsdk/scene/shading/fbxsurfacematerial.h>
//#include <fbxsdk/scene/animation/fbxanimstack.h>
//#include <fbxsdk/scene/animation/fbxanimlayer.h>
#include <BopFile.h>
#include <BtObject.h>
#include <collision.h>
#include <EditRange.h>
#include "btBulletDynamicsCommon.h"
#include "LinearMath/btIDebugDraw.h"
using namespace OrgWinGUI;
static int s_alloccnt = 0;
extern int g_previewFlag; // プレビューフラグ
extern WCHAR g_basedir[ MAX_PATH ];
extern ID3DXEffect* g_pEffect;
extern D3DXHANDLE g_hm3x4Mat;
extern D3DXHANDLE g_hmWorld;
extern float g_impscale;
extern btScalar G_ACC; // 重力加速度 : BPWorld.cpp
extern float g_l_kval[3];
extern float g_a_kval[3];
extern float g_ikfirst;
extern float g_ikrate;
extern int g_slerpoffflag;
extern int g_absikflag;
extern int g_applyendflag;
extern int g_bonemarkflag;
extern ChaVector3 g_camEye;
extern ChaVector3 g_camtargetpos;
int g_dbgflag = 0;
//////////
static FbxDouble3 GetMaterialProperty(const FbxSurfaceMaterial * pMaterial, const char * pPropertyName, const char * pFactorPropertyName, char** ppTextureName);
static int IsValidCluster( FbxCluster* pcluster );
static FbxAMatrix GetGlobalPosition(FbxNode* pNode, const FbxTime& pTime, FbxPose* pPose, FbxAMatrix* pParentGlobalPosition = NULL );
static FbxAMatrix GetPoseMatrix(FbxPose* pPose, int pNodeIndex);
static FbxAMatrix GetGeometry(FbxNode* pNode);
static int s_setrigidflag = 0;
static DWORD s_rigidflag = 0;
CModel::CModel()
{
InitParams();
s_alloccnt++;
m_modelno = s_alloccnt;
}
CModel::~CModel()
{
DestroyObjs();
}
int CModel::InitParams()
{
m_ikrotaxis = ChaVector3( 1.0f, 0.0f, 0.0f );
m_texpool = D3DPOOL_DEFAULT;
m_tmpmotspeed = 1.0f;
m_curreindex = 0;
m_rgdindex = 0;
m_rgdmorphid = -1;
strcpy_s( m_defaultrename, MAX_PATH, "default_ref.ref" );
strcpy_s( m_defaultimpname, MAX_PATH, "default_imp.imp" );
m_rigidbone.clear();
//m_btg = -1.0f;
m_fbxobj.clear();
m_btWorld = 0;
m_modelno = 0;
m_pdev = 0;
ZeroMemory( m_filename, sizeof( WCHAR ) * MAX_PATH );
ZeroMemory( m_dirname, sizeof( WCHAR ) * MAX_PATH );
ZeroMemory( m_modelfolder, sizeof( WCHAR ) * MAX_PATH );
m_loadmult = 1.0f;
ChaMatrixIdentity( &m_matWorld );
ChaMatrixIdentity( &m_matVP );
m_curmotinfo = 0;
m_modeldisp = true;
m_topbone = 0;
//m_firstbone = 0;
this->m_tlFunc = 0;
m_psdk = 0;
m_pimporter = 0;
m_pscene = 0;
m_btcnt = 0;
m_topbt = 0;
m_rigideleminfo.clear();
m_impinfo.clear();
InitUndoMotion( 0 );
return 0;
}
int CModel::DestroyObjs()
{
DestroyMaterial();
DestroyObject();
DestroyAncObj();
DestroyAllMotionInfo();
DestroyFBXSDK();
DestroyBtObject();
InitParams();
return 0;
}
int CModel::DestroyFBXSDK()
{
if( m_pimporter ){
FbxArrayDelete(mAnimStackNameArray);
}
// if( m_pscene ){
// m_pscene->Destroy();
// m_pscene = 0;
// }
if( m_pimporter ){
m_pimporter->Destroy();// インポータの削除
m_pimporter = 0;
}
return 0;
}
int CModel::DestroyAllMotionInfo()
{
map<int, MOTINFO*>::iterator itrmi;
for( itrmi = m_motinfo.begin(); itrmi != m_motinfo.end(); itrmi++ ){
MOTINFO* miptr = itrmi->second;
if( miptr ){
free( miptr );
}
}
m_motinfo.erase( m_motinfo.begin(), m_motinfo.end() );
m_curmotinfo = 0;
return 0;
}
int CModel::DestroyMaterial()
{
map<int, CMQOMaterial*>::iterator itr;
for( itr = m_material.begin(); itr != m_material.end(); itr++ ){
CMQOMaterial* delmat = itr->second;
if( delmat ){
delete delmat;
}
}
m_material.erase( m_material.begin(), m_material.end() );
return 0;
}
int CModel::DestroyObject()
{
map<int, CMQOObject*>::iterator itr;
for( itr = m_object.begin(); itr != m_object.end(); itr++ ){
CMQOObject* delobj = itr->second;
if( delobj ){
delete delobj;
}
}
m_object.erase( m_object.begin(), m_object.end() );
return 0;
}
int CModel::DestroyAncObj()
{
map<int, CBone*>::iterator itrbone;
for( itrbone = m_bonelist.begin(); itrbone != m_bonelist.end(); itrbone++ ){
CBone* delbone = itrbone->second;
if( delbone ){
delete delbone;
}
}
m_bonelist.erase( m_bonelist.begin(), m_bonelist.end() );
m_topbone = 0;
m_objectname.erase( m_objectname.begin(), m_objectname.end() );
m_bonename.erase( m_bonename.begin(), m_bonename.end() );
return 0;
}
int CModel::LoadMQO( ID3D10Device* pdev, WCHAR* wfile, WCHAR* modelfolder, float srcmult, int ismedia, int texpool )
{
if( modelfolder ){
wcscpy_s( m_modelfolder, MAX_PATH, modelfolder );
}else{
ZeroMemory( m_modelfolder, sizeof( WCHAR ) * MAX_PATH );
}
m_loadmult = srcmult;
m_pdev = pdev;
m_texpool = texpool;
WCHAR fullname[MAX_PATH];
if( ismedia == 1 ){
WCHAR str[MAX_PATH];
HRESULT hr;
hr = DXUTFindDXSDKMediaFileCch( str, MAX_PATH, wfile );
if( hr != S_OK ){
::MessageBoxA( NULL, "media not found error !!!", "load error", MB_OK );
_ASSERT( 0 );
return 1;
}
wcscpy_s( fullname, MAX_PATH, g_basedir );
wcscat_s( fullname, MAX_PATH, str );
}else{
wcscpy_s( fullname, MAX_PATH, wfile );
}
WCHAR* strLastSlash = NULL;
strLastSlash = wcsrchr( fullname, TEXT( '\\' ) );
if( strLastSlash )
{
*strLastSlash = 0;
wcscpy_s( m_dirname, MAX_PATH, fullname );
wcscpy_s( m_filename, MAX_PATH, strLastSlash + 1 );
}else{
ZeroMemory( m_dirname, sizeof( WCHAR ) * MAX_PATH );
wcscpy_s( m_filename, MAX_PATH, fullname );
}
//WCHAR* dbgfind = wcsstr( wfile, L"gplane" );
//if( dbgfile ){
// _ASSERT( 0 );
//}
SetCurrentDirectory( m_dirname );
DestroyMaterial();
DestroyObject();
CMQOFile mqofile;
ChaVector3 vop( 0.0f, 0.0f, 0.0f );
ChaVector3 vor( 0.0f, 0.0f, 0.0f );
CallF( mqofile.LoadMQOFile( m_pdev, srcmult, m_filename, vop, vor, this ), return 1 );
CallF( MakeObjectName(), return 1 );
CallF( CreateMaterialTexture(), return 1 );
SetMaterialName();
return 0;
}
int CModel::LoadFBX( int skipdefref, ID3D10Device* pdev, WCHAR* wfile, WCHAR* modelfolder, float srcmult, FbxManager* psdk, FbxImporter** ppimporter, FbxScene** ppscene )
{
//DestroyFBXSDK();
m_psdk = psdk;
*ppimporter = 0;
*ppscene = 0;
if( modelfolder ){
wcscpy_s( m_modelfolder, MAX_PATH, modelfolder );
}else{
ZeroMemory( m_modelfolder, sizeof( WCHAR ) * MAX_PATH );
}
m_loadmult = srcmult;
m_pdev = pdev;
WCHAR fullname[MAX_PATH];
wcscpy_s( fullname, MAX_PATH, wfile );
WCHAR* strLastSlash = NULL;
strLastSlash = wcsrchr( fullname, TEXT( '\\' ) );
if( strLastSlash )
{
*strLastSlash = 0;
wcscpy_s( m_dirname, MAX_PATH, fullname );
wcscpy_s( m_filename, MAX_PATH, strLastSlash + 1 );
}else{
ZeroMemory( m_dirname, sizeof( WCHAR ) * MAX_PATH );
wcscpy_s( m_filename, MAX_PATH, fullname );
}
DestroyMaterial();
DestroyObject();
char utf8path[MAX_PATH] = {0};
// Unicode 文字コードを第一引数で指定した文字コードに変換する
::WideCharToMultiByte( CP_UTF8, 0, wfile, -1, utf8path, MAX_PATH, NULL, NULL );
FbxScene* pScene = 0;
FbxImporter* pImporter = 0;
pScene = FbxScene::Create(m_psdk,"");
int lFileMajor, lFileMinor, lFileRevision;
int lSDKMajor, lSDKMinor, lSDKRevision;
bool lStatus;
FbxManager::GetFileFormatVersion(lSDKMajor, lSDKMinor, lSDKRevision);
pImporter = FbxImporter::Create(m_psdk,"");
const bool lImportStatus = pImporter->Initialize(utf8path, -1, m_psdk->GetIOSettings());
pImporter->GetFileVersion(lFileMajor, lFileMinor, lFileRevision);
if( !lImportStatus )
{
_ASSERT( 0 );
return 1;
}
//_ASSERT(0);
if (pImporter->IsFBX())
{
// Set the import states. By default, the import states are always set to
// true. The code below shows how to change these states.
(*(m_psdk->GetIOSettings())).SetBoolProp(IMP_FBX_MATERIAL, true);
(*(m_psdk->GetIOSettings())).SetBoolProp(IMP_FBX_TEXTURE, true);
(*(m_psdk->GetIOSettings())).SetBoolProp(IMP_FBX_LINK, true);
(*(m_psdk->GetIOSettings())).SetBoolProp(IMP_FBX_SHAPE, true);
(*(m_psdk->GetIOSettings())).SetBoolProp(IMP_FBX_GOBO, true);
(*(m_psdk->GetIOSettings())).SetBoolProp(IMP_FBX_ANIMATION, true);
(*(m_psdk->GetIOSettings())).SetBoolProp(IMP_FBX_GLOBAL_SETTINGS, true);
}
// Import the scene.
lStatus = pImporter->Import(pScene);
if(lStatus == false )
{
_ASSERT( 0 );
return 1;
}
// CallF( InitFBXManager( &pSdkManager, &pImporter, &pScene, utf8path ), return 1 );
m_bone2node.clear();
FbxNode *pRootNode = pScene->GetRootNode();
//CBone* rootbone = new CBone( this );
//_ASSERT( rootbone );
//rootbone->SetName( "ModelRootBone" );
//rootbone->m_topboneflag = 1;
//m_topbone = rootbone;
//m_bonelist[rootbone->m_boneno] = rootbone;
//m_bonename[ rootbone->m_bonename ] = rootbone;
m_topbone = 0;
// CBone* dummybone = new CBone( this );
// _ASSERT( dummybone );
// dummybone->SetName( "dummyBone" );
// m_bonelist[dummybone->m_boneno] = dummybone;//これをm_topboneにしてはいけない。これは0でエラーが起こらないための応急措置。
// m_bonename[dummybone->m_bonename] = dummybone;
CreateFBXBoneReq( pScene, pRootNode, 0 );
if( m_bonelist.size() <= 1 ){
_ASSERT( 0 );
delete (CBone*)(m_bonelist.begin()->second);
m_bonelist.clear();
m_topbone = 0;
}
CBone* chkbone = m_bonelist[0];
if( !chkbone ){
CBone* dummybone = new CBone( this );
_ASSERT( dummybone );
dummybone->SetName( "DummyBone" );
}
CreateFBXMeshReq( pRootNode );
DbgOut( L"fbx bonenum %d\r\n", m_bonelist.size() );
ChaMatrix offsetmat;
ChaMatrixIdentity( &offsetmat );
offsetmat._11 = srcmult;
offsetmat._22 = srcmult;
offsetmat._33 = srcmult;
map<int,CMQOObject*>::iterator itr;
for( itr = m_object.begin(); itr != m_object.end(); itr++ ){
CMQOObject* curobj = itr->second;
if( curobj ){
CallF( curobj->MultMat( offsetmat ), return 1 );
CallF( curobj->MultVertex(), return 1; );
}
}
//m_ktime0.SetTime(0, 0, 0, 1, 0, pScene->GetGlobalSettings().GetTimeMode());
// m_ktime0.SetSecondDouble( 1.0 / 300.0 );
// m_ktime0.SetSecondDouble( 1.0 / 30.0 );
CallF( MakePolyMesh4(), return 1 );
CallF( MakeObjectName(), return 1 );
CallF( CreateMaterialTexture(), return 1 );
if( m_topbone ){
CallF( CreateFBXSkinReq( pRootNode ), return 1 );
}
SetMaterialName();
map<int,CBone*>::iterator itrbone;
for( itrbone = m_bonelist.begin(); itrbone != m_bonelist.end(); itrbone++ ){
CBone* curbone = itrbone->second;
curbone->SetBtKinFlag( 1 );
}
map<int,CMQOObject*>::iterator itr2;
for( itr2 = m_object.begin(); itr2 != m_object.end(); itr2++ ){
CMQOObject* curobj = itr2->second;
if( curobj ){
char* findnd = strstr( (char*)curobj->GetName(), "_ND" );
if( findnd ){
curobj->SetDispFlag( 0 );
}
}
}
m_rigideleminfo.clear();
m_impinfo.clear();
if( skipdefref == 0 ){
REINFO reinfo;
ZeroMemory( &reinfo, sizeof( REINFO ) );
strcpy_s( reinfo.filename, MAX_PATH, m_defaultrename );
reinfo.btgscale = 9.07;
m_rigideleminfo.push_back( reinfo );
m_impinfo.push_back( m_defaultimpname );
if( m_topbone ){
CreateRigidElemReq( m_topbone, 1, m_defaultrename, 1, m_defaultimpname );
}
SetCurrentRigidElem( 0 );
m_curreindex = 0;
m_curimpindex = 0;
}
*ppimporter = pImporter;
*ppscene = pScene;
m_pimporter = pImporter;
m_pscene = pScene;
return 0;
}
int CModel::LoadFBXAnim( FbxManager* psdk, FbxImporter* pimporter, FbxScene* pscene, int (*tlfunc)( int srcmotid ) )
{
if( !psdk || !pimporter || !pscene ){
_ASSERT( 0 );
return 0;
}
if( !m_topbone ){
return 0;
}
this->m_tlFunc = tlfunc;
FbxNode *pRootNode = pscene->GetRootNode();
CallF( CreateFBXAnim( pscene, pRootNode ), return 1 );
map<int, CBone*>::iterator itrbone;
for( itrbone = m_bonelist.begin(); itrbone != m_bonelist.end(); itrbone++ ){
CBone* curbone = itrbone->second;
curbone->CalcAxisMat( 1, 0.0f );
}
return 0;
}
int CModel::CreateMaterialTexture()
{
map<int,CMQOMaterial*>::iterator itr;
for( itr = m_material.begin(); itr != m_material.end(); itr++ ){
CMQOMaterial* curmat = itr->second;
CallF( curmat->CreateTexture( m_dirname, m_texpool ), return 1 );
}
map<int,CMQOObject*>::iterator itrobj;
for( itrobj = m_object.begin(); itrobj != m_object.end(); itrobj++ ){
CMQOObject* curobj = itrobj->second;
if( curobj ){
map<int,CMQOMaterial*>::iterator itr;
for( itr = curobj->GetMaterialBegin(); itr != curobj->GetMaterialEnd(); itr++ ){
CMQOMaterial* curmat = itr->second;
CallF( curmat->CreateTexture( m_dirname, m_texpool ), return 1 );
}
}
}
return 0;
}
int CModel::OnRender( ID3D10Device* pdev, int lightflag, ChaVector4 diffusemult, int btflag )
{
map<int,CMQOObject*>::iterator itr;
for( itr = m_object.begin(); itr != m_object.end(); itr++ ){
CMQOObject* curobj = itr->second;
if( curobj && curobj->GetDispFlag() ){
if( curobj->GetDispObj() ){
CallF( SetShaderConst( curobj, btflag ), return 1 );
CMQOMaterial* rmaterial = 0;
if( curobj->GetPm3() ){
g_pEffect->SetMatrix( g_hmWorld, &m_matWorld );
CallF( curobj->GetDispObj()->RenderNormalPM3( lightflag, diffusemult ), return 1 );
}else if( curobj->GetPm4() ){
rmaterial = curobj->GetMaterialBegin()->second;
CallF( curobj->GetDispObj()->RenderNormal( rmaterial, lightflag, diffusemult ), return 1 );
}else{
_ASSERT( 0 );
}
}
if( curobj->GetDispLine() ){
CallF( curobj->GetDispLine()->RenderLine( diffusemult ), return 1 );
}
}
}
return 0;
}
int CModel::GetModelBound( MODELBOUND* dstb )
{
MODELBOUND mb;
MODELBOUND addmb;
ZeroMemory( &mb, sizeof( MODELBOUND ) );
int calcflag = 0;
map<int,CMQOObject*>::iterator itr;
for( itr = m_object.begin(); itr != m_object.end(); itr++ ){
CMQOObject* curobj = itr->second;
if( curobj->GetPm3() ){
curobj->GetPm3()->CalcBound();
if( calcflag == 0 ){
mb = curobj->GetPm3()->GetBound();
}else{
addmb = curobj->GetPm3()->GetBound();
AddModelBound( &mb, &addmb );
}
calcflag++;
}
if( curobj->GetPm4() ){
curobj->GetPm4()->CalcBound();
if( calcflag == 0 ){
mb = curobj->GetPm4()->GetBound();
}else{
addmb = curobj->GetPm4()->GetBound();
AddModelBound( &mb, &addmb );
}
calcflag++;
}
if( curobj->GetExtLine() ){
curobj->GetExtLine()->CalcBound();
if( calcflag == 0 ){
mb = curobj->GetExtLine()->m_bound;
}else{
addmb = curobj->GetExtLine()->m_bound;
AddModelBound( &mb, &addmb );
}
calcflag++;
}
}
*dstb = mb;
return 0;
}
int CModel::AddModelBound( MODELBOUND* mb, MODELBOUND* addmb )
{
ChaVector3 newmin = mb->min;
ChaVector3 newmax = mb->max;
if( newmin.x > addmb->min.x ){
newmin.x = addmb->min.x;
}
if( newmin.y > addmb->min.y ){
newmin.y = addmb->min.y;
}
if( newmin.z > addmb->min.z ){
newmin.z = addmb->min.z;
}
if( newmax.x < addmb->max.x ){
newmax.x = addmb->max.x;
}
if( newmax.y < addmb->max.y ){
newmax.y = addmb->max.y;
}
if( newmax.z < addmb->max.z ){
newmax.z = addmb->max.z;
}
mb->center = ( newmin + newmax ) * 0.5f;
mb->min = newmin;
mb->max = newmax;
ChaVector3 diff;
diff = mb->center - newmin;
mb->r = ChaVector3Length( &diff );
return 0;
}
int CModel::SetShapeNoReq( CMQOFace** ppface, int facenum, int searchp, int shapeno, int* setfacenum )
{
int fno;
CMQOFace* findface[200];
ZeroMemory( findface, sizeof( CMQOFace* ) * 200 );
int findnum = 0;
for( fno = 0; fno < facenum; fno++ ){
CMQOFace* curface = *( ppface + fno );
if( curface->GetShapeNo() != -1 ){
continue;
}
int chki;
for( chki = 0; chki < curface->GetPointNum(); chki++ ){
if( searchp == curface->GetIndex( chki ) ){
if( findnum >= 200 ){
_ASSERT( 0 );
return 1;
}
curface->SetShapeNo( shapeno );
findface[findnum] = curface;
findnum++;
break;
}
}
}
if( findnum > 0 ){
(*setfacenum) += findnum;
int findno;
for( findno = 0; findno < findnum; findno++ ){
CMQOFace* fface = findface[ findno ];
int i;
for( i = 0; i < fface->GetPointNum(); i++ ){
int newsearch = fface->GetIndex( i );
if( newsearch != searchp ){
SetShapeNoReq( ppface, facenum, newsearch, shapeno, setfacenum );
}
}
}
}
return 0;
}
int CModel::SetFaceOfShape( CMQOFace** ppface, int facenum, int shapeno, CMQOFace** ppface2, int setfacenum )
{
int setno = 0;
int fno;
for( fno = 0; fno < facenum; fno++ ){
CMQOFace* curface = *( ppface + fno );
if( curface->GetShapeNo() == shapeno ){
if( setno >= setfacenum ){
_ASSERT( 0 );
return 1;
}
*( ppface2 + setno ) = curface;
setno++;
}
}
_ASSERT( setno == setfacenum );
return 0;
}
int CModel::MakeObjectName()
{
map<int, CMQOObject*>::iterator itrobj;
for( itrobj = m_object.begin(); itrobj != m_object.end(); itrobj++ ){
CMQOObject* curobj = itrobj->second;
if( curobj ){
char* nameptr = (char*)curobj->GetName();
int sdefcmp, bdefcmp;
sdefcmp = strncmp( nameptr, "sdef:", 5 );
bdefcmp = strncmp( nameptr, "bdef:", 5 );
if( (sdefcmp != 0) && (bdefcmp != 0) ){
int leng = (int)strlen( nameptr );
string firstname( nameptr, nameptr + leng );
m_objectname[ firstname ] = curobj;
curobj->SetDispName( firstname );
}else{
char* startptr = nameptr + 5;
int leng = (int)strlen( startptr );
string firstname( startptr, startptr + leng );
m_objectname[ firstname ] = curobj;
curobj->SetDispName( firstname );
}
}
}
return 0;
}
int CModel::DbgDump()
{
DbgOut( L"######start DbgDump\r\n" );
DbgOut( L"Dump Bone And InfScope\r\n" );
if( m_topbone ){
DbgDumpBoneReq( m_topbone, 0 );
}
// MultiByteToWideChar( CP_ACP, MB_PRECOMPOSED, name, 256, wname, 256 );
DbgOut( L"######end DbgDump\r\n" );
return 0;
}
int CModel::DbgDumpBoneReq( CBone* boneptr, int broflag )
{
char mes[1024];
WCHAR wmes[1024];
if( boneptr->GetParent() ){
sprintf_s( mes, 1024, "\tboneno %d, bonename %s - parent %s\r\n", boneptr->GetBoneName(), boneptr->GetBoneName(), boneptr->GetParent()->GetBoneName() );
}else{
sprintf_s( mes, 1024, "\tboneno %d, bonename %s - parent NONE\r\n", boneptr->GetBoneNo(), boneptr->GetBoneName() );
}
MultiByteToWideChar( CP_ACP, MB_PRECOMPOSED, mes, 1024, wmes, 1024 );
DbgOut( wmes );
DbgOut( L"\t\tbonepos (%f, %f, %f), (%f, %f, %f)\r\n",
boneptr->GetJointWPos().x, boneptr->GetJointWPos().y, boneptr->GetJointWPos().z,
boneptr->GetJointFPos().x, boneptr->GetJointFPos().y, boneptr->GetJointFPos().z );
//DbgOut( L"\t\tinfscopenum %d\r\n", boneptr->m_isnum );
//int isno;
//for( isno = 0; isno < boneptr->m_isnum; isno++ ){
// CInfScope* curis = boneptr->m_isarray[ isno ];
// CBone* infbone = 0;
// if( curis->m_applyboneno >= 0 ){
// infbone = m_bonelist[ curis->m_applyboneno ];
// sprintf_s( mes, 1024, "\t\tInfScope %d, validflag %d, facenum %d, applybone %s\r\n",
// isno, curis->m_validflag, curis->m_facenum, infbone->m_bonename );
// MultiByteToWideChar( CP_ACP, MB_PRECOMPOSED, mes, 1024, wmes, 1024 );
// DbgOut( wmes );
// }else{
// DbgOut( L"\t\tInfScope %d, validflag %d, facenum %d, applybone is none\r\n",
// isno, curis->m_validflag, curis->m_facenum );
// }
//
// if( curis->m_targetobj ){
// sprintf_s( mes, 1024, "\t\t\ttargetobj %s\r\n", curis->m_targetobj->m_name );
// MultiByteToWideChar( CP_ACP, MB_PRECOMPOSED, mes, 1024, wmes, 1024 );
// DbgOut( wmes );
// }else{
// DbgOut( L"\t\t\ttargetobj is none\r\n" );
// }
//}
//////////
if( boneptr->GetChild() ){
DbgDumpBoneReq( boneptr->GetChild(), 1 );
}
if( (broflag == 1) && boneptr->GetBrother() ){
DbgDumpBoneReq( boneptr->GetBrother(), 1 );
}
return 0;
}
int CModel::MakePolyMesh3()
{
map<int,CMQOObject*>::iterator itr;
for( itr = m_object.begin(); itr != m_object.end(); itr++ ){
CMQOObject* curobj = itr->second;
if( curobj ){
CallF( curobj->MakePolymesh3( m_pdev, m_material ), return 1 );
}
}
return 0;
}
int CModel::MakePolyMesh4()
{
map<int,CMQOObject*>::iterator itr;
for( itr = m_object.begin(); itr != m_object.end(); itr++ ){
CMQOObject* curobj = itr->second;
if( curobj ){
CallF( curobj->MakePolymesh4( m_pdev ), return 1 );
}
}
return 0;
}
int CModel::MakeExtLine()
{
map<int,CMQOObject*>::iterator itr;
for( itr = m_object.begin(); itr != m_object.end(); itr++ ){
CMQOObject* curobj = itr->second;
if( curobj ){
CallF( curobj->MakeExtLine(), return 1 );
}
}
return 0;
}
int CModel::MakeDispObj()
{
int hasbone;
if( m_bonelist.empty() ){
hasbone = 0;
}else{
hasbone = 1;
}
map<int,CMQOObject*>::iterator itr;
for( itr = m_object.begin(); itr != m_object.end(); itr++ ){
CMQOObject* curobj = itr->second;
if( curobj ){
CallF( curobj->MakeDispObj( m_pdev, m_material, hasbone ), return 1 );
}
}
return 0;
}
int CModel::Motion2Bt( int firstflag, CModel* coldisp[COL_MAX], double nextframe, ChaMatrix* mW, ChaMatrix* mVP )
{
UpdateMatrix( mW, mVP );
if( m_topbt ){
SetBtKinFlagReq( m_topbt, 0 );
}
if( firstflag == 1 ){
map<int, CBone*>::iterator itrbone;
for( itrbone = m_bonelist.begin(); itrbone != m_bonelist.end(); itrbone++ ){
CBone* boneptr = itrbone->second;
if( boneptr ){
boneptr->SetStartMat2( boneptr->GetCurMp().GetWorldMat() );
}
}
}
if( !m_topbt ){
return 0;
}
map<int, CBone*>::iterator itrbone;
for( itrbone = m_bonelist.begin(); itrbone != m_bonelist.end(); itrbone++ ){
CBone* boneptr = itrbone->second;
if( boneptr ){
std::map<CBone*, CRigidElem*> tmpmap;
boneptr->GetRigidElemMap( tmpmap );
map<CBone*,CRigidElem*>::iterator itrre;
for( itrre = tmpmap.begin(); itrre != tmpmap.end(); itrre++ ){
CRigidElem* curre = itrre->second;
if( curre && (curre->GetSkipflag() != 1) ){
CBone* chilbone = itrre->first;
_ASSERT( chilbone );
boneptr->CalcRigidElemParams( coldisp, chilbone, firstflag );
}
}
}
}
/***
CBone* chkbone1 = m_bonename[ "FLOAT_BT_twinte1_L__Joint" ];
_ASSERT( chkbone1 );
CBone* chkbone2 = m_bonename[ "atama_Joint_bunki" ];
_ASSERT( chkbone2 );
DbgOut( L"check kinflag !!!! : previewflag %d, float kinflag %d, bunki kinflag %d\r\n",
g_previewFlag, chkbone1->m_btkinflag, chkbone2->m_btkinflag );
***/
Motion2BtReq( m_topbt );
// if (m_topbone){
// SetBtEquilibriumPointReq(m_topbone);
// }
return 0;
}
void CModel::Motion2BtReq( CBtObject* srcbto )
{
if( srcbto->GetBone() && (srcbto->GetBone()->GetBtKinFlag() == 1) ){
srcbto->Motion2Bt();
}
int chilnum = srcbto->GetChilBtSize();
int chilno;
for( chilno = 0; chilno < chilnum; chilno++ ){
Motion2BtReq( srcbto->GetChilBt( chilno ) );
}
}
int CModel::UpdateMatrix( ChaMatrix* wmat, ChaMatrix* vpmat )
{
m_matWorld = *wmat;
m_matVP = *vpmat;
if( !m_curmotinfo ){
return 0;//!!!!!!!!!!!!
}
int curmotid = m_curmotinfo->motid;
double curframe = m_curmotinfo->curframe;
// ChaMatrix inimat;
// ChaMatrixIdentity( &inimat );
// CQuaternion iniq;
// iniq.SetParams( 1.0f, 0.0f, 0.0f, 0.0f );
map<int, CBone*>::iterator itrbone;
for( itrbone = m_bonelist.begin(); itrbone != m_bonelist.end(); itrbone++ ){
CBone* curbone = itrbone->second;
if( curbone ){
curbone->UpdateMatrix( curmotid, curframe, wmat, vpmat );
}
}
/*
// for morph anim
//groundのUpdateMatrixでエラー
int chkcnt = 0;
int motionorder = -1;
map<int, MOTINFO*>::iterator itrmi;
for( itrmi = m_motinfo.begin(); itrmi != m_motinfo.end(); itrmi++ ){
MOTINFO* chkmi = itrmi->second;
if( chkmi ){
if( chkmi->motid == m_curmotinfo->motid ){
motionorder = chkcnt;
break;
}
}
chkcnt++;
}
if( motionorder < 0 ){
_ASSERT( 0 );
return 1;
}
//読み込み時にアニメがなければ以下はスキップ
const int lAnimStackCount = mAnimStackNameArray.GetCount();
if (lAnimStackCount <= 0){
//_ASSERT(0);
return 0;
}
FbxAnimStack * lCurrentAnimationStack = m_pscene->FindMember<FbxAnimStack>(mAnimStackNameArray[motionorder]->Buffer());
if (lCurrentAnimationStack == NULL){
_ASSERT( 0 );
return 1;
}
FbxAnimLayer * mCurrentAnimLayer;
mCurrentAnimLayer = lCurrentAnimationStack->GetMember<FbxAnimLayer>();
FbxTime lTime;
lTime.SetSecondDouble( m_curmotinfo->curframe / 30.0 );
//lTime.SetSecondDouble( m_curmotinfo->curframe / 300.0 );
map<int, CMQOObject*>::iterator itrobj;
for( itrobj = m_object.begin(); itrobj != m_object.end(); itrobj++ ){
CMQOObject* curobj = itrobj->second;
_ASSERT( curobj );
if( !(curobj->EmptyFindShape()) ){
GetShapeWeight( m_fbxobj[curobj].node, m_fbxobj[curobj].mesh, lTime, mCurrentAnimLayer, curobj );
CallF( curobj->UpdateMorphBuffer(), return 1 );
}
}
*/
return 0;
}
/***
int CModel::ComputeShapeDeformation(FbxNode* pNode, FbxMesh* pMesh, FbxTime& pTime, FbxAnimLayer * pAnimLayer, CMQOObject* curobj, char* takename )
{
int lVertexCount = pMesh->GetControlPointsCount();
if( lVertexCount != curobj->m_vertex ){
_ASSERT( 0 );
return 1;
}
MoveMemory( curobj->m_mpoint, curobj->m_pointbuf, sizeof( ChaVector3 ) * lVertexCount );
int lBlendShapeDeformerCount = pMesh->GetDeformerCount(FbxDeformer::eBlendShape);
for(int lBlendShapeIndex = 0; lBlendShapeIndex<lBlendShapeDeformerCount; ++lBlendShapeIndex)
{
FbxBlendShape* lBlendShape = (FbxBlendShape*)pMesh->GetDeformer(lBlendShapeIndex, FbxDeformer::eBlendShape);
int lBlendShapeChannelCount = lBlendShape->GetBlendShapeChannelCount();
for(int lChannelIndex = 0; lChannelIndex<lBlendShapeChannelCount; lChannelIndex++)
{
FbxBlendShapeChannel* lChannel = lBlendShape->GetBlendShapeChannel(lChannelIndex);
if(lChannel)
{
// Get the percentage of influence of the shape.
FbxAnimCurve* lFCurve;
double lWeight = 0.0;
lFCurve = pMesh->GetShapeChannel(lBlendShapeIndex, lChannelIndex, pAnimLayer);
if (lFCurve){
lWeight = lFCurve->Evaluate(pTime);
}else{
continue;
}
if( lWeight == 0.0 ){
continue;
}
//Find which shape should we use according to the weight.
int lShapeCount = lChannel->GetTargetShapeCount();
double* lFullWeights = lChannel->GetTargetShapeFullWeights();
for(int lShapeIndex = 0; lShapeIndex<lShapeCount; lShapeIndex++)
{
FbxShape* lShape = NULL;
lShape = lChannel->GetTargetShape(lShapeIndex);//lShapeIndex+1ではない!!!!!!!!!!!!!!!!
if(lShape)
{
FbxVector4* shapev = lShape->GetControlPoints();
for (int j = 0; j < lVertexCount; j++)
{
// Add the influence of the shape vertex to the mesh vertex.
ChaVector3 xv;
ChaVector3 diffpoint;
xv.x = (float)shapev[j][0];
xv.y = (float)shapev[j][1];
xv.z = (float)shapev[j][2];
diffpoint = (xv - *(curobj->m_pointbuf + j)) * (float)lWeight * 0.01f;
*(curobj->m_mpoint + j) += diffpoint;
}
}
}//For each target shape
}//If lChannel is valid
}//For each blend shape channel
}//For each blend shape deformer
return 0;
}
***/
int CModel::GetFBXShape( FbxMesh* pMesh, CMQOObject* curobj, FbxAnimLayer* panimlayer, int animleng, FbxTime starttime, FbxTime timestep )
{
int lVertexCount = pMesh->GetControlPointsCount();
if( lVertexCount != curobj->GetVertex() ){
_ASSERT( 0 );
return 1;
}
curobj->DestroyShapeObj();
int lBlendShapeDeformerCount = pMesh->GetDeformerCount(FbxDeformer::eBlendShape);
for(int lBlendShapeIndex = 0; lBlendShapeIndex<lBlendShapeDeformerCount; ++lBlendShapeIndex)
{
FbxBlendShape* lBlendShape = (FbxBlendShape*)pMesh->GetDeformer(lBlendShapeIndex, FbxDeformer::eBlendShape);
int lBlendShapeChannelCount = lBlendShape->GetBlendShapeChannelCount();
for(int lChannelIndex = 0; lChannelIndex<lBlendShapeChannelCount; lChannelIndex++)
{
FbxBlendShapeChannel* lChannel = lBlendShape->GetBlendShapeChannel(lChannelIndex);
if(lChannel)
{
FbxTime curtime = starttime;
int framecnt;
for( framecnt = 0; framecnt < animleng; framecnt++ ){
FbxAnimCurve* lFCurve;
double lWeight = 0.0;
lFCurve = pMesh->GetShapeChannel(lBlendShapeIndex, lChannelIndex, panimlayer);
if (lFCurve){
lWeight = lFCurve->Evaluate( curtime );
}else{
curtime += timestep;
continue;
}
if( lWeight == 0.0 ){
curtime += timestep;
continue;
}
int lShapeIndex = 0;
FbxShape* lShape = NULL;
lShape = lChannel->GetTargetShape(lShapeIndex);//lShapeIndex+1ではない!!!!!!!!!!!!!!!!
if(lShape)
{
const char* nameptr = lChannel->GetName();
int existshape = 0;
existshape = curobj->ExistShape( (char*)nameptr );
if( existshape == 0 ){
curobj->AddShapeName( (char*)nameptr );
//WCHAR wcurname[256]={0L};
//WCHAR wobjname[256]={0L};
//ZeroMemory( wcurname, sizeof( WCHAR ) * 256 );
//MultiByteToWideChar( CP_ACP, MB_PRECOMPOSED, (char*)nameptr, 256, wcurname, 256 );
//ZeroMemory( wobjname, sizeof( WCHAR ) * 256 );
//MultiByteToWideChar( CP_ACP, MB_PRECOMPOSED, (char*)curobj->m_name, 256, wobjname, 256 );
//DbgOut( L"addmorph : objname %s, targetname %s\r\n",
// wobjname, wcurname );
FbxVector4* shapev = lShape->GetControlPoints();
_ASSERT( shapev );
for (int j = 0; j < lVertexCount; j++)
{
ChaVector3 xv;
xv.x = (float)shapev[j][0];
xv.y = (float)shapev[j][1];
xv.z = (float)shapev[j][2];
curobj->SetShapeVert( (char*)nameptr, j, xv );
}
}
}
curtime += timestep;
}
}//If lChannel is validf
}//For each blend shape channel
}//For each blend shape deformer
return 0;
}
// Deform the vertex array with the shapes contained in the mesh.
int CModel::GetShapeWeight(FbxNode* pNode, FbxMesh* pMesh, FbxTime& pTime, FbxAnimLayer * pAnimLayer, CMQOObject* curobj )
{
int lVertexCount = pMesh->GetControlPointsCount();
if( lVertexCount != curobj->GetVertex() ){
_ASSERT( 0 );
return 1;
}
curobj->InitShapeWeight();
int lBlendShapeDeformerCount = pMesh->GetDeformerCount(FbxDeformer::eBlendShape);
for(int lBlendShapeIndex = 0; lBlendShapeIndex<lBlendShapeDeformerCount; ++lBlendShapeIndex)
{
FbxBlendShape* lBlendShape = (FbxBlendShape*)pMesh->GetDeformer(lBlendShapeIndex, FbxDeformer::eBlendShape);
int lBlendShapeChannelCount = lBlendShape->GetBlendShapeChannelCount();
for(int lChannelIndex = 0; lChannelIndex<lBlendShapeChannelCount; lChannelIndex++)
{
FbxBlendShapeChannel* lChannel = lBlendShape->GetBlendShapeChannel(lChannelIndex);
if(lChannel)
{
const char* nameptr = lChannel->GetName();
// Get the percentage of influence of the shape.
FbxAnimCurve* lFCurve;
double lWeight = 0.0;
lFCurve = pMesh->GetShapeChannel(lBlendShapeIndex, lChannelIndex, pAnimLayer);
if (lFCurve){
lWeight = lFCurve->Evaluate(pTime);
}else{
continue;
}
if( lWeight == 0.0 ){
continue;
}
//Find which shape should we use according to the weight.
int lShapeCount = lChannel->GetTargetShapeCount();
double* lFullWeights = lChannel->GetTargetShapeFullWeights();
for(int lShapeIndex = 0; lShapeIndex < lShapeCount; lShapeIndex++)
{
FbxShape* lShape = NULL;
lShape = lChannel->GetTargetShape(lShapeIndex);//lShapeIndex+1ではない!!!!!!!!!!!!!!!!
if(lShape)
{
curobj->SetShapeWeight( (char*)nameptr, (float)lWeight );
//double curframe = m_curmotinfo->curframe;
//WCHAR wtargetname[256]={0L};
//MultiByteToWideChar( CP_ACP, MB_PRECOMPOSED, (char*)nameptr, 256, wtargetname, 256 );
//DbgOut( L"weight check !!! : target %s, frame %f, weight %f\r\n",
// wtargetname, curframe, (float)lWeight );
}
}//For each target shape
}//If lChannel is valid
}//For each blend shape channel
}//For each blend shape deformer
return 0;
}
int CModel::SetShaderConst( CMQOObject* srcobj, int btflag )
{
if( !m_topbone ){
return 0;//!!!!!!!!!!!
}
float set3x4[MAXCLUSTERNUM][12];
ZeroMemory( set3x4, sizeof( float ) * 12 * MAXCLUSTERNUM );
int setclcnt = 0;
int clcnt;
for( clcnt = 0; clcnt < (int)srcobj->GetClusterSize(); clcnt++ ){
CBone* curbone = srcobj->GetCluster( clcnt );
if( !curbone ){
_ASSERT( 0 );
return 1;
}
CMotionPoint tmpmp = curbone->GetCurMp();
if( btflag == 0 ){
set3x4[clcnt][0] = tmpmp.GetWorldMat()._11;
set3x4[clcnt][1] = tmpmp.GetWorldMat()._12;
set3x4[clcnt][2] = tmpmp.GetWorldMat()._13;
set3x4[clcnt][3] = tmpmp.GetWorldMat()._21;
set3x4[clcnt][4] = tmpmp.GetWorldMat()._22;
set3x4[clcnt][5] = tmpmp.GetWorldMat()._23;
set3x4[clcnt][6] = tmpmp.GetWorldMat()._31;
set3x4[clcnt][7] = tmpmp.GetWorldMat()._32;
set3x4[clcnt][8] = tmpmp.GetWorldMat()._33;
set3x4[clcnt][9] = tmpmp.GetWorldMat()._41;
set3x4[clcnt][10] = tmpmp.GetWorldMat()._42;
set3x4[clcnt][11] = tmpmp.GetWorldMat()._43;
}else{
set3x4[clcnt][0] = tmpmp.GetBtMat()._11;
set3x4[clcnt][1] = tmpmp.GetBtMat()._12;
set3x4[clcnt][2] = tmpmp.GetBtMat()._13;
set3x4[clcnt][3] = tmpmp.GetBtMat()._21;
set3x4[clcnt][4] = tmpmp.GetBtMat()._22;
set3x4[clcnt][5] = tmpmp.GetBtMat()._23;
set3x4[clcnt][6] = tmpmp.GetBtMat()._31;
set3x4[clcnt][7] = tmpmp.GetBtMat()._32;
set3x4[clcnt][8] = tmpmp.GetBtMat()._33;
set3x4[clcnt][9] = tmpmp.GetBtMat()._41;
set3x4[clcnt][10] = tmpmp.GetBtMat()._42;
set3x4[clcnt][11] = tmpmp.GetBtMat()._43;
}
setclcnt++;
}
if( setclcnt > 0 ){
HRESULT hr;
hr = g_pEffect->SetValue( g_hm3x4Mat, (void*)set3x4, sizeof( float ) * 12 * MAXCLUSTERNUM );
if(FAILED(hr)){
_ASSERT( 0 );
return 1;
}
}
return 0;
}
int CModel::FillTimeLine( OrgWinGUI::OWP_Timeline& timeline, map<int, int>& lineno2boneno, map<int, int>& boneno2lineno )
{
lineno2boneno.erase( lineno2boneno.begin(), lineno2boneno.end() );
boneno2lineno.erase( boneno2lineno.begin(), boneno2lineno.end() );
if( m_bonelist.empty() ){
return 0;
}
int lineno = 0;
map<int, CBone*>::iterator itrbone;
for( itrbone = m_bonelist.begin(); itrbone != m_bonelist.end(); itrbone++ ){
CBone* curbone = itrbone->second;
_ASSERT( curbone );
//行を追加
if( curbone->GetType() != FBXBONE_NULL ){
timeline.newLine( 0, curbone->GetWBoneName() );
}else{
timeline.newLine( 1, curbone->GetWBoneName() );
}
lineno2boneno[ lineno ] = curbone->GetBoneNo();
boneno2lineno[ curbone->GetBoneNo() ] = lineno;
lineno++;
/***
_ASSERT( m_curmotinfo );
CMotionPoint* curmp = curbone->m_motionkey[ m_curmotinfo->motid ];
while( curmp ){
timeline.newKey( curbone->m_wbonename, curmp->m_frame, (void*)curmp );
curmp = curmp->m_next;
}
***/
}
/***
int lineno = 0;
FillTimelineReq( timeline, m_topbone, &lineno, lineno2boneno, boneno2lineno, 0 );
***/
//選択行を設定
timeline.setCurrentLineName( m_topbone->GetWBoneName() );
return 0;
}
void CModel::FillTimelineReq( OrgWinGUI::OWP_Timeline& timeline, CBone* curbone, int* linenoptr,
map<int, int>& lineno2boneno, map<int, int>& boneno2lineno, int broflag )
{
//行を追加
if( curbone->GetType() != FBXBONE_NULL ){
timeline.newLine( 0, curbone->GetWBoneName() );
}else{
timeline.newLine( 1, curbone->GetWBoneName() );
}
lineno2boneno[ *linenoptr ] = curbone->GetBoneNo();
boneno2lineno[ curbone->GetBoneNo() ] = *linenoptr;
(*linenoptr)++;
/***
_ASSERT( m_curmotinfo );
CMotionPoint* curmp = curbone->m_motionkey[ m_curmotinfo->motid ];
while( curmp ){
timeline.newKey( curbone->m_wbonename, curmp->m_frame, (void*)curmp );
curmp = curmp->m_next;
}
***/
if( curbone->GetChild() ){
FillTimelineReq( timeline, curbone->GetChild(), linenoptr, lineno2boneno, boneno2lineno, 1 );
}
if( broflag && curbone->GetBrother() ){
FillTimelineReq( timeline, curbone->GetBrother(), linenoptr, lineno2boneno, boneno2lineno, 1 );
}
}
int CModel::AddMotion(char* srcname, WCHAR* wfilename, double srcleng, int* dstid)
{
*dstid = -1;
int leng = (int)strlen(srcname);
int maxid = 0;
map<int, MOTINFO*>::iterator itrmi;
for (itrmi = m_motinfo.begin(); itrmi != m_motinfo.end(); itrmi++){
MOTINFO* chkmi = itrmi->second;
if (chkmi){
if (maxid < chkmi->motid){
maxid = chkmi->motid;
}
}
}
int newid = maxid + 1;
MOTINFO* newmi = (MOTINFO*)malloc(sizeof(MOTINFO));
if (!newmi){
_ASSERT(0);
return 1;
}
ZeroMemory(newmi, sizeof(MOTINFO));
strcpy_s(newmi->motname, 256, srcname);
if (wfilename){
wcscpy_s(newmi->wfilename, MAX_PATH, wfilename);
}
else{
ZeroMemory(newmi->wfilename, sizeof(WCHAR)* MAX_PATH);
}
ZeroMemory(newmi->engmotname, sizeof(char)* 256);
newmi->motid = newid;
newmi->frameleng = srcleng;
newmi->curframe = 0.0;
newmi->speed = 1.0;
newmi->loopflag = 1;
m_motinfo[newid] = newmi;
*dstid = newid;
return 0;
}
int CModel::SetCurrentMotion( int srcmotid )
{
m_curmotinfo = m_motinfo[ srcmotid ];
if( !m_curmotinfo ){
_ASSERT( 0 );
return 1;
}else{
return 0;
}
}
int CModel::SetMotionFrame( double srcframe )
{
if( !m_curmotinfo ){
_ASSERT( 0 );
return 1;
}
m_curmotinfo->curframe = max( 0.0, min( (m_curmotinfo->frameleng - 1), srcframe ) );
return 0;
}
int CModel::GetMotionFrame( double* dstframe )
{
if( !m_curmotinfo ){
_ASSERT( 0 );
return 1;
}
*dstframe = m_curmotinfo->curframe;
return 0;
}
int CModel::SetMotionSpeed( double srcspeed )
{
if( !m_curmotinfo ){
_ASSERT( 0 );
return 1;
}
m_curmotinfo->speed = srcspeed;
return 0;
}
int CModel::GetMotionSpeed( double* dstspeed )
{
if( !m_curmotinfo ){
_ASSERT( 0 );
return 1;
}
*dstspeed = m_curmotinfo->speed;
return 0;
}
int CModel::DeleteMotion( int motid )
{
map<int, CBone*>::iterator itrbone;
for( itrbone = m_bonelist.begin(); itrbone != m_bonelist.end(); itrbone++ ){
CBone* curbone = itrbone->second;
if( curbone ){
CallF( curbone->DeleteMotion( motid ), return 1 );
}
}
map<int, MOTINFO*>::iterator itrmi;
itrmi = m_motinfo.find( motid );
if( itrmi != m_motinfo.end() ){
MOTINFO* delmi = itrmi->second;
if( delmi ){
delete delmi;
}
m_motinfo.erase( itrmi );
}
int undono;
for( undono = 0; undono < UNDOMAX; undono++ ){
if( m_undomotion[undono].GetSaveMotInfo().motid == motid ){
m_undomotion[undono].SetValidFlag( 0 );
}
}
return 0;
}
int CModel::GetSymBoneNo( int srcboneno, int* dstboneno, int* existptr )
{
*existptr = 0;
CBone* srcbone = m_bonelist[ srcboneno ];
if( !srcbone ){
*dstboneno = -1;
return 0;
}
int findflag = 0;
WCHAR findname[256];
ZeroMemory( findname, sizeof( WCHAR ) * 256 );
wcscpy_s( findname, 256, srcbone->GetWBoneName() );
WCHAR* lpat = wcsstr( findname, L"_L_" );
if( lpat ){
*lpat = TEXT( '_' );
*(lpat + 1) = TEXT( 'R' );
*(lpat + 2) = TEXT( '_' );
//wcsncat_s( findname, 256, L"_R_", 3 );
findflag = 1;
}else{
WCHAR* rpat = wcsstr( findname, L"_R_" );
if( rpat ){
*rpat = TEXT( '_' );
*(rpat + 1) = TEXT( 'L' );
*(rpat + 2) = TEXT( '_' );
//wcsncat_s( findname, 256, L"_L_", 3 );
findflag = 1;
}
}
if( findflag == 0 ){
*dstboneno = srcboneno;
*existptr = 0;
}else{
CBone* dstbone = 0;
map<int, CBone*>::iterator itrbone;
for( itrbone = m_bonelist.begin(); itrbone != m_bonelist.end(); itrbone++ ){
CBone* chkbone = itrbone->second;
if( chkbone && (wcscmp( findname, chkbone->GetWBoneName() ) == 0) ){
dstbone = chkbone;
break;
}
}
if( dstbone ){
*dstboneno = dstbone->GetBoneNo();
*existptr = 1;
}else{
*dstboneno = srcboneno;
*existptr = 0;
}
}
return 0;
}
int CModel::PickBone( PICKINFO* pickinfo )
{
pickinfo->pickobjno = -1;
float fw, fh;
fw = (float)pickinfo->winx / 2.0f;
fh = (float)pickinfo->winy / 2.0f;
int minno = -1;
ChaVector3 cmpsc;
ChaVector3 picksc = ChaVector3( 0.0f, 0.0f, 0.0f );
ChaVector3 pickworld = ChaVector3( 0.0f, 0.0f, 0.0f );
float cmpdist;
float mindist = 0.0f;
int firstflag = 1;
map<int, CBone*>::iterator itrbone;
for( itrbone = m_bonelist.begin(); itrbone != m_bonelist.end(); itrbone++ ){
CBone* curbone = itrbone->second;
if( curbone ){
cmpsc.x = ( 1.0f + curbone->GetChildScreen().x ) * fw;
cmpsc.y = ( 1.0f - curbone->GetChildScreen().y ) * fh;
cmpsc.z = curbone->GetChildScreen().z;
if( (cmpsc.z >= 0.0f) && (cmpsc.z <= 1.0f) ){
float mag;
mag = ( (float)pickinfo->clickpos.x - cmpsc.x ) * ( (float)pickinfo->clickpos.x - cmpsc.x ) +
( (float)pickinfo->clickpos.y - cmpsc.y ) * ( (float)pickinfo->clickpos.y - cmpsc.y );
if( mag != 0.0f ){
cmpdist = sqrtf( mag );
}else{
cmpdist = 0.0f;
}
if( (firstflag || (cmpdist <= mindist)) && (cmpdist <= (float)pickinfo->pickrange ) ){
minno = curbone->GetBoneNo();
mindist = cmpdist;
picksc = cmpsc;
pickworld = curbone->GetChildWorld();
firstflag = 0;
}
}
}
}
pickinfo->pickobjno = minno;
if( minno >= 0 ){
pickinfo->objscreen = picksc;
pickinfo->objworld = pickworld;
}
return 0;
}
void CModel::SetSelectFlagReq( CBone* boneptr, int broflag )
{
boneptr->SetSelectFlag( 1 );
if( boneptr->GetChild() ){
SetSelectFlagReq( boneptr->GetChild(), 1 );
}
if( boneptr->GetBrother() && broflag ){
SetSelectFlagReq( boneptr->GetBrother(), 1 );
}
}
int CModel::CollisionNoBoneObj_Mouse( PICKINFO* pickinfo, char* objnameptr )
{
//当たったら1、当たらなかったら0を返す。エラーも0を返す。
CMQOObject* curobj = m_objectname[ objnameptr ];
if( !curobj ){
_ASSERT( 0 );
return 0;
}
ChaVector3 startlocal, dirlocal;
CalcMouseLocalRay( pickinfo, &startlocal, &dirlocal );
int colli = curobj->CollisionLocal_Ray( startlocal, dirlocal );
return colli;
}
int CModel::CalcMouseLocalRay( PICKINFO* pickinfo, ChaVector3* startptr, ChaVector3* dirptr )
{
ChaVector3 startsc, endsc;
float rayx, rayy;
rayx = (float)pickinfo->clickpos.x / ((float)pickinfo->winx / 2.0f) - 1.0f;
rayy = 1.0f - (float)pickinfo->clickpos.y / ((float)pickinfo->winy / 2.0f);
startsc = ChaVector3( rayx, rayy, 0.0f );
endsc = ChaVector3( rayx, rayy, 1.0f );
ChaMatrix mWVP, invmWVP;
mWVP = m_matWorld * m_matVP;
ChaMatrixInverse( &invmWVP, NULL, &mWVP );
ChaVector3 startlocal, endlocal;
ChaVector3TransformCoord( &startlocal, &startsc, &invmWVP );
ChaVector3TransformCoord( &endlocal, &endsc, &invmWVP );
ChaVector3 dirlocal = endlocal - startlocal;
ChaVector3Normalize( &dirlocal, &dirlocal );
*startptr = startlocal;
*dirptr = dirlocal;
return 0;
}
CBone* CModel::GetCalcRootBone( CBone* firstbone, int maxlevel )
{
int levelcnt = 0;
CBone* retbone = firstbone;
CBone* curbone = firstbone;
while( curbone && ((maxlevel == 0) || (levelcnt <= maxlevel)) )
{
retbone = curbone;
curbone = curbone->GetParent();
levelcnt++;
}
return retbone;
}
int CModel::TransformBone( int winx, int winy, int srcboneno, ChaVector3* worldptr, ChaVector3* screenptr, ChaVector3* dispptr )
{
CBone* curbone;
curbone = m_bonelist[ srcboneno ];
*worldptr = curbone->GetChildWorld();
ChaMatrix mWVP = curbone->GetCurMp().GetWorldMat() * m_matVP;
ChaVector3TransformCoord( screenptr, &curbone->GetJointFPos(), &mWVP );
float fw, fh;
fw = (float)winx / 2.0f;
fh = (float)winy / 2.0f;
dispptr->x = ( 1.0f + screenptr->x ) * fw;
dispptr->y = ( 1.0f - screenptr->y ) * fh;
dispptr->z = screenptr->z;
return 0;
}
int CModel::ChangeMotFrameLeng( int motid, double srcleng )
{
MOTINFO* dstmi = m_motinfo[ motid ];
if( dstmi ){
double befleng = dstmi->frameleng;
dstmi->frameleng = srcleng;
if( befleng > srcleng ){
map<int, CBone*>::iterator itrbone;
for( itrbone = m_bonelist.begin(); itrbone != m_bonelist.end(); itrbone++ ){
CBone* curbone = itrbone->second;
if( curbone ){
curbone->DeleteMPOutOfRange( motid, srcleng - 1.0 );
}
}
}
}
return 0;
}
int CModel::AdvanceTime( int previewflag, double difftime, double* nextframeptr, int* endflagptr, int srcmotid )
{
*endflagptr = 0;
int loopflag = 0;
MOTINFO* curmotinfo;
if( srcmotid >= 0 ){
curmotinfo = m_motinfo[ srcmotid ];
loopflag = 0;
}else{
curmotinfo = m_curmotinfo;
loopflag = curmotinfo->loopflag;
}
if( !curmotinfo ){
return 0;
}
double curspeed, curframe;
curspeed = curmotinfo->speed;
curframe = curmotinfo->curframe;
double nextframe;
double oneframe = 1.0 / 30.0;
//double oneframe = 1.0 / 300.0;
if( previewflag > 0 ){
nextframe = curframe + difftime / oneframe * curspeed;
if( nextframe > ( curmotinfo->frameleng - 1.0 ) ){
if( loopflag == 0 ){
nextframe = curmotinfo->frameleng - 1.0;
*endflagptr = 1;
}else{
nextframe = 0.0;
}
}
}else{
nextframe = curframe - difftime / oneframe * curspeed;
if( nextframe < 0.0 ){
if( loopflag == 0 ){
nextframe = 0.0;
*endflagptr = 1;
}else{
nextframe = curmotinfo->frameleng - 1.0;
}
}
}
*nextframeptr = nextframe;
return 0;
}
int CModel::MakeEnglishName()
{
map<int, CMQOObject*>::iterator itrobj;
for( itrobj = m_object.begin(); itrobj != m_object.end(); itrobj++ ){
CMQOObject* curobj = itrobj->second;
if( curobj ){
CallF( ConvEngName( ENGNAME_DISP, (char*)curobj->GetName(), 256, (char*)curobj->GetEngName(), 256 ), return 1 );
}
}
map<int, CBone*>::iterator itrbone;
for( itrbone = m_bonelist.begin(); itrbone != m_bonelist.end(); itrbone++ ){
CBone* curbone = itrbone->second;
if( curbone ){
CallF( ConvEngName( ENGNAME_BONE, (char*)curbone->GetBoneName(), 256, (char*)curbone->GetEngBoneName(), 256 ), return 1 );
}
}
map<int, MOTINFO*>::iterator itrmi;
for( itrmi = m_motinfo.begin(); itrmi != m_motinfo.end(); itrmi++ ){
MOTINFO* curmi = itrmi->second;
if( curmi ){
CallF( ConvEngName( ENGNAME_MOTION, curmi->motname, 256, curmi->engmotname, 256 ), return 1 );
}
}
return 0;
}
int CModel::AddDefMaterial()
{
CMQOMaterial* dummymat = new CMQOMaterial();
if( !dummymat ){
_ASSERT( 0 );
return 1;
}
int defmaterialno = m_material.size();
dummymat->SetMaterialNo( defmaterialno );
dummymat->SetName( "dummyMaterial" );
m_material[defmaterialno] = dummymat;
return 0;
}
int CModel::CreateFBXMeshReq( FbxNode* pNode )
{
FbxNodeAttribute *pAttrib = pNode->GetNodeAttribute();
if ( pAttrib ) {
FbxNodeAttribute::EType type = pAttrib->GetAttributeType();
FbxGeometryConverter lConverter(pNode->GetFbxManager());
char mes[256];
int shapecnt;
CMQOObject* newobj = 0;
switch ( type )
{
case FbxNodeAttribute::eMesh:
newobj = GetFBXMesh( pNode, pAttrib, pNode->GetName() ); // メッシュを作成
if (newobj){
shapecnt = pNode->GetMesh()->GetShapeCount();
if (shapecnt > 0){
sprintf_s(mes, 256, "%s, shapecnt %d", pNode->GetName(), shapecnt);
MessageBoxA(NULL, mes, "check", MB_OK);
}
}
break;
// case FbxNodeAttribute::eNURB:
// case FbxNodeAttribute::eNURBS_SURFACE:
// lConverter.TriangulateInPlace(pNode);
// GetFBXMesh( pAttrib, pNode->GetName() ); // メッシュを作成
break;
default:
break;
}
}
int childNodeNum;
childNodeNum = pNode->GetChildCount();
for ( int i = 0; i < childNodeNum; i++ )
{
FbxNode *pChild = pNode->GetChild(i); // 子ノードを取得
CreateFBXMeshReq( pChild );
}
return 0;
}
int CModel::CreateFBXShape( FbxAnimLayer* panimlayer, int animleng, FbxTime starttime, FbxTime timestep )
{
map<CMQOObject*,FBXOBJ>::iterator itrobjindex;
for( itrobjindex = m_fbxobj.begin(); itrobjindex != m_fbxobj.end(); itrobjindex++ ){
FBXOBJ curfbxobj = itrobjindex->second;
FbxMesh* curmesh = curfbxobj.mesh;
CMQOObject* curobj = itrobjindex->first;
if( curmesh && curobj ){
int shapecnt = curmesh->GetShapeCount();
if( shapecnt > 0 ){
CallF( GetFBXShape( curmesh, curobj, panimlayer, animleng, starttime, timestep ), return 1 );
}
}
}
return 0;
}
CMQOObject* CModel::GetFBXMesh( FbxNode* pNode, FbxNodeAttribute *pAttrib, const char* nodename )
{
FbxMesh *pMesh = (FbxMesh*)pAttrib;
if (strcmp("RootNode", pAttrib->GetName()) == 0){
_ASSERT(0);
return 0;
}
CMQOObject* newobj = new CMQOObject();
_ASSERT( newobj );
newobj->SetObjFrom( OBJFROM_FBX );
newobj->SetName( (char*)nodename );
m_object[ newobj->GetObjectNo() ] = newobj;
WCHAR wname[256];
ZeroMemory( wname, sizeof( WCHAR ) * 256 );
MultiByteToWideChar( CP_ACP, MB_PRECOMPOSED, nodename, 256, wname, 256 );
FBXOBJ fbxobj;
fbxobj.node = pNode;
fbxobj.mesh = pMesh;
m_fbxobj[newobj] = fbxobj;
//shape
// int morphnum = pMesh->GetShapeCount();
// newobj->m_morphnum = morphnum;
//マテリアル
FbxNode* node = pMesh->GetNode();
if ( node != 0 ) {
// マテリアルの数
int materialNum_ = node->GetMaterialCount();
// マテリアル情報を取得
for( int i = 0; i < materialNum_; ++i ) {
FbxSurfaceMaterial* material = node->GetMaterial( i );
if ( material != 0 ) {
CMQOMaterial* newmqomat = new CMQOMaterial();
int mqomatno = newobj->GetMaterialSize();
newmqomat->SetMaterialNo( mqomatno );
newobj->SetMaterial( mqomatno, newmqomat );
SetMQOMaterial( newmqomat, material );
}
}
}
//頂点
int PolygonNum = pMesh->GetPolygonCount();
int PolygonVertexNum = pMesh->GetPolygonVertexCount();
int *IndexAry = pMesh->GetPolygonVertices();
int controlNum = pMesh->GetControlPointsCount(); // 頂点数
FbxVector4* src = pMesh->GetControlPoints(); // 頂点座標配列
// コピー
newobj->SetVertex( controlNum );
newobj->SetPointBuf( (ChaVector3*)malloc( sizeof( ChaVector3 ) * controlNum ) );
for ( int i = 0; i < controlNum; ++i ) {
ChaVector3* curctrl = newobj->GetPointBuf() + i;
curctrl->x = (float)src[ i ][ 0 ];
curctrl->y = (float)src[ i ][ 1 ];
curctrl->z = (float)src[ i ][ 2 ];
//curctrl->w = (float)src[ i ][ 3 ];
//DbgOut( L"GetFBXMesh : ctrl %d, (%f, %f, %f)\r\n",
// i, curctrl->x, curctrl->y, curctrl->z );
}
newobj->SetFace( PolygonNum );
newobj->SetFaceBuf( new CMQOFace[ PolygonNum ] );
for ( int p = 0; p < PolygonNum; p++ ) {
int IndexNumInPolygon = pMesh->GetPolygonSize( p ); // p番目のポリゴンの頂点数
if( (IndexNumInPolygon != 3) && (IndexNumInPolygon != 4) ){
_ASSERT( 0 );
return 0;
}
CMQOFace* curface = newobj->GetFaceBuf() + p;
curface->SetPointNum( IndexNumInPolygon );
for ( int n = 0; n < IndexNumInPolygon; n++ ) {
// ポリゴンpを構成するn番目の頂点のインデックス番号
int IndexNumber = pMesh->GetPolygonVertex( p, n );
curface->SetFaceNo( p );
curface->SetIndex( n, IndexNumber );
curface->SetMaterialNo( 0 );
curface->SetBoneType( MIKOBONE_NONE );
}
}
/*
// Populate the array with vertex attribute, if by control point.
const FbxVector4 * lControlPoints = pMesh->GetControlPoints();
FbxVector4 lCurrentVertex;
FbxVector4 lCurrentNormal;
FbxVector2 lCurrentUV;
if (mAllByControlPoint)
{
const FbxGeometryElementNormal * lNormalElement = NULL;
const FbxGeometryElementUV * lUVElement = NULL;
if (mHasNormal)
{
lNormalElement = pMesh->GetElementNormal(0);
}
if (mHasUV)
{
lUVElement = pMesh->GetElementUV(0);
}
for (int lIndex = 0; lIndex < lPolygonVertexCount; ++lIndex)
{
// Save the vertex position.
lCurrentVertex = lControlPoints[lIndex];
lVertices[lIndex * VERTEX_STRIDE] = static_cast<float>(lCurrentVertex[0]);
lVertices[lIndex * VERTEX_STRIDE + 1] = static_cast<float>(lCurrentVertex[1]);
lVertices[lIndex * VERTEX_STRIDE + 2] = static_cast<float>(lCurrentVertex[2]);
lVertices[lIndex * VERTEX_STRIDE + 3] = 1;
// Save the normal.
if (mHasNormal)
{
int lNormalIndex = lIndex;
if (lNormalElement->GetReferenceMode() == FbxLayerElement::eIndexToDirect)
{
lNormalIndex = lNormalElement->GetIndexArray().GetAt(lIndex);
}
lCurrentNormal = lNormalElement->GetDirectArray().GetAt(lNormalIndex);
lNormals[lIndex * NORMAL_STRIDE] = static_cast<float>(lCurrentNormal[0]);
lNormals[lIndex * NORMAL_STRIDE + 1] = static_cast<float>(lCurrentNormal[1]);
lNormals[lIndex * NORMAL_STRIDE + 2] = static_cast<float>(lCurrentNormal[2]);
}
// Save the UV.
if (mHasUV)
{
int lUVIndex = lIndex;
if (lUVElement->GetReferenceMode() == FbxLayerElement::eIndexToDirect)
{
lUVIndex = lUVElement->GetIndexArray().GetAt(lIndex);
}
lCurrentUV = lUVElement->GetDirectArray().GetAt(lUVIndex);
lUVs[lIndex * UV_STRIDE] = static_cast<float>(lCurrentUV[0]);
lUVs[lIndex * UV_STRIDE + 1] = static_cast<float>(lCurrentUV[1]);
}
}
}
*/
//法線
int layerNum = pMesh->GetLayerCount();
for ( int i = 0; i < layerNum; ++i ) {
FbxLayer* layer = pMesh->GetLayer( i );
FbxLayerElementNormal* normalElem = layer->GetNormals();
if ( normalElem == 0 ) {
continue; // 法線無し
}
// 法線あった!
// 法線の数・インデックス
int normalNum = normalElem->GetDirectArray().GetCount();
int indexNum = normalElem->GetIndexArray().GetCount();
//DbgOut( L"GetFBXMesh : %s : normalNum %d : indexNum %d\r\n", wname, normalNum, indexNum );
// マッピングモード・リファレンスモード取得
FbxLayerElement::EMappingMode mappingMode = normalElem->GetMappingMode();
FbxLayerElement::EReferenceMode refMode = normalElem->GetReferenceMode();
if ( mappingMode == FbxLayerElement::eByPolygonVertex ) {
//DbgOut( L"GetFBXMesh : %s : mapping eByPolygonVertex\r\n", wname );
if ( refMode == FbxLayerElement::eDirect ) {
//DbgOut( L"GetFBXMesh : %s : ref eDirect\r\n", wname );
newobj->SetNormalLeng( normalNum );
newobj->SetNormal( (ChaVector3*)malloc( sizeof( ChaVector3 ) * normalNum ) );
// 直接取得
for ( int i = 0; i < normalNum; ++i ) {
ChaVector3* curn = newobj->GetNormal() + i;
curn->x = (float)normalElem->GetDirectArray().GetAt( i )[ 0 ];
curn->y = (float)normalElem->GetDirectArray().GetAt( i )[ 1 ];
curn->z = (float)normalElem->GetDirectArray().GetAt( i )[ 2 ];
}
}else if ( refMode == FbxLayerElement::eIndexToDirect ){
//DbgOut( L"GetFBXMesh : %s : ref eIndexToDirect\r\n", wname );
newobj->SetNormalLeng( indexNum );
newobj->SetNormal( (ChaVector3*)malloc( sizeof( ChaVector3 ) * indexNum ) );
int lIndex;
for( lIndex = 0; lIndex < indexNum; lIndex++ ){
int lNormalIndex = normalElem->GetIndexArray().GetAt(lIndex);
FbxVector4 lCurrentNormal;
lCurrentNormal = normalElem->GetDirectArray().GetAt(lNormalIndex);
ChaVector3* curn = newobj->GetNormal() + lIndex;
curn->x = static_cast<float>(lCurrentNormal[0]);
curn->y = static_cast<float>(lCurrentNormal[1]);
curn->z = static_cast<float>(lCurrentNormal[2]);
}
}
} else if ( mappingMode == FbxLayerElement::eByControlPoint ) {
//DbgOut( L"GetFBXMesh : %s : mapping eByControlPoint\r\n", wname );
if ( refMode == FbxLayerElement::eDirect ) {
//DbgOut( L"GetFBXMesh : %s : ref eDirect\r\n", wname );
newobj->SetNormalLeng( normalNum );
newobj->SetNormal( (ChaVector3*)malloc( sizeof( ChaVector3 ) * normalNum ) );
// 直接取得
for ( int i = 0; i < normalNum; ++i ) {
ChaVector3* curn = newobj->GetNormal() + i;
curn->x = (float)normalElem->GetDirectArray().GetAt( i )[ 0 ];
curn->y = (float)normalElem->GetDirectArray().GetAt( i )[ 1 ];
curn->z = (float)normalElem->GetDirectArray().GetAt( i )[ 2 ];
}
}else{
//DbgOut( L"GetFBXMesh : %s : ref %d\r\n", wname, refMode );
}
} else {
_ASSERT( 0 );
}
break;
}
//UV
int layerCount = pMesh->GetLayerCount(); // meshはFbxMesh
for ( int uvi = 0; uvi < layerCount; ++uvi ) {
FbxLayer* layer = pMesh->GetLayer( uvi );
FbxLayerElementUV* elem = layer->GetUVs();
if ( elem == 0 ) {
continue;
}
// UV情報を取得
// UVの数・インデックス
int UVNum = elem->GetDirectArray().GetCount();
int indexNum = elem->GetIndexArray().GetCount();
// int size = UVNum > indexNum ? UVNum : indexNum;
// マッピングモード・リファレンスモード別にUV取得
FbxLayerElement::EMappingMode mappingMode = elem->GetMappingMode();
FbxLayerElement::EReferenceMode refMode = elem->GetReferenceMode();
if (mappingMode == FbxLayerElement::eByPolygonVertex) {
DbgOut(L"GetFBXMesh : %s : UV : mapping eByPolygonVertex\r\n", wname);
if (refMode == FbxLayerElement::eDirect) {
DbgOut(L"GetFBXMesh : %s : UV : refMode eDirect\r\n", wname);
int size = UVNum;
newobj->SetUVLeng(size);
newobj->SetUVBuf((D3DXVECTOR2*)malloc(sizeof(D3DXVECTOR2) * size));
// 直接取得
for (int i = 0; i < size; ++i) {
(newobj->GetUVBuf() + i)->x = (float)elem->GetDirectArray().GetAt(i)[0];
(newobj->GetUVBuf() + i)->y = (float)elem->GetDirectArray().GetAt(i)[1];
}
}
else if (refMode == FbxLayerElement::eIndexToDirect) {
DbgOut(L"GetFBXMesh : %s : UV : refMode eIndexToDirect\r\n", wname);
int size = indexNum;
newobj->SetUVLeng(size);
newobj->SetUVBuf((D3DXVECTOR2*)malloc(sizeof(D3DXVECTOR2) * size));
// インデックスから取得
for (int i = 0; i < size; ++i) {
int index = elem->GetIndexArray().GetAt(i);
(newobj->GetUVBuf() + i)->x = (float)elem->GetDirectArray().GetAt(index)[0];
(newobj->GetUVBuf() + i)->y = (float)elem->GetDirectArray().GetAt(index)[1];
}
}
else {
DbgOut(L"GetFBXMesh : %s : UV : refMode %d\r\n", wname, refMode);
}
}
else if (mappingMode == FbxLayerElement::eByControlPoint) {
if (refMode == FbxLayerElement::eDirect) {
DbgOut(L"GetFBXMesh : %s : UV : refMode eDirect\r\n", wname);
int size = UVNum;
newobj->SetUVLeng(size);
newobj->SetUVBuf((D3DXVECTOR2*)malloc(sizeof(D3DXVECTOR2) * size));
// 直接取得
for (int i = 0; i < size; ++i) {
(newobj->GetUVBuf() + i)->x = (float)elem->GetDirectArray().GetAt(i)[0];
(newobj->GetUVBuf() + i)->y = (float)elem->GetDirectArray().GetAt(i)[1];
}
}
} else {
DbgOut( L"GetFBXMesh : %s : UV : mappingMode %d\r\n", wname, mappingMode );
DbgOut( L"GetFBXMesh : %s : UV : refMode %d\r\n", wname, refMode );
}
break;
}
return newobj;
}
int CModel::SetMQOMaterial( CMQOMaterial* newmqomat, FbxSurfaceMaterial* pMaterial )
{
newmqomat->SetName( (char*)pMaterial->GetName() );
char* emitex = 0;
const FbxDouble3 lEmissive = GetMaterialProperty(pMaterial,
FbxSurfaceMaterial::sEmissive, FbxSurfaceMaterial::sEmissiveFactor, &emitex);
if( emitex ){
DbgOut( L"SetMQOMaterial : emitexture find\r\n" );
}
ChaVector3 tmpemi;
tmpemi.x = (float)lEmissive[0];
tmpemi.y = (float)lEmissive[1];
tmpemi.z = (float)lEmissive[2];
newmqomat->SetEmi3F( tmpemi );
char* ambtex = 0;
const FbxDouble3 lAmbient = GetMaterialProperty(pMaterial,
FbxSurfaceMaterial::sAmbient, FbxSurfaceMaterial::sAmbientFactor, &ambtex);
if( ambtex ){
DbgOut( L"SetMQOMaterial : ambtexture find\r\n" );
}
ChaVector3 tmpamb;
tmpamb.x = (float)lAmbient[0];
tmpamb.y = (float)lAmbient[1];
tmpamb.z = (float)lAmbient[2];
newmqomat->SetAmb3F( tmpamb );
char* diffusetex = 0;
const FbxDouble3 lDiffuse = GetMaterialProperty(pMaterial,
FbxSurfaceMaterial::sDiffuse, FbxSurfaceMaterial::sDiffuseFactor, &diffusetex);
if( diffusetex ){
//strcpy_s( newmqomat->tex, 256, diffusetex );
DbgOut( L"SetMQOMaterial : diffusetexture find\r\n" );
}
ChaVector4 tmpdif;
tmpdif.x = (float)lDiffuse[0];
tmpdif.y = (float)lDiffuse[1];
tmpdif.z = (float)lDiffuse[2];
tmpdif.w = 1.0f;//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
newmqomat->SetDif4F( tmpdif );
char* spctex = 0;
const FbxDouble3 lSpecular = GetMaterialProperty(pMaterial,
FbxSurfaceMaterial::sSpecular, FbxSurfaceMaterial::sSpecularFactor, &spctex);
if( spctex ){
DbgOut( L"SetMQOMaterial : spctexture find\r\n" );
}
ChaVector3 tmpspc;
tmpspc.x = (float)lSpecular[0];
tmpspc.y = (float)lSpecular[1];
tmpspc.z = (float)lSpecular[2];
newmqomat->SetSpc3F( tmpspc );
FbxProperty lShininessProperty = pMaterial->FindProperty(FbxSurfaceMaterial::sShininess);
if (lShininessProperty.IsValid())
{
double lShininess = lShininessProperty.Get<FbxDouble>();
newmqomat->SetPower( static_cast<float>(lShininess) );
}
//texture
FbxProperty pProperty;
pProperty = pMaterial->FindProperty( FbxSurfaceMaterial::sDiffuse );
int lLayeredTextureCount = pProperty.GetSrcObjectCount<FbxLayeredTexture>();
if(lLayeredTextureCount > 0)
{
for(int j=0; j<lLayeredTextureCount; ++j)
{
FbxLayeredTexture *lLayeredTexture = pProperty.GetSrcObject<FbxLayeredTexture>(j);
int lNbTextures = lLayeredTexture->GetSrcObjectCount<FbxTexture>();
for(int k =0; k<lNbTextures; ++k)
{
char* nameptr = (char*)lLayeredTexture->GetName();
if( nameptr ){
char tempname[256];
strcpy_s( tempname, 256, nameptr );
char* lastslash = strrchr( tempname, '/' );
if( !lastslash ){
lastslash = strrchr( tempname, '\\' );
}
if( lastslash ){
newmqomat->SetTex( lastslash + 1 );
}else{
newmqomat->SetTex( tempname );
}
char* lastp = strrchr( (char*)newmqomat->GetTex(), '.' );
if( !lastp ){
newmqomat->Add2Tex( ".tga" );
}
WCHAR wname[256];
ZeroMemory( wname, sizeof( WCHAR ) * 256 );
MultiByteToWideChar( CP_ACP, MB_PRECOMPOSED, newmqomat->GetTex(), 256, wname, 256 );
DbgOut( L"SetMQOMaterial : layered texture %s\r\n", wname );
break;
}
}
}
}
else
{
//no layered texture simply get on the property
int lNbTextures = pProperty.GetSrcObjectCount<FbxTexture>();
if(lNbTextures > 0)
{
for(int j =0; j<lNbTextures; ++j)
{
FbxFileTexture* lTexture = pProperty.GetSrcObject<FbxFileTexture>(j);
if(lTexture)
{
char* nameptr = (char*)lTexture->GetFileName();
if( nameptr ){
char tempname[256];
strcpy_s( tempname, 256, nameptr );
char* lastslash = strrchr( tempname, '/' );
if( !lastslash ){
lastslash = strrchr( tempname, '\\' );
}
if( lastslash ){
newmqomat->SetTex( lastslash + 1 );
}else{
newmqomat->SetTex( tempname );
}
char* lastp = strrchr( (char*)newmqomat->GetTex(), '.' );
if( !lastp ){
newmqomat->Add2Tex( ".tga" );
}
WCHAR wname[256];
ZeroMemory( wname, sizeof( WCHAR ) * 256 );
MultiByteToWideChar( CP_ACP, MB_PRECOMPOSED, newmqomat->GetTex(), 256, wname, 256 );
DbgOut( L"SetMQOMaterial : texture %s\r\n", wname );
break;
}
}
}
}
}
return 0;
}
// Get specific property value and connected texture if any.
// Value = Property value * Factor property value (if no factor property, multiply by 1).
FbxDouble3 GetMaterialProperty(const FbxSurfaceMaterial * pMaterial,
const char * pPropertyName,
const char * pFactorPropertyName,
char** ppTextureName)
{
*ppTextureName = 0;
FbxDouble3 lResult(0, 0, 0);
const FbxProperty lProperty = pMaterial->FindProperty(pPropertyName);
const FbxProperty lFactorProperty = pMaterial->FindProperty(pFactorPropertyName);
if (lProperty.IsValid() && lFactorProperty.IsValid())
{
lResult = lProperty.Get<FbxDouble3>();
double lFactor = lFactorProperty.Get<FbxDouble>();
if (lFactor != 1)
{
lResult[0] *= lFactor;
lResult[1] *= lFactor;
lResult[2] *= lFactor;
}
}
return lResult;
}
int CModel::CreateFBXBoneReq( FbxScene* pScene, FbxNode* pNode, FbxNode* parnode )
{
// EFbxRotationOrder lRotationOrder0 = eEulerZXY;
// EFbxRotationOrder lRotationOrder1 = eEulerXYZ;
FbxNodeAttribute *pAttrib = pNode->GetNodeAttribute();
if ( pAttrib ) {
FbxNodeAttribute::EType type = pAttrib->GetAttributeType();
const char* nodename = pNode->GetName();
WCHAR wname[256];
MultiByteToWideChar( CP_ACP, MB_PRECOMPOSED, nodename, -1, wname, 256 );
if( type == FbxNodeAttribute::eSkeleton ){
DbgOut( L"CreateFbxBoneReq : pNode %s : type : skeleton\r\n", wname );
}else if( type == FbxNodeAttribute::eNull ){
DbgOut( L"CreateFbxBoneReq : pNode %s : type : null\r\n", wname );
}else{
DbgOut( L"CreateFbxBoneReq : pNode %s : type : other : %d\r\n", wname, type );
}
FbxNode* parbonenode = 0;
if( parnode ){
FbxNodeAttribute *parattr = parnode->GetNodeAttribute();
if ( parattr ) {
FbxNodeAttribute::EType partype = parattr->GetAttributeType();
const char* parnodename = parnode->GetName();
WCHAR parwname[256];
MultiByteToWideChar( CP_ACP, MB_PRECOMPOSED, parnodename, -1, parwname, 256 );
if( partype == FbxNodeAttribute::eSkeleton ){
DbgOut( L"CreateFbxBoneReq : parnode %s : type : skeleton\r\n", parwname );
}else if( type == FbxNodeAttribute::eNull ){
DbgOut( L"CreateFbxBoneReq : parnode %s : type : null\r\n", parwname );
}else{
DbgOut( L"CreateFbxBoneReq : parnode %s : type : other : %d\r\n", parwname, partype );
}
switch ( partype )
{
case FbxNodeAttribute::eSkeleton:
case FbxNodeAttribute::eNull:
parbonenode = parnode;
break;
default:
parbonenode = 0;
break;
}
}else{
const char* parnodename = parnode->GetName();
WCHAR parwname[256];
MultiByteToWideChar( CP_ACP, MB_PRECOMPOSED, parnodename, -1, parwname, 256 );
DbgOut( L"CreateFbxBoneReq : %s : parnode name %s : parattr NULL!!!!!\r\n", wname, parwname );
}
}else{
DbgOut( L"CreateFbxBoneReq : %s : parnode NULL!!!!\r\n", wname );
}
switch ( type )
{
case FbxNodeAttribute::eSkeleton:
case FbxNodeAttribute::eNull:
//EFbxRotationOrder lRotationOrder = eEULER_ZXY;
//pNode->SetRotationOrder(FbxNode::eSourcePivot , lRotationOrder0 );
//pNode->SetRotationOrder(FbxNode::eDestinationPivot , lRotationOrder1 );
DbgOut( L"CreateFBXBoneReq : skeleton : %s\r\n", wname );
if (strcmp(nodename, "RootNode") != 0){
if (parnode && (strcmp(parnode->GetName(), "RootNode") != 0)){
GetFBXBone(pScene, type, pAttrib, nodename, pNode, parbonenode);
}
else{
GetFBXBone(pScene, type, pAttrib, nodename, pNode, 0);
}
}
else{
_ASSERT(0);
}
break;
case FbxSkeleton::eRoot:
_ASSERT(0);
break;
default:
break;
}
}
int childNodeNum;
childNodeNum = pNode->GetChildCount();
for ( int i = 0; i < childNodeNum; i++ )
{
FbxNode *pChild = pNode->GetChild(i); // 子ノードを取得
CreateFBXBoneReq( pScene, pChild, pNode );
}
return 0;
}
int CModel::GetFBXBone( FbxScene* pScene, FbxNodeAttribute::EType type, FbxNodeAttribute *pAttrib, const char* nodename, FbxNode* curnode, FbxNode* parnode )
{
int settopflag = 0;
CBone* newbone = new CBone( this );
_ASSERT( newbone );
char newbonename[256];
strcpy_s(newbonename, 256, nodename);
TermJointRepeats(newbonename);
newbone->SetName(newbonename);
newbone->SetTopBoneFlag( 0 );
m_bonelist[newbone->GetBoneNo()] = newbone;
m_bonename[ newbone->GetBoneName() ] = newbone;
if( type == FbxNodeAttribute::eSkeleton ){
newbone->SetType( FBXBONE_NORMAL );
}else if( type == FbxNodeAttribute::eNull ){
newbone->SetType( FBXBONE_NULL );
}else{
_ASSERT( 0 );
}
// if( !parnode ){
// m_firstbone = curnode;
// }
if( !m_topbone ){
m_topbone = newbone;
m_bone2node[newbone] = curnode;
settopflag = 1;
}else{
m_bone2node[newbone] = curnode;
}
EFbxRotationOrder lRotationOrder0;
curnode->GetRotationOrder (FbxNode::eSourcePivot, lRotationOrder0);
EFbxRotationOrder lRotationOrder1 = eEulerXYZ;
curnode->SetRotationOrder(FbxNode::eDestinationPivot , lRotationOrder1 );
if( parnode ){
//const char* parbonename = parnode->GetName();
char parbonename[256];
strcpy_s(parbonename, 256, parnode->GetName());
TermJointRepeats(parbonename);
CBone* parbone = m_bonename[ parbonename ];
if( parbone ){
parbone->AddChild( newbone );
//_ASSERT(0);
}else{
/***
FbxNodeAttribute *parattr = parnode->GetNodeAttribute();
if( parattr ){
FbxNodeAttribute::EType type = parattr->GetAttributeType();
if( type == FbxNodeAttribute::eSkeleton ){
_ASSERT( 0 );
}else if( type == FbxNodeAttribute::eNull ){
_ASSERT( 0 );
}else{
_ASSERT( 0 );
}
}else{
_ASSERT( 0 );
}
***/
::MessageBoxA( NULL, "GetFBXBone : parbone NULL error ", parbonename, MB_OK );
}
}else{
if( settopflag == 0 ){
_ASSERT( 0 );
m_topbone->AddChild( newbone );
}else{
_ASSERT(0);
//::MessageBoxA( NULL, "GetFBXBone : parbone NULL error ", nodename, MB_OK );
}
}
return 0;
}
int CModel::MotionID2Index( int motid )
{
int retindex = -1;
int chkcnt = 0;
map<int,MOTINFO*>::iterator itrmotinfo;
for( itrmotinfo = m_motinfo.begin(); itrmotinfo != m_motinfo.end(); itrmotinfo++ ){
MOTINFO* curmi = itrmotinfo->second;
if( curmi ){
if( curmi->motid == motid ){
retindex = chkcnt;
break;
}
}
chkcnt++;
}
return retindex;
}
FbxAnimLayer* CModel::GetAnimLayer( int motid )
{
FbxAnimLayer *retAnimLayer = 0;
int motindex = MotionID2Index( motid );
if( motindex < 0 ){
return 0;
}
FbxAnimStack *lCurrentAnimationStack = m_pscene->FindMember<FbxAnimStack>(mAnimStackNameArray[motindex]->Buffer());
if (lCurrentAnimationStack == NULL){
_ASSERT( 0 );
return 0;
}
retAnimLayer = lCurrentAnimationStack->GetMember<FbxAnimLayer>();
return retAnimLayer;
}
int CModel::CreateFBXAnim( FbxScene* pScene, FbxNode* prootnode )
{
static int s_dbgcnt = 0;
s_dbgcnt++;
SetDefaultBonePos();
pScene->FillAnimStackNameArray(mAnimStackNameArray);
const int lAnimStackCount = mAnimStackNameArray.GetCount();
DbgOut( L"FBX anim num %d\r\n", lAnimStackCount );
if( lAnimStackCount <= 0 ){
_ASSERT( 0 );
return 0;
}
int animno;
for( animno = 0; animno < lAnimStackCount; animno++ ){
// select the base layer from the animation stack
//char* animname = mAnimStackNameArray[animno]->Buffer();
//MessageBoxA( NULL, animname, "check", MB_OK );
FbxAnimStack * lCurrentAnimationStack = m_pscene->FindMember<FbxAnimStack>(mAnimStackNameArray[animno]->Buffer());
if (lCurrentAnimationStack == NULL){
_ASSERT( 0 );
return 1;
}
FbxAnimLayer * mCurrentAnimLayer;
mCurrentAnimLayer = lCurrentAnimationStack->GetMember<FbxAnimLayer>();
pScene->GetEvaluator()->SetContext(lCurrentAnimationStack);
//pScene->GetRootNode()->ConvertPivotAnimationRecursive( mAnimStackNameArray[animno]->Buffer(), FbxNode::eDestinationPivot, 30.0, true );
//pScene->GetRootNode()->ConvertPivotAnimationRecursive( mAnimStackNameArray[animno]->Buffer(), FbxNode::eSourcePivot, 30.0, true );
FbxTakeInfo* lCurrentTakeInfo = pScene->GetTakeInfo(*(mAnimStackNameArray[animno]));
if (lCurrentTakeInfo)
{
mStart = lCurrentTakeInfo->mLocalTimeSpan.GetStart();
mStop = lCurrentTakeInfo->mLocalTimeSpan.GetStop();
double dstart = mStart.GetSecondDouble();
double dstop = mStop.GetSecondDouble();
//_ASSERT( 0 );
}
else
{
_ASSERT( 0 );
// Take the time line value
FbxTimeSpan lTimeLineTimeSpan;
pScene->GetGlobalSettings().GetTimelineDefaultTimeSpan(lTimeLineTimeSpan);
mStart = lTimeLineTimeSpan.GetStart();
mStop = lTimeLineTimeSpan.GetStop();
}
// int animleng = (int)mStop.GetFrame();// - mStart.GetFrame() + 1;
//mFrameTime.SetTime(0, 0, 0, 1, 0, pScene->GetGlobalSettings().GetTimeMode());
//mFrameTime2.SetTime(0, 0, 0, 1, 0, pScene->GetGlobalSettings().GetTimeMode());
mFrameTime.SetSecondDouble( 1.0 / 30.0 );
mFrameTime2.SetSecondDouble( 1.0 / 30.0 );
//mFrameTime.SetSecondDouble( 1.0 / 300.0 );
//mFrameTime2.SetSecondDouble( 1.0 / 300.0 );
// int fcnt = 0;
// FbxTime chktime;
// for( chktime = mStart; chktime < mStop; chktime += mFrameTime ){
// fcnt++;
// }
// int animleng = fcnt;
int animleng = (int)( (mStop.GetSecondDouble() - mStart.GetSecondDouble()) * 30.0 );
// int animleng = (int)( (mStop.GetSecondDouble() - mStart.GetSecondDouble()) * 300.0 );
// _ASSERT( 0 );
//char mes[256];
//sprintf_s( mes, 256, "%d", animleng );
//MessageBoxA( NULL, mes, "check", MB_OK );
//_ASSERT( 0 );
DbgOut( L"FBX anim %d, animleng %d\r\n", animno, animleng );
int curmotid = -1;
AddMotion( mAnimStackNameArray[animno]->Buffer(), 0, (double)animleng, &curmotid );
map<int,CBone*>::iterator itrbone;
for( itrbone = m_bonelist.begin(); itrbone != m_bonelist.end(); itrbone++ ){
CBone* curbone = itrbone->second;
if( curbone ){
curbone->SetGetAnimFlag( 0 );
}
}
//FbxPose* pPose = pScene->GetPose( animno );
//FbxPose* pPose = pScene->GetPose( 10 );
FbxPose* pPose = NULL;
CreateFBXAnimReq( animno, pPose, prootnode, curmotid, animleng, mStart, mFrameTime2 );
FillUpEmptyKeyReq( curmotid, animleng, m_topbone, 0 );
if( animno == 0 ){
CallF( CreateFBXShape( mCurrentAnimLayer, animleng, mStart, mFrameTime2 ), return 1 );
}
(this->m_tlFunc)( curmotid );
}
return 0;
}
int CModel::CreateFBXAnimReq( int animno, FbxPose* pPose, FbxNode* pNode, int motid, int animleng, FbxTime mStart, FbxTime mFrameTime )
{
//static int dbgcnt = 0;
//int lSkinCount;
FbxNodeAttribute *pAttrib = pNode->GetNodeAttribute();
if ( pAttrib ) {
FbxNodeAttribute::EType type = pAttrib->GetAttributeType();
switch ( type )
{
case FbxNodeAttribute::eMesh:
// case FbxNodeAttribute::eNURB:
// case FbxNodeAttribute::eNURBS_SURFACE:
GetFBXAnim( animno, pNode, pPose, pAttrib, motid, animleng, mStart, mFrameTime ); // メッシュを作成
break;
default:
break;
}
}
int childNodeNum;
childNodeNum = pNode->GetChildCount();
for ( int i = 0; i < childNodeNum; i++ )
{
FbxNode *pChild = pNode->GetChild(i); // 子ノードを取得
CreateFBXAnimReq( animno, pPose, pChild, motid, animleng, mStart, mFrameTime );
}
return 0;
}
int CModel::GetFBXAnim( int animno, FbxNode* pNode, FbxPose* pPose, FbxNodeAttribute *pAttrib, int motid, int animleng, FbxTime mStart, FbxTime mFrameTime )
{
FbxAMatrix pGlobalPosition;
pGlobalPosition.SetIdentity();
FbxMesh *pMesh = (FbxMesh*)pAttrib;
// スキンの数を取得
int skinCount = pMesh->GetDeformerCount( FbxDeformer::eSkin );
for ( int i = 0; i < skinCount; ++i ) {
// i番目のスキンを取得
FbxSkin* skin = (FbxSkin*)( pMesh->GetDeformer( i, FbxDeformer::eSkin ) );
// クラスターの数を取得
int clusterNum = skin->GetClusterCount();
for ( int j = 0; j < clusterNum; ++j ) {
// j番目のクラスタを取得
FbxCluster* cluster = skin->GetCluster( j );
const char* bonename = ((FbxNode*)cluster->GetLink())->GetName();
char bonename2[256];
strcpy_s(bonename2, 256, bonename);
TermJointRepeats(bonename2);
CBone* curbone = m_bonename[ (char*)bonename2 ];
WCHAR wname[256]={0L};
ZeroMemory( wname, sizeof( WCHAR ) * 256 );
MultiByteToWideChar( CP_ACP, MB_PRECOMPOSED, (char*)bonename2, 256, wname, 256 );
if( curbone && !curbone->GetGetAnimFlag()){
curbone->SetGetAnimFlag( 1 );
FbxAMatrix mat;
FbxTime ktime = mStart;
int framecnt;
for( framecnt = 0; framecnt < animleng; framecnt++ ){
FbxCluster::ELinkMode lClusterMode = cluster->GetLinkMode();
FbxAMatrix lReferenceGlobalInitPosition;
FbxAMatrix lReferenceGlobalCurrentPosition;
FbxAMatrix lAssociateGlobalInitPosition;
FbxAMatrix lAssociateGlobalCurrentPosition;
FbxAMatrix lClusterGlobalInitPosition;
FbxAMatrix lClusterGlobalCurrentPosition;
FbxAMatrix lReferenceGeometry;
FbxAMatrix lAssociateGeometry;
FbxAMatrix lClusterGeometry;
FbxAMatrix lClusterRelativeInitPosition;
FbxAMatrix lClusterRelativeCurrentPositionInverse;
cluster->GetTransformMatrix(lReferenceGlobalInitPosition);
lReferenceGlobalCurrentPosition = pGlobalPosition;
// Multiply lReferenceGlobalInitPosition by Geometric Transformation
lReferenceGeometry = GetGeometry(pMesh->GetNode());
lReferenceGlobalInitPosition *= lReferenceGeometry;
// Get the link initial global position and the link current global position.
cluster->GetTransformLinkMatrix(lClusterGlobalInitPosition);
lClusterGlobalCurrentPosition = GetGlobalPosition(cluster->GetLink(), ktime, pPose);
// Compute the initial position of the link relative to the reference.
lClusterRelativeInitPosition = lClusterGlobalInitPosition.Inverse() * lReferenceGlobalInitPosition;
// Compute the current position of the link relative to the reference.
lClusterRelativeCurrentPositionInverse = lReferenceGlobalCurrentPosition.Inverse() * lClusterGlobalCurrentPosition;
// Compute the shift of the link relative to the reference.
mat = lClusterRelativeCurrentPositionInverse * lClusterRelativeInitPosition;
ChaMatrix xmat;
xmat._11 = (float)mat.Get( 0, 0 );
xmat._12 = (float)mat.Get( 0, 1 );
xmat._13 = (float)mat.Get( 0, 2 );
xmat._14 = (float)mat.Get( 0, 3 );
xmat._21 = (float)mat.Get( 1, 0 );
xmat._22 = (float)mat.Get( 1, 1 );
xmat._23 = (float)mat.Get( 1, 2 );
xmat._24 = (float)mat.Get( 1, 3 );
xmat._31 = (float)mat.Get( 2, 0 );
xmat._32 = (float)mat.Get( 2, 1 );
xmat._33 = (float)mat.Get( 2, 2 );
xmat._34 = (float)mat.Get( 2, 3 );
xmat._41 = (float)mat.Get( 3, 0 );
xmat._42 = (float)mat.Get( 3, 1 );
xmat._43 = (float)mat.Get( 3, 2 );
xmat._44 = (float)mat.Get( 3, 3 );
if( (animno == 0) && (framecnt == 0) ){
curbone->SetFirstMat( xmat );
curbone->SetInitMat( xmat );
ChaMatrix calcmat = curbone->GetNodeMat() * curbone->GetInvFirstMat();
ChaVector3 zeropos(0.0f, 0.0f, 0.0f);
ChaVector3 tmppos;
ChaVector3TransformCoord(&tmppos, &zeropos, &calcmat);
curbone->SetJointFPos(tmppos);
}
CMotionPoint* curmp = 0;
int existflag = 0;
curmp = curbone->AddMotionPoint( motid, (double)(framecnt), &existflag );
if( !curmp ){
_ASSERT( 0 );
return 1;
}
curmp->SetWorldMat( xmat );
ktime += mFrameTime;
//ktime = mFrameTime * framecnt;
}
}
if (!curbone){
_ASSERT(0);
}
}
}
return 0;
}
int CModel::CreateFBXSkinReq( FbxNode* pNode )
{
FbxNodeAttribute *pAttrib = pNode->GetNodeAttribute();
if ( pAttrib ) {
FbxNodeAttribute::EType type = pAttrib->GetAttributeType();
switch ( type )
{
case FbxNodeAttribute::eMesh:
// case FbxNodeAttribute::eNURB:
// case FbxNodeAttribute::eNURBS_SURFACE:
GetFBXSkin( pAttrib, pNode ); // メッシュを作成
break;
default:
break;
}
}
int childNodeNum;
childNodeNum = pNode->GetChildCount();
for ( int i = 0; i < childNodeNum; i++ )
{
FbxNode *pChild = pNode->GetChild(i); // 子ノードを取得
CreateFBXSkinReq( pChild );
}
return 0;
}
int CModel::GetFBXSkin( FbxNodeAttribute *pAttrib, FbxNode* pNode )
{
const char* nodename = pNode->GetName();
FbxMesh *pMesh = (FbxMesh*)pAttrib;
CMQOObject* newobj = 0;
newobj = m_objectname[ nodename ];
if( !newobj ){
_ASSERT( 0 );
return 1;
}
//スキン
// スキンの数を取得
int skinCount = pMesh->GetDeformerCount( FbxDeformer::eSkin );
int makecnt = 0;
for ( int i = 0; i < skinCount; ++i ) {
// i番目のスキンを取得
FbxSkin* skin = (FbxSkin*)( pMesh->GetDeformer( i, FbxDeformer::eSkin ) );
// クラスターの数を取得
int clusterNum = skin->GetClusterCount();
DbgOut( L"fbx : skin : org clusternum %d\r\n", clusterNum );
for ( int j = 0; j < clusterNum; ++j ) {
// j番目のクラスタを取得
FbxCluster* cluster = skin->GetCluster( j );
int validflag = IsValidCluster( cluster );
if( validflag == 0 ){
continue;
}
const char* bonename = ((FbxNode*)cluster->GetLink())->GetName();
char bonename2[256];
strcpy_s(bonename2, 256, bonename);
TermJointRepeats(bonename2);
// int namelen = (int)strlen( clustername );
WCHAR wname[256];
ZeroMemory( wname, sizeof( WCHAR ) * 256 );
MultiByteToWideChar( CP_ACP, MB_PRECOMPOSED, bonename2, -1, wname, 256 );
// DbgOut( L"cluster (%d, %d), name : %s\r\n", i, j, wname );
CBone* curbone = m_bonename[ (char*)bonename2 ];
if( curbone ){
int curclusterno = newobj->GetClusterSize();
if( curclusterno >= MAXCLUSTERNUM ){
WCHAR wmes[256];
swprintf_s( wmes, 256, L"1つのパーツに影響できるボーンの制限数(%d個)を超えました。読み込めません。", MAXCLUSTERNUM );
MessageBoxW( NULL, wmes, L"ボーン数エラー", MB_OK );
_ASSERT( 0 );
return 1;
}
newobj->PushBackCluster( curbone );
int pointNum = cluster->GetControlPointIndicesCount();
int* pointAry = cluster->GetControlPointIndices();
double* weightAry = cluster->GetControlPointWeights();
FbxCluster::ELinkMode lClusterMode = cluster->GetLinkMode();
int index;
float weight;
for ( int i2 = 0; i2 < pointNum; i2++ ) {
// 頂点インデックスとウェイトを取得
index = pointAry[ i2 ];
weight = (float)weightAry[ i2 ];
int isadditive;
if( lClusterMode == FbxCluster::eAdditive ){
isadditive = 1;
}else{
isadditive = 0;
}
if( (lClusterMode == FbxCluster::eAdditive) || (weight >= 0.05f) ){
//if ((lClusterMode == FbxCluster::eAdditive)){
newobj->AddInfBone( curclusterno, index, weight, isadditive );
}
}
makecnt++;
}else{
_ASSERT( 0 );
}
}
newobj->NormalizeInfBone();
}
DbgOut( L"fbx skin : make cluster %d\r\n", makecnt );
return 0;
}
int IsValidCluster( FbxCluster* cluster )
{
int findflag = 0;
int pointNum = cluster->GetControlPointIndicesCount();
int* pointAry = cluster->GetControlPointIndices();
double* weightAry = cluster->GetControlPointWeights();
FbxCluster::ELinkMode lClusterMode = cluster->GetLinkMode();
int index;
double weight;
for ( int i2 = 0; i2 < pointNum; i2++ ) {
// 頂点インデックスとウェイトを取得
index = pointAry[ i2 ];
weight = weightAry[ i2 ];
if( (lClusterMode == FbxCluster::eAdditive) || (weight >= 0.05) ){
//if ((lClusterMode == FbxCluster::eAdditive)){
findflag = 1;
break;
}
}
return findflag;
}
int CModel::RenderBoneMark( ID3D10Device* pdev, CModel* bmarkptr, CMySprite* bcircleptr, CModel* cpslptr[COL_MAX], int selboneno, int skiptopbonemark )
{
if( m_bonelist.empty() ){
return 0;
}
map<int, CBone*>::iterator itrb;
for( itrb = m_bonelist.begin(); itrb != m_bonelist.end(); itrb++ ){
CBone* curbone = itrb->second;
if( curbone ){
curbone->SetSelectFlag( 0 );
}
}
if( selboneno > 0 ){
CBone* selbone = m_bonelist[ selboneno ];
if( selbone ){
SetSelectFlagReq( selbone, 0 );
selbone->SetSelectFlag( 2 );
CBone* parbone = selbone->GetParent();
if( parbone ){
// parbone->m_selectflag = 2;
CBtObject* curbto = FindBtObject( selbone->GetBoneNo() );
if( curbto ){
int tmpflag = parbone->GetSelectFlag() + 4;
parbone->SetSelectFlag( tmpflag );
}
}
}
}
//pdev->SetRenderState( D3DRS_ZFUNC, D3DCMP_ALWAYS );
if( g_bonemarkflag && bmarkptr ){
map<int, CBone*>::iterator itrbone;
for( itrbone = m_bonelist.begin(); itrbone != m_bonelist.end(); itrbone++ ){
CBone* boneptr = itrbone->second;
if( boneptr ){
CBone* chilbone = boneptr->GetChild();
while (chilbone){
int renderflag = 0;
if (skiptopbonemark == 0){
renderflag = 1;
}
else{
CBone* parbone = boneptr->GetParent();
if (parbone){
renderflag = 1;
}
else{
renderflag = 0;
}
}
if (renderflag == 1){
ChaVector3 aftbonepos;
ChaVector3TransformCoord(&aftbonepos, &boneptr->GetJointFPos(), &(boneptr->GetCurMp().GetWorldMat()));
ChaVector3 aftchilpos;
ChaVector3TransformCoord(&aftchilpos, &chilbone->GetJointFPos(), &(chilbone->GetCurMp().GetWorldMat()));
boneptr->CalcAxisMatZ(&aftbonepos, &aftchilpos);
ChaMatrix bmmat;
bmmat = boneptr->GetLAxisMat();// * boneptr->m_curmp.m_worldmat;
ChaVector3 diffvec = aftchilpos - aftbonepos;
float diffleng = ChaVector3Length(&diffvec);
float fscale;
ChaMatrix scalemat;
ChaMatrixIdentity(&scalemat);
fscale = diffleng / 50.0f;
scalemat._11 = fscale;
scalemat._22 = fscale;
scalemat._33 = fscale;
bmmat = scalemat * bmmat;
bmmat._41 = aftbonepos.x;
bmmat._42 = aftbonepos.y;
bmmat._43 = aftbonepos.z;
g_pEffect->SetMatrix(g_hmWorld, &bmmat);
bmarkptr->UpdateMatrix(&bmmat, &m_matVP);
ChaVector4 difmult;
if (boneptr->GetSelectFlag() == 2){
difmult = ChaVector4(1.0f, 0.0f, 0.0f, 0.5f);
}
else{
difmult = ChaVector4(0.25f, 0.5f, 0.5f, 0.5f);
}
CallF(bmarkptr->OnRender(pdev, 0, difmult), return 1);
}
chilbone = chilbone->GetBrother();
}
}
}
}
if( cpslptr ){
map<int, CBone*>::iterator itrbone;
for( itrbone = m_bonelist.begin(); itrbone != m_bonelist.end(); itrbone++ ){
CBone* boneptr = itrbone->second;
if( boneptr ){
map<CBone*,CRigidElem*> tmpmap;
boneptr->GetRigidElemMap( tmpmap );
map<CBone*,CRigidElem*>::iterator itrre;
for( itrre = tmpmap.begin(); itrre != tmpmap.end(); itrre++ ){
CRigidElem* curre = itrre->second;
if( curre && (curre->GetSkipflag() != 1) ){
CBone* chilbone = itrre->first;
_ASSERT( chilbone );
CModel* curcoldisp = cpslptr[curre->GetColtype()];
_ASSERT( curcoldisp );
//DbgOut( L"check!!!: curbone %s, chilbone %s\r\n", boneptr->m_wbonename, chilbone->m_wbonename );
boneptr->CalcRigidElemParams( cpslptr, chilbone, 0 );
g_pEffect->SetMatrix( g_hmWorld, &(curre->GetCapsulemat()) );
curcoldisp->UpdateMatrix( &(curre->GetCapsulemat()), &m_matVP );
ChaVector4 difmult;
if( boneptr->GetSelectFlag() & 4 ){
difmult = ChaVector4( 1.0f, 0.0f, 0.0f, 0.5f );
}else{
difmult = ChaVector4( 0.25f, 0.5f, 0.5f, 0.5f );
}
CallF( curcoldisp->OnRender( pdev, 0, difmult ), return 1 );
}
}
}
}
}
if( g_bonemarkflag && bcircleptr ){
map<int, CBone*>::iterator itrbone;
for( itrbone = m_bonelist.begin(); itrbone != m_bonelist.end(); itrbone++ ){
CBone* boneptr = itrbone->second;
if( boneptr && (boneptr->GetType() == FBXBONE_NORMAL) ){
ChaMatrix bcmat;
bcmat = boneptr->GetCurMp().GetWorldMat();
//CBone* parbone = boneptr->GetParent();
//CBone* chilbone = boneptr->GetChild();
ChaMatrix transmat = bcmat * m_matVP;
ChaVector3 scpos;
ChaVector3 firstpos = boneptr->GetJointFPos();
ChaVector3TransformCoord( &scpos, &firstpos, &transmat );
scpos.z = 0.0f;
bcircleptr->SetPos( scpos );
D3DXVECTOR2 bsize;
if( boneptr->GetSelectFlag() & 2 ){
bcircleptr->SetColor( ChaVector4( 0.0f, 0.0f, 1.0f, 0.7f ) );
bsize = D3DXVECTOR2( 0.050f, 0.050f );
bcircleptr->SetSize( bsize );
}else if( boneptr->GetSelectFlag() & 1 ){
bcircleptr->SetColor( ChaVector4( 1.0f, 0.0f, 0.0f, 0.7f ) );
bsize = D3DXVECTOR2( 0.025f, 0.025f );
bcircleptr->SetSize( bsize );
}else{
bcircleptr->SetColor( ChaVector4( 1.0f, 1.0f, 1.0f, 0.7f ) );
bsize = D3DXVECTOR2( 0.025f, 0.025f );
bcircleptr->SetSize( bsize );
}
CallF( bcircleptr->OnRender(), return 1 );
}
}
}
//pdev->SetRenderState( D3DRS_ZFUNC, D3DCMP_LESSEQUAL );
return 0;
}
void CModel::SetDefaultBonePosReq( CBone* curbone, const FbxTime& pTime, FbxPose* pPose, FbxAMatrix* pParentGlobalPosition )
{
FbxNode* pNode = m_bone2node[ curbone ];
FbxAMatrix lGlobalPosition;
bool lPositionFound = false;//バインドポーズを書き出さない場合やHipsなどの場合は0になる?
if( pPose ){
int lNodeIndex = pPose->Find(pNode);
if (lNodeIndex > -1)
{
// The bind pose is always a global matrix.
// If we have a rest pose, we need to check if it is
// stored in global or local space.
if (pPose->IsBindPose() || !pPose->IsLocalMatrix(lNodeIndex))
{
lGlobalPosition = GetPoseMatrix(pPose, lNodeIndex);
}
else
{
// We have a local matrix, we need to convert it to
// a global space matrix.
FbxAMatrix lParentGlobalPosition;
if (pParentGlobalPosition)
{
lParentGlobalPosition = *pParentGlobalPosition;
}
else
{
if (pNode->GetParent())
{
lParentGlobalPosition = GetGlobalPosition(pNode->GetParent(), pTime, pPose);
}
}
FbxAMatrix lLocalPosition = GetPoseMatrix(pPose, lNodeIndex);
lGlobalPosition = lParentGlobalPosition * lLocalPosition;
}
lPositionFound = true;
}
}
if (!lPositionFound)
{
// There is no pose entry for that node, get the current global position instead.
// Ideally this would use parent global position and local position to compute the global position.
// Unfortunately the equation
// lGlobalPosition = pParentGlobalPosition * lLocalPosition
// does not hold when inheritance type is other than "Parent" (RSrs).
// To compute the parent rotation and scaling is tricky in the RrSs and Rrs cases.
lGlobalPosition = pNode->EvaluateGlobalTransform(pTime);
}
ChaMatrix nodemat;
nodemat._11 = (float)lGlobalPosition.Get( 0, 0 );
nodemat._12 = (float)lGlobalPosition.Get( 0, 1 );
nodemat._13 = (float)lGlobalPosition.Get( 0, 2 );
nodemat._14 = (float)lGlobalPosition.Get( 0, 3 );
nodemat._21 = (float)lGlobalPosition.Get( 1, 0 );
nodemat._22 = (float)lGlobalPosition.Get( 1, 1 );
nodemat._23 = (float)lGlobalPosition.Get( 1, 2 );
nodemat._24 = (float)lGlobalPosition.Get( 1, 3 );
nodemat._31 = (float)lGlobalPosition.Get( 2, 0 );
nodemat._32 = (float)lGlobalPosition.Get( 2, 1 );
nodemat._33 = (float)lGlobalPosition.Get( 2, 2 );
nodemat._34 = (float)lGlobalPosition.Get( 2, 3 );
nodemat._41 = (float)lGlobalPosition.Get( 3, 0 );
nodemat._42 = (float)lGlobalPosition.Get( 3, 1 );
nodemat._43 = (float)lGlobalPosition.Get( 3, 2 );
nodemat._44 = (float)lGlobalPosition.Get( 3, 3 );
curbone->SetPositionFound(lPositionFound);//!!!
curbone->SetNodeMat( nodemat );
curbone->SetGlobalPosMat( lGlobalPosition );
ChaVector3 zeropos( 0.0f, 0.0f, 0.0f );
ChaVector3 tmppos;
ChaVector3TransformCoord( &tmppos, &zeropos, &(curbone->GetNodeMat()) );
curbone->SetJointWPos( tmppos );
curbone->SetJointFPos( tmppos );
//WCHAR wname[256];
//ZeroMemory( wname, sizeof( WCHAR ) * 256 );
//MultiByteToWideChar( CP_ACP, MB_PRECOMPOSED, curbone->m_bonename, 256, wname, 256 );
//DbgOut( L"SetDefaultBonePos : %s : wpos (%f, %f, %f)\r\n", wname, curbone->m_jointfpos.x, curbone->m_jointfpos.y, curbone->m_jointfpos.z );
if( curbone->GetChild() ){
SetDefaultBonePosReq( curbone->GetChild(), pTime, pPose, &curbone->GetGlobalPosMat() );
}
if( curbone->GetBrother() ){
SetDefaultBonePosReq( curbone->GetBrother(), pTime, pPose, pParentGlobalPosition );
}
}
int CModel::SetDefaultBonePos()
{
if( !m_topbone ){
return 0;
}
FbxPose* bindpose = 0;
FbxPose* curpose = m_pscene->GetPose( 0 );
int curpindex = 1;
while( curpose ){
if( curpose->IsBindPose() ){
bindpose = curpose;
break;
}
curpose = m_pscene->GetPose( curpindex );
curpindex++;
}
if( !bindpose ){
::MessageBoxA( NULL, "バインドポーズがありません。", "警告", MB_OK );
bindpose = m_pscene->GetPose( 0 );
}
FbxTime pTime;
pTime.SetSecondDouble( 0.0 );
//CBone* secbone = m_topbone->GetChild();
CBone* secbone = m_topbone;
if( secbone ){
SetDefaultBonePosReq( secbone, pTime, bindpose, 0 );
}
return 0;
}
FbxAMatrix GetGlobalPosition(FbxNode* pNode, const FbxTime& pTime, FbxPose* pPose, FbxAMatrix* pParentGlobalPosition)
{
FbxAMatrix lGlobalPosition;
bool lPositionFound = false;
if (pPose)
{
int lNodeIndex = pPose->Find(pNode);
if (lNodeIndex > -1)
{
// The bind pose is always a global matrix.
// If we have a rest pose, we need to check if it is
// stored in global or local space.
if (pPose->IsBindPose() || !pPose->IsLocalMatrix(lNodeIndex))
{
lGlobalPosition = GetPoseMatrix(pPose, lNodeIndex);
}
else
{
// We have a local matrix, we need to convert it to
// a global space matrix.
FbxAMatrix lParentGlobalPosition;
if (pParentGlobalPosition)
{
lParentGlobalPosition = *pParentGlobalPosition;
}
else
{
if (pNode->GetParent())
{
lParentGlobalPosition = GetGlobalPosition(pNode->GetParent(), pTime, pPose);
}
}
FbxAMatrix lLocalPosition = GetPoseMatrix(pPose, lNodeIndex);
lGlobalPosition = lParentGlobalPosition * lLocalPosition;
}
lPositionFound = true;
}
}
if (!lPositionFound)
{
// There is no pose entry for that node, get the current global position instead.
// Ideally this would use parent global position and local position to compute the global position.
// Unfortunately the equation
// lGlobalPosition = pParentGlobalPosition * lLocalPosition
// does not hold when inheritance type is other than "Parent" (RSrs).
// To compute the parent rotation and scaling is tricky in the RrSs and Rrs cases.
lGlobalPosition = pNode->EvaluateGlobalTransform(pTime);
}
return lGlobalPosition;
}
// Get the matrix of the given pose
FbxAMatrix GetPoseMatrix(FbxPose* pPose, int pNodeIndex)
{
FbxAMatrix lPoseMatrix;
FbxMatrix lMatrix = pPose->GetMatrix(pNodeIndex);
memcpy((double*)lPoseMatrix, (double*)lMatrix, sizeof(lMatrix.mData));
return lPoseMatrix;
}
// Get the geometry offset to a node. It is never inherited by the children.
FbxAMatrix GetGeometry(FbxNode* pNode)
{
const FbxVector4 lT = pNode->GetGeometricTranslation(FbxNode::eSourcePivot);
const FbxVector4 lR = pNode->GetGeometricRotation(FbxNode::eSourcePivot);
const FbxVector4 lS = pNode->GetGeometricScaling(FbxNode::eSourcePivot);
return FbxAMatrix(lT, lR, lS);
}
void CModel::FillUpEmptyKeyReq( int motid, int animleng, CBone* curbone, CBone* parbone )
{
ChaMatrix parfirstmat, invparfirstmat;
ChaMatrixIdentity( &parfirstmat );
ChaMatrixIdentity( &invparfirstmat );
if( parbone ){
double zeroframe = 0.0;
int existz = 0;
CMotionPoint* parmp = parbone->AddMotionPoint( motid, zeroframe, &existz );
if( existz && parmp ){
parfirstmat = parmp->GetWorldMat();//!!!!!!!!!!!!!! この時点ではm_matWorldが掛かっていないから後で修正必要かも??
ChaMatrixInverse( &invparfirstmat, NULL, &parfirstmat );
}else{
ChaMatrixIdentity( &parfirstmat );
ChaMatrixIdentity( &invparfirstmat );
}
}
int framecnt;
for( framecnt = 0; framecnt < animleng; framecnt++ ){
double frame = (double)framecnt;
ChaMatrix mvmat;
ChaMatrixIdentity( &mvmat );
CMotionPoint* pbef = 0;
CMotionPoint* pnext = 0;
int existflag = 0;
curbone->GetBefNextMP( motid, frame, &pbef, &pnext, &existflag );
if( existflag == 0 ){
int exist2 = 0;
CMotionPoint* newmp = curbone->AddMotionPoint( motid, frame, &exist2 );
if( !newmp ){
_ASSERT( 0 );
return;
}
if( parbone ){
int exist3 = 0;
CMotionPoint* parmp = parbone->AddMotionPoint( motid, frame, &exist3 );
ChaMatrix tmpmat = parbone->GetInvFirstMat() * parmp->GetWorldMat();//!!!!!!!!!!!!!!!!!! endjointはこれでうまく行くが、floatと分岐が不動になる。
newmp->SetWorldMat( tmpmat );
}
}
}
if( curbone->GetChild() ){
FillUpEmptyKeyReq( motid, animleng, curbone->GetChild(), curbone );
}
if( curbone->GetBrother() ){
FillUpEmptyKeyReq( motid, animleng, curbone->GetBrother(), parbone );
}
}
int CModel::FillUpEmptyMotion(int srcmotid)
{
MOTINFO* curmi = GetMotInfo( srcmotid );
_ASSERT(curmi);
if (curmi){
FillUpEmptyKeyReq(curmi->motid, curmi->frameleng, m_topbone, 0);
return 0;
}
else{
_ASSERT(0);
return 1;
}
}
int CModel::SetMaterialName()
{
m_materialname.clear();
map<int, CMQOMaterial*>::iterator itrmat;
for( itrmat = m_material.begin(); itrmat != m_material.end(); itrmat++ ){
CMQOMaterial* curmat = itrmat->second;
m_materialname[ curmat->GetName() ] = curmat;
}
return 0;
}
int CModel::DestroyBtObject()
{
if( m_topbt ){
DestroyBtObjectReq( m_topbt );
}
m_topbt = 0;
m_rigidbone.clear();
map<int,CBone*>::iterator itrbone;
for( itrbone = m_bonelist.begin(); itrbone != m_bonelist.end(); itrbone++ ){
CBone* curbone = itrbone->second;
curbone->ClearBtObject();
}
return 0;
}
void CModel::DestroyBtObjectReq( CBtObject* curbt )
{
std::vector<CBtObject*> tmpbt;
curbt->CopyChilBt( tmpbt );
delete curbt;
int chilno;
for( chilno = 0; chilno < (int)tmpbt.size(); chilno++ ){
CBtObject* chilbt = tmpbt[ chilno ];
if( chilbt ){
DestroyBtObjectReq( chilbt );
}
}
}
/***
int CModel::CalcBtAxismat( float delta )
{
if( !m_topbone ){
return 0;
}
CalcBtAxismatReq( m_topbone, delta );//!!!!!!!!!!!!!
return 0;
}
***/
void CModel::SetBtKinFlagReq( CBtObject* srcbto, int oncreateflag )
{
CBone* srcbone = srcbto->GetBone();
if( srcbone ){
// srcbone->m_btkinflag = 0;
int cmp0 = strncmp( srcbone->GetBoneName(), "BT_", 3 );
if( (cmp0 == 0) || (srcbone->GetBtForce() == 1)){
if (srcbone->GetParent()){
CRigidElem* curre = srcbone->GetParent()->GetRigidElem(srcbone);
if (curre){
if (curre->GetSkipflag() == 0){
srcbone->SetBtKinFlag(0);
}
else{
srcbone->SetBtKinFlag(1);
}
}
else{
srcbone->SetBtKinFlag(1);
}
}
else{
srcbone->SetBtKinFlag(1);
}
}else{
srcbone->SetBtKinFlag( 1 );
}
if( (srcbone->GetBtKinFlag() == 1) && (srcbto->GetRigidBody()) ){
DWORD curflag = srcbto->GetRigidBody()->getCollisionFlags();
if( s_setrigidflag == 0 ){
s_rigidflag = curflag;
s_setrigidflag = 1;
}
//srcbto->GetRigidBody()->setCollisionFlags(btCollisionObject::CF_KINEMATIC_OBJECT);
srcbto->GetRigidBody()->setCollisionFlags( curflag | btCollisionObject::CF_KINEMATIC_OBJECT);
//srcbto->m_rigidbody->setActivationState(DISABLE_DEACTIVATION);
//srcbto->m_rigidbody->setActivationState(WANTS_DEACTIVATION);
//srcbto->m_rigidbody->setActivationState(DISABLE_SIMULATION);
//CF_STATIC_OBJECT
}else if( srcbto->GetRigidBody() ){
if( srcbone->GetParent() ){
CRigidElem* curre = srcbone->GetParent()->GetRigidElem( srcbone );
if( curre ){
if ((m_curreindex >= 0) && (m_curreindex < m_rigideleminfo.size())){
srcbto->GetRigidBody()->setGravity(btVector3(0.0f, curre->GetBtg() * m_rigideleminfo[m_curreindex].btgscale, 0.0f));
srcbto->GetRigidBody()->applyGravity();
}
else{
_ASSERT(0);
}
}
}
}
}
int chilno;
for( chilno = 0; chilno < srcbto->GetChilBtSize(); chilno++ ){
CBtObject* chilbto = srcbto->GetChilBt( chilno );
SetBtKinFlagReq( chilbto, oncreateflag );
}
}
int CModel::CreateBtConstraint()
{
if( !m_topbone ){
return 0;
}
if( !m_topbt ){
return 0;
}
CreateBtConstraintReq( m_topbt );
CreateBtConnectReq( m_topbone );
return 0;
}
void CModel::CreateBtConstraintReq( CBtObject* curbto )
{
if( curbto->GetTopFlag() == 0 ){
CallF( curbto->CreateBtConstraint(), return );
}
int btono;
for( btono = 0; btono < (int)curbto->GetChilBtSize(); btono++ ){
CBtObject* chilbto = curbto->GetChilBt( btono );
if( chilbto ){
CreateBtConstraintReq( chilbto );
}
}
}
void CModel::CreateBtConnectReq(CBone* curbone)
{
if (curbone->GetChild()){
CBone* brobone1 = curbone->GetChild()->GetBrother();
if (brobone1){
CBone* brobone2 = brobone1->GetBrother();
while (brobone2){
map<CBone*, CBtObject*>::iterator itrbto1;
for (itrbto1 = brobone1->GetBtObjectMapBegin(); itrbto1 != brobone1->GetBtObjectMapEnd(); itrbto1++){
CBtObject* bto1 = itrbto1->second;
if (bto1 && bto1->GetRigidBody()){
map<CBone*, CBtObject*>::iterator itrbto2;
for (itrbto2 = brobone2->GetBtObjectMapBegin(); itrbto2 != brobone2->GetBtObjectMapEnd(); itrbto2++){
CBtObject* bto2 = itrbto2->second;
if (bto2 && bto2->GetRigidBody()){
float angPAI2, angPAI;
angPAI2 = 90.0f * (float)DEG2PAI;
angPAI = 180.0f * (float)DEG2PAI;
float lmax, lmin;
lmax = 10000.0f;
lmin = -10000.0f;
btGeneric6DofSpringConstraint* dofC;
btTransform tmpA, tmpA2;
bto1->GetFrameA(tmpA);
bto2->GetFrameA(tmpA2);
dofC = new btGeneric6DofSpringConstraint(*bto1->GetRigidBody(), *bto2->GetRigidBody(), tmpA, tmpA2, true);
_ASSERT(dofC);
dofC->setLinearLowerLimit(btVector3(lmin, lmin, lmin));
dofC->setLinearUpperLimit(btVector3(lmax, lmax, lmax));
dofC->setAngularLowerLimit(btVector3(angPAI, angPAI2, angPAI));
dofC->setAngularUpperLimit(btVector3(-angPAI, -angPAI2, -angPAI));
dofC->setBreakingImpulseThreshold(FLT_MAX);
int l_kindex = bto1->GetBone()->GetRigidElem(bto1->GetEndBone())->GetLKindex();
int a_kindex = bto1->GetBone()->GetRigidElem(bto1->GetEndBone())->GetAKindex();
float l_damping = bto1->GetBone()->GetRigidElem(bto1->GetEndBone())->GetLDamping();
float a_damping = bto1->GetBone()->GetRigidElem(bto1->GetEndBone())->GetADamping();
float l_cusk = bto1->GetBone()->GetRigidElem(bto1->GetEndBone())->GetCusLk();
float a_cusk = bto1->GetBone()->GetRigidElem(bto1->GetEndBone())->GetCusAk();
int dofid;
for (dofid = 0; dofid < 3; dofid++){
dofC->enableSpring(dofid, true);//!!!!!!!!!!!!!!!!!!!
dofC->setStiffness(dofid, 1.0e12);
//dofC->setStiffness(dofid, 1.0e6);
dofC->setDamping(dofid, 0.5f);
}
for (dofid = 3; dofid < 6; dofid++){
dofC->enableSpring(dofid, true);//!!!!!!!!!!!!!!!!!
dofC->setStiffness(dofid, 80.0f);
//dofC->setStiffness(dofid, 1000.0f);
dofC->setDamping(dofid, 0.01f);
}
dofC->setEquilibriumPoint();
bto1->PushBackConstraint(dofC);
m_btWorld->addConstraint(dofC, false);//!!!!!!!!!!!! disable collision between linked bodies
//m_btWorld->addConstraint(dofC, true);
}
}
}
}
brobone2 = brobone2->GetBrother();
}
}
}
if (curbone->GetChild()){
CreateBtConnectReq(curbone->GetChild());
}
if (curbone->GetBrother()){
CreateBtConnectReq(curbone->GetBrother());
}
}
/*
void CModel::CreateBtConnectReq( CBone* curbone )
{
char* findpat = strstr( (char*)curbone->GetBoneName(), "bunki" );
if( findpat ){
map<CBone*,CBtObject*>::iterator itrbto1;
for( itrbto1 = curbone->GetBtObjectMapBegin(); itrbto1 != curbone->GetBtObjectMapEnd(); itrbto1++ ){
CBtObject* bto1 = itrbto1->second;
map<CBone*,CBtObject*>::iterator itrbto2;
for( itrbto2 = curbone->GetBtObjectMapBegin(); itrbto2 != curbone->GetBtObjectMapEnd(); itrbto2++ ){
CBtObject* bto2 = itrbto2->second;
//if( (bto1 != bto2) && bto1->m_rigidbody && bto2->m_rigidbody && (bto1->m_connectflag == 0) && (bto2->m_connectflag == 0) ){
if( (bto1 != bto2) && bto1->GetRigidBody() && bto2->GetRigidBody() && (bto2->GetConnectFlag() == 0) ){
ChaVector3 diffchil;
diffchil = bto1->GetEndBone()->GetJointFPos() - bto2->GetEndBone()->GetJointFPos();
float diffleng = ChaVector3Length( &diffchil );
if( diffleng < 0.0001f ){
DbgOut( L"CreateBtConnect : bto1 %s--%s, bto2 %s--%s\r\n",
bto1->GetBone()->GetWBoneName(), bto1->GetEndBone()->GetWBoneName(),
bto2->GetBone()->GetWBoneName(), bto2->GetEndBone()->GetWBoneName()
);
float angPAI2, angPAI;
angPAI2 = 90.0f * (float)DEG2PAI;
angPAI = 180.0f * (float)DEG2PAI;
float lmax, lmin;
lmax = 10000.0f;
lmin = -10000.0f;
btGeneric6DofSpringConstraint* dofC;
btTransform tmpA, tmpA2;
bto1->GetFrameA( tmpA );
bto2->GetFrameA( tmpA2 );
dofC = new btGeneric6DofSpringConstraint( *bto1->GetRigidBody(), *bto2->GetRigidBody(), tmpA, tmpA2, true );
_ASSERT( dofC );
dofC->setLinearLowerLimit( btVector3( lmin, lmin, lmin ) );
dofC->setLinearUpperLimit( btVector3( lmax, lmax, lmax ) );
//dofC->setAngularLowerLimit( btVector3( -angPAI, -angPAI2, -angPAI ) );
//dofC->setAngularUpperLimit( btVector3( angPAI, angPAI2, angPAI ) );
dofC->setAngularLowerLimit( btVector3( angPAI, angPAI2, angPAI ) );
dofC->setAngularUpperLimit( btVector3( -angPAI, -angPAI2, -angPAI ) );
dofC->setBreakingImpulseThreshold( FLT_MAX );
int l_kindex = bto1->GetBone()->GetRigidElem( bto1->GetEndBone() )->GetLKindex();
int a_kindex = bto1->GetBone()->GetRigidElem( bto1->GetEndBone() )->GetAKindex();
float l_damping = bto1->GetBone()->GetRigidElem( bto1->GetEndBone() )->GetLDamping();
float a_damping = bto1->GetBone()->GetRigidElem( bto1->GetEndBone() )->GetADamping();
float l_cusk = bto1->GetBone()->GetRigidElem( bto1->GetEndBone() )->GetCusLk();
float a_cusk = bto1->GetBone()->GetRigidElem( bto1->GetEndBone() )->GetCusAk();
int dofid;
for( dofid = 0; dofid < 3; dofid++ ){
dofC->enableSpring( dofid, true );//!!!!!!!!!!!!!!!!!!!
//dofC->setStiffness( dofid, 1000.0f );
//dofC->setStiffness( dofid, 2000.0f );
dofC->setStiffness( dofid, 1.0e12 );
dofC->setDamping( dofid, 0.5f );
}
for( dofid = 3; dofid < 6; dofid++ ){
dofC->enableSpring( dofid, true );//!!!!!!!!!!!!!!!!!
//dofC->setStiffness( dofid, 0.5f );
dofC->setStiffness( dofid, 80.0f );
dofC->setDamping( dofid, 0.01f );
}
dofC->setEquilibriumPoint();
bto1->PushBackConstraint( dofC );
//m_btWorld->addConstraint(dofC, true);
m_btWorld->addConstraint(dofC, false);//!!!!!!!!!!!! disable collision between linked bodies
bto2->SetConnectFlag( 1 );
}
}
}
bto1->SetConnectFlag( 1 );
}
}
if( curbone->GetChild() ){
CreateBtConnectReq( curbone->GetChild() );
}
if( curbone->GetBrother() ){
CreateBtConnectReq( curbone->GetBrother() );
}
}
*/
int CModel::CreateBtObject( CModel* coldisp[COL_MAX], int onfirstcreate )
{
DestroyBtObject();
if( !m_topbone ){
return 0;
}
CalcBtAxismatReq( coldisp, m_topbone, 0.0f );//!!!!!!!!!!!!!
m_topbt = new CBtObject( 0, m_btWorld );
if( !m_topbt ){
_ASSERT( 0 );
return 1;
}
m_topbt->SetTopFlag( 1 );
//CBone* startbone = m_bonename[ "jiku_Joint_bunki" ];
//CBone* startbone = m_bonename[ "jiku_Joint" ];
CBone* startbone = m_topbone;
//CBone* startbone = m_bonename[ "Bip01" ];
_ASSERT( startbone );
CreateBtObjectReq( coldisp, m_topbt, startbone, startbone->GetChild() );
//CreateBtObjectReq( coldisp, m_topbt, startbone->m_parent, startbone );
/***
CBone* brobone = GetValidBroBone( startbone );
if( brobone ){
CreateBtObjectReq( coldisp, m_topbt, brobone, brobone->m_child );
brobone = brobone->m_brother;
}
***/
CreateBtConstraint();
if( m_topbt ){
SetBtKinFlagReq( m_topbt, onfirstcreate );
}
if (m_topbone){
SetBtEquilibriumPointReq(m_topbone);
}
return 0;
}
int CModel::SetBtEquilibriumPointReq( CBone* curbone )
{
map<CBone*, CBtObject*>::iterator itrbto;
for (itrbto = curbone->GetBtObjectMapBegin(); itrbto != curbone->GetBtObjectMapEnd(); itrbto++){
CBtObject* curbto = itrbto->second;
if (curbto){
int lflag, aflag;
double curframe = m_curmotinfo->curframe;
if (curframe == 0.0){
lflag = 1;
}
else{
lflag = 0;
}
aflag = 1;
curbto->SetEquilibriumPoint( lflag, aflag );
}
}
if (curbone->GetBrother()){
SetBtEquilibriumPointReq(curbone->GetBrother());
}
if (curbone->GetChild()){
SetBtEquilibriumPointReq(curbone->GetChild());
}
return 0;
}
void CModel::CreateBtObjectReq( CModel* cpslptr[COL_MAX], CBtObject* parbt, CBone* parbone, CBone* curbone )
{
map<CBone*, CRigidElem*> tmpmap;
curbone->GetRigidElemMap(tmpmap);
CBtObject* newbto = 0;
CBone* chilbone = 0;
map<CBone*, CRigidElem*>::iterator itrre;
for (itrre = tmpmap.begin(); itrre != tmpmap.end(); itrre++){
CRigidElem* curre = itrre->second;
chilbone = itrre->first;
ChaVector3 diffbone = curbone->GetJointFPos() - chilbone->GetJointFPos();
float leng = ChaVector3Length(&diffbone);
map<CBone*, CBone*>::iterator itrfind = m_rigidbone.find(chilbone);
if (curre && chilbone){
if (itrfind == m_rigidbone.end()){
if (curre->GetSkipflag() == 0){
DbgOut(L"CreateBtObject : curbone %s, chilbone %s\r\n",
curbone->GetWBoneName(), chilbone->GetWBoneName());
m_rigidbone[chilbone] = curbone;
newbto = new CBtObject(parbt, m_btWorld);
if (!newbto){
_ASSERT(0);
return;
}
CallF(newbto->CreateObject(parbt, parbone, curbone, chilbone), return);
curbone->SetBtObject(chilbone, newbto);
}
}
}
else{
_ASSERT(0);
}
}
if (curbone->GetChild()){
CreateBtObjectReq(cpslptr, newbto, curbone, curbone->GetChild());
}
if (curbone->GetBrother()){
CreateBtObjectReq(cpslptr, parbt, parbone, curbone->GetBrother());
}
}
void CModel::CalcBtAxismatReq( CModel* coldisp[COL_MAX], CBone* curbone, float delta )
{
int setstartflag;
if( delta == 0.0f ){
setstartflag = 1;
curbone->SetStartMat2( curbone->GetCurMp().GetWorldMat() );
}else{
setstartflag = 0;
}
if( curbone->GetChild() ){
//curbone->CalcAxisMat( firstflag, delta );
curbone->CalcRigidElemParams( coldisp, curbone->GetChild(), setstartflag );
CBone* bro = curbone->GetChild()->GetBrother();
while( bro ){
curbone->CalcRigidElemParams( coldisp, bro, setstartflag );
bro = bro->GetBrother();
}
DbgOut( L"check!!!!:CalcBtAxismatReq : %s, %s\r\n", curbone->GetWBoneName(), curbone->GetChild()->GetWBoneName() );
}
if( curbone->GetChild() ){
CalcBtAxismatReq( coldisp, curbone->GetChild(), delta );
}
if( curbone->GetBrother() ){
CalcBtAxismatReq( coldisp, curbone->GetBrother(), delta );
}
}
int CModel::SetBtMotion( int ragdollflag, double srcframe, ChaMatrix* wmat, ChaMatrix* vpmat, double difftime )
{
m_matWorld = *wmat;
m_matVP = *vpmat;
if( !m_topbt ){
_ASSERT( 0 );
return 0;
}
if( !m_curmotinfo ){
_ASSERT( 0 );
return 0;//!!!!!!!!!!!!
}
int curmotid = m_curmotinfo->motid;
double curframe = m_curmotinfo->curframe;
ChaMatrix inimat;
ChaMatrixIdentity( &inimat );
CQuaternion iniq;
iniq.SetParams( 1.0f, 0.0f, 0.0f, 0.0f );
map<int, CBone*>::iterator itrbone;
for( itrbone = m_bonelist.begin(); itrbone != m_bonelist.end(); itrbone++ ){
CBone* curbone = itrbone->second;
if( curbone ){
CMotionPoint curmp = curbone->GetCurMp();
curmp.SetBtFlag( 0 );
curbone->SetCurMp( curmp );
}
}
SetBtMotionReq( m_topbt, wmat, vpmat );
for( itrbone = m_bonelist.begin(); itrbone != m_bonelist.end(); itrbone++ ){
CBone* curbone = itrbone->second;
if( curbone && (curbone->GetCurMp().GetBtFlag() == 0) ){
if( g_previewFlag == 4 ){
if( curbone->GetBtKinFlag() == 0 ){
if( curbone->GetParent() ){
//curbone->m_curmp.m_btmat = curbone->m_parent->m_curmp.m_btmat;
ChaMatrix invstart;
ChaMatrixInverse( &invstart, NULL, &(curbone->GetParent()->GetStartMat2()) );
ChaMatrix diffmat;
diffmat = invstart * curbone->GetParent()->GetCurMp().GetBtMat();
CMotionPoint curmp = curbone->GetCurMp();
curmp.SetBtMat( curbone->GetStartMat2() * diffmat );
curbone->SetCurMp( curmp );
}else{
CMotionPoint curmp = curbone->GetCurMp();
curmp.SetBtMat( curbone->GetStartMat2() );
curbone->SetCurMp( curmp );
}
}else{
CMotionPoint curmp = curbone->GetCurMp();
curmp.SetBtMat( curmp.GetWorldMat() );
curbone->SetCurMp( curmp );
}
}else if( g_previewFlag == 5 ){
if( curbone->GetParent() ){
//curbone->m_curmp.m_btmat = curbone->m_parent->m_curmp.m_btmat;
ChaMatrix invstart;
ChaMatrixInverse( &invstart, NULL, &(curbone->GetParent()->GetStartMat2()) );
ChaMatrix diffmat;
diffmat = invstart * curbone->GetParent()->GetCurMp().GetBtMat();
CMotionPoint curmp = curbone->GetCurMp();
curmp.SetBtMat( curbone->GetStartMat2() * diffmat );
curbone->SetCurMp( curmp );
}else{
CMotionPoint curmp = curbone->GetCurMp();
curmp.SetBtMat( curbone->GetStartMat2() );
curbone->SetCurMp( curmp );
}
}
CMotionPoint curmp = curbone->GetCurMp();
curmp.SetBtFlag( 1 );
curbone->SetCurMp( curmp );
}
}
if (m_topbone){
SetBtEquilibriumPointReq(m_topbone);
}
/*
//resetbt処理との問題で一時的にコメントアウト
///// morph
if( (ragdollflag == 1) && (m_rgdmorphid >= 0) ){
MOTINFO* rgdmorphinfo = GetRgdMorphInfo();
if( rgdmorphinfo ){
double nextframe = 0.0;
int endflag = 0;
AdvanceTime( g_previewFlag, difftime, &nextframe, &endflag, rgdmorphinfo->motid );
rgdmorphinfo->curframe = nextframe;
DampAnim( rgdmorphinfo );
//DbgOut( L"!!!!! setbtmotion : rgd : morph : rgdmotid %d, curframe %f, difftime %f, frameleng %f\r\n",
// rgdmorphinfo->motid, rgdmorphinfo->curframe, difftime, rgdmorphinfo->frameleng );
FbxAnimStack * lCurrentAnimationStack = m_pscene->FindMember<FbxAnimStack>(mAnimStackNameArray[m_rgdmorphid]->Buffer());
if (lCurrentAnimationStack == NULL){
_ASSERT( 0 );
return 1;
}
FbxAnimLayer * mCurrentAnimLayer;
mCurrentAnimLayer = lCurrentAnimationStack->GetMember<FbxAnimLayer>();
FbxTime lTime;
lTime.SetSecondDouble( rgdmorphinfo->curframe / 30.0 );
// lTime.SetSecondDouble( rgdmorphinfo->curframe / 300.0 );
//lTime.SetTime(0, 0, 0, (int)rgdmorphinfo->curframe, 0, m_pscene->GetGlobalSettings().GetTimeMode());
map<int, CMQOObject*>::iterator itrobj;
for( itrobj = m_object.begin(); itrobj != m_object.end(); itrobj++ ){
CMQOObject* curobj = itrobj->second;
_ASSERT( curobj );
if( !(curobj->EmptyFindShape()) ){
GetShapeWeight( m_fbxobj[curobj].node, m_fbxobj[curobj].mesh, lTime, mCurrentAnimLayer, curobj );
CallF( curobj->UpdateMorphBuffer(), return 1 );
}
}
}
}
*/
return 0;
}
int CModel::DampAnim( MOTINFO* rgdmorphinfo )
{
if( !rgdmorphinfo || (m_rgdindex < 0) ){
return 0;
}
double diffframe = rgdmorphinfo->curframe;
if( m_rgdindex >= (int)m_rigideleminfo.size() ){
_ASSERT( 0 );
return 0;
}
//float minval = 0.000050f;
float minval = 0.000005f;
map<int,CBone*>::iterator itrbone;
for( itrbone = m_bonelist.begin(); itrbone != m_bonelist.end(); itrbone++ ){
CBone* curbone = itrbone->second;
if( curbone ){
CBone* parbone = curbone->GetParent();
if( parbone ){
CRigidElem* curre = parbone->GetRigidElem( curbone );
if( curre ){
float newdampl = curre->GetLDamping() - (float)diffframe * curre->GetDampanimL() * curre->GetLDamping();
if( newdampl < minval ){
newdampl = minval;
}
float newdampa = curre->GetADamping() - (float)diffframe * curre->GetDampanimA() * curre->GetADamping();
if( newdampa < minval ){
newdampa = minval;
}
CBtObject* curbto = FindBtObject( curbone->GetBoneNo() );
if( curbto ){
int constraintnum = curbto->GetConstraintSize();
int constraintno;
for( constraintno = 0; constraintno < constraintnum; constraintno++ ){
btGeneric6DofSpringConstraint* curct = curbto->GetConstraint( constraintno );
if( curct ){
int dofid;
for( dofid = 0; dofid < 3; dofid++ ){
curct->setDamping( dofid, newdampl );
}
for( dofid = 3; dofid < 6; dofid++ ){
curct->setDamping( dofid, newdampa );
}
}
}
}
}
}
}
}
return 0;
}
MOTINFO* CModel::GetRgdMorphInfo()
{
MOTINFO* retmi = 0;
int motionnum = m_motinfo.size();
if( m_rgdmorphid < motionnum ){
map<int,MOTINFO*>::iterator itrmi;
itrmi = m_motinfo.begin();
int infcnt;
for( infcnt = 0; infcnt < m_rgdmorphid; infcnt++ ){
itrmi++;
if( itrmi == m_motinfo.end() ){
break;
}
}
if( itrmi != m_motinfo.end() ){
retmi = itrmi->second;
}
}
return retmi;
}
void CModel::SetBtMotionReq( CBtObject* curbto, ChaMatrix* wmat, ChaMatrix* vpmat )
{
if( g_previewFlag == 4 ){
if( (curbto->GetTopFlag() == 0) && curbto->GetBone() && (curbto->GetBone()->GetBtKinFlag() == 0) ){
curbto->SetBtMotion();
}
}else if( g_previewFlag == 5 ){
if( (curbto->GetTopFlag() == 0) && curbto->GetBone() ){
curbto->SetBtMotion();
}
}
int chilno;
for( chilno = 0; chilno < curbto->GetChilBtSize(); chilno++ ){
CBtObject* chilbto = curbto->GetChilBt( chilno );
if( chilbto ){
SetBtMotionReq( chilbto, wmat, vpmat );
}
}
}
void CModel::CreateRigidElemReq( CBone* curbone, int reflag, string rename, int impflag, string impname )
{
CBone* parbone = curbone->GetParent();
if (parbone){
parbone->CreateRigidElem(curbone, reflag, rename, impflag, impname);
}
/*
CBone* chil = curbone->GetChild();
if( chil ){
curbone->CreateRigidElem( chil, reflag, rename, impflag, impname );
CBone* chilbro;
chilbro = chil->GetBrother();
while( chilbro ){
curbone->CreateRigidElem( chilbro, reflag, rename, impflag, impname );
chilbro = chilbro->GetBrother();
}
}
*/
if( curbone->GetChild() ){
CreateRigidElemReq( curbone->GetChild(), reflag, rename, impflag, impname );
}
if( curbone->GetBrother() ){
CreateRigidElemReq( curbone->GetBrother(), reflag, rename, impflag, impname );
}
}
int CModel::SetBtImpulse()
{
if( !m_topbt ){
return 0;
}
if( !m_topbone ){
return 0;
}
SetBtImpulseReq( m_topbone );
return 0;
}
void CModel::SetBtImpulseReq( CBone* srcbone )
{
CBone* parbone = srcbone->GetParent();
if( parbone ){
ChaVector3 setimp( 0.0f, 0.0f, 0.0f );
int impnum = parbone->GetImpMapSize();
if( (m_curimpindex >= 0) && (m_curimpindex < impnum) ){
string curimpname = m_impinfo[ m_curimpindex ];
map<string, map<CBone*, ChaVector3>>::iterator findimpmap;
findimpmap = parbone->FindImpMap( curimpname );
if( findimpmap != parbone->GetImpMapEnd() ){
map<CBone*,ChaVector3>::iterator itrimp;
itrimp = findimpmap->second.find( srcbone );
if( itrimp != findimpmap->second.end() ){
setimp = itrimp->second;
}
}
}
else{
_ASSERT(0);
}
CRigidElem* curre = parbone->GetRigidElem( srcbone );
if( curre ){
ChaVector3 imp = setimp * g_impscale;
CBtObject* findbto = FindBtObject( srcbone->GetBoneNo() );
if( findbto && findbto->GetRigidBody() ){
findbto->GetRigidBody()->applyImpulse( btVector3( imp.x, imp.y, imp.z ), btVector3( 0.0f, 0.0f, 0.0f ) );
}
}
else{
_ASSERT(0);
}
}
if( srcbone->GetChild() ){
SetBtImpulseReq( srcbone->GetChild() );
}
if( srcbone->GetBrother() ){
SetBtImpulseReq( srcbone->GetBrother() );
}
}
CBtObject* CModel::FindBtObject( int srcboneno )
{
CBtObject* retbto = 0;
if( !m_topbt ){
return 0;
}
FindBtObjectReq( m_topbt, srcboneno, &retbto );
return retbto;
}
void CModel::FindBtObjectReq( CBtObject* srcbto, int srcboneno, CBtObject** ppret )
{
if( *ppret ){
return;
}
if( srcbto->GetBone() ){
CBone* curbone;
curbone = m_bonelist[ srcboneno ];
if( curbone ){
CBone* parbone;
parbone = curbone->GetParent();
if( parbone ){
if( (srcbto->GetBone() == parbone) && (srcbto->GetEndBone() == curbone) ){
*ppret = srcbto;
return;
}
}
}
}
int chilno;
for( chilno = 0; chilno < srcbto->GetChilBtSize(); chilno++ ){
CBtObject* chilbto = srcbto->GetChilBt( chilno );
FindBtObjectReq( chilbto, srcboneno, ppret );
}
}
int CModel::SetDispFlag( char* srcobjname, int srcflag )
{
CMQOObject* curobj = m_objectname[ srcobjname ];
if( curobj ){
curobj->SetDispFlag( srcflag );
}
return 0;
}
int CModel::EnableAllRigidElem(int srcrgdindex)
{
if (!m_topbone){
return 0;
}
EnableAllRigidElemReq(m_topbone, srcrgdindex);
return 0;
}
int CModel::DisableAllRigidElem(int srcrgdindex)
{
if (!m_topbone){
return 0;
}
DisableAllRigidElemReq(m_topbone, srcrgdindex);
return 0;
}
void CModel::EnableAllRigidElemReq(CBone* srcbone, int srcrgdindex)
{
if ((srcrgdindex >= 0) && (srcrgdindex < m_rigideleminfo.size())){
if (srcbone->GetParent()){
char* filename = m_rigideleminfo[srcrgdindex].filename;
CRigidElem* curre = srcbone->GetParent()->GetRigidElemOfMap(filename, srcbone);
if (curre){
//if (curre->GetBoneLeng() >= 0.00001f){
curre->SetSkipflag(0);
//}
}
}
}
else{
_ASSERT(0);
}
if (srcbone->GetChild()){
EnableAllRigidElemReq(srcbone->GetChild(), srcrgdindex);
}
if (srcbone->GetBrother()){
EnableAllRigidElemReq(srcbone->GetBrother(), srcrgdindex);
}
}
void CModel::DisableAllRigidElemReq(CBone* srcbone, int srcrgdindex)
{
if ((srcrgdindex >= 0) && (srcrgdindex < m_rigideleminfo.size())){
if (srcbone->GetParent()){
char* filename = m_rigideleminfo[srcrgdindex].filename;
CRigidElem* curre = srcbone->GetParent()->GetRigidElemOfMap(filename, srcbone);
if (curre){
curre->SetSkipflag(1);
}
}
}
else{
_ASSERT(0);
}
if (srcbone->GetChild()){
DisableAllRigidElemReq(srcbone->GetChild(), srcrgdindex);
}
if (srcbone->GetBrother()){
DisableAllRigidElemReq(srcbone->GetBrother(), srcrgdindex);
}
}
int CModel::SetAllBtgData( int gid, int reindex, float btg )
{
if( !m_topbone ){
return 0;
}
if( reindex < 0 ){
return 0;
}
SetBtgDataReq( gid, reindex, m_topbone, btg );
return 0;
}
void CModel::SetBtgDataReq( int gid, int reindex, CBone* srcbone, float btg )
{
if ((reindex >= 0) && (reindex < m_rigideleminfo.size())){
if (srcbone->GetParent()){
char* filename = m_rigideleminfo[reindex].filename;
CRigidElem* curre = srcbone->GetParent()->GetRigidElemOfMap(filename, srcbone);
if (curre){
if ((gid == -1) || (gid == curre->GetGroupid())){
curre->SetBtg(btg);
}
}
}
}
else{
_ASSERT(0);
}
if( srcbone->GetChild() ){
SetBtgDataReq( gid, reindex, srcbone->GetChild(), btg );
}
if( srcbone->GetBrother() ){
SetBtgDataReq( gid, reindex, srcbone->GetBrother(), btg );
}
}
int CModel::SetAllDampAnimData( int gid, int rgdindex, float valL, float valA )
{
if( !m_topbone ){
return 0;
}
if( rgdindex < 0 ){
return 0;
}
SetDampAnimDataReq( gid, rgdindex, m_topbone, valL, valA );
return 0;
}
void CModel::SetDampAnimDataReq( int gid, int rgdindex, CBone* srcbone, float valL, float valA )
{
if( rgdindex < 0 ){
return;
}
if ((rgdindex >= 0) && (rgdindex < m_rigideleminfo.size())){
if (srcbone->GetParent()){
char* filename = m_rigideleminfo[rgdindex].filename;
CRigidElem* curre = srcbone->GetParent()->GetRigidElemOfMap(filename, srcbone);
if (curre){
if ((gid == -1) || (gid == curre->GetGroupid())){
curre->SetDampanimL(valL);
curre->SetDampanimA(valA);
}
}
}
}
else{
_ASSERT(0);
}
if( srcbone->GetChild() ){
SetDampAnimDataReq( gid, rgdindex, srcbone->GetChild(), valL, valA );
}
if( srcbone->GetBrother() ){
SetDampAnimDataReq( gid, rgdindex, srcbone->GetBrother(), valL, valA );
}
}
int CModel::SetAllImpulseData( int gid, float impx, float impy, float impz )
{
if( !m_topbone ){
return 0;
}
ChaVector3 srcimp = ChaVector3( impx, impy, impz );
SetImpulseDataReq( gid, m_topbone, srcimp );
return 0;
}
void CModel::SetImpulseDataReq( int gid, CBone* srcbone, ChaVector3 srcimp )
{
if ((m_rgdindex < 0) || (m_rgdindex >= m_rigideleminfo.size())){
return;
}
CBone* parbone = srcbone->GetParent();
if( parbone ){
int renum = m_rigideleminfo.size();
int impnum = parbone->GetImpMapSize();
if( (m_curimpindex >= 0) && (m_curimpindex < impnum) && (m_curreindex >= 0) && (m_curreindex < renum) ){
char* filename = m_rigideleminfo[m_rgdindex].filename;//!!! rgdindex !!!
CRigidElem* curre = parbone->GetRigidElemOfMap( filename, srcbone );
if( curre ){
if( (gid == -1) || (gid == curre->GetGroupid()) ){
string curimpname = m_impinfo[ m_curimpindex ];
map<string, map<CBone*, ChaVector3>>::iterator findimpmap;
findimpmap = parbone->FindImpMap( curimpname );
if( findimpmap != parbone->GetImpMapEnd() ){
map<CBone*,ChaVector3>::iterator itrimp;
itrimp = findimpmap->second.find( srcbone );
if( itrimp != findimpmap->second.end() ){
itrimp->second = srcimp;
}
}
}
}
}
}
if( srcbone->GetChild() ){
SetImpulseDataReq( gid, srcbone->GetChild(), srcimp );
}
if( srcbone->GetBrother() ){
SetImpulseDataReq( gid, srcbone->GetBrother(), srcimp );
}
}
int CModel::SetImp( int srcboneno, int kind, float srcval )
{
if( !m_topbone ){
return 0;
}
if( srcboneno < 0 ){
return 0;
}
if( m_curimpindex < 0 ){
return 0;
}
CBone* curbone = m_bonelist[srcboneno];
if( !curbone ){
return 0;
}
CBone* parbone = curbone->GetParent();
if( !parbone ){
return 0;
}
int impnum = parbone->GetImpMapSize();
if( m_curimpindex >= impnum ){
_ASSERT( 0 );
return 0;
}
string curimpname = m_impinfo[ m_curimpindex ];
if( parbone->GetImpMapSize2( curimpname ) > 0 ){
map<string, map<CBone*, ChaVector3>>::iterator itrfindmap;
itrfindmap = parbone->FindImpMap( curimpname );
map<CBone*,ChaVector3>::iterator itrimp;
itrimp = itrfindmap->second.find( curbone );
if( itrimp == itrfindmap->second.end() ){
if (kind == 0){
itrfindmap->second[curbone].x = srcval;
}
else if (kind == 1){
itrfindmap->second[curbone].y = srcval;
}
else if (kind == 2){
itrfindmap->second[curbone].z = srcval;
}
}
else{
if (kind == 0){
itrimp->second.x = srcval;
}
else if (kind == 1){
itrimp->second.y = srcval;
}
else if (kind == 2){
itrimp->second.z = srcval;
}
}
}else{
_ASSERT( 0 );
}
return 0;
}
int CModel::SetAllDmpData( int gid, int reindex, float ldmp, float admp )
{
if( !m_topbone ){
return 0;
}
if( reindex < 0 ){
return 0;
}
SetDmpDataReq( gid, reindex, m_topbone, ldmp, admp );
return 0;
}
void CModel::SetDmpDataReq( int gid, int reindex, CBone* srcbone, float ldmp, float admp )
{
if( srcbone->GetParent() ){
if ((reindex >= 0) && (reindex < m_rigideleminfo.size())){
char* filename = m_rigideleminfo[reindex].filename;
CRigidElem* curre = srcbone->GetParent()->GetRigidElemOfMap(filename, srcbone);
if (curre){
if ((gid == -1) || (gid == curre->GetGroupid())){
curre->SetLDamping(ldmp);
curre->SetADamping(admp);
}
}
}
else{
_ASSERT(0);
}
}
if( srcbone->GetChild() ){
SetDmpDataReq( gid, reindex, srcbone->GetChild(), ldmp, admp );
}
if( srcbone->GetBrother() ){
SetDmpDataReq( gid, reindex, srcbone->GetBrother(), ldmp, admp );
}
}
int CModel::SetAllRestData( int gid, int reindex, float rest, float fric )
{
if( !m_topbone ){
return 0;
}
if( reindex < 0 ){
return 0;
}
SetRestDataReq( gid, reindex, m_topbone, rest, fric );
return 0;
}
void CModel::SetRestDataReq( int gid, int reindex, CBone* srcbone, float rest, float fric )
{
if( srcbone->GetParent() ){
if ((reindex >= 0) && (reindex < m_rigideleminfo.size())){
char* filename = m_rigideleminfo[reindex].filename;
CRigidElem* curre = srcbone->GetParent()->GetRigidElemOfMap(filename, srcbone);
if (curre){
if ((gid == -1) || (gid == curre->GetGroupid())){
curre->SetRestitution(rest);
curre->SetFriction(fric);
}
}
}
else{
_ASSERT(0);
}
}
if( srcbone->GetChild() ){
SetRestDataReq( gid, reindex, srcbone->GetChild(), rest, fric );
}
if( srcbone->GetBrother() ){
SetRestDataReq( gid, reindex, srcbone->GetBrother(), rest, fric );
}
}
int CModel::SetAllKData( int gid, int reindex, int srclk, int srcak, float srccuslk, float srccusak )
{
if( !m_topbone ){
return 0;
}
if( reindex < 0 ){
return 0;
}
SetKDataReq( gid, reindex, m_topbone, srclk, srcak, srccuslk, srccusak );
return 0;
}
void CModel::SetKDataReq( int gid, int reindex, CBone* srcbone, int srclk, int srcak, float srccuslk, float srccusak )
{
if( srcbone->GetParent() ){
if ((reindex >= 0) && (reindex < m_rigideleminfo.size())){
char* filename = m_rigideleminfo[reindex].filename;
CRigidElem* curre = srcbone->GetParent()->GetRigidElemOfMap(filename, srcbone);
if (curre){
if ((gid == -1) || (gid == curre->GetGroupid())){
curre->SetLKindex(srclk);
curre->SetAKindex(srcak);
curre->SetCusLk(srccuslk);
curre->SetCusAk(srccusak);
}
}
}
else{
_ASSERT(0);
}
}
if( srcbone->GetChild() ){
SetKDataReq( gid, reindex, srcbone->GetChild(), srclk, srcak, srccuslk, srccusak );
}
if( srcbone->GetBrother() ){
SetKDataReq( gid, reindex, srcbone->GetBrother(), srclk, srcak, srccuslk, srccusak );
}
}
int CModel::SetAllMassData( int gid, int reindex, float srcmass )
{
if( !m_topbone ){
return 0;
}
if( reindex < 0 ){
return 0;
}
SetMassDataReq( gid, reindex, m_topbone, srcmass );
return 0;
}
void CModel::SetMassDataReq( int gid, int reindex, CBone* srcbone, float srcmass )
{
if( srcbone->GetParent() ){
if ((reindex >= 0) && (reindex < m_rigideleminfo.size())){
char* filename = m_rigideleminfo[reindex].filename;
CRigidElem* curre = srcbone->GetParent()->GetRigidElemOfMap(filename, srcbone);
if (curre){
if ((gid == -1) || (gid == curre->GetGroupid())){
curre->SetMass(srcmass);
}
}
}
else{
_ASSERT(0);
}
}
if( srcbone->GetChild() ){
SetMassDataReq( gid, reindex, srcbone->GetChild(), srcmass );
}
if( srcbone->GetBrother() ){
SetMassDataReq( gid, reindex, srcbone->GetBrother(), srcmass );
}
}
int CModel::SetRagdollKinFlag()
{
if( !m_topbt ){
return 0;
}
SetRagdollKinFlagReq( m_topbt );
return 0;
}
void CModel::SetRagdollKinFlagReq( CBtObject* srcbto )
{
if( srcbto->GetBone() && srcbto->GetRigidBody() ){
DWORD curflag = srcbto->GetRigidBody()->getCollisionFlags();
srcbto->GetRigidBody()->setCollisionFlags( curflag & ~btCollisionObject::CF_KINEMATIC_OBJECT);
// _ASSERT( s_setrigidflag );
// srcbto->m_rigidbody->setCollisionFlags( s_rigidflag );
// srcbto->m_rigidbody->setCollisionFlags( s_rigidflag | btCollisionObject::CF_STATIC_OBJECT);
// srcbto->m_rigidbody->setActivationState(DISABLE_DEACTIVATION);
if( srcbto->GetBone()->GetParent() ){
CRigidElem* curre = srcbto->GetBone()->GetParent()->GetRigidElem( srcbto->GetBone() );
if( curre ){
if ((m_rgdindex >= 0) && (m_rgdindex < m_rigideleminfo.size())){
srcbto->GetRigidBody()->setGravity(btVector3(0.0f, curre->GetBtg() * m_rigideleminfo[m_rgdindex].btgscale, 0.0f));
srcbto->GetRigidBody()->applyGravity();
}
else{
_ASSERT(0);
}
}
}
}
int chilno;
for( chilno = 0; chilno < srcbto->GetChilBtSize(); chilno++ ){
CBtObject* chilbto = srcbto->GetChilBt( chilno );
if( chilbto ){
SetRagdollKinFlagReq( chilbto );
}
}
}
int CModel::SetCurrentRigidElem( int curindex )
{
if( curindex < 0 ){
return 0;
}
if( curindex >= (int)m_rigideleminfo.size() ){
_ASSERT( 0 );
return 0;
}
m_curreindex = curindex;
string curname = m_rigideleminfo[ curindex ].filename;
map<int,CBone*>::iterator itrbone;
for( itrbone = m_bonelist.begin(); itrbone != m_bonelist.end(); itrbone++ ){
CBone* curbone = itrbone->second;
CallF( curbone->SetCurrentRigidElem( curname ), return 1 );
}
return 0;
}
int CModel::MultDispObj( ChaVector3 srcmult, ChaVector3 srctra )
{
map<int,CMQOObject*>::iterator itrobj;
for( itrobj = m_object.begin(); itrobj != m_object.end(); itrobj++ ){
CMQOObject* curobj = itrobj->second;
if( curobj ){
CallF( curobj->MultScale( srcmult, srctra ), return 1 );
}
}
return 0;
}
int CModel::SetColiIDtoGroup( CRigidElem* srcre )
{
if( !m_topbone ){
return 0;
}
if( m_curreindex < 0 ){
return 0;
}
SetColiIDReq( m_topbone, srcre );
return 0;
}
void CModel::SetColiIDReq( CBone* srcbone, CRigidElem* srcre )
{
if( srcbone->GetParent() ){
if ((m_curreindex >= 0) && (m_curreindex < m_rigideleminfo.size())){
char* filename = m_rigideleminfo[m_curreindex].filename;
CRigidElem* curre = srcbone->GetParent()->GetRigidElemOfMap(filename, srcbone);
if (curre){
if (curre->GetGroupid() == srcre->GetGroupid()){
curre->CopyColiids(srcre);
}
}
}
else{
_ASSERT(0);
}
}
if( srcbone->GetChild() ){
SetColiIDReq( srcbone->GetChild(), srcre );
}
if( srcbone->GetBrother() ){
SetColiIDReq( srcbone->GetBrother(), srcre );
}
}
int CModel::ResetBt()
{
if( !m_topbt ){
return 0;
}
ResetBtReq( m_topbt );
return 0;
}
void CModel::ResetBtReq( CBtObject* curbto )
{
if( curbto->GetRigidBody() ){
if (curbto->GetRigidBody()->getMotionState())
{
btDefaultMotionState* myMotionState = (btDefaultMotionState*)curbto->GetRigidBody()->getMotionState();
myMotionState->m_graphicsWorldTrans = myMotionState->m_startWorldTrans;
curbto->GetRigidBody()->setCenterOfMassTransform( myMotionState->m_graphicsWorldTrans );
curbto->GetRigidBody()->setInterpolationWorldTransform( myMotionState->m_startWorldTrans );
curbto->GetRigidBody()->forceActivationState(ACTIVE_TAG);
curbto->GetRigidBody()->activate();
curbto->GetRigidBody()->setDeactivationTime(0);
//colObj->setActivationState(WANTS_DEACTIVATION);
}
if (curbto->GetRigidBody() && !curbto->GetRigidBody()->isStaticObject())
{
curbto->GetRigidBody()->setLinearVelocity(btVector3(0,0,0));
curbto->GetRigidBody()->setAngularVelocity(btVector3(0,0,0));
}
}
int chilno;
for( chilno = 0; chilno < curbto->GetChilBtSize(); chilno++ ){
CBtObject* chilbto = curbto->GetChilBt( chilno );
if( chilbto ){
ResetBtReq( chilbto );
}
}
}
int CModel::SetBefEditMat( CEditRange* erptr, CBone* curbone, int maxlevel )
{
int levelcnt0 = 0;
while( curbone && ((maxlevel == 0) || (levelcnt0 < (maxlevel+1))) )
{
list<KeyInfo>::iterator itrki;
double firstframe = 0.0;
for( itrki = erptr->m_ki.begin(); itrki != erptr->m_ki.end(); itrki++ ){
double curframe = itrki->time;
int existflag3 = 0;
CMotionPoint* editmp = 0;
CMotionPoint* nextmp = 0;
curbone->GetBefNextMP( m_curmotinfo->motid, curframe, &editmp, &nextmp, &existflag3 );
if( existflag3 ){
editmp->SetBefEditMat( editmp->GetWorldMat() );
}else{
_ASSERT( 0 );
}
}
curbone = curbone->GetParent();
levelcnt0++;
}
return 0;
}
int CModel::SetBefEditMatFK( CEditRange* erptr, CBone* curbone )
{
list<KeyInfo>::iterator itrki;
double firstframe = 0.0;
for( itrki = erptr->m_ki.begin(); itrki != erptr->m_ki.end(); itrki++ ){
double curframe = itrki->time;
int existflag3 = 0;
CMotionPoint* editmp = 0;
CMotionPoint* nextmp = 0;
curbone->GetBefNextMP( m_curmotinfo->motid, curframe, &editmp, &nextmp, &existflag3 );
if( existflag3 ){
editmp->SetBefEditMat( editmp->GetWorldMat() );
}else{
_ASSERT( 0 );
}
}
return 0;
}
int CModel::IKRotate( CEditRange* erptr, int srcboneno, ChaVector3 targetpos, int maxlevel )
{
CBone* firstbone = m_bonelist[ srcboneno ];
if( !firstbone ){
_ASSERT( 0 );
return -1;
}
ChaVector3 ikaxis = g_camtargetpos - g_camEye;
ChaVector3Normalize( &ikaxis, &ikaxis );
int keynum;
double startframe, endframe, applyframe;
erptr->GetRange( &keynum, &startframe, &endframe, &applyframe );
CBone* curbone = firstbone;
SetBefEditMat( erptr, curbone, maxlevel );
CBone* lastpar = firstbone->GetParent();
curbone = firstbone;
int calcnum = 3;
int calccnt;
for( calccnt = 0; calccnt < calcnum; calccnt++ ){
int levelcnt = 0;
float currate = 1.0f;
CBone* curbone = firstbone;
while( curbone && ((maxlevel == 0) || (levelcnt < maxlevel)) )
{
CBone* parbone = curbone->GetParent();
if( parbone && (curbone->GetJointFPos() != parbone->GetJointFPos()) ){
ChaVector3 parworld, chilworld;
ChaVector3TransformCoord( &chilworld, &(curbone->GetJointFPos()), &(curbone->GetCurMp().GetWorldMat()) );
ChaVector3TransformCoord( &parworld, &(parbone->GetJointFPos()), &(parbone->GetCurMp().GetWorldMat()) );
ChaVector3 parbef, chilbef, tarbef;
parbef = parworld;
CalcShadowToPlane( chilworld, ikaxis, parworld, &chilbef );
CalcShadowToPlane( targetpos, ikaxis, parworld, &tarbef );
ChaVector3 vec0, vec1;
vec0 = chilbef - parbef;
ChaVector3Normalize( &vec0, &vec0 );
vec1 = tarbef - parbef;
ChaVector3Normalize( &vec1, &vec1 );
ChaVector3 rotaxis2;
ChaVector3Cross( &rotaxis2, &vec0, &vec1 );
ChaVector3Normalize( &rotaxis2, &rotaxis2 );
float rotdot2, rotrad2;
rotdot2 = ChaVector3Dot( &vec0, &vec1 );
rotdot2 = min( 1.0f, rotdot2 );
rotdot2 = max( -1.0f, rotdot2 );
rotrad2 = (float)acos( rotdot2 );
rotrad2 *= currate;
double firstframe = 0.0;
if( fabs( rotrad2 ) > 1.0e-4 ){
CQuaternion rotq;
rotq.SetAxisAndRot( rotaxis2, rotrad2 );
if( keynum >= 2 ){
int keyno = 0;
list<KeyInfo>::iterator itrki;
for( itrki = erptr->m_ki.begin(); itrki != erptr->m_ki.end(); itrki++ ){
double curframe = itrki->time;
double changerate;
if( curframe <= applyframe ){
if( applyframe != startframe ){
changerate = 1.0 / (applyframe - startframe);
}else{
changerate = 1.0;
}
}else{
if( applyframe != endframe ){
changerate = 1.0 / (endframe - applyframe );
}else{
changerate = 0.0;
}
}
if( keyno == 0 ){
firstframe = curframe;
}
if( g_absikflag == 0 ){
if( g_slerpoffflag == 0 ){
CQuaternion endq;
endq.SetParams( 1.0f, 0.0f, 0.0f, 0.0f );
CQuaternion curq;
double currate2;
if( curframe <= applyframe ){
if( applyframe != startframe ){
currate2 = changerate * (curframe - startframe);
}else{
currate2 = 1.0;
}
}else{
currate2 = changerate * (endframe - curframe);
}
rotq.Slerp2( endq, 1.0 - currate2, &curq );
parbone->RotBoneQReq( 0, m_curmotinfo->motid, curframe, curq );
}else{
parbone->RotBoneQReq( 0, m_curmotinfo->motid, curframe, rotq );
}
}else{
if( keyno == 0 ){
parbone->RotBoneQReq( 0, m_curmotinfo->motid, curframe, rotq );
}else{
parbone->SetAbsMatReq( 0, m_curmotinfo->motid, curframe, firstframe );
}
}
keyno++;
}
}else{
parbone->RotBoneQReq( 0, m_curmotinfo->motid, m_curmotinfo->curframe, rotq );
}
if( g_applyendflag == 1 ){
//curmotinfo->curframeから最後までcurmotinfo->curframeの姿勢を適用
int tolast;
for( tolast = (int)m_curmotinfo->curframe + 1; tolast < m_curmotinfo->frameleng; tolast++ ){
(m_bonelist[ 0 ])->PasteRotReq( m_curmotinfo->motid, m_curmotinfo->curframe, tolast );
}
}
//parbone->RotBoneQReq( 0, m_curmotinfo->motid, m_curmotinfo->curframe, rotq );
UpdateMatrix( &m_matWorld, &m_matVP );
}else{
UpdateMatrix( &m_matWorld, &m_matVP );
}
}
if( curbone->GetParent() ){
lastpar = curbone->GetParent();
}
curbone = curbone->GetParent();
levelcnt++;
currate = pow( g_ikrate, g_ikfirst * levelcnt );
}
if( (calccnt == (calcnum - 1)) && g_absikflag && lastpar ){
AdjustBoneTra( erptr, lastpar );
}
}
if( lastpar ){
return lastpar->GetBoneNo();
}else{
return srcboneno;
}
}
int CModel::AdjustBoneTra( CEditRange* erptr, CBone* lastpar )
{
if( g_applyendflag == 1 ){
if( lastpar && (erptr->m_ki.size() >= 2) ){
list<KeyInfo>::iterator itrki;
int keyno = 0;
int startframe = (int)erptr->m_ki.begin()->time;
int endframe = (int)m_curmotinfo->frameleng - 1;
double curframe;
for( curframe = startframe; curframe <= endframe; curframe += 1.0 ){
if( keyno >= 1 ){
int existflag2 = 0;
CMotionPoint* pbef = 0;
CMotionPoint* pnext = 0;
int curmotid = m_curmotinfo->motid;
lastpar->GetBefNextMP( curmotid, curframe, &pbef, &pnext, &existflag2 );
if( existflag2 ){
ChaVector3 orgpos;
ChaVector3TransformCoord( &orgpos, &(lastpar->GetJointFPos()), &(pbef->GetBefEditMat()) );
ChaVector3 newpos;
ChaVector3TransformCoord( &newpos, &(lastpar->GetJointFPos()), &(pbef->GetWorldMat()) );
ChaVector3 diffpos;
diffpos = orgpos - newpos;
CEditRange tmper;
KeyInfo tmpki;
tmpki.time = curframe;
list<KeyInfo> tmplist;
tmplist.push_back( tmpki );
tmper.SetRange( tmplist, curframe );
FKBoneTra( &tmper, lastpar->GetBoneNo(), diffpos );
}
}
keyno++;
}
}
}else{
if( lastpar && (erptr->m_ki.size() >= 2) ){
list<KeyInfo>::iterator itrki;
int keyno = 0;
for( itrki = erptr->m_ki.begin(); itrki != erptr->m_ki.end(); itrki++ ){
if( keyno >= 1 ){
double curframe = itrki->time;
int existflag2 = 0;
CMotionPoint* pbef = 0;
CMotionPoint* pnext = 0;
int curmotid = m_curmotinfo->motid;
lastpar->GetBefNextMP( curmotid, curframe, &pbef, &pnext, &existflag2 );
if( existflag2 ){
ChaVector3 orgpos;
ChaVector3TransformCoord( &orgpos, &(lastpar->GetJointFPos()), &(pbef->GetBefEditMat()) );
ChaVector3 newpos;
ChaVector3TransformCoord( &newpos, &(lastpar->GetJointFPos()), &(pbef->GetWorldMat()) );
ChaVector3 diffpos;
diffpos = orgpos - newpos;
CEditRange tmper;
KeyInfo tmpki;
tmpki.time = curframe;
list<KeyInfo> tmplist;
tmplist.push_back( tmpki );
tmper.SetRange( tmplist, curframe );
FKBoneTra( &tmper, lastpar->GetBoneNo(), diffpos );
}
}
keyno++;
}
}
}
return 0;
}
int CModel::IKRotateAxisDelta( CEditRange* erptr, int axiskind, int srcboneno, float delta, int maxlevel, int ikcnt )
{
ChaMatrix selectmat = ChaMatrix( 0.0f, 0.0f, 0.0f, 0.0f,
0.0f, 0.0f, 0.0f, 0.0f,
0.0f, 0.0f, 0.0f, 0.0f,
0.0f, 0.0f, 0.0f, 0.0f );
int levelcnt = 0;
CBone* firstbone = m_bonelist[ srcboneno ];
if( !firstbone ){
_ASSERT( 0 );
return 1;
}
CBone* curbone = firstbone;
SetBefEditMat( erptr, curbone, maxlevel );
CBone* calcrootbone = GetCalcRootBone( firstbone, maxlevel );
_ASSERT( calcrootbone );
ChaVector3 rootpos = calcrootbone->GetChildWorld();
ChaVector3 axis0;
ChaVector3 targetpos;
ChaMatrix mat, befrotmat, rotmat, aftrotmat;
float rotrad;
selectmat = firstbone->GetAxisMatPar() * firstbone->GetCurMp().GetWorldMat();
selectmat._41 = 0.0f;
selectmat._42 = 0.0f;
selectmat._43 = 0.0f;
if( axiskind == PICK_X ){
axis0 = ChaVector3( 1.0f, 0.0f, 0.0f );
ChaVector3TransformCoord( &m_ikrotaxis, &axis0, &selectmat );
ChaVector3Normalize( &m_ikrotaxis, &m_ikrotaxis );
}else if( axiskind == PICK_Y ){
axis0 = ChaVector3( 0.0f, 1.0f, 0.0f );
ChaVector3TransformCoord( &m_ikrotaxis, &axis0, &selectmat );
ChaVector3Normalize( &m_ikrotaxis, &m_ikrotaxis );
}else if( axiskind == PICK_Z ){
axis0 = ChaVector3( 0.0f, 0.0f, 1.0f );
ChaVector3TransformCoord( &m_ikrotaxis, &axis0, &selectmat );
ChaVector3Normalize( &m_ikrotaxis, &m_ikrotaxis );
}else{
_ASSERT( 0 );
return 1;
}
rotrad = delta / 10.0f * (float)PAI / 12.0f;
if( fabs(rotrad) < (0.02f * (float)DEG2PAI) ){
return 0;
}
int keynum;
double startframe, endframe, applyframe;
erptr->GetRange( &keynum, &startframe, &endframe, &applyframe );
int calcnum = 3;
CBone* lastpar = firstbone;
double firstframe = 0.0;
if( (firstbone == calcrootbone) && !firstbone->GetParent() ){
int calccnt;
for( calccnt = 0; calccnt < calcnum; calccnt++ ){
int levelcnt = 0;
float currate = 1.0f;
float rotrad2 = rotrad * currate;
if( fabs( rotrad2 ) > 1.0e-4 ){
CQuaternion rotq;
rotq.SetAxisAndRot( m_ikrotaxis, rotrad2 );
if( keynum >= 2 ){
int keyno = 0;
list<KeyInfo>::iterator itrki;
for( itrki = erptr->m_ki.begin(); itrki != erptr->m_ki.end(); itrki++ ){
double curframe = itrki->time;
double changerate;
if( curframe <= applyframe ){
if( applyframe != startframe ){
changerate = 1.0 / (applyframe - startframe);
}else{
changerate = 1.0;
}
}else{
if( applyframe != endframe ){
changerate = 1.0 / (endframe - applyframe );
}else{
changerate = 0.0;
}
}
if( keyno == 0 ){
firstframe = curframe;
}
if( g_absikflag == 0 ){
if( g_slerpoffflag == 0 ){
CQuaternion endq;
endq.SetParams( 1.0f, 0.0f, 0.0f, 0.0f );
CQuaternion curq;
double currate2;
if( curframe <= applyframe ){
if( applyframe != startframe ){
currate2 = changerate * (curframe - startframe);
}else{
currate2 = 1.0;
}
}else{
currate2 = changerate * (endframe - curframe);
}
rotq.Slerp2( endq, 1.0 - currate2, &curq );
firstbone->RotBoneQReq( 0, m_curmotinfo->motid, curframe, curq );
}else{
firstbone->RotBoneQReq( 0, m_curmotinfo->motid, curframe, rotq );
}
}else{
if( keyno == 0 ){
firstbone->RotBoneQReq( 0, m_curmotinfo->motid, curframe, rotq );
}else{
firstbone->SetAbsMatReq( 0, m_curmotinfo->motid, curframe, firstframe );
}
}
keyno++;
}
if( g_applyendflag == 1 ){
//curmotinfo->curframeから最後までcurmotinfo->curframeの姿勢を適用
int tolast;
for( tolast = (int)m_curmotinfo->curframe + 1; tolast < (int)m_curmotinfo->frameleng; tolast++ ){
(m_bonelist[ 0 ])->PasteRotReq( m_curmotinfo->motid, m_curmotinfo->curframe, tolast );
}
}
}else{
firstbone->RotBoneQReq( 0, m_curmotinfo->motid, m_curmotinfo->curframe, rotq );
}
//parbone->RotBoneQReq( 0, m_curmotinfo->motid, m_curmotinfo->curframe, rotq );
UpdateMatrix( &m_matWorld, &m_matVP );
if( (calccnt == (calcnum - 1)) && g_absikflag ){
AdjustBoneTra( erptr, firstbone );
}
}
}
}else{
ChaVector3 rcen;
ChaVector3TransformCoord( &rcen, &(firstbone->GetJointFPos()), &(firstbone->GetCurMp().GetWorldMat()) );
ChaMatrixTranslation( &befrotmat, -rootpos.x, -rootpos.y, -rootpos.z );
ChaMatrixTranslation( &aftrotmat, rootpos.x, rootpos.y, rootpos.z );
ChaMatrixRotationAxis( &rotmat, &m_ikrotaxis, rotrad );
mat = firstbone->GetCurMp().GetWorldMat() * befrotmat * rotmat * aftrotmat;
ChaVector3TransformCoord( &targetpos, &firstbone->GetJointFPos(), &mat );
int calccnt;
for( calccnt = 0; calccnt < calcnum; calccnt++ ){
int levelcnt = 0;
float currate = 1.0f;
CBone* curbone = firstbone;
while( curbone && ((maxlevel == 0) || (levelcnt < maxlevel)) )
{
CBone* parbone = curbone->GetParent();
if( parbone && (curbone->GetJointFPos() != parbone->GetJointFPos()) ){
ChaVector3 parworld, chilworld;
//chilworld = firstbone->m_childworld;
ChaVector3TransformCoord( &chilworld, &(curbone->GetJointFPos()), &(curbone->GetCurMp().GetWorldMat()) );
ChaVector3TransformCoord( &parworld, &(parbone->GetJointFPos()), &(parbone->GetCurMp().GetWorldMat()) );
ChaVector3 parbef, chilbef, tarbef;
parbef = parworld;
CalcShadowToPlane( chilworld, m_ikrotaxis, parworld, &chilbef );
CalcShadowToPlane( targetpos, m_ikrotaxis, parworld, &tarbef );
ChaVector3 vec0, vec1;
vec0 = chilbef - parbef;
ChaVector3Normalize( &vec0, &vec0 );
vec1 = tarbef - parbef;
ChaVector3Normalize( &vec1, &vec1 );
ChaVector3 rotaxis2;
ChaVector3Cross( &rotaxis2, &vec0, &vec1 );
ChaVector3Normalize( &rotaxis2, &rotaxis2 );
float rotdot2, rotrad2;
rotdot2 = ChaVector3Dot( &vec0, &vec1 );
rotdot2 = min( 1.0f, rotdot2 );
rotdot2 = max( -1.0f, rotdot2 );
rotrad2 = (float)acos( rotdot2 );
rotrad2 *= currate;
if( fabs( rotrad2 ) > 1.0e-4 ){
CQuaternion rotq;
rotq.SetAxisAndRot( rotaxis2, rotrad2 );
if( keynum >= 2 ){
int keyno = 0;
list<KeyInfo>::iterator itrki;
for( itrki = erptr->m_ki.begin(); itrki != erptr->m_ki.end(); itrki++ ){
double curframe = itrki->time;
double changerate;
if( curframe <= applyframe ){
if( applyframe != startframe ){
changerate = 1.0 / (applyframe - startframe);
}else{
changerate = 1.0;
}
}else{
if( applyframe != endframe ){
changerate = 1.0 / (endframe - applyframe );
}else{
changerate = 0.0;
}
}
if( keyno == 0 ){
firstframe = curframe;
}
if( g_absikflag == 0 ){
if( g_slerpoffflag == 0 ){
double currate2;
CQuaternion endq;
CQuaternion curq;
endq.SetParams( 1.0f, 0.0f, 0.0f, 0.0f );
if( curframe <= applyframe ){
if( applyframe != startframe ){
currate2 = changerate * (curframe - startframe);
}else{
currate2 = 1.0;
}
}else{
currate2 = changerate * (endframe - curframe);
}
rotq.Slerp2( endq, 1.0 - currate2, &curq );
parbone->RotBoneQReq( 0, m_curmotinfo->motid, curframe, curq );
}else{
parbone->RotBoneQReq( 0, m_curmotinfo->motid, curframe, rotq );
}
}else{
if( keyno == 0 ){
parbone->RotBoneQReq( 0, m_curmotinfo->motid, curframe, rotq );
}else{
parbone->SetAbsMatReq( 0, m_curmotinfo->motid, curframe, firstframe );
}
}
keyno++;
}
}else{
parbone->RotBoneQReq( 0, m_curmotinfo->motid, m_curmotinfo->curframe, rotq );
}
if( g_applyendflag == 1 ){
//curmotinfo->curframeから最後までcurmotinfo->curframeの姿勢を適用
int tolast;
for( tolast = (int)m_curmotinfo->curframe + 1; tolast < (int)m_curmotinfo->frameleng; tolast++ ){
(m_bonelist[ 0 ])->PasteRotReq( m_curmotinfo->motid, m_curmotinfo->curframe, tolast );
}
}
//parbone->RotBoneQReq( 0, m_curmotinfo->motid, m_curmotinfo->curframe, rotq );
UpdateMatrix( &m_matWorld, &m_matVP );
}else{
UpdateMatrix( &m_matWorld, &m_matVP );
}
}
if( curbone->GetParent() ){
lastpar = curbone->GetParent();
}
curbone = curbone->GetParent();
levelcnt++;
currate = pow( g_ikrate, g_ikfirst * levelcnt );
}
if( (calccnt == (calcnum - 1)) && g_absikflag && lastpar ){
AdjustBoneTra( erptr, lastpar );
}
}
}
if( lastpar ){
return lastpar->GetBoneNo();
}else{
return srcboneno;
}
}
int CModel::RotateXDelta( CEditRange* erptr, int srcboneno, float delta )
{
CBone* firstbone = m_bonelist[ srcboneno ];
if( !firstbone ){
_ASSERT( 0 );
return 1;
}
CBone* curbone = firstbone;
SetBefEditMatFK( erptr, curbone );
CBone* lastpar = firstbone->GetParent();
float rotrad;
ChaVector3 axis0, rotaxis;
ChaMatrix selectmat;
selectmat = curbone->GetAxisMatPar() * curbone->GetCurMp().GetWorldMat();
selectmat._41 = 0.0f;
selectmat._42 = 0.0f;
selectmat._43 = 0.0f;
axis0 = ChaVector3( 1.0f, 0.0f, 0.0f );
ChaVector3TransformCoord( &rotaxis, &axis0, &selectmat );
ChaVector3Normalize( &rotaxis, &rotaxis );
rotrad = delta / 10.0f * (float)PAI / 12.0f;
if( fabs(rotrad) < (0.02f * (float)DEG2PAI) ){
return 0;
}
CQuaternion rotq;
rotq.SetAxisAndRot( rotaxis, rotrad );
int keynum;
double startframe, endframe, applyframe;
erptr->GetRange( &keynum, &startframe, &endframe, &applyframe );
curbone = firstbone;
double firstframe = 0.0;
if( keynum >= 2 ){
int keyno = 0;
list<KeyInfo>::iterator itrki;
for( itrki = erptr->m_ki.begin(); itrki != erptr->m_ki.end(); itrki++ ){
double curframe = itrki->time;
double changerate;
if( curframe <= applyframe ){
if( applyframe != startframe ){
changerate = 1.0 / (applyframe - startframe);
}else{
changerate = 1.0;
}
}else{
if( applyframe != endframe ){
changerate = 1.0 / (endframe - applyframe );
}else{
changerate = 0.0;
}
}
if( keyno == 0 ){
firstframe = curframe;
}
if( g_absikflag == 0 ){
if( g_slerpoffflag == 0 ){
double currate2;
CQuaternion endq;
CQuaternion curq;
endq.SetParams( 1.0f, 0.0f, 0.0f, 0.0f );
if( curframe <= applyframe ){
if( applyframe != startframe ){
currate2 = changerate * (curframe - startframe);
}else{
currate2 = 1.0;
}
}else{
currate2 = changerate * (endframe - curframe);
}
rotq.Slerp2( endq, 1.0 - currate2, &curq );
curbone->RotBoneQReq( 0, m_curmotinfo->motid, curframe, curq );
}else{
curbone->RotBoneQReq( 0, m_curmotinfo->motid, curframe, rotq );
}
}else{
if( keyno == 0 ){
curbone->RotBoneQReq( 0, m_curmotinfo->motid, curframe, rotq );
}else{
curbone->SetAbsMatReq( 0, m_curmotinfo->motid, curframe, firstframe );
}
}
keyno++;
}
if( g_applyendflag == 1 ){
//curmotinfo->curframeから最後までcurmotinfo->curframeの姿勢を適用
int tolast;
for( tolast = (int)m_curmotinfo->curframe + 1; tolast < (int)m_curmotinfo->frameleng; tolast++ ){
(m_bonelist[ 0 ])->PasteRotReq( m_curmotinfo->motid, m_curmotinfo->curframe, tolast );
}
}
}else{
curbone->RotBoneQReq( 0, m_curmotinfo->motid, m_curmotinfo->curframe, rotq );
}
UpdateMatrix( &m_matWorld, &m_matVP );
if( g_absikflag && curbone ){
AdjustBoneTra( erptr, curbone );
}
return curbone->GetBoneNo();
}
//int CModel::FKRotate( double srcframe, int srcboneno, ChaMatrix srcmat )
int CModel::FKRotate(int reqflag, CBone* bvhbone, int traflag, ChaVector3 traanim, double srcframe, int srcboneno, CQuaternion rotq, int setmatflag, ChaMatrix* psetmat)
{
static CMotionPoint* s_dbgmp0 = 0;
static CMotionPoint* s_dbgmp1 = 0;
if( srcboneno < 0 ){
_ASSERT( 0 );
return 1;
}
CBone* firstbone = m_bonelist[ srcboneno ];
if( !firstbone ){
_ASSERT( 0 );
return 1;
}
CBone* curbone = firstbone;
CBone* parbone = curbone->GetParent();
CMotionPoint* parmp = 0;
if (parbone){
CMotionPoint* pbef = 0;
CMotionPoint* pnext = 0;
int existflag = 0;
parbone->GetBefNextMP(m_curmotinfo->motid, srcframe, &pbef, &pnext, &existflag);
if ((existflag != 0) && pbef){
parmp = pbef;
}
}
if (reqflag == 1){
curbone->RotBoneQReq(0, m_curmotinfo->motid, srcframe, rotq, bvhbone, traanim, setmatflag, psetmat);
}
else if(bvhbone){
ChaMatrix setmat = bvhbone->GetTmpMat();
curbone->RotBoneQOne(parmp, m_curmotinfo->motid, srcframe, setmat);
}
//UpdateMatrix(&m_matWorld, &m_matVP);
/*
CBone* lastpar = curbone->GetParent();
double curframe = srcframe;
int existflag2 = 0;
CMotionPoint* pbef = 0;
CMotionPoint* pnext = 0;
int curmotid = m_curmotinfo->motid;
lastpar->GetBefNextMP(curmotid, curframe, &pbef, &pnext, &existflag2);
if (existflag2){
ChaVector3 orgpos;
ChaVector3TransformCoord(&orgpos, &(lastpar->GetJointFPos()), &(pbef->GetBefEditMat()));
ChaVector3 newpos;
ChaVector3TransformCoord(&newpos, &(lastpar->GetJointFPos()), &(pbef->GetWorldMat()));
ChaVector3 diffpos;
diffpos = orgpos - newpos;
CEditRange tmper;
KeyInfo tmpki;
tmpki.time = curframe;
list<KeyInfo> tmplist;
tmplist.push_back(tmpki);
tmper.SetRange(tmplist, curframe);
FKBoneTra(&tmper, lastpar->GetBoneNo(), diffpos);
}
*/
return curbone->GetBoneNo();
}
int CModel::FKBoneTra( CEditRange* erptr, int srcboneno, ChaVector3 addtra )
{
static CMotionPoint* s_dbgmp0 = 0;
static CMotionPoint* s_dbgmp1 = 0;
if( srcboneno < 0 ){
_ASSERT( 0 );
return 1;
}
CBone* firstbone = m_bonelist[ srcboneno ];
if( !firstbone ){
_ASSERT( 0 );
return 1;
}
CBone* curbone = firstbone;
SetBefEditMatFK( erptr, curbone );
CBone* lastpar = firstbone->GetParent();
int keynum;
double startframe, endframe, applyframe;
erptr->GetRange( &keynum, &startframe, &endframe, &applyframe );
curbone = firstbone;
double firstframe = 0.0;
if( keynum >= 2 ){
float changerate = 1.0f / (float)(endframe - startframe);
int keyno = 0;
list<KeyInfo>::iterator itrki;
for( itrki = erptr->m_ki.begin(); itrki != erptr->m_ki.end(); itrki++ ){
double curframe = itrki->time;
double changerate;
if( curframe <= applyframe ){
if( applyframe != startframe ){
changerate = 1.0 / (applyframe - startframe);
}else{
changerate = 1.0;
}
}else{
if( applyframe != endframe ){
changerate = 1.0 / (endframe - applyframe );
}else{
changerate = 0.0;
}
}
if( keyno == 0 ){
firstframe = curframe;
}
if( g_absikflag == 0 ){
if( g_slerpoffflag == 0 ){
double currate2;
if( curframe <= applyframe ){
if( applyframe != startframe ){
currate2 = changerate * (curframe - startframe);
}else{
currate2 = 1.0;
}
}else{
currate2 = changerate * (endframe - curframe);
}
ChaVector3 curtra;
curtra = (float)currate2 * addtra;
//currate2 = changerate * keyno;
//ChaVector3 curtra;
//curtra = (1.0 - currate2) * addtra;
curbone->AddBoneTraReq( 0, m_curmotinfo->motid, curframe, curtra );
}else{
curbone->AddBoneTraReq( 0, m_curmotinfo->motid, curframe, addtra );
}
}else{
if( keyno == 0 ){
curbone->AddBoneTraReq( 0, m_curmotinfo->motid, curframe, addtra );
int existflag0 = 0;
CMotionPoint* pbef0 = 0;
CMotionPoint* pnext0 = 0;
curbone->GetBefNextMP( m_curmotinfo->motid, curframe, &pbef0, &pnext0, &existflag0 );
_ASSERT( existflag0 );
s_dbgmp0 = pbef0;
}else{
curbone->SetAbsMatReq( 0, m_curmotinfo->motid, curframe, firstframe );
int existflag1 = 0;
CMotionPoint* pbef1 = 0;
CMotionPoint* pnext1 = 0;
curbone->GetBefNextMP( m_curmotinfo->motid, curframe, &pbef1, &pnext1, &existflag1 );
_ASSERT( existflag1 );
s_dbgmp1 = pbef1;
}
}
keyno++;
}
}else{
curbone->AddBoneTraReq( 0, m_curmotinfo->motid, startframe, addtra );
}
UpdateMatrix( &m_matWorld, &m_matVP );
return curbone->GetBoneNo();
}
int CModel::InitUndoMotion( int saveflag )
{
int undono;
for( undono = 0; undono < UNDOMAX; undono++ ){
m_undomotion[ undono ].ClearData();
}
m_undoid = 0;
if( saveflag ){
m_undomotion[0].SaveUndoMotion( this, -1, -1 );
}
return 0;
}
int CModel::SaveUndoMotion( int curboneno, int curbaseno )
{
if( m_bonelist.empty() || !m_curmotinfo ){
return 0;
}
int nextundoid;
nextundoid = m_undoid + 1;
if( nextundoid >= UNDOMAX ){
nextundoid = 0;
}
m_undoid = nextundoid;
CallF( m_undomotion[m_undoid].SaveUndoMotion( this, curboneno, curbaseno ), return 1 );
return 0;
}
int CModel::RollBackUndoMotion( int redoflag, int* curboneno, int* curbaseno )
{
if( m_bonelist.empty() || !m_curmotinfo ){
return 0;
}
int rbundoid = -1;
if( redoflag == 0 ){
GetValidUndoID( &rbundoid );
}else{
GetValidRedoID( &rbundoid );
}
if( rbundoid >= 0 ){
m_undomotion[ rbundoid ].RollBackMotion( this, curboneno, curbaseno );
m_undoid = rbundoid;
}
return 0;
}
int CModel::GetValidUndoID( int* rbundoid )
{
int retid = -1;
int chkcnt;
int curid = m_undoid;
for( chkcnt = 0; chkcnt < UNDOMAX; chkcnt++ ){
curid = curid - 1;
if( curid < 0 ){
curid = UNDOMAX - 1;
}
if( m_undomotion[curid].GetValidFlag() == 1 ){
retid = curid;
break;
}
}
*rbundoid = retid;
return 0;
}
int CModel::GetValidRedoID( int* rbundoid )
{
int retid = -1;
int chkcnt;
int curid = m_undoid;
for( chkcnt = 0; chkcnt < UNDOMAX; chkcnt++ ){
curid = curid + 1;
if( curid >= UNDOMAX ){
curid = 0;
}
if( m_undomotion[curid].GetValidFlag() == 1 ){
retid = curid;
break;
}
}
*rbundoid = retid;
return 0;
}
int CModel::AddBoneMotMark( OWP_Timeline* owpTimeline, int curboneno, int curlineno, double startframe, double endframe, int flag )
{
if( (curboneno < 0) || (curlineno < 0) ){
_ASSERT( 0 );
return 1;
}
CBone* curbone = m_bonelist[ curboneno ];
if( curbone ){
curbone->AddBoneMotMark( m_curmotinfo->motid, owpTimeline, curlineno, startframe, endframe, flag );
}
return 0;
}
float CModel::GetTargetWeight( int motid, double srcframe, double srctimescale, CMQOObject* srcbaseobj, std::string srctargetname )
{
FbxAnimLayer* curanimlayer = GetAnimLayer( motid );
if( !curanimlayer ){
return 0.0f;
}
FbxTime lTime;
lTime.SetSecondDouble( srcframe / srctimescale );
return GetFbxTargetWeight( m_fbxobj[srcbaseobj].node, m_fbxobj[srcbaseobj].mesh, srctargetname, lTime, curanimlayer, srcbaseobj );
}
float CModel::GetFbxTargetWeight(FbxNode* pbaseNode, FbxMesh* pbaseMesh, std::string targetname, FbxTime& pTime, FbxAnimLayer * pAnimLayer, CMQOObject* baseobj )
{
int lVertexCount = pbaseMesh->GetControlPointsCount();
if( lVertexCount != baseobj->GetVertex() ){
_ASSERT( 0 );
return 0.0f;
}
int lBlendShapeDeformerCount = pbaseMesh->GetDeformerCount(FbxDeformer::eBlendShape);
for(int lBlendShapeIndex = 0; lBlendShapeIndex<lBlendShapeDeformerCount; ++lBlendShapeIndex)
{
FbxBlendShape* lBlendShape = (FbxBlendShape*)pbaseMesh->GetDeformer(lBlendShapeIndex, FbxDeformer::eBlendShape);
int lBlendShapeChannelCount = lBlendShape->GetBlendShapeChannelCount();
for(int lChannelIndex = 0; lChannelIndex<lBlendShapeChannelCount; lChannelIndex++)
{
FbxBlendShapeChannel* lChannel = lBlendShape->GetBlendShapeChannel(lChannelIndex);
if(lChannel)
{
const char* nameptr = lChannel->GetName();
int cmp0;
cmp0 = strcmp( nameptr, targetname.c_str() );
if( cmp0 == 0 ){
FbxAnimCurve* lFCurve;
double lWeight = 0.0;
lFCurve = pbaseMesh->GetShapeChannel(lBlendShapeIndex, lChannelIndex, pAnimLayer);
if (lFCurve){
lWeight = lFCurve->Evaluate(pTime);
}else{
lWeight = 0.0;
}
return (float)lWeight;
}
}//If lChannel is valid
}//For each blend shape channel
}//For each blend shape deformer
return 0.0f;
}
int CModel::SetFirstFrameBonePos(HINFO* phinfo)
{
int motid = m_curmotinfo->motid;
if (motid < 0){
_ASSERT(0);
return 0;
}
if (!GetTopBone()){
_ASSERT(0);
return 0;
}
SetFirstFrameBonePosReq(GetTopBone(), motid, phinfo);
if (phinfo->maxh >= phinfo->minh){
phinfo->height = phinfo->maxh - phinfo->minh;
}
else{
phinfo->height = 0.0f;
_ASSERT(0);
}
return 0;
}
void CModel::SetFirstFrameBonePosReq(CBone* srcbone, int srcmotid, HINFO* phinfo)
{
if (srcbone){
CMotionPoint* curmp = 0;
double curframe = 0.0;
int existflag = 0;
CMotionPoint* befmp = 0;
CMotionPoint* nextmp = 0;
srcbone->GetBefNextMP(srcmotid, curframe, &befmp, &nextmp, &existflag);
if (existflag && befmp){
curmp = befmp;
}
else{
_ASSERT(0);
curmp = 0;
}
if (curmp){
ChaMatrix firstmat = curmp->GetWorldMat();
srcbone->CalcFirstFrameBonePos(firstmat);
ChaVector3 firstpos = srcbone->GetFirstFrameBonePos();
if (firstpos.y < phinfo->minh){
phinfo->minh = firstpos.y;
}
if (firstpos.y > phinfo->maxh){
phinfo->maxh = firstpos.y;
}
}
}
if (srcbone->GetChild()){
SetFirstFrameBonePosReq(srcbone->GetChild(), srcmotid, phinfo);
}
if (srcbone->GetBrother()){
SetFirstFrameBonePosReq(srcbone->GetBrother(), srcmotid, phinfo);
}
}
| [
"info@ochakkolab.moo.jp"
] | info@ochakkolab.moo.jp |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.