text
stringlengths 8
6.88M
|
|---|
#pragma once
#include "utils/ptts.hpp"
#include "proto/config_gongdou.pb.h"
using namespace std;
namespace pc = proto::config;
namespace nora {
namespace config {
using gongdou_ptts = ptts<pc::gongdou>;
gongdou_ptts& gongdou_ptts_instance();
void gongdou_ptts_set_funcs();
}
}
|
#include<bits/stdc++.h>
using namespace std;
void print(int n){
//Base case
if(n == 0){
return;
}
//Recursion
print(n-1); // 1 2 3 4 ......... n-1
cout<<n<<endl;
}
void print1(int n){
//Base case
if(n == 0){
return;
}
cout<<n<<endl;
//Recursion
print1(n-1); // n-1.........4 3 2 1
}
int main(){
int n;
cout<<"Enter value of n: "<<endl;
cin>>n;
cout<<"In sequence: "<<endl;
print(n);
cout<<"In reverse sequence: "<<endl;
print1(n);
return 0;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 2000-2009 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
*/
#ifndef __MIME_LIB_H__
#define __MIME_LIB_H__
#ifndef _MIME_SEC_ENABLED_
#if defined(_SUPPORT_SMIME_) || defined(_SUPPORT_OPENPGP_)
#define _MIME_SEC_ENABLED_
#endif
#endif
#ifdef _MIME_SEC_ENABLED_
#include "modules/datastream/fl_lib.h"
uint32 ScanForEOL(const unsigned char *buf, uint32 len);
class Hash_Item : public DataStream
{
// This class is a sink
public:
SSL_HashAlgorithmType alg;
SSL_Hash *hasher;
uint32 count;
public:
Hash_Item(SSL_HashAlgorithmType _alg, Hash_Item *org);
Hash_Item(SSL_HashAlgorithmType alg);
~Hash_Item();
uint32 GetByteCount(){return count;}
Hash_Item *Suc(){return (Hash_Item *) Link::Suc();}
Hash_Item *Pred(){return (Hash_Item *) Link::Pred();}
void InitHash();
void HashData(const unsigned char *buffer, unsigned long len);
void ExtractL(SSL_varvector32 &digest);
public:
virtual void WriteDataL(const unsigned char *buffer, unsigned long len);
#ifdef _PGP_STREAM_DEBUG_
protected:
virtual const char *Debug_ClassName(){return "Hash_Item";};
virtual const char *Debug_OutputFilename(){return "stream.txt";};
#endif
};
class Hash_Head : public DataStream, public Head
{
private:
BOOL binary;
SSL_secure_varvector32 text_buffer;
public:
Hash_Head();
~Hash_Head();
void CopyL(Hash_Head *src);
void AddMethodL(SSL_HashAlgorithmType _alg);
Hash_Item *GetDigest(SSL_HashAlgorithmType _alg);
void SetBinary(BOOL flag){binary = flag; text_buffer.Resize(0);}
void HashDataL(const unsigned char *buffer, unsigned long len);
Hash_Item *First(){return (Hash_Item *) Head::First();};
Hash_Item *Last(){return (Hash_Item *) Head::Last();};
public:
virtual void WriteDataL(const unsigned char *buffer, unsigned long len);
private:
void HashDataStep(const unsigned char *buffer, unsigned long len);
#ifdef _PGP_STREAM_DEBUG_
protected:
virtual const char *Debug_ClassName(){return "Hash_Head";};
virtual const char *Debug_OutputFilename(){return "stream.txt";};
#endif
};
class MIME_Signed_Processor
{
private:
Hash_Head digests;
protected:
MIME_Signed_Processor();
~MIME_Signed_Processor();
public:
void AddDigestAlgL(SSL_HashAlgorithmType alg);
Hash_Head &AccessDigests(){return digests;}
protected:
void PerformDigestProcessingL(const unsigned char *src, unsigned long src_len);
};
#endif // _MIME_SEC_ENABLED_
#endif
|
#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <memory.h>
#include <math.h>
#include <string>
#include <sstream>
#include <string.h>
#include <queue>
#include <vector>
#include <set>
#include <map>
typedef long long LL;
typedef unsigned long long ULL;
#define PI 3.1415926535897932384626433832795
#define sqr(x) ((x)*(x))
using namespace std;
struct Node {
int l, r;
int add, ma, mi;
int minind;
} T[222222];
set<int> q[222222];
int n, m, k, id, cnt = 0, kupe[222222];
char line[222];
void Init(int x, int l, int r) {
T[x].l = l, T[x].r = r;
T[x].minind = l;
if (l != r) {
int c = (l + r) >> 1;
Init(x + x, l, c);
Init(x + x + 1, c + 1, r);
}
}
void Add(int x, int p, int dy) {
if (T[x].l == T[x].r) {
T[x].add += dy;
T[x].ma += dy;
T[x].mi += dy;
return;
}
int c = (T[x].l + T[x].r) >> 1;
if (p <= c) Add(x + x, p, dy); else
Add(x + x + 1, p, dy);
T[x].ma = max(T[x + x].ma, T[x + x + 1].ma) + T[x].add;
if (T[x].ma == T[x + x].ma + T[x].add)
T[x].minind = T[x + x].minind;else
T[x].minind = T[x + x + 1].minind;
T[x].mi = min(T[x + x].mi, T[x + x + 1].mi) + T[x].add;
}
int Free(int x) {
if (T[x].l == T[x].r) return T[x].r;
if (T[x].mi == T[x + x].mi + T[x].add) {
return Free(x + x);
} else
return Free(x + x + 1);
}
inline bool Bad() {
return T[1].ma - T[1].mi >= 2;
}
int GetMax(int x, int l, int r) {
if (l <= T[x].l && r>= T[x].r) {
return T[x].ma;
}
if (l > T[x].r || r < T[x].l) return -(int)1e9;
return max(GetMax(x + x, l, r), GetMax(x + x + 1, l, r)) + T[x].add;
}
int MinIndMax(int x, int l, int r, int& minind) {
if (l <= T[x].l && r >= T[x].r) {
minind = T[x].minind;
return T[x].ma;
}
int c = (T[x].l + T[x].r) >> 1;
if (l > c) return MinIndMax(x + x + 1, l , r, minind);else
if (r <= c) return MinIndMax(x + x, l , r, minind);
int m1, m2;
int t1 = MinIndMax(x + x, l, r, m1);
int t2 = MinIndMax(x + x + 1, l, r, m2);
if (t1 >= t2) minind = m1; else minind = m2;
return max(t1, t2) + T[x].add;
}
int MaxKupe(int x, int nei) {
int step = 20, offset = 0;
while (step >= 0) {
if (GetMax(x, nei - offset - (1 << step), nei + offset + (1 <<step)) != T[1].ma) {
offset += (1 << step);
}
step--;
}
int m1;
MinIndMax(x, nei - offset - 1, nei + offset + 1, m1);
return m1;
}
int main() {
// freopen(".in", "r", stdin);
// freopen(".out", "w", stdout);
scanf("%d%d%d\n", &m, &n, &k);
Init(1, 1, n);
while (m--) {
gets(line);
if (line[0] == '+') {
++cnt;
int kid = Free(1);
// cerr << kid << endl;
kupe[cnt] = kid;
Add(1, kid, 1);
q[kid].insert(cnt);
} else {
sscanf(line + 2, "%d", &id);
int kid = kupe[id];
q[kid].erase(id);
kupe[id] = -1;
Add(1, kid, -1);
if (Bad()) {
int kidi = MaxKupe(1, kid);
int it = *q[kidi].begin(); q[kidi].erase(q[kidi].begin());
kupe[it] = kid;
q[kid].insert(it);
Add(1, kid, 1);
Add(1, kidi, -1);
}
}
}
for (int i = 1; i <= n; i++) {
printf("%d", q[i].size());
for (set<int>::iterator j = q[i].begin(); j != q[i].end(); j++)
printf(" %d", *j);
puts("");
}
return 0;
}
|
#include <iostream>
using namespace std;
long long ncr(int n,int r,long long prev)
{
long long res;
res=prev*(n-r+2)*(n-r+1)/((n+1)*r);
return res;
}
int main()
{
std::ios::sync_with_stdio(false);
int T,n;
long long p,q,x,y,temp,M;
cin>>T;
while(T>0)
{
cin>>n;
cin>>M;
//f(n)=fibo(n+1) fibonacci number with series fibo(0)=1&fibo(1)=1
//A(n)=n-digit nos without 11 starting with 1
//B(n)=n-digit nos without 11 starting with 0
//f(n)=A(n)+B(n)
//A(n+1)=B(n),B(n+1)=A(n)+B(n)=B(n-1)+B(n)=fibo(n+1)=f(n)
//A(1)=1,B(1)=1,B(0)=1
//sum of n+1 fibo nos(i.e. fibo(0)+fibo(1)+....fibo(n)=fibo(n+2)-1
//S(n)=fibo(2)+fibo(3)+....fibo(n+1)
//S(n)=fibo(n+3)-3
p=0;
q=1;
x=1;
y=1;
/*[fibo(n+3)] ([1 1]) [ 1 ]
| | = pow{ (| |), n+2} * | |
[fibo(n+2)] ([1 0]) [ 1 ] */
n=n+2;
while(n>0)
{
if(n%2==0)
{
temp=p;
p=(p*p+q*q)%M;
q=(q*q+2*temp*q)%M;
n/=2;
}
else
{
temp=x;
x=(x*(p+q)+y*q)%M;
y=(temp*q+y*p)%M;
n--;
}
}
x=x-3;
while(x<0)
{
x+=M;
}
cout<<x<<endl;
T--;
}
return 0;
}
|
#pragma once
#include "ExampleBase.h"
#include "Camera.h"
#include <set>
#include <map>
using namespace std;
using namespace glm;
class BlendColor : public ExampleBase
{
private:
GLuint vao;
GLuint textures[2];
mat4 model, view, projection;
GLfloat lastX, lastY;
GLfloat lastTime;
set<int> dirPress;
Camera camera;
public:
void tryMoveCamera() {
float now = glfwGetTime();
lastTime = lastTime == 0 ? now : lastTime;
float deltaTime = now - lastTime;
lastTime = now;
for each (int dir in dirPress) {
if (dir == GLFW_KEY_W) {
camera.move(FORWARD, deltaTime);
}
else if (dir == GLFW_KEY_S) {
camera.move(BACKWARD, deltaTime);
}
else if (dir == GLFW_KEY_A) {
camera.move(LEFT, deltaTime);
}
else {
camera.move(RIGHT, deltaTime);
}
}
}
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) {
__super::key_callback(window, key, scancode, action, mods);
if (key == GLFW_KEY_W || key == GLFW_KEY_A || key == GLFW_KEY_S || key == GLFW_KEY_D)
{
if (action == GLFW_PRESS) {
dirPress.insert(key);
}
else if (action == GLFW_RELEASE) {
dirPress.erase(key);
}
}
}
void mouse_callback(GLFWwindow* window, double xpos, double ypos) {
lastX = lastX == 0 ? xpos : lastX;
lastY = lastY == 0 ? ypos : lastY;
GLfloat xoffset = xpos - lastX;
GLfloat yoffset = lastY - ypos; // Reversed since y-coordinates go from bottom to left
lastX = xpos;
lastY = ypos;
camera.shake(xoffset, yoffset);
}
// 每一帧更新
void resetMatrix() {
projection = perspective(3.1415926f / 4, 1.0f*WINDOW_WIDTH / WINDOW_HEIGHT, 0.1f, 100.0f);
//model = rotate(model, 0.01f, vec3(0.5f, 1.0f, 0.0f));
view = camera.matrix();
glUniformMatrix4fv(shader->getUniformId("model"), 1, GL_FALSE, value_ptr(model));
glUniformMatrix4fv(shader->getUniformId("view"), 1, GL_FALSE, value_ptr(view));
glUniformMatrix4fv(shader->getUniformId("projection"), 1, GL_FALSE, value_ptr(projection));
}
void initGLData() {
glViewport(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT);
const char *className = typeid(*this).name() + 6;
shader = new Shader(className);
shader->use();
initTextures();
initVertexData();
glEnable(GL_DEPTH_TEST);
glDepthMask(GL_TRUE);
glDepthFunc(GL_LESS); // 默认
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glBlendEquation(GL_FUNC_ADD); // 默认
}
void renderLoop() {
glClearColor(0.3f, 0.3f, 0.7f, 1.f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
tryMoveCamera();
resetMatrix();
// Cubes
glBindVertexArray(cubeVAO);
glUniform1i(shader->getUniformId("boxTexture"), 0);
model = mat4();
model = translate(model, vec3(-1.0f, 0.0f, -1.0f));
glUniformMatrix4fv(shader->getUniformId("model"), 1, GL_FALSE, value_ptr(model));
glDrawArrays(GL_TRIANGLES, 0, 36);
model = mat4();
model = translate(model, vec3(2.0f, 0.0f, 0.0f));
glUniformMatrix4fv(shader->getUniformId("model"), 1, GL_FALSE, value_ptr(model));
glDrawArrays(GL_TRIANGLES, 0, 36);
// Floor
glBindVertexArray(planeVAO);
model = mat4();
glUniformMatrix4fv(shader->getUniformId("model"), 1, GL_FALSE, value_ptr(model));
glDrawArrays(GL_TRIANGLES, 0, 6);
// Sort windows
map<GLfloat, vec3> sorted;
for (GLuint i = 0; i < windows.size(); i++)
{
GLfloat distance = length(camera.Position - windows[i]);
sorted[distance] = windows[i];
}
glDepthMask(GL_FALSE);
glUniform1i(shader->getUniformId("boxTexture"), 1);
glBindVertexArray(transparentVAO);
for each (auto it in sorted)
{
model = mat4();
model = translate(model, it.second);
glUniformMatrix4fv(shader->getUniformId("model"), 1, GL_FALSE, value_ptr(model));
glDrawArrays(GL_TRIANGLES, 0, 6);
}
glDepthMask(GL_TRUE);
glBindVertexArray(0);
}
void initTextures() {
glGenTextures(2, textures);
char* pics[2] = { "images/container.jpg", "images/window.png" };
int width, height, nrChannels;
for (int i = 0; i < 2; i++) {
glActiveTexture(GL_TEXTURE0 + i);
glBindTexture(GL_TEXTURE_2D, textures[i]);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
stbi_uc *data = stbi_load(pics[i], &width, &height, &nrChannels, 0);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, i == 1 ? GL_RGBA : GL_RGB, GL_UNSIGNED_BYTE, data);
glGenerateMipmap(GL_TEXTURE_2D);
stbi_image_free(data);
}
}
void initVertexData() {
windows.push_back(vec3(-1.5f, 0.0f, -0.48f));
windows.push_back(vec3(1.5f, 0.0f, 0.51f));
windows.push_back(vec3(0.0f, 0.0f, 0.7f));
windows.push_back(vec3(-0.3f, 0.0f, -2.3f));
windows.push_back(vec3(0.5f, 0.0f, -0.6f));
GLfloat cubeVertices[] = {
// Positions // Texture Coords
-0.5f, -0.5f, -0.5f, 0.0f, 0.0f,
0.5f, -0.5f, -0.5f, 1.0f, 0.0f,
0.5f, 0.5f, -0.5f, 1.0f, 1.0f,
0.5f, 0.5f, -0.5f, 1.0f, 1.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f,
-0.5f, -0.5f, -0.5f, 0.0f, 0.0f,
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f,
0.5f, -0.5f, 0.5f, 1.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.0f, 1.0f,
0.5f, 0.5f, 0.5f, 1.0f, 1.0f,
-0.5f, 0.5f, 0.5f, 0.0f, 1.0f,
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f,
-0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
-0.5f, 0.5f, -0.5f, 1.0f, 1.0f,
-0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
-0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f,
-0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
0.5f, 0.5f, -0.5f, 1.0f, 1.0f,
0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
0.5f, -0.5f, 0.5f, 0.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
-0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
0.5f, -0.5f, -0.5f, 1.0f, 1.0f,
0.5f, -0.5f, 0.5f, 1.0f, 0.0f,
0.5f, -0.5f, 0.5f, 1.0f, 0.0f,
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f,
-0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f,
0.5f, 0.5f, -0.5f, 1.0f, 1.0f,
0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
-0.5f, 0.5f, 0.5f, 0.0f, 0.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f
};
GLfloat planeVertices[] = {
// Positions // Texture Coords (note we set these higher than 1 that together with GL_REPEAT as texture wrapping mode will cause the floor texture to repeat)
5.0f, -0.5f, 5.0f, 1.0f, 0.0f,
-5.0f, -0.5f, 5.0f, 0.0f, 0.0f,
-5.0f, -0.5f, -5.0f, 0.0f, 1.0f,
5.0f, -0.5f, 5.0f, 1.0f, 0.0f,
-5.0f, -0.5f, -5.0f, 0.0f, 1.0f,
5.0f, -0.5f, -5.0f, 1.0f, 1.0f
};
GLfloat transparentVertices[] = {
// Positions // Texture Coords (swapped y coordinates because texture is flipped upside down)
0.0f, 0.5f, 0.0f, 0.0f, 0.0f,
0.0f, -0.5f, 0.0f, 0.0f, 1.0f,
1.0f, -0.5f, 0.0f, 1.0f, 1.0f,
0.0f, 0.5f, 0.0f, 0.0f, 0.0f,
1.0f, -0.5f, 0.0f, 1.0f, 1.0f,
1.0f, 0.5f, 0.0f, 1.0f, 0.0f
};
// Setup cube VAO
GLuint cubeVBO;
glGenVertexArrays(1, &cubeVAO);
glGenBuffers(1, &cubeVBO);
glBindVertexArray(cubeVAO);
glBindBuffer(GL_ARRAY_BUFFER, cubeVBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(cubeVertices), &cubeVertices, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)0);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat)));
glBindVertexArray(0);
// Setup plane VAO
GLuint planeVBO;
glGenVertexArrays(1, &planeVAO);
glGenBuffers(1, &planeVBO);
glBindVertexArray(planeVAO);
glBindBuffer(GL_ARRAY_BUFFER, planeVBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(planeVertices), &planeVertices, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)0);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat)));
glBindVertexArray(0);
// Setup transparent plane VAO
GLuint transparentVBO;
glGenVertexArrays(1, &transparentVAO);
glGenBuffers(1, &transparentVBO);
glBindVertexArray(transparentVAO);
glBindBuffer(GL_ARRAY_BUFFER, transparentVBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(transparentVertices), transparentVertices, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)0);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat)));
glBindVertexArray(0);
}
private:
GLuint transparentVAO, planeVAO, cubeVAO;
vector<vec3> windows;
};
|
#include "DetectorConstruction.hh"
#include "PrimaryGeneratorAction.hh"
#include "SteppingVerbose.hh"
#include "PhysicsList.hh"
#include<G4RunManager.hh>
#include<G4UImanager.hh>
#include<G4UIterminal.hh>
#include<G4VisExecutive.hh>
#include<G4Material.hh>
#include<G4UserRunAction.hh>
#include<G4Run.hh>
#include <QGSP_BIC_HP.hh>
#include<iostream>
#include<string>
#include<CLHEP/Random/Random.h>
#include<unistd.h>
#include<time.h>
using namespace std;
const char macros[]="/home/nick/g4work/ExG4/v.mac";
class RunAction: public G4UserRunAction
{
public:
void BeginOfRunAction(const G4Run* aRun)
{
G4cout << "### Run " << aRun->GetRunID() << " start." << G4endl;
}
};
int main(int argc,char** argv)
{
G4VSteppingVerbose::SetInstance(new SteppingVerbose);
CLHEP::HepRandom::setTheSeed(time(0)+getpid());
G4RunManager * runManager = new G4RunManager;
DetectorConstruction* detector_c = new DetectorConstruction;
runManager->SetUserInitialization(detector_c);
G4VUserPhysicsList *p = new QGSP_BIC_HP;
runManager->SetUserInitialization(p);
G4VisManager* visManager = new G4VisExecutive;
visManager->Initialize();
runManager->SetUserAction(new PrimaryGeneratorAction(detector_c));
runManager->SetUserAction(new RunAction);
runManager->Initialize();
cout<<"===============================================================";
cout<<endl;
cout<< *(G4Material::GetMaterialTable()) << endl;
cout<<"===============================================================";
cout<<endl;
G4UImanager * UI = G4UImanager::GetUIpointer();
G4UIsession * session = new G4UIterminal();
UI->ExecuteMacroFile(macros);
session->SessionStart();
delete session;
delete visManager;
delete runManager;
return 0;
}
|
#include <bits/stdc++.h>
using namespace std;
const int maxn = 100010;
long long n, m, q, u, v, t, tmp, d = 0;
struct queue {
long long l = 1, r = 0, v[maxn];
inline void push(int x) {
v[++r] = x;
}
inline int pop() {
return v[l++];
}
inline int front() {
return v[l];
}
void print() {
for (int i = l; i <= r; i++)
printf("%lld ", v[i] + d);
puts("");
}
} a, b, c;
inline int pop() {
if (a.front() > b.front()) {
if (a.front() > c.front()) {
return a.pop();
} else {
return c.pop();
}
} else {
if (b.front() > c.front()) {
return b.pop();
} else {
return c.pop();
}
}
}
int main() {
scanf("%lld%lld%lld%lld%lld%lld", &n, &m, &q, &u, &v, &t);
for (int i = 1; i <= n; i++) scanf("%lld", &tmp), a.push(tmp);
long long f, g;
for (int i = 1; i <= m; i++) {
f = pop() + d; g = f * u / v;
b.push(g - q), c.push(f - g - q);
d += q;
if (!(i % t)) printf("%lld ", f);
}
puts("");
return 0;
}
|
#pragma once
#include<iostream>
#include<iomanip>
#include<vector>
#include<queue>
#include"tools.h"
using namespace std;
template<class dataType>
class adjMaxtrix
{
public:
//构造函数,初始图
adjMaxtrix();
//在图G中插入n个顶点信息V和e条边信息E
void CreatGraph(dataType V[], int n, RowColWeight E[], int e);
//输出邻接矩阵
void print();
//函数功能:DFS遍历,假设为非连通图的接口函数,内部会逐个顶点地调用连通图的函数。
void DepthFirstSearch(void Visited(dataType item));
//函数功能:BFS遍历,假设为非连通图的接口函数,内部会逐个顶点地调用连通图的函数。
void BroadFirstSearch(void Visited(dataType item));
//函数功能:Prim构建最小生成树,参数是开始点的下标
int prim(int n);
//析构函数撤销图
~adjMaxtrix();
private:
vector<dataType> vexs; //顶点
int **edge;
int edgeNum;
int const MAX_VEX;
int const MAX_WEIGHT;
//函数功能:插入一个顶点,在顶点矩阵
//参数:新顶点
void InsertVertex(dataType vertex);
//函数功能:无向图插入一条边
//参数:顶点v1和v2连接的边,权值为weight
void InsertEdge(int v1, int v2, int weight);
//函数功能:删除一条边,无向图
//参数:点v1与点v2
void DeleteEdge(int v1, int v2);
//函数功能:取顶点v行的第一个邻接顶点
//参数:顶点v。返回值,成功返回该行第一个顶点的列下标,失败返回-1
int GetFirstVex(int v);
//函数功能,取v1行v2后的下一个顶点
//参数:v1行,v2列
int GetNextVex(int v1, int v2);
//函数功能:连通图的dfs,会被假设为非连通图的接口函数的逐个顶点调用
void DFS(int v, int visited[], void Visit(dataType));
//函数功能:连通图的bfs,会被假设为非连通图的接口函数的逐个顶点调用
void BFS(int v, int visited[], void Visit(dataType));
};
template<class dataType>
adjMaxtrix<dataType>::adjMaxtrix() :MAX_VEX(5), MAX_WEIGHT(999999)
{
//矩阵置空
edge = new int *[MAX_VEX];
for (int i = 0; i < MAX_VEX; i++) {
edge[i] = new int[MAX_VEX];
for (int j = 0; j < MAX_VEX; j++)
edge[i][j] = MAX_WEIGHT;
}
edgeNum = 0;
}
template<class dataType>
void adjMaxtrix<dataType>::InsertVertex(dataType vertex) {
vexs.push_back(vertex); //向向量中添加一个点
}
template<class dataType>
void adjMaxtrix<dataType>::InsertEdge(int v1, int v2, int weight) {
if (v1 < 0 || v1 >= vexs.size() || v2 < 0 || v2 >= vexs.size()) {
cout << "插入边v1或v2越界";
return;
}
edge[v1][v2] = edge[v2][v1] = weight; //插入一条无向边
edgeNum++;
}
template<class dataType>
void adjMaxtrix<dataType>::DeleteEdge(int v1, int v2) {
if (v1 < 0 || v1 >= vexs.size() || v2 < 0 || v2 >= vexs.size()) {
cout << "插入边v1或v2越界";
return;
}
if (edge[v1][v2] == MAX_WEIGHT || edge[v2][v1] == MAX_WEIGHT || v1 == v2) {
cout << "边不存在";
return;
}
edge[v1][v2] == edge[v2][v1] == MAX_WEIGHT; //删除边,置为最大值
edgeNum--;
}
template<class dataType>
int adjMaxtrix<dataType>::GetFirstVex(int v) {
int col;
if (v < 0 || v >= vexs.size()) {
cout << "取第一个邻接顶点参数v越界";
return -1;
}
//查找v顶点的,也就是第v行的第一个有效顶点,放回其列col
for (col = 0; col < vexs.size(); col++) {
if (edge[v][col] != MAX_WEIGHT)
return col;
}
return -1;
}
template<class dataType>
int adjMaxtrix<dataType>::GetNextVex(int v1, int v2) {
int col;
if (v1 < 0 || v1 >= vexs.size() || v2 < 0 || v2 >= vexs.size()) {
cout << "参数v1或v2越界";
return -1;
}
//查找v顶点的,也就是第v行的第一个有效顶点,放回其列col
for (col = v2 + 1; col < vexs.size(); col++) {
if (edge[v1][col] != MAX_WEIGHT)
return col;
}
return -1;
}
template<class dataType>
adjMaxtrix<dataType>::~adjMaxtrix()
{
//撤销矩阵
for (int i = 0; i < vexs.size(); i++)
delete[] edge[i];
}
//在图G中插入n个顶点信息V和e条边信息E
template<class dataType>
void adjMaxtrix<dataType>::CreatGraph(dataType V[], int n, RowColWeight E[], int e)
{
int i, k;
//Initiate(n); //顶点顺序表初始化
for (i = 0; i < n; i++)
InsertVertex(V[i]); //插入顶点
for (k = 0; k < e; k++)
InsertEdge(E[k].row, E[k].col, E[k].weight);//插入边
}
//输出邻接矩阵
template<class dataType>
void adjMaxtrix<dataType>::print() {
for (int i = 0; i < vexs.size(); i++) {
for (int j = 0; j < vexs.size(); j++) {
cout << setw(6) << edge[i][j] << " ";
}
cout << endl;
}
}
//接口的dfs,非连通图
template<class dataType>
void adjMaxtrix<dataType>::DepthFirstSearch(void Visit(dataType item)) {
int i;
int *visited = new int[vexs.size()];
for (i = 0; i < vexs.size(); i++)
visited[i] = 0; //初始标记数组
for (i = 0; i < vexs.size(); i++)
if (!visited[i])
DFS(i, visited, Visit); //以每个顶点为初始顶点进行调用
delete[] visited;
}
//连通图的dfs
//这里的Visit是函数当参数,为用户想要的访问操作
//参数:v为以v为初始顶点,visited[]标记是否访问过
template<class dataType>
void adjMaxtrix<dataType>::DFS(int v, int visited[], void Visit(dataType)) {
int w;
Visit(vexs[v]); //访问顶点v,只是遍历顶点
visited[v] = 1; //标记为访问过
w = GetFirstVex(v); //获取第一个邻接顶点
while (w != -1) {
if (!visited[w])
DFS(w, visited, Visit); //如果没访问过,递归调用访问
w = GetNextVex(v, w);
}
}
//广度优先搜索
template<class dataType>
void adjMaxtrix<dataType>::BroadFirstSearch(void Visit(dataType item)) {
int i;
int *visited = new int[vexs.size()];
for (i = 0; i < vexs.size(); i++)
visited[i] = 0;
for (i = 0; i < vexs.size(); i++)
if (!visited[i])
BFS(i, visited, Visit);
delete[] visited;
}
template<class dataType>
void adjMaxtrix<dataType>::BFS(int v, int visited[], void Visit(dataType item)) {
int u, w;
queue<int> myQueue; //队列
Visit(vexs[v]); //访问
visited[v] = 1;
myQueue.push(v); //初始顶点v入队列
while (!myQueue.empty()) {
u = myQueue.front(); //出队列
myQueue.pop();
w = GetFirstVex(u); //取顶点u的第一个邻接顶点
while (w != -1) {
if (!visited[w]) {
Visit(vexs[w]); //访问顶点w
visited[w] = 1; //置为已访问
myQueue.push(w);//入队w
}
w = GetNextVex(u, w);
}
}
}
//Prim算法构建最小生成树,参照:http://blog.csdn.net/yeruby/article/details/38615045
template<class dataType>
int adjMaxtrix<dataType>::prim(int n){
int lowcost[5]; //以lowcost[i]是以i为终点的边的最小权值
int mst[5]; //mst[i]表示对应于lowcost[i]的起点
int i,j,min,minid,sum=0; //sum最小代价,min临时权值,minid临时路径
int path[5];
int begin=0;
int temp;
for(i=0;i<n;i++){
lowcost[i]=edge[0][i]; //置lowcost为图矩阵的第一行
mst[i]=0; //置所有路径为1,记得改begin
}
mst[begin]=0; //以下标为0开始构建最小生成树
minid=0;
for(i=1;i<n;i++){
min=MAX_WEIGHT;
for(j=0;j<n;j++){
if(minid!=j&&lowcost[j]<min&&lowcost[j]!=0){
min=lowcost[j];
minid=j;
}
}
//cout<<"v"<<mst[minid]<<"-v"<<minid<<"="<<min<<endl;
cout<<vexs[mst[minid]]<<"-"<<vexs[minid]<<"="<<min<<endl;
sum+=min;
lowcost[minid]=0; //表示加入U集合,已访问过
//这一块与上面的的一样,全部更新lowcost[]和mst[]为对应图的下一行
temp=mst[minid];
for(j=0;j<n;j++){
if(edge[minid][j]<lowcost[j]){
lowcost[j]=edge[minid][j];
mst[j]=minid;
}
}
lowcost[temp]=0;
}
return sum;
}
|
#include <iostream>
using namespace std;
// recursive function to determine Greatest Common divisor of 2 numbers
// it is very fast to work
long long GreatestCommondivisor(long long FirstNum, long long SecondNum)
{
if (SecondNum==0)
{
return FirstNum;
}
else
{
if (FirstNum>SecondNum)
{
return GreatestCommondivisor(SecondNum,FirstNum%SecondNum);
}
else if (SecondNum>FirstNum)
{
return GreatestCommondivisor(FirstNum,SecondNum%FirstNum);
}
else
{
return FirstNum;
}
}
}
int main()
{ long long FirstNum=0, SecondNum=0;
cout<< " enter the 2 numbers "<<endl;
cin>>FirstNum>>SecondNum;
cout<<"the Greatest Common divisor of the 2 numbers is "<< GreatestCommondivisor(FirstNum,SecondNum)<<endl;
return 0;
}
|
// Copyright (c) 2014 Agustin Berge
//
// SPDX-License-Identifier: BSL-1.0
// 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)
#pragma once
#include <pika/futures/traits/is_future.hpp>
#include <pika/type_support/pack.hpp>
#include <tuple>
#include <type_traits>
namespace pika::traits {
template <typename Tuple, typename Enable = void>
struct is_future_tuple : std::false_type
{
};
template <typename... Ts>
struct is_future_tuple<std::tuple<Ts...>> : util::detail::all_of<is_future<Ts>...>
{
};
} // namespace pika::traits
|
#include "OpenFlight/DotExporter.h"
#include "OpenFlight/OpenFlightReader.h"
#include <iostream>
#include <sstream>
#include <string>
#include <set>
#include <vector>
using namespace std;
struct Options
{
Options() :
mDebug(false),
mExportToDot(false),
mVertexDataSkipped(false),
mDotInclusions(),
mFilenamePath(){}
bool mDebug;
bool mExportToDot;
bool mVertexDataSkipped;
set<OpenFlight::opCode> mDotInclusions;
string mFilenamePath;
};
set<OpenFlight::opCode> makePrimaryInclusions()
{
using namespace OpenFlight;
set<OpenFlight::opCode> r;
r.insert( ocUnsupported);
r.insert( ocHeader );
r.insert( ocGroup );
r.insert( ocObject );
r.insert( ocFace );
r.insert( ocDegreeofFreedom );
r.insert( ocBinarySeparatingPlane );
r.insert( ocInstanceReference );
r.insert( ocInstanceDefinition );
r.insert( ocExternalReference );
r.insert( ocVertexList );
r.insert( ocLevelOfDetail);
r.insert( ocMesh );
r.insert( ocLocalVertexPool );
r.insert( ocMeshPrimitive );
r.insert( ocRoadSegment );
r.insert( ocRoadZone );
r.insert( ocMorphVertexList );
r.insert( ocSound );
r.insert( ocRoadPath );
r.insert( ocText );
r.insert( ocSwitch );
r.insert( ocClipRegion );
r.insert( ocExtension );
r.insert( ocLightSource );
r.insert( ocReserved103 );
r.insert( ocReserved104 );
r.insert( ocReserved110 );
r.insert( ocLightPoint );
r.insert( ocContinuouslyAdaptiveTerrain );
r.insert( ocCatData );
r.insert( ocReserved117 );
r.insert( ocReserved118 );
r.insert( ocReserved120 );
r.insert( ocReserved121 );
r.insert( ocReserved124 );
r.insert( ocReserved125 );
r.insert( ocCurve );
r.insert( ocRoadConstruction );
r.insert( ocIndexedLightPoint );
r.insert( ocLightPointSystem );
r.insert( ocIndexedString );
r.insert( ocReserved134 );
r.insert( ocReserved144 );
r.insert( ocReserved146 );
return r;
}
set<OpenFlight::opCode> makeAncillaryInclusions()
{
using namespace OpenFlight;
set<OpenFlight::opCode> r;
r.insert(ocContinuation);
r.insert(ocComment);
r.insert(ocColorPalette);
r.insert(ocLongId);
r.insert(ocMatrix);
r.insert(ocVector);
r.insert(ocMultitexture);
r.insert(ocUvList);
r.insert(ocReplicate);
r.insert(ocTexturePalette);
r.insert(ocVertexPalette);
r.insert(ocVertexWithColor);
r.insert(ocVertexWithColorAndNormal);
r.insert(ocVertexWithColorNormalAndUv);
r.insert(ocVertexWithColorAndUv);
r.insert(ocBoundingBox);
r.insert(ocRotateAboutEdge);
r.insert(ocTranslate);
r.insert(ocScale);
r.insert(ocRotateAboutPoint);
r.insert(ocRotateScaleToPoint);
r.insert(ocPut);
r.insert(ocEyepointAndTrackplanePalette);
r.insert(ocLinkagePalette);
r.insert(ocSoundPalette);
r.insert(ocGeneralMatrix);
r.insert(ocLineStylePalette);
r.insert(ocLightSourcePalette);
r.insert(ocBoundingSphere);
r.insert(ocBoundingCylinder);
r.insert(ocBoundingConvexHull);
r.insert(ocBoundingVolumeCenter);
r.insert(ocBoundingVolumeOrientation);
r.insert(ocTextureMappingPalette);
r.insert(ocMaterialPalette);
r.insert(ocNameTable);
r.insert(ocBoundingHistogram);
r.insert(ocLightPointAppearancePalette);
r.insert(ocLightPointAnimationPalette);
r.insert(ocShaderPalette);
r.insert(ocExtendedMaterialHeader);
r.insert(ocExtendedMaterialAmbient);
r.insert(ocExtendedMaterialDiffuse);
r.insert(ocExtendedMaterialSpecular);
r.insert(ocExtendedMaterialEmissive);
r.insert(ocExtendedMaterialAlpha);
r.insert(ocExtendedMaterialLightMap);
r.insert(ocExtendedMaterialNormalMap);
r.insert(ocExtendedMaterialBumpMap);
r.insert(ocExtendedMaterialShadowMap);
r.insert(ocExtendedMaterialReflectionMap);
r.insert(ocExtensionGuidPalette);
r.insert(ocExtensionFieldBoolean);
r.insert(ocExtensionFieldInteger);
r.insert(ocExtensionFieldFloat);
r.insert(ocExtensionFieldDouble);
r.insert(ocExtensionFieldString);
r.insert(ocExtensionFieldXmlString);
return r;
}
set<OpenFlight::opCode> makePaletteInclusions()
{
using namespace OpenFlight;
set<OpenFlight::opCode> r;
r.insert(ocColorPalette);
r.insert(ocTexturePalette);
r.insert(ocVertexPalette);
r.insert(ocEyepointAndTrackplanePalette);
r.insert(ocLinkagePalette);
r.insert(ocSoundPalette);
r.insert(ocLineStylePalette);
r.insert(ocLightSourcePalette);
r.insert(ocTextureMappingPalette);
r.insert(ocMaterialPalette);
r.insert(ocNameTable);
r.insert(ocLightPointAppearancePalette);
r.insert(ocLightPointAnimationPalette);
r.insert(ocShaderPalette);
r.insert(ocExtendedMaterialHeader);
r.insert(ocExtendedMaterialAmbient);
r.insert(ocExtendedMaterialDiffuse);
r.insert(ocExtendedMaterialSpecular);
r.insert(ocExtendedMaterialEmissive);
r.insert(ocExtendedMaterialAlpha);
r.insert(ocExtendedMaterialLightMap);
r.insert(ocExtendedMaterialNormalMap);
r.insert(ocExtendedMaterialBumpMap);
r.insert(ocExtendedMaterialShadowMap);
r.insert(ocExtendedMaterialReflectionMap);
r.insert(ocExtensionGuidPalette);
return r;
}
Options parseArgs(int argc, char** argv)
{
// Default value if no args
Options opt;
if(argc > 1)
{
for(int i = 1; i < argc; ++i)
{
if( string(argv[i]) == "-debug" )
opt.mDebug = true;
if( string(argv[i]) == "-dotExport" )
{
opt.mExportToDot = true;
while( argc > (i+1) && string(argv[i+1]).find("-") == string::npos )
{
string inclusion(argv[++i]);
if(inclusion == "primaryRecords")
{
set<OpenFlight::opCode> e = makePrimaryInclusions();
opt.mDotInclusions.insert(e.begin(), e.end()) ;
}
if(inclusion == "ancillaryRecords")
{
set<OpenFlight::opCode> e = makeAncillaryInclusions();
opt.mDotInclusions.insert(e.begin(), e.end()) ;
}
if(inclusion == "paletteRecords")
{
set<OpenFlight::opCode> e = makePaletteInclusions();
opt.mDotInclusions.insert(e.begin(), e.end()) ;
}
if(inclusion == "headerRecord")
{ opt.mDotInclusions.insert( OpenFlight::ocHeader ); }
if(inclusion == "externalReference")
{ opt.mDotInclusions.insert( OpenFlight::ocExternalReference ); }
if(inclusion == "groupRecord")
{ opt.mDotInclusions.insert( OpenFlight::ocGroup ); }
if(inclusion == "objectRecord")
{ opt.mDotInclusions.insert( OpenFlight::ocObject ); }
if(inclusion == "matrixRecord")
{ opt.mDotInclusions.insert( OpenFlight::ocMatrix ); }
}
}
if(string(argv[i]) == "-skipVertexData" )
{
opt.mVertexDataSkipped = true;
}
if( string(argv[i]) == "-f" && argc > i+1)
{
opt.mFilenamePath = argv[++i];
}
}
}
return opt;
}
bool progressUpdate(const OpenFlight::ProgressData &iData, void *ipUserData)
{
cout << "read file " << iData.mCurrentFileBeingProcessed <<
" (" << iData.mNumberOfRecordParsed << " / " <<
iData.mTotalNumberOfRecordToParse << " )\r";
if (iData.mActivity == OpenFlight::ProgressData::aDone)
{
cout << "\n";
}
return true;
}
int main(int argc, char** argv)
{
OpenFlight::OpenFlightReader ofr;
ofr.setProgressCallback(&progressUpdate, nullptr);
Options opt = parseArgs(argc, argv);
if(!opt.mFilenamePath.empty())
{
OpenFlight::OpenFlightReader::Options ofrOptions;
ofrOptions.mDebugEnabled = opt.mDebug;
ofrOptions.mVertexDataSkipped = opt.mVertexDataSkipped;
ofr.setOptions(ofrOptions);
OpenFlight::HeaderRecord *pRoot = ofr.open( opt.mFilenamePath );
if ( !ofr.hasErrors() )
{
if(ofr.hasWarnings())
{ cout << "Warnings: " << ofr.getAndClearLastWarnings() << endl; }
if( pRoot && opt.mExportToDot )
{
cout << OpenFlight::toDotFormat( pRoot, opt.mDotInclusions );
}
}
else
{ cout << "Errors while reading flt file: " << opt.mFilenamePath << "\n" << ofr.getAndClearLastErrors(); }
if(pRoot)
delete pRoot;
}
else
{
ostringstream oss;
oss<< "Usage: ofReader [-debug] [-dotExport [exlusionList]] -f filenamePath\n\n"<<
"\t -debug: will print, for each record found, the record type and the binary payload.\n\n"<<
"\t -dotExport: will print the graph in dot format to be visualize with graphViz for example.\n"<<
"\t\t Inclusion list must follow the -dotExport options. Every record type listed will appear in the dot export.\n"<<
"\t\t Currently supported inclusion:\n"<<
"\t\t\t all: all records\n"<<
"\t\t\t primaryRecords: all primary records\n"<<
"\t\t\t ancillaryRecords: all ancillary records\n"<<
"\t\t\t paletteRecords: all palette records\n"<<
"\t\t\t headerRecord: header record\n"<<
"\t\t\t externalReference: group record\n"<<
"\t\t\t groupRecord: group record\n"<<
"\t\t\t objectRecord: object record\n"<<
"\t\t\t matrixRecord: matrix record\n"<<
"\t -skipVertexData: All vertex data (vertex palette content and vertex pool content records) will be skipped.\n\n"<<
"\t -f: The filename path to be read.\n\n"<<
"Examples: \n"<<
"\t ofReader -debug -f /Users/Documents/flt/test.flt\n"<<
"\t ofReader -dotExport -f /Users/Documents/flt/test.flt\n"<<
"\t ofReader -dotExport headerRecord groupRecord objectRecord -f /Users/Documents/flt/test.flt\n\n";
cout << oss.str();
}
return 0;
}
|
#ifndef CANTRANSCEIVER_MOCK_H_
#define CANTRANSCEIVER_MOCK_H_
#include "can/ICANTransceiver.h"
#include "busId/BusId.h"
namespace can
{
class CanTransceiverMock
: public ICANTransceiver
{
public:
CanTransceiverMock()
{}
virtual ErrorCode init()
{
return CAN_ERR_OK;
}
virtual void shutdown() {}
virtual ErrorCode open()
{
return CAN_ERR_OK;
}
virtual ErrorCode close()
{
return CAN_ERR_OK;
}
virtual ErrorCode mute()
{
return CAN_ERR_OK;
}
virtual ErrorCode unmute()
{
return CAN_ERR_OK;
}
virtual ErrorCode write(const can::CANFrame& frame)
{
return CAN_ERR_OK;
}
virtual uint32 getBaudrate() const
{
return 500000;
}
virtual uint16 getHwQueueTimeout() const
{
return 50;
}
};
} // namespace can
#endif /* end of include guard */
|
/****************************************************************************
* *
* Author : lukasz.iwaszkiewicz@gmail.com *
* ~~~~~~~~ *
* License : see COPYING file for details. *
* ~~~~~~~~~ *
****************************************************************************/
#include "Device.h"
#include <iostream>
#include <AL/alut.h>
#include <vector>
#include <string>
#include "SoundException.h"
#include "Buffer.h"
/****************************************************************************/
struct Device::Impl {
BufferMap buffers;
};
/****************************************************************************/
Device::Device () : buffersNum (7), impl (new Impl) {}
/****************************************************************************/
Device::~Device ()
{
assert (alutExit ());
#if 0
ALCcontext *context = alcGetCurrentContext ();
ALCdevice *device = alcGetContextsDevice (context);
alcMakeContextCurrent (NULL);
alcDestroyContext (context);
alcCloseDevice (device);
#endif
delete impl;
}
/****************************************************************************/
void Device::init ()
{
#if 0
// Initialization
ALCdevice *device = alcOpenDevice (NULL); // select the "preferred device"
if (device) {
ALCcontext *context = alcCreateContext (device, NULL);
if (context) {
alcMakeContextCurrent (context);
}
}
#endif
if (!alutInit (NULL, NULL)) {
throw Sound::SoundException ("Device::init () : alutInit : " + std::string (alutGetErrorString (alutGetError ())));
}
}
/****************************************************************************/
void Device::printInfo ()
{
if (alcIsExtensionPresent(NULL, "ALC_ENUMERATION_EXT") == AL_TRUE) {
std::cout << "ALC_ENUMERATION_EXT present... Available devices :" << std::endl;
}
/*--------------------------------------------------------------------------*/
const ALCchar *devices = alcGetString (NULL, ALC_DEVICE_SPECIFIER);
const ALCchar *defaultDeviceName = alcGetString (NULL, ALC_DEFAULT_DEVICE_SPECIFIER);
char nullCnt = 0;
typedef std::vector <std::string> Vec;
Vec deviceNames;
std::string tmp;
ALCchar c = '\0';
while (true) {
c = *devices++;
nullCnt += (!c);
nullCnt = ((c) ? (0) : (nullCnt));
if (nullCnt >= 2) {
break;
}
if (!c) {
deviceNames.push_back (tmp);
tmp.clear ();
break;
}
tmp += c;
}
for (Vec::const_iterator i = deviceNames.begin (); i != deviceNames.end (); ++i) {
std::cout << " " << *i;
if (*i == defaultDeviceName) {
std::cout << " [default]";
}
std::cout << std::endl;
}
}
/****************************************************************************/
void Device::registerBuffer (std::string const &name, Buffer *b)
{
impl->buffers[name] = b;
}
/****************************************************************************/
void Device::unregisterBuffer (std::string const &name)
{
impl->buffers.erase (name);
}
/****************************************************************************/
Buffer *Device::getBuffer (std::string const &name)
{
BufferMap::iterator i = impl->buffers.find (name);
return ((i != impl->buffers.end ()) ? (i->second) : (NULL));
}
|
#include<stdio.h>
int main()
{
char a[20][21]; //假设这里的地图不超过20*20
int i, j, sum, map = 0, p, q, x, y, n, m;
//读入n和m,n表示有多少行字符,m表示有多少列
scanf("%d %d", &n, &m);
//读入n行字符
for(i = 0; i <= n-1; i++)
scanf("%s", a[i]);
//用两重循环枚举地图中的每一个点
for(i = 0; i <= n-1; i++)
{
for(j = 0; j <= m-1; j++)
{
//首先判断这个点是不是平地,是平地才可以被放置炸弹
if(a[i][j] == '.')
{
sum = 0; //sum用来计数(可以消灭的敌人数),所以需要初始化为0
//将当前坐标i, j复制到两个新变量x, y中以便向上下左右四个方向分别统计可以消灭的敌人数
//向上统计可以消灭的敌人数
x = i;
y = j;
while(a[x][y] != '#') //判断是不是墙,如果不是墙就继续
{
//如果当前点是敌人就进行计数
if(a[x][y] == 'G')
sum++;
//x--的作用是继续向上统计
x--;
}
//向下统计可以消灭的敌人数
x = i;
y = j;
while(a[x][y] != '#') //判断是不是墙,如果不是墙就继续
{
//如果当前点是敌人就进行计数
if(a[x][y] == 'G')
sum++;
//x++的作用是继续向下统计
x++;
}
//向左统计可以消灭的敌人数
x = i;
y = j;
while(a[x][y] != '#') //判断是不是墙,如果不是墙就继续
{
//如果当前点是敌人就进行计数
if(a[x][y] == 'G')
sum++;
//y--的作用是继续向左统计
y--;
}
//向右统计可以消灭的敌人数
x = i;
y = j;
while(a[x][y] != '#') //判断是不是墙,如果不是墙就继续
{
//如果当前点是敌人就进行计数
if(a[x][y] == 'G')
sum++;
//y++的作用是继续向右统计
y++;
}
//更新map的值
if(sum > map)
{
//如果当前点所能消灭的敌人总数大于map,则更新map
map = sum;
//并用p和q记录当前点的坐标
p = i;
q = j;
}
}
}
}
printf("将炸弹放置在(%d, %d),最多可以消灭%d个敌人\n",p, q, map);
getchar();
getchar();
return 0;
}
|
#include <ctype.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdint.h>
#include <list.h>
#include <node.h>
#include <context.h>
#include <ll.h>
#include <reader.h>
/*
SNode::SNode()
: Node((void*)NULL, 0)
{
}
SNode::SNode(char* str)
: Node((void*)NULL, 0)
{
this->read_list(str, str+strlen(str));
}
SNode::SNode(const char* str)
: SNode((char*) str)
{
}
enum ntype SNode::type(void)
{
return *(this->base<enum ntype*>());
}
List<SNode*>* SNode::value_list(void)
{
static Logger* logger = new Logger("snode value list");
List<SNode*>* list = new List<SNode*>();
int num = this->size() / 4;
iref_t* ptr = (iref_t*) (this->base<uintptr_t>() + sizeof(enum ntype));
while(--num > 0)
{
SNode* snode = (SNode*) ((void*)this->getNode(*ptr++)->node);
if(snode != NULL)
list->pushBack(snode);
else
logger->log(lerror, "couldn't resolve pointer in list");
}
return list;
}
char* SNode::value_string(void)
{
return (char*)(this->base<uintptr_t>() + sizeof(enum ntype));
}
int SNode::value_integer(void)
{
return *((int*) (this->base<uintptr_t>() + sizeof(enum ntype)));
}
void SNode::print(void)
{
this->print(0);
}
void SNode::print(int indent)
{
if(this->size() > 4)
{
for(int i = 0; i < indent; i++) printf("\t");
List<SNode*>* list;
ListIterator<SNode*>* it;
switch(this->type())
{
case LIST:
printf("(\n");
list = this->value_list();
it = new ListIterator<SNode*>(list);
while(! it->isLast())
{
it->getCurrent()->print(indent+1);
it->next();
}
delete it;
delete list;
for(int i = 0; i < indent; i++) printf("\t");
printf(")\n");
break;
case SYMBOL:
case STRING:
printf("%s\n", this->value_string());
break;
case INTEGER:
printf("%d\n", this->value_integer());
break;
}
}
}
*/
|
#include <SCC.h>
scc::scc()
{
// initialise register masks
data_reg[INDX].setMask(0x80003F00);
data_reg[RAND].setMask(0x00003F00); //TODO: rand register: this may be done differently
data_reg[RAND].readOnly();
data_reg[TLBL].setMask(0xFFFFFF00);
data_reg[CTXT].setMask(0xFFFFFFFC);
data_reg[CTXT].readOnly();
data_reg[DCIC].setMask(0xEF800000);
data_reg[DCIC].write(0xE0800000);
data_reg[BADV].readOnly();
data_reg[TLBH].setMask(0xFFFFFFC0);
data_reg[SR].setMask(0xF27FFF3F);
data_reg[CAUSE].setMask(0xB000FF7C);
data_reg[CAUSE].readOnly();
data_reg[EPC].readOnly();
data_reg[PRID].setMask(0x0000FFFF);
data_reg[PRID].readOnly();
// initialise register values
data_reg[PRID].writeBits(2);
// TODO: initialise function pointers
/*instruction
{
};*/
}
void scc::writeDataReg(word data_in, unsigned dest_reg)
{
if (dest_reg > 15)
return;
data_reg[dest_reg].write(data_in);
}
word scc::readDataReg(unsigned dest_reg) const
{
if (dest_reg > 15)
return 0;
return data_reg[dest_reg].read();
}
void TLBR()
{
}
void TLBWI()
{
}
void TLBWR()
{
}
void TLBP()
{
}
void scc::RFE()
{
// move prev to current
word KUp = (data_reg[SR].read() >> 3) & 1;
word IEp = (data_reg[SR].read() >> 2) & 1;
data_reg[SR].writeBits(KUp, 1, 1);
data_reg[SR].writeBits(IEp, 0, 1);
// move old to prev
word KUo = (data_reg[SR].read() >> 5) & 1;
word IEo = (data_reg[SR].read() >> 4) & 1;
data_reg[SR].writeBits(KUo, 3, 1);
data_reg[SR].writeBits(IEo, 2, 1);
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-2012 Opera Software ASA. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
*/
#include <core/pch.h>
#ifdef DOM_EXTENSIONS_CONTEXT_MENU_API_SUPPORT
#include "modules/dom/src/extensions/domextensionmenuitem.h"
#include "modules/dom/src/extensions/domextensionmenucontext_proxy.h"
#include "modules/dom/src/extensions/domextensioncontexts.h"
#include "modules/dom/src/extensions/domextension_background.h"
#include "modules/dom/src/extensions/domextensionscope.h"
#include "modules/util/glob.h"
#include "modules/windowcommander/src/WindowCommander.h"
#include "modules/doc/frm_doc.h"
#include "modules/logdoc/urlimgcontprov.h"
#include "modules/dom/src/domcore/node.h"
#include "modules/dom/src/extensions/domextensionmenuevent.h"
#include "modules/content_filter/content_filter.h"
/* static */ OP_STATUS
DOM_ExtensionMenuItem::Make(DOM_ExtensionMenuItem*& new_obj, DOM_ExtensionSupport* extension_support, DOM_Runtime* origining_runtime)
{
RETURN_IF_ERROR(DOMSetObjectRuntime(new_obj = OP_NEW(DOM_ExtensionMenuItem, (extension_support)), origining_runtime, origining_runtime->GetPrototype(DOM_Runtime::EXTENSION_MENUITEM_PROTOTYPE), "MenuItem"));
return new_obj->Init();
}
DOM_ExtensionMenuItem::DOM_ExtensionMenuItem(DOM_ExtensionSupport* extension_support)
: DOM_ExtensionMenuContext(extension_support)
, m_disabled(FALSE)
, m_type(MENU_ITEM_COMMAND)
, m_parent_menu(NULL)
, m_icon_bitmap(NULL)
{
}
DOM_ExtensionMenuItem::~DOM_ExtensionMenuItem()
{
ResetIconImage();
if (m_icon_loading_listener.InList())
GetFramesDocument()->StopLoadingInline(m_icon_url, &m_icon_loading_listener);
}
/* static */ OP_STATUS
DOM_ExtensionMenuItem::CloneArray(ES_Value& es_array, DOM_Runtime* runtime)
{
// We assume that input es_array is properly validated before.
OP_ASSERT(es_array.type == VALUE_OBJECT);
ES_Object* input = es_array.value.object;
ES_Object* cloned = NULL;
ES_Value tmp_val;
OP_BOOLEAN result = runtime->GetName(input, UNI_L("length"), &tmp_val);
RETURN_IF_ERROR(result);
OP_ASSERT(result == OpBoolean::IS_TRUE || !"No length?");
unsigned int len = TruncateDoubleToUInt(tmp_val.value.number);
RETURN_IF_ERROR(runtime->CreateNativeArrayObject(&cloned, len));
for (unsigned int i = 0; i < len; ++i)
{
result = runtime->GetIndex(input, i, &tmp_val);
RETURN_IF_ERROR(result);
if (result != OpBoolean::IS_TRUE)
return OpStatus::ERR; // Sparse arrays are not supported.
result = runtime->PutIndex(cloned, i, tmp_val);
RETURN_IF_ERROR(result);
}
DOMSetObject(&es_array, cloned);
return OpStatus::OK;
}
OP_STATUS
DOM_ExtensionMenuItem::SetMenuItemProperties(ES_Object* props)
{
m_type = TypeString2TypeEnum(DOMGetDictionaryString(props, UNI_L("type"), UNI_L("")));
m_disabled = DOMGetDictionaryBoolean(props, UNI_L("disabled"), FALSE);
RETURN_IF_ERROR(m_title.Set(DOMGetDictionaryString(props, UNI_L("title"), UNI_L(""))));
RETURN_IF_ERROR(m_id.Set(DOMGetDictionaryString(props, UNI_L("id"), UNI_L(""))));
DOM_Runtime* runtime = GetRuntime();
ES_Value icon_val;
OP_BOOLEAN status = runtime->GetName(props, UNI_L("icon"), &icon_val);
RETURN_IF_ERROR(status);
if (status != OpBoolean::IS_TRUE || icon_val.type != VALUE_STRING)
status = SetIcon(NULL);
else
status = SetIcon(icon_val.value.string);
RETURN_IF_ERROR(status);
ES_Value prop_val;
if (runtime->GetName(props, UNI_L("onclick"), &prop_val) == OpBoolean::IS_TRUE)
{
ES_PutState status = PutName(UNI_L("onclick"), OP_ATOM_UNASSIGNED, &prop_val, runtime);
if (status != PUT_SUCCESS)
{
OP_ASSERT(status == PUT_NO_MEMORY);
return OpStatus::ERR_NO_MEMORY;
}
}
if (runtime->GetName(props, UNI_L("contexts"), &prop_val) != OpBoolean::IS_TRUE)
{
ES_Object* default_value;
RETURN_IF_ERROR(runtime->CreateNativeArrayObject(&default_value, 0));
ES_Value page_str;
DOMSetString(&page_str, UNI_L("page"));
RETURN_IF_ERROR(runtime->PutIndex(default_value, 0, page_str));
DOMSetObject(&prop_val, default_value);
}
else
RETURN_IF_ERROR(CloneArray(prop_val, runtime));
RETURN_IF_ERROR(runtime->PutName(GetNativeObject(), UNI_L("contexts"), prop_val));
const uni_char* object_propnames[2]; /* ARRAY OK 2012-06-12 wmaslowski */
object_propnames[0] = UNI_L("documentURLPatterns");
object_propnames[1] = UNI_L("targetURLPatterns");
for (unsigned int i = 0 ; i < ARRAY_SIZE(object_propnames); ++i)
{
if (runtime->GetName(props, object_propnames[i], &prop_val) != OpBoolean::IS_TRUE || prop_val.type != VALUE_OBJECT)
DOMSetNull(&prop_val);
else
RETURN_IF_ERROR(CloneArray(prop_val, runtime));
RETURN_IF_ERROR(runtime->PutName(GetNativeObject(), object_propnames[i], prop_val));
}
return OpStatus::OK;
}
const uni_char*
DOM_ExtensionMenuItem::GetTitle()
{
if (m_title.HasContent())
return m_title.CStr();
else
{
OpGadget* gadget = m_extension_support->GetGadget();
OP_ASSERT(gadget);
BOOL unused;
const uni_char* wgt_name = gadget->GetClass()->GetAttribute(WIDGET_NAME_SHORT, &unused);
if (!wgt_name)
wgt_name = gadget->GetClass()->GetAttribute(WIDGET_NAME_TEXT, &unused);
return wgt_name;
}
}
/* virtual */ OP_STATUS
DOM_ExtensionMenuItem::SetIcon(const uni_char* icon_url)
{
ResetIconImage();
if (m_icon_loading_listener.InList())
GetFramesDocument()->StopLoadingInline(m_icon_url, &m_icon_loading_listener);
if (icon_url && *icon_url)
{
OpString gadget_url_str;
m_extension_support->GetGadget()->GetGadgetUrl(gadget_url_str);
URL gadget_url = g_url_api->GetURL(gadget_url_str.CStr());
OpString8 icon_url8; // Temporary workaround for CORE-46995. Use uni_char when it is fixed.
RETURN_IF_ERROR(icon_url8.SetUTF8FromUTF16(icon_url));
m_icon_url = g_url_api->GetURL(gadget_url, icon_url8, FALSE, m_extension_support->GetGadget()->UrlContextId());
if (m_icon_url.GetAttribute(URL::KLoadStatus) != URL_LOADED)
OpStatus::Ignore(GetFramesDocument()->LoadInline(m_icon_url, &m_icon_loading_listener));
}
else
m_icon_url = URL();
return OpStatus::OK;
}
/* virtual */ ES_PutState
DOM_ExtensionMenuItem::PutName(const uni_char* property_name, int property_atom, ES_Value* value, ES_Runtime* origining_runtime)
{
return DOM_ExtensionMenuContext::PutName(property_name, property_atom, value, origining_runtime);
}
/* virtual */ ES_PutState
DOM_ExtensionMenuItem::PutName(OpAtom property_atom, ES_Value* value, ES_Runtime* origining_runtime)
{
switch (property_atom)
{
case OP_ATOM_title:
if (value->type != VALUE_STRING)
return PUT_NEEDS_STRING;
else
PUT_FAILED_IF_ERROR(m_title.Set(value->value.string));
return PUT_SUCCESS;
case OP_ATOM_id:
case OP_ATOM_parent:
case OP_ATOM_type:
return PUT_READ_ONLY;
case OP_ATOM_icon:
if (value->type == VALUE_NULL || value->type == VALUE_UNDEFINED)
OpStatus::Ignore(SetIcon(NULL));
else if (value->type != VALUE_STRING)
return PUT_NEEDS_STRING;
else
PUT_FAILED_IF_ERROR(SetIcon(value->value.string));
return PUT_SUCCESS;
case OP_ATOM_disabled:
if (value->type != VALUE_BOOLEAN)
return PUT_NEEDS_BOOLEAN;
m_disabled = value->value.boolean;
return PUT_SUCCESS;
}
return DOM_ExtensionMenuContext::PutName(property_atom, value, origining_runtime);
}
/* virtual */ ES_GetState
DOM_ExtensionMenuItem::GetName(OpAtom property_atom, ES_Value* value, ES_Runtime* origining_runtime)
{
switch (property_atom)
{
case OP_ATOM_disabled:
DOMSetBoolean(value, GetDisabled());
return GET_SUCCESS;
case OP_ATOM_type:
DOMSetString(value, TypeEnum2TypeString(m_type));
return GET_SUCCESS;
case OP_ATOM_title:
DOMSetString(value, m_title.CStr());
return GET_SUCCESS;
case OP_ATOM_id:
DOMSetString(value, GetId());
return GET_SUCCESS;
case OP_ATOM_icon:
DOMSetString(value, GetIconURL());
return GET_SUCCESS;
case OP_ATOM_parent:
DOMSetObject(value, m_parent_menu);
return GET_SUCCESS;
}
return DOM_ExtensionMenuContext::GetName(property_atom, value, origining_runtime);
}
/* static */ void
DOM_ExtensionMenuItem::GetMediaType(HTML_Element* element, const uni_char*& type, const uni_char*& url)
{
type = NULL;
url = NULL;
while (element)
{
if (element->IsMatchingType(Markup::HTE_IMAGE, NS_HTML))
type = UNI_L("image");
#ifdef MEDIA_HTML_SUPPORT
else if (element->IsMatchingType(Markup::HTE_AUDIO, NS_HTML))
type = UNI_L("audio");
else if (element->IsMatchingType(Markup::HTE_VIDEO, NS_HTML))
type = UNI_L("video");
#endif // MEDIA_HTML_SUPPORT
if (type)
{
url = element->GetStringAttr(Markup::HA_SRC, NS_HTML);
return;
}
element = element->ParentActual();
}
}
OP_BOOLEAN
DOM_ExtensionMenuItem::CheckContexts(OpDocumentContext* document_context, FramesDocument* document, HTML_Element* element)
{
ES_Value contexts_val;
DOM_Runtime* runtime = GetRuntime();
OP_BOOLEAN get_result = runtime->GetName(GetNativeObject(), UNI_L("contexts"), &contexts_val);
RETURN_IF_ERROR(get_result);
if (get_result == OpBoolean::IS_TRUE && contexts_val.type == VALUE_OBJECT)
{
ES_Object* es_contexts = contexts_val.value.object;
ES_Value len_val;
get_result = runtime->GetName(es_contexts, UNI_L("length"), &len_val);
RETURN_IF_ERROR(get_result);
if (get_result == OpBoolean::IS_TRUE && len_val.type == VALUE_NUMBER)
{
unsigned int len = TruncateDoubleToUInt(len_val.value.number);
for (unsigned int i = 0; i < len; ++i)
{
ES_Value context_val;
get_result = runtime->GetIndex(es_contexts, i, &context_val);
RETURN_IF_ERROR(get_result);
if (get_result == OpBoolean::IS_TRUE && context_val.type == VALUE_STRING)
{
BOOL is_in_frame = document ? !!document->GetParentDoc() : FALSE; // Let's assume svg is a frame too...
switch (MenuContextType type = ContextNameToEnum(context_val.value.string))
{
case MENU_CONTEXT_PAGE:
if (!is_in_frame &&
!document_context->HasTextSelection() &&
!document_context->HasLink() &&
!document_context->HasEditableText() &&
#ifdef MEDIA_HTML_SUPPORT
!document_context->HasMedia() &&
#endif // MEDIA_HTML_SUPPORT
!document_context->HasImage()
)
return OpBoolean::IS_TRUE;
break;
case MENU_CONTEXT_FRAME:
if (is_in_frame)
return OpBoolean::IS_TRUE;
break;
case MENU_CONTEXT_SELECTION:
if (document_context->HasTextSelection())
return OpBoolean::IS_TRUE;
break;
case MENU_CONTEXT_LINK:
if (document_context->HasLink() && CheckLinkPatterns(document_context, document, element) == OpBoolean::IS_TRUE)
return OpBoolean::IS_TRUE;
break;
case MENU_CONTEXT_EDITABLE:
if (document_context->HasEditableText())
return OpBoolean::IS_TRUE;
break;
case MENU_CONTEXT_IMAGE:
if (document_context->HasImage())
return OpBoolean::IS_TRUE;
break;
#ifdef MEDIA_HTML_SUPPORT
case MENU_CONTEXT_VIDEO:
case MENU_CONTEXT_AUDIO:
if (document_context->HasMedia())
{
const uni_char* media_type;
const uni_char* unused;
GetMediaType(element, media_type, unused);
if ((uni_str_eq(media_type, UNI_L("video")) && type == MENU_CONTEXT_VIDEO) ||
(uni_str_eq(media_type, UNI_L("audio")) && type == MENU_CONTEXT_AUDIO))
return OpBoolean::IS_TRUE;
}
break;
#endif // MEDIA_HTML_SUPPORT
case MENU_CONTEXT_ALL:
return OpBoolean::IS_TRUE;
default:
OP_ASSERT(FALSE);
case MENU_CONTEXT_NONE:
break;
}
}
else if (get_result != OpBoolean::IS_TRUE)
break; // No support for sparse arrays.
}
}
}
return OpBoolean::IS_FALSE;
}
/* static */ BOOL
DOM_ExtensionMenuItem::URLMatchesRule(const uni_char* url, const uni_char* rule)
{
return URLFilter::MatchUrlPattern(url, rule);
}
OP_BOOLEAN
DOM_ExtensionMenuItem::CheckDocumentPatterns(OpDocumentContext* document_context, FramesDocument* document, HTML_Element* element)
{
ES_Value document_patterns_val;
OP_BOOLEAN get_result = GetRuntime()->GetName(GetNativeObject(), UNI_L("documentURLPatterns"), &document_patterns_val);
RETURN_IF_ERROR(get_result);
if (get_result == OpBoolean::IS_TRUE && document_patterns_val.type == VALUE_OBJECT)
{
ES_Object* es_document_patterns = document_patterns_val.value.object;
ES_Value len_val;
get_result = GetRuntime()->GetName(es_document_patterns, UNI_L("length"), &len_val);
RETURN_IF_ERROR(get_result);
if (get_result == OpBoolean::IS_TRUE && len_val.type == VALUE_NUMBER)
{
unsigned int len = TruncateDoubleToUInt(len_val.value.number);
for (unsigned int i = 0; i < len; ++i)
{
ES_Value rule_val;
get_result = GetRuntime()->GetIndex(es_document_patterns, i, &rule_val);
RETURN_IF_ERROR(get_result);
if (get_result == OpBoolean::IS_TRUE && rule_val.type == VALUE_STRING)
{
FramesDocument* cur_doc = document;
while (cur_doc)
{
const uni_char* cur_doc_url = cur_doc->GetURL().GetAttribute(URL::KUniName_With_Fragment, TRUE);
if (URLMatchesRule(cur_doc_url, rule_val.value.string))
return OpBoolean::IS_TRUE;
else
cur_doc = cur_doc->GetParentDoc();
}
}
else if (get_result != OpBoolean::IS_TRUE)
break; // No support for sparse arrays.
}
}
return OpBoolean::IS_FALSE;
}
return OpBoolean::IS_TRUE; // No documentURLPatterns property or it being an object means accept all urls.
}
OP_BOOLEAN
DOM_ExtensionMenuItem::CheckLinkPatterns(OpDocumentContext* document_context, FramesDocument* document, HTML_Element* element)
{
ES_Value target_patterns_val;
OP_BOOLEAN get_result = GetRuntime()->GetName(GetNativeObject(), UNI_L("targetURLPatterns"), &target_patterns_val);
RETURN_IF_ERROR(get_result);
if (get_result == OpBoolean::IS_TRUE && target_patterns_val.type == VALUE_OBJECT)
{
URL anchor_url;
HTML_Element* cur_elm = element;
while (cur_elm)
{
anchor_url = cur_elm->GetAnchor_URL(document);
if (!anchor_url.IsEmpty())
break;
cur_elm = cur_elm->ParentActual();
}
const uni_char* target_addr = anchor_url.GetAttribute(URL::KUniName_With_Fragment, FALSE);
ES_Object* es_target_patterns = target_patterns_val.value.object;
ES_Value len_val;
get_result = GetRuntime()->GetName(es_target_patterns, UNI_L("length"), &len_val);
RETURN_IF_ERROR(get_result);
if (get_result == OpBoolean::IS_TRUE && len_val.type == VALUE_NUMBER)
{
unsigned int len = TruncateDoubleToUInt(len_val.value.number);
for (unsigned int i = 0; i < len; ++i)
{
ES_Value rule_val;
get_result = GetRuntime()->GetIndex(es_target_patterns, i, &rule_val);
RETURN_IF_ERROR(get_result);
if (get_result == OpBoolean::IS_TRUE && rule_val.type == VALUE_STRING &&
URLMatchesRule(target_addr, rule_val.value.string))
return OpBoolean::IS_TRUE;
else if (get_result != OpBoolean::IS_TRUE)
break; // No support for sparse arrays.
}
}
return OpBoolean::IS_FALSE;
}
return OpBoolean::IS_TRUE; // No targetURLPatterns property or it being an object means accept all link urls.
}
OP_BOOLEAN
DOM_ExtensionMenuItem::IsAllowedInContext(OpDocumentContext* document_context, FramesDocument* document, HTML_Element* element)
{
if (m_disabled)
return OpBoolean::IS_FALSE;
OP_BOOLEAN status = CheckContexts(document_context, document, element);
if (status == OpBoolean::IS_TRUE)
status = CheckDocumentPatterns(document_context, document, element);
return status;
}
//'all', 'page', 'frame', 'selection', 'link', 'editable', 'image', 'video' and 'audio'
DOM_ExtensionMenuItem::MenuContextType
DOM_ExtensionMenuItem::ContextNameToEnum(const uni_char* string)
{
if (uni_str_eq(string, UNI_L("page")))
return MENU_CONTEXT_PAGE;
else if (uni_str_eq(string, UNI_L("frame")))
return MENU_CONTEXT_FRAME;
else if (uni_str_eq(string, UNI_L("selection")))
return MENU_CONTEXT_SELECTION;
else if (uni_str_eq(string, UNI_L("link")))
return MENU_CONTEXT_LINK;
else if (uni_str_eq(string, UNI_L("editable")))
return MENU_CONTEXT_EDITABLE;
else if (uni_str_eq(string, UNI_L("image")))
return MENU_CONTEXT_IMAGE;
else if (uni_str_eq(string, UNI_L("video")))
return MENU_CONTEXT_VIDEO;
else if (uni_str_eq(string, UNI_L("audio")))
return MENU_CONTEXT_AUDIO;
else if (uni_str_eq(string, UNI_L("all")))
return MENU_CONTEXT_ALL;
return MENU_CONTEXT_NONE;
}
DOM_ExtensionMenuItem::ItemType
DOM_ExtensionMenuItem::TypeString2TypeEnum(const uni_char* type)
{
if (uni_str_eq(type, UNI_L("folder")))
return MENU_ITEM_SUBMENU;
else if (uni_str_eq(type, UNI_L("line")))
return MENU_ITEM_SEPARATOR;
return MENU_ITEM_COMMAND; // default
}
const uni_char*
DOM_ExtensionMenuItem::TypeEnum2TypeString(ItemType type)
{
switch (type)
{
case MENU_ITEM_SUBMENU:
return UNI_L("folder");
case MENU_ITEM_SEPARATOR:
return UNI_L("line");
default:
OP_ASSERT(FALSE);
// Intentional fall through.
case MENU_ITEM_COMMAND:
return UNI_L("entry");
}
}
/* virtual */ void
DOM_ExtensionMenuItem::GCTrace()
{
GCMark(FetchEventTarget());
for (UINT32 i = 0; i < m_items.GetCount(); ++i)
GCMark(m_items.Get(i));
DOM_ExtensionMenuContext::GCTrace();
}
BOOL
DOM_ExtensionMenuItem::IsAncestorOf(DOM_ExtensionMenuContext* item)
{
while (item)
{
DOM_ExtensionMenuContext* parent = item->IsA( DOM_TYPE_EXTENSION_MENUITEM) ? static_cast<DOM_ExtensionMenuItem*>(item)->m_parent_menu : NULL;
if (parent == this)
return TRUE;
item = parent;
}
return FALSE;
}
/* virtual */ DOM_ExtensionMenuContext::CONTEXT_MENU_ADD_STATUS
DOM_ExtensionMenuItem::AddItem(DOM_ExtensionMenuItem* item, DOM_ExtensionMenuItem* before)
{
OP_ASSERT(item);
if (m_type != MENU_ITEM_SUBMENU)
return ContextMenuAddStatus::ERR_WRONG_MENU_TYPE; // Invalid node type
if ((before && before->m_parent_menu != this) ||
item == this ||
item->IsAncestorOf(this))
return ContextMenuAddStatus::ERR_WRONG_HIERARCHY; // Hierarchy Error
if (before == item)
return OpStatus::OK;
INT32 insert_pos = before ? m_items.Find(before) : m_items.GetCount();
OP_ASSERT(!item->m_parent_menu || item->m_parent_menu->IsA(DOM_TYPE_EXTENSION_MENUITEM)); // We catch adding top level item earlier.
DOM_ExtensionMenuItem* parent = static_cast<DOM_ExtensionMenuItem*>(item->m_parent_menu);
INT32 item_pos = parent ? parent->m_items.Find(item) : -1;
RETURN_IF_ERROR(m_items.Insert(insert_pos, NULL)); // 'Allocate' slot in vector.
if (parent == this && item_pos >= insert_pos)
++item_pos;
if (parent)
parent->m_items.Remove(item_pos);
if (parent == this && item_pos < insert_pos)
--insert_pos;
OpStatus::Ignore(m_items.Replace(insert_pos, item));
item->m_parent_menu = this;
return OpStatus::OK;
}
/* virtual */ void
DOM_ExtensionMenuItem::RemoveItem(unsigned int index)
{
if (index < m_items.GetCount())
{
DOM_ExtensionMenuItem* item = m_items.Remove(index);
OP_ASSERT(item);
item->m_parent_menu = NULL;
}
}
/* virtual */ DOM_ExtensionMenuItem*
DOM_ExtensionMenuItem::GetItem(unsigned int index)
{
if (index < m_items.GetCount())
return m_items.Get(index);
else
return NULL;
}
/* virtual */ unsigned int
DOM_ExtensionMenuItem::GetLength()
{
return m_items.GetCount();
}
OP_STATUS
DOM_ExtensionMenuItem::AppendContextMenu(OpWindowcommanderMessages_MessageSet::PopupMenuRequest::MenuItemList& menu_items, OpDocumentContext* document_context, FramesDocument* document, HTML_Element* element)
{
OP_BOOLEAN allowed = IsAllowedInContext(document_context, document, element);
RETURN_IF_ERROR(allowed);
if (allowed != OpBoolean::IS_TRUE)
return OpStatus::OK;
OpAutoPtr<OpWindowcommanderMessages_MessageSet::PopupMenuRequest_MenuItem> menu_item_info(OP_NEW(OpWindowcommanderMessages_MessageSet::PopupMenuRequest::MenuItem, ()));
RETURN_OOM_IF_NULL(menu_item_info.get());
RETURN_IF_ERROR(menu_item_info->Construct());
menu_item_info->SetId(m_type == MENU_ITEM_COMMAND ? DocumentMenuItem::GetId() : 0);
if (GetTitle())
RETURN_IF_ERROR(menu_item_info->SetLabel(GetTitle()));
menu_item_info->SetIconId((m_icon_url.IsValid() && m_icon_url.GetAttribute(URL::KLoadStatus) == URL_LOADED) ? DocumentMenuItem::GetId() : 0);
if (m_type == MENU_ITEM_SUBMENU)
{
OpWindowcommanderMessages_MessageSet::PopupMenuRequest::MenuItemList* menu_item_list = OP_NEW(OpWindowcommanderMessages_MessageSet::PopupMenuRequest::MenuItemList, ());
if (!menu_item_list || OpStatus::IsError(menu_item_list->Construct()))
{
OP_DELETE(menu_item_list);
return OpStatus::ERR_NO_MEMORY;
}
menu_item_info->SetSubMenuItemList(menu_item_list);
}
for (UINT32 i = 0; i < m_items.GetCount(); ++i)
{
DOM_ExtensionMenuItem* child_menu_item = m_items.Get(i);
RETURN_IF_ERROR(child_menu_item->AppendContextMenu(*menu_item_info->GetSubMenuItemList(), document_context, document, element));
}
RETURN_IF_ERROR(menu_items.GetMenuItemsRef().Add(menu_item_info.get()));
menu_item_info.release();
return OpStatus::OK;
}
/* virtual */ OP_STATUS
DOM_ExtensionMenuItem::GetIconBitmap(OpBitmap*& icon_bitmap)
{
if (m_icon_image.IsEmpty())
{
if (m_icon_url.IsValid() && m_icon_url.GetAttribute(URL::KLoadStatus) == URL_LOADED)
{
// OOM here shouldnt cancel everything - If we fail with allocating/decoding images it is better to at least show text menus.
UrlImageContentProvider* url_img_content_provider = UrlImageContentProvider::FindImageContentProvider(m_icon_url);
if (!url_img_content_provider)
url_img_content_provider = OP_NEW(UrlImageContentProvider, (m_icon_url));
if (url_img_content_provider)
{
url_img_content_provider->IncRef();
m_icon_image = url_img_content_provider->GetImage();
if (OpStatus::IsSuccess(m_icon_image.IncVisible(null_image_listener)))
{
if (OpStatus::IsError(m_icon_image.OnLoadAll(url_img_content_provider)) || m_icon_image.IsFailed())
{
m_icon_image.DecVisible(null_image_listener);
m_icon_image.Empty();
}
}
else
m_icon_image.Empty(); // Unset so we don't call when resetting image.
url_img_content_provider->DecRef();
}
}
}
OP_ASSERT(!m_icon_image.IsEmpty() || !m_icon_bitmap); // assert that we never have bitmap if image is empty
if (!m_icon_bitmap && !m_icon_image.IsEmpty())
m_icon_bitmap = m_icon_image.GetBitmap(null_image_listener);
icon_bitmap = m_icon_bitmap;
return OpStatus::OK;
}
void DOM_ExtensionMenuItem::ResetIconImage()
{
if (m_icon_bitmap)
{
OP_ASSERT(!m_icon_image.IsEmpty());
m_icon_image.ReleaseBitmap();
}
if (!m_icon_image.IsEmpty())
m_icon_image.DecVisible(null_image_listener);
m_icon_image.Empty();
}
void
DOM_ExtensionMenuItem::OnClick(OpDocumentContext* document_context, FramesDocument* document, HTML_Element* element)
{
if (m_disabled || m_type != MENU_ITEM_COMMAND)
return;
OpString document_url;
OP_BOOLEAN status = document->GetURL().GetAttribute(URL::KUniName_With_Fragment, document_url, TRUE);
DOM_Event* menu_event = NULL;
if (OpStatus::IsSuccess(status))
status = DOM_ExtensionMenuEvent_Background::Make(menu_event, document_context, document_url.CStr(), document->GetWindow()->Id(), m_extension_support, GetRuntime());
if (OpStatus::IsSuccess(status))
{
menu_event->InitEvent(ONCLICK, this);
menu_event->SetCurrentTarget(this);
menu_event->SetEventPhase(ES_PHASE_ANY);
status = GetEnvironment()->SendEvent(menu_event);
}
if (OpStatus::IsSuccess(status))
{
// Send the event also to top level background context.
DOM_ExtensionBackground* background = m_extension_support->GetBackground();
if (background)
{
DOM_ExtensionMenuContext* menu_context = background->GetContexts()->GetMenuContext();
if (menu_context)
{
DOM_Event* toplevel_menu_event;
status = DOM_ExtensionMenuEvent_Background::Make(toplevel_menu_event, document_context, document_url.CStr(), document->GetWindow()->Id(), m_extension_support, menu_context->GetRuntime());
if (OpStatus::IsSuccess(status))
{
toplevel_menu_event->InitEvent(ONCLICK, this, NULL, menu_context);
toplevel_menu_event->SetCurrentTarget(this);
toplevel_menu_event->SetEventPhase(ES_PHASE_ANY);
status = menu_context->GetEnvironment()->SendEvent(toplevel_menu_event);
}
}
}
}
if (OpStatus::IsSuccess(status))
{
// Send the event also to userJS.
// @note In multi_process this will be done via sending a message.
DOM_ExtensionScope* userjs = m_extension_support->FindExtensionUserJS(document);
if (userjs)
{
DOM_ExtensionMenuContextProxy* menu_context = userjs->GetMenuContext();
if (menu_context)
menu_context->OnMenuItemClicked(static_cast<DocumentMenuItem*>(this)->GetId(), GetId(), document_context, document, element);
}
}
if (OpStatus::IsMemoryError(status))
g_memory_manager->RaiseCondition(status);
}
#endif // DOM_EXTENSIONS_CONTEXT_MENU_API_SUPPORT
|
#pragma once
#include <glad/glad.h>
class TimeQuery
{
public:
TimeQuery();
~TimeQuery();
void start();
void stop();
//milliseconds
double getDeltaTime();
double getFPS();
private:
double _deltaTime;
unsigned int _queryID[2];
GLuint64 _startTime;
GLuint64 _stopTime;
};
|
#include "Cell.h"
#include <string>
Cell::Cell(std::string Type, int x, int y) : LandScapeT(Type), x(x), y(y)
{
}
std::string Cell::getCellType() const
{
return LandScapeT;
}
int Cell::getCellPositionx() const
{
return y;
}
int Cell::getCellPositiony() const
{
return x;
}
std::string Cell::getOllData() const
{
std::string fData ="x:" + std::to_string(getCellPositionx()) +
";" + "y:" + std::to_string(getCellPositiony()) + ";"+"T:" + getCellType();
return(fData);
}
Cell::~Cell()
{
}
|
#ifndef CHROME_BROWSER_EXTENSIONS_API_BROWSER_TRANSFORM_API_H_
#define CHROME_BROWSER_EXTENSIONS_API_BROWSER_TRANSFORM_API_H_
#include "chrome/common/extensions/api/transform.h"
#include "chrome/browser/extensions/chrome_extension_function.h"
#include "extensions/common/extension.h"
#include "extensions/browser/event_router.h"
// #include "extensions/browser/extension_host.h"
#include "extensions/browser/extension_registry.h"
#include "extensions/browser/extension_registry_observer.h"
namespace extensions {
namespace api {
class TransformOpenFileInCurrentTabFunction : public ChromeAsyncExtensionFunction {
public:
TransformOpenFileInCurrentTabFunction();
protected:
~TransformOpenFileInCurrentTabFunction() override;
bool RunAsync() override;
private:
DECLARE_EXTENSION_FUNCTION("transform.openFileInCurrentTab", TRANSFORM_OPENFILEINCURRENTTAB)
};
class TransformOpenFileInNewTabFunction : public ChromeAsyncExtensionFunction {
public:
TransformOpenFileInNewTabFunction();
protected:
~TransformOpenFileInNewTabFunction() override;
bool RunAsync() override;
private:
DECLARE_EXTENSION_FUNCTION("transform.openFileInNewTab", TRANSFORM_OPENFILEINNEWTAB);
};
class TransformShowFileInFloderFunction : public ChromeAsyncExtensionFunction {
public:
TransformShowFileInFloderFunction();
protected:
~TransformShowFileInFloderFunction() override;
bool RunAsync() override;
private:
DECLARE_EXTENSION_FUNCTION("transform.showFileInFloder", TRANSFORM_SHOWFILEINFLODER);
};
class ExtensionTransformEventRouter
: public extensions::EventRouter::Observer,
public extensions::ExtensionRegistryObserver {
public:
ExtensionTransformEventRouter(Profile* profile,
scoped_refptr<const Extension> extension);
~ExtensionTransformEventRouter() override;
void SendStartTransform();
private:
Profile* profile_;
scoped_refptr<const Extension> extension_;
DISALLOW_COPY_AND_ASSIGN(ExtensionTransformEventRouter);
};
} // namespace api
} // namespace extensions
#endif // CHROME_BROWSER_EXTENSIONS_API_BROWSER_TRANSFORM_API_H_
|
#include <cstdio>
#include <iostream>
#include <vector>
#include <string>
#include <stack>
#include <unordered_map>
#include <unordered_set>
#include <queue>
#include <algorithm>
#define INT_MAX 0x7fffffff
#define INT_MIN 0x80000000
using namespace std;
vector<string> anagrams(vector<string> &strs){
unordered_map<string,int> mytable;
vector<string> res;
for(int i=0;i<strs.size();i++){
string str = strs[i];
sort(str.begin(),str.end());
auto got = mytable.find(str);
if(got == mytable.end()){
mytable[str] = i;
}else{
res.push_back(strs[i]);
if(got->second!= -1 ){
res.push_back(strs[got->second]);
got->second = -1;
}
}
}
return res;
}
int main(){
string str;
vector<string> strs;
vector<string> res;
while(getline(cin,str))
strs.push_back(str);
res = anagrams(strs);
for(auto x : res)
cout << x << endl;
}
|
#include <chuffed/branching/branching.h>
#include <chuffed/core/engine.h>
#include <chuffed/core/propagator.h>
#include <chuffed/vars/modelling.h>
#include <cassert>
#include <cstdio>
int csplib_capacities[] = {12, 14, 17, 18, 19, 20, 23, 24, 25, 26,
27, 28, 29, 30, 32, 35, 39, 42, 43, 44};
int csplib_orders[][2] = {
{4, 1}, {22, 2}, {9, 3}, {5, 4}, {8, 5}, {3, 6}, {3, 4}, {4, 7}, {7, 4},
{7, 8}, {3, 6}, {2, 6}, {2, 4}, {8, 9}, {5, 10}, {7, 11}, {4, 7}, {7, 11},
{5, 10}, {7, 11}, {8, 9}, {3, 1}, {25, 12}, {14, 13}, {3, 6}, {22, 14}, {19, 15},
{19, 15}, {22, 16}, {22, 17}, {22, 18}, {20, 19}, {22, 20}, {5, 21}, {4, 22}, {10, 23},
{26, 24}, {17, 25}, {20, 26}, {16, 27}, {10, 28}, {19, 29}, {10, 30}, {10, 31}, {23, 32},
{22, 33}, {26, 34}, {27, 35}, {22, 36}, {27, 37}, {22, 38}, {22, 39}, {13, 40}, {14, 41},
{16, 27}, {26, 34}, {26, 42}, {27, 35}, {22, 36}, {20, 43}, {26, 24}, {22, 44}, {13, 45},
{19, 46}, {20, 47}, {16, 48}, {15, 49}, {17, 50}, {10, 28}, {20, 51}, {5, 52}, {26, 24},
{19, 53}, {15, 54}, {10, 55}, {10, 56}, {13, 57}, {13, 58}, {13, 59}, {12, 60}, {12, 61},
{18, 62}, {10, 63}, {18, 64}, {16, 65}, {20, 66}, {12, 67}, {6, 68}, {6, 68}, {15, 69},
{15, 70}, {15, 70}, {21, 71}, {30, 72}, {30, 73}, {30, 74}, {30, 75}, {23, 76}, {15, 77},
{15, 78}, {27, 79}, {27, 80}, {27, 81}, {27, 82}, {27, 83}, {27, 84}, {27, 79}, {27, 85},
{27, 86}, {10, 87}, {3, 88}};
class SteelMill : public Problem {
public:
// Constants
vec<int> capacities; // Allowed capacity of slabs in ascending order
vec<int> loss_table; // Load -> Loss table
int max_cap; // Maximum capacity
int max_loss; // Maximum loss
int n_colours; // Number of colours
int n_orders; // Number of orders
int n_slabs; // Number of slabs
vec<int> weight; // weight of ith order
vec<int> colour; // colour of ith order
// Core variables
vec<IntVar*> x; // assign to which slab
vec<IntVar*> load; // load on ith slab
vec<IntVar*> loss; // loss on ith slab
IntVar* total_loss; // total loss
// Intermediate variables
vec<vec<BoolView> > b_order_slab; // whether order i is assigned to slab j
vec<vec<IntVar*> > b2i_order_slab; // whether order i is assigned to slab j
vec<vec<IntVar*> > b2i_slab_colour; // whether slab i is assigned colour j
SteelMill(int n) : n_colours(88), n_orders(n), n_slabs(n) {
for (int& csplib_capacitie : csplib_capacities) {
capacities.push(csplib_capacitie);
}
for (int i = 0; i < n_orders; i++) {
weight.push(csplib_orders[i][0]);
}
for (int i = 0; i < n_orders; i++) {
colour.push(csplib_orders[i][1]);
}
max_cap = capacities.last();
loss_table.growTo(max_cap + 1, 0);
max_loss = 0;
for (int j = 1; j < capacities[0]; j++) {
loss_table[j] = capacities[0] - j;
if (loss_table[j] > max_loss) {
max_loss = loss_table[j];
}
}
for (int i = 0; i < capacities.size() - 1; i++) {
for (int j = capacities[i] + 1; j < capacities[i + 1]; j++) {
loss_table[j] = capacities[i + 1] - j;
if (loss_table[j] > max_loss) {
max_loss = loss_table[j];
}
}
}
for (int i = 0; i < max_cap; i++) {
printf("%d ", loss_table[i]);
}
printf("\n");
// Create vars
createVars(x, n_orders, 0, n_slabs - 1, true);
createVars(load, n_slabs, 0, max_cap, true);
createVars(loss, n_slabs, 0, max_loss, true);
total_loss = newIntVar(0, max_loss * n_slabs);
total_loss->specialiseToEL();
createVars(b_order_slab, n_orders, n_slabs);
createVars(b2i_order_slab, n_orders, n_slabs, 0, 1);
createVars(b2i_slab_colour, n_slabs, n_colours, 0, 1);
// Post some constraints
// Channel constraints for order/slab
for (int i = 0; i < n_orders; i++) {
for (int j = 0; j < n_slabs; j++) {
int_rel_reif(x[i], IRT_EQ, j, b_order_slab[i][j]);
bool2int(b_order_slab[i][j], b2i_order_slab[i][j]);
}
}
// Channel constraints for slab/colour
for (int i = 0; i < n_slabs; i++) {
for (int j = 0; j < n_colours; j++) {
BoolView t = newBoolVar();
bool2int(t, b2i_slab_colour[i][j]);
for (int k = 0; k < n_orders; k++) {
if (colour[k] != j + 1) {
continue;
}
bool_rel(~b_order_slab[k][i], BRT_OR, t);
}
}
}
// Packing constraints
for (int i = 0; i < n_slabs; i++) {
vec<IntVar*> t;
for (int j = 0; j < n_orders; j++) {
t.push(b2i_order_slab[j][i]);
}
int_linear(weight, t, IRT_EQ, load[i]);
}
// Redundant packing constraint
int total_weight = 0;
for (int i = 0; i < n_orders; i++) {
total_weight += weight[i];
}
vec<int> a_slabs(n_slabs, 1);
int_linear(a_slabs, load, IRT_EQ, total_weight);
// Color constraints
vec<int> a_colour(n_colours, 1);
for (int i = 0; i < n_slabs; i++) {
int_linear(a_colour, b2i_slab_colour[i], IRT_LE, 2);
}
// Compute losses
for (int i = 0; i < n_slabs; i++) {
array_int_element(load[i], loss_table, loss[i]);
}
int_linear(a_slabs, loss, IRT_LE, total_loss);
// Post some branchings
branch(x, VAR_SIZE_MIN, VAL_MIN);
optimize(total_loss, OPT_MIN);
// Declare symmetries (optional)
val_sym_break(x, 0, n_slabs - 1);
}
void restrict_learnable() override {
printf("Setting learnable white list\n");
for (int i = 0; i < sat.nVars(); i++) {
sat.flags[i] = 0;
}
for (int i = 0; i < x.size(); i++) {
assert(x[i]->getType() == INT_VAR_EL);
((IntVarEL*)x[i])->setVLearnable();
((IntVarEL*)x[i])->setVDecidable(true);
}
}
// Function to print out solution
void print(std::ostream& os) override {
for (int i = 0; i < n_orders; i++) {
os << x[i]->getVal() << ", ";
}
/*
for (int i = 0; i < n_slabs; i++) {
for (int j = 0; j < n_orders; j++) {
if (x[j]->getVal() != i) continue;
printf("%d:%d ", weight[j], colour[j]);
}
printf("\n");
}
*/
os << "Loss = " << total_loss->getVal() << "\n";
}
};
int main(int argc, char** argv) {
parseOptions(argc, argv);
int n;
assert(argc == 2);
n = atoi(argv[1]);
engine.solve(new SteelMill(n));
return 0;
}
|
#include "mutiplex/ServerSocket.h"
#include "mutiplex/InetAddress.h"
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdexcept>
#include "Debug.h"
namespace muti
{
ServerSocket::ServerSocket()
: fd_(socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, IPPROTO_TCP))
{
if (fd_ < 0) {
LOG_DEBUG("create socket error %d", errno);
}
}
ServerSocket::~ServerSocket()
{
::close(fd_);
}
void ServerSocket::bind(const InetAddress& addr)
{
struct sockaddr_in in_addr;
in_addr.sin_family = AF_INET;
in_addr.sin_port = addr.port();
uint32_t ip = addr.ip();
memcpy(&in_addr.sin_addr.s_addr, &ip, sizeof(ip));
int ret = ::bind(fd_, (const sockaddr*) &in_addr, sizeof(in_addr));
if (ret < 0) {
LOG_DEBUG("bind error %s", strerror(errno));
throw std::runtime_error("invalid addr " + addr.to_string());
}
listen();
}
void ServerSocket::listen()
{
if (::listen(fd_, SOMAXCONN) < 0) {
LOG_DEBUG("lisetn error %d", errno);
}
}
int ServerSocket::accept(InetAddress& addr)
{
struct sockaddr_in in_addr;
socklen_t len = sizeof(in_addr);
memset(&in_addr, 0, len);
int fd = ::accept4(fd_, (struct sockaddr*) &in_addr, &len, SOCK_NONBLOCK | SOCK_CLOEXEC);
if (fd < 0) {
LOG_DEBUG("accept4 error %d", errno);
}
addr = InetAddress(in_addr.sin_addr.s_addr, in_addr.sin_port);
return fd;
}
void ServerSocket::reuse_address(bool on)
{
int optval = on ? 1 : 0;
::setsockopt(fd_, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval));
}
void ServerSocket::reuse_port(bool on)
{
int optval = on ? 1 : 0;
::setsockopt(fd_, SOL_SOCKET, SO_REUSEPORT, &optval, sizeof(optval));
}
}
|
//============================================================================
// Name : NewRedGreenYellow.cpp
// Author :
// Version :
// Copyright : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <iostream>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <vector>
using namespace std;
class RandomSeq {
private:
enum {
RED, GREEN, YELLOW
};
vector<int> seq;
vector<int> guess;
int result[3];
void setRandomSeq(int length) {
int baseRand = getRandomNumber(length);
intToVec(seq, baseRand);
}
int getRandomNumber(int length) {
srand((unsigned int) time(0));
int max = (int) pow(10, length) - 100;
int min = (int) pow(10, length - 1);
int num = (rand() % max) + min;
return num;
}
int findGreens(vector<int>& seq) {
int greenCount = 0;
for (int i = 0; i < (int) guess.size(); i++) {
if (seq[i] == guess[i]) {
greenCount++;
guess.erase(guess.begin() + i);
seq.erase(seq.begin() + i);
i--; //move index back because we have erased an entry
}
}
return greenCount;
}
int findYellows(vector<int>& seq) {
int yellowCount = 0;
for (int i = 0; i < (int) guess.size(); i++) {
for (int j = 0; j < (int) seq.size(); j++) {
if (guess[i] == seq[j]) {
yellowCount++;
guess.erase(guess.begin() + i);
seq.erase(seq.begin() + j);
i--; j--; //move index back because we have erased an entry
break;
}
}
}
return yellowCount;
}
void intToVec(vector<int>& vec, int num) {
vec.erase(vec.begin(), vec.end());
int length = floor(log10(abs(num))) + 1;
int curDigit;
for (int i = 0; i < length; i++) {
curDigit = (int) (num / pow(10, i)) % 10;
vec.push_back(curDigit);
}
}
void clearInstanceVars() {
for (int i = 0; i < 3; i++) {
result[i] = 0;
}
guess.erase(guess.begin(), guess.end());
}
public:
RandomSeq(int length) {
setRandomSeq(length);
}
bool evaluateGuess(int num) {
// makes sure result array and guess vector are empty.
clearInstanceVars();
//copies the guess number into the instance var guess
intToVec(guess, num);
//maximum number of green entries possible
int greenMax = guess.size();
/* in this version of the red-green-yellow game, entries cannot be
* counted twice. i.e.
* if
* a guessed digit n is green
* AND n is unique in the random sequence
* then
* another guessed digit with the same value n must be red
* Other versions of this game would have the second digit assigned
* the color yellow, since it exists within the random sequence
*
* So, matched entries are removed from their respective arrays
* this prevents double counting, but requires a copy of the
* random sequence array, since that array persists between guesses
*/
vector<int> temp = seq;
//find matching colors
//digits that have been assigned a color are removed
result[GREEN] = findGreens(temp);
result[YELLOW] = findYellows(temp);
//# digits not matched is calculated. These are red values.
result[RED] = greenMax - (result[GREEN] + result[YELLOW]);
if (result[GREEN] == greenMax) {
cout << "CONGRATULATIONS, YOU ARE CORRECT!!!!!!!!!!!!!!!";
return true;
} else {
printResult();
return false;
}
}
void printResult() {
cout << "You have: ";
string indexToColor[] = { "red", "green", "yellow" };
for (int i = 0; i < 3; i++) {
cout << result[i] << " " << indexToColor[i] << endl;
}
cout << endl;
}
void printSeq() {
for (int i = ((int) seq.size() - 1); i >= 0; i--)
cout << seq[i];
cout << endl;
}
void printGuess() {
for (int i = ((int) guess.size() - 1); i >= 0; i--)
cout << guess[i];
cout << endl;
}
};
int main() {
RandomSeq rand(3);
bool done = false;
do {
int guess;
cin >> guess;
done = rand.evaluateGuess(guess);
} while (!done);
return 0;
}
|
#ifndef TERRAIN_H
#define TERRAIN_H
#include <cstdlib>
#include <cstring>
#include <vector>
#include <GL/gl.h>
#include "../mat.h"
#define ALG_PERLIN 0
#define ALG_DIAMOND 1
class Terrain
{
friend class Scene;
public:
Terrain(double stride, char htsgen);
virtual ~Terrain();
protected:
private:
int w, h, sz;
double* hMap;
double stride;
GLuint _vbo;
GLuint _uvbo;
GLuint _tex;
GLuint _szVert;
vec3 _pos;
};
#endif // TERRAIN_H
|
#pragma once
#include "LayerNode.hpp"
#include "Nodes/VariableNode.hpp"
#include "Utils/NotNull.hpp"
#include "Utils/Math.hpp"
#include <algorithm>
using MatrixMultiplyFunction = void(ArrayView<float const> inputVector,
ArrayView<float const> weightsMatrix,
ArrayView<float> outputVector);
template<class Type>
struct FullyConnectedLayerNode : LayerNode<Type>
{
FullyConnectedLayerNode(NotNull<ComputationNode<Type>> inputLayer,
NotNull<VariableNode<Type>> variables,
std::size_t numOutputs,
MatrixMultiplyFunction* matrixMultiplyFunction)
: m_inputLayer(inputLayer)
, m_weights(variables)
, m_errorsForInput(inputLayer->getNumOutputs())
, m_errorsForWeights(variables->getNumOutputs())
, m_outputs(numOutputs)
, m_matrixMultiplyFunction(matrixMultiplyFunction)
{
}
void forwardPass() override
{
m_matrixMultiplyFunction(m_inputLayer->getOutputValues(),
m_weights->getOutputValues(),
m_outputs);
resetErrorsForInput();
}
std::size_t getNumOutputs() const override
{
return m_outputs.size();
}
ArrayView<Type const> getOutputValues() const override
{
return m_outputs;
}
void backPropagate(ArrayView<Type const> errors) override
{
for(std::size_t i = 0; i < errors.size(); ++i)
{
backPropagateSingleError(errors[i], getNthLayerWeights(i), getNthLayerWeightsErrors(i));
}
}
void backPropagationPass() override
{
m_inputLayer->backPropagate(m_errorsForInput);
m_weights->backPropagate(m_errorsForWeights);
}
private:
void resetErrorsForInput()
{
std::fill(std::begin(m_errorsForInput), std::end(m_errorsForInput), Type{});
std::fill(std::begin(m_errorsForWeights), std::end(m_errorsForWeights), Type{});
}
void backPropagateSingleError(Type error, ArrayView<Type const> weights, ArrayView<Type> deltas)
{
auto inputs = m_inputLayer->getOutputValues();
deltas[0] += error;
for(auto i = 0u; i < inputs.size(); ++i)
{
m_errorsForInput[i] += error * weights[i + 1];
deltas[i + 1] += error * inputs[i];
}
}
Type calculateSingleOutput(ArrayView<Type const> input, ArrayView<Type const> weights) const
{
Type output = weights[0];
for(auto i = 0; i < input.size(); ++i)
{
output += input[i] * weights[i + 1];
}
return output;
}
ArrayView<Type const> getNthLayerWeights(std::size_t layerIndex) const
{
auto layerSize =(m_inputLayer->getNumOutputs() + 1);
auto layerStart = layerSize * layerIndex;
return m_weights->getOutputValues()(layerStart, layerStart + layerSize);
}
ArrayView<Type> getNthLayerWeightsErrors(std::size_t layerIndex)
{
auto layerSize =(m_inputLayer->getNumOutputs() + 1);
auto layerStart = layerSize * layerIndex;
return ArrayView<Type>(m_errorsForWeights)(layerStart, layerStart + layerSize);
}
private:
NotNull<ComputationNode<Type>> m_inputLayer;
NotNull<VariableNode<Type>> m_weights;
std::vector<Type> m_errorsForInput;
std::vector<Type> m_errorsForWeights;
std::vector<Type> m_outputs;
MatrixMultiplyFunction* m_matrixMultiplyFunction;
};
|
// #include "c-flo.h"
// #include "c-flo-workaround.h"
// #include "ota.h"
#include "1dpong.h"
OneDimensionalPong _pongGame;
// Cflow _cflo("mainhall", "espong", "espong");
const char* mqtt_server = "c-beam.cbrp3.c-base.org";
void onGameStart() {
// _cflo.sendGameStartMsg();
}
void onBallHit(int pos, String direction, int speed) {
// _cflo.sendBallHitMsg(pos, direction, speed);
}
void onPlayerVictory(int playerId) {
// _cflo.sendPlayerVictoryMsg(playerId);
}
void setup() {
Serial.begin(115200);
while (!Serial); // wait for serial port to connect. Needed for native USB port only
// setupOta();
// _cflo.init();
OneDimensionalPong::PongCallbacks cb{0};
cb.onGameStart = onGameStart;
cb.onBallHit = onBallHit;
cb.onPlayerVictory = onPlayerVictory;
_pongGame.setCallbacks(cb);
_pongGame.init();
}
void loop() {
// ArduinoOTA.handle();
_pongGame.tick();
// _cflo.tick();
}
|
#pragma once
#include <iostream>
#include <memory>
#include <type_traits>
|
// This is generated file. Do not modify directly.
// Path to the code generator: /home/avakimov_am/flex_typeclass_plugin/codegen/cxtpl/typeclass/typeclass_gen_hpp.cxtpl.
#pragma once
#include "type_erasure_common.hpp"
#include <array>
#include <functional>
#include <memory>
#include <stdexcept>
#include <utility>
#include <vector>
#include <cstddef>
#include <new> // launder
#include <type_traits> // aligned_storage
#if !defined(NDEBUG)
#include <cassert>
#endif // NDEBUG
namespace morph {
namespace generated {
template<
typename T,
typename V,
typename std::enable_if<std::is_same<Typeclass<SummableTraits<int, int>>, T>::value>::type* = nullptr
>
int sum_with (const V&, const int arg1, const int arg2 ) noexcept ;
// It is Concept - abstract base class
// that is hidden under the covers.
// Typeclass will store pointer to |implBase_|
// We use |implBase_| as base class for typeclass instance
template<>
struct TypeclassImplBase<SummableTraits<int, int>> {
TypeclassImplBase() = default;
// We store a pointer to the base type
// and rely on TypeclassImplBase's virtual dtor to free the object.
virtual ~TypeclassImplBase() {}
virtual
std::unique_ptr<TypeclassImplBase>
clone_as_unique_ptr() const = 0;
virtual
std::unique_ptr<TypeclassImplBase>
move_clone_as_unique_ptr() = 0;
virtual int __sum_with (
const int arg1, const int arg2 ) const noexcept = 0 ;
};
template<>
struct Typeclass<SummableTraits<int, int>>
{
// may be used to import existing typeclass
struct type
: public SummableTraits<int, int>
{};
// use it when you want to implement logic, example:
// `void has_enough_mana<MagicItem::typeclass>`
// using - Type alias, alias template (since C++11)
using typeclass
= Typeclass<SummableTraits<int, int>>;
Typeclass()
: implBase_{}
{}
Typeclass(
const Typeclass<SummableTraits<int, int>>
& rhs)
: implBase_(
rhs.implBase_->clone_as_unique_ptr())
{}
Typeclass(
Typeclass<SummableTraits<int, int>>
&& rhs)
{
implBase_
= rhs.implBase_->move_clone_as_unique_ptr();
}
/// \note use TypeclassRef<ImplType> for references
template<
typename ImplType
/// \note can not pass Typeclass here
, typename std::enable_if<
!std::is_same<Typeclass, std::decay_t<ImplType>>::value
>::type* = nullptr
>
Typeclass(ImplType&& impl)
: implBase_(
std::make_unique<
TypeclassImpl<
std::decay_t<ImplType>
, SummableTraits<int, int>
>
>
(std::forward<ImplType>(impl)))
{}
/// \note use Typeclass<ImplType> for references
template<
typename ImplType
/// \note can not pass Typeclass here
, typename std::enable_if<
!std::is_same<Typeclass, std::decay_t<ImplType>>::value
>::type* = nullptr
>
Typeclass& operator=(ImplType&& impl)
{
implBase_
= std::make_unique<
TypeclassImpl<
std::decay_t<ImplType>
, SummableTraits<int, int>
>
>
(std::forward<ImplType>(impl));
return *this;
}
Typeclass<SummableTraits<int, int>>& operator=
(const Typeclass<SummableTraits<int, int>>
& rhs)
{
implBase_
= rhs.implBase_->clone_as_unique_ptr();
return *this;
}
Typeclass<SummableTraits<int, int>>& operator=
(Typeclass<SummableTraits<int, int>>
&& rhs)
{
implBase_
= rhs.implBase_->move_clone_as_unique_ptr();
return *this;
}
int sum_with (
const int arg1, const int arg2 ) const noexcept {
return implBase_->__sum_with
(arg1, arg2);
}
private:
// This is actually a ptr to an impl type.
std::unique_ptr<
TypeclassImplBase<SummableTraits<int, int>>
> implBase_;
};
// It is Concept - abstract base class
// that is hidden under the covers.
/// \note version of typeclass that uses aligned storage
/// instead of unique_ptr
// Typeclass will store pointer to |implBase_|
// We use |implBase_| as base class for typeclass instance
template<>
struct InplaceTypeclassImplBase<SummableTraits<int, int>>
{
InplaceTypeclassImplBase() = default;
// We store a pointer to the base type
// and rely on InplaceTypeclassImplBase's virtual dtor to free the object.
virtual ~InplaceTypeclassImplBase() {}
virtual
InplaceTypeclassImplBase*
clone_as_raw_ptr(void* addr) const = 0;
virtual
InplaceTypeclassImplBase*
move_clone_as_raw_ptr(void* addr) = 0;
virtual int __sum_with (
const int arg1, const int arg2 ) const noexcept = 0 ;
};
/// \note version of typeclass that uses aligned storage
/// instead of unique_ptr
template<>
struct InplaceTypeclass<
SummableTraits<int, int>
>
{
// may be used to import existing typeclass
struct type
: public SummableTraits<int, int>
{};
// use it when you want to implement logic, example:
// `void has_enough_mana<MagicItem::typeclass>`
// using - Type alias, alias template (since C++11)
using typeclass
= Typeclass<SummableTraits<int, int>>;
InplaceTypeclass()
{}
InplaceTypeclass(
const InplaceTypeclass<
SummableTraits<int, int>
>
& rhs)
{
#if !defined(_GLIBCXX_HAVE_BUILTIN_LAUNDER)
implBase_ =
#endif // _GLIBCXX_HAVE_BUILTIN_LAUNDER
rhs.__implBase()->clone_as_raw_ptr(&storage_);
}
InplaceTypeclass(
InplaceTypeclass<
SummableTraits<int, int>
>
&& rhs)
{
#if !defined(_GLIBCXX_HAVE_BUILTIN_LAUNDER)
implBase_ =
#endif // _GLIBCXX_HAVE_BUILTIN_LAUNDER
rhs.__implBase()->move_clone_as_raw_ptr(&storage_);
}
/// \note static_assert used only for compile-time checks, so
/// also don't forget to provide some runtime checks by assert-s
/// \note we use template,
/// so compiler will be able to
/// print required |Size| and |Alignment|
template<
std::size_t ActualSize
, std::size_t ActualAlignment
>
constexpr
inline /* use `inline` to eleminate function call overhead */
static
void static_validate() noexcept
{
static_assert(
BufferAlignment >= ActualAlignment
, "Typeclass: Alignment must be at least alignof(T)");
static_assert(
BufferSize >= ActualSize
, "Typeclass: sizeof(T) must be at least 'Size'");
}
/// \note use InplaceTypeclassRef<ImplType> for references
template<
typename ImplType
/// \note can not pass InplaceTypeclass here
, typename std::enable_if<
!std::is_same<InplaceTypeclass, std::decay_t<ImplType>>::value
>::type* = nullptr
>
InplaceTypeclass(ImplType&& impl)
{
// wrap static_assert into static_validate
// for console message with desired sizeof in case of error
static_validate<sizeof(ImplType), alignof(ImplType)>();
#if !defined(_GLIBCXX_HAVE_BUILTIN_LAUNDER)
implBase_ =
#endif // _GLIBCXX_HAVE_BUILTIN_LAUNDER
new (&storage_)
InplaceTypeclassImpl<
std::decay_t<ImplType>
, SummableTraits<int, int>
>(std::forward<ImplType>(impl));
}
/// \note use InplaceTypeclassRef<ImplType> for references
template<
typename ImplType
/// \note can not pass InplaceTypeclass here
, typename std::enable_if<
!std::is_same<InplaceTypeclass, std::decay_t<ImplType>>::value
>::type* = nullptr
>
InplaceTypeclass& operator=(ImplType&& impl)
{
// wrap static_assert into static_validate
// for console message with desired sizeof in case of error
static_validate<sizeof(ImplType), alignof(ImplType)>();
#if !defined(NDEBUG)
assert(__implBase());
#endif // NDEBUG
__implBase()->
~InplaceTypeclassImplBase<SummableTraits<int, int>>();
#if !defined(_GLIBCXX_HAVE_BUILTIN_LAUNDER)
implBase_ =
#endif // _GLIBCXX_HAVE_BUILTIN_LAUNDER
new (&storage_)
InplaceTypeclassImpl<
std::decay_t<ImplType>
, SummableTraits<int, int>
>(std::forward<ImplType>(impl));
return *this;
}
InplaceTypeclass<
SummableTraits<int, int>
>& operator=
(const InplaceTypeclass<
SummableTraits<int, int>
>
& rhs)
{
#if !defined(NDEBUG)
assert(__implBase());
#endif // NDEBUG
__implBase()->
~InplaceTypeclassImplBase<SummableTraits<int, int>>();
#if !defined(_GLIBCXX_HAVE_BUILTIN_LAUNDER)
implBase_ =
#endif // _GLIBCXX_HAVE_BUILTIN_LAUNDER
rhs.__implBase()->
clone_as_raw_ptr(&storage_);
return *this;
}
InplaceTypeclass<
SummableTraits<int, int>
>& operator=
(InplaceTypeclass<
SummableTraits<int, int>
>
&& rhs)
{
#if !defined(NDEBUG)
assert(__implBase());
#endif // NDEBUG
__implBase()->
~InplaceTypeclassImplBase<SummableTraits<int, int>>();
#if !defined(_GLIBCXX_HAVE_BUILTIN_LAUNDER)
implBase_ =
#endif // _GLIBCXX_HAVE_BUILTIN_LAUNDER
rhs.__implBase()->
move_clone_as_raw_ptr(&storage_);
return *this;
}
int sum_with (
const int arg1, const int arg2 ) const noexcept {
return __implBase()->
__sum_with
(arg1, arg2);
}
private:
inline /* use `inline` to eleminate function call overhead */
InplaceTypeclassImplBase<SummableTraits<int, int>>*
__implBase() const noexcept
{
#if defined(_GLIBCXX_HAVE_BUILTIN_LAUNDER)
// requires std >= 201703L
return
(InplaceTypeclassImplBase<SummableTraits<int, int>>*)
(std::launder(&storage_));
#else // _GLIBCXX_HAVE_BUILTIN_LAUNDER
return implBase_;
#endif // _GLIBCXX_HAVE_BUILTIN_LAUNDER
}
private:
static constexpr std::size_t BufferSize
= 64;
static const size_t BufferAlignment
= std::alignment_of_v<
InplaceTypeclassImplBase<SummableTraits<int, int>>
>;
/// \note avoid UB related to |aligned_storage_t|
/// see https://mropert.github.io/2017/12/23/undefined_ducks/
/// or use std::launder
/// \note |aligned_storage_t| ensures that memory is contiguous in the class,
/// avoids cache miss.
/// (comparing to dynamic heap allocation approach where impl may be in heap,
/// but the class may be in stack or another region in heap)
/// \see about `Data Locality` https://gameprogrammingpatterns.com/data-locality.html
std::aligned_storage_t<
BufferSize
, BufferAlignment
> storage_
{};
#if !defined(_GLIBCXX_HAVE_BUILTIN_LAUNDER)
// This is actually a ptr to an impl type.
/// \note doing a reinterpret_cast from derived to base
/// is not guaranteed to do what you expect.
/// A solution to that is to save the result of the new expression
/// see https://mropert.github.io/2017/12/23/undefined_ducks/
InplaceTypeclassImplBase<SummableTraits<int, int>>*
implBase_ = nullptr;
#endif // _GLIBCXX_HAVE_BUILTIN_LAUNDER
};
// using - Type alias, alias template (since C++11)
using InHeapIntSummable
= Typeclass<SummableTraits<int, int>>;
// using - Type alias, alias template (since C++11)
using InPlaceIntSummable
= InplaceTypeclass<SummableTraits<int, int>>;
// using - Type alias, alias template (since C++11)
using IntSummable
= InPlaceIntSummable;
// fullBaseType may be VERY long templated type,
// but we can shorten it with #define
#define DEFINE_IntSummable \
SummableTraits<int, int>
} // namespace morph
} // namespace generated
|
#pragma once
#include <chrono>
#include <iostream>
#include "Config.h"
#include "Encoder.h"
#include "Helpers.h"
class Orientation {
public:
typedef typename Encoder<uint16_t, double> EncType;
struct Position {
Point p;
double& x, & y;
double theta = 0;
double vx = 0, vy = 0, omega = 0, v = 0;
void print() {
std::cout << "x:\t" << x << "\t\ty:\t" << y << "\t\tTheta:\t" << theta << "\n";
}
Position() : p(0, 0), x(p.x), y(p.y) {}
Position& operator=(const Position& rhs) {
p = rhs.p;
theta = rhs.theta;
vx = rhs.vx;
vy = rhs.vy;
omega = rhs.omega;
v = rhs.v;
return *this;
}
Position(const Position& rhs) : p(rhs.p), x(p.x), y(p.y), theta(rhs.theta), vx(rhs.vx), vy(rhs.vy), omega(rhs.omega), v(rhs.v) {}
};
private:
EncType left, right;
Encoder<signed short, double> theta;
Position pos;
const double d, radius;
using clock = std::chrono::steady_clock;
decltype(clock::now()) lastTick;
public:
Orientation() : left(config::rob::tick2mm), right(config::rob::tick2mm),
theta(config::rob::tick2deg, config::rob::thetaMin, config::rob::thetaMax),
d(config::rob::d), radius(config::rob::r) { }
void init(unsigned short l = 0, unsigned short r = 0, signed short theta = 0);
void tick(uint16_t l, uint16_t r, signed short angle);
const EncType& getLeft() const {
return left;
}
const EncType& getRight() const {
return right;
}
double getTheta() const {
return theta.getPosition();
}
Position getPosition() const {
return pos;
}
};
|
/*
* AUTHOR : Sayanatan Pal
* DATE : 03.01.2020
* Prime number check (Primality Test Method [sqrt(n)]) --> O(sqrt(n))
* Link : https://www.geeksforgeeks.org/primality-test-set-1-introduction-and-school-method/
*/
/*
Note : Always use <bits/stdc++.h> instead of iostream
*/
#include <bits/stdc++.h>
using namespace std;
bool isPrime(int n)
{
// Corner cases
if (n <= 1) return false;
if (n <= 3) return true;
// This is checked so that we can skip
// middle five numbers in below loop
if (n%2 == 0 || n%3 == 0) return false;
for (int i=5; i<sqrt(n); i=i+6)
if (n%i == 0 || n%(i+2) == 0)
return false;
return true;
}
// Driver Program
int main()
{
int input;
cin >> input;
isPrime(input) ? cout << "true\n" : cout << "false\n";
return 0;
}
|
/*
EXECUTE THE CIRCULAR MANEUVER
*/
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//HEADER FILES
#include "maneuvers/circle_maneuver.h"
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
using namespace std;
using namespace Eigen;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//CONSTRUCTOR
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
circle_traverse::circle_traverse(const ros::NodeHandle& nh): nh_(nh)
{
//Obtaining the radius of the circular trajectory to be traversed from the parameter server. The
//default radius is 1.0m
nh_.param<double>("/trajectory_generator/circle_radius", circle_radius, 1.0);
//Obtaining the angular velocity of the circular trajectory to be traversed from the parameter
//server. The default angular velocity is 0.1 rad/s
nh_.param<double>("/trajectory_generator/circle_angvel", circle_ang_velocity, 0.1);
//Obtaining the height of the circular trajectory to be traversed from the parameter
//server. The default height is 5.0m
nh_.param<double>("/trajectory_generator/circle_height", circle_height, 5.0);
//Number of revolutions of the given circle to be executed. Default is 5
nh_.param<int>("/trajectory_generator/circle_rev", circle_rev, 5.0);
}
circle_traverse::~circle_traverse() {
//Destructor
}
double circle_traverse::maneuver_init(double time)
{
//The total execution time of the trajectory = Number of revolutions * Time Period of a single revolution
return circle_rev*(2*M_PI/circle_ang_velocity);
}
void circle_traverse::trajectory_generator(double time)
{
//Circular trajectory generation is quite straightforward and is done using the parametric equation of the circle.
target_position << circle_radius*sin(circle_ang_velocity*time), circle_radius*cos(circle_ang_velocity*time), circle_height;
//The velocity, acceleration and jerk along the trajectory can be appropriately obtained by differentiating the
//parametric equation for position of the circle.
target_velocity << cos(circle_ang_velocity*time), -sin(circle_ang_velocity*time), 0;
target_velocity *= circle_radius*circle_ang_velocity;
target_acceleration << sin(circle_ang_velocity*time), cos(circle_ang_velocity*time), 0;
target_acceleration *= -circle_radius*circle_ang_velocity*circle_ang_velocity;
target_jerk = -target_velocity*circle_ang_velocity*circle_ang_velocity;
//The method of calculation of the angular velocity is described in detail in the github wiki.
target_angvel = calculate_trajectory_angvel();
//Yaw is calculated to ensure that the quadrotor always aligns itself to the direction of motion. The front of
//the quadrotor is 90 degree offset from the 0 degree yaw direction of the controller. Thus an additional
//offset term is required.
target_yaw = atan2(target_position(1),target_position(0)) - M_PI/2.0;
//This parameter decides the mode of operation of the controller. The controller can work in 5 modes
//MODE 0 - IGNORE ALL TRAJECTORY TARGET INPUTS (POSITION, VELOCITY, ACCELERATION, ANGULAR VELOCITY, YAW)
//MODE 1 - ACCEPT ALL TRAJECTORY TARGET INPUTS FOR CONTROL OUTPUT CALCULATION
//MODE 2 - IGNORE ONLY POSITION FOR CONTROL OUTPUT CALCULATION (ERROR IS TAKEN AS 0)
//MODE 3 - IGNORE ONLY VELOCITY FOR CONTROL OUTPUT CALCULATION (ERROR IS TAKEN AS 0)
//MODE 4 - IGNORE POSITION AND VELOCITY FOR CONTROL OUTPUT CALCULATION (ERROR IS TAKEN AS 0)
type = 1;
}
Eigen::Vector3d circle_traverse::calculate_trajectory_angvel()
{
Eigen::Vector3d acc, jerk, h, zb, w, xc, yb, xb;
float m = 0.95;
Eigen::Vector3d g;
g << 0, 0, 9.8;
acc = target_acceleration + g;
jerk = target_jerk;
double u = acc.norm();
zb = acc/u;
xc << cos(target_yaw),sin(target_yaw),0;
yb = zb.cross(xc) / (zb.cross(xc)).norm();
xb = yb.cross(zb) / (yb.cross(zb)).norm();
h = (m/u)*(jerk - (zb.dot(jerk))*zb);
w(0) = -h.dot(yb);
w(1) = h.dot(xb);
w(2) = 0;
return w;
}
Eigen::Vector3d circle_traverse::get_target_pos()
{
//Return the desired position
return target_position;
}
Eigen::Vector3d circle_traverse::get_target_vel()
{
//Return the desired velocity
return target_velocity;
}
Eigen::Vector3d circle_traverse::get_target_acc()
{
//Return the desired acceleration
return target_acceleration;
}
Eigen::Vector3d circle_traverse::get_target_angvel()
{
//Return the desired anguler velocity
return target_angvel;
}
Eigen::Vector3d circle_traverse::get_target_jerk()
{
//Return the desired jerk
return target_jerk;
}
double circle_traverse::get_target_yaw()
{
//Return the desired yaw
return target_yaw;
}
int circle_traverse::get_type()
{
//Return the desired mode of controller operation
return type;
}
|
#include <cassert>
#include "OpenFlight/DotExporter.h"
#include "OpenFlight/OpenFlightReader.h"
#include <iostream>
#include <fstream>
#include <string>
#include "OpenFlight/StreamUtilities.h"
using namespace std;
namespace
{
//---------------------------------------------------------------------
#define CHECK( iCondition ) \
do{ \
if (iCondition) printf("%s: %s\n", #iCondition, "passes"); \
string f = string("fails at ") + __FILE__;\
if (!iCondition) { printf("%s: %s (%d)\n", #iCondition, f.c_str(), __LINE__); } \
} while(0);
//---------------------------------------------------------------------
#define CHECK_TRUE( iCondition ) \
CHECK( (iCondition) );
//---------------------------------------------------------------------
#define CHECK_FALSE( iCondition ) \
CHECK( !(iCondition) );
}
//--------------------------------------------------------------------------
void testFile()
{
printf("\n\n --- testMultiTextureRecord --- \n");
OpenFlight::OpenFlightReader ofr;
OpenFlight::OpenFlightReader::Options ofrOptions;
ofrOptions.mDebugEnabled = false;
ofr.setOptions(ofrOptions);
ofr.open("D:/work/Projet/Commando/FLTs/ebbr/ebbr_5m.flt");
}
//--------------------------------------------------------------------------
void testMultiTextureRecord()
{
printf("\n\n --- testMultiTextureRecord --- \n");
OpenFlight::OpenFlightReader ofr;
OpenFlight::OpenFlightReader::Options ofrOptions;
ofrOptions.mDebugEnabled = false;
ofr.setOptions(ofrOptions);
//--------
string filenamePath = "./MultiTextureRecord.flt";
ofstream ofs;
ofs.open(filenamePath, ifstream::out | ios_base::binary);
//make header record
OpenFlight::writeUint16(ofs, OpenFlight::ocHeader);
OpenFlight::writeUint16(ofs, 600);
string data(600-4, 0);
OpenFlight::writeBytes(ofs, data);
// push
OpenFlight::writeUint16(ofs, OpenFlight::ocPushLevel);
OpenFlight::writeUint16(ofs, 4);
// make multitexture node.
OpenFlight::writeUint16(ofs, OpenFlight::ocMultitexture);
OpenFlight::writeUint16(ofs, 4 + 4 + 8*2);
// layer 0 and 2 (1 and 3)...
uint32_t attribMask = 0xA0000000; //-> 1010 0000 0000 0000 0000 0000 0000 0000
OpenFlight::writeUint32(ofs, attribMask);
OpenFlight::writeUint16(ofs, 1);
OpenFlight::writeUint16(ofs, OpenFlight::MultiTextureRecord::etTextureEnvironment);
OpenFlight::writeUint16(ofs, 3);
OpenFlight::writeUint16(ofs, 4);
OpenFlight::writeUint16(ofs, 5);
OpenFlight::writeUint16(ofs, OpenFlight::MultiTextureRecord::etBump);
OpenFlight::writeUint16(ofs, 7);
OpenFlight::writeUint16(ofs, 8);
// make UV LIST RECORD.
OpenFlight::writeUint16(ofs, OpenFlight::ocUvList);
OpenFlight::writeUint16(ofs, 4 + 4 + 8*4);
OpenFlight::writeInt32(ofs, attribMask);
// only two vertice define for layer 1 and 3.
//Vertex 0
//u layer 1
OpenFlight::writeFloat32(ofs, 1.5);
//v layer 1
OpenFlight::writeFloat32(ofs, 2.5);
//u layer 3
OpenFlight::writeFloat32(ofs, 3.5);
//v layer 3
OpenFlight::writeFloat32(ofs, 4.5);
//Vertex 1
//u layer 1
OpenFlight::writeFloat32(ofs, 5.5);
//v layer 1
OpenFlight::writeFloat32(ofs, 6.5);
//u layer 3
OpenFlight::writeFloat32(ofs, 7.5);
//v layer 3
OpenFlight::writeFloat32(ofs, 8.5);
//!!!!!!!!! FIN DU CONTENU BIDON
ofs.close();
OpenFlight::HeaderRecord *pRoot = ofr.open( filenamePath );
{
// fetch MultiTexture record and validate.
OpenFlight::MultiTextureRecord *pMulti = (OpenFlight::MultiTextureRecord*)pRoot->getAncillaryRecord(0);
CHECK_TRUE(pMulti);
CHECK_TRUE(pMulti->hasLayer(0));
CHECK_FALSE(pMulti->hasLayer(1));
CHECK_TRUE(pMulti->hasLayer(2));
CHECK_FALSE(pMulti->hasLayer(3));
CHECK_FALSE(pMulti->hasLayer(4));
CHECK_FALSE(pMulti->hasLayer(5));
CHECK_FALSE(pMulti->hasLayer(6));
CHECK_TRUE(pMulti->hasLayers());
CHECK_TRUE( pMulti->getTexturePatternIndex(0) == 1 );
CHECK_TRUE( pMulti->getEffect(0) == OpenFlight::MultiTextureRecord::etTextureEnvironment);
CHECK_TRUE( pMulti->getMappingIndex(0) == 3);
CHECK_TRUE( pMulti->getData(0) == 4);
CHECK_TRUE( pMulti->getTexturePatternIndex(1) == -1);
CHECK_TRUE( pMulti->getEffect(1) == OpenFlight::MultiTextureRecord::etUserDefined);
CHECK_TRUE( pMulti->getMappingIndex(1) == -1);
CHECK_TRUE( pMulti->getData(1) == -1);
CHECK_TRUE( pMulti->getTexturePatternIndex(2) == 5);
CHECK_TRUE( pMulti->getEffect(2) == OpenFlight::MultiTextureRecord::etBump);
CHECK_TRUE( pMulti->getMappingIndex(2) == 7);
CHECK_TRUE( pMulti->getData(2) == 8);
CHECK_TRUE( pMulti->getTexturePatternIndex(11) == -1);
CHECK_TRUE( pMulti->getMappingIndex(11) == -1);
CHECK_TRUE( pMulti->getEffect(11) == OpenFlight::MultiTextureRecord::etUserDefined);
CHECK_TRUE( pMulti->getData(11) == -1);
// fetch Uv list record and validate.
OpenFlight::UvListRecord *pUv = (OpenFlight::UvListRecord*)pRoot->getAncillaryRecord(1);
CHECK_TRUE(pUv);
CHECK_TRUE(pUv->hasLayers());
CHECK_TRUE(pUv->hasLayer(0));
CHECK_FALSE(pUv->hasLayer(1));
CHECK_TRUE(pUv->hasLayer(2));
CHECK_FALSE(pUv->hasLayer(3));
CHECK_FALSE(pUv->hasLayer(4));
CHECK_FALSE(pUv->hasLayer(5));
CHECK_FALSE(pUv->hasLayer(6));
OpenFlight::Vector2f l0v0 = pUv->getUv(0, 0);
OpenFlight::Vector2f l1v0 = pUv->getUv(1, 0);
OpenFlight::Vector2f l2v0 = pUv->getUv(2, 0);
OpenFlight::Vector2f l3v0 = pUv->getUv(3, 0);
OpenFlight::Vector2f l22v0 = pUv->getUv(22, 0);
OpenFlight::Vector2f l0v1 = pUv->getUv(0, 1);
OpenFlight::Vector2f l2v1 = pUv->getUv(2, 1);
CHECK_TRUE(l0v0.mX == 1.5);
CHECK_TRUE(l0v0.mY == 2.5);
CHECK_TRUE(l1v0.mX == 0.0);
CHECK_TRUE(l1v0.mY == 0.0);
CHECK_TRUE(l2v0.mX == 3.5);
CHECK_TRUE(l2v0.mY == 4.5);
CHECK_TRUE(l0v1.mX == 5.5);
CHECK_TRUE(l0v1.mY == 6.5);
CHECK_TRUE(l2v1.mX == 7.5);
CHECK_TRUE(l2v1.mY == 8.5);
}
delete pRoot;
}
//--------------------------------------------------------------------------
void testSwitchRecord()
{
printf("\n\n --- testSwitchRecord --- \n");
OpenFlight::OpenFlightReader ofr;
OpenFlight::OpenFlightReader::Options ofrOptions;
ofrOptions.mDebugEnabled = false;
ofr.setOptions(ofrOptions);
OpenFlight::HeaderRecord *hr = ofr.open("../../assets/testFiles/switch.flt");
CHECK_TRUE(!ofr.hasErrors());
//CHECK_TRUE(!ofr.hasWarnings());
OpenFlight::PrimaryRecord *pr = hr->getChild(0)->getChild(0)->getChild(0);
CHECK_TRUE(pr->getOpCode() == OpenFlight::ocSwitch);
OpenFlight::SwitchRecord *sr = (OpenFlight::SwitchRecord*)pr;
CHECK_TRUE(sr->getCurrentMaskIndex() == 0);
CHECK_TRUE(sr->getNumberOfMasks() == 3);
CHECK_TRUE(sr->getNumberOfWordsPerMask() == 2);
CHECK_TRUE(sr->getMaskName(0) == "mask 0");
CHECK_TRUE(sr->getMaskName(1) == "mask 1");
CHECK_TRUE(sr->getMaskName(2) == "mask 2");
// mask 0; 0 - 11
vector<int> selectedChilds = sr->getSelectedChildFromMask(0);
for(int i = 0; i < selectedChilds.size(); ++i)
CHECK_TRUE(selectedChilds[i] == i);
// mask 1; 12 - 24
selectedChilds = sr->getSelectedChildFromMask(1);
for(int i = 0; i < selectedChilds.size(); ++i)
CHECK_TRUE(selectedChilds[i] == i+12);
// mask 2; 25 - 44
selectedChilds = sr->getSelectedChildFromMask(2);
for(int i = 0; i < selectedChilds.size(); ++i)
CHECK_TRUE(selectedChilds[i] == i+25);
}
//--------------------------------------------------------------------------
void testTextureAttribute()
{
printf("\n\n --- testTextureAttribute --- \n");
OpenFlight::TextureAttribute ta;
ta.readFromFile("../../assets/testFiles/ice_rwy.rgb.attr");
CHECK_TRUE(ta.isValid());
CHECK_TRUE(ta.getEnvironmentType() == OpenFlight::TextureAttribute::etModulate);
CHECK_TRUE(ta.getFileFormatType() == OpenFlight::TextureAttribute::SgiRgb);
CHECK_TRUE(ta.getMagnificationFilterType() == OpenFlight::TextureAttribute::mmftBilinear);
CHECK_TRUE(ta.getMinificationFilterType() == OpenFlight::TextureAttribute::mmftBilinear);
CHECK_TRUE(ta.getRealWorldSizeX() == 1000.0);
CHECK_TRUE(ta.getRealWorldSizeY() == 1000.0);
CHECK_TRUE(ta.getSizeInTexelsX() == 512);
CHECK_TRUE(ta.getSizeInTexelsY() == 512);
CHECK_TRUE(ta.getWrapMethodU() == OpenFlight::TextureAttribute::wmNone);
CHECK_TRUE(ta.getWrapMethodUV() == OpenFlight::TextureAttribute::wmRepeat);
CHECK_TRUE(ta.getWrapMethodU() == OpenFlight::TextureAttribute::wmNone);
}
//--------------------------------------------------------------------------
int main(int argc, char** argv)
{
testMultiTextureRecord();
testSwitchRecord();
testTextureAttribute();
//testFile();
return 0;
}
|
#pragma once
typedef int LinkID;
class User
{
public:
User(LinkID linkID);
virtual ~User();
LinkID& GetLinkID() { return mLinkID; };
public:
int mUserID;
int mUserType;
private:
LinkID mLinkID;
bool mFlvSeqHeaderFlag;
};
|
#include <vector>
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include <list>
#include <algorithm>
#include <sstream>
#include <set>
#include <cmath>
#include <map>
#include <stack>
#include <queue>
#include <stdio.h>
#include <string.h>
using namespace std;
#define INF (1<<20)
#define PI 3.14159265
string alpha = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
class StrIIRec {
public:
int
calc_inv(string str)
{
int ans = 0;
for (int i=0; i<str.size(); ++i) {
for (int j=i; j<str.size(); ++j) {
if (str[i] > str[j]) {
++ans;
}
}
}
return ans;
}
string
next(string s)
{
for (int left = (int)s.size()-2; left >= 0; --left) {
for (int right = (int)s.size()-1; right > left; --right) {
if (s[left] < s[right]) {
swap(s[left], s[right]);
return s;
}
}
}
return s;
}
string
recovstr(int n, int minInv, string minStr)
{
int pos = 0;
while (minStr.size() < n) {
if (minStr.find(alpha[pos]) == string::npos) {
minStr.push_back(alpha[pos]);
}
++pos;
}
while (calc_inv(minStr) < minInv) {
minStr = next(minStr);
}
return minStr;
}
};
|
#include "SFML/Graphics.hpp"
#include <vector>
#include "MacroValues.h"
#include "TileMap.h"
#include <boost/serialization/serialization.hpp>
#include "Handler.h"
#include "GameEngine.h"
#include "Button.h"
#include <functional>
GameEngine* engine;
void SetupButtons(GameEngine* engine);
int mapTemp[32][40];
int main() {
init();
WINDOW_WIDTH += 100;
std::copy(&map1[0][0], &map1[0][0] + 32 * 40, &mapTemp[0][0]);
TileMap* tilemap = new TileMap();
sf::RenderWindow window(sf::VideoMode(WINDOW_WIDTH, WINDOW_HEIGHT), "SFML works!");
sf::View camera = window.getDefaultView();
engine = new GameEngine(camera);
InputHandler* input = new InputHandler(engine);
camera.zoom(1);
camera.setCenter(WINDOW_WIDTH/ 2, WINDOW_HEIGHT / 2);
camera.setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
SetupButtons(engine);
engine->map->LoadMap(1);
while (window.isOpen()) {
window.setView(camera);
sf::Event event;
sf::Vector2i pixelPos = sf::Mouse::getPosition(window);
// convert it to world coordinates
sf::Vector2f worldPos = window.mapPixelToCoords(pixelPos);
while (window.pollEvent(event))
{
if (event.type == sf::Event::MouseButtonPressed) {
}
if (event.type == sf::Event::MouseWheelScrolled) {
engine->input->scrollMouse(worldPos, (float)event.mouseWheelScroll.delta);
std::cout << event.mouseWheelScroll.delta << ", " << sprites->offset << std::endl;
}
// "close requested" event: we close the window
if (event.type == sf::Event::Closed)
window.close();
}
// get the current mouse position in the window
input->checkMouse(worldPos);
window.clear(sf::Color::Blue);
for (int i = 0; i < engine->map->Tiles.size(); i++) {
for (int j = 0; j < engine->map->Tiles[i].size(); j++) {
window.draw(engine->map->Tiles[i][j]->icon);
}
}
for (int i = 0;i < sprites->sprites.size(); i++) {
window.draw(sprites->sprites[i]);
}
window.draw(engine->loadButton->icon);
window.draw(engine->saveButton->icon);
window.display();
}
return 0;
}
void SaveMap() {
Handler* h = new Handler();
h->serializeMap();
printf("saved");
}
void LoadMap() {
Handler* h = new Handler();
h->LoadMap();
printf("loaded");
engine->map->LoadMap(currentMap);
}
void SetupButtons(GameEngine* engine) {
engine->loadButton = new Button(LoadMap);
engine->saveButton = new Button(SaveMap);
//setup load image and place
sf::Texture* tex = new sf::Texture();
tex->loadFromFile("load.png", sf::IntRect(0, 0, 64, 32));
engine->loadButton->icon.setTexture(*tex);
engine->loadButton->icon.setPosition(1285, 960);
engine->loadButton->icon.setScale(1, 1);
sf::Texture* tex2 = new sf::Texture();
tex2->loadFromFile("save.png", sf::IntRect(0, 0, 64, 32));
engine->saveButton->icon.setTexture(*tex2);
engine->saveButton->icon.setPosition(1285, 992);
engine->saveButton->icon.setScale(1, 1);
}
|
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <functional>
#include <queue>
#include <string>
#include <cstring>
#include <numeric>
#include <cstdlib>
#include <cmath>
using namespace std;
typedef long long ll;
#define INF 10e10
#define rep(i,n) for(int i=0; i<n; i++)
#define rep_r(i,n,m) for(int i=m; i<n; i++)
#define END cout << endl
#define MOD 1000000007
#define pb push_back
// 昇順sort
#define sorti(x) sort(x.begin(), x.end())
// 降順sort
#define sortd(x) sort(x.begin(), x.end(), std::greater<int>())
int main() {
int h,w,n; cin >> h >> w >> n;
vector<pair<int,int> > a(n);
rep(i,n) {
pair<int,int> p;
cin >> p.second;
p.first = i + 1;
a[i] = p;
}
int res[h][w];
ll count = 0, row = 0;
bool flag = true;
for (auto itr : a) {
for (int i = 0; i < itr.second; ++i) {
res[row][count] = itr.first;
if (flag) {
count += 1;
if (count >= w) {
row += 1;
count = w-1;
flag = false;
}
} else {
count -= 1;
if (count < 0) {
row += 1;
count = 0;
flag = true;
}
}
}
}
for (int i = 0; i < h; ++i) {
for (int j = 0; j < w; ++j) {
cout << res[i][j] << " ";
}
END;
}
}
|
#include "Game.h"
#include <string>
Game* Game::m_gamePtr{nullptr};
Game::Game() :
m_window{ sf::VideoMode{ 1000, 800, 32 }, "Tag" },
m_exitGame{ false },
m_client(nullptr),
m_server(nullptr)
{
Game::m_gamePtr = this;
m_client = new Client("127.0.0.1", 1111);// , this);
if (!m_client->Connect())
{
// You're Server
m_server = new Server(1111, false);
std::thread PST(listenForNewConnections, std::ref(*m_server));
PST.detach();
m_gameThreads.push_back(&PST);
isServer = true;
}
initialize();
}
Game::~Game()
{
}
void Game::run()
{
sf::Clock clock;
sf::Time timeSinceLastUpdate = sf::Time::Zero;
sf::Time timePerFrame = sf::seconds(1.f / 60.f); // 60 fps
while (m_window.isOpen())
{
processEvents(); // as many as possible
timeSinceLastUpdate += clock.restart();
while (timeSinceLastUpdate > timePerFrame)
{
timeSinceLastUpdate -= timePerFrame;
processEvents(); // at least 60 fps
update(timePerFrame); //60 fps
}
render(); // as many as possible
}
}
void Game::Clear(int id)
{
for(int i = 0; i < m_otherPlayers.size(); i++)
{
if (id == m_otherPlayers.at(i)->id)
{
m_otherPlayers.erase(m_otherPlayers.begin() + i);
return;
}
}
}
void Game::processEvents()
{
while (m_window.pollEvent(event))
{
if (sf::Event::Closed == event.type) // window message
{
m_window.close();
}
if (sf::Event::KeyPressed == event.type) //user key press
{
if (sf::Keyboard::Escape == event.key.code)
{
m_exitGame = true;
}
}
if (event.type == sf::Event::MouseButtonPressed)
{
if (event.mouseButton.button == sf::Mouse::Left)
{
}
}
if (event.type == sf::Event::MouseButtonReleased)
{
if (event.mouseButton.button == sf::Mouse::Left)
{
}
}
}
}
void Game::initialize()
{
if (isServer == true)
{
m_client->Connect();
}
m_client->sendPosition(Game::m_gamePtr->m_player.m_circle.getPosition().x, Game::m_gamePtr->m_player.m_circle.getPosition().y);
if (m_player.m_circle.getFillColor() == sf::Color::Red)
m_client->sendColor(0);
else if (m_player.m_circle.getFillColor() == sf::Color::Blue)
m_client->sendColor(1);
else if (m_player.m_circle.getFillColor() == sf::Color::Green)
m_client->sendColor(2);
else if (m_player.m_circle.getFillColor() == sf::Color::White)
m_client->sendColor(3);
else if (m_player.m_circle.getFillColor() == sf::Color::Yellow)
m_client->sendColor(4);
}
void Game::update(sf::Time t_deltaTime)
{
if (m_exitGame)
{
m_window.close(); // Exiting the game
}
if (gameEnd == false)
{
if (playersInGame < m_otherPlayers.size())
{
m_client->sendPosition(Game::m_gamePtr->m_player.m_circle.getPosition().x, Game::m_gamePtr->m_player.m_circle.getPosition().y);
if (m_player.m_circle.getFillColor() == sf::Color::Red)
m_client->sendColor(0);
else if (m_player.m_circle.getFillColor() == sf::Color::Blue)
m_client->sendColor(1);
else if (m_player.m_circle.getFillColor() == sf::Color::Green)
m_client->sendColor(2);
else if (m_player.m_circle.getFillColor() == sf::Color::White)
m_client->sendColor(3);
else if (m_player.m_circle.getFillColor() == sf::Color::Yellow)
m_client->sendColor(4);
playersInGame++;
m_clock.restart();
}
if (playersInGame > 0)
{
m_timer = m_clock.getElapsedTime();
}
bool move = false;
if (sf::Keyboard::isKeyPressed(sf::Keyboard::D))
{
m_player.m_circle.setPosition(sf::Vector2f(m_player.m_circle.getPosition().x + 3, m_player.m_circle.getPosition().y));
move = true;
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::A))
{
m_player.m_circle.setPosition(sf::Vector2f(m_player.m_circle.getPosition().x - 3, m_player.m_circle.getPosition().y));
move = true;
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::W))
{
m_player.m_circle.setPosition(sf::Vector2f(m_player.m_circle.getPosition().x, m_player.m_circle.getPosition().y - 3));
move = true;
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::S))
{
m_player.m_circle.setPosition(sf::Vector2f(m_player.m_circle.getPosition().x, m_player.m_circle.getPosition().y + 3));
move = true;
}
if (move == true)
{
m_client->sendPosition(Game::m_gamePtr->m_player.m_circle.getPosition().x, Game::m_gamePtr->m_player.m_circle.getPosition().y);
}
m_player.update(t_deltaTime);
for (auto otherPlayer : m_otherPlayers)
{
if (m_player.isColliding(otherPlayer))
{
gameEnd = true;
m_client->sendEnd(1);
std::cout << "Game lasted: " << std::to_string(m_timer.asSeconds()) << " seconds" << std::endl;
}
}
}
}
void Game::render()
{
m_window.clear(sf::Color::Black);
for (auto otherPlayer : m_otherPlayers)
{
otherPlayer->render(m_window);
}
m_player.render(m_window);
m_window.display();
}
void Game::listenForNewConnections(Server& t_server)
{
while (true)
{
t_server.ListenForNewConnection();
}
}
void Game::updatePosition(int t_id, float t_xPos, float t_yPos)
{
for (auto player : m_otherPlayers)
{
if (t_id == player->id)
{
player->m_circle.setPosition(sf::Vector2f(t_xPos, t_yPos));
return;
}
}
// New player needed
Player* otherPlayer = new Player();
otherPlayer->id = t_id;
otherPlayer->m_circle.setPosition(t_xPos, t_yPos);
m_otherPlayers.push_back(otherPlayer);
}
void Game::updateColor(int id, int t_newCol)
{
for (auto player : m_otherPlayers)
{
if (id == player->id)
{
switch (t_newCol)
{
case 0:
player->m_circle.setFillColor(sf::Color::Red);
break;
case 1:
player->m_circle.setFillColor(sf::Color::Blue);
break;
case 2:
player->m_circle.setFillColor(sf::Color::Green);
break;
case 3:
player->m_circle.setFillColor(sf::Color::White);
break;
case 4:
player->m_circle.setFillColor(sf::Color::Yellow);
break;
default:
break;
}
}
}
}
void Game::endGame(int end)
{
if (end == 1)
{
gameEnd = true;
}
}
|
/* \
| Name & Surname : Halil Emin Çalışkan |
| School Number : 1306180055 |
| Date : 22/12/2019 |
| Development Environment : Visual Studio 2019 |
\ */
// I import important library in this area.
#include <iostream>
#include <vector>
#include <string>
using namespace std;
// I define edge class. It must have a name and childrens. I use vector for childrens.
class Edge
{
public:
string edgeName;
vector <Edge*> childrens;
};
// This function is for printing every word that can be create.
void printing(string &row, Edge& thisEdge, size_t funcMaxRowLength) {
// This row is empty because first edge isn't children. In the if loop below for print childrens.
row += thisEdge.edgeName;
cout << row << endl;
if (row.size() <= funcMaxRowLength-1) {
for (size_t i = 0; i < thisEdge.childrens.size(); i++) {
printing(row, *thisEdge.childrens[i], funcMaxRowLength);
}
}
row = row.substr(0, row.size() - 1);
}
// This function is for learn how much letter in string.
int howMuchLetterInString(char thisString[], int sizeOfString) {
int letterInString = 0;
for (int i = 0; i < sizeOfString - 1; i++) {
if (int(thisString[i]) >= 65 && int(thisString[i]) <= 90) {
letterInString++;
}
}
return letterInString;
}
// In this project I don't take any input when program is running so, I take string with argv.
int main(int argc, char* argv[])
{
// This if loop checking argument count (argc).
if ( argc == 2 ) {
string str = argv[1];
char inputString[sizeof(str)];
strcpy_s(inputString, str.c_str()); // I couldn't assign string to char so, I used strcpy_s for copy string to char.
string emptyRow = "";
int firstLetterInAscii = 65;
int sumLetterInString = howMuchLetterInString(inputString, strlen(inputString));
bool isItFirstTimeNumber = 1;
bool isItFirstTimeLetter = 1;
string maxRowLength = "";
string parentName = "";
string childrenName = "";
Edge* edge = new Edge[sumLetterInString]; // I created edges as many letter in string.
// I gived edgeName for every created edges.
for (int i = 0; i < sumLetterInString; i++) {
int thisAsciiCode = firstLetterInAscii + i;
edge[i].edgeName = (char)thisAsciiCode;
}
for (size_t i = 0; i < strlen(inputString); i++) {
// Checking for is it number.
if (int(inputString[i]) >= 48 && int(inputString[i]) <= 57) {
isItFirstTimeLetter = 1; // If the number has come, the next letter is displayed for the first time.
// Checking for is it first time number.
if (isItFirstTimeNumber == 1) {
maxRowLength += inputString[i];
}
// If it is separated by 1, it continues without doing anything.
else if (inputString[i] == 49) {
continue;
}
// Giving error if it is not separated by 1..
else {
cout << "Please seperate between letters with 1." << endl;
}
}
// Checking for is it letter.
else if (int(inputString[i]) >= 65 && int(inputString[i]) <= 90) {
isItFirstTimeNumber = 0; // This is only to check the number at the beginning of the string so once the letter display you do not need to do it again 1.
// Checking for is it first time number. If it is first time, it is parent.
if (isItFirstTimeLetter == 1) {
parentName = inputString[i];
isItFirstTimeLetter = 0; // After the first letter we make 0 to other letters make children.
}
// If it isn't first time it is children.
else {
childrenName = inputString[i];
// If it is children we connect childrens with their parent.
for (int k = 0; k < sumLetterInString; k++) {
if (edge[k].edgeName == parentName) {
for (int m = 0; m < sumLetterInString; m++) {
if (edge[m].edgeName == childrenName) {
edge[k].childrens.push_back(&edge[m]);
}
}
}
}
}
}
// Give error if they input something other than a letter or number.
else {
cout << "Please check the your input. Turkish characters, symbols and lower case aren't accepted." << endl;
break;
}
}
// If still isItFirstTimeNumber == 0 , It means they didn't enter any letter.
if (isItFirstTimeNumber == 0) {
// If isItFirstTimeLetter == 0 , It means they didn't finish string with letter.
if (isItFirstTimeLetter == 0) {
int intMaxRowLength = stoi(maxRowLength);
printing(emptyRow, edge[0], intMaxRowLength);
}
else {
cout << "Your input must be finish with a letter !" << endl;
}
}
else {
cout << "You need to give a edge. (ex. 5ABCD)" << endl;
}
}
else {
cout << "You give " << argc << " argument(s) but you must give 2 arguments." << endl;
}
return 0;
}
|
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int n = nums.size();
if (n > 0) {
int s = -1;
int e = -1;
for (int i = 0; i < n; ++i) {
if (nums[i] == 0) {
if (s == -1) s = e = i;
else ++e;
} else if (nums[i] != 0 && s != -1) {
swap(nums[i], nums[s]);
++s, ++e;
}
}
}
}
};
int main() {
return 0;
}
|
using namespace std;
#include <iostream>
#include <math.h>
#include <plib.h>
double factrl(int n)
{
static int ntop=4;
static double a[33]={1.0,1.0,2.0,6.0,24.0};
int j;
if (n < 0)
cerr << "Negative factorial in routine FACTRL" << endl;
if (n > 32) return exp(gammln(n+1.0));
while (ntop<n) {
j=ntop++;
a[ntop]=a[j]*ntop;
}
return a[n];
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-2010 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
*/
#ifndef VEGAD3D10FBO_H
#define VEGAD3D10FBO_H
#ifdef VEGA_BACKEND_DIRECT3D10
#include "modules/libvega/vega3ddevice.h"
#ifdef VEGA_BACKEND_D2D_INTEROPERABILITY
#include <d2d1.h>
class VEGAD3d10FramebufferObject;
#endif
#ifdef VEGA_BACKEND_D2D_INTEROPERABILITY
class FontFlushListener
{
public:
/*
The flushFontBatch listener is called when EndDraw()/Flush() is called.
This gives the platform the possibility to limit the number of
DrawText/DrawGlypRun calls on the render target, which speeds
up font rendering.
*/
virtual void flushFontBatch() = 0;
/*
discardBatch is usually only called if the render target is resized before
the EndDraw() calls happens. The platform should then reset the font batch.
*/
virtual void discardBatch() = 0;
};
#endif // VEGA_BACKEND_D2D_INTEROPERABILITY
class VEGAD3d10RenderbufferObject : public VEGA3dRenderbufferObject
{
public:
VEGAD3d10RenderbufferObject(unsigned int w, unsigned int h, ColorFormat fmt, unsigned int quality);
~VEGAD3d10RenderbufferObject();
OP_STATUS Construct(ID3D10Device1* d3dDevice);
ID3D10RenderTargetView* getRenderTargetView(){return m_rtView;}
ID3D10DepthStencilView* getDepthStencilView(){return m_dsView;}
ID3D10Texture2D* getTextureResource(){return m_texture;}
virtual unsigned int getWidth(){return m_width;}
virtual unsigned int getHeight(){return m_height;}
virtual ColorFormat getFormat(){return m_format;}
virtual unsigned int getNumSamples(){return m_samples;}
#ifdef VEGA_BACKEND_D2D_INTEROPERABILITY
void setActiveD2DFBO(VEGAD3d10FramebufferObject* fbo);
#endif // VEGA_BACKEND_D2D_INTEROPERABILITY
virtual unsigned int getRedBits();
virtual unsigned int getGreenBits();
virtual unsigned int getBlueBits();
virtual unsigned int getAlphaBits();
virtual unsigned int getDepthBits();
virtual unsigned int getStencilBits();
private:
unsigned int m_width;
unsigned int m_height;
ColorFormat m_format;
unsigned int m_samples;
ID3D10RenderTargetView* m_rtView;
ID3D10DepthStencilView* m_dsView;
ID3D10Texture2D* m_texture;
#ifdef VEGA_BACKEND_D2D_INTEROPERABILITY
VEGAD3d10FramebufferObject* m_activeD2DFBO;
#endif // VEGA_BACKEND_D2D_INTEROPERABILITY
};
class VEGAD3d10FramebufferObject : public VEGA3dFramebufferObject
{
public:
VEGAD3d10FramebufferObject(ID3D10Device1* d3dDevice
#ifdef VEGA_BACKEND_D2D_INTEROPERABILITY
, ID2D1Factory* d2dFactory, D2D1_FEATURE_LEVEL flevel, D2D1_TEXT_ANTIALIAS_MODE textMode
#endif
, bool featureLevel9);
virtual ~VEGAD3d10FramebufferObject();
virtual unsigned int getWidth();
virtual unsigned int getHeight();
virtual OP_STATUS attachColor(class VEGA3dTexture* color, VEGA3dTexture::CubeSide side);
virtual OP_STATUS attachColor(VEGA3dRenderbufferObject* color);
virtual OP_STATUS attachDepth(VEGA3dRenderbufferObject* depth);
virtual OP_STATUS attachStencil(VEGA3dRenderbufferObject* stencil);
virtual OP_STATUS attachDepthStencil(VEGA3dRenderbufferObject* depthStencil);
virtual class VEGA3dTexture* getAttachedColorTexture();
virtual class VEGA3dRenderbufferObject* getAttachedColorBuffer();
virtual class VEGA3dRenderbufferObject* getAttachedDepthStencilBuffer();
virtual unsigned int getRedBits();
virtual unsigned int getGreenBits();
virtual unsigned int getBlueBits();
virtual unsigned int getAlphaBits();
virtual unsigned int getDepthBits();
virtual unsigned int getStencilBits();
virtual unsigned int getSubpixelBits();
virtual unsigned int getSampleBuffers();
virtual unsigned int getSamples();
ID3D10RenderTargetView* getRenderTargetView();
ID3D10DepthStencilView* getDepthStencilView();
ID3D10Texture2D* getColorResource();
#ifdef VEGA_BACKEND_D2D_INTEROPERABILITY
ID2D1RenderTarget* getD2DRenderTarget(bool requireDestAlpha, FontFlushListener* fontFlushListener);
void StopDrawingD2D();
# ifdef VEGA_NATIVE_FONT_SUPPORT
virtual void flushFonts();
# endif
#endif
private:
VEGA3dTexture* m_attachedColorTex;
VEGA3dRenderbufferObject* m_attachedColorBuf;
VEGA3dRenderbufferObject* m_attachedDepthStencilBuf;
ID3D10RenderTargetView* m_texRTView;
ID3D10Device1* m_d3dDevice;
#ifdef VEGA_BACKEND_D2D_INTEROPERABILITY
ID2D1Factory* m_d2dFactory;
D2D1_FEATURE_LEVEL m_d2dFLevel;
ID2D1RenderTarget* m_d2dRenderTarget;
bool m_isDrawingD2D;
D2D1_TEXT_ANTIALIAS_MODE m_textMode;
FontFlushListener* m_fontFlushListener;
#endif // VEGA_BACKEND_D2D_INTEROPERABILITY
bool m_featureLevel9;
};
#endif // VEGA_BACKEND_DIRECT3D10
#endif // !VEGAD3D10FBO_H
|
#include <iostream>
#include "sales_data.h"
// reads several transactions and counts how many transactions occur for each ISBN
int main()
{
Sales_data bookIn, currentBook;
int count=0;
std::cin >> currentBook.bookId >> currentBook.unitsSold >> currentBook.revenue;
count++;
while (std::cin >> bookIn.bookId >> bookIn.unitsSold >> bookIn.revenue){
if (bookIn.bookId == currentBook.bookId){
count++;
}
else{
// new book
// print count of last book
std::cout << "ISBN: " << currentBook.bookId << " " << count << " Transactions" << std::endl;
currentBook.bookId = bookIn.bookId;
currentBook.unitsSold = bookIn.unitsSold;
currentBook.revenue = bookIn.revenue;
count=1;
}
}
//print last transaction
std::cout << "ISBN: " << currentBook.bookId << " " << count << " Transactions" << std::endl;
}
|
/* -*- Mode: c++; indent-tabs-mode: nil; c-file-style: "gnu" -*-
*
* Copyright (C) 1995-2002 Opera Software ASA. All rights reserved.
*
* This file is part of the Opera web browser. It may not be distributed
* under any circumstances.
*/
#ifndef XMLPARSER_XMLSTSUPPORT_H
#define XMLPARSER_XMLSTSUPPORT_H
#ifdef SELFTEST
#include "modules/xmlparser/xmlinternalparser.h"
class XMLSelftestHelper
{
public:
enum Mode
{
PARSE, // Check for well-formedness.
PARSE_EE, // Check for well-formedness with external entities.
VALIDATE, // Validate.
TOKENS // Test that produced tokens have the correct values.
};
enum Expected
{
NOT_WELL_FORMED,
INVALID,
NO_ERRORS
};
enum EndOfData
{
NORMAL, ///< All data avaiable immediately.
NO_CONSUME, ///< The data source never consumes data when asked to (XMLDataSource::Consume returns zero.)
LEVEL_1, ///< One character more becomes available whenever the parsers asks for more data.
LEVEL_2, ///< One character more becomes available every time the parser stops because it had no more data.
LEVEL_3, ///< One character more becomes available when the parser asks for more data after it has stopped because it had no more data.
MAX_TOKENS ///< Set max_tokens_per_call to 1.
};
XMLSelftestHelper (const char *source, unsigned source_length, const uni_char *basename, Mode mode, Expected expected, EndOfData endofdata);
~XMLSelftestHelper ();
static BOOL FromFile (const char *filename, Mode mode, Expected expected, EndOfData endofdata = NORMAL);
BOOL Parse ();
protected:
const char *source;
unsigned source_length;
const uni_char *basename;
Mode mode;
Expected expected;
EndOfData endofdata;
};
#ifdef XML_VALIDATING
class XMLSelftestValidityHelper
{
public:
XMLSelftestValidityHelper (const char *source);
~XMLSelftestValidityHelper ();
BOOL Parse ();
BOOL CheckErrorsCount (unsigned count);
BOOL CheckError (unsigned error_index, XMLInternalParser::ParseError error);
BOOL CheckRangesCount (unsigned error_index, unsigned count);
BOOL CheckRange (unsigned error_index, unsigned range_index, unsigned start_line, unsigned start_column, unsigned end_line, unsigned end_column);
BOOL CheckDataCount (unsigned error_index, unsigned count);
BOOL CheckDatum (unsigned error_index, unsigned datum_index, const uni_char *datum);
protected:
XMLValidityReport *report;
const char *source;
};
#endif // XML_VALIDATING
#endif // SELFTEST
#endif // XMLPARSER_XMLSTSUPPORT_H
|
#include "opennwa/Nwa.hpp"
#include "opennwa/NestedWord.hpp"
#include "opennwa/construct/intersect.hpp"
#include "opennwa/construct/complement.hpp"
#include "opennwa/query/language.hpp"
namespace opennwa {
namespace query {
bool
languageContains(Nwa const & nwa, NestedWord const & word)
{
return nwa.isMemberNondet(word);
}
bool
languageSubsetEq(Nwa const & first, Nwa const & second)
{
Nwa second_copy = second;
// We have to synchronize alphabets first
for (Nwa::SymbolIterator sym = first.beginSymbols();
sym != first.endSymbols(); ++sym)
{
second_copy.addSymbol(*sym);
}
//Check L(a1) contained in L(a2) by checking
//if L(a1) intersect (complement L(a2)) is empty.
NwaRefPtr comp = construct::complement(second_copy);
NwaRefPtr inter = construct::intersect(first, *comp);
//inter.intersect(first, comp); //L(a1) intersect (complement L(a2))
return languageIsEmpty(*inter);
}
bool
languageIsEmpty(Nwa const & nwa)
{
return nwa._private_isEmpty_();
}
bool
languageEquals(Nwa const & first, Nwa const & second)
{
//The languages accepted by two NWAs are equivalent if they are both contained
//in each other, ie L(a1) contained in L(a2) and L(a2) contained in L(a1).
bool first_in_second = query::languageSubsetEq(first, second);
bool second_in_first = query::languageSubsetEq(second, first);
return (first_in_second && second_in_first );
}
}
}
// Yo, Emacs!
// Local Variables:
// c-file-style: "ellemtel"
// c-basic-offset: 2
// End:
|
/*
* Copyright (c) 2016, GNSS Sensor Ltd.
*
* 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.
*/
#pragma once
#include "imapdev.h"
#include <memory>
class PNP : public IMappedDevice {
public:
PNP();
virtual bool isAddrValid(uint64_t addr) {
return (addr >= 0x0FFFFF000ull && addr < 0x100000000ull);
}
virtual void write(uint64_t addr, uint8_t *buf, int size) {
uint64_t off = addr - 0xFFFFF000;
memcpy(reinterpret_cast<char *>(&map_) + off, buf, size);
}
virtual void read(uint64_t addr, uint8_t *buf, int size) {
uint64_t off = addr - 0xFFFFF000;
memcpy(buf, reinterpret_cast<char *>(&map_) + off, size);
}
private:
static const int PNP_CONFIG_DEFAULT_BYTES = 16;
typedef struct PnpConfigType {
uint32_t xmask;
uint32_t xaddr;
uint16_t did;
uint16_t vid;
uint8_t size;
uint8_t rsrv[3];
} PnpConfigType;
typedef struct pnp_map {
volatile uint32_t hwid; /// Read only HW ID
volatile uint32_t fwid; /// Read/Write Firmware ID
volatile uint32_t tech; /// Read only technology index
volatile uint32_t rsrv1; ///
volatile uint64_t idt; ///
volatile uint64_t malloc_addr; /// debuggind memalloc pointer
volatile uint64_t malloc_size; /// debugging memalloc size
volatile uint64_t fwdbg1; /// FW debug register
volatile uint64_t rsrv[2];
PnpConfigType slaves[64];
} pnp_map;
pnp_map map_;
};
|
//
// main.cpp
// MirrorChess
//
// Created by Sergio Colado on 20.04.20.
// Copyright © 2020 Sergio Colado. All rights reserved.
//
#include "Game.hpp"
int main()
{
Game game;
game.init();
}
|
/************************************************************************/
/* X10 Rx/Tx library for the XM10/TW7223/TW523 interface, v1.4. */
/* */
/* This library is free software: you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation, either version 3 of the License, or */
/* (at your option) any later version. */
/* */
/* This library is distributed in the hope that it will be useful, but */
/* WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU */
/* General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this library. If not, see <http://www.gnu.org/licenses/>. */
/* */
/* Written by Thomas Mittet thomas@mittet.nu October 2010. */
/************************************************************************/
#if defined(ARDUINO) && ARDUINO >= 100
#include "Arduino.h"
#else
#include "WProgram.h"
#endif
#include "pins_arduino.h"
#include <avr/eeprom.h>
#include "X10ex.h"
const uint8_t X10ex::HOUSE_CODE[16] =
{
B0110,B1110,B0010,B1010,B0001,B1001,B0101,B1101,
B0111,B1111,B0011,B1011,B0000,B1000,B0100,B1100,
};
const uint8_t X10ex::UNIT_CODE[16] =
{
B0110,B1110,B0010,B1010,B0001,B1001,B0101,B1101,
B0111,B1111,B0011,B1011,B0000,B1000,B0100,B1100,
};
X10ex *x10exInstance = NULL;
void x10exZeroCross_wrapper()
{
if(x10exInstance) x10exInstance->zeroCross();
}
// Hack to get extra interrupt on non ATmega8, 168 and 328 pin 4 to 7
#if defined(__AVR_ATmega8__) || defined(__AVR_ATmega168__) || defined(__AVR_ATmega328P__)
SIGNAL(PCINT2_vect)
{
if(x10exInstance) x10exInstance->zeroCross();
}
#endif
void x10exIoTimer_wrapper()
{
if(x10exInstance) x10exInstance->ioTimer();
}
ISR(TIMER1_OVF_vect)
{
x10exIoTimer_wrapper();
}
X10ex::X10ex(
uint8_t zeroCrossInt, uint8_t zeroCrossPin, uint8_t transmitPin,
uint8_t receivePin, bool receiveTransmits, plcReceiveCallback_t plcReceiveCallback,
uint8_t phases, uint8_t sineWaveHz)
{
this->zeroCrossInt = zeroCrossInt;
this->zeroCrossPin = zeroCrossPin;
this->transmitPin = transmitPin;
transmitPort = digitalPinToPort(transmitPin);
transmitBitMask = digitalPinToBitMask(transmitPin);
this->receivePin = receivePin;
receivePort = digitalPinToPort(receivePin);
receiveBitMask = digitalPinToBitMask(receivePin);
this->receiveTransmits = receiveTransmits;
this->plcReceiveCallback = plcReceiveCallback;
// Setup IO fields
ioStopState = phases * 2;
inputDelayCycles = round(.5 * F_CPU * X10_SAMPLE_DELAY / 1000000);
// Sine wave half cycle devided by number of phases
outputDelayCycles = round(.5 * F_CPU / phases / sineWaveHz / 2);
outputLengthCycles = round(.5 * F_CPU * X10_SIGNAL_LENGTH / 1000000);
// Init. misc fields
sendBfEnd = X10_BUFFER_SIZE - 1;
rxHouse = DATA_UNKNOWN;
rxUnit = DATA_UNKNOWN;
rxExtUnit = DATA_UNKNOWN;
rxCommand = DATA_UNKNOWN;
x10exInstance = this;
}
//////////////////////////////
/// Public
//////////////////////////////
void X10ex::begin()
{
// Using arduino digitalWrite here ensures that pins are
// set up correctly (pwm timers are turned off, etc).
#if defined(ARDUINO) && ARDUINO >= 101
pinMode(zeroCrossPin, INPUT_PULLUP);
pinMode(receivePin, INPUT_PULLUP);
#else
digitalWrite(zeroCrossPin, HIGH);
pinMode(zeroCrossPin, INPUT);
digitalWrite(receivePin, HIGH);
pinMode(receivePin, INPUT);
#endif
pinMode(transmitPin, OUTPUT);
digitalWrite(transmitPin, LOW);
// Setup IO timer
TCCR1A = 0;
TCCR1B = _BV(WGM13) & ~(_BV(CS10) | _BV(CS11) | _BV(CS12));
TIMSK1 = _BV(TOIE1);
ICR1 = inputDelayCycles;
// Attach zero cross interrupt
attachInterrupt(zeroCrossInt, x10exZeroCross_wrapper, CHANGE);
// Make sure interrupts are enabled
sei();
// Hack to get extra interrupt on non ATmega8, 168 and 328 pin 4 to 7
#if defined(__AVR_ATmega8__) || defined(__AVR_ATmega168__) || defined(__AVR_ATmega328P__)
if(zeroCrossInt == 2 && zeroCrossPin >= 4 && zeroCrossPin <= 7)
{
PCMSK2 |= digitalPinToBitMask(zeroCrossPin);
PCICR |= 0x01 << digitalPinToPort(zeroCrossPin) - 2;
}
#endif
}
bool X10ex::sendAddress(uint8_t house, uint8_t unit, uint8_t repetitions)
{
// Using CMD_STATUS_REQUEST to address modules (prepare for BRIGHT, DIM, etc.).
// I've not seen any modules that reply to the request, and even if they did
// it would not cause any harm.
return sendCmd(house, unit, CMD_STATUS_REQUEST, repetitions);
}
bool X10ex::sendCmd(uint8_t house, uint8_t command, uint8_t repetitions)
{
return sendCmd(house, 0, command, repetitions);
}
bool X10ex::sendCmd(uint8_t house, uint8_t unit, uint8_t command, uint8_t repetitions)
{
return sendExt(house, unit, command, 0, 0, repetitions);
}
// You can enable this by changing defined value in header file. If you're using a
// PLC interface and modules that support extended code, use the "sendExtDim" method.
#if X10_USE_PRE_SET_DIM
bool X10ex::sendDim(uint8_t house, uint8_t unit, uint8_t percent, uint8_t repetitions)
{
if(percent == 0)
{
return sendExt(house, unit, CMD_OFF, 0, 0, repetitions);
}
else
{
uint8_t brightness = percentToX10Brightness(percent * 2);
return sendExt(
house, unit, brightness >> 4 ? CMD_PRE_SET_DIM_1 : CMD_PRE_SET_DIM_0,
// Reverse nibble before sending
(((brightness * 0x0802LU & 0x22110LU) | (brightness * 0x8020LU & 0x88440LU)) * 0x10101LU >> 20) & B1111, 0,
repetitions);
}
}
#endif
// This method works with all X10 modules that support extended code. The only
// exception is the time attribute, that may result in unexpected behaviour
// when set to anything but the default value 0, on some X10 modules.
bool X10ex::sendExtDim(uint8_t house, uint8_t unit, uint8_t percent, uint8_t time, uint8_t repetitions)
{
if(percent == 0)
{
return sendExt(house, unit, CMD_OFF, 0, 0, repetitions);
}
else
{
uint8_t data = percentToX10Brightness(percent, time);
return sendExt(
house, unit, CMD_EXTENDED_CODE,
data, EXC_PRE_SET_DIM,
repetitions);
}
}
// Returns true when command was buffered successfully
bool X10ex::sendExt(uint8_t house, uint8_t unit, uint8_t command, uint8_t extData, uint8_t extCommand, uint8_t repetitions)
{
house = parseHouseCode(house);
unit--;
// Validate input
if(house > 0xF || (unit > 0xF && unit != 0xFF))
{
return 1;
}
// Add house nibble (bit 32-29)
uint32_t message = (uint32_t)HOUSE_CODE[house] << 28;
// No unit code X10 message
if(unit == 0xFF)
{
message |=
(uint32_t)command << 24 | // Add command nibble (bit 28-25)
1LU << 23 | // Set message type (bit 24) to 1 (command)
X10_MSG_CMD; // Set data type (bit 3-1)
}
// Standard X10 message
else if(command != CMD_EXTENDED_CODE && command != CMD_EXTENDED_DATA)
{
// If type is preset dim, send data; if not, repeat house code
uint8_t houseData = (command & B1110) == CMD_PRE_SET_DIM_0 ? extData : HOUSE_CODE[house];
message |=
(uint32_t)UNIT_CODE[unit] << 24 | // Add unit nibble (bit 28-25)
(uint16_t)houseData << 8 | // Add house/data nibble (bit 12-9)
(uint16_t)command << 4 | // Add command nibble (bit 8-5)
1 << 3 | // Set message type (bit 4) to 1 (command)
X10_MSG_STD; // Set data type (bit 3-1)
}
// Extended X10 message
else
{
message |=
(uint32_t)command << 24 | // Add command nibble (bit 28-25)
1LU << 23 | // Set message type (bit 24) to 1 (command)
(uint32_t)UNIT_CODE[unit] << 19 | // Add unit nibble (bit 23-20)
(uint32_t)extData << 11 | // Set extended data byte (bit 19-12)
(uint16_t)extCommand << 3 | // Set extended command byte (bit 11-4)
X10_MSG_EXT; // Set data type (bit 3-1)
}
// Current command is buffered again
if(sendBf[sendBfStart].repetitions > 0 && sendBf[sendBfStart].message == message)
{
// Just reset repetitions
sendBf[sendBfStart].repetitions = repetitions;
sendBfLastMs = millis();
return 0;
}
// If slots are available in buffer
else if((sendBfEnd + 2) % X10_BUFFER_SIZE != sendBfStart)
{
// Make sure identical message is not sent within rebuffer delay
if(sendBf[sendBfEnd].message != message || millis() > sendBfLastMs + X10_REBUFFER_DELAY || sendBfLastMs - 1 > millis())
{
sendBfEnd = (sendBfEnd + 1) % X10_BUFFER_SIZE;
// Buffer message and repetitions
sendBf[sendBfEnd].message = message;
sendBf[sendBfEnd].repetitions = repetitions;
sendBfLastMs = millis();
}
// Return success even if message was not rebuffered because of rebuffer delay
// There is really no point in buffering two identical commands in quick succession
// If commands must be repeated several times, use the repetitions attribute
return 0;
}
return 1;
}
X10state X10ex::getModuleState(uint8_t house, uint8_t unit)
{
bool isSeen = 0;
bool isKnown = 0;
bool isOn = 0;
uint8_t data = 0;
#if X10_PERSIST_MOD_DATA
// Validate input
#if X10_PERSIST_MOD_DATA == 1
uint8_t state = eepromRead(house, unit);
#else
house = parseHouseCode(house);
unit--;
uint8_t state = 0;
if(house <= 0xF && unit <= 0xF) state = moduleState[house << 4 | unit];
#endif
// Bit 1 and 2 in state byte has the state, last 6 bits is brightness
// 00 = Not seen, Not known, Not On
// 01 = Seen, Not known, Not On
// 10 = Seen, Known, Not On
// 11 = Seen, Known, On
if(state & B11000000)
{
isSeen = 1;
isKnown = state & B10000000;
isOn = state >= B11000000;
if(isKnown) data = state & B111111;
}
#endif
return (X10state) { isSeen, isKnown, isOn, data };
}
// WARNING:
// - If house is outside range A-P, state of all modules is wiped
// - If unit is outside range 1-16, state of all modules in house is wiped
void X10ex::wipeModuleState(uint8_t house, uint8_t unit)
{
#if X10_PERSIST_MOD_DATA
wipeModuleData(house, unit, 0);
#endif
}
#if X10_PERSIST_MOD_DATA == 1
X10info X10ex::getModuleInfo(uint8_t house, uint8_t unit)
{
uint8_t infoData = eepromRead(house, unit, 256);
X10info info;
info.type = infoData >> 6;
uint8_t ix = 0;
#if not defined(__AVR_ATmega8__) && not defined(__AVR_ATmega168__)
if(infoData & B100000)
{
uint16_t nameAddr = (infoData & B11111) * X10_INFO_NAME_LEN + 512;
while(ix < X10_INFO_NAME_LEN)
{
info.name[ix] = eepromRead(nameAddr + ix);
if(info.name[ix] == '\0') break;
ix++;
}
}
#endif
info.name[ix] = '\0';
return info;
}
void X10ex::setModuleType(uint8_t house, uint8_t unit, uint8_t type)
{
if(type <= B11)
{
// Make sure module is marked as seen
updateModuleState(house, unit, DATA_UNKNOWN);
// Update module type
eepromWrite(house, unit, (eepromRead(house, unit, 256) | B11000000) & (type << 6 | B111111), 256);
}
}
#if not defined(__AVR_ATmega8__) && not defined(__AVR_ATmega168__)
bool X10ex::setModuleName(uint8_t house, uint8_t unit, char name[X10_INFO_NAME_LEN], uint8_t length)
{
uint16_t nameAddr;
uint8_t infoData = eepromRead(house, unit, 256);
if(infoData & B100000)
{
nameAddr = (infoData & B11111) * X10_INFO_NAME_LEN + 512;
}
else
{
// Find empty slot in EEPROM
nameAddr = 512;
while(nameAddr < 1024)
{
if(eepromRead(nameAddr) == '\0') break;
nameAddr += X10_INFO_NAME_LEN;
}
// If we have run out of space: abort by returning error code
if(nameAddr > 1024 - X10_INFO_NAME_LEN) return 1;
// Make sure module is marked as seen
updateModuleState(house, unit, DATA_UNKNOWN);
// Update module pointer to name address
eepromWrite(
house, unit,
infoData & B11000000 | B100000 | (nameAddr / X10_INFO_NAME_LEN - 512),
256);
}
for(uint8_t ix = 0; ix < X10_INFO_NAME_LEN; ix++)
{
if(name[ix] && ix < length)
{
eepromWrite(nameAddr + ix, name[ix]);
}
else
{
eepromWrite(nameAddr + ix, '\0');
// Clear module pointer to name address if name is cleared
if(!ix) eepromWrite(house, unit, infoData & B11000000, 256);
break;
}
}
return 0;
}
#endif
// WARNING:
// - If house is outside range A-P, all module info is wiped
// - If unit is outside range 1-16, all module info in house is wiped
void X10ex::wipeModuleInfo(uint8_t house, uint8_t unit)
{
wipeModuleData(house, unit, 1);
}
#endif
uint8_t X10ex::percentToX10Brightness(uint8_t brightness, uint8_t time)
{
brightness = brightness >= 100 ? 62 : round(brightness / 100.0 * 62.0);
brightness |= time >= B11 ? B11000000 : time << 6;
return brightness;
}
uint8_t X10ex::x10BrightnessToPercent(uint8_t brightness)
{
return round(100.0 * (brightness & B111111) / 62.0);
}
//////////////////////////////
/// Public (Interrupt Methods)
//////////////////////////////
void X10ex::zeroCross()
{
zcInput = 0;
// Start IO timer
TCNT1 = 1;
TCCR1B |= _BV(CS10);
// Get bit to output from buffer
if(sendBf[sendBfStart].repetitions && (sentCount || zeroCount > X10_PRE_CMD_CYCLES - 1))
{
// Start output as soon as possible after zero crossing
if(zcOutput) fastDigitalWrite(transmitPort, transmitBitMask, HIGH);
zcOutput = getBitToSend();
}
else
{
zcOutput = 0;
}
}
void X10ex::ioTimer()
{
// Read input
if(ioState == 1)
{
ICR1 = outputLengthCycles - inputDelayCycles;
zcInput = receiveTransmits || !sendBf[sendBfStart].repetitions ? !(*portInputRegister(receivePort) & receiveBitMask) : 0;
}
// Set output low, stop timer, and check receive
else if((!zcOutput && ioState == 2) || ioState == ioStopState)
{
fastDigitalWrite(transmitPort, transmitBitMask, LOW);
// Stop IO timer
TCCR1B &= ~_BV(CS10);
// Reset timer (ready for next zero cross)
ICR1 = inputDelayCycles;
ioState = 0;
// If start sequence is found: receive message
if(receivedCount)
{
receiveMessage();
}
// Search for start sequence and keep track of silence
else
{
// If we received a one: increment bit count
if(zcInput)
{
zeroCount = 0;
receivedBits++;
}
else
{
// 3 consecutive ones is the startcode
if(receivedBits == 3 && plcReceiveCallback)
{
// We have reached zero crossing 4 after startcode: set it to start receiving message
receivedCount = 4;
}
receivedBits = 0;
zeroCount += zeroCount == 255 ? 0 : 1;
}
}
}
// Set output High
else if(ioState % 2)
{
ICR1 = outputLengthCycles;
fastDigitalWrite(transmitPort, transmitBitMask, HIGH);
}
// Set output Low
else if(ioState)
{
ICR1 = outputDelayCycles - outputLengthCycles;
fastDigitalWrite(transmitPort, transmitBitMask, LOW);
}
ioState++;
}
//////////////////////////////
/// Private
//////////////////////////////
bool X10ex::getBitToSend()
{
sentCount++;
bool output;
// Send start bits
if(sentCount - sendOffset < 5)
{
output = sentCount - sendOffset < 4;
}
// Send X10 message
else
{
bool isOdd = sentCount % 2;
// Get bit position in buffer
uint8_t bitPosition = (sentCount - (isOdd ? 3 : 4)) / 2;
// Get data type
uint8_t type = sendBf[sendBfStart].message & B111;
// Get bit to send from buffer, and xor it with odd field
// to make complement bit for every even zero cross count
output = !(sendBf[sendBfStart].message >> 32 - bitPosition & B1) ^ isOdd;
// If type is standard X10 message
if(type == X10_MSG_STD)
{
// Add cycles of silence after part one; make sure there are
// 5 zero crosses of silence before part two is transmitted
if(sentCount > 22 && sentCount <= 40)
{
output = 0;
if(sentCount == 40 && zeroCount <= 2) sentCount--;
}
// Part one sent: restart by sending new start sequence then start at bit 21 in buffer
if(sentCount == 40) sendOffset = 40;
}
// All messages end after 31 bits (the 62nd zero crossing)
// If type is standard X10 message with no unit code: end after part one (11 bits)
if(sentCount == 62 || (type == X10_MSG_CMD && sentCount == 22))
{
// If message has no unit code and command is BRIGHT or DIM: repeat without any silence
zeroCount = type == X10_MSG_CMD && (sendBf[sendBfStart].message >> 24 & B1110) == CMD_DIM ? 7 : 0;
sentCount = 0;
sendOffset = 0;
if(sendBf[sendBfStart].repetitions > 1)
{
sendBf[sendBfStart].repetitions--;
}
else
{
sendBf[sendBfStart].repetitions = 0;
sendBfStart = (sendBfStart + 1) % X10_BUFFER_SIZE;
}
}
}
return output;
}
void X10ex::receiveMessage()
{
receivedCount++;
// Get data bit (odd)
if(receivedCount % 2)
{
receivedDataBit = zcInput;
}
// If data bit complement is correct
else if(receivedDataBit != zcInput)
{
receivedBits++;
// Buffer one byte
if(receivedBits < 9) receiveBuffer += receivedDataBit << 8 - receivedBits;
// At zero crossing 22 standard message is complete: parse it
if(receivedCount == 22)
{
receiveStandardMessage();
}
// Extended command received: parse extended message
else if(rxCommand == CMD_EXTENDED_CODE || rxCommand == CMD_EXTENDED_DATA)
{
receiveExtendedMessage();
}
}
// If data bit complement is no longer correct, it means we have stopped receiving data
else
{
if(rxCommand != DATA_UNKNOWN)
{
uint8_t house = findCodeIndex(HOUSE_CODE, rxHouse) + 65;
uint8_t unit = findCodeIndex(UNIT_CODE, rxExtUnit != DATA_UNKNOWN ? rxExtUnit : rxUnit) + 1;
#if X10_PERSIST_MOD_DATA
if(unit) updateModuleState(house, unit, rxCommand);
#endif
// Trigger receive callback
plcReceiveCallback(house, unit, rxCommand, rxData, rxExtCommand, receivedBits);
}
rxCommand = DATA_UNKNOWN;
rxData = 0;
rxExtCommand = 0;
clearReceiveBuffer();
receivedCount = 0;
}
}
void X10ex::receiveStandardMessage()
{
// Clear extended message unit code
rxExtUnit = DATA_UNKNOWN;
// Address (House + Unit)
if(!receivedDataBit)
{
rxHouse = (receiveBuffer & B11110000) >> 4;
rxUnit = receiveBuffer & B1111;
}
#if X10_USE_PRE_SET_DIM
// Pre-Set Dim (LSBs + Command + MSB)
else if((receiveBuffer & B1110) == CMD_PRE_SET_DIM_0)
{
rxCommand = CMD_PRE_SET_DIM_0;
rxData =
(
// Get the four least significant bits in reverse (bit 8-5 => 1-4)
((((receiveBuffer * 0x0802LU & 0x22110LU) | (receiveBuffer * 0x8020LU & 0x88440LU)) * 0x10101LU >> 16) & B1111) +
// Add most significant bit (bit 1 => 5)
((receiveBuffer & B0001) << 4)
) * 2;
}
#endif
// Command (House + Command)
else
{
rxHouse = (receiveBuffer & B11110000) >> 4;
rxCommand = receiveBuffer & B1111;
}
clearReceiveBuffer();
}
void X10ex::receiveExtendedMessage()
{
// Unit
if(receivedCount == 30)
{
rxExtUnit = (receiveBuffer >> 4) & B1111;
clearReceiveBuffer();
}
// Data
else if(receivedCount == 46)
{
rxData = receiveBuffer;
clearReceiveBuffer();
}
// Command
else if(receivedCount == 62)
{
rxExtCommand = receiveBuffer;
clearReceiveBuffer();
}
}
#if X10_PERSIST_MOD_DATA
void X10ex::updateModuleState(uint8_t house, uint8_t unit, uint8_t command)
{
#if X10_PERSIST_MOD_DATA == 1
uint8_t state = eepromRead(house, unit);
#else
uint8_t state = moduleState[parseHouseCode(house) << 4 | (unit - 1)];
#endif
// Bit 1 and 2 in state byte has the state, last 6 bits is brightness
// 00 = Not seen, Not known, Not On
// 01 = Seen, Not known, Not On
// 10 = Seen, Known, Not On
// 11 = Seen, Known, On
uint8_t brightness = state & B111111;
// If not seen, set seen
if(!(state & B11000000)) state |= B1000000;
// Dim: estimate brightness
if(command == CMD_DIM)
{
// Module is off: set full brightness
if(state >> 6 == B1)
{
brightness = 62;
}
// Module is on: decrease until limit
else
{
brightness = brightness > 9 ? brightness - 9 : 1;
}
}
// Bright: estimate brightness
else if(command == CMD_BRIGHT)
{
// Module is off: set low brightness
if(state >> 6 == B1)
{
brightness = 11;
}
// Module is on: increase until limit
else
{
brightness = brightness <= 53 ? brightness + 9 : 62;
}
}
// Off: set state and get brightness from buffer
if(command == CMD_OFF || command == CMD_STATUS_OFF)
{
state = brightness | B10000000;
rxData = brightness;
}
// On: set state and get brightness from buffer
else if(command == CMD_DIM || command == CMD_BRIGHT || command == CMD_ON || command == CMD_STATUS_ON)
{
state = brightness | B11000000;
rxData = brightness;
}
// X10 standard or extended code message pre set dim commands
else if((command & B1110) == CMD_PRE_SET_DIM_0 || (command == CMD_EXTENDED_CODE && rxExtCommand == EXC_PRE_SET_DIM))
{
// Brightness > 0: update state and set brightness
if(rxData > 0)
{
state = rxData | B11000000;
}
// Brightness 0: set state off
else
{
state = brightness | B10000000;
}
}
#if X10_PERSIST_MOD_DATA == 1
eepromWrite(house, unit, state);
#else
moduleState[parseHouseCode(house) << 4 | (unit - 1)] = state;
#endif
}
#endif
void X10ex::wipeModuleData(uint8_t house, uint8_t unit, bool info)
{
#if X10_PERSIST_MOD_DATA
house = parseHouseCode(house);
unit--;
uint16_t ix = 0;
uint8_t endIx = 255;
if(house <= 0xF)
{
ix = house << 4;
if(unit <= 0xF)
{
ix += unit;
endIx = ix;
}
else
{
endIx = ix + 0xF;
}
}
while(ix <= endIx)
{
if(info)
{
#if X10_PERSIST_MOD_DATA == 1
#if not defined(__AVR_ATmega8__) && not defined(__AVR_ATmega168__)
uint8_t infoData = eepromRead(ix + 256);
if(infoData & B100000)
{
eepromWrite((infoData & B11111) * X10_INFO_NAME_LEN + 512, '\0');
}
#endif
eepromWrite(ix + 256, 0);
#endif
}
else
{
#if X10_PERSIST_MOD_DATA == 1
eepromWrite(ix, 0);
#else
moduleState[ix] = 0;
#endif
}
ix++;
}
#endif
}
#if X10_PERSIST_MOD_DATA == 1
uint8_t X10ex::eepromRead(uint16_t address)
{
// Return byte read from EEPROM, add 1 because of initial EEPROM value 255
return eeprom_read_byte((unsigned char *)address) + 1;
}
uint8_t X10ex::eepromRead(uint8_t house, uint8_t unit, uint16_t offset)
{
house = parseHouseCode(house);
unit--;
// If house or unit code is out of range: return 0
if(house > 0xF || unit > 0xF) return 0;
return eepromRead((house << 4 | unit) + offset);
}
uint8_t X10ex::eepromWrite(uint16_t address, uint8_t data)
{
// Subtract 1 because of initial EEPROM value 255
eeprom_write_byte((unsigned char *)address, data - 1);
}
uint8_t X10ex::eepromWrite(uint8_t house, uint8_t unit, uint8_t data, uint16_t offset)
{
house = parseHouseCode(house);
unit--;
// If house and unit code is within valid range
if(house <= 0xF && unit <= 0xF)
{
eepromWrite((house << 4 | unit) + offset, data);
}
}
#endif
void X10ex::clearReceiveBuffer()
{
receivedBits = 0;
receiveBuffer = 0;
}
uint8_t X10ex::parseHouseCode(uint8_t house)
{
return house - (house < 0xF ? 0 : house >= 0x61 ? 0x61 : 0x41);
}
int8_t X10ex::findCodeIndex(const uint8_t codeList[16], uint8_t code)
{
for(uint8_t i = 0; i <= 0xF; i++)
{
if(codeList[i] == code) return i;
}
return -1;
}
void X10ex::fastDigitalWrite(uint8_t port, uint8_t bitMask, uint8_t value)
{
if(port == NOT_A_PIN) return;
volatile uint8_t *out = portOutputRegister(port);
uint8_t sreg = SREG;
cli();
if(value == LOW)
{
*out &= ~bitMask;
}
else
{
*out |= bitMask;
}
SREG = sreg;
}
|
#include "igContext.h"
#include <iostream>
static igIdent nullId = GEN_NULL_ID;
void sysSetCliboardString(std::string str);
std::string sysGetCliboardString();
using namespace igSizing;
int gfxCharAt(int x, int y, const char* text, int style, int mouseX);
igContext::igContext()
{
hotItem = nullId;
activeItem = nullId;
keyboardItem = nullId;
dragItem = nullId;
mouseWheel = 0;
leftDown = leftLastDown = false;
charEntered = 0;
backspace = false;
textCharPos = 0;
textCharPos2 = 0;
dragPointer = 0;
shift = false;
ctrlC = false;
ctrlX = false;
ctrlV = false;
ctrlA = false;
}
bool igContext::MouseInside(int x, int y, int width, int height)
{
if(MouseClipped())
return false;
return mouseX >= x && mouseY >= y && mouseX <= x+width && mouseY <= y+height;
}
bool igContext::MouseClipped()
{
if(!currentMouseClipping.active)
return false;
if(mouseX < currentMouseClipping.x)
return true;
if(mouseY < currentMouseClipping.y)
return true;
if(mouseX > currentMouseClipping.x+currentMouseClipping.width)
return true;
if(mouseY > currentMouseClipping.y+currentMouseClipping.height)
return true;
return false;
}
void igContext::Begin()
{
canDrop = false;
dragMissing = true;
hotItem = nullId;
if(textCharPos < 0)
textCharPos = 0;
if(textCharPos2 < 0)
textCharPos2 = 0;
currentMouseClipping.active = false;
}
igDragged igContext::End()
{
if(leftDown == false)
{
activeItem = nullId;
}
charEntered = 0;
backspace = false;
if(dragMissing)
{
dragItem = nullId;
dragPointer = 0;
}
igDragged dragged;
if(dragItem != nullId && dragMoved)
{
dragged.canDrop = canDrop;
dragged.show = true;
dragged.title = dragTitle;
dragged.rect = dragRect;
}
mouseWheel = 0;
leftLastDown = leftDown;
ctrlC = false;
ctrlX = false;
ctrlV = false;
ctrlA = false;
return dragged;
}
bool igContext::LeftJustUp()
{
return leftLastDown && !leftDown;
}
igButton igContext::Button(igIdent id, int x, int y,
int width, int height, const char* title)
{
igButton button;
button.rect = igRect(x, y, width, height);
button.title = title;
if(MouseInside(x, y, width, height))
{
hotItem = id;
if(leftDown && activeItem == nullId)
activeItem = id;
button.hover = true;
}
button.clicked = leftDown == false && hotItem == id && activeItem == id;
button.down = leftDown && activeItem == id;
return button;
}
igCheckbox igContext::Checkbox(igIdent id, int x, int y, int width, int height, bool value)
{
igCheckbox checkbox;
checkbox.rect = igRect(x, y, width, height);
checkbox.value = value;
if(MouseInside(x, y, width, height))
{
hotItem = id;
if(leftDown && activeItem == nullId)
activeItem = id;
checkbox.hover = true;
}
checkbox.clicked = leftDown == false && hotItem == id && activeItem == id;
checkbox.down = leftDown && activeItem == id;
return checkbox;
}
igVScroll igContext::VScroll(igIdent id, int x, int y, int width, int height, float aspect, float& value)
{
float prevValue = value;
if(MouseInside(x, y, width, height))
{
hotItem = id;
if(leftDown && activeItem == nullId)
{
activeItem = id;
}
}
if(leftDown && activeItem == id)
{
value = (float)(mouseY - y)/height - aspect/2.0f;
if(value < 0) value = 0;
if(value > 1.0f - aspect) value = 1.0f - aspect;
}
igVScroll scrollbar;
scrollbar.changed = prevValue != value;
scrollbar.rect = igRect(x, y, width, height);
scrollbar.aspect = aspect;
scrollbar.value = value;
return scrollbar;
}
igTextbox igContext::TextBox(igIdent id, int x, int y, int width, int height,
std::string& value, const std::string& charset)
{
igTextbox textbox;
std::string prevValue = value;
if(MouseInside(x, y, width, height))
{
hotItem = id;
textbox.hover = true;
if(leftDown && activeItem == nullId)
{
activeItem = id;
keyboardItem = id;
textCharPos2 = textCharPos = gfxCharAt(x+width/2, y + height/2, value.c_str(), 0, mouseX);
}
} else if(leftDown && !leftLastDown)
{
if(keyboardItem == id)
keyboardItem = nullId;
if(activeItem == id)
activeItem = nullId;
}
if(leftDown && activeItem == id)
{
textCharPos2 = gfxCharAt(x+width/2, y + height/2, value.c_str(), 0, mouseX);
}
if(keyboardItem == id)
{
if(textCharPos > (int)value.size())
textCharPos = value.size();
if(textCharPos2 > (int)value.size())
textCharPos2 = value.size();
if(charEntered)
{
for(int i=0; i<(int)charset.size(); i++)
if(charset[i] == charEntered)
{
int pipePos1 = textCharPos;
int pipePos2 = textCharPos2;
if(pipePos1 > pipePos2)
std::swap(pipePos1, pipePos2);
value.erase(pipePos1, pipePos2-pipePos1);
value.insert(pipePos1, 1, (char)charEntered);
pipePos1++;
textCharPos2 = textCharPos = pipePos1;
break;
}
}
if(charEntered == 8 && (textCharPos > 0 || textCharPos!=textCharPos2)) // backspace
{
if(textCharPos != textCharPos2)
{
int pipePos1 = textCharPos;
int pipePos2 = textCharPos2;
if(pipePos1 > pipePos2)
std::swap(pipePos1, pipePos2);
value.erase(pipePos1, pipePos2-pipePos1);
textCharPos2 = textCharPos = pipePos1;
} else
{
textCharPos--;
textCharPos2 = textCharPos;
value.erase(textCharPos, 1);
}
}
if(charEntered == 127) // delete
{
if(textCharPos != textCharPos2)
{
int pipePos1 = textCharPos;
int pipePos2 = textCharPos2;
if(pipePos1 > pipePos2)
std::swap(pipePos1, pipePos2);
value.erase(pipePos1, pipePos2-pipePos1);
textCharPos2 = textCharPos = pipePos1;
} else
value.erase(textCharPos, 1);
}
if(ctrlC)
{
int textPos1 = textCharPos < textCharPos2 ? textCharPos : textCharPos2;
int textPos2 = textCharPos > textCharPos2 ? textCharPos : textCharPos2;
if(textPos1 != textPos2)
sysSetCliboardString(value.substr(textPos1, textPos2-textPos1));
else
sysSetCliboardString(value);
}
if(ctrlX)
{
int textPos1 = textCharPos < textCharPos2 ? textCharPos : textCharPos2;
int textPos2 = textCharPos > textCharPos2 ? textCharPos : textCharPos2;
if(textPos1 != textPos2)
{
sysSetCliboardString(value.substr(textPos1, textPos2-textPos1));
value.erase(textPos1, textPos2-textPos1);
textCharPos2 = textCharPos = textPos1;
}
}
if(ctrlV)
{
int textPos1 = textCharPos < textCharPos2 ? textCharPos : textCharPos2;
int textPos2 = textCharPos > textCharPos2 ? textCharPos : textCharPos2;
if(textPos1 != textPos2)
{
value.erase(textPos1, textPos2-textPos1);
textCharPos2 = textCharPos = textPos1;
}
std::string clipboardText = sysGetCliboardString();
std::string allowedChars;
if(clipboardText.empty() == false) allowedChars.reserve(clipboardText.size());
for(int i=0; i<(int)clipboardText.size(); i++)
{
for(int j=0; j<(int)charset.size(); j++)
if(charset[j] == clipboardText[i])
allowedChars += clipboardText[i];
}
value = value.substr(0, textPos1) + allowedChars + value.substr(textPos1);
textCharPos2 = textCharPos = textPos1 + allowedChars.size();
}
if(ctrlA)
{
textCharPos = 0;
textCharPos2 = value.size();
}
}
if(activeItem == id && leftDown) textbox.down = true;
textbox.rect = igRect(x, y, width, height);
textbox.pipePos1 = textCharPos;
textbox.pipePos2 = textCharPos2;
textbox.textFocus = keyboardItem == id;
textbox.value = value;
return textbox;
}
igDrag<igDraggable> igContext::Drag(igIdent id, int x, int y, int width, int height,
const char* title, igDraggable* userData, igAcceptDrop fun)
{
igDraggable* result = 0;
igDrag<igDraggable> drag;
if(dragPointer && userData==dragPointer)
dragMissing = false;
if(dragItem == id)
{
dragRect.x = mouseX - dragX;
dragRect.y = mouseY - dragY;
drag.down = true;
if(abs(x - dragRect.x) > 1 || abs(y - dragRect.y) > 1)
dragMoved = true;
dragTitle = title;
if(leftDown == false)
{
dragItem = nullId;
}
} else
{
if(MouseInside(x, y, width, height))
{
drag.hover = true;
hotItem = id;
if(leftDown && dragItem == nullId && activeItem == nullId)
{
drag.down = true;
activeItem = dragItem = id;
dragX = mouseX - x;
dragY = mouseY - y;
dragRect.x = x;
dragRect.y = y;
dragRect.w = width;
dragRect.h = height;
dragPointer = userData;
dragMoved = false;
dragMissing = false;
}
if(LeftJustUp() && dragPointer!=0)
{
result = dragPointer;
if(fun(result) == false) result = 0;
dragPointer = 0;
}
}
}
drag.drop = result;
drag.rect = igRect(x, y, width, height);
drag.title = title;
return drag;
}
igMove igContext::Move(igIdent id, int& x, int& y, int width, int height, const char* title)
{
int prevX = x, prevY = y;
bool result = false;
igMove move;
if(dragItem == id)
{
dragMissing = false;
x = mouseX - dragX;
y = mouseY - dragY;
if(leftDown == false)
{
dragItem = nullId;
} else
{
move.down = true;
}
result = true;
} else
{
if(MouseInside(x, y, width, height))
{
move.hover = true;
hotItem = id;
if(leftDown && dragItem == nullId && activeItem == nullId)
{
activeItem = dragItem = id;
dragX = mouseX - x;
dragY = mouseY - y;
dragMoved = false;
result = true;
dragMissing = false;
move.down = true;
}
}
}
move.rect = igRect(x, y, width, height);
move.moved = prevX != x || prevY != y;
move.prevX = prevX;
move.prevY = prevY;
return move;
}
// this is really stupid function :)
igLabel igContext::Label(int x, int y, int width, int height, const std::string& text, igTextAlign halign)
{
igLabel label;
label.rect = igRect(x, y, width, height);
label.align = halign;
label.value = text;
return label;
}
igSlider igContext::HSlider( igIdent id, int x, int y, int width, int height, float& value )
{
float prevValue = value;
igSlider slider;
if(MouseInside(x, y, width, height))
{
slider.hover = true;
hotItem = id;
if(leftDown && activeItem == nullId)
{
activeItem = id;
}
}
if(leftDown && activeItem == id)
{
slider.down = true;
value = (float)(mouseX - x)/width;
if(value < 0) value = 0;
if(value > 1.0f) value = 1.0f;
}
slider.value = value;
slider.rect = igRect(x, y, width, height);
return slider;
}
igAreaBG igContext::BeginScrollArea( igIdent id, int x, int y, int width, int height, int& offset, bool scrollbar, igColor color )
{
currentMouseClipping.active = true;
currentMouseClipping.x = x; currentMouseClipping.y = y;
currentMouseClipping.width = width; currentMouseClipping.height = height;
scrollArea.startX = (int)x; scrollArea.startY = (int)y;
scrollArea.currX = scrollArea.startX + SCROLLAREA_MARGIN_X + scrollArea.indent;
scrollArea.width = (int)width; scrollArea.height = (int)height;
scrollArea.id = id;
scrollArea.offset = &offset;
scrollArea.indent = 0;
scrollArea.currMaxHeight = 0;
scrollArea.scrollbar = scrollbar ? 1 : 0;
scrollArea.currY = y - *scrollArea.offset;
igAreaBG scrollArea;
scrollArea.rect = igRect(x, y, width, height);
return scrollArea;
}
igAreaFG igContext::EndScrollArea()
{
currentMouseClipping.active = false;
float totalSize = (float)(scrollArea.currY - scrollArea.startY + *scrollArea.offset);
float aspect = scrollArea.height/totalSize;
float curr = *scrollArea.offset/totalSize;
igAreaFG areaFG;
if(scrollArea.scrollbar != 0)
{
int posX = scrollArea.startX + scrollArea.width - SCROLLBAR_WIDTH;
float value = *scrollArea.offset/totalSize;
float newAspect = aspect;
if(aspect > 1) newAspect = 1;
areaFG.scroll = VScroll(scrollArea.id, posX, scrollArea.startY, SCROLLBAR_WIDTH, scrollArea.height, newAspect, value);
*scrollArea.offset = (int)(value * totalSize+0.5f);
if(MouseInside(scrollArea.startX, scrollArea.startY, scrollArea.width, scrollArea.height))
*scrollArea.offset -= mouseWheel*30;
if(aspect >= 1.0f)
{
*scrollArea.offset = 0;
}
if(*scrollArea.offset > totalSize - scrollArea.height)
*scrollArea.offset = (int)(totalSize - scrollArea.height);
if(*scrollArea.offset < 0) *scrollArea.offset = 0;
}
return areaFG;
}
void igContext::AdjustNewScrollAreaHeight( int height )
{
if(scrollArea.currMaxHeight < height)
scrollArea.currMaxHeight = height;
}
void igContext::NewLine()
{
scrollArea.currY += scrollArea.currMaxHeight + SCROLLAREA_MARGIN_Y;
scrollArea.currX = scrollArea.startX + SCROLLAREA_MARGIN_X + scrollArea.indent;
scrollArea.currMaxHeight = 0;
}
igButton igContext::Button( igIdent id, const char* title, int width )
{
const int x = scrollArea.currX;
const int y = scrollArea.currY;
bool maxSize = width == 0;
if(maxSize)
{
int currXPos = scrollArea.currX-scrollArea.startX;
width = scrollArea.width - currXPos - SCROLLAREA_MARGIN_X - SCROLLBAR_WIDTH*scrollArea.scrollbar;
}
igButton button = Button(id, x, y, width, BUTTON_HEIGHT, title);
AdjustNewScrollAreaHeight(BUTTON_HEIGHT);
if(maxSize)
NewLine();
else
scrollArea.currX += width + SCROLLAREA_MARGIN_X;
return button;
}
igCheckbox igContext::Checkbox( igIdent id, bool value, const char* title)
{
const int x = scrollArea.currX;
const int y = scrollArea.currY+CHECKBOX_HEIGHT/2-CHECKBOX_SIZE/2;
igCheckbox result = Checkbox(id, x, y, CHECKBOX_SIZE, CHECKBOX_SIZE, value);
scrollArea.currX += CHECKBOX_SIZE + SCROLLAREA_MARGIN_X;
return result;
}
igTextbox igContext::TextBox( igIdent id, std::string& value, int width )
{
const int x = scrollArea.currX;
const int y = scrollArea.currY;
bool maxSize = width == 0;
if(maxSize)
{
int currXPos = scrollArea.currX-scrollArea.startX;
width = scrollArea.width - currXPos - SCROLLAREA_MARGIN_X - SCROLLBAR_WIDTH*scrollArea.scrollbar;
}
igTextbox& result = TextBox(id, x, y, width, TEXTBOX_HEIGHT, value);
AdjustNewScrollAreaHeight(TEXTBOX_HEIGHT);
if(maxSize)
NewLine();
else
scrollArea.currX += width + SCROLLAREA_MARGIN_X;
return result;
}
void igContext::Space( int width )
{
if(width == 0)
NewLine();
else
scrollArea.currX += width + SCROLLAREA_MARGIN_X;
}
igLabel igContext::Label( const std::string& text, igTextAlign halign, int width)
{
const int x = scrollArea.currX;
const int y = scrollArea.currY+SCROLLAREA_MARGIN_Y;
bool maxSize = width == 0;
if(maxSize)
{
int currXPos = scrollArea.currX-scrollArea.startX;
width = scrollArea.width - currXPos - SCROLLAREA_MARGIN_X - SCROLLBAR_WIDTH*scrollArea.scrollbar;
}
igLabel& label = Label(x, y, width, LABEL_HEIGHT, text, halign);
AdjustNewScrollAreaHeight(LABEL_HEIGHT);
if(maxSize)
NewLine();
else
scrollArea.currX += width + SCROLLAREA_MARGIN_X;
return label;
}
igSlider igContext::Slider( igIdent id, float& value, float minVal, float maxVal, int width/*=0*/ )
{
const int x = scrollArea.currX + SLIDER_THUMB_SIZE/2;
const int y = scrollArea.currY+SCROLLAREA_MARGIN_Y;
bool maxSize = width == 0;
if(maxSize)
{
int currXPos = scrollArea.currX-scrollArea.startX;
width = scrollArea.width - currXPos - SCROLLAREA_MARGIN_X - SCROLLBAR_WIDTH*scrollArea.scrollbar - SLIDER_THUMB_SIZE;
}
igSlider& result = HSlider(id, x, y, width, 20, value);
AdjustNewScrollAreaHeight(SLIDER_HEIGHT);
if(maxSize)
NewLine();
else
scrollArea.currX += width + SLIDER_THUMB_SIZE + SCROLLAREA_MARGIN_X;
return result;
}
const int indentSize = 20;
void igContext::Indent()
{
scrollArea.indent += indentSize;
scrollArea.currX = scrollArea.startX + SCROLLAREA_MARGIN_X + scrollArea.indent;
}
void igContext::Unindent()
{
scrollArea.indent -= indentSize;
scrollArea.currX = scrollArea.startX + SCROLLAREA_MARGIN_X + scrollArea.indent;
}
igSeparator igContext::Separator()
{
igSeparator separator;
int x = scrollArea.startX;
int y = scrollArea.currY + SCROLLAREA_MARGIN_Y + SEPARATOR_HEIGHT/2 - SEPARATOR_SIZE/2;
int width = scrollArea.width - SCROLLBAR_WIDTH*scrollArea.scrollbar;
int height = SEPARATOR_SIZE;
separator.rect = igRect(x, y, width, height);
AdjustNewScrollAreaHeight(SEPARATOR_HEIGHT);
NewLine();
return separator;
}
void igContext::ArrowLeftDown()
{
if(shift)
{
textCharPos--;
} else if(textCharPos == textCharPos2)
{
textCharPos--;
textCharPos2 = textCharPos;
} else
{
textCharPos2 = textCharPos;
}
}
void igContext::ArrowRightDown()
{
if(shift)
{
textCharPos++;
} else if(textCharPos == textCharPos2)
{
textCharPos++;
textCharPos2 = textCharPos;
} else
{
textCharPos2 = textCharPos;
}
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 2009-2010 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
*/
/**
* @file GadgetSignatureVerifier.cpp
*
* Gadget signature verifier implementation.
*
* @author Alexei Khlebnikov <alexeik@opera.com>
*
*/
#include "core/pch.h"
#ifdef SIGNED_GADGET_SUPPORT
#include "modules/libcrypto/include/GadgetSignatureVerifier.h"
#include "modules/libcrypto/include/GadgetSignatureStorage.h"
// Limitations as mentioned in the internal spec.
// Maximum 100 distributor signatures.
// Rationale: hinder DOS by eating all processing power
// and all time of user's life.
#define MAX_DISTRIBUTOR_SIGNATURE_COUNT 100
// Maximum number of digits in distributor signature number is 9.
// I.e. the maximum number is 999 999 999 and the last possible
// distributor signature filename is "signature999999999.xml".
// Enough and fits into 32-bit int.
// Rationale: prevent parsing buffer overflows, integer overflows.
#define MAX_SIGNATURE_DIGIT_COUNT 9
// Maximum size of signature file is 640K. Should be enough for everyone.
// Rationale: hinder DOS by eating all memory.
#define MAX_SIGNATURE_FILE_SIZE (640 * 1024 * 1024)
GadgetSignatureVerifier::GadgetSignatureVerifier()
: m_ca_storage(NULL)
, m_gadget_signature_storage(NULL)
, m_author_signature_filename(NULL)
, m_current_signature_index(0)
{}
GadgetSignatureVerifier::~GadgetSignatureVerifier()
{
// m_author_signature_filename doesn't own the memory.
// m_gadget_signature_storage doesn't own the memory.
// m_ca_storage doesn't own the memory.
}
void GadgetSignatureVerifier::SetGadgetFilenameL(const OpString& zipped_gadget_filename)
{
m_gadget_filename.SetL(zipped_gadget_filename);
}
void GadgetSignatureVerifier::SetCAStorage(const CryptoCertificateStorage* ca_storage)
{
m_ca_storage = ca_storage;
}
void GadgetSignatureVerifier::SetGadgetSignatureStorageContainer(GadgetSignatureStorage* signature_storage)
{
m_gadget_signature_storage = signature_storage;
}
void GadgetSignatureVerifier::ProcessL()
{
if (m_gadget_filename.IsEmpty() || !m_ca_storage || !m_gadget_signature_storage)
LEAVE(OpStatus::ERR_OUT_OF_RANGE);
m_gadget_signature_storage->Clear();
VerifyOffline();
#ifdef CRYPTO_OCSP_SUPPORT
CryptoXmlSignature::VerifyError common_verify_error =
m_gadget_signature_storage->GetCommonVerifyError();
if (common_verify_error != CryptoXmlSignature::OK_CHECKED_LOCALLY)
{
// Offline verification already failed. Finish now.
NotifyAboutFinishedVerification();
}
else
{
// Offline verification succeeded. Check OCSP.
VerifyOnline();
}
#else
NotifyAboutFinishedVerification();
#endif
}
MH_PARAM_1 GadgetSignatureVerifier::Id() const
{
return reinterpret_cast <MH_PARAM_1> (this);
}
#ifdef CRYPTO_OCSP_SUPPORT
void GadgetSignatureVerifier::HandleCallback(OpMessage msg, MH_PARAM_1 par1, MH_PARAM_2 par2)
{
switch (msg)
{
case MSG_GADGET_SIGNATURE_PROCESS_OCSP:
LaunchOCSPProcessing();
break;
case MSG_OCSP_CERTIFICATE_CHAIN_VERIFICATION_FINISHED:
ProcessOCSPVerificationResult();
break;
}
}
#endif
void GadgetSignatureVerifier::VerifyOffline()
{
TRAPD(status,
CheckWidgetFileExistsL();
CheckWidgetIsZipFileL();
LookForSignaturesL();
ProcessAllSignaturesOfflineL();
);
if (m_gadget_file.IsOpen())
m_gadget_file.Close();
}
void GadgetSignatureVerifier::CheckWidgetFileExistsL()
{
ANCHORD(OpFile, file);
LEAVE_IF_ERROR(file.Construct(m_gadget_filename, OPFILE_ABSOLUTE_FOLDER));
BOOL found = FALSE;
LEAVE_IF_ERROR(file.Exists(found));
if (found == FALSE)
{
OP_ASSERT(m_gadget_signature_storage);
m_gadget_signature_storage->SetCommonVerifyError(CryptoXmlSignature::WIDGET_ERROR_ZIP_FILE_NOT_FOUND);
LEAVE(OpStatus::ERR);
}
}
void GadgetSignatureVerifier::CheckWidgetIsZipFileL()
{
// Doing it using OpZip::Open() instead of OpZip::IsZipFile()
// because the first variant contains the second plus additional checks.
OP_STATUS status = m_gadget_file.Open(m_gadget_filename, /* write_perm = */ FALSE);
if (OpStatus::IsError(status))
{
OP_ASSERT(m_gadget_signature_storage);
m_gadget_signature_storage->SetCommonVerifyError(CryptoXmlSignature::WIDGET_ERROR_NOT_A_ZIPFILE);
LEAVE(status);
}
}
void GadgetSignatureVerifier::LookForSignaturesL()
{
OP_ASSERT(m_gadget_file.IsOpen());
m_number2filename.RemoveAll();
m_distributor_signature_list.Clear();
m_author_signature_filename = NULL;
m_file_list.DeleteAll();
LEAVE_IF_ERROR(m_gadget_file.GetFileNameList(m_file_list));
const unsigned int file_count = m_file_list.GetCount();
for (unsigned int file_idx = 0; file_idx < file_count; file_idx++)
{
// Get pathname of a zip file entry (file or directory).
const OpString* entry = m_file_list.Get(file_idx);
OP_ASSERT(entry);
// Skip directories.
const OpStringC& pathname = *entry;
const int len = pathname.Length();
OP_ASSERT(len > 0);
// Condition to check if it's not a directory taken from OpZipFolderLister::IsFolder().
if (pathname[len - 1] == (uni_char)PATHSEPCHAR)
continue;
// Check if it is an author signature.
if (IsAuthorSignature(pathname))
{
m_author_signature_filename = entry;
continue;
}
// Check if it is a distributor signature.
unsigned int distributor_signature_number = 0;
if (IsDistributorSignature(pathname, &distributor_signature_number))
{
OP_ASSERT(distributor_signature_number != 0);
AddDistributorSignatureFilenameL(pathname, distributor_signature_number);
continue;
}
}
}
BOOL GadgetSignatureVerifier::IsAuthorSignature(const OpStringC& pathname)
{
return (pathname == UNI_L("author-signature.xml"));
}
BOOL GadgetSignatureVerifier::IsDistributorSignature(const OpStringC& pathname, unsigned int* distributor_signature_number)
{
// Check if it is a distributor signature.
// Prefix.
const uni_char* prefix = UNI_L("signature");
const unsigned int prefix_len = uni_strlen(prefix);
// Suffix.
const uni_char* suffix = UNI_L(".xml");
const unsigned int suffix_len = uni_strlen(suffix);
// Possible string lengths.
const unsigned int min_len = prefix_len + 1 + suffix_len;
const unsigned int max_len = prefix_len + MAX_SIGNATURE_DIGIT_COUNT + suffix_len;
const unsigned int len = pathname.Length();
// Check string length.
if (len < min_len || len > max_len)
// Wrong filename length. Not a signature.
return FALSE;
// Check prefix.
if (pathname.Compare(prefix, prefix_len))
return FALSE;
// Check suffix.
const unsigned int real_suffix_pos = len - suffix_len;
const uni_char* real_suffix = pathname.CStr() + real_suffix_pos;
if (uni_strcmp(real_suffix, suffix))
return FALSE;
// Check digits.
const unsigned int expected_digit_count = real_suffix_pos - prefix_len;
OP_ASSERT(expected_digit_count >= 1 && expected_digit_count <= MAX_SIGNATURE_DIGIT_COUNT);
const uni_char* expected_digits = pathname.CStr() + prefix_len;
const unsigned int real_digit_count = uni_strspn(expected_digits, UNI_L("0123456789"));
if (real_digit_count != expected_digit_count || expected_digits[0] == (uni_char)'0')
return FALSE;
// Calculate distributor_signature_number.
if (distributor_signature_number)
{
// Copy digits because we need a null-terminated string.
uni_char digits[MAX_SIGNATURE_DIGIT_COUNT + 1]; /* ARRAY OK 2010-10-26 alexeik */
uni_strncpy(digits, expected_digits, expected_digit_count);
digits[expected_digit_count] = (uni_char)'\0';
OP_ASSERT(uni_strlen(digits) == expected_digit_count);
// Using atoi(), because we are sure that expected_digits
// consists entirely of digits, thus the conversion should not fail.
*distributor_signature_number = uni_atoi(digits);
}
return TRUE;
}
void GadgetSignatureVerifier::AddDistributorSignatureFilenameL(const OpStringC& pathname, unsigned int number)
{
// OpINT32Vector stores signed integers. OpUINT32Vector does not exist. :(
// Let's convert our argument now, check the value and avoid compiler warnings.
INT32 signed_number = static_cast <INT32> (number);
OP_ASSERT(sizeof(INT32) == sizeof(unsigned int));
OP_ASSERT(signed_number >= 0);
// Check if we reached MAX_DISTRIBUTOR_SIGNATURE_COUNT limit.
const unsigned int distributor_signature_count = m_distributor_signature_list.GetCount();
if (distributor_signature_count >= MAX_DISTRIBUTOR_SIGNATURE_COUNT)
{
// Ignore extra signatures.
return;
}
// W3C spec, 9.1.3: sort the list of signatures by the file name
// in ascending numerical order.
// For example, signature1.xml followed by signature2.xml
// followed by signature3.xml and so on.
// As another example, signature9.xml followed by signature44.xml
// followed by signature122134.xml and so on.
unsigned int insert_idx = m_distributor_signature_list.Search(signed_number);
OP_ASSERT(insert_idx <= distributor_signature_count);
// Insert new signature number only if it's not a duplicate.
// Duplicates might happen if we have a bogus zip file with
// duplicate filenames.
if (insert_idx == distributor_signature_count ||
m_distributor_signature_list.Get(insert_idx) != signed_number)
{
OP_STATUS status = m_distributor_signature_list.Insert(insert_idx, signed_number);
LEAVE_IF_ERROR(status);
status = m_number2filename.Add(signed_number, &pathname);
if (OpStatus::IsError(status))
{
m_distributor_signature_list.Remove(insert_idx);
LEAVE(status);
}
}
OP_ASSERT(m_distributor_signature_list.GetCount() == (UINT32)m_number2filename.GetCount());
OP_ASSERT(m_number2filename.GetCount() > 0);
}
void GadgetSignatureVerifier::ProcessAllSignaturesOfflineL()
{
const unsigned int distributor_signature_count = m_distributor_signature_list.GetCount();
if (!m_author_signature_filename && distributor_signature_count == 0)
{
OP_ASSERT(m_gadget_signature_storage);
m_gadget_signature_storage->SetCommonVerifyError(CryptoXmlSignature::SIGNATURE_FILE_MISSING);
LEAVE(OpStatus::ERR);
}
// W3C spec, 9.1.6: Validate the signature files in the signatures list in
// descending numerical order, with distributor signatures first (if any).
// For example, validate signature3.xml, then signature2.xml,
// then signature1.xml and lastly author-signature.xml.
// As another example, validate signature122134.xml, then signature44.xml,
// and then signature9.xml, and lastly author-signature.xml.
for (m_current_signature_index = 0; m_current_signature_index < distributor_signature_count; m_current_signature_index++)
{
unsigned int distributor_signature_idx =
distributor_signature_count - 1 - m_current_signature_index;
// Resolve signature filename.
unsigned int signature_number = m_distributor_signature_list.Get(distributor_signature_idx);
const OpStringC* signature_filename = NULL;
LEAVE_IF_ERROR( m_number2filename.GetData(signature_number, &signature_filename) );
OP_ASSERT(signature_filename);
ProcessSignatureOfflineL(*signature_filename);
}
if (m_author_signature_filename)
ProcessSignatureOfflineL(*m_author_signature_filename);
}
void GadgetSignatureVerifier::ProcessSignatureOfflineL(const OpStringC& signature_filename)
{
OP_ASSERT(m_gadget_signature_storage);
CryptoXmlSignature::VerifyError verify_error = CryptoXmlSignature::SIGNATURE_FILE_XML_GENERIC_ERROR;
ANCHORD(OpAutoPtr <CryptoCertificateChain>, signer_certificate_chain);
TRAPD(status,
VerifySignatureOfflineL(signature_filename, verify_error, signer_certificate_chain)
);
AddSignatureToStorageL(signature_filename, verify_error, signer_certificate_chain);
// Applying policy "any valid signature is required."
// If it's the first signature - set its error code as common error code.
if (m_current_signature_index == 0)
{
m_gadget_signature_storage->SetCommonVerifyError(verify_error);
// The best signature index is already set to 0, because we have
// cleared m_gadget_signature_storage in ProcessL().
OP_ASSERT(m_gadget_signature_storage->GetBestSignature() ==
m_gadget_signature_storage->GetSignatureByFlatIndex(m_current_signature_index));
// No need to update best signature index.
}
else
{
CryptoXmlSignature::VerifyError current_common_verify_error =
m_gadget_signature_storage->GetCommonVerifyError();
// If it's the first successfully verified signature - set error code to success.
if (current_common_verify_error != CryptoXmlSignature::OK_CHECKED_LOCALLY &&
verify_error == CryptoXmlSignature::OK_CHECKED_LOCALLY)
{
m_gadget_signature_storage->SetCommonVerifyError(verify_error);
m_gadget_signature_storage->SetBestSignatureIndex(m_current_signature_index);
}
// Otherwise maintain the current error code.
}
// If we reached this point - best signature exists.
OP_ASSERT(m_gadget_signature_storage->GetBestSignature());
// Common error matches the best signature error.
OP_ASSERT(m_gadget_signature_storage->GetCommonVerifyError() ==
m_gadget_signature_storage->GetBestSignature()->GetVerifyError());
}
void GadgetSignatureVerifier::VerifySignatureOfflineL(
const OpStringC& signature_filename,
CryptoXmlSignature::VerifyError& verify_error,
OpAutoPtr <CryptoCertificateChain>& signer_certificate_chain)
{
OP_ASSERT(m_gadget_file.IsOpen());
// Check signature file size.
{
ANCHORD(OpString, signature_filename_tmp);
signature_filename_tmp.SetL(signature_filename);
const int zip_entry_idx = m_gadget_file.GetFileIndex(
&signature_filename_tmp, /* unused argument */ NULL);
if (zip_entry_idx < 0)
LEAVE(OpStatus::ERR_FILE_NOT_FOUND);
OpZip::file_attributes zip_entry_attr;
m_gadget_file.GetFileAttributes(zip_entry_idx, &zip_entry_attr);
if (zip_entry_attr.length > MAX_SIGNATURE_FILE_SIZE)
LEAVE(OpStatus::ERR);
}
ANCHORD(OpString, signature_full_path);
signature_full_path.SetL(m_gadget_filename);
signature_full_path.AppendL(UNI_L(PATHSEP));
signature_full_path.AppendL(signature_filename);
// Containers for parsing results.
OpAutoStringHashTable <CryptoXmlSignature::SignedReference> reference_objects(/* case_sensitive = */ TRUE);
ANCHOR(OpAutoStringHashTable <CryptoXmlSignature::SignedReference>, reference_objects);
ANCHORD(OpAutoVector <TempBuffer>, X509_certificates);
ANCHORD(ByteBuffer, signed_info_element_signature);
CryptoCipherAlgorithm signature_cipher_type;
ANCHORD(CryptoHashAlgorithm, signature_hash_type);
ANCHORD(ByteBuffer, canonicalized_signed_info);
ANCHORD(OpAutoPtr <CryptoHash>, canonicalized_signed_info_hash);
ANCHORD(OpString, canonicalization_method);
ANCHORD(OpString, signature_profile);
ANCHORD(OpString, signature_role);
ANCHORD(OpString, signature_identifier);
// Parse XML.
OP_STATUS status = CryptoXmlSignature::ParseSignaturXml(
signature_full_path.CStr(),
FALSE,
verify_error,
reference_objects,
X509_certificates,
signed_info_element_signature,
signature_cipher_type,
signature_hash_type,
canonicalized_signed_info,
canonicalized_signed_info_hash,
canonicalization_method,
signature_profile,
signature_role,
signature_identifier);
LEAVE_IF_ERROR(status);
// Check signature properties.
CheckSignaturePropertiesL(
signature_filename,
verify_error,
signature_profile,
signature_role,
signature_identifier);
// Check the signing of <SignedInfo> element, create cert chain.
CryptoCertificateChain* certificate_chain = NULL;
status = CryptoXmlSignature::CreateX509CertificateFromBinary(
certificate_chain,
m_ca_storage,
verify_error,
X509_certificates);
LEAVE_IF_ERROR(status);
// Write certificate_chain into output parameter signer_certificate_chain.
signer_certificate_chain = certificate_chain;
// certificate_chain memory is now owned by signer_certificate_chain.
// Check that all files are signed.
CheckAllFilesSignedL(signature_filename, verify_error, reference_objects);
// Check the signature.
status = CryptoXmlSignature::CheckHashSignature(
signed_info_element_signature,
signature_hash_type,
certificate_chain,
canonicalized_signed_info_hash.get(),
verify_error);
LEAVE_IF_ERROR(status);
// Check that the file-digests are correct.
status = CryptoXmlSignature::CheckFileDigests(
m_gadget_filename.CStr(),
verify_error,
reference_objects);
LEAVE_IF_ERROR(status);
verify_error = CryptoXmlSignature::OK_CHECKED_LOCALLY;
}
void GadgetSignatureVerifier::CheckSignaturePropertiesL(
const OpStringC& signature_filename,
CryptoXmlSignature::VerifyError& verify_error,
const OpStringC& signature_profile,
const OpStringC& signature_role,
const OpStringC& signature_identifier)
{
do
{
if (signature_profile != UNI_L("http://www.w3.org/ns/widgets-digsig#profile"))
break;
if (IsAuthorSignature(signature_filename) &&
signature_role != UNI_L("http://www.w3.org/ns/widgets-digsig#role-author"))
break;
if (IsDistributorSignature(signature_filename) &&
signature_role != UNI_L("http://www.w3.org/ns/widgets-digsig#role-distributor"))
break;
if (signature_identifier.IsEmpty())
break;
return;
} while (0);
verify_error = CryptoXmlSignature::SIGNATURE_VERIFYING_WRONG_PROPERTIES;
LEAVE(OpStatus::ERR);
}
void GadgetSignatureVerifier::CheckAllFilesSignedL(
const OpStringC& signature_filename,
CryptoXmlSignature::VerifyError& verify_error,
const OpStringHashTable <CryptoXmlSignature::SignedReference>& reference_objects)
{
const unsigned int file_count = m_file_list.GetCount();
for (unsigned int file_idx = 0; file_idx < file_count; file_idx++)
{
// Get pathname of a zip file entry (file or directory).
const OpString* entry = m_file_list.Get(file_idx);
OP_ASSERT(entry);
// Skip directories.
const OpStringC& pathname = *entry;
const int len = pathname.Length();
OP_ASSERT(len > 0);
// Condition to check if it's not a directory taken from OpZipFolderLister::IsFolder().
if (pathname[len - 1] == (uni_char)PATHSEPCHAR)
continue;
// Distributor signatures are not signed. Skip them.
if (IsDistributorSignature(pathname))
continue;
// Author signature is signed by distributor signatures,
// but not by the author signature itself.
if (IsAuthorSignature(pathname) && IsAuthorSignature(signature_filename))
continue;
// Check if pathname is in the signed objects list.
if ( !reference_objects.Contains(pathname.CStr()) )
{
OP_ASSERT(m_gadget_signature_storage);
verify_error = CryptoXmlSignature::WIDGET_SIGNATURE_VERIFYING_FAILED_ALL_FILES_NOT_SIGNED;
LEAVE(OpStatus::ERR);
}
}
}
void GadgetSignatureVerifier::AddSignatureToStorageL(
const OpStringC& signature_filename,
CryptoXmlSignature::VerifyError& verify_error,
OpAutoPtr <CryptoCertificateChain>& signer_certificate_chain)
{
// Create GadgetSignature.
GadgetSignature* gadget_signature = OP_NEW_L(GadgetSignature, ());
OP_ASSERT(gadget_signature);
ANCHOR_PTR(GadgetSignature, gadget_signature);
// Fill GadgetSignature.
gadget_signature->SetSignatureFilenameL(signature_filename);
gadget_signature->SetVerifyError(verify_error);
gadget_signature->SetCertificateChain(signer_certificate_chain.get());
// Certificate chain memory is now owned by gadget_signature.
signer_certificate_chain.release();
// Add GadgetSignature to GadgetSignatureStorage.
// Decide on role.
OP_ASSERT(IsAuthorSignature(signature_filename) ^ IsDistributorSignature(signature_filename));
if (IsAuthorSignature(signature_filename))
m_gadget_signature_storage->AddAuthorSignatureL(gadget_signature);
else
m_gadget_signature_storage->AddDistributorSignatureL(gadget_signature);
// gadget_signature is now owned by m_gadget_signature_storage.
ANCHOR_PTR_RELEASE(gadget_signature);
}
#ifdef CRYPTO_OCSP_SUPPORT
void GadgetSignatureVerifier::VerifyOnline()
{
// Initialize common error with the worst error code, then "upgrade"
// the error code when more information is available.
OP_ASSERT(m_gadget_signature_storage);
m_gadget_signature_storage->SetCommonVerifyError(
CryptoXmlSignature::CERTIFICATE_REVOKED);
m_current_signature_index = 0;
g_main_message_handler->SetCallBack(this, MSG_GADGET_SIGNATURE_PROCESS_OCSP, Id());
ScheduleOCSPProcessing();
}
void GadgetSignatureVerifier::ScheduleOCSPProcessing()
{
OP_ASSERT(g_main_message_handler);
g_main_message_handler->PostMessage(
MSG_GADGET_SIGNATURE_PROCESS_OCSP, Id(), 0);
}
void GadgetSignatureVerifier::LaunchOCSPProcessing()
{
OP_ASSERT(m_gadget_signature_storage);
GadgetSignature* signature = GetCurrentSignature();
if (signature)
{
// Process OCSP for this signature.
TRAPD(status, ProcessOCSPL(*signature));
if (OpStatus::IsError(status))
{
CryptoXmlSignature::VerifyError signature_verify_error =
signature->GetVerifyError();
CryptoXmlSignature::VerifyError common_verify_error =
m_gadget_signature_storage->GetCommonVerifyError();
BOOL upgrade_common =
(signature_verify_error == CryptoXmlSignature::OK_CHECKED_LOCALLY) &&
(common_verify_error == CryptoXmlSignature::CERTIFICATE_REVOKED);
FinishOCSPVerification(signature_verify_error, upgrade_common);
}
}
else
{
#ifdef _DEBUG
const unsigned int total_signature_count =
m_gadget_signature_storage->GetDistributorSignatureCount() +
m_gadget_signature_storage->GetAuthorSignatureCount();
OP_ASSERT(m_current_signature_index == total_signature_count);
#endif
NotifyAboutFinishedVerification();
}
}
GadgetSignature* GadgetSignatureVerifier::GetCurrentSignature() const
{
OP_ASSERT(m_gadget_signature_storage);
GadgetSignature* signature =
m_gadget_signature_storage->GetSignatureByFlatIndex(m_current_signature_index);
#ifdef _DEBUG
const unsigned int distributor_signature_count =
m_gadget_signature_storage->GetDistributorSignatureCount();
if (m_current_signature_index < distributor_signature_count)
{
// Distributor signature.
OP_ASSERT(signature);
OP_ASSERT(IsDistributorSignature(signature->GetSignatureFilename()));
}
else if (m_current_signature_index == distributor_signature_count &&
m_gadget_signature_storage->GetAuthorSignatureCount())
{
// Author signature.
OP_ASSERT(signature);
OP_ASSERT(IsAuthorSignature(signature->GetSignatureFilename()));
}
else
OP_ASSERT(!signature);
#endif
return signature;
}
void GadgetSignatureVerifier::ProcessOCSPL(GadgetSignature& gadget_signature)
{
CryptoXmlSignature::VerifyError local_error_code = gadget_signature.GetVerifyError();
if (local_error_code != CryptoXmlSignature::OK_CHECKED_LOCALLY)
{
// The signature was not verified successfully locally.
// As local verification has failed already,
// it doesn't make sense to do OCSP check.
// It may even be impossible, because the certificate chain
// may not have been built.
// Let's LEAVE and LaunchOCSPProcessing() will
// ScheduleOCSPProcessing() of the next signature.
LEAVE(OpStatus::ERR_OUT_OF_RANGE);
}
// The local verification succeeded, the certificate chain must be present.
const CryptoCertificateChain* certificate_chain = gadget_signature.GetCertificateChain();
OP_ASSERT(certificate_chain);
m_ocsp_verifier.SetCertificateChain(certificate_chain);
m_ocsp_verifier.SetCAStorage(m_ca_storage);
m_ocsp_verifier.SetRetryCount(CRYPTO_GADGET_SIGNATURE_VERIFICATION_OCSP_RETRY_COUNT);
m_ocsp_verifier.SetTimeout(CRYPTO_GADGET_SIGNATURE_VERIFICATION_OCSP_TIMEOUT);
g_main_message_handler->SetCallBack(
this, MSG_OCSP_CERTIFICATE_CHAIN_VERIFICATION_FINISHED, m_ocsp_verifier.Id());
m_ocsp_verifier.ProcessL();
}
void GadgetSignatureVerifier::ProcessOCSPVerificationResult()
{
CryptoXmlSignature::VerifyError common_verify_error =
m_gadget_signature_storage->GetCommonVerifyError();
CryptoXmlSignature::VerifyError signature_verify_error;
BOOL upgrade_common = FALSE;
// Determine signature_verify_error and "upgrade" common_verify_error if necessary.
CryptoCertificateChain::VerifyStatus verify_status = m_ocsp_verifier.GetVerifyStatus();
switch (verify_status)
{
case CryptoCertificateChain::OK_CHECKED_WITH_OCSP:
signature_verify_error = CryptoXmlSignature::OK_CHECKED_WITH_OCSP;
// Only upgrade status.
if (common_verify_error != CryptoXmlSignature::OK_CHECKED_WITH_OCSP)
upgrade_common = TRUE;
break;
case CryptoCertificateChain::CERTIFICATE_REVOKED:
signature_verify_error = CryptoXmlSignature::CERTIFICATE_REVOKED;
// Only upgrade status.
if (common_verify_error != CryptoXmlSignature::OK_CHECKED_WITH_OCSP &&
common_verify_error != CryptoXmlSignature::OK_CHECKED_LOCALLY &&
common_verify_error != CryptoXmlSignature::CERTIFICATE_REVOKED
)
upgrade_common = TRUE;
break;
default:
OP_ASSERT(verify_status == CryptoCertificateChain::VERIFY_STATUS_UNKNOWN);
signature_verify_error = CryptoXmlSignature::OK_CHECKED_LOCALLY;
// Only upgrade status.
if (common_verify_error != CryptoXmlSignature::OK_CHECKED_WITH_OCSP &&
common_verify_error != CryptoXmlSignature::OK_CHECKED_LOCALLY
)
upgrade_common = TRUE;
}
GadgetSignature* signature = GetCurrentSignature();
if (signature)
signature->SetVerifyError(signature_verify_error);
else
OP_ASSERT(!"Should be impossible: NULL signature pointer!");
FinishOCSPVerification(signature_verify_error, upgrade_common);
// If we reached this point - best signature exists.
OP_ASSERT(m_gadget_signature_storage->GetBestSignature());
// Common error matches the best signature error.
OP_ASSERT(m_gadget_signature_storage->GetCommonVerifyError() ==
m_gadget_signature_storage->GetBestSignature()->GetVerifyError());
}
void GadgetSignatureVerifier::FinishOCSPVerification(CryptoXmlSignature::VerifyError signature_verify_error, BOOL upgrade_common)
{
if (upgrade_common)
{
m_gadget_signature_storage->SetCommonVerifyError(signature_verify_error);
m_gadget_signature_storage->SetBestSignatureIndex(m_current_signature_index);
}
m_current_signature_index++;
ScheduleOCSPProcessing();
}
#endif // CRYPTO_OCSP_SUPPORT
void GadgetSignatureVerifier::NotifyAboutFinishedVerification()
{
OP_ASSERT(g_main_message_handler);
#ifdef CRYPTO_OCSP_SUPPORT
g_main_message_handler->UnsetCallBacks(this);
#endif
g_main_message_handler->PostMessage(
MSG_GADGET_SIGNATURE_VERIFICATION_FINISHED, Id(), 0);
}
#endif // SIGNED_GADGET_SUPPORT
|
// Created on: 1993-01-09
// Created by: CKY / Contract Toubro-Larsen ( SIVA )
// Copyright (c) 1993-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _IGESDimen_RadiusDimension_HeaderFile
#define _IGESDimen_RadiusDimension_HeaderFile
#include <Standard.hxx>
#include <Standard_Type.hxx>
#include <gp_XY.hxx>
#include <IGESData_IGESEntity.hxx>
#include <Standard_Integer.hxx>
class IGESDimen_GeneralNote;
class IGESDimen_LeaderArrow;
class gp_Pnt2d;
class gp_Pnt;
class IGESDimen_RadiusDimension;
DEFINE_STANDARD_HANDLE(IGESDimen_RadiusDimension, IGESData_IGESEntity)
//! Defines IGES Radius Dimension, type <222> Form <0, 1>,
//! in package IGESDimen.
//! A Radius Dimension Entity consists of a General Note, a
//! leader, and an arc center point. A second form of this
//! entity accounts for the occasional need to have two
//! leader entities referenced.
class IGESDimen_RadiusDimension : public IGESData_IGESEntity
{
public:
Standard_EXPORT IGESDimen_RadiusDimension();
Standard_EXPORT void Init (const Handle(IGESDimen_GeneralNote)& aNote, const Handle(IGESDimen_LeaderArrow)& anArrow, const gp_XY& arcCenter, const Handle(IGESDimen_LeaderArrow)& anotherArrow);
//! Allows to change Form Number
//! (1 admits null arrow)
Standard_EXPORT void InitForm (const Standard_Integer form);
//! returns the General Note entity
Standard_EXPORT Handle(IGESDimen_GeneralNote) Note() const;
//! returns the Leader Arrow entity
Standard_EXPORT Handle(IGESDimen_LeaderArrow) Leader() const;
//! returns the coordinates of the Arc Center
Standard_EXPORT gp_Pnt2d Center() const;
//! returns the coordinates of the Arc Center after Transformation
//! (Z coord taken from ZDepth of Leader Entity)
Standard_EXPORT gp_Pnt TransformedCenter() const;
//! returns True if form is 1, False if 0
Standard_EXPORT Standard_Boolean HasLeader2() const;
//! returns Null handle if Form is 0
Standard_EXPORT Handle(IGESDimen_LeaderArrow) Leader2() const;
DEFINE_STANDARD_RTTIEXT(IGESDimen_RadiusDimension,IGESData_IGESEntity)
protected:
private:
Handle(IGESDimen_GeneralNote) theNote;
Handle(IGESDimen_LeaderArrow) theLeaderArrow;
gp_XY theCenter;
Handle(IGESDimen_LeaderArrow) theLeader2;
};
#endif // _IGESDimen_RadiusDimension_HeaderFile
|
// Created on: 2004-11-23
// Created by: Pavel TELKOV
// Copyright (c) 2004-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
// The original implementation Copyright: (C) RINA S.p.A
#ifndef TObj_TReference_HeaderFile
#define TObj_TReference_HeaderFile
#include <TObj_Common.hxx>
#include <TDF_Attribute.hxx>
#include <TDF_Label.hxx>
class TObj_Object;
class Standard_GUID;
/**
* Attribute for storing references to the objects which implement
* TObj_Object interface in the OCAF tree.
* Its persistency mechanism provides transparent method for storing
* cross-model references.
* Each reference, when created, registers itself in the referred object,
* to support back references
*/
class TObj_TReference : public TDF_Attribute
{
public:
//! Standard methods of OCAF attribute
//! Empty constructor
Standard_EXPORT TObj_TReference();
//! This method is used in implementation of ID()
static Standard_EXPORT const Standard_GUID& GetID();
//! Returns the ID of TObj_TReference attribute.
Standard_EXPORT const Standard_GUID& ID() const Standard_OVERRIDE;
public:
//! Method for create TObj_TReference object
//! Creates reference on TDF_Label <theLabel> to the object <theObject> and
//! creates backreference from the object <theObject> to <theMaster> one.
static Standard_EXPORT Handle(TObj_TReference) Set
(const TDF_Label& theLabel,
const Handle(TObj_Object)& theObject,
const Handle(TObj_Object)& theMaster);
public:
//! Methods for setting and obtaining referenced object
//! Sets the reference to the theObject
Standard_EXPORT void Set(const Handle(TObj_Object)& theObject,
const TDF_Label& theMasterLabel);
//! Sets the reference to the theObject at indicated Label.
//! It is method for persistent only. Don`t use anywhere else.
Standard_EXPORT void Set(const TDF_Label& theLabel,
const TDF_Label& theMasterLabel);
//! Returns the referenced theObject
Standard_EXPORT Handle(TObj_Object) Get() const;
//! Returns the Label of master object.
TDF_Label GetMasterLabel() const {return myMasterLabel;}
//! Returns the referred label.
TDF_Label GetLabel() const {return myLabel;}
public:
//! Redefined OCAF abstract methods
//! Returns an new empty TObj_TReference attribute. It is used by the
//! copy algorithm.
Standard_EXPORT Handle(TDF_Attribute) NewEmpty() const Standard_OVERRIDE;
//! Restores the backuped contents from <theWith> into this one. It is used
//! when aborting a transaction.
Standard_EXPORT void Restore(const Handle(TDF_Attribute)& theWith) Standard_OVERRIDE;
//! This method is used when copying an attribute from a source structure
//! into a target structure.
Standard_EXPORT void Paste(const Handle(TDF_Attribute)& theInto,
const Handle(TDF_RelocationTable)& theRT) const Standard_OVERRIDE;
//! Remove back references of it reference if it is in other document.
virtual Standard_EXPORT void BeforeForget() Standard_OVERRIDE;
//! It is necessary for tranzaction mechanism (Undo/Redo).
virtual Standard_EXPORT Standard_Boolean BeforeUndo
(const Handle(TDF_AttributeDelta)& theDelta,
const Standard_Boolean isForced = Standard_False) Standard_OVERRIDE;
//! It is necessary for tranzaction mechanism (Undo/Redo).
virtual Standard_EXPORT Standard_Boolean AfterUndo
(const Handle(TDF_AttributeDelta)& theDelta,
const Standard_Boolean isForced = Standard_False) Standard_OVERRIDE;
//! Check if back reference exists for reference.
virtual Standard_EXPORT void AfterResume() Standard_OVERRIDE;
//! Called after retrieval reference from file.
virtual Standard_EXPORT Standard_Boolean AfterRetrieval
(const Standard_Boolean forceIt = Standard_False) Standard_OVERRIDE;
private:
//! Fields
TDF_Label myLabel; //!< Label that indicate referenced object
TDF_Label myMasterLabel; //!< Label of object that have this reference.
public:
//! CASCADE RTTI
DEFINE_STANDARD_RTTIEXT(TObj_TReference,TDF_Attribute)
};
//! Define handle class for TObj_TReference
DEFINE_STANDARD_HANDLE(TObj_TReference,TDF_Attribute)
#endif
#ifdef _MSC_VER
#pragma once
#endif
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2008 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*/
#include "core/pch.h"
#ifdef AUTO_UPDATE_SUPPORT
#ifdef AUTOUPDATE_PACKAGE_INSTALLATION
#include "WindowsAUFileUtils.h"
#define UPDATE_EXECUTABLE_NAME "OperaUpgrader.exe"
#include "win_file_utils.h"
AUFileUtils* AUFileUtils::Create()
{
return new WindowsAUFileUtils;
}
AUFileUtils::AUF_Status WindowsAUFileUtils::GetUpgradeFolder(uni_char **temp_path, BOOL with_exe_name)
{
// returns a subdirectory of the Windows Temp Path,
// where the name of that subdirectory is the Opera installation path
// without the colon and slashes
uni_char tempdir[MAX_PATH*2];
uni_char *path_end = tempdir;
if (!GetTempPath(MAX_PATH, path_end))
return ERR;
do { path_end++; } while (*path_end);
if (*(path_end-1) != '\\')
*path_end++ = '\\';
if (!GetModuleFileName(NULL, path_end, MAX_PATH))
return ERR;
uni_char *filename = uni_strrchr(path_end, '\\');
uni_char *path_pos = path_end;
while (path_pos < filename)
{
if (*path_pos != '\\' && *path_pos != ':')
*path_end++ = *path_pos;
path_pos++;
}
*path_end++ = '\\';
*path_end = 0;
UINT path_len = path_end-tempdir;
*temp_path = new uni_char[path_len + (with_exe_name ? ARRAY_SIZE(UNI_L(UPDATE_EXECUTABLE_NAME)) : 1)];
if (!*temp_path)
return ERR_MEM;
uni_strcpy(*temp_path, tempdir);
if (with_exe_name)
uni_strcpy(*temp_path + path_len, UNI_L(UPDATE_EXECUTABLE_NAME));
return OK;
}
AUFileUtils::AUF_Status WindowsAUFileUtils::GetExePath(uni_char **exe_path)
{
uni_char fullpath[MAX_PATH];
DWORD length = GetModuleFileName(NULL, fullpath, MAX_PATH);
if (!length)
return ERR;
*exe_path = new uni_char[length+1];
if (!*exe_path)
return ERR_MEM;
uni_strcpy(*exe_path, fullpath);
return OK;
}
AUFileUtils::AUF_Status WindowsAUFileUtils::GetWaitFilePath(uni_char **wait_file_path, BOOL look_in_exec_folder)
{
uni_char* folder_to_search = NULL;
AUF_Status status = ERR;
if(look_in_exec_folder)
{
do
{
status = GetExePath(&folder_to_search);
if(status != OK)
break;
int path_sep_char_index = uni_strlen(folder_to_search) - 1;
for(; path_sep_char_index >= 0; --path_sep_char_index)
{
if(folder_to_search[path_sep_char_index] == UNI_L(PATHSEPCHAR))
break;
}
if(path_sep_char_index < 0)
{
OP_DELETEA(folder_to_search);
status = ERR;
break;
}
folder_to_search[path_sep_char_index + 1] = UNI_L('\0');
} while(0);
}
else
{
status = GetUpgradeFolder(&folder_to_search, FALSE);
}
if(status != OK)
return status;
int buffer_size = uni_strlen(folder_to_search) + uni_strlen(AUTOUPDATE_UPDATE_WAITFILE) + 1;
*wait_file_path = OP_NEWA(uni_char, buffer_size);
if(!*wait_file_path)
{
OP_DELETEA(folder_to_search);
return ERR_MEM;
}
uni_strcpy(*wait_file_path, folder_to_search);
uni_strcat(*wait_file_path, AUTOUPDATE_UPDATE_WAITFILE);
OP_DELETEA(folder_to_search);
return OK;
}
AUFileUtils::AUF_Status WindowsAUFileUtils::IsUpdater(BOOL &is_updater)
{
is_updater = FALSE;
uni_char fullpath[MAX_PATH];
if (!GetModuleFileName(NULL, fullpath, MAX_PATH))
return ERR;
uni_char *filename = uni_strrchr(fullpath, '\\');
if (!filename)
filename = fullpath;
else
filename++;
uni_char *updater_name = UNI_L(UPDATE_EXECUTABLE_NAME);
// inlined uni_stricmp, making it available here from the stdlib module would be a major PITA
while (*updater_name)
{
if ((*filename | 0x20) != (*updater_name | 0x20))
return OK;
filename++;
updater_name++;
}
is_updater = TRUE;
return OK;
}
AUFileUtils::AUF_Status WindowsAUFileUtils::GetUpdateName(uni_char **name)
{
*name = new uni_char[ARRAY_SIZE(UNI_L(UPDATE_EXECUTABLE_NAME))];
if (!*name)
return ERR_MEM;
uni_strcpy(*name, UNI_L(UPDATE_EXECUTABLE_NAME));
return OK;
}
AUFileUtils::AUF_Status WindowsAUFileUtils::ConvertError()
{
switch (GetLastError())
{
case ERROR_FILE_NOT_FOUND:
case ERROR_PATH_NOT_FOUND:
return FILE_NOT_FOUND;
case ERROR_ACCESS_DENIED:
return NO_ACCESS;
case ERROR_NOT_ENOUGH_MEMORY:
return ERR_MEM;
}
return ERR;
}
AUFileUtils::AUF_Status WindowsAUFileUtils::ConvertError(DWORD error_code)
{
switch (error_code)
{
case ERROR_SUCCESS:
return AUFileUtils::OK;
case ERROR_FILE_NOT_FOUND:
case ERROR_PATH_NOT_FOUND:
return FILE_NOT_FOUND;
case ERROR_ACCESS_DENIED:
return NO_ACCESS;
case ERROR_NOT_ENOUGH_MEMORY:
return ERR_MEM;
}
return ERR;
}
AUFileUtils::AUF_Status WindowsAUFileUtils::Exists(uni_char *file, unsigned int &size)
{
WIN32_FIND_DATA findfiledata;
HANDLE handle = FindFirstFile(file, &findfiledata);
if (handle == INVALID_HANDLE_VALUE)
return ConvertError();
size = findfiledata.nFileSizeLow;
FindClose(handle);
return OK;
}
AUFileUtils::AUF_Status WindowsAUFileUtils::Read(uni_char *file, char** buffer, size_t& buf_size)
{
return ConvertError(WinFileUtils::Read(file,buffer,buf_size));
}
AUFileUtils::AUF_Status WindowsAUFileUtils::Delete(uni_char *file)
{
if (!DeleteFile(file))
return ConvertError();
return OK;
}
AUFileUtils::AUF_Status WindowsAUFileUtils::CreateEmptyFile(uni_char *file)
{
HANDLE handle = CreateFile(file, GENERIC_WRITE, 0, NULL, CREATE_NEW, 0, 0);
if (handle == INVALID_HANDLE_VALUE)
return ConvertError();
CloseHandle(handle);
return OK;
}
#endif // AUTOUPDATE_PACKAGE_INSTALLATION
#endif // AUTO_UPDATE_SUPPORT
|
#include <ros/ros.h>
#include <ros/package.h>
#include <vector>
#include <string>
#include <cstdlib>
#include <geometry_msgs/Pose.h>
#include <moveit_msgs/RobotState.h>
#include <moveit/move_group_interface/move_group.h>
#include <moveit/planning_scene_interface/planning_scene_interface.h>
#include <moveit/robot_state/robot_state.h>
#include <moveit/robot_state/conversions.h>
#include <moveit_msgs/PositionIKRequest.h>
#include <moveit_msgs/GetPositionIK.h>
#include <Eigen/Geometry>
#include <tf/transform_broadcaster.h>
#include <tf/transform_listener.h>
#include <tf/transform_datatypes.h>
#include <tf_conversions/tf_eigen.h>
#include <tf/transform_broadcaster.h>
#include <visualization_msgs/Marker.h>
#include <narms_utils.h>
#include <narms/target_pose.h>
int main(int argc, char*argv[]){
ros::init(argc, argv, "pr2_planning_test");
ros::NodeHandle nh;
moveit::planning_interface::PlanningSceneInterface planning_scene_interface;
tf::TransformBroadcaster tf_broadcaster;
// Visualization markers
ros::Publisher ik_vis_pub = nh.advertise<visualization_msgs::Marker>( "ik_goals", 0 );
// IK stuff
moveit_msgs::GetPositionIK ik_srv;
ros::ServiceClient compute_ik = nh.serviceClient<moveit_msgs::GetPositionIK>("compute_ik");
// PR2 Specific Messages
std::string pr2_planning_group("pr2_right_arm");
ros::ServiceClient pr2_move_arm_server = nh.serviceClient<narms::target_pose>("pr2_move_arm_server");
// Roman Specific Messages
std::string roman_planning_group("roman_right_arm");
ros::ServiceClient roman_move_arm_server = nh.serviceClient<narms::target_pose>("roman_move_arm_server");
double x_scale, y_scale, z_scale;
ros::param::get("object_x_scale", x_scale);
ros::param::get("object_y_scale", y_scale);
ros::param::get("object_z_scale", z_scale);
// Add a visualization marker for shits and giggles**************************
visualization_msgs::Marker viz_marker;
viz_marker.header.frame_id = "world";
viz_marker.id = 0;
viz_marker.type = visualization_msgs::Marker::CUBE;
viz_marker.action = visualization_msgs::Marker::ADD;
viz_marker.scale.x = x_scale;
viz_marker.scale.y = y_scale;
viz_marker.scale.z = z_scale;
viz_marker.color.a = 1.0;
viz_marker.color.r = 1.0;
bool handoff_success = false;
double sampling_variance_inflation_m = 0.0;
double sampling_variance_inflation_step_m = 0.01;
geometry_msgs::Pose pr2_pose;
geometry_msgs::Pose roman_pose;
for(int i = 0; i < 500; i++)
{
if(!ros::ok()) {return 0;}
geometry_msgs::Pose randPose = generateRandomPose();
tf::StampedTransform randTf(geoPose2Transform(randPose), ros::Time::now(), "world_link", "object");
getGraspingPoses(randTf, pr2_pose, roman_pose);
tf_broadcaster.sendTransform(tf::StampedTransform(geoPose2Transform(pr2_pose), ros::Time::now(), "world_link", "pr2_grasp"));
tf_broadcaster.sendTransform(tf::StampedTransform(geoPose2Transform(roman_pose), ros::Time::now(), "world_link", "roman_grasp"));
tf_broadcaster.sendTransform(randTf);
// vizualize pose
viz_marker.pose = randPose;
viz_marker.header.stamp = ros::Time::now();
ik_vis_pub.publish(viz_marker);
getIKServerRequest(pr2_pose, pr2_planning_group, ik_srv);
int n_reached = 0;
// PR2 IK ***********************************************************************************
ros::WallTime t0 = ros::WallTime::now();
bool ik_suc = compute_ik.call(ik_srv);
ros::WallTime t1 = ros::WallTime::now();
std::cout << "pr2 compute_IK call time: " << (t1-t0).toSec() << "\n";
if(ik_suc){
if(ik_srv.response.error_code.val == 1){
std::cout << "PR2 can reach goal!\n";
n_reached++;
}
}else{
std::cout << "Could not call PR2 IK service\n";
}
// Roman IK **********************************************************************************
getIKServerRequest(roman_pose, roman_planning_group, ik_srv);
t0 = ros::WallTime::now();
ik_suc = compute_ik.call(ik_srv);
t1 = ros::WallTime::now();
std::cout << "roman compute_IK call time: " << (t1-t0).toSec() << "\n";
if(ik_suc){
if(ik_srv.response.error_code.val == 1){
std::cout << "ROMAN can reach goal!\n";
n_reached++;
}
} else {
std::cout << "Could not call ROMAN IK service\n";
}
// Planning and Execution ******************************************************************
if (n_reached >= 2){
// Solution is feasible for both PR2 and ROMAN,
// Now plan and execute
int n_planned = 0;
// PR2 planning and execution
narms::target_pose pr2_mas_request;
pr2_mas_request.request.pose = pr2_pose;
ros::WallTime t2 = ros::WallTime::now();
pr2_move_arm_server.call(pr2_mas_request);
ros::WallTime t3 = ros::WallTime::now();
std::cout << "pr2 move_arm_server call time: " << (t3-t2).toSec() << "\n";
if(pr2_mas_request.response.result == true){
std::cout << "PR2 plan found!\n";
n_planned ++;
}
// Roman planning and execution
narms::target_pose roman_mas_request;
roman_mas_request.request.pose = roman_pose;
t2 = ros::WallTime::now();
roman_move_arm_server.call(roman_mas_request);
t3 = ros::WallTime::now();
std::cout << "roman move_arm_server call time: " << (t3-t2).toSec() << "\n";
if(roman_mas_request.response.result == true)
{
std::cout << "ROMAN Plan executed!\n";
n_planned++;
}
if(n_planned >= 2){
std::cout << "\nBOTH ARM REACHED OBJECT\n";
printPose(randPose);
ros::Duration(2).sleep();
}
}
}
return 0;
}
|
/*
Analog input, analog output, serial output
Reads an analog input pin, maps the result to a range from 0 to 255
and uses the result to set the pulsewidth modulation (PWM) of an output pin.
Also prints the results to the serial monitor.
The circuit:
* potentiometer connected to analog pin 0.
Center pin of the potentiometer goes to the analog pin.
side pins of the potentiometer go to +5V and ground
* LED connected from digital pin 9 to ground
created 29 Dec. 2008
modified 9 Apr 2012
by Tom Igoe
This example code is in the public domain.
// channel one on top two on bottom
*/
// These constants won't change. They're used to give names
// to the pins used:
const int analogInPin = A0;
void setup() {
pinMode(32, OUTPUT);
pinMode(25, OUTPUT);
pinMode(27, OUTPUT);
pinMode(12, OUTPUT);
pinMode(13, OUTPUT);
Serial.begin(115200);
}
void loop() {
//int sensorValue = analogRead(analogInPin);
digitalWrite(32, HIGH);
delay(1000);
digitalWrite(25, HIGH);
delay(1000);
digitalWrite(32, LOW);
delay(1000);
digitalWrite(25, LOW);
delay(1000);
digitalWrite(32, HIGH);
delay(1000);
digitalWrite(25, HIGH);
delay(1000);
digitalWrite(32, LOW);
delay(1000);
digitalWrite(25, LOW);
delay(1000);
//Serial.print("\n sensor X = ");
//Serial.print(sensorValue);
//Serial.print("\n");
//if (sensorValue>800)
//{
// digitalWrite(10,HIGH);
//delay(1000);
// digitalWrite(10,LOW);
// }
}
|
#pragma once
namespace qp
{
class CMultipleChoiceQuestion;
typedef std::shared_ptr<CMultipleChoiceQuestion> CMultipleChoiceQuestionPtr;
typedef std::shared_ptr<const CMultipleChoiceQuestion> CConstMultipleChoiceQuestionPtr;
}
|
#include "../idlib/precompiled.h"
#pragma hdrstop
#include "Game_local.h"
// RAVEN BEGIN
// bdube: client entities
#include "client/ClientEffect.h"
// shouchard: ban list support
#define BANLIST_FILENAME "banlist.txt"
// RAVEN END
/*
===============================================================================
Client running game code:
- entity events don't work and should not be issued
- entities should never be spawned outside idGameLocal::ClientReadSnapshot
===============================================================================
*/
// adds tags to the network protocol to detect when things go bad ( internal consistency )
// NOTE: this changes the network protocol
#ifndef ASYNC_WRITE_TAGS
#define ASYNC_WRITE_TAGS 0
#endif
idCVar net_clientShowSnapshot( "net_clientShowSnapshot", "0", CVAR_GAME | CVAR_INTEGER, "", 0, 3, idCmdSystem::ArgCompletion_Integer<0,3> );
idCVar net_clientShowSnapshotRadius( "net_clientShowSnapshotRadius", "128", CVAR_GAME | CVAR_FLOAT, "" );
idCVar net_clientMaxPrediction( "net_clientMaxPrediction", "1000", CVAR_SYSTEM | CVAR_INTEGER | CVAR_NOCHEAT, "maximum number of milliseconds a client can predict ahead of server." );
idCVar net_clientLagOMeter( "net_clientLagOMeter", "0", CVAR_GAME | CVAR_BOOL | CVAR_NOCHEAT | PC_CVAR_ARCHIVE, "draw prediction graph" );
// RAVEN BEGIN
// ddynerman: performance profiling
int net_entsInSnapshot;
int net_snapshotSize;
extern const int ASYNC_PLAYER_FRAG_BITS;
// RAVEN END
/*
================
idGameLocal::InitAsyncNetwork
================
*/
void idGameLocal::InitAsyncNetwork( void ) {
memset( clientEntityStates, 0, sizeof( clientEntityStates ) );
memset( clientPVS, 0, sizeof( clientPVS ) );
memset( clientSnapshots, 0, sizeof( clientSnapshots ) );
eventQueue.Init();
// NOTE: now that we removed spawning by typeNum, we could stick to a >0 entityDefBits
// not making the change at this point because of proto69 back compat stuff
entityDefBits = -( idMath::BitsForInteger( declManager->GetNumDecls( DECL_ENTITYDEF ) ) + 1 );
localClientNum = 0; // on a listen server SetLocalUser will set this right
realClientTime = 0;
isNewFrame = true;
}
/*
================
idGameLocal::ShutdownAsyncNetwork
================
*/
void idGameLocal::ShutdownAsyncNetwork( void ) {
entityStateAllocator.Shutdown();
snapshotAllocator.Shutdown();
eventQueue.Shutdown();
memset( clientEntityStates, 0, sizeof( clientEntityStates ) );
memset( clientPVS, 0, sizeof( clientPVS ) );
memset( clientSnapshots, 0, sizeof( clientSnapshots ) );
}
/*
================
idGameLocal::InitLocalClient
================
*/
void idGameLocal::InitLocalClient( int clientNum ) {
isServer = false;
isClient = true;
localClientNum = clientNum;
}
/*
================
idGameLocal::ServerAllowClient
clientId is the ID of the connecting client - can later be mapped to a clientNum by calling networkSystem->ServerGetClientNum( clientId )
================
*/
allowReply_t idGameLocal::ServerAllowClient( int clientId, int numClients, const char *IP, const char *guid, const char *password, const char *privatePassword, char reason[ MAX_STRING_CHARS ] ) {
reason[0] = '\0';
// RAVEN BEGIN
// shouchard: ban support
if ( IsGuidBanned( guid ) ) {
idStr::snPrintf( reason, MAX_STRING_CHARS, "#str_107239" );
return ALLOW_NO;
}
// RAVEN END
if ( serverInfo.GetInt( "si_pure" ) && !mpGame.IsPureReady() ) {
idStr::snPrintf( reason, MAX_STRING_CHARS, "#str_107139" );
return ALLOW_NOTYET;
}
if ( !serverInfo.GetInt( "si_maxPlayers" ) ) {
idStr::snPrintf( reason, MAX_STRING_CHARS, "#str_107140" );
return ALLOW_NOTYET;
}
// completely full
if ( numClients >= serverInfo.GetInt( "si_maxPlayers" ) ) {
idStr::snPrintf( reason, MAX_STRING_CHARS, "#str_107141" );
return ALLOW_NOTYET;
}
// check private clients
if( serverInfo.GetInt( "si_privatePlayers" ) > 0 ) {
// just in case somehow we have a stale private clientId that matches a new client
mpGame.RemovePrivatePlayer( clientId );
const char *privatePass = cvarSystem->GetCVarString( "g_privatePassword" );
if( privatePass[ 0 ] == '\0' ) {
common->Warning( "idGameLocal::ServerAllowClient() - si_privatePlayers > 0 with no g_privatePassword" );
cmdSystem->BufferCommandText( CMD_EXEC_NOW, "say si_privatePlayers is set but g_privatePassword is empty" );
idStr::snPrintf( reason, MAX_STRING_CHARS, "#str_107142" );
return ALLOW_NOTYET;
}
int numPrivateClients = cvarSystem->GetCVarInteger( "si_numPrivatePlayers" );
// private clients that take up public slots are considered public clients
numPrivateClients = idMath::ClampInt( 0, serverInfo.GetInt( "si_privatePlayers" ), numPrivateClients );
if ( !idStr::Cmp( privatePass, privatePassword ) ) {
// once this client spawns in, they'll be marked private
mpGame.AddPrivatePlayer( clientId );
} else if( (numClients - numPrivateClients) >= (serverInfo.GetInt( "si_maxPlayers" ) - serverInfo.GetInt( "si_privatePlayers" )) ) {
// if the number of public clients is greater than or equal to the number of public slots, require a private slot
idStr::snPrintf( reason, MAX_STRING_CHARS, "#str_107141" );
return ALLOW_NOTYET;
}
}
if ( !cvarSystem->GetCVarBool( "si_usePass" ) ) {
return ALLOW_YES;
}
const char *pass = cvarSystem->GetCVarString( "g_password" );
if ( pass[ 0 ] == '\0' ) {
common->Warning( "si_usePass is set but g_password is empty" );
cmdSystem->BufferCommandText( CMD_EXEC_NOW, "say si_usePass is set but g_password is empty" );
// avoids silent misconfigured state
idStr::snPrintf( reason, MAX_STRING_CHARS, "#str_107142" );
return ALLOW_NOTYET;
}
if ( !idStr::Cmp( pass, password ) ) {
return ALLOW_YES;
}
idStr::snPrintf( reason, MAX_STRING_CHARS, "#str_107143" );
Printf( "Rejecting client %s from IP %s: invalid password\n", guid, IP );
return ALLOW_BADPASS;
}
/*
================
idGameLocal::ServerClientConnect
================
*/
void idGameLocal::ServerClientConnect( int clientNum, const char *guid ) {
// make sure no parasite entity is left
if ( entities[ clientNum ] ) {
common->DPrintf( "ServerClientConnect: remove old player entity\n" );
delete entities[ clientNum ];
}
unreliableMessages[ clientNum ].Init( 0 );
userInfo[ clientNum ].Clear();
mpGame.ServerClientConnect( clientNum );
Printf( "client %d connected.\n", clientNum );
}
/*
================
idGameLocal::ServerClientBegin
================
*/
void idGameLocal::ServerClientBegin( int clientNum ) {
idBitMsg outMsg;
byte msgBuf[MAX_GAME_MESSAGE_SIZE];
// spawn the player
SpawnPlayer( clientNum );
if ( clientNum == localClientNum ) {
mpGame.EnterGame( clientNum );
}
// ddynerman: connect time
((idPlayer*)entities[ clientNum ])->SetConnectTime( time );
// send message to spawn the player at the clients
outMsg.Init( msgBuf, sizeof( msgBuf ) );
outMsg.BeginWriting();
outMsg.WriteByte( GAME_RELIABLE_MESSAGE_SPAWN_PLAYER );
outMsg.WriteByte( clientNum );
outMsg.WriteLong( spawnIds[ clientNum ] );
networkSystem->ServerSendReliableMessage( -1, outMsg );
if( gameType != GAME_TOURNEY ) {
((idPlayer*)entities[ clientNum ])->JoinInstance( 0 );
} else {
// instance 0 might be empty in Tourney
((idPlayer*)entities[ clientNum ])->JoinInstance( ((rvTourneyGameState*)gameLocal.mpGame.GetGameState())->GetNextActiveArena( 0 ) );
}
//RAVEN BEGIN
//asalmon: This client has finish loading and will be spawned mark them as ready.
#ifdef _XENON
Live()->ClientReady(clientNum);
#endif
//RAVEN END
}
/*
================
idGameLocal::ServerClientDisconnect
clientNum == MAX_CLIENTS for cleanup of server demo recording data
================
*/
void idGameLocal::ServerClientDisconnect( int clientNum ) {
int i;
idBitMsg outMsg;
byte msgBuf[MAX_GAME_MESSAGE_SIZE];
if ( clientNum < MAX_CLIENTS ) {
outMsg.Init( msgBuf, sizeof( msgBuf ) );
outMsg.BeginWriting();
outMsg.WriteByte( GAME_RELIABLE_MESSAGE_DELETE_ENT );
outMsg.WriteBits( ( spawnIds[ clientNum ] << GENTITYNUM_BITS ) | clientNum, 32 ); // see GetSpawnId
networkSystem->ServerSendReliableMessage( -1, outMsg );
}
// free snapshots stored for this client
FreeSnapshotsOlderThanSequence( clientNum, 0x7FFFFFFF );
// free entity states stored for this client
for ( i = 0; i < MAX_GENTITIES; i++ ) {
if ( clientEntityStates[ clientNum ][ i ] ) {
entityStateAllocator.Free( clientEntityStates[ clientNum ][ i ] );
clientEntityStates[ clientNum ][ i ] = NULL;
}
}
// clear the client PVS
memset( clientPVS[ clientNum ], 0, sizeof( clientPVS[ clientNum ] ) );
if ( clientNum == MAX_CLIENTS ) {
return;
}
// only drop MP clients if we're in multiplayer and the server isn't going down
if ( gameLocal.isMultiplayer && !(gameLocal.isListenServer && clientNum == gameLocal.localClientNum ) ) {
// idMultiplayerGame::DisconnectClient will do the delete in MP
mpGame.DisconnectClient( clientNum );
} else {
// delete the player entity
delete entities[ clientNum ];
}
}
/*
================
idGameLocal::ServerWriteInitialReliableMessages
Send reliable messages to initialize the client game up to a certain initial state.
================
*/
void idGameLocal::ServerWriteInitialReliableMessages( int clientNum ) {
int i;
idBitMsg outMsg;
byte msgBuf[MAX_GAME_MESSAGE_SIZE];
// spawn players
for ( i = 0; i < MAX_CLIENTS; i++ ) {
if ( entities[i] == NULL || i == clientNum ) {
continue;
}
outMsg.Init( msgBuf, sizeof( msgBuf ) );
outMsg.BeginWriting( );
outMsg.WriteByte( GAME_RELIABLE_MESSAGE_SPAWN_PLAYER );
outMsg.WriteByte( i );
outMsg.WriteLong( spawnIds[ i ] );
networkSystem->ServerSendReliableMessage( clientNum, outMsg );
}
// update portals for opened doors
int numPortals = gameRenderWorld->NumPortals();
outMsg.Init( msgBuf, sizeof( msgBuf ) );
outMsg.BeginWriting();
outMsg.WriteByte( GAME_RELIABLE_MESSAGE_PORTALSTATES );
outMsg.WriteLong( numPortals );
for ( i = 0; i < numPortals; i++ ) {
outMsg.WriteBits( gameRenderWorld->GetPortalState( (qhandle_t) (i+1) ) , NUM_RENDER_PORTAL_BITS );
}
networkSystem->ServerSendReliableMessage( clientNum, outMsg );
mpGame.ServerWriteInitialReliableMessages( clientNum );
}
/*
================
idGameLocal::FreeSnapshotsOlderThanSequence
================
*/
void idGameLocal::FreeSnapshotsOlderThanSequence( int clientNum, int sequence ) {
snapshot_t *snapshot, *lastSnapshot, *nextSnapshot;
entityState_t *state;
for ( lastSnapshot = NULL, snapshot = clientSnapshots[clientNum]; snapshot; snapshot = nextSnapshot ) {
nextSnapshot = snapshot->next;
if ( snapshot->sequence < sequence ) {
for ( state = snapshot->firstEntityState; state; state = snapshot->firstEntityState ) {
snapshot->firstEntityState = snapshot->firstEntityState->next;
entityStateAllocator.Free( state );
}
if ( lastSnapshot ) {
lastSnapshot->next = snapshot->next;
} else {
clientSnapshots[clientNum] = snapshot->next;
}
snapshotAllocator.Free( snapshot );
} else {
lastSnapshot = snapshot;
}
}
}
/*
================
idGameLocal::ApplySnapshot
================
*/
bool idGameLocal::ApplySnapshot( int clientNum, int sequence ) {
snapshot_t *snapshot, *lastSnapshot, *nextSnapshot;
entityState_t *state;
FreeSnapshotsOlderThanSequence( clientNum, sequence );
for ( lastSnapshot = NULL, snapshot = clientSnapshots[clientNum]; snapshot; snapshot = nextSnapshot ) {
nextSnapshot = snapshot->next;
if ( snapshot->sequence == sequence ) {
for ( state = snapshot->firstEntityState; state; state = state->next ) {
if ( clientEntityStates[clientNum][state->entityNumber] ) {
entityStateAllocator.Free( clientEntityStates[clientNum][state->entityNumber] );
}
clientEntityStates[clientNum][state->entityNumber] = state;
}
// ~512 bytes
memcpy( clientPVS[clientNum], snapshot->pvs, sizeof( snapshot->pvs ) );
if ( lastSnapshot ) {
lastSnapshot->next = nextSnapshot;
} else {
clientSnapshots[clientNum] = nextSnapshot;
}
snapshotAllocator.Free( snapshot );
return true;
} else {
lastSnapshot = snapshot;
}
}
return false;
}
/*
================
idGameLocal::WriteGameStateToSnapshot
================
*/
void idGameLocal::WriteGameStateToSnapshot( idBitMsgDelta &msg ) const {
int i;
for( i = 0; i < MAX_GLOBAL_SHADER_PARMS; i++ ) {
msg.WriteFloat( globalShaderParms[i] );
}
mpGame.WriteToSnapshot( msg );
}
/*
================
idGameLocal::ReadGameStateFromSnapshot
================
*/
void idGameLocal::ReadGameStateFromSnapshot( const idBitMsgDelta &msg ) {
int i;
for( i = 0; i < MAX_GLOBAL_SHADER_PARMS; i++ ) {
globalShaderParms[i] = msg.ReadFloat();
}
mpGame.ReadFromSnapshot( msg );
}
/*
================
idGameLocal::ServerWriteSnapshot
Write a snapshot of the current game state for the given client.
================
*/
// RAVEN BEGIN
// jnewquist: Use dword array to match pvs array so we don't have endianness problems.
void idGameLocal::ServerWriteSnapshot( int clientNum, int sequence, idBitMsg &msg, dword *clientInPVS, int numPVSClients, int lastSnapshotFrame ) {
// RAVEN END
int i, msgSize, msgWriteBit;
idPlayer *player, *spectated = NULL;
idEntity *ent;
pvsHandle_t pvsHandle;
idBitMsgDelta deltaMsg;
snapshot_t *snapshot;
entityState_t *base, *newBase;
int numSourceAreas, sourceAreas[ idEntity::MAX_PVS_AREAS ];
player = static_cast<idPlayer *>( entities[ clientNum ] );
if ( !player ) {
return;
}
if ( player->spectating && player->spectator != clientNum && entities[ player->spectator ] ) {
spectated = static_cast< idPlayer * >( entities[ player->spectator ] );
} else {
spectated = player;
}
// free too old snapshots
// ( that's a security, normal acking from server keeps a smaller backlog of snaps )
FreeSnapshotsOlderThanSequence( clientNum, sequence - 64 );
// allocate new snapshot
snapshot = snapshotAllocator.Alloc();
snapshot->sequence = sequence;
snapshot->firstEntityState = NULL;
snapshot->next = clientSnapshots[clientNum];
clientSnapshots[clientNum] = snapshot;
memset( snapshot->pvs, 0, sizeof( snapshot->pvs ) );
// get PVS for this player
// don't use PVSAreas for networking - PVSAreas depends on animations (and md5 bounds), which are not synchronized
numSourceAreas = gameRenderWorld->BoundsInAreas( spectated->GetPlayerPhysics()->GetAbsBounds(), sourceAreas, idEntity::MAX_PVS_AREAS );
pvsHandle = gameLocal.pvs.SetupCurrentPVS( sourceAreas, numSourceAreas, PVS_NORMAL );
#if ASYNC_WRITE_TAGS
idRandom tagRandom;
tagRandom.SetSeed( random.RandomInt() );
msg.WriteLong( tagRandom.GetSeed() );
#endif
// write unreliable messages
unreliableMessages[ clientNum ].FlushTo( msg );
#if ASYNC_WRITE_TAGS
msg.WriteLong( tagRandom.RandomInt() );
#endif
// create the snapshot
for( ent = spawnedEntities.Next(); ent != NULL; ent = ent->spawnNode.Next() ) {
// if the entity is not in the player PVS
if ( !ent->PhysicsTeamInPVS( pvsHandle ) && ent->entityNumber != clientNum ) {
continue;
}
// RAVEN BEGIN
// ddynerman: don't transmit entities not in your clip world
if ( ent->GetInstance() != player->GetInstance() ) {
continue;
}
// RAVEN END
// if the entity is a map entity, mark it in PVS
if ( isMapEntity[ ent->entityNumber ] ) {
snapshot->pvs[ ent->entityNumber >> 5 ] |= 1 << ( ent->entityNumber & 31 );
}
// if that entity is not marked for network synchronization
if ( !ent->fl.networkSync ) {
continue;
}
// add the entity to the snapshot PVS
snapshot->pvs[ ent->entityNumber >> 5 ] |= 1 << ( ent->entityNumber & 31 );
// save the write state to which we can revert when the entity didn't change at all
msg.SaveWriteState( msgSize, msgWriteBit );
// write the entity to the snapshot
msg.WriteBits( ent->entityNumber, GENTITYNUM_BITS );
base = clientEntityStates[clientNum][ent->entityNumber];
if ( base ) {
base->state.BeginReading();
}
newBase = entityStateAllocator.Alloc();
newBase->entityNumber = ent->entityNumber;
newBase->state.Init( newBase->stateBuf, sizeof( newBase->stateBuf ) );
newBase->state.BeginWriting();
deltaMsg.InitWriting( base ? &base->state : NULL, &newBase->state, &msg );
deltaMsg.WriteBits( spawnIds[ ent->entityNumber ], 32 - GENTITYNUM_BITS );
assert( ent->entityDefNumber > 0 );
deltaMsg.WriteBits( ent->entityDefNumber, entityDefBits );
// write the class specific data to the snapshot
ent->WriteToSnapshot( deltaMsg );
if ( !deltaMsg.HasChanged() ) {
msg.RestoreWriteState( msgSize, msgWriteBit );
entityStateAllocator.Free( newBase );
} else {
newBase->next = snapshot->firstEntityState;
snapshot->firstEntityState = newBase;
#if ASYNC_WRITE_TAGS
msg.WriteLong( tagRandom.RandomInt() );
#endif
}
}
msg.WriteBits( ENTITYNUM_NONE, GENTITYNUM_BITS );
// write the PVS to the snapshot
#if ASYNC_WRITE_PVS
for ( i = 0; i < idEntity::MAX_PVS_AREAS; i++ ) {
if ( i < numSourceAreas ) {
msg.WriteLong( sourceAreas[ i ] );
} else {
msg.WriteLong( 0 );
}
}
gameLocal.pvs.WritePVS( pvsHandle, msg );
#endif
for ( i = 0; i < ENTITY_PVS_SIZE; i++ ) {
msg.WriteDeltaLong( clientPVS[clientNum][i], snapshot->pvs[i] );
}
// free the PVS
pvs.FreeCurrentPVS( pvsHandle );
// write the game and player state to the snapshot
base = clientEntityStates[clientNum][ENTITYNUM_NONE]; // ENTITYNUM_NONE is used for the game and player state
if ( base ) {
base->state.BeginReading();
}
newBase = entityStateAllocator.Alloc();
newBase->entityNumber = ENTITYNUM_NONE;
newBase->next = snapshot->firstEntityState;
snapshot->firstEntityState = newBase;
newBase->state.Init( newBase->stateBuf, sizeof( newBase->stateBuf ) );
newBase->state.BeginWriting();
deltaMsg.InitWriting( base ? &base->state : NULL, &newBase->state, &msg );
if ( player->spectating && player->spectator != player->entityNumber && entities[ player->spectator ] ) {
assert( entities[ player->spectator ]->IsType( idPlayer::GetClassType() ) );
deltaMsg.WriteBits( player->spectator, idMath::BitsForInteger( MAX_CLIENTS ) );
static_cast< idPlayer * >( gameLocal.entities[ player->spectator ] )->WritePlayerStateToSnapshot( deltaMsg );
} else {
deltaMsg.WriteBits( player->entityNumber, idMath::BitsForInteger( MAX_CLIENTS ) );
player->WritePlayerStateToSnapshot( deltaMsg );
}
WriteGameStateToSnapshot( deltaMsg );
// copy the client PVS string
// RAVEN BEGIN
// JSinger: Changed to call optimized memcpy
// jnewquist: Use dword array to match pvs array so we don't have endianness problems.
const int numDwords = ( numPVSClients + 31 ) >> 5;
for ( i = 0; i < numDwords; i++ ) {
clientInPVS[i] = snapshot->pvs[i];
}
// RAVEN END
}
/*
===============
idGameLocal::ServerWriteServerDemoSnapshot
===============
*/
void idGameLocal::ServerWriteServerDemoSnapshot( int sequence, idBitMsg &msg, int lastSnapshotFrame ) {
snapshot_t *snapshot;
int i, msgSize, msgWriteBit;
idEntity *ent;
entityState_t *base, *newBase;
idBitMsgDelta deltaMsg;
bool ret = ServerApplySnapshot( MAX_CLIENTS, sequence - 1 );
ret = ret; // silence warning
assert( ret || sequence == 1 ); // past the first snapshot of the server demo stream, there's always exactly one to clear
snapshot = snapshotAllocator.Alloc();
snapshot->sequence = sequence;
snapshot->firstEntityState = NULL;
snapshot->next = clientSnapshots[ MAX_CLIENTS ];
clientSnapshots[ MAX_CLIENTS ] = snapshot;
unreliableMessages[ MAX_CLIENTS ].FlushTo( msg );
for ( ent = spawnedEntities.Next(); ent != NULL; ent = ent->spawnNode.Next() ) {
if ( !ent->fl.networkSync ) {
continue;
}
// only record instance 0 ( tourney games )
if ( ent->GetInstance() != 0 ) {
continue;
}
msg.SaveWriteState( msgSize, msgWriteBit );
msg.WriteBits( ent->entityNumber, GENTITYNUM_BITS );
base = clientEntityStates[ MAX_CLIENTS ][ ent->entityNumber ];
if ( base ) {
base->state.BeginReading();
}
newBase = entityStateAllocator.Alloc();
newBase->entityNumber = ent->entityNumber;
newBase->state.Init( newBase->stateBuf, sizeof( newBase->stateBuf ) );
newBase->state.BeginWriting();
deltaMsg.InitWriting( base ? &base->state : NULL, &newBase->state, &msg );
deltaMsg.WriteBits( spawnIds[ ent->entityNumber ], 32 - GENTITYNUM_BITS );
assert( ent->entityDefNumber > 0 );
deltaMsg.WriteBits( ent->entityDefNumber, entityDefBits );
ent->WriteToSnapshot( deltaMsg );
if ( !deltaMsg.HasChanged() ) {
msg.RestoreWriteState( msgSize, msgWriteBit );
entityStateAllocator.Free( newBase );
} else {
newBase->next = snapshot->firstEntityState;
snapshot->firstEntityState = newBase;
}
}
msg.WriteBits( ENTITYNUM_NONE, GENTITYNUM_BITS );
// write player states and game states
base = clientEntityStates[MAX_CLIENTS][ENTITYNUM_NONE]; // ENTITYNUM_NONE is used for the game and player state
if ( base ) {
base->state.BeginReading();
}
newBase = entityStateAllocator.Alloc();
newBase->entityNumber = ENTITYNUM_NONE;
newBase->next = snapshot->firstEntityState;
snapshot->firstEntityState = newBase;
newBase->state.Init( newBase->stateBuf, sizeof( newBase->stateBuf ) );
newBase->state.BeginWriting();
deltaMsg.InitWriting( base ? &base->state : NULL, &newBase->state, &msg );
// all the players
for ( i = 0; i < numClients; i++ ) {
if ( entities[i] ) {
assert( entities[i]->IsType( idPlayer::GetClassType() ) );
idPlayer *p = static_cast< idPlayer * >( entities[i] );
p->WritePlayerStateToSnapshot( deltaMsg );
}
}
// and the game state
WriteGameStateToSnapshot( deltaMsg );
}
/*
================
idGameLocal::ServerApplySnapshot
================
*/
bool idGameLocal::ServerApplySnapshot( int clientNum, int sequence ) {
return ApplySnapshot( clientNum, sequence );
}
/*
================
idGameLocal::NetworkEventWarning
================
*/
void idGameLocal::NetworkEventWarning( const entityNetEvent_t *event, const char *fmt, ... ) {
char buf[1024];
int length = 0;
va_list argptr;
int entityNum = event->spawnId & ( ( 1 << GENTITYNUM_BITS ) - 1 );
int id = event->spawnId >> GENTITYNUM_BITS;
length += idStr::snPrintf( buf+length, sizeof(buf)-1-length, "event %d for entity %d %d: ", event->event, entityNum, id );
va_start( argptr, fmt );
length = idStr::vsnPrintf( buf+length, sizeof(buf)-1-length, fmt, argptr );
va_end( argptr );
idStr::Append( buf, sizeof(buf), "\n" );
common->DWarning( buf );
}
/*
================
idGameLocal::ServerProcessEntityNetworkEventQueue
================
*/
void idGameLocal::ServerProcessEntityNetworkEventQueue( void ) {
idEntity *ent;
entityNetEvent_t *event;
idBitMsg eventMsg;
while ( eventQueue.Start() ) {
event = eventQueue.Start();
if ( event->time > time ) {
break;
}
idEntityPtr< idEntity > entPtr;
if( !entPtr.SetSpawnId( event->spawnId ) ) {
NetworkEventWarning( event, "Entity does not exist any longer, or has not been spawned yet." );
} else {
ent = entPtr.GetEntity();
assert( ent );
eventMsg.Init( event->paramsBuf, sizeof( event->paramsBuf ) );
eventMsg.SetSize( event->paramsSize );
eventMsg.BeginReading();
if ( !ent->ServerReceiveEvent( event->event, event->time, eventMsg ) ) {
NetworkEventWarning( event, "unknown event" );
}
}
#ifdef _DEBUG
entityNetEvent_t* freedEvent = eventQueue.Dequeue();
assert( freedEvent == event );
#else
eventQueue.Dequeue();
#endif
eventQueue.Free( event );
}
}
/*
================
idGameLocal::ServerSendChatMessage
================
*/
void idGameLocal::ServerSendChatMessage( int to, const char *name, const char *text, const char *parm ) {
idBitMsg outMsg;
byte msgBuf[ MAX_GAME_MESSAGE_SIZE ];
outMsg.Init( msgBuf, sizeof( msgBuf ) );
outMsg.BeginWriting();
outMsg.WriteByte( GAME_RELIABLE_MESSAGE_CHAT );
outMsg.WriteString( name );
outMsg.WriteString( text );
outMsg.WriteString( parm );
networkSystem->ServerSendReliableMessage( to, outMsg );
if ( to == -1 || to == localClientNum ) {
idStr temp = va( "%s%s", common->GetLocalizedString( text ), parm );
mpGame.AddChatLine( "%s^0: %s", name, temp.c_str() );
}
}
/*
================
idGameLocal::ServerProcessReliableMessage
================
*/
void idGameLocal::ServerProcessReliableMessage( int clientNum, const idBitMsg &msg ) {
int id;
id = msg.ReadByte();
switch( id ) {
case GAME_RELIABLE_MESSAGE_CHAT:
case GAME_RELIABLE_MESSAGE_TCHAT: {
char name[128];
char text[128];
char parm[128];
msg.ReadString( name, sizeof( name ) );
msg.ReadString( text, sizeof( text ) );
// This parameter is ignored - it is only used when going to client from server
msg.ReadString( parm, sizeof( parm ) );
mpGame.ProcessChatMessage( clientNum, id == GAME_RELIABLE_MESSAGE_TCHAT, name, text, NULL );
break;
}
case GAME_RELIABLE_MESSAGE_VCHAT: {
int index = msg.ReadLong();
bool team = msg.ReadBits( 1 ) != 0;
mpGame.ProcessVoiceChat( clientNum, team, index );
break;
}
case GAME_RELIABLE_MESSAGE_KILL: {
mpGame.WantKilled( clientNum );
break;
}
case GAME_RELIABLE_MESSAGE_DROPWEAPON: {
mpGame.DropWeapon( clientNum );
break;
}
case GAME_RELIABLE_MESSAGE_CALLVOTE: {
mpGame.ServerCallVote( clientNum, msg );
break;
}
case GAME_RELIABLE_MESSAGE_CASTVOTE: {
bool vote = ( msg.ReadByte() != 0 );
mpGame.CastVote( clientNum, vote );
break;
}
// RAVEN BEGIN
// shouchard: multivalue votes
case GAME_RELIABLE_MESSAGE_CALLPACKEDVOTE: {
mpGame.ServerCallPackedVote( clientNum, msg );
break;
}
// RAVEN END
#if 0
// uncomment this if you want to track when players are in a menu
case GAME_RELIABLE_MESSAGE_MENU: {
bool menuUp = ( msg.ReadBits( 1 ) != 0 );
break;
}
#endif
case GAME_RELIABLE_MESSAGE_EVENT: {
entityNetEvent_t *event;
// allocate new event
event = eventQueue.Alloc();
eventQueue.Enqueue( event, idEventQueue::OUTOFORDER_DROP );
event->spawnId = msg.ReadBits( 32 );
event->event = msg.ReadByte();
event->time = msg.ReadLong();
event->paramsSize = msg.ReadBits( idMath::BitsForInteger( MAX_EVENT_PARAM_SIZE ) );
if ( event->paramsSize ) {
if ( event->paramsSize > MAX_EVENT_PARAM_SIZE ) {
NetworkEventWarning( event, "invalid param size" );
return;
}
msg.ReadByteAlign();
msg.ReadData( event->paramsBuf, event->paramsSize );
}
break;
}
// RAVEN BEGIN
// jscott: voice comms
case GAME_RELIABLE_MESSAGE_VOICEDATA_CLIENT:
case GAME_RELIABLE_MESSAGE_VOICEDATA_CLIENT_ECHO:
case GAME_RELIABLE_MESSAGE_VOICEDATA_CLIENT_TEST:
case GAME_RELIABLE_MESSAGE_VOICEDATA_CLIENT_ECHO_TEST: {
mpGame.ReceiveAndForwardVoiceData( clientNum, msg, id - GAME_RELIABLE_MESSAGE_VOICEDATA_CLIENT );
break;
}
// ddynerman: stats
case GAME_RELIABLE_MESSAGE_STAT: {
int client = msg.ReadByte();
statManager->SendStat( clientNum, client );
break;
}
// shouchard: voice chat
case GAME_RELIABLE_MESSAGE_VOICECHAT_MUTING: {
int clientDest = msg.ReadByte();
bool mute = ( 0 != msg.ReadByte() );
mpGame.ServerHandleVoiceMuting( clientNum, clientDest, mute );
break;
}
// shouchard: server admin
case GAME_RELIABLE_MESSAGE_SERVER_ADMIN: {
int commandType = msg.ReadByte();
int clientNum = msg.ReadByte();
if ( SERVER_ADMIN_REMOVE_BAN == commandType ) {
mpGame.HandleServerAdminRemoveBan( "" );
} else if ( SERVER_ADMIN_KICK == commandType ) {
mpGame.HandleServerAdminKickPlayer( clientNum );
} else if ( SERVER_ADMIN_FORCE_SWITCH == commandType ) {
mpGame.HandleServerAdminForceTeamSwitch( clientNum );
} else {
Warning( "Server admin packet with bad type %d", commandType );
}
break;
}
// mekberg: get ban list for server
case GAME_RELIABLE_MESSAGE_GETADMINBANLIST: {
ServerSendBanList( clientNum );
break;
}
// RAVEN END
default: {
Warning( "Unknown client->server reliable message: %d", id );
break;
}
}
}
/*
================
idGameLocal::ClientShowSnapshot
================
*/
void idGameLocal::ClientShowSnapshot( int clientNum ) const {
int baseBits;
idEntity *ent;
idPlayer *player;
idMat3 viewAxis;
idBounds viewBounds;
entityState_t *base;
if ( !net_clientShowSnapshot.GetInteger() ) {
return;
}
player = static_cast<idPlayer *>( entities[clientNum] );
if ( !player ) {
return;
}
viewAxis = player->viewAngles.ToMat3();
viewBounds = player->GetPhysics()->GetAbsBounds().Expand( net_clientShowSnapshotRadius.GetFloat() );
for( ent = snapshotEntities.Next(); ent != NULL; ent = ent->snapshotNode.Next() ) {
if ( net_clientShowSnapshot.GetInteger() == 1 && ent->snapshotBits == 0 ) {
continue;
}
const idBounds &entBounds = ent->GetPhysics()->GetAbsBounds();
if ( !entBounds.IntersectsBounds( viewBounds ) ) {
continue;
}
base = clientEntityStates[clientNum][ent->entityNumber];
if ( base ) {
baseBits = base->state.GetNumBitsWritten();
} else {
baseBits = 0;
}
if ( net_clientShowSnapshot.GetInteger() == 2 && baseBits == 0 ) {
continue;
}
gameRenderWorld->DebugBounds( colorGreen, entBounds );
gameRenderWorld->DrawText( va( "%d: %s (%d,%d bytes of %d,%d)\n", ent->entityNumber,
ent->name.c_str(), ent->snapshotBits >> 3, ent->snapshotBits & 7, baseBits >> 3, baseBits & 7 ),
entBounds.GetCenter(), 0.1f, colorWhite, viewAxis, 1 );
}
}
/*
================
idGameLocal::UpdateLagometer
================
*/
void idGameLocal::UpdateLagometer( int aheadOfServer, int dupeUsercmds ) {
int i, j, ahead;
for ( i = 0; i < LAGO_HEIGHT; i++ ) {
memmove( (byte *)lagometer + LAGO_WIDTH * 4 * i, (byte *)lagometer + LAGO_WIDTH * 4 * i + 4, ( LAGO_WIDTH - 1 ) * 4 );
}
j = LAGO_WIDTH - 1;
for ( i = 0; i < LAGO_HEIGHT; i++ ) {
lagometer[i][j][0] = lagometer[i][j][1] = lagometer[i][j][2] = lagometer[i][j][3] = 0;
}
ahead = idMath::Rint( (float)aheadOfServer / 16.0f );
if ( ahead >= 0 ) {
for ( i = 2 * Max( 0, 5 - ahead ); i < 2 * 5; i++ ) {
lagometer[i][j][1] = 255;
lagometer[i][j][3] = 255;
}
} else {
for ( i = 2 * 5; i < 2 * ( 5 + Min( 10, -ahead ) ); i++ ) {
lagometer[i][j][0] = 255;
lagometer[i][j][1] = 255;
lagometer[i][j][3] = 255;
}
}
for ( i = LAGO_HEIGHT - 2 * Min( 6, dupeUsercmds ); i < LAGO_HEIGHT; i++ ) {
lagometer[i][j][0] = 255;
lagometer[i][j][1] = 255;
lagometer[i][j][3] = 255;
}
}
/*
================
idGameLocal::ClientReadSnapshot
================
*/
void idGameLocal::ClientReadSnapshot( int clientNum, int snapshotSequence, const int gameFrame, const int gameTime, const int dupeUsercmds, const int aheadOfServer, const idBitMsg &msg ) {
int i, entityDefNumber, numBitsRead;
idEntity *ent;
idPlayer *player, *spectated;
pvsHandle_t pvsHandle;
idDict args;
idBitMsgDelta deltaMsg;
snapshot_t *snapshot;
entityState_t *base, *newBase;
int spawnId;
int numSourceAreas, sourceAreas[ idEntity::MAX_PVS_AREAS ];
int proto69TypeNum = 0;
bool proto69 = ( gameLocal.GetCurrentDemoProtocol() == 69 );
const idDeclEntityDef *decl;
if ( net_clientLagOMeter.GetBool() && renderSystem && !IsServerDemo() ) {
UpdateLagometer( aheadOfServer, dupeUsercmds );
if ( !renderSystem->UploadImage( LAGO_IMAGE, (byte *)lagometer, LAGO_IMG_WIDTH, LAGO_IMG_HEIGHT ) ) {
common->Printf( "lagometer: UploadImage failed. turning off net_clientLagOMeter\n" );
net_clientLagOMeter.SetBool( false );
}
}
InitLocalClient( clientNum );
gameRenderWorld->DebugClear( time );
// update the game time
framenum = gameFrame;
time = gameTime;
// RAVEN BEGIN
// bdube: use GetMSec access rather than USERCMD_TIME
previousTime = time - GetMSec();
// RAVEN END
// so that StartSound/StopSound doesn't risk skipping
isNewFrame = true;
// clear the snapshot entity list
snapshotEntities.Clear();
// allocate new snapshot
snapshot = snapshotAllocator.Alloc();
snapshot->sequence = snapshotSequence;
snapshot->firstEntityState = NULL;
snapshot->next = clientSnapshots[clientNum];
clientSnapshots[clientNum] = snapshot;
#if ASYNC_WRITE_TAGS
idRandom tagRandom;
tagRandom.SetSeed( msg.ReadLong() );
#endif
ClientReadUnreliableMessages( msg );
#if ASYNC_WRITE_TAGS
if ( msg.ReadLong() != tagRandom.RandomInt() ) {
Error( "error after read unreliable" );
}
#endif
// read all entities from the snapshot
for ( i = msg.ReadBits( GENTITYNUM_BITS ); i != ENTITYNUM_NONE; i = msg.ReadBits( GENTITYNUM_BITS ) ) {
base = clientEntityStates[clientNum][i];
if ( base ) {
base->state.BeginReading();
}
newBase = entityStateAllocator.Alloc();
newBase->entityNumber = i;
newBase->next = snapshot->firstEntityState;
snapshot->firstEntityState = newBase;
newBase->state.Init( newBase->stateBuf, sizeof( newBase->stateBuf ) );
newBase->state.BeginWriting();
numBitsRead = msg.GetNumBitsRead();
deltaMsg.InitReading( base ? &base->state : NULL, &newBase->state, &msg );
spawnId = deltaMsg.ReadBits( 32 - GENTITYNUM_BITS );
if ( proto69 ) {
proto69TypeNum = deltaMsg.ReadBits( idClass::GetTypeNumBits() );
}
entityDefNumber = deltaMsg.ReadBits( entityDefBits );
ent = entities[i];
// if there is no entity or an entity of the wrong type
if ( !ent || ent->entityDefNumber != entityDefNumber || spawnId != spawnIds[ i ] ) {
if ( i < MAX_CLIENTS && ent ) {
// SPAWN_PLAYER should be taking care of spawning the entity with the right spawnId
common->Warning( "ClientReadSnapshot: recycling client entity %d\n", i );
}
delete ent;
spawnCount = spawnId;
args.Clear();
args.SetInt( "spawn_entnum", i );
args.Set( "name", va( "entity%d", i ) );
// assume any items spawned from a server-snapshot are in our instance
if ( gameLocal.GetLocalPlayer() ) {
args.SetInt( "instance", gameLocal.GetLocalPlayer()->GetInstance() );
}
if ( entityDefNumber >= 0 ) {
if ( entityDefNumber >= declManager->GetNumDecls( DECL_ENTITYDEF ) ) {
Error( "server has %d entityDefs instead of %d", entityDefNumber, declManager->GetNumDecls( DECL_ENTITYDEF ) );
}
decl = static_cast< const idDeclEntityDef * >( declManager->DeclByIndex( DECL_ENTITYDEF, entityDefNumber, false ) );
assert( decl && decl->GetType() == DECL_ENTITYDEF );
args.Set( "classname", decl->GetName() );
if ( !SpawnEntityDef( args, &ent ) || !entities[i] ) {
Error( "Failed to spawn entity with classname '%s' of type '%s'", decl->GetName(), decl->dict.GetString( "spawnclass" ) );
}
} else {
// we no longer support spawning entities by type num only. we would only hit this when playing 1.2 demos for backward compatibility
assert( proto69 );
switch ( proto69TypeNum ) {
case 183:
ent = SpawnEntityType( rvViewWeapon::GetClassType(), &args, true );
break;
case 182:
ent = SpawnEntityType( idAnimatedEntity::GetClassType(), &args, true );
ent->fl.networkSync = true;
break;
default:
Error( "Unexpected protocol 69 typenum (%d) for spawning entity by type", proto69TypeNum );
}
if ( !entities[i] ) {
Error( "Failed to spawn entity by typenum %d ( protocol 69 backwards compat )", proto69TypeNum );
}
}
if ( i < MAX_CLIENTS && i >= numClients ) {
numClients = i + 1;
}
}
// add the entity to the snapshot list
ent->snapshotNode.AddToEnd( snapshotEntities );
ent->snapshotSequence = snapshotSequence;
// RAVEN BEGIN
// bdube: stale network entities
// Ensure the clipmodel is relinked when transitioning from state
if ( ent->fl.networkStale ) {
ent->GetPhysics()->LinkClip();
}
// RAVEN END
// read the class specific data from the snapshot
ent->ReadFromSnapshot( deltaMsg );
// once we read new snapshot data, unstale the ent
if( ent->fl.networkStale ) {
ent->ClientUnstale();
ent->fl.networkStale = false;
}
ent->snapshotBits = msg.GetNumBitsRead() - numBitsRead;
#if ASYNC_WRITE_TAGS
if ( msg.ReadLong() != tagRandom.RandomInt() ) {
//cmdSystem->BufferCommandText( CMD_EXEC_NOW, "writeGameState" );
assert( entityDefNumber >= 0 );
assert( entityDefNumber < declManager->GetNumDecls( DECL_ENTITYDEF ) );
const char * classname = declManager->DeclByIndex( DECL_ENTITYDEF, entityDefNumber, false )->GetName();
Error( "write to and read from snapshot out of sync for classname '%s'\n", classname );
}
#endif
}
player = static_cast<idPlayer *>( entities[clientNum] );
if ( !player ) {
return;
}
if ( player->spectating && player->spectator != clientNum && entities[ player->spectator ] ) {
spectated = static_cast< idPlayer * >( entities[ player->spectator ] );
} else {
spectated = player;
}
// get PVS for this player
// don't use PVSAreas for networking - PVSAreas depends on animations (and md5 bounds), which are not synchronized
numSourceAreas = gameRenderWorld->BoundsInAreas( spectated->GetPlayerPhysics()->GetAbsBounds(), sourceAreas, idEntity::MAX_PVS_AREAS );
pvsHandle = gameLocal.pvs.SetupCurrentPVS( sourceAreas, numSourceAreas, PVS_NORMAL );
// read the PVS from the snapshot
#if ASYNC_WRITE_PVS
int serverPVS[idEntity::MAX_PVS_AREAS];
i = numSourceAreas;
while ( i < idEntity::MAX_PVS_AREAS ) {
sourceAreas[ i++ ] = 0;
}
for ( i = 0; i < idEntity::MAX_PVS_AREAS; i++ ) {
serverPVS[ i ] = msg.ReadLong();
}
if ( memcmp( sourceAreas, serverPVS, idEntity::MAX_PVS_AREAS * sizeof( int ) ) ) {
common->Warning( "client PVS areas != server PVS areas, sequence 0x%x", snapshotSequence );
for ( i = 0; i < idEntity::MAX_PVS_AREAS; i++ ) {
common->DPrintf( "%3d ", sourceAreas[ i ] );
}
common->DPrintf( "\n" );
for ( i = 0; i < idEntity::MAX_PVS_AREAS; i++ ) {
common->DPrintf( "%3d ", serverPVS[ i ] );
}
common->DPrintf( "\n" );
}
gameLocal.pvs.ReadPVS( pvsHandle, msg );
#endif
for ( i = 0; i < ENTITY_PVS_SIZE; i++ ) {
snapshot->pvs[i] = msg.ReadDeltaLong( clientPVS[clientNum][i] );
}
// RAVEN BEGIN
// ddynerman: performance profiling
net_entsInSnapshot += snapshotEntities.Num();
net_snapshotSize += msg.GetSize();
// RAVEN END
// add entities in the PVS that haven't changed since the last applied snapshot
idEntity *nextSpawnedEnt;
for( ent = spawnedEntities.Next(); ent != NULL; ent = nextSpawnedEnt ) {
nextSpawnedEnt = ent->spawnNode.Next();
// if the entity is already in the snapshot
if ( ent->snapshotSequence == snapshotSequence ) {
continue;
}
// if the entity is not in the snapshot PVS
if ( !( snapshot->pvs[ent->entityNumber >> 5] & ( 1 << ( ent->entityNumber & 31 ) ) ) ) {
if ( !ent->fl.networkSync ) {
// don't do stale / unstale on entities that are not marked network sync
continue;
}
if ( ent->PhysicsTeamInPVS( pvsHandle ) ) {
if ( ent->entityNumber >= MAX_CLIENTS && isMapEntity[ ent->entityNumber ] ) {
// server says it's not in PVS, client says it's in PVS
// if that happens on map entities, most likely something is wrong
// I can see that moving pieces along several PVS could be a legit situation though
// this is a band aid, which means something is not done right elsewhere
if ( net_warnStale.GetInteger() > 1 || ( net_warnStale.GetInteger() == 1 && !ent->fl.networkStale ) ) {
common->Warning( "client thinks map entity 0x%x (%s) is stale, sequence 0x%x", ent->entityNumber, ent->name.c_str(), snapshotSequence );
}
}
// RAVEN BEGIN
// bdube: hide while not in snapshot
if ( !ent->fl.networkStale ) {
if ( ent->ClientStale() ) {
delete ent;
ent = NULL;
} else {
ent->fl.networkStale = true;
}
}
} else {
if ( !ent->fl.networkStale ) {
if ( ent->ClientStale() ) {
delete ent;
ent = NULL;
} else {
ent->fl.networkStale = true;
}
}
}
// RAVEN END
continue;
}
// add the entity to the snapshot list
ent->snapshotNode.AddToEnd( snapshotEntities );
ent->snapshotSequence = snapshotSequence;
ent->snapshotBits = 0;
// RAVEN BEGIN
// bdube: hide while not in snapshot
// Ensure the clipmodel is relinked when transitioning from state
if ( ent->fl.networkStale ) {
ent->GetPhysics()->LinkClip();
}
// RAVEN END
base = clientEntityStates[clientNum][ent->entityNumber];
if ( !base ) {
// entity has probably fl.networkSync set to false
// non netsynced map entities go in and out of PVS, and may need stale/unstale calls
if ( ent->fl.networkStale ) {
ent->ClientUnstale();
ent->fl.networkStale = false;
}
continue;
}
if ( !ent->fl.networkSync ) {
// this is not supposed to happen
// it did however, when restarting a map with a different inhibit of entities caused entity numbers to be laid differently
// an idLight would occupy the entity number of an idItem for instance, and although it's not network-synced ( static level light ),
// the presence of a base would cause the system to think that it is and corrupt things
// we changed the map population so the entity numbers are kept the same no matter how things are inhibited
// this code is left as a fall-through fixup / sanity type of thing
// if this still happens, it's likely "client thinks map entity is stale" is happening as well, and we're still at risk of corruption
Warning( "ClientReadSnapshot: entity %d of type %s is not networkSync and has a snapshot base", ent->entityNumber, ent->GetType()->classname );
entityStateAllocator.Free( clientEntityStates[clientNum][ent->entityNumber] );
clientEntityStates[clientNum][ent->entityNumber] = NULL;
continue;
}
base->state.BeginReading();
deltaMsg.InitReading( &base->state, NULL, (const idBitMsg *)NULL );
spawnId = deltaMsg.ReadBits( 32 - GENTITYNUM_BITS );
if ( proto69 ) {
deltaMsg.ReadBits( idClass::GetTypeNumBits() );
}
entityDefNumber = deltaMsg.ReadBits( entityDefBits );
// read the class specific data from the base state
ent->ReadFromSnapshot( deltaMsg );
// after snapshot read, notify client of unstale
if ( ent->fl.networkStale ) {
ent->ClientUnstale();
ent->fl.networkStale = false;
}
}
// RAVEN BEGIN
// ddynerman: add the ambient lights to the snapshot entities
for( int i = 0; i < ambientLights.Num(); i++ ) {
ambientLights[ i ]->snapshotNode.AddToEnd( snapshotEntities );
ambientLights[ i ]->fl.networkStale = false;
}
// RAVEN END
// free the PVS
pvs.FreeCurrentPVS( pvsHandle );
// read the game and player state from the snapshot
base = clientEntityStates[clientNum][ENTITYNUM_NONE]; // ENTITYNUM_NONE is used for the game and player state
if ( base ) {
base->state.BeginReading();
}
newBase = entityStateAllocator.Alloc();
newBase->entityNumber = ENTITYNUM_NONE;
newBase->next = snapshot->firstEntityState;
snapshot->firstEntityState = newBase;
newBase->state.Init( newBase->stateBuf, sizeof( newBase->stateBuf ) );
newBase->state.BeginWriting();
deltaMsg.InitReading( base ? &base->state : NULL, &newBase->state, &msg );
int targetPlayer = deltaMsg.ReadBits( idMath::BitsForInteger( MAX_CLIENTS ) );
if ( entities[ targetPlayer ] ) {
static_cast< idPlayer* >( entities[ targetPlayer ] )->ReadPlayerStateFromSnapshot( deltaMsg );
} else {
player->ReadPlayerStateFromSnapshot( deltaMsg );
}
ReadGameStateFromSnapshot( deltaMsg );
// visualize the snapshot
ClientShowSnapshot( clientNum );
// process entity events
ClientProcessEntityNetworkEventQueue();
}
/*
===============
idGameLocal::ClientReadServerDemoSnapshot
server demos use a slightly different snapshot format
mostly, we don't need to transmit any PVS visibility information, as we transmit the whole entity activity
plus, we read that data to the virtual 'seeing it all' MAX_CLIENTS client
===============
*/
void idGameLocal::ClientReadServerDemoSnapshot( int sequence, const int gameFrame, const int gameTime, const idBitMsg &msg ) {
int i;
snapshot_t *snapshot;
entityState_t *base, *newBase;
idBitMsgDelta deltaMsg;
int numBitsRead, spawnId, entityDefNumber;
idEntity *ent;
idDict args;
const idDeclEntityDef *decl;
int proto69TypeNum = 0;
bool proto69 = ( gameLocal.GetCurrentDemoProtocol() == 69 );
bool ret = ClientApplySnapshot( MAX_CLIENTS, sequence - 1 );
ret = ret; // silence warning
assert( ret || sequence == 1 ); // past the first snapshot of the server demo stream, there's always exactly one to clear
gameRenderWorld->DebugClear( time );
framenum = gameFrame;
time = gameTime;
previousTime = time - GetMSec();
isNewFrame = true;
snapshotEntities.Clear();
snapshot = snapshotAllocator.Alloc();
snapshot->sequence = sequence;
snapshot->firstEntityState = NULL;
snapshot->next = clientSnapshots[ MAX_CLIENTS ];
clientSnapshots[ MAX_CLIENTS ] = snapshot;
ClientReadUnreliableMessages( msg );
for ( i = msg.ReadBits( GENTITYNUM_BITS ); i != ENTITYNUM_NONE; i = msg.ReadBits( GENTITYNUM_BITS ) ) {
base = clientEntityStates[ MAX_CLIENTS ][i];
if ( base ) {
base->state.BeginReading();
}
newBase = entityStateAllocator.Alloc();
newBase->entityNumber = i;
newBase->next = snapshot->firstEntityState;
snapshot->firstEntityState = newBase;
newBase->state.Init( newBase->stateBuf, sizeof( newBase->stateBuf ) );
newBase->state.BeginWriting();
numBitsRead = msg.GetNumBitsRead();
deltaMsg.InitReading( base ? &base->state : NULL, &newBase->state, &msg );
spawnId = deltaMsg.ReadBits( 32 - GENTITYNUM_BITS );
if ( proto69 ) {
proto69TypeNum = deltaMsg.ReadBits( idClass::GetTypeNumBits() );
}
entityDefNumber = deltaMsg.ReadBits( entityDefBits );
ent = entities[i];
// if there is no entity or an entity of the wrong type
if ( !ent || ent->entityDefNumber != entityDefNumber || spawnId != spawnIds[ i ] ) {
if ( i < MAX_CLIENTS && ent ) {
// SpawnPlayer should be taking care of spawning the entity with the right spawnId
common->Warning( "ClientReadServerDemoSnapshot: recycling client entity %d\n", i );
}
delete ent;
spawnCount = spawnId;
args.Clear();
args.SetInt( "spawn_entnum", i );
args.Set( "name", va( "entity%d", i ) );
// assume any items spawned from a server-snapshot are in our instance
// FIXME: hu ho gonna have to rework that for server demos
if ( gameLocal.GetLocalPlayer() ) {
args.SetInt( "instance", gameLocal.GetLocalPlayer()->GetInstance() );
}
if ( entityDefNumber >= 0 ) {
if ( entityDefNumber >= declManager->GetNumDecls( DECL_ENTITYDEF ) ) {
Error( "server has %d entityDefs instead of %d", entityDefNumber, declManager->GetNumDecls( DECL_ENTITYDEF ) );
}
decl = static_cast< const idDeclEntityDef * >( declManager->DeclByIndex( DECL_ENTITYDEF, entityDefNumber, false ) );
assert( decl && decl->GetType() == DECL_ENTITYDEF );
args.Set( "classname", decl->GetName() );
if ( !SpawnEntityDef( args, &ent ) || !entities[i] ) {
Error( "Failed to spawn entity with classname '%s' of type '%s'", decl->GetName(), decl->dict.GetString( "spawnclass" ) );
}
} else {
// we no longer support spawning entities by type num only. we would only hit this when playing 1.2 demos for backward compatibility
assert( proto69 );
switch ( proto69TypeNum ) {
case 183:
ent = SpawnEntityType( rvViewWeapon::GetClassType(), &args, true );
break;
case 182:
ent = SpawnEntityType( idAnimatedEntity::GetClassType(), &args, true );
ent->fl.networkSync = true;
break;
default:
Error( "Unexpected protocol 69 typenum (%d) for spawning entity by type", proto69TypeNum );
}
if ( !entities[i] ) {
Error( "Failed to spawn entity by typenum %d ( protocol 69 backwards compat )", proto69TypeNum );
}
}
if ( i < MAX_CLIENTS && i >= numClients ) {
numClients = i + 1;
}
}
// add the entity to the snapshot list
ent->snapshotNode.AddToEnd( snapshotEntities );
ent->snapshotSequence = sequence;
// RAVEN BEGIN
// bdube: stale network entities
// Ensure the clipmodel is relinked when transitioning from state
if ( ent->fl.networkStale ) {
ent->GetPhysics()->LinkClip();
}
// RAVEN END
// read the class specific data from the snapshot
ent->ReadFromSnapshot( deltaMsg );
// once we read new snapshot data, unstale the ent
if( ent->fl.networkStale ) {
ent->ClientUnstale();
ent->fl.networkStale = false;
}
ent->snapshotBits = msg.GetNumBitsRead() - numBitsRead;
}
// add entities that haven't changed since the last applied snapshot
idEntity *nextSpawnedEnt;
for( ent = spawnedEntities.Next(); ent != NULL; ent = nextSpawnedEnt ) {
nextSpawnedEnt = ent->spawnNode.Next();
// if the entity is already in the snapshot
if ( ent->snapshotSequence == sequence ) {
continue;
}
// add the entity to the snapshot list
ent->snapshotNode.AddToEnd( snapshotEntities );
ent->snapshotSequence = sequence;
ent->snapshotBits = 0;
// Ensure the clipmodel is relinked when transitioning from stale
if ( ent->fl.networkStale ) {
ent->GetPhysics()->LinkClip();
}
base = clientEntityStates[ MAX_CLIENTS ][ ent->entityNumber ];
if ( !base ) {
// entity has probably fl.networkSync set to false
// non netsynced map entities go in and out of PVS, and may need stale/unstale calls
if ( ent->fl.networkStale ) {
ent->ClientUnstale();
ent->fl.networkStale = false;
}
continue;
}
base->state.BeginReading();
deltaMsg.InitReading( &base->state, NULL, (const idBitMsg *)NULL );
spawnId = deltaMsg.ReadBits( 32 - GENTITYNUM_BITS );
if ( proto69 ) {
deltaMsg.ReadBits( idClass::GetTypeNumBits() );
}
entityDefNumber = deltaMsg.ReadBits( entityDefBits );
// if the entity is not the right type
if ( ent->entityDefNumber != entityDefNumber ) {
// should never happen
common->DWarning( "entity '%s' is not the right type ( 0x%x, expected 0x%x )", ent->GetName(), ent->entityDefNumber, entityDefNumber );
continue;
}
// read the class specific data from the base state
ent->ReadFromSnapshot( deltaMsg );
// after snapshot read, notify client of unstale
if( ent->fl.networkStale ) {
// FIXME: does this happen ( in a server demo replay? )
assert( false );
ent->ClientUnstale();
ent->fl.networkStale = false;
}
}
// RAVEN BEGIN
// ddynerman: add the ambient lights to the snapshot entities
for( i = 0; i < ambientLights.Num(); i++ ) {
ambientLights[ i ]->snapshotNode.AddToEnd( snapshotEntities );
ambientLights[ i ]->fl.networkStale = false;
}
// RAVEN END
// visualize the snapshot
// FIXME
// ClientShowSnapshot( MAX_CLIENTS );
// read the game and player states
base = clientEntityStates[MAX_CLIENTS][ENTITYNUM_NONE]; // ENTITYNUM_NONE is used for the game and player state
if ( base ) {
base->state.BeginReading();
}
newBase = entityStateAllocator.Alloc();
newBase->entityNumber = ENTITYNUM_NONE;
newBase->next = snapshot->firstEntityState;
snapshot->firstEntityState = newBase;
newBase->state.Init( newBase->stateBuf, sizeof( newBase->stateBuf ) );
newBase->state.BeginWriting();
deltaMsg.InitReading( base ? &base->state : NULL, &newBase->state, &msg );
// all the players
for ( i = 0; i < numClients; i++ ) {
if ( entities[i] ) {
assert( entities[i]->IsType( idPlayer::GetClassType() ) );
idPlayer *p = static_cast< idPlayer * >( entities[i] );
p->ReadPlayerStateFromSnapshot( deltaMsg );
}
}
// the game state
ReadGameStateFromSnapshot( deltaMsg );
// process entity events
ClientProcessEntityNetworkEventQueue();
}
/*
================
idGameLocal::ClientApplySnapshot
================
*/
bool idGameLocal::ClientApplySnapshot( int clientNum, int sequence ) {
return ApplySnapshot( clientNum, sequence );
}
/*
================
idGameLocal::ClientProcessEntityNetworkEventQueue
================
*/
void idGameLocal::ClientProcessEntityNetworkEventQueue( void ) {
idEntity *ent;
entityNetEvent_t *event;
idBitMsg eventMsg;
while( eventQueue.Start() ) {
event = eventQueue.Start();
// only process forward, in order
if ( event->time > time ) {
break;
}
idEntityPtr< idEntity > entPtr;
if( !entPtr.SetSpawnId( event->spawnId ) ) {
if( !gameLocal.entities[ event->spawnId & ( ( 1 << GENTITYNUM_BITS ) - 1 ) ] ) {
// if new entity exists in this position, silently ignore
NetworkEventWarning( event, "Entity does not exist any longer, or has not been spawned yet." );
}
} else {
ent = entPtr.GetEntity();
assert( ent );
eventMsg.Init( event->paramsBuf, sizeof( event->paramsBuf ) );
eventMsg.SetSize( event->paramsSize );
eventMsg.BeginReading();
if ( !ent->ClientReceiveEvent( event->event, event->time, eventMsg ) ) {
NetworkEventWarning( event, "unknown event" );
}
}
#ifdef _DEBUG
entityNetEvent_t* freedEvent = eventQueue.Dequeue();
assert( freedEvent == event );
#else
eventQueue.Dequeue();
#endif
eventQueue.Free( event );
}
}
// RAVEN BEGIN
// bdube: client side hitscan
/*
================
idGameLocal::ClientHitScan
================
*/
void idGameLocal::ClientHitScan( const idBitMsg &msg ) {
int hitscanDefIndex;
idVec3 muzzleOrigin;
idVec3 dir;
idVec3 fxOrigin;
const idDeclEntityDef *decl;
int num_hitscans;
int i;
idEntity *owner;
assert( isClient );
hitscanDefIndex = msg.ReadLong();
decl = static_cast< const idDeclEntityDef *>( declManager->DeclByIndex( DECL_ENTITYDEF, hitscanDefIndex ) );
if ( !decl ) {
common->Warning( "idGameLocal::ClientHitScan: entity def index %d not found\n", hitscanDefIndex );
return;
}
num_hitscans = decl->dict.GetInt( "hitscans", "1" );
owner = entities[ msg.ReadBits( idMath::BitsForInteger( MAX_CLIENTS ) ) ];
muzzleOrigin[0] = msg.ReadFloat();
muzzleOrigin[1] = msg.ReadFloat();
muzzleOrigin[2] = msg.ReadFloat();
fxOrigin[0] = msg.ReadFloat();
fxOrigin[1] = msg.ReadFloat();
fxOrigin[2] = msg.ReadFloat();
// one direction sent per hitscan
for( i = 0; i < num_hitscans; i++ ) {
dir = msg.ReadDir( 24 );
gameLocal.HitScan( decl->dict, muzzleOrigin, dir, fxOrigin, owner );
}
}
// RAVEN END
/*
================
idGameLocal::ClientProcessReliableMessage
================
*/
void idGameLocal::ClientProcessReliableMessage( int clientNum, const idBitMsg &msg ) {
int id;
idDict backupSI;
InitLocalClient( clientNum );
if ( serverDemo ) {
assert( demoState == DEMO_PLAYING );
int record_type = msg.ReadByte();
assert( record_type < DEMO_RECORD_COUNT );
// if you need to do some special filtering:
switch ( record_type ) {
case DEMO_RECORD_CLIENTNUM: {
msg.ReadByte();
/*
int client = msg.ReadByte();
if ( client != -1 ) {
// reliable was targetted
if ( followPlayer != client ) {
// we're free flying or following someone else
return;
}
}
*/
break;
}
case DEMO_RECORD_EXCLUDE: {
int exclude = msg.ReadByte();
exclude = exclude; // silence warning
assert( exclude != -1 );
/*
if ( exclude == followPlayer ) {
return;
}
*/
break;
}
}
}
id = msg.ReadByte();
switch( id ) {
case GAME_RELIABLE_MESSAGE_SPAWN_PLAYER: {
int client = msg.ReadByte();
int spawnId = msg.ReadLong();
if ( !entities[ client ] ) {
SpawnPlayer( client );
entities[ client ]->FreeModelDef();
}
// fix up the spawnId to match what the server says
// otherwise there is going to be a bogus delete/new of the client entity in the first ClientReadFromSnapshot
spawnIds[ client ] = spawnId;
break;
}
case GAME_RELIABLE_MESSAGE_DELETE_ENT: {
int spawnId = msg.ReadBits( 32 );
idEntityPtr< idEntity > entPtr;
if( !entPtr.SetSpawnId( spawnId ) ) {
break;
}
if( entPtr.GetEntity() && entPtr.GetEntity()->entityNumber < MAX_CLIENTS ) {
delete entPtr.GetEntity();
gameLocal.mpGame.UpdatePlayerRanks();
} else {
delete entPtr.GetEntity();
}
break;
}
case GAME_RELIABLE_MESSAGE_CHAT:
case GAME_RELIABLE_MESSAGE_TCHAT: { // (client should never get a TCHAT though)
char name[128];
char text[128];
char parm[128];
msg.ReadString( name, sizeof( name ) );
msg.ReadString( text, sizeof( text ) );
msg.ReadString( parm, sizeof( parm ) );
idStr temp = va( "%s%s", common->GetLocalizedString( text ), parm );
mpGame.AddChatLine( "%s^0: %s\n", name, temp.c_str() );
break;
}
case GAME_RELIABLE_MESSAGE_DB: {
msg_evt_t msg_evt = (msg_evt_t)msg.ReadByte();
int parm1, parm2;
parm1 = msg.ReadByte( );
parm2 = msg.ReadByte( );
mpGame.PrintMessageEvent( -1, msg_evt, parm1, parm2 );
break;
}
case GAME_RELIABLE_MESSAGE_EVENT: {
entityNetEvent_t *event;
// allocate new event
event = eventQueue.Alloc();
eventQueue.Enqueue( event, idEventQueue::OUTOFORDER_IGNORE );
event->spawnId = msg.ReadBits( 32 );
event->event = msg.ReadByte();
event->time = msg.ReadLong();
event->paramsSize = msg.ReadBits( idMath::BitsForInteger( MAX_EVENT_PARAM_SIZE ) );
if ( event->paramsSize ) {
if ( event->paramsSize > MAX_EVENT_PARAM_SIZE ) {
NetworkEventWarning( event, "invalid param size" );
return;
}
msg.ReadByteAlign();
msg.ReadData( event->paramsBuf, event->paramsSize );
}
break;
}
case GAME_RELIABLE_MESSAGE_SERVERINFO: {
idDict info;
msg.ReadDeltaDict( info, NULL );
SetServerInfo( info );
break;
}
case GAME_RELIABLE_MESSAGE_RESTART: {
MapRestart();
break;
}
case GAME_RELIABLE_MESSAGE_STARTVOTE: {
char voteString[ MAX_STRING_CHARS ];
int clientNum = msg.ReadByte( );
msg.ReadString( voteString, sizeof( voteString ) );
mpGame.ClientStartVote( clientNum, voteString );
break;
}
case GAME_RELIABLE_MESSAGE_PRINT: {
char str[ MAX_PRINT_LEN ] = { '\0' };
msg.ReadString( str, MAX_PRINT_LEN );
mpGame.PrintMessage( -1, str );
break;
}
// RAVEN BEGIN
// shouchard: multifield vote stuff
case GAME_RELIABLE_MESSAGE_STARTPACKEDVOTE: {
voteStruct_t voteData;
memset( &voteData, 0, sizeof( voteData ) );
int clientNum = msg.ReadByte();
voteData.m_fieldFlags = msg.ReadShort();
char mapName[256];
if ( 0 != ( voteData.m_fieldFlags & VOTEFLAG_KICK ) ) {
voteData.m_kick = msg.ReadByte();
}
if ( 0 != ( voteData.m_fieldFlags & VOTEFLAG_MAP ) ) {
msg.ReadString( mapName, sizeof( mapName ) );
voteData.m_map = mapName;
}
if ( 0 != ( voteData.m_fieldFlags & VOTEFLAG_GAMETYPE ) ) {
voteData.m_gameType = msg.ReadByte();
}
if ( 0 != ( voteData.m_fieldFlags & VOTEFLAG_TIMELIMIT ) ) {
voteData.m_timeLimit = msg.ReadByte();
}
if ( 0 != ( voteData.m_fieldFlags & VOTEFLAG_FRAGLIMIT ) ) {
voteData.m_fragLimit = msg.ReadShort();
}
if ( 0 != ( voteData.m_fieldFlags & VOTEFLAG_TOURNEYLIMIT ) ) {
voteData.m_tourneyLimit = msg.ReadShort();
}
if ( 0 != ( voteData.m_fieldFlags & VOTEFLAG_CAPTURELIMIT ) ) {
voteData.m_captureLimit = msg.ReadShort();
}
if ( 0 != ( voteData.m_fieldFlags & VOTEFLAG_BUYING ) ) {
voteData.m_buying = msg.ReadByte();
}
if ( 0 != ( voteData.m_fieldFlags & VOTEFLAG_TEAMBALANCE ) ) {
voteData.m_teamBalance = msg.ReadByte();
}
if ( 0 != ( voteData.m_fieldFlags & VOTEFLAG_CONTROLTIME ) ) {
voteData.m_controlTime = msg.ReadShort();
}
mpGame.ClientStartPackedVote( clientNum, voteData );
break;
}
// RAVEN END
case GAME_RELIABLE_MESSAGE_UPDATEVOTE: {
int result = msg.ReadByte( );
int yesCount = msg.ReadByte( );
int noCount = msg.ReadByte( );
// RAVEN BEGIN
// shouchard: multifield vote stuff
int multiVote = msg.ReadByte( );
voteStruct_t voteData;
char mapNameBuffer[256];
memset( &voteData, 0, sizeof( voteData ) );
if ( multiVote ) {
voteData.m_fieldFlags = msg.ReadShort();
voteData.m_kick = msg.ReadByte();
msg.ReadString( mapNameBuffer, sizeof( mapNameBuffer ) );
voteData.m_map = mapNameBuffer;
voteData.m_gameType = msg.ReadByte();
voteData.m_timeLimit = msg.ReadByte();
voteData.m_fragLimit = msg.ReadShort();
voteData.m_tourneyLimit = msg.ReadShort();
voteData.m_captureLimit = msg.ReadShort();
voteData.m_buying = msg.ReadByte();
voteData.m_teamBalance = msg.ReadByte();
if ( gameLocal.GetCurrentDemoProtocol() == 69 ) {
voteData.m_controlTime = 0;
} else {
voteData.m_controlTime = msg.ReadShort();
}
}
mpGame.ClientUpdateVote( (idMultiplayerGame::vote_result_t)result, yesCount, noCount, voteData );
// RAVEN END
break;
}
case GAME_RELIABLE_MESSAGE_PORTALSTATES: {
int numPortals = msg.ReadLong();
assert( numPortals == gameRenderWorld->NumPortals() );
for ( int i = 0; i < numPortals; i++ ) {
gameRenderWorld->SetPortalState( (qhandle_t) (i+1), msg.ReadBits( NUM_RENDER_PORTAL_BITS ) );
}
break;
}
case GAME_RELIABLE_MESSAGE_PORTAL: {
qhandle_t portal = msg.ReadLong();
int blockingBits = msg.ReadBits( NUM_RENDER_PORTAL_BITS );
assert( portal > 0 && portal <= gameRenderWorld->NumPortals() );
gameRenderWorld->SetPortalState( portal, blockingBits );
break;
}
case GAME_RELIABLE_MESSAGE_STARTSTATE: {
mpGame.ClientReadStartState( msg );
break;
}
// RAVEN BEGIN
// bdube:
case GAME_RELIABLE_MESSAGE_ITEMACQUIRESOUND:
mpGame.PlayGlobalItemAcquireSound( msg.ReadBits ( gameLocal.entityDefBits ) );
break;
// ddynerman: death messagse
case GAME_RELIABLE_MESSAGE_DEATH: {
int attackerEntityNumber = msg.ReadByte( );
int attackerScore = -1;
if( attackerEntityNumber >= 0 && attackerEntityNumber < MAX_CLIENTS ) {
attackerScore = msg.ReadBits( ASYNC_PLAYER_FRAG_BITS );
}
int victimEntityNumber = msg.ReadByte( );
int victimScore = -1;
if( victimEntityNumber >= 0 && victimEntityNumber < MAX_CLIENTS ) {
victimScore = msg.ReadBits( ASYNC_PLAYER_FRAG_BITS );
}
idPlayer* attacker = (attackerEntityNumber != 255 ? static_cast<idPlayer*>(gameLocal.entities[ attackerEntityNumber ]) : NULL);
idPlayer* victim = (victimEntityNumber != 255 ? static_cast<idPlayer*>(gameLocal.entities[ victimEntityNumber ]) : NULL);
int methodOfDeath = msg.ReadByte( );
mpGame.ReceiveDeathMessage( attacker, attackerScore, victim, victimScore, methodOfDeath );
break;
}
// ddynerman: game state
case GAME_RELIABLE_MESSAGE_GAMESTATE: {
mpGame.GetGameState()->ReceiveState( msg );
break;
}
// ddynerman: game stats
case GAME_RELIABLE_MESSAGE_STAT: {
statManager->ReceiveStat( msg );
break;
}
// asalmon: game stats for Xenon receive all client stats
case GAME_RELIABLE_MESSAGE_ALL_STATS: {
statManager->ReceiveAllStats( msg );
break;
}
// ddynerman: multiple instances
case GAME_RELIABLE_MESSAGE_SET_INSTANCE: {
mpGame.ClientSetInstance( msg );
break;
}
// ddynerman: awards
case GAME_RELIABLE_MESSAGE_INGAMEAWARD: {
statManager->ReceiveInGameAward( msg );
break;
}
// mekberg: get ban list for server
case GAME_RELIABLE_MESSAGE_GETADMINBANLIST: {
mpBanInfo_t banInfo;
char name[MAX_STRING_CHARS];
char guid[MAX_STRING_CHARS];
FlushBanList( );
while ( msg.ReadString( name, MAX_STRING_CHARS ) && msg.ReadString( guid, MAX_STRING_CHARS ) ) {
banInfo.name = name;
strncpy( banInfo.guid, guid, CLIENT_GUID_LENGTH );
banList.Append( banInfo );
}
break;
}
// RAVEN END
// RAVEN END
default: {
Error( "Unknown server->client reliable message: %d", id );
break;
}
}
}
// RAVEN BEGIN
/*
================
idGameLocal::ClientRun
Called once each client render frame (before any ClientPrediction frames have been run)
================
*/
void idGameLocal::ClientRun( void ) {
if( isMultiplayer ) {
mpGame.ClientRun();
}
}
/*
================
idGameLocal::ClientEndFrame
Called once each client render frame (after all ClientPrediction frames have been run)
================
*/
void idGameLocal::ClientEndFrame( void ) {
if( isMultiplayer ) {
mpGame.ClientEndFrame();
}
}
/*
================
idGameLocal::ProcessRconReturn
================
*/
void idGameLocal::ProcessRconReturn( bool success ) {
if( isMultiplayer ) {
mpGame.ProcessRconReturn( success );
}
}
/*
================
idGameLocal::ResetGuiRconStatus
================
*/
void idGameLocal::ResetRconGuiStatus( void ) {
if( isMultiplayer ) {
mpGame.ResetRconGuiStatus( );
}
}
// RAVEN END
/*
================
idGameLocal::ClientPrediction
server demos: clientNum == MAX_CLIENTS
================
*/
gameReturn_t idGameLocal::ClientPrediction( int clientNum, const usercmd_t *clientCmds, bool lastPredictFrame, ClientStats_t *cs ) {
idEntity *ent;
idPlayer *player; // may be NULL when predicting for a server demo
gameReturn_t ret;
ret.sessionCommand[ 0 ] = '\0';
if ( clientNum == MAX_CLIENTS ) {
// clientCmds[ MAX_CLIENTS ] has the local interaction
// firing -> cycle follow players, jump -> free fly and cycle map spawns
int btn_mask;
player = NULL;
oldUsercmd = usercmd;
usercmd = clientCmds[ MAX_CLIENTS ];
btn_mask = usercmd.buttons ^ oldUsercmd.buttons;
if ( usercmd.buttons & btn_mask & BUTTON_ATTACK ) {
// find the next suitable player to follow
int delta = 0;
while ( true ) {
int i_next = GetNextClientNum( followPlayer );
if ( followPlayer < i_next ) {
delta += i_next - followPlayer;
} else {
delta += numClients - followPlayer + i_next;
}
if ( delta > numClients ) {
// tried them all, no fit
followPlayer = -1;
break;
}
followPlayer = i_next;
if ( !entities[ followPlayer ] ) {
continue;
}
idPlayer *p = static_cast< idPlayer * >( entities[ followPlayer ] );
if ( p->spectating ) {
continue;
}
// Tourney games, we only record instance 0, only cycle on instance 0 players
if ( p->GetInstance() != 0 ) {
continue;
}
break;
}
}
if ( usercmd.upmove & !oldUsercmd.upmove ) {
if ( followPlayer != -1 ) {
// set yourself up a bit above whoever you were following
freeView.SetFreeView( followPlayer );
} else {
// pick a random spawn spot to start flying from
freeView.PickRandomSpawn();
}
followPlayer = -1;
}
player = NULL;
if ( followPlayer >= 0 ) {
player = static_cast< idPlayer* >( entities[ followPlayer ] );
if ( !player ) {
// that player we were following was removed from the game
freeView.PickRandomSpawn();
} else if ( player->spectating ) {
// our followed player went spectator, go free fly
freeView.SetFreeView( followPlayer );
player = NULL;
followPlayer = -1;
}
}
if ( !player && !freeView.Initialized() ) {
freeView.PickRandomSpawn();
}
} else {
player = static_cast<idPlayer *>( entities[clientNum] );
}
// RAVEN BEGIN
// bdube: added advanced debug support
if ( g_showDebugHud.GetInteger() && net_entsInSnapshot && net_snapshotSize) {
gameDebug.SetInt( "snap_ents", net_entsInSnapshot );
gameDebug.SetInt( "snap_size", net_snapshotSize );
net_entsInSnapshot = 0;
net_snapshotSize = 0;
}
if ( clientNum == localClientNum ) {
gameDebug.BeginFrame( );
gameLog->BeginFrame( time );
}
isLastPredictFrame = lastPredictFrame;
// RAVEN END
// check for local client lag
if ( player ) {
if ( networkSystem->ClientGetTimeSinceLastPacket() >= net_clientMaxPrediction.GetInteger() ) {
player->isLagged = true;
} else {
player->isLagged = false;
}
}
InitLocalClient( clientNum );
// update the game time
framenum++;
previousTime = time;
// RAVEN BEGIN
// bdube: use GetMSec access rather than USERCMD_TIME
time += GetMSec();
// RAVEN END
// update the real client time and the new frame flag
if ( time > realClientTime ) {
realClientTime = time;
isNewFrame = true;
} else {
isNewFrame = false;
}
if ( cs ) {
cs->isLastPredictFrame = isLastPredictFrame;
cs->isLagged = player ? player->isLagged : false;
cs->isNewFrame = isNewFrame;
}
// set the user commands for this frame
// RAVEN BEGIN
usercmds = clientCmds;
// RAVEN END
if ( clientNum == MAX_CLIENTS && !player ) {
freeView.Fly( usercmd );
}
// TMP
bool verbose = cvarSystem->GetCVarBool( "verbose_predict" );
// run prediction on all entities from the last snapshot
for ( ent = snapshotEntities.Next(); ent != NULL; ent = ent->snapshotNode.Next() ) {
#if 0
ent->thinkFlags |= TH_PHYSICS;
ent->ClientPredictionThink();
#else
// don't force TH_PHYSICS on, only call ClientPredictionThink if thinkFlags != 0
// it's better to synchronize TH_PHYSICS on specific entities when needed ( movers may be trouble )
// thinkMask is a temp thing see if there are problems with only checking for TH_PHYSICS
if ( ent->thinkFlags != 0 ) {
if ( verbose ) {
common->Printf( "%d: %s %d\n", ent->entityNumber, ent->GetType()->classname, ent->thinkFlags );
}
ent->ClientPredictionThink();
} else {
if ( verbose ) {
common->Printf( "skip %d: %s %d\n", ent->entityNumber, ent->GetType()->classname, ent->thinkFlags );
}
}
#endif
}
// RAVEN BEGIN
// bdube: client entities
// run client entities
if ( isNewFrame ) {
// rjohnson: only run the entire logic when it is a new frame
rvClientEntity* cent;
for ( cent = clientSpawnedEntities.Next(); cent != NULL; cent = cent->spawnNode.Next() ) {
cent->Think();
}
}
// RAVEN END
// service any pending events
idEvent::ServiceEvents();
// show any debug info for this frame
if ( isNewFrame ) {
RunDebugInfo();
D_DrawDebugLines();
}
if ( sessionCommand.Length() ) {
strncpy( ret.sessionCommand, sessionCommand, sizeof( ret.sessionCommand ) );
sessionCommand = "";
}
// RAVEN BEGIN
// ddynerman: client logging/debugging
if ( clientNum == localClientNum ) {
gameDebug.EndFrame();
gameLog->EndFrame();
}
// RAVEN END
g_simpleItems.ClearModified();
return ret;
}
/*
===============
idGameLocal::Tokenize
===============
*/
void idGameLocal::Tokenize( idStrList &out, const char *in ) {
char buf[ MAX_STRING_CHARS ];
char *token, *next;
idStr::Copynz( buf, in, MAX_STRING_CHARS );
token = buf;
next = strchr( token, ';' );
while ( token ) {
if ( next ) {
*next = '\0';
}
idStr::ToLower( token );
out.Append( token );
if ( next ) {
token = next + 1;
next = strchr( token, ';' );
} else {
token = NULL;
}
}
}
/*
===============
idGameLocal::DownloadRequest
===============
*/
bool idGameLocal::DownloadRequest( const char *IP, const char *guid, const char *paks, char urls[ MAX_STRING_CHARS ] ) {
if ( !cvarSystem->GetCVarInteger( "net_serverDownload" ) ) {
return false;
}
if ( cvarSystem->GetCVarInteger( "net_serverDownload" ) == 1 ) {
// 1: single URL redirect
if ( !strlen( cvarSystem->GetCVarString( "si_serverURL" ) ) ) {
common->Warning( "si_serverURL not set" );
return false;
}
idStr::snPrintf( urls, MAX_STRING_CHARS, "1;%s", cvarSystem->GetCVarString( "si_serverURL" ) );
return true;
} else {
// 2: table of pak URLs
// first token is the game pak if requested, empty if not requested by the client
// there may be empty tokens for paks the server couldn't pinpoint - the order matters
idStr reply = "2;";
idStrList dlTable, pakList;
bool matchAll = false;
int i, j;
if ( !idStr::Icmp( cvarSystem->GetCVarString( "net_serverDlTable" ), "*" ) ) {
matchAll = true;
} else {
Tokenize( dlTable, cvarSystem->GetCVarString( "net_serverDlTable" ) );
}
Tokenize( pakList, paks );
for ( i = 0; i < pakList.Num(); i++ ) {
if ( i > 0 ) {
reply += ";";
}
if ( pakList[ i ][ 0 ] == '\0' ) {
if ( i == 0 ) {
// pak 0 will always miss when client doesn't ask for game bin
common->DPrintf( "no game pak request\n" );
} else {
common->DPrintf( "no pak %d\n", i );
}
continue;
}
if ( matchAll ) {
idStr url = cvarSystem->GetCVarString( "net_serverDlBaseURL" );
url.AppendPath( pakList[i] );
reply += url;
common->Printf( "download for %s: %s\n", IP, url.c_str() );
} else {
for ( j = 0; j < dlTable.Num(); j++ ) {
if ( !pakList[ i ].Icmp( dlTable[ j ] ) ) {
break;
}
}
if ( j == dlTable.Num() ) {
common->Printf( "download for %s: pak not matched: %s\n", IP, pakList[ i ].c_str() );
} else {
idStr url = cvarSystem->GetCVarString( "net_serverDlBaseURL" );
url.AppendPath( dlTable[ j ] );
reply += url;
common->Printf( "download for %s: %s\n", IP, url.c_str() );
}
}
}
idStr::Copynz( urls, reply, MAX_STRING_CHARS );
return true;
}
}
/*
===============
idGameLocal::HTTPRequest
===============
*/
bool idGameLocal::HTTPRequest( const char *IP, const char *file, bool isGamePak ) {
return false;
}
/*
===============
idEventQueue::Alloc
===============
*/
entityNetEvent_t* idEventQueue::Alloc() {
entityNetEvent_t* event = eventAllocator.Alloc();
event->prev = NULL;
event->next = NULL;
return event;
}
/*
===============
idEventQueue::Free
===============
*/
void idEventQueue::Free( entityNetEvent_t *event ) {
// should only be called on an unlinked event!
assert( !event->next && !event->prev );
eventAllocator.Free( event );
}
/*
===============
idEventQueue::Shutdown
===============
*/
void idEventQueue::Shutdown() {
eventAllocator.Shutdown();
this->Init();
}
/*
===============
idEventQueue::Init
===============
*/
void idEventQueue::Init( void ) {
start = NULL;
end = NULL;
}
/*
===============
idEventQueue::Dequeue
===============
*/
entityNetEvent_t* idEventQueue::Dequeue( void ) {
entityNetEvent_t* event = start;
if ( !event ) {
return NULL;
}
start = start->next;
if ( !start ) {
end = NULL;
} else {
start->prev = NULL;
}
event->next = NULL;
event->prev = NULL;
return event;
}
/*
===============
idEventQueue::RemoveLast
===============
*/
entityNetEvent_t* idEventQueue::RemoveLast( void ) {
entityNetEvent_t *event = end;
if ( !event ) {
return NULL;
}
end = event->prev;
if ( !end ) {
start = NULL;
} else {
end->next = NULL;
}
event->next = NULL;
event->prev = NULL;
return event;
}
/*
===============
idEventQueue::Enqueue
===============
*/
void idEventQueue::Enqueue( entityNetEvent_t *event, outOfOrderBehaviour_t behaviour ) {
if ( behaviour == OUTOFORDER_DROP ) {
// go backwards through the queue and determine if there are
// any out-of-order events
while ( end && end->time > event->time ) {
entityNetEvent_t *outOfOrder = RemoveLast();
common->DPrintf( "WARNING: new event with id %d ( time %d ) caused removal of event with id %d ( time %d ), game time = %d.\n", event->event, event->time, outOfOrder->event, outOfOrder->time, gameLocal.time );
Free( outOfOrder );
}
} else if ( behaviour == OUTOFORDER_SORT && end ) {
// NOT TESTED -- sorting out of order packets hasn't been
// tested yet... wasn't strictly necessary for
// the patch fix.
entityNetEvent_t *cur = end;
// iterate until we find a time < the new event's
while ( cur && cur->time > event->time ) {
cur = cur->prev;
}
if ( !cur ) {
// add to start
event->next = start;
event->prev = NULL;
start = event;
} else {
// insert
event->prev = cur;
event->next = cur->next;
cur->next = event;
}
return;
}
// add the new event
event->next = NULL;
event->prev = NULL;
if ( end ) {
end->next = event;
event->prev = end;
} else {
start = event;
}
end = event;
}
// RAVEN BEGIN
// shouchard: ban list stuff here
/*
================
idGameLocal::LoadBanList
================
*/
void idGameLocal::LoadBanList() {
// open file
idStr token;
idFile *banFile = fileSystem->OpenFileRead( BANLIST_FILENAME );
mpBanInfo_t banInfo;
if ( NULL == banFile ) {
common->DPrintf( "idGameLocal::LoadBanList: unable to open ban list file!\n" ); // fixme: need something better here
return;
}
// parse file (read three consecutive strings per banInfo (real complex ;) ) )
while ( banFile->ReadString( token ) > 0 ) {
// name
banInfo.name = token;
// guid
if ( banFile->ReadString( token ) > 0 && token.Length() >= 11 ) {
idStr::Copynz( banInfo.guid, token.c_str(), CLIENT_GUID_LENGTH );
banList.Append( banInfo );
continue;
}
gameLocal.Warning( "idGameLocal::LoadBanList: Potential curruption of banlist file (%s).", BANLIST_FILENAME );
}
fileSystem->CloseFile( banFile );
banListLoaded = true;
banListChanged = false;
}
/*
================
idGameLocal::SaveBanList
================
*/
void idGameLocal::SaveBanList() {
if ( !banListChanged ) {
return;
}
// open file
idFile *banFile = fileSystem->OpenFileWrite( BANLIST_FILENAME );
if ( NULL == banFile ) {
common->DPrintf( "idGameLocal::SaveBanList: unable to open ban list file!\n" ); // fixme: need something better here
return;
}
for ( int i = 0; i < banList.Num(); i++ ) {
const mpBanInfo_t& banInfo = banList[ i ];
char temp[ 16 ] = { 0, };
banFile->WriteString( va( "%s", banInfo.name.c_str() ) );
idStr::Copynz( temp, banInfo.guid, CLIENT_GUID_LENGTH );
banFile->WriteString( temp );
// idStr::Copynz( temp, (const char*)banInfo.ip, 15 );
// banFile->WriteString( "255.255.255.255" );
}
fileSystem->CloseFile( banFile );
banListChanged = false;
}
/*
================
idGameLocal::FlushBanList
================
*/
void idGameLocal::FlushBanList() {
banList.Clear();
banListLoaded = false;
banListChanged = false;
}
/*
================
idGameLocal::IsPlayerBanned
================
*/
bool idGameLocal::IsPlayerBanned( const char *name ) {
assert( name );
if ( !banListLoaded ) {
LoadBanList();
}
// check vs. each line in the list, if we found one return true
for ( int i = 0; i < banList.Num(); i++ ) {
if ( 0 == idStr::Icmp( name, banList[ i ].name ) ) {
return true;
}
}
return false;
}
/*
================
idGameLocal::IsGuidBanned
================
*/
bool idGameLocal::IsGuidBanned( const char *guid ) {
assert( guid );
if ( !banListLoaded ) {
LoadBanList();
}
// check vs. each line in the list, if we found one return true
for ( int i = 0; i < banList.Num(); i++ ) {
if ( 0 == idStr::Icmp( guid, banList[ i ].guid ) ) {
return true;
}
}
return false;
}
/*
================
idGameLocal::AddGuidToBanList
================
*/
void idGameLocal::AddGuidToBanList( const char *guid ) {
assert( guid );
if ( !banListLoaded ) {
LoadBanList();
}
mpBanInfo_t banInfo;
char name[ 512 ]; // TODO: clean this up
gameLocal.GetPlayerName( gameLocal.GetClientNumByGuid( guid ), name );
banInfo.name = name;
idStr::Copynz( banInfo.guid, guid, CLIENT_GUID_LENGTH );
// SIMDProcessor->Memset( banInfo.ip, 0xFF, 15 );
banList.Append( banInfo );
banListChanged = true;
}
/*
================
idGameLocal::RemoveGuidFromBanList
================
*/
void idGameLocal::RemoveGuidFromBanList( const char *guid ) {
assert( guid );
if ( !banListLoaded ) {
LoadBanList();
}
// check vs. each line in the list, if we find a match remove it.
for ( int i = 0; i < banList.Num(); i++ ) {
if ( 0 == idStr::Icmp( guid, banList[ i ].guid ) ) {
banList.RemoveIndex( i );
banListChanged = true;
return;
}
}
}
/*
================
idGameLocal::RegisterClientGuid
================
*/
void idGameLocal::RegisterClientGuid( int clientNum, const char *guid ) {
assert( clientNum >= 0 && clientNum < MAX_CLIENTS );
assert( guid );
memset( clientGuids[ clientNum ], 0, CLIENT_GUID_LENGTH ); // just in case
idStr::Copynz( clientGuids[ clientNum ], guid, CLIENT_GUID_LENGTH );
}
/*
================
idGameLocal::GetBanListCount
================
*/
int idGameLocal::GetBanListCount() {
if ( !banListLoaded ) {
LoadBanList();
}
return banList.Num();
}
/*
================
idGameLocal::GetBanListEntry
================
*/
const mpBanInfo_t* idGameLocal::GetBanListEntry( int entry ) {
if ( !banListLoaded ) {
LoadBanList();
}
if ( entry < 0 || entry >= banList.Num() ) {
return NULL;
}
return &banList[ entry ];
}
/*
================
idGameLocal::GetGuidByClientNum
================
*/
const char *idGameLocal::GetGuidByClientNum( int clientNum ) {
assert( clientNum >= 0 && clientNum < numClients );
return clientGuids[ clientNum ];
}
/*
================
idGameLocal::GetClientNumByGuid
================
*/
int idGameLocal::GetClientNumByGuid( const char * guid ) {
assert( guid );
for ( int i = 0; i < MAX_CLIENTS; i++ ) {
if ( !idStr::Icmp( networkSystem->GetClientGUID( i ), guid ) ) {
return i;
}
}
return -1;
}
// mekberg: send ban list to client
/*
================
idGameLocal::ServerSendBanList
================
*/
void idGameLocal::ServerSendBanList( int clientNum ) {
idBitMsg outMsg;
byte msgBuf[ MAX_GAME_MESSAGE_SIZE ];
outMsg.Init( msgBuf, sizeof( msgBuf ) );
outMsg.WriteByte( GAME_RELIABLE_MESSAGE_GETADMINBANLIST ) ;
if ( !banListLoaded ) {
LoadBanList();
}
int i;
int c = banList.Num();
for ( i = 0; i < c; i++ ) {
outMsg.WriteString( banList[ i ].name.c_str() );
outMsg.WriteString( banList[ i ].guid, CLIENT_GUID_LENGTH );
}
networkSystem->ServerSendReliableMessage( clientNum, outMsg );
}
// mekberg: so we can populate ban list outside of multiplayer game
/*
===================
idGameLocal::PopulateBanList
===================
*/
void idGameLocal::PopulateBanList( idUserInterface* hud ) {
if ( !hud ) {
return;
}
int bans = GetBanListCount();
for ( int i = 0; i < bans; i++ ) {
const mpBanInfo_t * banInfo = GetBanListEntry( i );
hud->SetStateString( va( "sa_banList_item_%d", i ), va( "%d: %s\t%s", i+1, banInfo->name.c_str(), banInfo->guid ) );
}
hud->DeleteStateVar( va( "sa_banList_item_%d", bans ) );
hud->SetStateString( "sa_banList_sel_0", "-1" );
// used to trigger a redraw, was slow, and doesn't seem to do anything so took it out. fixes #13675
hud->StateChanged( gameLocal.time, false );
}
// RAVEN END
/*
================
idGameLocal::ServerSendInstanceReliableMessageExcluding
Works like networkSystem->ServerSendReliableMessageExcluding, but only sends to entities in the owner's instance
================
*/
void idGameLocal::ServerSendInstanceReliableMessageExcluding( const idEntity* owner, int excludeClient, const idBitMsg& msg ) {
int i;
assert( isServer );
if ( owner == NULL ) {
networkSystem->ServerSendReliableMessageExcluding( excludeClient, msg );
return;
}
for( i = 0; i < numClients; i++ ) {
if ( i == excludeClient ) {
continue;
}
if( entities[ i ] == NULL ) {
continue;
}
if( entities[ i ]->GetInstance() != owner->GetInstance() ) {
continue;
}
networkSystem->ServerSendReliableMessage( i, msg );
}
}
/*
================
idGameLocal::ServerSendInstanceReliableMessage
Works like networkSystem->ServerSendReliableMessage, but only sends to entities in the owner's instance
================
*/
void idGameLocal::ServerSendInstanceReliableMessage( const idEntity* owner, int clientNum, const idBitMsg& msg ) {
int i;
assert( isServer );
if( owner == NULL ) {
networkSystem->ServerSendReliableMessage( clientNum, msg );
return;
}
if( clientNum == -1 ) {
for( i = 0; i < numClients; i++ ) {
if( entities[ i ] == NULL ) {
continue;
}
if( entities[ i ]->GetInstance() != owner->GetInstance() ) {
continue;
}
networkSystem->ServerSendReliableMessage( i, msg );
}
} else {
if( entities[ clientNum ] && entities[ clientNum ]->GetInstance() == owner->GetInstance() ) {
networkSystem->ServerSendReliableMessage( clientNum, msg );
}
}
}
/*
===============
idGameLocal::SendUnreliableMessage
for spectating support, we have to loop through the clients and emit to the spectator client too
note that a clientNum == -1 means send to everyone
===============
*/
void idGameLocal::SendUnreliableMessage( const idBitMsg &msg, const int clientNum ) {
int icl;
idPlayer *player;
for ( icl = 0; icl < numClients; icl++ ) {
if ( icl == localClientNum ) {
// not to local client
// note that if local is spectated he will still get it
continue;
}
if ( !entities[ icl ] ) {
continue;
}
if ( icl != clientNum ) {
player = static_cast< idPlayer * >( entities[ icl ] );
// drop all clients except the ones that follow the client we emit to
if ( !player->spectating || player->spectator != clientNum ) {
continue;
}
}
unreliableMessages[ icl ].Add( msg.GetData(), msg.GetSize(), false );
}
if ( demoState == DEMO_RECORDING ) {
// record the type and destination for remap on readback
idBitMsg dest;
byte msgBuf[ 16 ];
dest.Init( msgBuf, sizeof( msgBuf ) );
dest.WriteByte( GAME_UNRELIABLE_RECORD_CLIENTNUM );
dest.WriteByte( clientNum );
unreliableMessages[ MAX_CLIENTS ].AddConcat( dest.GetData(), dest.GetSize(), msg.GetData(), msg.GetSize(), false );
}
}
/*
===============
idGameLocal::SendUnreliableMessagePVS
instanceEnt to NULL for no instance checks
excludeClient to -1 for no exclusions
===============
*/
void idGameLocal::SendUnreliableMessagePVS( const idBitMsg &msg, const idEntity *instanceEnt, int area1, int area2 ) {
int icl;
int matchInstance = instanceEnt ? instanceEnt->GetInstance() : -1;
idPlayer *player;
int areas[ 2 ];
int numEvAreas;
numEvAreas = 0;
if ( area1 != -1 ) {
areas[ 0 ] = area1;
numEvAreas++;
}
if ( area2 != -1 ) {
areas[ numEvAreas ] = area2;
numEvAreas++;
}
for ( icl = 0; icl < numClients; icl++ ) {
if ( icl == localClientNum ) {
// local client is always excluded
continue;
}
if ( !entities[ icl ] ) {
continue;
}
if ( matchInstance >= 0 && entities[ icl ]->GetInstance() != matchInstance ) {
continue;
}
if ( clientsPVS[ icl ].i < 0 ) {
// clients for which we don't have PVS info won't get anything
continue;
}
player = static_cast< idPlayer * >( entities[ icl ] );
// if no areas are given, this is a global emit
if ( numEvAreas ) {
// ony send if pvs says this client can see it
if ( !pvs.InCurrentPVS( clientsPVS[ icl ], areas, numEvAreas ) ) {
continue;
}
}
unreliableMessages[ icl ].Add( msg.GetData(), msg.GetSize(), false );
}
if ( demoState == DEMO_RECORDING ) {
// record the target areas to the message
idBitMsg dest;
byte msgBuf[ 16 ];
// Tourney games: only record from instance 0
if ( !instanceEnt || instanceEnt->GetInstance() == 0 ) {
dest.Init( msgBuf, sizeof( msgBuf ) );
dest.WriteByte( GAME_UNRELIABLE_RECORD_AREAS );
dest.WriteLong( area1 );
dest.WriteLong( area2 );
unreliableMessages[ MAX_CLIENTS ].AddConcat( dest.GetData(), dest.GetSize(), msg.GetData(), msg.GetSize(), false );
}
}
}
/*
===============
idGameLocal::ClientReadUnreliableMessages
===============
*/
void idGameLocal::ClientReadUnreliableMessages( const idBitMsg &_msg ) {
idMsgQueue localQueue;
int size;
byte msgBuf[MAX_GAME_MESSAGE_SIZE];
idBitMsg msg;
localQueue.ReadFrom( _msg );
msg.Init( msgBuf, sizeof( msgBuf ) );
while ( localQueue.Get( msg.GetData(), msg.GetMaxSize(), size, false ) ) {
msg.SetSize( size );
msg.BeginReading();
ProcessUnreliableMessage( msg );
msg.BeginWriting();
}
}
/*
===============
idGameLocal::DemoReplayInAreas
checks if our current demo replay view ( server demo ) matches the areas given
===============
*/
bool idGameLocal::IsDemoReplayInAreas( int area1, int area2 ) {
int areas[2];
int numAreas;
idVec3 view;
pvsHandle_t handle;
bool ret;
numAreas = 0;
if ( area1 != -1 ) {
areas[ 0 ] = area1;
numAreas++;
}
if ( area2 != -1 ) {
areas[ numAreas ] = area2;
numAreas++;
}
assert( serverDemo );
assert( demoState == DEMO_PLAYING );
if ( followPlayer == -1 ) {
view = freeView.GetOrigin();
} else {
view = entities[ followPlayer ]->GetPhysics()->GetOrigin();
}
// could probably factorize this, at least for processing all unreliable messages, maybe at a higher level of the loop?
handle = pvs.SetupCurrentPVS( view );
ret = pvs.InCurrentPVS( handle, areas, numAreas );
pvs.FreeCurrentPVS( handle );
return ret;
}
/*
===============
idGameLocal::ProcessUnreliableMessage
===============
*/
void idGameLocal::ProcessUnreliableMessage( const idBitMsg &msg ) {
if ( serverDemo ) {
assert( demoState == DEMO_PLAYING );
int record_type = msg.ReadByte();
assert( record_type < GAME_UNRELIABLE_RECORD_COUNT );
switch ( record_type ) {
case GAME_UNRELIABLE_RECORD_CLIENTNUM: {
int client = msg.ReadByte();
if ( client != -1 ) {
// unreliable was targetted
if ( followPlayer != client ) {
// either free flying, or following someone else
return;
}
}
break;
}
case GAME_UNRELIABLE_RECORD_AREAS: {
int area1 = msg.ReadLong();
int area2 = msg.ReadLong();
if ( !IsDemoReplayInAreas( area1, area2 ) ) {
return;
}
break;
}
}
}
int type = msg.ReadByte();
switch ( type ) {
case GAME_UNRELIABLE_MESSAGE_EVENT: {
idEntityPtr<idEntity> p;
int spawnId = msg.ReadBits( 32 );
p.SetSpawnId( spawnId );
if ( p.GetEntity() ) {
p.GetEntity()->ClientReceiveEvent( msg.ReadByte(), time, msg );
} else {
Warning( "ProcessUnreliableMessage: no local entity 0x%x for event %d", spawnId & ( ( 1 << GENTITYNUM_BITS ) - 1 ), msg.ReadByte() );
}
break;
}
case GAME_UNRELIABLE_MESSAGE_EFFECT: {
idCQuat quat;
idVec3 origin, origin2;
rvClientEffect* effect;
effectCategory_t category;
const idDecl *decl;
decl = idGameLocal::ReadDecl( msg, DECL_EFFECT );
origin.x = msg.ReadFloat( );
origin.y = msg.ReadFloat( );
origin.z = msg.ReadFloat( );
quat.x = msg.ReadFloat( );
quat.y = msg.ReadFloat( );
quat.z = msg.ReadFloat( );
bool loop = msg.ReadBits( 1 ) != 0;
origin2.x = msg.ReadFloat( );
origin2.y = msg.ReadFloat( );
origin2.z = msg.ReadFloat( );
category = ( effectCategory_t )msg.ReadByte();
if ( bse->CanPlayRateLimited( category ) ) {
effect = new rvClientEffect( decl );
effect->SetOrigin( origin );
effect->SetAxis( quat.ToMat3() );
effect->Play( time, loop, origin2 );
}
break;
}
case GAME_UNRELIABLE_MESSAGE_HITSCAN: {
ClientHitScan( msg );
break;
}
#ifdef _USE_VOICECHAT
case GAME_UNRELIABLE_MESSAGE_VOICEDATA_SERVER: {
mpGame.ReceiveAndPlayVoiceData( msg );
break;
}
#else
case GAME_UNRELIABLE_MESSAGE_VOICEDATA_SERVER: {
break;
}
#endif
default: {
Error( "idGameLocal::ProcessUnreliableMessage() - Unknown unreliable message '%d'\n", type );
}
}
}
/*
===============
idGameLocal::WriteNetworkInfo
===============
*/
void idGameLocal::WriteNetworkInfo( idFile* file, int clientNum ) {
int i, j;
snapshot_t *snapshot;
entityState_t *entityState;
if ( !IsServerDemo() ) {
// save the current states
for ( i = 0; i < MAX_GENTITIES; i++ ) {
entityState = clientEntityStates[clientNum][i];
file->WriteBool( !!entityState );
if ( entityState ) {
file->WriteInt( entityState->entityNumber );
file->WriteInt( entityState->state.GetSize() );
file->Write( entityState->state.GetData(), entityState->state.GetSize() );
}
}
// save the PVS states
for ( i = 0; i < MAX_CLIENTS; i++ ) {
for ( j = 0; j < ENTITY_PVS_SIZE; j++ ) {
file->WriteInt( clientPVS[i][j] );
}
}
}
// players ( including local client )
j = 0;
for ( i = 0; i < MAX_CLIENTS; i++ ) {
if ( !entities[i] ) {
continue;
}
j++;
}
file->WriteInt( j );
for ( i = 0; i < MAX_CLIENTS; i++ ) {
if ( !entities[i] ) {
continue;
}
file->WriteInt( i );
file->WriteInt( spawnIds[ i ] );
}
if ( !IsServerDemo() ) {
// write number of snapshots so on readback we know how many to allocate
i = 0;
for ( snapshot = clientSnapshots[ clientNum ]; snapshot; snapshot = snapshot->next ) {
i++;
}
file->WriteInt( i );
for ( snapshot = clientSnapshots[ clientNum ]; snapshot; snapshot = snapshot->next ) {
file->WriteInt( snapshot->sequence );
// write number of entity states in the snapshot
i = 0;
for ( entityState = snapshot->firstEntityState; entityState; entityState = entityState->next ) {
i++;
}
file->WriteInt( i );
for ( entityState = snapshot->firstEntityState; entityState; entityState = entityState->next ) {
file->WriteInt( entityState->entityNumber );
file->WriteInt( entityState->state.GetSize() );
file->Write( entityState->state.GetData(), entityState->state.GetSize() );
}
file->Write( snapshot->pvs, sizeof( snapshot->pvs ) );
}
}
// write the 'initial reliables' data
mpGame.WriteNetworkInfo( file, clientNum );
}
/*
===============
idGameLocal::ReadNetworkInfo
===============
*/
void idGameLocal::ReadNetworkInfo( int gameTime, idFile* file, int clientNum ) {
int i, j, num, numStates, stateSize;
snapshot_t *snapshot, **lastSnap;
entityState_t *entityState, **lastState;
int proto69TypeNum = 0;
bool proto69 = ( gameLocal.GetCurrentDemoProtocol() == 69 );
assert( clientNum == MAX_CLIENTS || !IsServerDemo() );
InitLocalClient( clientNum );
time = gameTime;
previousTime = gameTime;
// force new frame
realClientTime = 0;
isNewFrame = true;
// clear the snapshot entity list
snapshotEntities.Clear();
if ( !IsServerDemo() ) {
for ( i = 0; i < MAX_GENTITIES; i++ ) {
bool isValid;
file->ReadBool( isValid );
if ( isValid ) {
clientEntityStates[clientNum][i] = entityStateAllocator.Alloc();
entityState = clientEntityStates[clientNum][i];
entityState->next = NULL;
file->ReadInt( entityState->entityNumber );
file->ReadInt( stateSize );
entityState->state.Init( entityState->stateBuf, sizeof( entityState->stateBuf ) );
entityState->state.SetSize( stateSize );
file->Read( entityState->state.GetData(), stateSize );
} else {
clientEntityStates[clientNum][i] = NULL;
}
}
for ( i = 0; i < MAX_CLIENTS; i++ ) {
for ( j = 0; j < ENTITY_PVS_SIZE; j++ ) {
file->ReadInt( clientPVS[i][j] );
}
}
}
// spawn player entities. ( numClients is not a count but the watermark of client indexes )
file->ReadInt( num );
for ( i = 0; i < num; i++ ) {
int icl, spawnId;
file->ReadInt( icl );
file->ReadInt( spawnId );
SpawnPlayer( icl );
spawnIds[ icl ] = spawnId;
numClients = icl + 1;
}
if ( !IsServerDemo() ) {
file->ReadInt( num );
lastSnap = &clientSnapshots[ localClientNum ];
for ( i = 0; i < num; i++ ) {
snapshot = snapshotAllocator.Alloc();
snapshot->firstEntityState = NULL;
snapshot->next = NULL;
file->ReadInt( snapshot->sequence );
file->ReadInt( numStates );
lastState = &snapshot->firstEntityState;
for ( j = 0; j < numStates; j++ ) {
entityState = entityStateAllocator.Alloc();
file->ReadInt( entityState->entityNumber );
file->ReadInt( stateSize );
entityState->state.Init( entityState->stateBuf, sizeof( entityState->stateBuf ) );
entityState->state.SetSize( stateSize );
file->Read( entityState->state.GetData(), stateSize );
entityState->next = NULL;
assert( !(*lastState ) );
*lastState = entityState;
lastState = &entityState->next;
}
file->Read( snapshot->pvs, sizeof( snapshot->pvs ) );
assert( !(*lastSnap) );
*lastSnap = snapshot;
lastSnap = &snapshot->next;
}
// spawn entities
for ( i = 0; i < ENTITYNUM_NONE; i++ ) {
int spawnId, entityDefNumber;
idBitMsgDelta deltaMsg;
idDict args;
entityState_t *base = clientEntityStates[clientNum][i];
idEntity *ent = entities[i];
const idDeclEntityDef *decl;
if ( !base ) {
continue;
}
base->state.BeginReading();
deltaMsg.InitReading( &base->state, NULL, NULL );
spawnId = deltaMsg.ReadBits( 32 - GENTITYNUM_BITS );
if ( proto69 ) {
proto69TypeNum = deltaMsg.ReadBits( idClass::GetTypeNumBits() );
}
entityDefNumber = deltaMsg.ReadBits( entityDefBits );
if ( !ent || ent->entityDefNumber != entityDefNumber || spawnId != spawnIds[ i ] ) {
delete ent;
spawnCount = spawnId;
args.Clear();
args.SetInt( "spawn_entnum", i );
args.Set( "name", va( "entity%d", i ) );
// assume any items spawned from a server-snapshot are in our instance
if( gameLocal.GetLocalPlayer() ) {
args.SetInt( "instance", gameLocal.GetLocalPlayer()->GetInstance() );
}
if ( entityDefNumber >= 0 ) {
if ( entityDefNumber >= declManager->GetNumDecls( DECL_ENTITYDEF ) ) {
Error( "server has %d entityDefs instead of %d", entityDefNumber, declManager->GetNumDecls( DECL_ENTITYDEF ) );
}
decl = static_cast< const idDeclEntityDef * >( declManager->DeclByIndex( DECL_ENTITYDEF, entityDefNumber, false ) );
assert( decl && decl->GetType() == DECL_ENTITYDEF );
args.Set( "classname", decl->GetName() );
if ( !SpawnEntityDef( args, &ent ) || !entities[i] ) {
Error( "Failed to spawn entity with classname '%s' of type '%s'", decl->GetName(), decl->dict.GetString("spawnclass") );
}
} else {
// we no longer support spawning entities by type num only. we would only hit this when playing 1.2 demos for backward compatibility
assert( proto69 );
switch ( proto69TypeNum ) {
case 183:
ent = SpawnEntityType( rvViewWeapon::GetClassType(), &args, true );
break;
case 182:
ent = SpawnEntityType( idAnimatedEntity::GetClassType(), &args, true );
ent->fl.networkSync = true;
break;
default:
Error( "Unexpected protocol 69 typenum (%d) for spawning entity by type", proto69TypeNum );
}
if ( !entities[i] ) {
Error( "Failed to spawn entity by typenum %d ( protocol 69 backwards compat )", proto69TypeNum );
}
}
}
// add the entity to the snapshot list
ent->snapshotNode.AddToEnd( snapshotEntities );
// read the class specific data from the snapshot
ent->ReadFromSnapshot( deltaMsg );
// this is useful. for instance on idPlayer, resets stuff so powerups actually appear
ent->ClientUnstale();
}
{
// specific state read for game and player state
idBitMsgDelta deltaMsg;
entityState_t *base = clientEntityStates[clientNum][ENTITYNUM_NONE];
idPlayer *player;
int targetPlayer;
// it's possible to have a recording start right at CS_INGAME and not have a base for reading this yet
if ( base ) {
base->state.BeginReading();
deltaMsg.InitReading( &base->state, NULL, NULL );
targetPlayer = deltaMsg.ReadBits( idMath::BitsForInteger( MAX_CLIENTS ) );
player = static_cast< idPlayer* >( entities[ targetPlayer ] );
if ( !player ) {
Error( "ReadNetworkInfo: no local player entity" );
return;
}
player->ReadPlayerStateFromSnapshot( deltaMsg );
ReadGameStateFromSnapshot( deltaMsg );
}
}
// set self spectating state according to userinfo settings
GetLocalPlayer()->Spectate( idStr::Icmp( userInfo[ clientNum ].GetString( "ui_spectate" ), "Spectate" ) == 0 );
}
// read the 'initial reliables' data
mpGame.ReadNetworkInfo( file, clientNum );
}
/*
============
idGameLocal::SetDemoState
============
*/
void idGameLocal::SetDemoState( demoState_t state, bool _serverDemo, bool _timeDemo ) {
if ( demoState == DEMO_RECORDING && state == DEMO_NONE ) {
ServerClientDisconnect( MAX_CLIENTS );
}
demoState = state;
serverDemo = _serverDemo;
timeDemo = _timeDemo;
if ( demoState == DEMO_NONE ) {
demo_hud = NULL;
demo_mphud = NULL;
demo_cursor = NULL;
}
}
/*
===============
idGameLocal::ValidateDemoProtocol
===============
*/
bool idGameLocal::ValidateDemoProtocol( int minor_ref, int minor ) {
// 1.1 beta : 67
// 1.1 final: 68
// 1.2 : 69
// 1.3 : 71
// let 1.3 play 1.2 demos - keep a careful eye on snapshotting changes
demo_protocol = minor;
return ( minor_ref == minor || ( minor_ref == 71 && minor == 69 ) );
}
/*
===============
idGameLocal::RandomSpawn
===============
*/
idPlayerStart *idGameLocal::RandomSpawn( void ) {
return spawnSpots[ random.RandomInt( spawnSpots.Num() ) ];
}
|
#include "Arduino.h"
#define SWM_ACOMP_I2 1
void analogDetach(uint8_t pin)
{
SCT.detach(pin);
}
void analogWrite(uint8_t pin, uint8_t val)
{
SCT.attach(pin, val / 255.f);
}
#define ACOMP_VOLTAGE_LADDER_STEPS 32
#define ACOMP_VOLTAGE_LADDER_SETTLE_TIME 100 // Arduino takes about 100 usec to read an analog input
int analogRead(uint8_t pin)
{
if (pin == SWM_ACOMP_I2) {
static bool initialized = false;
if (!initialized) {
/* Comparator should be powered up first; use of comparator requires BOD */
LPC_SYSCON->PDRUNCFG &= ~((1 << 15) | (1 << 3));
/* Enable the clock to the comparator register interface */
LPC_SYSCON->SYSAHBCLKCTRL |= (1 << 19) | (1 << 18) | (1 << 7);
/* Reset the analog comparator */
LPC_SYSCON->PRESETCTRL &= ~(1 << 12);
LPC_SYSCON->PRESETCTRL |= (1 << 12);
/* Disable pull-up/pull-down resistor */
LPC_IOCON->PIO0_1 &= ~(0x3 << 3);
/* Enable ACOMP_I2 fixed-pin function. Require to disable CLKIN */
LPC_SWM->PINENABLE0 = (LPC_SWM->PINENABLE0 & ~(1 << 1)) | (1 << 7);
LPC_SYSCON->SYSAHBCLKCTRL &= ~((1 << 18) | (1 << 7));
/* Select voltage ladder as comparator positive voltage input, and ACOMP_I2 as negative voltage input */
LPC_CMP->CTRL = (0x0 << 8) | (0x2 << 11);
initialized = true;
}
byte step;
for (step = 0; step < ACOMP_VOLTAGE_LADDER_STEPS - 1; step++) {
LPC_CMP->LAD = (step << 1) | 0x1;
delayMicroseconds(ACOMP_VOLTAGE_LADDER_SETTLE_TIME);
if (LPC_CMP->CTRL & COMPSTAT)
break;
}
return map(step, 0, ACOMP_VOLTAGE_LADDER_STEPS - 1, 0, 1023);
}
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2009 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser. It may not be distributed
* under any circumstances.
*/
#ifndef COCOA_OPERA_LISTENER_H
#define COCOA_OPERA_LISTENER_H
#include "modules/hardcore/component/OpComponentPlatform.h"
#include "platforms/posix_ipc/posix_ipc_process_manager.h"
class CocoaOperaListener : public OpComponentPlatform
{
public:
CocoaOperaListener(BOOL tracking=FALSE, void*killDate=NULL);
virtual ~CocoaOperaListener();
void SetTracking(BOOL tracking);
void* KillDate() { return m_killDate; }
static CocoaOperaListener* GetListener() {return s_current_opera_listener;}
bool IsInsideProcessEvents() { return m_insideProcessEvents; }
protected:
// Implementation of OpComponentPlatform
virtual void RequestRunSlice(unsigned int limit);
virtual OP_STATUS RequestPeer(int& peer, OpMessageAddress requester, OpComponentType type);
virtual OP_STATUS SendMessage(OpTypedMessage* message);
virtual OP_STATUS ProcessEvents(unsigned int timeout, EventFlags flags);
private:
void* m_data;
void* m_killDate;
void* m_killTimer;
bool m_insideProcessEvents;
static PosixIpcProcessManager s_process_manager;
CocoaOperaListener* m_previous_listener;
static CocoaOperaListener* s_current_opera_listener;
};
extern CocoaOperaListener* gCocoaOperaListener;
#endif // COCOA_OPERA_LISTENER_H
|
#include <iostream>
using std::cerr;
using std::endl;
using std::to_string;
#include "player.h"
int main() {
logger *l = new logger();
player *p = new player(1, l);
bool sts = false;
int rv = 0;
int errors = 0;
p->dump_resources();
rv = p->add_resource(wood);
l->debug("returned " + to_string(rv));
p->dump_resources();
if (p->spend_resource(ore)) {
l->error("Should not be able to spend " + to_string(ore));
errors++;
}
if (errors) {
l->error("Failed tests: " + to_string(errors));
}
else {
l->debug("All tests passed");
}
}//end main()
|
#include <iostream>
#include <string>
#include "src/Utility.h"
#include "src/ResourceManager.h"
#include "src/Input.h"
#include "src/Time.h"
#include "src/Scene.h"
#include "App.h"
int screenWidth = 1280;
int screenHeight = 720;
std::unique_ptr<App> app;
void Draw()
{
app->Draw();
}
void Resize(int width, int height)
{
app->Resize(width, height);
}
void Idle()
{
app->Idle();
}
void Timer(int value) {
glutTimerFunc(1000/60, Timer, 0);
}
int main(int argc, char **argv)
{
glutInit(&argc, argv);
glutInitContextVersion(4, 2);
glutInitContextProfile(GLUT_CORE_PROFILE);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(screenWidth, screenHeight);
glutInitWindowPosition(0, 0);
glutCreateWindow("Museum");
glewInit();
std::cout<<"Vendor: "<< glGetString(GL_VENDOR)<<'\n'; // Returns the vendor
std::cout << "Renderer: " << glGetString(GL_RENDERER)<<'\n'; // Returns a hint to the model
//Bind callback functions
glutDisplayFunc(Draw);
glutIdleFunc(Idle);
glutTimerFunc(1000/60, Timer, 0);
glutReshapeFunc(Resize);
glutKeyboardFunc(Input::InputCallback);
glutKeyboardUpFunc(Input::InputUpCallback);
glutMouseFunc(Input::MouseButtonCallback);
//Both events call the same callback function, to always capture mouse position
glutMotionFunc(Input::MousePosCallback); //when button is pressed
glutPassiveMotionFunc(Input::MousePosCallback); //when no button is pressed
//Enable features
glClearColor(0.3f, 0.3f, 0.3f, 1.0f);
glEnable(GL_DEPTH_TEST);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_CULL_FACE);
Input::Init();
Scene::Init();
app = std::make_unique<App>(screenWidth, screenHeight);
glutMainLoop(); //start
app.reset();
return(0);
}
|
#ifndef _esgui_canvas_intf_h_
#define _esgui_canvas_intf_h_
class ESE_ABSTRACT EsguiCanvasIntf
{
public:
/// @brief Return true if context was initialized
/// @return true, if context instance was initialized, false otherwise
///
virtual bool isInitialized() const ESE_NOTHROW = 0;
/// Lockable interface support
virtual rtosStatus lock() ESE_NOTHROW = 0;
virtual void unlock() ESE_NOTHROW = 0;
#if defined(ESGUI_USE_STD_COLORS) && (0 != ESGUI_USE_STD_COLORS)
# if (ESGUI_USE_STD_COLORS & ESGUI_USE_STD_COLORS_MONO)
virtual ESGUI_COLOR black() const ESE_NOTHROW = 0;
virtual ESGUI_COLOR white() const ESE_NOTHROW = 0;
# endif
# if (ESGUI_USE_STD_COLORS & ESGUI_USE_STD_COLORS_BASIC_MIN)
virtual ESGUI_COLOR darkGrey() const ESE_NOTHROW = 0;
virtual ESGUI_COLOR lightGrey() const ESE_NOTHROW = 0;
virtual ESGUI_COLOR darkRed() const ESE_NOTHROW = 0;
virtual ESGUI_COLOR lightRed() const ESE_NOTHROW = 0;
virtual ESGUI_COLOR darkGreen() const ESE_NOTHROW = 0;
virtual ESGUI_COLOR lightGreen() const ESE_NOTHROW = 0;
virtual ESGUI_COLOR darkBlue() const ESE_NOTHROW = 0;
virtual ESGUI_COLOR lightBlue() const ESE_NOTHROW = 0;
virtual ESGUI_COLOR darkYellow() const ESE_NOTHROW = 0;
virtual ESGUI_COLOR lightYellow() const ESE_NOTHROW = 0;
virtual ESGUI_COLOR magenta() const ESE_NOTHROW = 0;
# endif
#endif
/// @brief Access common canvas string buffer contents
virtual ESE_STR strBufferGet() ESE_NOTHROW = 0;
virtual ESE_CSTR strBufferGet() const ESE_NOTHROW = 0;
virtual int strBufferLengthGet() const ESE_NOTHROW = 0;
/// @brief Direct access to an internal HDC instance
/// @return HDC instance, held internally
///
virtual ESGUI_HDC hdcGet() ESE_NOTHROW = 0;
/// @brief Wrapper around low-level driver screen rotation routine
/// @param [in] rotation One of the screen rotation codes @see ESGUI_SCREEN_ROTATION
/// @return Code of previous screen rotation
///
virtual ESGUI_SCREEN_ROTATION screenRotationSet(ESGUI_SCREEN_ROTATION rotation) ESE_NOTHROW = 0;
/// @brief Get current screen extent rectangle
/// @return constant pointer to the screen rectangle. @see ESGUI_DC
///
virtual const ESGUI_RECT* screenExtGet() const ESE_NOTHROW = 0;
/// @brief Set current clipping rectangle.
/// @param [in] r Clipping rectangle to set. r may be NULL, in which case
/// the clipping rect is equal to screen rect
///
virtual void clipRectSet(const ESGUI_RECT* r) ESE_NOTHROW = 0;
/// @brief return the current clipping rect
/// @return Currently set clipping rect, or entire screen rect, if no clipping was set
///
virtual const ESGUI_RECT* clipRectGet() const ESE_NOTHROW = 0;
/// @brief reset clipping rect to the full screen
///
virtual void clipRectReset() ESE_NOTHROW = 0;
/// @brief Set position update logic
/// @param [in] bUpdate If true, position is updated upon primitive is drawn,
/// otherwise, position is not updated
/// @return Previous value of position update flag
///
virtual bool updatePosSet(bool bUpdate) ESE_NOTHROW = 0;
/// @brief Get current position update logic
/// @return Value of position update flag
///
virtual bool updatePosGet() const ESE_NOTHROW = 0;
/// @brief Set text transparency mode. NB! transparent text rendering is slower than opaque one.
/// @param [in] bOpaque If true, text is drawn opaque, using background color,
/// otherwise, only char pixels are drawn and background is preserved
/// @return Previous value of text opacity flag
///
virtual bool opaqueTextSet(bool bOpaque) ESE_NOTHROW = 0;
/// @brief Query text opacity mode
/// @return Value of text opacity flag
///
virtual bool opaqueTextGet() const ESE_NOTHROW = 0;
/// @brief Set foreground color.
/// @param [in] color New foreground color
/// @return Old foreground color
///
virtual ESGUI_COLOR fgColorSet(ESGUI_COLOR color) ESE_NOTHROW = 0;
/// @brief Get foreground color
/// @return Current foreground color
///
virtual ESGUI_COLOR fgColorGet() const ESE_NOTHROW = 0;
/// @brief Get raw (in screen format) foreground color
/// @return Current raw foreground color
///
virtual ESGUI_Color_t fgColorGetRaw() const ESE_NOTHROW = 0;
/// @brief Set background color.
/// @param [in] color New background color
/// @return Old background color
///
virtual ESGUI_COLOR bgColorSet(ESGUI_COLOR color) ESE_NOTHROW = 0;
/// @brief Get background color
/// @return Current background color
///
virtual ESGUI_COLOR bgColorGet() const ESE_NOTHROW = 0;
/// @brief Get raw (in screen format) background color
/// @return Current raw background color
///
virtual ESGUI_Color_t bgColorGetRaw() const ESE_NOTHROW = 0;
/// @brief Get currently set palette
/// @param [out] pal Currently set palette is copied
///
virtual const ESGUI_PALETTE* paletteGet() const ESE_NOTHROW = 0;
virtual void paletteSet(const ESGUI_PALETTE* pal) ESE_NOTHROW = 0;
/// @brief Reset palette to the system one [bgnd, fg], which is always realized
virtual void sysPaletteSet() ESE_NOTHROW = 0;
/// Realize palette into native driver colours
virtual void realizePaletteFromPalette(ESGUI_PALETTE* dest, const ESGUI_PALETTE* src) ESE_NOTHROW = 0;
virtual void realizePalette(ESGUI_PALETTE* pal, const ESGUI_COLOR* cols, esU32 colCnt) ESE_NOTHROW = 0;
/// Unrealize palette - convert native driver colours palette to the generic ones
virtual void unrealizePalette(ESGUI_COLOR* cols, esU32 colCnt, const ESGUI_PALETTE* pal) ESE_NOTHROW = 0;
#if defined(ESGUI_USE_FONT) && 1 == ESGUI_USE_FONT
/// Set current font
virtual void fontSet(const ESGUI_FONT* fnt) ESE_NOTHROW = 0;
/// Get current font
virtual const ESGUI_FONT* fontGet() const ESE_NOTHROW = 0;
#endif
/// Draw horizontal line, starting from org, with length len
virtual void hline(const ESGUI_POINT* org, int len) ESE_NOTHROW = 0;
virtual void hline(int x, int y, int len) ESE_NOTHROW = 0;
/// Draw vertical line, starting from org, with lenght len
virtual void vline(const ESGUI_POINT* org, int len) ESE_NOTHROW = 0;
virtual void vline(int x, int y, int len) ESE_NOTHROW = 0;
/// Move pen position
virtual void penMove(const ESGUI_POINT* pos) ESE_NOTHROW = 0;
virtual void penMove(int x, int y) ESE_NOTHROW = 0;
/// Draw pixel point at specified position
virtual void point(const ESGUI_POINT* pos) ESE_NOTHROW = 0;
virtual void point(int x, int y) ESE_NOTHROW = 0;
/// Draw rectangle. do not update current position in any way
virtual void rectDraw(const ESGUI_RECT* r) ESE_NOTHROW = 0;
virtual void rectDraw(const ESGUI_POINT* org, const ESGUI_POINT* edge) ESE_NOTHROW = 0;
virtual void rectDraw(int x0, int y0, int x1, int y1) ESE_NOTHROW = 0;
/// Fill rect with background color, do not update current position in any way
virtual void rectFill(const ESGUI_RECT* r) ESE_NOTHROW = 0;
virtual void rectFill(const ESGUI_POINT* org, const ESGUI_POINT* edge) ESE_NOTHROW = 0;
virtual void rectFill(int x0, int y0, int x1, int y1) ESE_NOTHROW = 0;
/// Clear canvas with background color
virtual void clear() ESE_NOTHROW = 0;
/// Draw an arbitrary line
virtual void line(const ESGUI_POINT* beg, const ESGUI_POINT* end) ESE_NOTHROW = 0;
virtual void line(int x0, int y0, int x1, int y1) ESE_NOTHROW = 0;
/// Draw an arbitrary line from the current position
virtual void lineTo(const ESGUI_POINT* end) ESE_NOTHROW = 0;
virtual void lineTo(int x, int y) ESE_NOTHROW = 0;
/// Draw properly clipped circle centered at center, with radius r
virtual void circle(const ESGUI_POINT* center, int r) ESE_NOTHROW = 0;
/// Draw circle centered in rect, with radius equal to minimal rect extent,
/// height or width
///
virtual void circle(const ESGUI_RECT* r) ESE_NOTHROW = 0;
#if defined(ESGUI_USE_FONT) && 1 == ESGUI_USE_FONT
/// Font block management
///
/// Initialize font structure block
virtual void fontInit(ESGUI_FONT* font, const ESGUI_FONT_DATA* block) const ESE_NOTHROW = 0;
/// Append font sub-block to the existing font block chain
virtual void fontBlockAdd(ESGUI_FONT* font, ESGUI_FONT* block) const ESE_NOTHROW = 0;
/// Remove font block from the chain
virtual void fontBlockRemove(ESGUI_FONT* block) const ESE_NOTHROW = 0;
/// String drawing
///
/// Return font height. If NULL, return height of the currently set canvas font
virtual int fontHeightGet(const ESGUI_FONT* fnt = NULL) const ESE_NOTHROW = 0;
/// Return string extent, based on ESGUI_FONT data.
virtual void stringExtentN(const ESGUI_FONT* fnt, ESE_CSTR text, int strlen, int tabWidth, ESGUI_POINT* ext ) ESE_NOTHROW = 0;
virtual void stringExtent(const ESGUI_FONT* fnt, ESE_CSTR text, int tabWidth, ESGUI_POINT* ext ) ESE_NOTHROW = 0;
/// Return string extent when text wrapping is enabled
virtual void stringExtentWrapN(const ESGUI_FONT* fnt, ESE_CSTR text, int strlen, int tabWidth, int width, ESGUI_POINT* ext ) ESE_NOTHROW = 0;
/// Return string extent based on ESGUI_FONT data, when optional string wrapping
/// is enabled.
///
virtual void stringExtentWrap(const ESGUI_FONT* fnt, ESE_CSTR text, int tabWidth, int width, ESGUI_POINT* ext ) ESE_NOTHROW = 0;
typedef void (*CharDrawCallbackT)(EsguiCanvasIntf& canvas, ESGUI_CharCallbackReason reason, ESE_CSTR pos, const ESGUI_RECT* rect, void* data);
/// Draw string of chars
virtual void stringDrawN(const ESGUI_POINT* pos, ESE_CSTR pStr, int strlen, int tabWidth = ESGUI_TAB_WIDTH_STD, EsguiCanvasIntf::CharDrawCallbackT cbk = NULL, void* data = NULL) ESE_NOTHROW = 0;
virtual void stringDrawN(int x, int y, ESE_CSTR pStr, int strlen, int tabWidth = ESGUI_TAB_WIDTH_STD, EsguiCanvasIntf::CharDrawCallbackT cbk = NULL, void* data = NULL) ESE_NOTHROW = 0;
virtual void stringDraw(const ESGUI_POINT* pos, ESE_CSTR pStr, int tabWidth = ESGUI_TAB_WIDTH_STD, EsguiCanvasIntf::CharDrawCallbackT cbk = NULL, void* data = NULL) ESE_NOTHROW = 0;
virtual void stringDraw(int x, int y, ESE_CSTR pStr, int tabWidth = ESGUI_TAB_WIDTH_STD, EsguiCanvasIntf::CharDrawCallbackT cbk = NULL, void* data = NULL) ESE_NOTHROW = 0;
/// Draw string of chars, fitting it into the specified rectangle
/// using text alignment & positioning parameters
///
virtual void stringDrawRect(const ESGUI_RECT* rect, ESE_CSTR pStr, int tabWidth, esU32 flags) ESE_NOTHROW = 0;
#endif // ESGUI_USE_FONT
#if defined(ESGUI_USE_BITMAP) && 1 == ESGUI_USE_BITMAP
/// Return bitmap height, width, and extent
virtual int pictureWidthGet(const ESGUI_BITMAP* bmp) const ESE_NOTHROW = 0;
virtual int pictureHeightGet(const ESGUI_BITMAP* bmp) const ESE_NOTHROW = 0;
virtual ESGUI_POINT pictureExtGet(const ESGUI_BITMAP* bmp) const ESE_NOTHROW = 0;
/// Draw picture using ROP. optional view rect specifies which portion of bitmap should be drawn.
virtual void pictureDrawROP(int x, int y, const ESGUI_BITMAP* bmp, const ESGUI_RECT* view = NULL, ESGUI_BITOP nRop = ESGUI_COPY) ESE_NOTHROW = 0;
virtual void pictureDrawROP(const ESGUI_POINT* pos, const ESGUI_BITMAP* bmp, const ESGUI_RECT* view = NULL, ESGUI_BITOP nRop = ESGUI_COPY) ESE_NOTHROW = 0;
#endif // ESGUI_USE_BITMAP
};
#endif //< _esgui_canvas_intf_h_
|
#include <iberbar/RHI/D3D9/Device.h>
#include <iberbar/RHI/D3D9/Buffer.h>
#include <iberbar/RHI/D3D9/CommandContext.h>
#include <iberbar/RHI/D3D9/Shader.h>
#include <iberbar/RHI/D3D9/VertexDeclaration.h>
#include <iberbar/RHI/D3D9/ShaderState.h>
#include <iberbar/RHI/D3D9/ShaderVariables.h>
#include <iberbar/RHI/D3D9/Texture.h>
#include <iberbar/RHI/D3D9/RenderState.h>
#include <iberbar/RHI/D3D9/Types.h>
#include <iberbar/Utility/OS/Windows/Error.h>
#include <DxErr.h>
iberbar::RHI::D3D9::CDevice::CDevice()
: IDevice( UApiType::D3D9 )
, m_hWnd( nullptr )
, m_hInstance( nullptr )
, m_pD3D( nullptr )
, m_pD3DDevice( nullptr )
, m_pD3DVertexBuffer( nullptr )
, m_nVertexBufferStride( 0 )
, m_pD3DIndexBuffer( nullptr )
, m_pD3DVertexShader( nullptr )
, m_pD3DPixelShader( nullptr )
, m_bIsHardwareVertexProcessing( false )
, m_bIsRendering( false )
, m_bHasLostDevice( false )
, m_pD3DTextures()
, m_D3DPresentParams()
{
memset( m_pD3DTextures, 0, sizeof( m_pD3DTextures ) );
}
iberbar::RHI::D3D9::CDevice::~CDevice()
{
for ( int i = 0; i < 8; i++ )
{
D3D_SAFE_RELEASE( m_pD3DTextures[ i ] );
}
D3D_SAFE_RELEASE( m_pD3DVertexBuffer );
D3D_SAFE_RELEASE( m_pD3DIndexBuffer );
D3D_SAFE_RELEASE( m_pD3DVertexShader );
D3D_SAFE_RELEASE( m_pD3DPixelShader );
D3D_SAFE_RELEASE( m_pD3DDevice );
D3D_SAFE_RELEASE( m_pD3D );
}
void iberbar::RHI::D3D9::CDevice::LostDevice()
{
m_bHasLostDevice = true;
BindVertexBuffer( nullptr, 0 );
BindIndexBuffer( nullptr );
SetVertexShader( nullptr );
SetPixelShader( nullptr );
for ( int i = 0; i < 8; i++ )
{
SetTexture( i, nullptr );
}
if ( m_CallbackLost )
{
m_CallbackLost( this );
}
}
iberbar::CResult iberbar::RHI::D3D9::CDevice::ResetDevice( int nBackBufferWidth, int nBackBufferHeight, bool bIsWindow )
{
m_ContextSize = CSize2i( nBackBufferWidth, nBackBufferHeight );
m_bIsWindow = bIsWindow;
m_D3DPresentParams.BackBufferWidth = nBackBufferWidth;
m_D3DPresentParams.BackBufferHeight = nBackBufferHeight;
m_D3DPresentParams.Windowed = bIsWindow;
HRESULT hResult = m_pD3DDevice->Reset( &m_D3DPresentParams );
if ( FAILED( hResult ) )
{
return MakeResult( ResultCode::Bad, DXGetErrorStringA( hResult ) );
}
if ( m_CallbackReset )
{
CResult ret = m_CallbackReset( this );
if ( ret.IsOK() == false )
return ret;
}
return CResult();
}
void iberbar::RHI::D3D9::CDevice::CreateTexture( ITexture** ppOutTexture )
{
assert( ppOutTexture );
TSmartRefPtr<CTexture> pTexture = TSmartRefPtr<CTexture>::_sNew( this );
UNKNOWN_SAFE_RELEASE_NULL( *ppOutTexture );
(*ppOutTexture) = pTexture;
(*ppOutTexture)->AddRef();
}
iberbar::CResult iberbar::RHI::D3D9::CDevice::CreateVertexBuffer( uint32 nInSize, uint32 nUsage, IVertexBuffer** ppOutBuffer )
{
assert( ppOutBuffer );
TSmartRefPtr<CVertexBuffer> pVertexBuffer = TSmartRefPtr<CVertexBuffer>::_sNew( this, nInSize, nUsage );
CResult ret = pVertexBuffer->Initial();
if ( ret.IsOK() == false )
return ret;
UNKNOWN_SAFE_RELEASE_NULL( *ppOutBuffer );
(*ppOutBuffer) = pVertexBuffer;
(*ppOutBuffer)->AddRef();
return CResult();
}
iberbar::CResult iberbar::RHI::D3D9::CDevice::CreateIndexBuffer( uint32 nStride, uint32 nInSize, uint32 nUsage, IIndexBuffer** ppOutBuffer )
{
assert( ppOutBuffer );
TSmartRefPtr<CIndexBuffer> pIndexBuffer = TSmartRefPtr<CIndexBuffer>::_sNew( this, nInSize, nUsage );
CResult ret = pIndexBuffer->Initial();
if ( ret.IsOK() == false )
return ret;
UNKNOWN_SAFE_RELEASE_NULL( *ppOutBuffer );
(*ppOutBuffer) = pIndexBuffer;
(*ppOutBuffer)->AddRef();
return CResult();
}
iberbar::CResult iberbar::RHI::D3D9::CDevice::CreateVertexShader( IShader** ppOutShader )
{
assert( ppOutShader );
TSmartRefPtr<CVertexShader> pShader = TSmartRefPtr<CVertexShader>::_sNew( this );
UNKNOWN_SAFE_RELEASE_NULL( *ppOutShader );
(*ppOutShader) = pShader;
(*ppOutShader)->AddRef();
return CResult();
}
iberbar::CResult iberbar::RHI::D3D9::CDevice::CreatePixelShader( IShader** ppOutShader )
{
assert( ppOutShader );
TSmartRefPtr<CPixelShader> pShader = TSmartRefPtr<CPixelShader>::_sNew( this );
UNKNOWN_SAFE_RELEASE_NULL( *ppOutShader );
( *ppOutShader ) = pShader;
( *ppOutShader )->AddRef();
return CResult();
}
iberbar::CResult iberbar::RHI::D3D9::CDevice::CreateHullShader( IShader** ppOutShader )
{
return MakeResult( ResultCode::Bad, "Not support hull shader" );
}
iberbar::CResult iberbar::RHI::D3D9::CDevice::CreateGeometryShader( IShader** ppOutShader )
{
return MakeResult( ResultCode::Bad, "Not support geometry shader" );
}
iberbar::CResult iberbar::RHI::D3D9::CDevice::CreateDomainShader( IShader** ppOutShader )
{
return MakeResult( ResultCode::Bad, "Not support domain shader" );
}
iberbar::CResult iberbar::RHI::D3D9::CDevice::CreateComputeShader( IShader** ppOutShader )
{
return MakeResult( ResultCode::Bad, "Not support compute shader" );
}
iberbar::CResult iberbar::RHI::D3D9::CDevice::CreateVertexDeclaration( IVertexDeclaration** ppOutDeclaration, const UVertexElement* pVertexElements, uint32 nVertexElementsCount, uint32 nStride )
{
assert( ppOutDeclaration );
TSmartRefPtr<CVertexDeclaration> pDeclaration = TSmartRefPtr<CVertexDeclaration>::_sNew( this, pVertexElements, nVertexElementsCount, nStride );
CResult ret = pDeclaration->Initial();
if ( ret.IsOK() == false )
return ret;
UNKNOWN_SAFE_RELEASE_NULL( *ppOutDeclaration );
(*ppOutDeclaration) = pDeclaration;
(*ppOutDeclaration)->AddRef();
return CResult();
}
iberbar::CResult iberbar::RHI::D3D9::CDevice::CreateShaderState(
IShaderState** ppOutShaderState,
IVertexDeclaration* pVertexDeclaration,
IShader* pVertexShader,
IShader* pPixelShader,
IShader* pHullShader,
IShader* pGeometryShader,
IShader* pDomainShader )
{
assert( ppOutShaderState );
TSmartRefPtr<CShaderState> pShaderState = TSmartRefPtr<CShaderState>::_sNew( this, (CVertexDeclaration*)pVertexDeclaration, (CVertexShader*)pVertexShader, (CPixelShader*)pPixelShader );
UNKNOWN_SAFE_RELEASE_NULL( *ppOutShaderState );
(*ppOutShaderState) = pShaderState;
(*ppOutShaderState)->AddRef();
return CResult();
}
void iberbar::RHI::D3D9::CDevice::CreateShaderVariableTable( IShaderVariableTable** ppOutShaderVarTable )
{
assert( ppOutShaderVarTable );
TSmartRefPtr<CShaderVariableTable> pShaderVarTable = TSmartRefPtr<CShaderVariableTable>::_sNew( this );
UNKNOWN_SAFE_RELEASE_NULL( *ppOutShaderVarTable );
(*ppOutShaderVarTable) = pShaderVarTable;
(*ppOutShaderVarTable)->AddRef();
}
iberbar::CResult iberbar::RHI::D3D9::CDevice::CreateBlendState( IBlendState** ppOutBlendState, const UBlendDesc& BlendDesc )
{
assert( ppOutBlendState );
TSmartRefPtr<CBlendState> pBlendState = TSmartRefPtr<CBlendState>::_sNew( BlendDesc );
UNKNOWN_SAFE_RELEASE_NULL( *ppOutBlendState );
( *ppOutBlendState ) = pBlendState;
( *ppOutBlendState )->AddRef();
return CResult();
}
iberbar::CResult iberbar::RHI::D3D9::CDevice::CreateDepthStencilState( IDepthStencilState** ppOutDepthStencilState, const UDepthStencilDesc& DepthStencilDesc )
{
assert( ppOutDepthStencilState );
TSmartRefPtr<CDepthStencilState> pDepthStencilState = TSmartRefPtr<CDepthStencilState>::_sNew( DepthStencilDesc );
UNKNOWN_SAFE_RELEASE_NULL( *ppOutDepthStencilState );
(*ppOutDepthStencilState) = pDepthStencilState;
(*ppOutDepthStencilState)->AddRef();
return CResult();
}
iberbar::CResult iberbar::RHI::D3D9::CDevice::CreateSamplerState( ISamplerState** ppOutSamplerState, const UTextureSamplerState& SamplerDesc )
{
assert( ppOutSamplerState );
TSmartRefPtr<CSamplerState> pBlendState = TSmartRefPtr<CSamplerState>::_sNew( SamplerDesc );
UNKNOWN_SAFE_RELEASE_NULL( *ppOutSamplerState );
( *ppOutSamplerState ) = pBlendState;
( *ppOutSamplerState )->AddRef();
return CResult();
}
void iberbar::RHI::D3D9::CDevice::CreateCommandContext( ICommandContext** ppOutContext )
{
assert( ppOutContext );
TSmartRefPtr<CCommandContext> pNewContext = TSmartRefPtr<CCommandContext>::_sNew( this );
UNKNOWN_SAFE_RELEASE_NULL( *ppOutContext );
(*ppOutContext) = pNewContext;
(*ppOutContext)->AddRef();
}
iberbar::CResult iberbar::RHI::D3D9::CDevice::Begin()
{
HRESULT hr;
if ( m_bHasLostDevice == true )
{
if ( FAILED( hr = m_pD3DDevice->TestCooperativeLevel() ) )
{
// the device has been lost but cannot be reset at this time
if ( hr == D3DERR_DEVICELOST )
{
// request repaint and exit
InvalidateRect( m_hWnd, NULL, TRUE );
return MakeResult( ResultCode::Bad, "device lost" );
}
// the device has been lost and can be reset
if ( hr == D3DERR_DEVICENOTRESET )
{
// do lost/reset/restore cycle
LostDevice();
CResult RetReset = ResetDevice();
if ( RetReset.IsOK() == false )
return RetReset;
}
}
m_bHasLostDevice = false;
}
m_pD3DDevice->Clear( NULL, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, (uint32)m_ClearColor, 1.0f, 0 );
m_pD3DDevice->BeginScene();
return CResult();
}
void iberbar::RHI::D3D9::CDevice::End()
{
HRESULT hResult;
m_pD3DDevice->EndScene();
hResult = m_pD3DDevice->Present( NULL, NULL, NULL, NULL );
m_bHasLostDevice = (hResult == D3DERR_DEVICELOST);
}
iberbar::CResult iberbar::RHI::D3D9::CDevice::CreateDevice( HWND hWnd, bool bWindowed, int nSuitedWidth, int nSuitedHeight )
{
assert( m_hWnd == nullptr );
HRESULT hResult = S_OK;
m_hWnd = hWnd;
if ( m_pD3D || m_pD3DDevice )
return MakeResult( ResultCode::Bad, "has been initialized" );
m_pD3D = Direct3DCreate9( D3D_SDK_VERSION );
D3DCAPS9 caps;
m_pD3D->GetDeviceCaps( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, &caps );
int vp = 0;
if ( caps.DevCaps & D3DDEVCAPS_HWTRANSFORMANDLIGHT )
{
vp = D3DCREATE_HARDWARE_VERTEXPROCESSING;
m_bIsHardwareVertexProcessing = true;
}
else
{
vp = D3DCREATE_SOFTWARE_VERTEXPROCESSING;
m_bIsHardwareVertexProcessing = false;
}
// Default to none.
// 默认不使用多采样
D3DMULTISAMPLE_TYPE multiType = D3DMULTISAMPLE_NONE;
// Check if 4x AA is supported, if so use it.
// 检查是否支持4倍速率采样
if ( m_pD3D->CheckDeviceMultiSampleType( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, D3DFMT_D16, TRUE, D3DMULTISAMPLE_4_SAMPLES, NULL ) == D3D_OK )
{
// 保存多采样类型
multiType = D3DMULTISAMPLE_4_SAMPLES;
}
m_D3DPresentParams.BackBufferWidth = nSuitedWidth;
m_D3DPresentParams.BackBufferHeight = nSuitedHeight;
m_D3DPresentParams.BackBufferFormat = D3DFMT_A8R8G8B8;
m_D3DPresentParams.BackBufferCount = 1;
m_D3DPresentParams.MultiSampleType = multiType;
m_D3DPresentParams.MultiSampleQuality = 0;
m_D3DPresentParams.SwapEffect = D3DSWAPEFFECT_DISCARD;
m_D3DPresentParams.hDeviceWindow = m_hWnd;
m_D3DPresentParams.Windowed = TRUE;
m_D3DPresentParams.EnableAutoDepthStencil = TRUE;
m_D3DPresentParams.AutoDepthStencilFormat = D3DFMT_D16;
m_D3DPresentParams.Flags = 0;
m_D3DPresentParams.FullScreen_RefreshRateInHz = D3DPRESENT_RATE_DEFAULT;
m_D3DPresentParams.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;
if ( FAILED( hResult = m_pD3D->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, m_hWnd, vp, &m_D3DPresentParams, &m_pD3DDevice ) ) )
{
return MakeResult( ResultCode::Bad, DXGetErrorStringA( hResult ) );
}
D3DSURFACE_DESC SurfaceDesc;
IDirect3DSurface9* pD3DSurface = NULL;
if ( FAILED( hResult = m_pD3DDevice->GetBackBuffer( 0, 0, D3DBACKBUFFER_TYPE_MONO, &pD3DSurface ) ) )
{
return MakeResult( ResultCode::Bad, DXGetErrorStringA( hResult ) );
}
pD3DSurface->GetDesc( &SurfaceDesc );
pD3DSurface->Release();
pD3DSurface = NULL;
m_ContextSize = CSize2i( SurfaceDesc.Width, SurfaceDesc.Height );
m_bIsWindow = bWindowed;
if ( m_CallbackCreated )
{
CResult ret = m_CallbackCreated( this );
if ( ret.IsOK() == false )
return ret;
}
return CResult();
}
void iberbar::RHI::D3D9::CDevice::SetSamplerState( uint32 nStage, const UTextureSamplerState& SamplerState )
{
m_pD3DDevice->SetSamplerState( nStage, D3DSAMP_MIPFILTER, ConvertTextureFilterType( SamplerState.nMipFilter ) );
m_pD3DDevice->SetSamplerState( nStage, D3DSAMP_MINFILTER, ConvertTextureFilterType( SamplerState.nMinFilter ) );
m_pD3DDevice->SetSamplerState( nStage, D3DSAMP_MAGFILTER, ConvertTextureFilterType( SamplerState.nMagFilter ) );
m_pD3DDevice->SetSamplerState( nStage, D3DSAMP_ADDRESSU, ConvertTextureAddress( SamplerState.nAddressU ) );
m_pD3DDevice->SetSamplerState( nStage, D3DSAMP_ADDRESSV, ConvertTextureAddress( SamplerState.nAddressV ) );
m_pD3DDevice->SetSamplerState( nStage, D3DSAMP_ADDRESSW, ConvertTextureAddress( SamplerState.nAddressW ) );
}
void iberbar::RHI::D3D9::CDevice::SetBlendState( IBlendState* pBlendState )
{
assert( m_pBlendState );
const UBlendDesc& BlendDesc = m_pBlendState->GetDesc();
BOOL AlphaTest = BlendDesc.RenderTargets[0].BlendEnable == true ? TRUE : FALSE;
m_pD3DDevice->SetRenderState( D3DRS_ALPHABLENDENABLE, AlphaTest );
m_pD3DDevice->SetRenderState( D3DRS_SRCBLEND, ConvertBlend( BlendDesc.RenderTargets[0].SrcBlend ) );
m_pD3DDevice->SetRenderState( D3DRS_DESTBLEND, ConvertBlend( BlendDesc.RenderTargets[0].DestBlend ) );
m_pD3DDevice->SetRenderState( D3DRS_ALPHATESTENABLE, AlphaTest );
m_pD3DDevice->SetRenderState( D3DRS_BLENDOP, ConvertBlendOP( BlendDesc.RenderTargets[0].BlendOp ) );
m_pD3DDevice->SetRenderState( D3DRS_SRCBLENDALPHA, ConvertBlend( BlendDesc.RenderTargets[0].SrcBlendAlpha ) );
m_pD3DDevice->SetRenderState( D3DRS_DESTBLENDALPHA, ConvertBlend( BlendDesc.RenderTargets[0].DestBlendAlpha ) );
m_pD3DDevice->SetRenderState( D3DRS_BLENDOPALPHA, ConvertBlendOP( BlendDesc.RenderTargets[0].BlendOpAlpha ) );
m_pD3DDevice->SetRenderState( D3DRS_COLORWRITEENABLE, D3DCOLORWRITEENABLE_ALPHA | D3DCOLORWRITEENABLE_BLUE | D3DCOLORWRITEENABLE_GREEN | D3DCOLORWRITEENABLE_RED );
m_pD3DDevice->SetRenderState( D3DRS_BLENDFACTOR, 0 );
}
|
#include<bits/stdc++.h>
#define rep(i,n) for (int i =0; i <(n); i++)
using namespace std;
using ll = long long;
int check_digit(int a){
int ret = 0;
while(a){
a /= 10;
ret++;
}
return ret;
}
int main(){
int N;
cin >> N;
int ans = 0;
for(int i = 1; i <= N; i++){
int now = check_digit(i);
if(now %2 == 0)continue;
else ans++;
}
cout << ans << endl;
return 0;
}
|
//Using KMP. Time-0.000s
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define vll vector<ll>
#define ld long double
char T[1005], P[1005]; // T = text, P = pattern
int b[1005], n, m; // b = back table, n = length of T, m = length of P
void kmpPreprocess() { // call this before calling kmpSearch()
int i = 0, j = -1; b[0] = -1; // starting values
while (i < m) { // pre-process the pattern string P
while (j >= 0 && P[i] != P[j]) j = b[j]; // different, reset j using b
i++; j++; // if same, advance both pointers
b[i] = j; // observe i = 8, 9, 10, 11, 12, 13 with j = 0, 1, 2, 3, 4, 5
} } // in the example of P = "SEVENTY SEVEN" above
int kmpSearch() { // this is similar as kmpPreprocess(), but on string T
int i = 0, j = 0; // starting values
while (i < n) { // search through string T
while (j >= 0 && T[i] != P[j]) j = b[j]; // different, reset j using b
i++; j++; // if same, advance both pointers
if (j == m) { // a match found when j == m
//printf("P is found at index %d in T\n", i - j);
//j = b[j]; // prepare j for the next possible match
}
}
return j;
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
ll t,k,w;
cin>>t;
for(int i=0;i<t;i++)
{
cin>>k>>w;
string s[w];
for(int i=0;i<w;i++)
{
cin>>s[i];
}
ll ans=k;
for(int i=0;i<w-1;i++)
{
for(int j=0;j<k;j++)
{
P[j]=s[i+1][j];
T[j]=s[i][j];
}
n=k; m=k;
kmpPreprocess();
int tail=kmpSearch();
ans+=k-tail;
}
cout<<ans<<"\n";
}
}
|
#include <SDL2/SDL.h>
#include <stdlib.h>
#include <time.h>
#include <array>
#define DEBUG
#define WIDTH 300
#define HEIGHT 352
#define TILE_SIZE 22
#define TETRIS_W 10
#define TETRIS_H 16
bool running;
SDL_Renderer *renderer;
SDL_Window *window;
int frameCount, timerFPS, lastFrame, fps;
bool left, right, up, down, space;
bool landed[TETRIS_H][TETRIS_W];
struct block
{
SDL_Color color;
bool active;
};
using matrix = bool[4][4];
using spawnLocation = std::array<double, 2>;
spawnLocation getSpawn()
{
spawnLocation a{rand()%4+(double)2,(double)-(rand() % 5) - 4};
return a;
}
struct shape
{
SDL_Color color;
matrix matrix;
double x, y;
int size;
int index;
};
//<-- blocks
shape blocks[7] = {{{255,165,0},
{{0,0,1,0} // L BLOCK
,{1,1,1,0}
,{0,0,0,0}
,{0,0,0,0}
},0,0,3,0}
,{{255,0,0}, // Z BLOCK
{{1,1,0,0}
,{0,1,1,0}
,{0,0,0,0}
,{0,0,0,0}
},0,0,3,1}
,{{224,255,255}, // I BLOCK
{{0,0,0,0}
,{1,1,1,1}
,{0,0,0,0}
,{0,0,0,0}
},0,0,4,2}
,{{0,0,255}, // J BLOCK
{{1,0,0,0}
,{1,1,1,0}
,{0,0,0,0}
,{0,0,0,0}
},0,0,3,3}
,{{255,255,0}, // O BLOCK
{{1,1,0,0}
,{1,1,0,0}
,{0,0,0,0}
,{0,0,0,0}
},0,0,2,4}
,{{0,0,255}, // S BLOCK
{{0,1,1,0}
,{1,1,0,0}
,{0,0,0,0}
,{0,0,0,0}
},0,0,3,5}
,{{128,0,128}, // T BLOCK
{{0,1,0,0}
,{1,1,1,0}
,{0,0,0,0}
,{0,0,0,0}
},0,0,3,6}}, cur;
//-->
//<--Rotation
shape reverseCols(shape s)
{
shape tmp = s;
for(int row = 0; row < s.size; row++)
{
for(int col = 0; col < s.size/2; col++)
{
bool t = s.matrix[row][col];
tmp.matrix[row][col] = s.matrix[row][s.size-col-1];
tmp.matrix[row][s.size-col-1] = t;
}
}
return tmp;
}
shape transpose(shape s)
{
shape tmp = s;
for(int row = 0; row < s.size; row ++) {
for(int col = 0; col < s.size; col++) {
tmp.matrix[row][col]=s.matrix[col][row];
}
}
return tmp;
}
void rotate()
{
cur = reverseCols(transpose(cur));
}
//-->
SDL_Rect rect;
void draw(shape s)
{
for(int row = 0; row < TETRIS_H; row++)
{
for(int col = 0; col < TETRIS_W; col++)
{
rect.x = col * TILE_SIZE; rect.y = row * TILE_SIZE;
if(landed[row][col])
SDL_SetRenderDrawColor(renderer, 255, 0, 0, 255);
else
SDL_SetRenderDrawColor(renderer, 82, 82, 82, 255);
SDL_RenderFillRect(renderer, &rect);
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
SDL_RenderDrawRect(renderer, &rect);
}
}
for(int row = 0; row < s.size; row++)
{
for(int col = 0; col < s.size; col++)
{
if(s.matrix[row][col] && s.y + row >= 0)
{
rect.x = (s.x + col) * TILE_SIZE; rect.y = (s.y + row) * TILE_SIZE;
SDL_SetRenderDrawColor(renderer, s.color.r, s.color.g, s.color.b, 255);
SDL_RenderFillRect(renderer, &rect);
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
SDL_RenderDrawRect(renderer, &rect);
}
}
}
}
void printLanded()
{
printf("\n");
for(int r = 0; r < TETRIS_H; r++)
{
for(int c = 0; c < TETRIS_W; c++)
{
printf("%d ", landed[r][c]);
}
printf("\n");
}
}
void spawnNew()
{
cur = blocks[cur.index = rand() % 7];
cur.x = getSpawn()[0], cur.y = getSpawn()[1];
for(int i = 0; i < rand() % 4; i++)
{
rotate();
}
}
//checks if there is collision for given imaginary shape s
bool collision(shape s, int x, int y)
{
s.x = x, s.y = y;
for(int row = 0; row < s.size; row++)
{
for(int col = 0; col < s.size; col++)
{
if(s.matrix[row][col]) //if there is a block at position
{
if(s.x + col > TETRIS_W - 1 || s.x + col < 0 || s.y + row > TETRIS_H - 1) return true;
if(s.y + row < 0) continue;
if(landed[(int)s.y + row][(int)s.x + col]) //check if there is landed in real position
{
return true;
}
}
}
}
return false;
}
bool isGrounded(shape s)
{
for(int row = 0; row < s.size; row++)
{
for(int col = 0; col < s.size; col++)
{
if(collision(s, s.x, s.y + 1)) //adding 1 to simulate moving the block down 1 and checking for collision
{
return true;
}
}
}
return false;
}
void land()
{
for(int r = 0; r < cur.size; r++)
{
for(int c = 0; c < cur.size; c++)
{
if(cur.y + r < 0) //game over
{
printf("GAME OVER");
running = false;
return;
}
if(cur.matrix[r][c])
{
landed[(int)cur.y + r][(int)cur.x + c] = true;
}
}
}
cur.index = -1;
}
void clearLines()
{
for(int r = 0; r < TETRIS_H; r++)
{
bool line = true;
for(int c = 0; c < TETRIS_W; c++)
{
if(!landed[r][c])
{
line = false;
break;
}
}
if(line)
{
for(int row = r; row > 0; row--)
{
for(int col = 0; col < TETRIS_W; col++)
{
landed[row][col] = landed[row - 1][col];
}
}
}
}
}
void drop() //drop EET
{
if(!collision(cur, cur.x, cur.y + 1))
{
cur.y++;
}
}
//<--Update
void update()
{
if(left && !collision(cur, cur.x - 1, cur.y))
{
cur.x--;
}
if(right && !collision(cur, cur.x + 1, cur.y))
{
cur.x++;
}
if(down && !collision(cur, cur.x, cur.y + 1))
{
cur.y++;
}
if(up)
{
if(!collision(reverseCols(transpose(cur)), cur.x, cur.y))
{
rotate();
}
else if(!collision(reverseCols(transpose(cur)), cur.x + 1, cur.y))
{
rotate();
cur.x++;
}
else if(!collision(reverseCols(transpose(cur)), cur.x - 1, cur.y))
{
rotate();
cur.x--;
}
}
if(space)
{
while(!isGrounded(cur))
{
drop();
}
land();
clearLines();
spawnNew();
return;
}
if(frameCount == 0)
{
drop();
if(isGrounded(cur))
{
land();
clearLines();
}
if(cur.index == -1)
{
spawnNew();
}
}
#ifdef DEBUG
// printf("%5.d %5.d %5.d %5.d\n", frameCount, timerFPS, lastFrame, fps);
#endif
}
//-->
//<-- input
void input()
{
up = down = left = right = space = 0;
SDL_Event event;
while(SDL_PollEvent(&event))
{
if(event.type == SDL_QUIT) running = false;
switch(event.type)
{
case SDL_KEYDOWN: //down
switch(event.key.keysym.sym)
{
case SDLK_LEFT:
left = 1;
break;
case SDLK_RIGHT:
right = 1;
break;
case SDLK_UP:
up = 1;
break;
case SDLK_DOWN:
down = 1;
break;
case SDLK_SPACE:
space = 1;
break;
case SDLK_ESCAPE:
running = false;
break;
#ifdef DEBUG
case SDLK_1:
cur = blocks[0];
break;
case SDLK_2:
cur = blocks[1];
break;
case SDLK_3:
cur = blocks[2];
break;
case SDLK_4:
cur = blocks[3];
break;
case SDLK_5:
cur = blocks[4];
break;
case SDLK_6:
cur = blocks[5];
break;
case SDLK_7:
cur = blocks[6];
break;
#endif
}
}
}
}
//-->
void render()
{
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
SDL_RenderClear(renderer);
frameCount++;
int timerFPS = SDL_GetTicks() - lastFrame;
if(timerFPS < (1000/60))
{
SDL_Delay((1000/60) - timerFPS);
}
draw(cur);
SDL_RenderPresent(renderer);
}
int main(int argc, char *argv[])
{
srand(time(NULL));
spawnNew();
rect.w = rect.h = TILE_SIZE;
for(int row = 0; row < TETRIS_H; row++)
{
for(int col = 0; col < TETRIS_W; col++)
{
landed[row][col] = 0;
}
}
running = true;
static int lastTime = 0;
SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "0");
if(SDL_Init(SDL_INIT_EVERYTHING) < 0) printf("Failed at SDL_INIT!");
if(SDL_CreateWindowAndRenderer(WIDTH, HEIGHT, 0, &window, &renderer) < 0) printf("Failed at creation of Window and Renderer");
SDL_SetWindowTitle(window, "Tetris");
while(running)
{
lastFrame = SDL_GetTicks();
if(lastFrame >= (lastTime + 1000))
{
lastTime = lastFrame;
fps = frameCount;
frameCount = 0;
}
update();
input();
render();
}
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 2010 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
*/
#ifndef SVG_CHILD_ITERATOR_H
#define SVG_CHILD_ITERATOR_H
#ifdef SVG_SUPPORT
#include "modules/svg/src/svgpch.h"
#include "modules/svg/src/SVGTextElementStateContext.h" // SVGTextNodePool
#include "modules/util/adt/opvector.h"
class SVGElementContext;
struct SVGElementInfo;
class SVGChildIterator
{
public:
virtual SVGElementContext* FirstChild(SVGElementInfo& info) = 0;
virtual SVGElementContext* NextChild(SVGElementContext* parent_context,
SVGElementContext* child_context) = 0;
};
class SVGRenderingTreeChildIterator : public SVGChildIterator
{
public:
virtual SVGElementContext* FirstChild(SVGElementInfo& info);
virtual SVGElementContext* NextChild(SVGElementContext* parent_context,
SVGElementContext* child_context);
};
class SVGLogicalTreeChildIterator : public SVGChildIterator
{
public:
virtual SVGElementContext* FirstChild(SVGElementInfo& info);
virtual SVGElementContext* NextChild(SVGElementContext* parent_context,
SVGElementContext* child_context);
protected:
SVGElementContext* GetNextChildContext(SVGElementContext* parent_context,
HTML_Element* candidate_child);
};
class SVGTreePathChildIterator : public SVGChildIterator
{
public:
SVGTreePathChildIterator(OpVector<HTML_Element>* treepath) : m_treepath(treepath) {}
virtual SVGElementContext* FirstChild(SVGElementInfo& info);
virtual SVGElementContext* NextChild(SVGElementContext* parent_context,
SVGElementContext* child_context);
protected:
OpVector<HTML_Element>* m_treepath;
};
#endif // SVG_SUPPORT
#endif // SVG_CHILD_ITERATOR_H
|
/*
* ADCMainTest.cpp
*
* Adaption of the SAG C example for ADABAS calls
* - provides wrapper classes for Sessions, ACBX and/or ACB
*
* Created on: 08.04.2015
* Author: Fraxinus Ash
*
* Version 0.8.01
*/
#include <iostream>
#include <stdio.h>
#if defined(_WIN32) || defined(_WIN64)
#include <algorithm>
#include <windows.h>
#include <time.h>
#else
#include <unistd.h>
#include <macros.h>
#endif
#include "ADCSession.h"
static ADC acb;
int dbid;
int emp_file;
struct TRecord {
char firstname[20];
char name[20];
int salary;
};
char fullname[50];
void dump_usage();
int open_db();
int close_db();
void dump_response();
int update(int salary);
int find();
int rollback();
char* getFullname(TRecord*);
int main(int argc, char **argv) {
printf("ADC Unit Test\n");
if (argc == 3) {
if (sscanf(argv[1], "%d", &dbid) == 0)
dump_usage();
if (sscanf(argv[2], "%d", &emp_file) == 0)
dump_usage();
} else {
dump_usage();
}
/*
* Usage of sessions
*/
printf("Demonstrate sessions\n");
char openrb[100];
sprintf(openrb, "UPD=%d.", emp_file);
TRecord findrb;
char findfb[] = "BA,20,BC,20,LB1,4,F.";
char updfb[] = "LB1,4,F.";
ADCSession as1 = ADCSession("user_01");
//as1.setTraceLevel(9);
int rc = as1.open(dbid, openrb, -1, -1);
if (rc != ADA_NORMAL) {
as1.dumpResponse();
}
//as1.setTraceLevel(0);
ADCSession as2 = ADCSession("user_02");
rc = as2.open(dbid, openrb, -1, -1);
if (rc != ADA_NORMAL) {
as2.dumpResponse();
}
as1.setTraceLevel(9);
rc = as1.find(emp_file, "FIND", true, findfb, "BC,5.", "SMITH",
strlen("SMITH"), sizeof(TRecord));
as1.setTraceLevel(0);
if (rc == ADA_NORMAL) {
printf("Found %ld records with name 'SMITH'\n",
as1.getControlBlock()->getISNQuantity());
rc = as1.getNext();
if (rc == ADA_NORMAL) {
as1.getControlBlock()->getRecordBuffer((char*) &findrb,
sizeof(TRecord));
printf(" ISN=%6ld, name='%-25s', salary=%7d\n",
as1.getControlBlock()->getISN(), getFullname(&findrb),
findrb.salary);
}
/*as1.setTraceLevel(9);
if ((rc = as1.remove()) != ADA_NORMAL) {
as1.dumpResponse();
}
as1.setTraceLevel(0);*/
}
rc = as2.find(emp_file, "FIND", true, findfb, "BC,9.", "Johansson",
strlen("Johansson"), sizeof(TRecord));
if (rc == ADA_NORMAL) {
printf("Found %ld records with name 'Johansson'\n",
as2.getControlBlock()->getISNQuantity());
rc = as2.getNext();
if (rc == ADA_NORMAL) {
as2.getControlBlock()->getRecordBuffer((char*) &findrb,
sizeof(TRecord));
findrb.name[19] = 0;
printf(" ISN=%6ld, name='%-25s', salary=%7d\n",
as2.getControlBlock()->getISN(), getFullname(&findrb),
findrb.salary);
}
}
printf("Read and update the remaining records\n");
while ((rc = as1.getNext()) == ADA_NORMAL) {
as1.getControlBlock()->getRecordBuffer((char*) &findrb,
sizeof(TRecord));
int new_salary = findrb.salary + findrb.salary / 10;
//as1.setTraceLevel(9);
if ((rc = as1.update(updfb, &new_salary, 4)) != ADA_NORMAL) {
as1.dumpResponse();
new_salary = findrb.salary;
}
//as1.setTraceLevel(0);
printf(" ISN=%6ld, name='%-25s', salary=%7d, new_salary=%7d\n",
as1.getControlBlock()->getISN(), getFullname(&findrb),
findrb.salary, new_salary);
}
while ((rc = as2.getNext()) == ADA_NORMAL) {
as2.getControlBlock()->getRecordBuffer((char*) &findrb,
sizeof(TRecord));
int new_salary = findrb.salary + 100;
//as2.setTraceLevel(9);
if ((rc = as2.update(updfb, &new_salary, 4)) != ADA_NORMAL) {
as2.dumpResponse();
new_salary = findrb.salary;
}
//as2.setTraceLevel(0);
printf(" ISN=%6ld, name='%-25s', salary=%7d, new_salary=%7d\n",
as2.getControlBlock()->getISN(), getFullname(&findrb),
findrb.salary, new_salary);
}
if (as1.rollback() != ADA_NORMAL) {
as1.dumpResponse();
}
if (as2.rollback() != ADA_NORMAL) {
as2.dumpResponse();
}
if (as1.close() != ADA_NORMAL) {
as1.dumpResponse();
}
if (as2.close() != ADA_NORMAL) {
as2.dumpResponse();
}
printf("Press Enter to Continue");
fflush(stdout);
getchar();
/*
* Normal usage (ACBX)
*/
printf("Demonstrate single user access\n");
acb.setControlBufferType('X');
if (open_db() != ADA_NORMAL) {
dump_response();
} else {
int upd = 0;
acb.clear();
if (find() == ADA_NORMAL) {
printf(
"Found %ld records with name 'SMITH', increase salary by 10 %%\n",
acb.getISNQuantity());
while (acb.getReturnCode() == ADA_NORMAL
&& acb.getISNQuantity() != 0) {
int old_salary;
acb.getRecordBuffer((char*) &old_salary, 4);
int new_salary = old_salary + old_salary / 10;
if (update(new_salary) != ADA_NORMAL) {
//cb.cb_isn_quantity = 0;
} else {
upd++;
printf(
"%3d. ISN = %8d old salary = %10ld new salary = %10ld\n",
upd, acb.getISN(), old_salary, new_salary);
find(); // next record
}
}
}
if (acb.getReturnCode() != ADA_NORMAL) {
dump_response();
//cb.cb_return_code = ADA_NORMAL;
if (upd != 0) {
if (rollback() == ADA_NORMAL)
upd = 0;
else
dump_response();
}
}
rollback();
if (close_db() != ADA_NORMAL)
dump_response();
}
return 0;
}
/*
* Print usage
*/
void dump_usage() {
printf("usage: <program> <dbid> <employees file number>\n");
exit(1);
}
/*
* Print response
*/
void dump_response() {
printf("** Response code %d(%d) from ADABAS for Command %-2.2s\n",
acb.getReturnCode(), acb.getErrorSubCode(), acb.getCommand());
char add2[4];
acb.getAddition(add2, CB_L_AD2, 2);
printf("** Additions2 %d %d\n", add2[2], add2[3]);
return;
}
/*
* Open DB
*/
int open_db() {
printf("Open database.\n");
acb.clear();
acb.setDatabase(dbid);
acb.setCommand("OP");
char openrb[100];
sprintf(openrb, "UPD=%d.", emp_file);
acb.setRecordBuffer(openrb, strlen(openrb));
acb.setAddition("FRAX_ASH", 8, 1);
int result = 0;
do {
result = acb.process();
} while (result == ADA_TABT);
return result;
}
/*
* Close DB
*/
int close_db() {
printf("Close database.\n");
acb.clear();
acb.setDatabase(dbid);
acb.setCommand("CL");
return acb.process();
}
/*
* Find record(s)
*/
int find() {
if (acb.getISNQuantity() == 0) {
printf("Find record(s).\n");
//acb.clear();
acb.setDatabase(dbid);
acb.setFileNo(emp_file);
acb.setCommand("S4");
acb.setCommandId("FIND", 4);
acb.setFormatBuffer("LB1,4,F.", 8);
acb.setSearchBuffer("BC,5.", 5);
acb.setValueBuffer("SMITH", 5);
acb.setRecordBuffer("", 4);
if (acb.process() == ADA_EOF) {
acb.clear();
return acb.getReturnCode();
}
}
acb.setCommand("L4");
acb.setOption(ADA_GET_NEXT, (short) 2);
if (acb.process() == ADA_EOF) {
acb.clear();
}
return acb.getReturnCode();
}
/*
* Update record
*/
int update(int salary) {
acb.setCommand("A1");
acb.setRecordBuffer((const char*) &salary, 4);
return acb.process();
}
/*
* Backout transaction
*/
int rollback() {
acb.clear();
acb.setDatabase(dbid);
acb.setCommand("BT");
return acb.process();
}
char* getFullname(TRecord* findrb) {
findrb->name[19] = 0;
findrb->firstname[19] = 0;
sscanf(findrb->name, "%s", findrb->name);
sscanf(findrb->firstname, "%s", findrb->firstname);
sprintf(fullname, "%s, %s", findrb->name, findrb->firstname);
return fullname;
}
|
//堆
#include<iostream>
#include<map>
#define Type int //定义对节点数据类型
#define MIN_HEAP //定义最大最小堆
#define EXTREME -1 //关于大小堆的极端值定义,在删除操作中要用到
using namespace std;
class heap
{
private:
struct HeapNode {
Type d; //节点值
map<Type,int>::iterator pos;
//指向map中以该节点值为关键字的那个点的迭代器(实际上就是指针)
};
int size,len; //size是数据规模,在初始化时要给出具体规模值
//len是当前堆中的节点数
HeapNode *hp; //hp就是堆节点集
map<Type,int> rpos; //rpos是一个map,第一个是堆中节点值,第二个
//是该节点值在堆中位置
public:
heap(int);
void insert(Type &);
void pop(); //删除堆顶值
void Delete(Type &); //删除值为Type的节点
void down(int);
void up(int);
void swap(HeapNode &,HeapNode &);
Type top(); //返回堆顶值
bool comp(Type &x,Type &y) //最大最小堆的比较,
{
#ifdef MIN_HEAP
return x<y;
#else ifdef MAX_HEAP
return x>y;
#endif;
}
};
heap::heap(int InitSize)
{
size=InitSize+1;
len=0;
hp=new HeapNode[size+1];
}
void heap::insert(Type &x)
{
hp[++len].d=x;
hp[len].pos=(rpos.insert(pair<Type,int>(x,len)).first);
up(len);
}
void heap::pop()
{
if (len>0)
{
rpos.erase(hp[1].pos);
hp[len].pos->second=1;
hp[1]=hp[len--];
down(1);
}
}
void heap::Delete(Type &x)
{
int w=rpos[x];
hp[w].d=EXTREME;
up(w);
pop();
}
void heap::swap(HeapNode &x,HeapNode &y)
{
HeapNode tmp=x;x=y;y=tmp;
}
Type heap::top()
{
if (len>0) return hp[1].d;
else return -1;
}
void heap::down(int x)
{
int y;
if (x*2<=len) {
if (x*2==len) y=x*2;
else if (comp(hp[x*2].d,hp[x*2+1].d)) y=x*2;
else y=x*2+1;
if (comp(hp[y].d,hp[x].d)) {
hp[x].pos->second=y;
hp[y].pos->second=x;
swap(hp[x],hp[y]);
down(y);
}else return;
}
}
void heap::up(int x)
{
if (x>1){
int y=x/2;
if (comp(hp[x].d,hp[y].d)) {
hp[x].pos->second=y;
hp[y].pos->second=x;
swap(hp[x],hp[y]);
up(y);
}else return;
}
}
int main()
{
heap a(100000);
for(int i=1;i<=100000;++i)
a.insert(i);
for (int i=1;i<=100000;++i)
a.pop();
cout<<a.top()<<endl;
return 0;
}
|
#include <iostream>
//stive
using namespace std;
/* 1. Să se implementeze cu alocare dinamică o stivă de numere întregi, cu
următoarele operatii:
(a) void push (a, stiva) care adaugă elementul a în vârful stivei;
(b) int pop (stiva) care scoate elementul din vârful stivei şi îl intoarce ca
rezultat al funcţiei;
(c) int peek(stiva) care întoarce elementul din vârful stivei, fără a-l
scoate;
(d) bool empty(stiva) care verifică dacă stiva este vidă sau nu;
(e) int search(a, stiva) care intoarce -1 daca elementul a nu se află in
stiva. Daca a apare in stiva, atunci functia intoarce distanta de la varful stivei
pana la aparitia cea mai apropiata de varf. Se va considera ca varful se afla la
distanta 0.
(f) void afiseaza(stiva) care afiseaza stiva, pornind de la varful ei si
continuand spre baza.*/
struct nod
{
int info;
nod *back;
};
nod *varf;
void push(nod* &a,int x)
{
nod *c;
if(!a)
{
a=new nod;
a->info=x;
a->back=0;
}
else
{
c=new nod;
c->back=a;
c->info=x;
a=c;
}
}
void afisare(nod *a)
{
nod *c;
c=a;
while(c)
{
cout<<c->info<<" ";
c=c->back;
}
}
int pop(nod* &a)
{
nod* c;
int b;
c=a;
b=a->info;
a=a->back;
delete c;
return b;
}
int peek(nod* &a)
{
nod* c;
int b;
c=a;
b=a->info;
return b;
}
bool empty(nod* &a)
{
if(!a)
return 0;
else
return 1;
}
int search(nod* &a,int x)
{
nod *c;
int i=0;
c=a;
while(c)
{
if(c->info==x)
return i;
c=c->back;
i++;
}
return -1;
}
int main()
{
int n,a,x;
cout<<"Numarul nodurilor din stiva: ";
cin>>n;
for(int i=1; i<=n; i++)
{
cout<<"(a)Valoarea ce urmeaza sa fie adaugata in stiva: ";
cin>>a;
push(varf,a);
}
if(empty(varf)==0)
{
cout<<"Stiva este nula";
return 0;
}
cout<<"Stiva arata astfel: ";
afisare(varf);
cout<<endl;
if(empty(varf)!=0)
{
cout<<endl<<"(b)Urmeaza sa fie eliminat varful stivei: "<<pop(varf);
n--;
if(empty(varf)!=0)
{
cout<<endl<<"Stiva arata astfel: ";
afisare(varf);
}
}
else
{
cout<<"(b)Stiva este nula."<<endl;
return 0;
}
cout<<endl<<"(c)Varful stivei: "<<peek(varf)<<endl;
if(empty(varf)==0)
cout<<"(d)Stiva este nula.";
else
cout<<"(d)Stiva nu este nula.";
cout<<endl;
cout<<"(e)Se va cauta in stiva valoarea: ";
cin>>x;
int pozitie = search(varf, x);
if(pozitie == -1)
cout<<"Valoarea nu se regaseste in stiva";
else
cout<<"Valoarea se regaseste in stiva la o distanta: "<<pozitie;
return 0;
}
|
#pragma once
#pragma once
#include "../../Graphics/Light/PointLight/PointLight.h"
#include "../../UI/Dependencies/IncludeImGui.h"
namespace ae
{
namespace priv
{
namespace ui
{
inline void PointLightToEditor( PointLight& _PointLight )
{
float Radius = _PointLight.GetRadius();
ImGui::DragFloat( "Radius", &Radius, 1.0f, Math::Epsilon(), std::numeric_limits<float>::max() );
_PointLight.SetRadius( Radius );
}
}
} // priv
} // ae
|
//#include <string>
#include <iostream>
#include <fstream>
#include <direct.h>
#include <math.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <windows.h>
#include <conio.h>
#include <stdio.h>
#include <dirent.h>
#include <direct.h>
#include "VirtualMachine.h"
#include "createSolver.h"
using namespace std;
double stddev(double * nums,double mean,int count);
double mean(double * nums,int count);
bool DeleteDirectory(string path);
createSolver solver;
void fill_file(string file, int seedUp);
vector<string> next_generation(int gen, string * gen_path, string * prev_gen, double * performance,mssv vars);
int main(int argc, char ** argv){
if(argc < 2){
cout <<"Usage: ./mss <config file>\n";
return -1;
}
//file checking
ifstream cfg_stream(argv[1]);
if(! cfg_stream.good()){
cout <<"could not open config file: " << argv[1] <<"\n";
return -2;
}
//---------load configuration---------
string lang_def, test_dir, game_diff, s_generations, s_iterations, s_population, s_threshold, s_mutation, s_combination;
int generations, iterations, population;
double threshold, mutation, combination;
//lang_def
cfg_stream >> lang_def;
cfg_stream >> lang_def;
//test_dir
cfg_stream >> test_dir;
cfg_stream >> test_dir;
//game_diff
cfg_stream >> game_diff;
cfg_stream >> game_diff;
//generations
cfg_stream >> s_generations;
cfg_stream >> s_generations;
generations = atoi(s_generations.c_str());
//interations
cfg_stream >> s_iterations;
cfg_stream >> s_iterations;
iterations = atoi(s_iterations.c_str());
//population
cfg_stream >> s_population;
cfg_stream >> s_population;
population = atoi(s_population.c_str());
//threshold
cfg_stream >> s_threshold;
cfg_stream >> s_threshold;
threshold=atof(s_threshold.c_str());
//mutation
cfg_stream >> s_mutation;
cfg_stream >> s_mutation;
mutation = atof(s_mutation.c_str());
//combination
cfg_stream >> s_combination;
cfg_stream >> s_combination;
combination = atof(s_combination.c_str());
mssv vars;
vars.test_dir = test_dir;
vars.lang_def = lang_def;
vars.population = population;
vars.iterations = iterations;
vars.generations = generations;
vars.threshold = threshold;
vars.mutation = mutation;
vars.combination = combination;
cout <<"config file loaded\n";
cfg_stream.close();
/*If test directory exists, delete
struct stat dir_exist;
if(stat(test_dir.c_str(), &dir_exist) == 0){
//if(!DeleteDirectory(test_dir.c_str())){
//cout <<"could not delete test directory\n";
//return -8;
//}
Directory::Delete(test_dir, true);
cout <<"directory deleted\n";
}*/
//build test directory structure
if(_mkdir(test_dir.c_str()) < 0){
cout <<"could not create test directory: " << test_dir <<"\n";
return -3;
}
cout <<"test dir: "<< test_dir << " created\n";
string cur_dir;
string * dirs = new string[generations];//array to hold the directories
char buf[32];//buffer for _itoa_s
//create generation folders
for(int i=0;i<generations;i++){
cur_dir = test_dir;
cur_dir.append("\\");
cur_dir.append(test_dir);
cur_dir.append("_gen_");
_itoa_s(i,buf,10);
cur_dir.append(buf);
if(_mkdir(cur_dir.c_str())<0){
cout <<"error filling test directory: "<<cur_dir<<"\n";
_rmdir(test_dir.c_str());
return -4;
}
dirs[i] = cur_dir;
}
cout <<"test dir filled\n";
//build sample population
string target_file;
string * population_files = new string[population];//array of program names for virtual machine
for(int i = 0;i<population;i++){
target_file = dirs[0];
target_file.append("\\population_");
_itoa_s(i,buf,10);
target_file.append(buf);
target_file.append(".mss");
population_files[i] = target_file;
cout << target_file << endl;
//fill target file
fill_file(target_file, i);
}
cout << "generation: " << 0 << " poplulated\n";
double * performance = new double[population];
//test sample populations
for(int i=0;i<generations;i++){
VirtualMachine vm(lang_def,population_files,population,iterations,performance);
cout <<"Generation " << i << " completed\n";
vector<string> selected_files = next_generation(i,dirs,population_files,performance,vars);
solver.combine_best(selected_files, vars, i);
}
cout <<"Press any key to exit...\n";
getchar();
return 0;
}
//
bool DeleteDirectory(string path){
DIR *dirPtr;
struct dirent *entryPtr;
struct stat statBuf;
char cCurrentPath[_MAX_PATH];
dirPtr = opendir(path.c_str());
if(!dirPtr){
perror("Could not open path:");
return false;
}
if (!getcwd(cCurrentPath, _MAX_PATH))
return false;
int i = 0;
//Checks the size of argv
while(cCurrentPath[i] != '\0'){
i++;
}
//If the last element in argv is not a /, add one
if(cCurrentPath[i-1] != '\\'){
cCurrentPath[i] = '\\';
}
while(entryPtr = readdir(dirPtr)){
char buffer[_MAX_PATH];
stat(entryPtr->d_name, &statBuf);
if(strcmp(entryPtr->d_name, "..") && strcmp(entryPtr->d_name, ".")){
sprintf(buffer, "%s%s", cCurrentPath, entryPtr->d_name);
if((statBuf.st_mode) & S_IFDIR && strcmp(entryPtr->d_name, ".")){
if(!DeleteDirectory(buffer)){
return false;
}
}else{
remove(buffer);
}
}
}
closedir(dirPtr);
return rmdir(path.c_str());
}
void fill_file(string file, int seedUp){
solver.sCreate(file, seedUp);
//ofstream out(file.c_str());
//if(! out.good()){
// cout <<"error creating pop member: "<<file<<"\n";
// exit(-6);
//}
////------------random file creation--------------
////----------------------------------------------
//out <<"#pick squares sequentially starting at 0,0\n";
//out <<"int xpos=0\n";
//out <<"int ypos=0\n";
//out <<"while xpos<9\n";
//out <<"while ypos<9\n";
//out <<"picsq xpos,ypos\n";
//out <<"update ypos=ypos+1\n";
//out <<"ewhile\n";
//out <<"update ypos=0\n";
//out <<"update xpos=xpos+1\n";
//out <<"ewhile\n";
////-------------------------------------------------
////-------------------------------------------------
//out.close();
}
double mean(double * nums, int count){
double sum=0;
for(int i = 0;i<count;i++){
sum+=nums[i];
}
return sum / count;
}
double stddev(double * nums,double mean,int count){
//standard deviation
double sum=0;
double mean_dev;
//mean deviations
sum = 0;
for(int i = 0;i<count;i++){
mean_dev = nums[i] - mean;
//mean squared deviations
mean_dev = mean_dev * mean_dev;
sum += mean_dev;
}
sum = sum / count;
double std_dev = sqrt(sum);
return std_dev;
}
//Returns a vector of all selected files going to next generation
vector<string> next_generation(int gen, string * gen_path,string * prev_gen, double * performance, mssv vars){
//------------statistics calculation------------------
//----------------------------------------------------
vector<string> selected_files;
string stats_path = gen_path[gen];
stats_path.append("\\stats.txt");
ofstream stats_file(stats_path.c_str());
if(! stats_file.good()){
cout <<"error opening stats file\n";
exit(-7);
}
double mn = mean(performance,vars.population);
double std_dev = stddev(performance,mn,vars.population );
stats_file << "Mean: " << mn << "\n";
stats_file << "Standard deviation: " << std_dev << "\n\n";
stats_file << "Population performance ( ** denotes selection)\n";
//loop through programs and select any that preformed above mean + (threshold * std_dev) for the next generation
for(int i = 0 ;i<vars.population;i++){
stats_file << prev_gen[i] << ": " << performance[i] << " %";
if(performance[i] >= mn + (vars.threshold * std_dev)){
//push selected files on vector
selected_files.push_back(prev_gen[i]);
stats_file << " **";
}
stats_file << "\n";
}
return selected_files;
}
|
#pragma once
#include "pch.h"
#include <fbxsdk.h>
#include <iostream>
#include <string>
#include "Animation\Channel.h"
#include <fbxsdk.h>
class FbxUtil
{
public:
enum FbxType
{
kAnimation,
kMesh
};
static const Vector4 epsilon;
static bool IsEqual( float lhs, float rhs );
static bool IsEqual( const XMFLOAT4& lhs, const XMFLOAT4& rhs );
static bool IsEqual( const XMFLOAT3& lhs, const XMFLOAT3& rhs );
static bool IsEqual( const XMFLOAT2& lhs, const XMFLOAT2& rhs );
static void Convert(const char* path, FbxType type);
static FbxAMatrix ObjOffsetTransform(FbxNode* node);
static void GlobalTween( const hg::Channel& channel, hg::Transform::TransformData& tween, float currentTime );
};
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-2005 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
*/
#ifndef OPGLRENDERER_H
#define OPGLRENDERER_H
#ifdef CANVAS3D_SUPPORT
/** Interface to render to a memory buffer using OpenGL. */
class OpGlRenderer
{
public:
/** Create and OpenGL renderer which renderes to the specified buffer
* of the specified size and stride. */
static OP_STATUS Create(OpGlRenderer** renderer, UINT32* buffer, UINT32 width, UINT32 height, UINT32 stride);
virtual ~OpGlRenderer() {}
#ifdef LINK_WITHOUT_OPENGL
/** Get the OpenGL dll loaded by the renderer. */
virtual class OpDLL* GetDLL() = 0;
#endif // LINK_WITHOUT_OPENGL
/** Resize the buffer to which OpenGL renders. */
virtual OP_STATUS Resize(UINT32* buffer, UINT32 width, UINT32 height, UINT32 stride) = 0;
/** Activate the current OpenGL renderer. If there are several this must
* be called for OpenGL to know where to render. */
virtual OP_STATUS Activate() = 0;
/** Update the buffer. Will cause all OpenGL drawing to be copied to the buffer. */
virtual OP_STATUS UpdateBuffer() = 0;
};
#endif // CANVAS3D_SUPPORT
#endif // !OPGLRENDERER_H
|
#include "StaffManage.h"
//定义全局变量
StaffManage SM;
StaffManage::StaffManage() {
count = 0;
}
StaffManage::~StaffManage() {
if (count == 0) {
delete (head);
delete (current);
} else {
while (head->next != nullptr) {
BaseStaff *headPtr = head;
head = head->next;
delete (headPtr);
}
}
}
//查找指定的工号或姓名是否存在,如果存在,则返回对象在链表中的指针;如果不存在,返回NULL;
BaseStaff *StaffManage::search(string searchKey) {
//根据传入的值,判断在链表结构中,是否存在编号或姓名为searchKey的员工对象
BaseStaff *tmp = head;
//循环遍历链表中的每个对象
while (tmp != nullptr) {
//判断输入工号或姓名是否有匹配
if (tmp->getStaffNumber() == searchKey || tmp->getStaffNumber() == searchKey) {
return tmp;
}
tmp = tmp->next;
}
return nullptr;
}
//增加员工信息(功能1)
void StaffManage::addStaffInfos() {
//每添加一个员工信息计数就加1
count++;
// 员工类型分类
cout << "------------员工类型-------------" << endl;
cout << "【1】技术类人员" << endl;
cout << "【2】营销类人员" << endl;
cout << "【3】管理类人员" << endl;
cout << "【4】操作类人员" << endl;
cout << "-------------------------------" << endl;
cout << "-->请输入:";
int inputType;
cin >> inputType;
//判断用户输入是否正确
while ((inputType != 1) && (inputType != 2) && (inputType != 3) && (inputType != 4)) {
cout << "-->输入格式错误,请重新输入!" << endl;
cin.clear();
cin >> inputType;
}
if (inputType == 1) // 如果是技术类人员
{
if (count == 1) // 若链表结构不存在,则创建一个新技术人员对象,并赋值给head
{
head = new TechnicalStaff();
head->next = nullptr;
current = head;
cout << "添加员工信息成功!" << endl;
return;
} else {
//创建新的对象
BaseStaff *newTechnicalPtr = new TechnicalStaff();
BaseStaff *tmp = head;
//遍历链表查看是否有编号相同的对象
while (tmp != nullptr) {
if (tmp->getStaffNumber() == newTechnicalPtr->getStaffNumber()) {
cout << "编号:" << newTechnicalPtr->getStaffNumber() << "已存在!" << endl;
//回收对象
delete (newTechnicalPtr);
return;
}
tmp = tmp->next;
}
current->next = newTechnicalPtr;
current = newTechnicalPtr; // 将新指针对象赋值给current
current->next = nullptr;
cout << "添加员工信息成功!" << endl;
return;
}
}
if (inputType == 2) // 营销类人员
{
if (count == 1) //如果链表结构不存在,则创建一个新营销人员对象
{
head = new MarketingStaff();
current = head;
current->next = nullptr;
cout << "添加员工信息成功!" << endl;
} else {
BaseStaff *newMarketingPtr = new MarketingStaff();
BaseStaff *tmp = head;
while (tmp != nullptr) {
if (tmp->getStaffNumber() == newMarketingPtr->getStaffNumber()) {
cout << "编号" << newMarketingPtr->getStaffNumber() << "已存在!" << endl;
delete (newMarketingPtr);
return;
}
tmp = tmp->next;
}
current->next = newMarketingPtr;
current = newMarketingPtr;
current->next = nullptr;
cout << "添加员工信息成功!" << endl;
return;
}
}
if (inputType == 3) //管理类人员
{
if (count == 1) { //如果链表结构不存在,则创建一个新管理类人员对象
head = new ManagementStaff();
current = head;
current->next = nullptr;
cout << "添加员工信息成功!" << endl;
} else {
BaseStaff *newManagementPtr = new ManagementStaff();
BaseStaff *tmp = head;
while (tmp != nullptr) {
if (tmp->getStaffNumber() == newManagementPtr->getStaffNumber()) {
cout << "编号" << newManagementPtr->getStaffNumber() << "已存在" << endl;
delete (newManagementPtr);
return;
}
tmp = tmp->next;
}
current->next = newManagementPtr;
current = newManagementPtr;
current = nullptr;
cout << "添加员工信息成功!" << endl;
return;
}
}
if (inputType == 4) // 操作类人员
{
if (count == 1) { //如果链表结构不存在,则创建一个新操作类人员对象
head = new OperatorStaff();
current = head;
current->next = nullptr;
cout << "添加员工信息成功!" << endl;
} else {
BaseStaff *newOperatorPtr = new OperatorStaff();
BaseStaff *tmp = head;
while (tmp != nullptr) {
if (tmp->getStaffNumber() == newOperatorPtr->getStaffNumber()) {
cout << "编号" << newOperatorPtr->getStaffNumber() << "已存在" << endl;
delete (newOperatorPtr);
return;
}
tmp = tmp->next;
}
current->next = newOperatorPtr;
current = newOperatorPtr;
current = nullptr;
cout << "添加员工信息成功!" << endl;
return;
}
}
}
//修改企业员工信息(功能2)
void StaffManage::modifyStaffInfos() {
cout << "-->请输入工号:";
string searchKey;
cin >> searchKey;
//调用search方法
BaseStaff *staffInfoPtr = search(searchKey);
if (staffInfoPtr == nullptr) {
cout << "-->工号为:" << searchKey << "的员工不存在!" << endl;
return;
} else {
//查找是那个指针对象
BaseStaff *tmp = head;
while (tmp != staffInfoPtr) {
tmp = tmp->next;
}
cout << "原工号:" << tmp->getStaffNumber() << "\n新工号:";
tmp->setStaffNumber();
cout << "原姓名:" << tmp->getStaffName() << "\n新姓名:";
tmp->setStaffName();
cout << "原性别:" << tmp->getStaffSex() << "\n新性别:";
tmp->setStaffSex();
cout << "原工龄:" << tmp->getWorkYears() << "\n新工龄:";
tmp->setWorkYears();
cout << "原工资:" << tmp->getStaffSalary() << "\n新工资:";
tmp->setStaffSalary();
cout << "原等级:" << tmp->getStaffGrade() << "\n新等级:";
tmp->setStaffGrade();
cout << searchKey << "员工信息修改成功!" << endl;
}
}
//删除员工信息(功能3)
void StaffManage::deleteStaffInfos() {
cout << "-->请输入工号:";
string searchKey;
cin >> searchKey;
//调用search方法
BaseStaff *staffInfoPtr = search(searchKey);
if (staffInfoPtr == nullptr) {
cout << searchKey << "员工信息不存在!" << endl;
return;
} else {
//查找是那个指针对象
BaseStaff *tmp = head;
while (tmp != staffInfoPtr) {
tmp = tmp->next;
}
tmp = staffInfoPtr->next;
// 回收内存空间
delete (staffInfoPtr);
cout << searchKey << "员工信息删除成功!" << endl;
}
}
//查询单个员工信息(功能4)
void StaffManage::searchStaffInfos() {
cout << "-->请输入你要查询的工号:";
string searchKey;
cin >> searchKey;
//调用search方法
BaseStaff *staffInfoPtr = search(searchKey);
if (staffInfoPtr == nullptr) {
cout << "工号为" << searchKey << "的员工不存在!" << endl;
return;
} else {
cout << staffInfoPtr;
}
}
//显示所有员工信息(功能5)
void StaffManage::showAllStaffInfos() {
//判断head是否为NULL
if (head == nullptr) {
cout << "\n-->暂无职工信息!\n" << endl;
return;
}
//将head指针值赋值给临时定义的指针变量
BaseStaff *tmp = head;
while (tmp != nullptr) {
cout << tmp;
tmp = tmp->next;
}
}
//程序启动时,将文件中的数据加载到程序中
void StaffManage::readDatas() {
fstream inFile;
inFile.open("..\\staffdatas.dat", ios::in);
if (!inFile) {
cout << "打开文件失败!" << endl;
exit(1);
} else {
cout << "数据读取成功!" << endl;
}
while (!inFile.eof()) // 判断文件是否读取结束
{
if (inFile.peek() == EOF) {
inFile.close();
break;
} else {
int i; //i就是staffDutyType
inFile >> i;//读取文件中当前行第一列的值,以" "分割的
count++;
if (count == 1) // 判断链表中是否已经有指针对象
{
switch (i) {
case 1: {
TechnicalStaff *TechnicalPtr = new TechnicalStaff();
head = TechnicalPtr;
current = TechnicalPtr;
current->next = nullptr;
current->staffDutyType = i;
//读取为对象赋值的顺序与写入的顺序保持一致
inFile >> current->staffNumber
>> current->staffName
>> current->staffSex
>> current->staffWorkYears
>> current->staffSalary
>> current->staffGrade
>> current->technology
>> current->devote;
break;
}
case 2: {
MarketingStaff *MarketingPtr = new MarketingStaff();
head = MarketingPtr;
current = MarketingPtr;
current->next = nullptr;
current->staffDutyType = i;
inFile >> current->staffNumber
>> current->staffName
>> current->staffSex
>> current->staffWorkYears
>> current->staffSalary
>> current->staffGrade
>> current->totalAnnualSales
>> current->customerReception;
break;
}
case 3: {
ManagementStaff *ManagementPtr = new ManagementStaff();
head = ManagementPtr;
current = ManagementPtr;
current->next = nullptr;
current->staffDutyType = i;
inFile >> current->staffNumber
>> current->staffName
>> current->staffSex
>> current->staffWorkYears
>> current->staffSalary
>> current->staffGrade
>> current->planningSuccessRate
>> current->targeAchievementRate
>> current->staffManagementRate;
break;
}
case 4: {
OperatorStaff *OperatorPtr = new OperatorStaff();
head = OperatorPtr;
current = OperatorPtr;
current->next = nullptr;
current->staffDutyType = i;
inFile >> current->staffNumber
>> current->staffName
>> current->staffSex
>> current->staffWorkYears
>> current->staffSalary
>> current->staffGrade
>> current->resolveFailureRate
>> current->workEfficiency
>> current->projectCompletion;
break;
}
}
} else { //如果链表中包含指针对象
switch (i) {
case 1: {
TechnicalStaff *TechnicalPtr = new TechnicalStaff();
TechnicalPtr->staffDutyType = i;
inFile >> TechnicalPtr->staffNumber
>> TechnicalPtr->staffName
>> TechnicalPtr->staffSex
>> TechnicalPtr->staffWorkYears
>> TechnicalPtr->staffSalary
>> TechnicalPtr->staffGrade
>> TechnicalPtr->technology
>> TechnicalPtr->devote;
current->next = TechnicalPtr;
current = TechnicalPtr;
current->next = nullptr;
break;
}
case 2: {
MarketingStaff *MarketingPtr = new MarketingStaff();
MarketingPtr->staffDutyType = i;
inFile >> MarketingPtr->staffNumber
>> MarketingPtr->staffName
>> MarketingPtr->staffSex
>> MarketingPtr->staffWorkYears
>> MarketingPtr->staffSalary
>> MarketingPtr->staffGrade
>> MarketingPtr->totalAnnualSales
>> MarketingPtr->customerReception;
current->next = MarketingPtr;
current = MarketingPtr;
current->next = nullptr;
break;
}
case 3: {
ManagementStaff *ManagementPtr = new ManagementStaff();
ManagementPtr->staffDutyType = i;
inFile >> ManagementPtr->staffNumber
>> ManagementPtr->staffName
>> ManagementPtr->staffSex
>> ManagementPtr->staffWorkYears
>> ManagementPtr->staffSalary
>> ManagementPtr->staffGrade
>> ManagementPtr->planningSuccessRate
>> ManagementPtr->targeAchievementRate
>> ManagementPtr->staffManagementRate;
current->next = ManagementPtr;
current = ManagementPtr;
current->next = nullptr;
break;
}
case 4: {
OperatorStaff *OperatorPtr = new OperatorStaff();
OperatorPtr->staffDutyType = i;
inFile >> OperatorPtr->staffNumber
>> OperatorPtr->staffName
>> OperatorPtr->staffSex
>> OperatorPtr->staffWorkYears
>> OperatorPtr->staffSalary
>> OperatorPtr->staffGrade
>> OperatorPtr->resolveFailureRate
>> OperatorPtr->workEfficiency
>> OperatorPtr->projectCompletion;
current->next = OperatorPtr;
current = OperatorPtr;
current->next = nullptr;
break;
}
}
}
}
}
}
//在程序退出或添加,修改,删除时,将数据保存到文件中
void StaffManage::writeDatas() {
fstream outFile;
outFile.open("..\\staffdatas.dat", ios::out | ios::trunc);
if (!outFile) {
cout << "打开文件失败!" << endl;
exit(1);
}
BaseStaff *headPtr = head;
//判断是否头指针存在值
if (headPtr == nullptr) {
cout << "无数据需要保存!" << endl;
return;
}
//链表有多个指针,需要保存从头指针开始,一直到最后的指针对象
while (headPtr->next != nullptr) {
if (headPtr->staffDutyType == 1)//判断指针对象是否是技术类人员
{
outFile << headPtr->staffDutyType << " "
<< headPtr->getStaffNumber() << " "
<< headPtr->getStaffName() << " "
<< headPtr->getStaffSex() << " "
<< headPtr->getWorkYears() << " "
<< headPtr->getStaffGrade() << " "
<< headPtr->getStaffSalary() << " "
<< headPtr->technology << " "
<< headPtr->devote << endl;
}
if (headPtr->staffDutyType == 2) //营销类人员
{
outFile << headPtr->staffDutyType << " "
<< headPtr->getStaffNumber() << " "
<< headPtr->getStaffName() << " "
<< headPtr->getStaffSex() << " "
<< headPtr->getWorkYears() << " "
<< headPtr->getStaffGrade() << " "
<< headPtr->getStaffSalary() << " "
<< headPtr->totalAnnualSales << " "
<< headPtr->customerReception << endl;
}
if (headPtr->staffDutyType == 3) //管理类人员
{
outFile << headPtr->staffDutyType << " "
<< headPtr->getStaffNumber() << " "
<< headPtr->getStaffName() << " "
<< headPtr->getStaffSex() << " "
<< headPtr->getWorkYears() << " "
<< headPtr->getStaffGrade() << " "
<< headPtr->getStaffSalary() << " "
<< headPtr->planningSuccessRate << " "
<< headPtr->targeAchievementRate << " "
<< headPtr->staffManagementRate << endl;
}
if (headPtr->staffDutyType == 4) //操作类人员
{
outFile << headPtr->staffDutyType << " "
<< headPtr->getStaffNumber() << " "
<< headPtr->getStaffName() << " "
<< headPtr->getStaffSex() << " "
<< headPtr->getWorkYears() << " "
<< headPtr->getStaffGrade() << " "
<< headPtr->getStaffSalary() << " "
<< headPtr->resolveFailureRate << " "
<< headPtr->workEfficiency << " "
<< headPtr->projectCompletion << endl;
}
headPtr = headPtr->next;
}
//保存最后一个指针元素的数据
if (headPtr->staffDutyType == 1)//判断指针对象是否是技术类人员
{
outFile << headPtr->staffDutyType << " "
<< headPtr->getStaffNumber() << " "
<< headPtr->getStaffName() << " "
<< headPtr->getStaffSex() << " "
<< headPtr->getWorkYears() << " "
<< headPtr->getStaffGrade() << " "
<< headPtr->getStaffSalary() << " "
<< headPtr->technology << " "
<< headPtr->devote << endl;
}
if (headPtr->staffDutyType == 2) //营销类人员
{
outFile << headPtr->staffDutyType << " "
<< headPtr->getStaffNumber() << " "
<< headPtr->getStaffName() << " "
<< headPtr->getStaffSex() << " "
<< headPtr->getWorkYears() << " "
<< headPtr->getStaffGrade() << " "
<< headPtr->getStaffSalary() << " "
<< headPtr->totalAnnualSales << " "
<< headPtr->customerReception << endl;
}
if (headPtr->staffDutyType == 3) //管理类人员
{
outFile << headPtr->staffDutyType << " "
<< headPtr->getStaffNumber() << " "
<< headPtr->getStaffName() << " "
<< headPtr->getStaffSex() << " "
<< headPtr->getWorkYears() << " "
<< headPtr->getStaffGrade() << " "
<< headPtr->getStaffSalary() << " "
<< headPtr->planningSuccessRate << " "
<< headPtr->targeAchievementRate << " "
<< headPtr->staffManagementRate << endl;
}
if (headPtr->staffDutyType == 4) //操作类人员
{
outFile << headPtr->staffDutyType << " "
<< headPtr->getStaffNumber() << " "
<< headPtr->getStaffName() << " "
<< headPtr->getStaffSex() << " "
<< headPtr->getWorkYears() << " "
<< headPtr->getStaffGrade() << " "
<< headPtr->getStaffSalary() << " "
<< headPtr->resolveFailureRate << " "
<< headPtr->workEfficiency << " "
<< headPtr->projectCompletion << endl;
}
cout << "数据保存成功!" << endl;
outFile.close(); //关闭文件流
}
|
//
// Created by sergo on 12/27/19.
//
#include <iostream>
#include <chrono>
#include <vector>
#include <omp.h>
#include <random>
#include "matrix.hpp"
#include "task_4_lib.cpp"
using namespace std;
int main() {
uint64_t size = 1000;
Matrix<uint64_t> A(size);
randomizeMatrix(A);
Matrix<uint64_t> B(size);
randomizeMatrix(B);
auto res1 = printExecTime(prodOneThread, A, B);
auto res2 = printExecTime(prodBS, A, B);
auto res3 = printExecTime(prodCB, A, B);
cout << (*res1 == *res2 and *res2 == *res3 ? "COOL" : "NOT COOL") << endl;
return 0;
}
|
#include <iberbar/RHI/D3D11/VertexDeclaration.h>
#include <iberbar/RHI/D3D11/Types.h>
void iberbar::RHI::D3D11::CVertexDeclaration::BuildD3DInputElementDescritions( D3D11_INPUT_ELEMENT_DESC* pRefArray )
{
const UVertexElement* pRHIElement = nullptr;
memset( pRefArray, 0, sizeof( D3D11_INPUT_ELEMENT_DESC ) * 16 );
uint32 i = 0;
for ( ; i < m_nVertexElementsCount; i++ )
{
pRHIElement = &m_VertexElements[ i ];
pRefArray[ i ].SemanticName = ConvertVertexDeclareUsage( pRHIElement->nSemantic );
pRefArray[ i ].SemanticIndex = (UINT)pRHIElement->nSemanticIndex;
pRefArray[ i ].Format = ConvertVertexFormat( pRHIElement->nFormat );
pRefArray[ i ].InputSlot = pRHIElement->nSlot;
pRefArray[ i ].AlignedByteOffset = pRHIElement->nOffset;
pRefArray[ i ].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
pRefArray[ i ].InstanceDataStepRate = 0;
}
}
|
#pragma once
#include "aeGOAddOn.h"
#include "aeTransform.h"
#include "aeModel.h"
namespace aeEngineSDK
{
class AE_ENGINE_EXPORT aeRendererAddOn : public aeGOAddOn
{
friend class aeGOFactory;
public:
aeRendererAddOn();
aeRendererAddOn(const aeRendererAddOn& AO);
~aeRendererAddOn();
public:
AE_RESULT Init() override;
void Update() override;
void Destroy() override;
void Render(const aeTransform& Transform);
AE_ADD_ON_ID GetComponentId() const override;
public:
aeModelResource m_xModel;
};
}
|
/* -*- Mode: c++; tab-width: 4; c-basic-offset: 4 -*-
*
* Copyright (C) 2007-2011 Opera Software ASA. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*/
#ifndef POSIX_UA_COMPONENT_MANAGER_H
# define POSIX_UA_COMPONENT_MANAGER_H __FILE__
# ifdef POSIX_OK_HOST
# include "modules/pi/OpUAComponentManager.h"
/** Basic implementation of OpUAComponentManager.
*
* This class provides GetOSString, because that's what it makes sense to
* implement using POSIX APIs. The optional APIs of this class (see
* TWEAK_URL_UA_COMPONENTS_CONTEXT) relate to project-specific choices.
*
* You also need to provide an implementation of
* OpUAComponentManager::Create() along the lines of this:
*
* @code
* OP_STATUS OpUAComponentManager::Create(OpUAComponentManager **target_pp)
* {
* OpAutoPtr<PosixUAComponentManager> manager(OP_NEW(PosixUAComponentManager, ()));
* if (!manager.get())
* return OpStatus::ERR_NO_MEMORY;
* RETURN_IF_ERROR(manager->Construct());
* *target_pp = manager.release();
* return OpStatus::OK;
* }
* @endcode
*
* An instance of this class requires second-stage construction: call its
* Construct() method and check the status it returns.
*/
class PosixUAComponentManager :
public OpUAComponentManager
{
protected:
friend class OpUAComponentManager; // for its Create()
/** Constructor.
*
* Only for use by OpComponentUAManager::Create() or a derived class's
* constructor.
*/
PosixUAComponentManager();
/** Set-up.
*
* Must be called by OpComponentUAManager::Create(), possibly via derived
* class over-riding this method. Derived classes that do so must call
* this.
*
* @return OK on success, else error value indicating problem.
*/
virtual OP_STATUS Construct();
public:
virtual const char *GetOSString(Args &args)
{
OP_ASSERT(m_os_ver.CStr() || !"Did you neglect to call Construct() ?");
return (args.ua == UA_MSIE_Only) ? m_ms_ie_ver : m_os_ver.CStr();
}
private:
/** OS to claim we're using, when claiming to be MSIE.
*
* Initialized by constructor; for use in user-agent strings, via
* GetOSString().
*/
char m_ms_ie_ver[sizeof(POSIX_IE_SYSNAME)]; // ARRAY OK 2011-10-07 peter
/** True identification of operating system.
*
* Initialized by constructor; for use in user-agent strings, via
* GetOSString(). Includes hardware type and, where easy, version information.
*/
OpString8 m_os_ver;
};
# endif // POSIX_OK_HOST
#endif // POSIX_UA_COMPONENT_MANAGER_H
|
//--------------------------------------------------------------------
// CS215-401 LAB 1
//--------------------------------------------------------------------
// Author: Andrew Cassidy
// Date: 9/5/2019
// Description: My first C++ program. It does arithmetic on two numbers.
//--------------------------------------------------------------------
#include <iostream>
using namespace std;
int main() {
//
cout << " _ \n";
cout << " | | \n";
cout << " __ _ _ __ __| |_ __ _____ __\n";
cout << " / _` | '_ \\ / _` | '__/ _ \\ \\ /\\ / /\n";
cout << "| (_| | | | | (_| | | | __/\\ V V /\n";
cout << " \\__,_|_| |_|\\__,_|_| \\___| \\_/\\_/\n\n";
// Title Box.
cout << "+-------------------------------+\n";
cout << "| Number Fun! |\n";
cout << "| By: Andrew Cassidy |\n";
cout << "+-------------------------------+\n";
// Initialize num1 and num2 for user input.
int num1;
int num2;
// Prompt user to input two numbers.
cout << "Enter a number: "; cin >> num1;
cout << "Enter another: "; cin >> num2; cout << endl;
// Calculate sum, diff, prod, int qout and float quot.
int sum = num1 + num2;
int diff = num1 - num2;
int prod = num1 * num2;
int int_quot = num1 / num2;
float float_quot = static_cast<double>(num1) / num2;
// Calculate and print sum, diff, prod, int qout and float qout.
cout << "Sum: " << sum << endl;
cout << "Difference: " << diff << endl;
cout << "Product: " << prod << endl;
cout << "Int Quotient: " << int_quot << endl;
cout << "Float Quotient: " << float_quot << endl;
// End statements.
system("Pause");
return 0;
}
|
#pragma once
#include "Tool.h"
#include <cmath>
namespace CAE
{
class MoveView : public Tool
{
private:
sf::View& viewToMove;
bool keyPress;
bool ImGuiDisabled;
float zoom = 1;
void assetUpdated() override {}
public:
MoveView(EMHolder& m, const sf::Texture& t, sf::RenderWindow& window, sf::View& v) : Tool(m, t, window), viewToMove(v), keyPress(false){}
void Enable() override
{
EventsHolder["MoveView"].setEnable(true);
}
void Disable() override
{
EventsHolder["MoveView"].setEnable(false);
keyPress = false;
}
void Init() override
{
auto& eManager = EventsHolder.addEM("MoveView", false);
eManager.addEvent(MouseEvent::ButtonPressed(sf::Mouse::Left), [this](sf::Event& event)
{
keyPress = true;
//oldPos = sf::Vector2f(sf::Mouse::getPosition(*window));
});
eManager.addEvent(MouseEvent(sf::Event::MouseButtonReleased), [this](sf::Event& event)
{
keyPress = false;
});
eManager.addEvent(MouseEvent(sf::Event::MouseMoved), [this](sf::Event& event)
{
if (keyPress && ImGuiDisabled)
{
auto delta = (sf::Vector2f)EventsHolder.getDelta();
delta.x *= zoom;
delta.y *= zoom;
viewToMove.move(delta);
}
});
eManager.addEvent(MouseEvent(sf::Event::MouseWheelScrolled), [this](sf::Event& event)
{
if (!keyPress && ImGuiDisabled)
{
if (event.mouseWheelScroll.delta <= -1)
zoom = std::min(2.f, zoom + .1f);
else if (event.mouseWheelScroll.delta >= 1)
zoom = std::max(.1f, zoom - .1f);
viewToMove.setSize(window->getDefaultView().getSize());
viewToMove.zoom(zoom);
EventsHolder.zoom = zoom;
}
});
}
void update() override
{
window->setView(viewToMove);
if (ImGui::IsAnyWindowHovered() || ImGui::IsAnyItemHovered()) { ImGuiDisabled = keyPress = false; }
else ImGuiDisabled = true;
}
void draw(sf::RenderWindow&) override {}
};
}
|
#include "watchedFlow.h"
#include "watchedObj.h"
#include "redisClient.h"
#include <algorithm>
watchedFlow::watchedFlow(){}
watchedFlow::~watchedFlow(){}
void print(queue<string> Queue) {
queue<string> q = Queue;
int count = q.size();
for (int i = 0; i < count; i++) {
cout << q.front() << " ;";
q.pop();
}
}
//监视一个key
void watchedFlow::watchedForKey(string table, redisClient *c)
{
int count = watchedObjs.size();
for (int i = 0; i < count; i++) {
if (watchedObjs[i].table == table) {
// push之前加个判定,有可能该用户已经存在了,
// 但其实也可不加,毕竟一直更新着,大不了置多遍位呗
watchedObjs[i].theClients.push_back(c);
return;
}
}
watchedObj theWatchedObj;
theWatchedObj.table = table;
theWatchedObj.theClients.push_back(c);
watchedObjs.push_back(theWatchedObj);
}
//监视所有key
void watchedFlow::watchCommand(redisClient *c, queue<string> testTable)
{
//cout << "监视事务开始,当前监视的表如下:" << endl;
//print(testTable);
int count = testTable.size();
for (int i = 0; i < count; i++) {
watchedForKey(testTable.front(), c);
//cout << "本轮监视的表:" << testTable.front() << endl;
testTable.pop();
}
//cout << "此时监视字典结构如下:" << endl;
//count = watchedObjs.size();
//for (int i = 0; i < count; i++) {
// list<redisClient*>::iterator it;
// for (it = watchedObjs[i].theClients.begin(); it != watchedObjs[i].theClients.end(); it++) {
// cout << *it << endl;
// }
//}
}
//触碰到主键,触碰的条件是什么,之前是有人手动更改数据,现在应该是一个事务执行的快(写操作),导致了其它事务执行失败
void watchedFlow::touchWatchedKey(string table)
{
int count = watchedObjs.size();
// 只有一种情况,只要在里面,就被人监视着,给这些监视的人置负一
for (int i = 0; i < count; i++) {
if (watchedObjs[i].table == table) {
list<redisClient*>::iterator it;
for (it = watchedObjs[i].theClients.begin(); it != watchedObjs[i].theClients.end(); it++) {
(*it)->flags = 10; // 一下没注意咋写了个 == 呢
// cout << "key:" << key << (*it)->flags << endl;
}
return;
}
}
}
void watchedFlow::TouchWatchedKey(queue<string> keys)
{
if (watchedObjs.size() == 0)
return;
int count = keys.size();
for (int i = 0; i < count; i++) {
touchWatchedKey(keys.front());
keys.pop();
}
//cout << "此时监视字典结构如下:" << endl;
//count = watchedObjs.size();
//for (int i = 0; i < count; i++) {
// list<redisClient*>::iterator it;
// cout << watchedObjs[i].table << " ";
// for (it = watchedObjs[i].theClients.begin(); it != watchedObjs[i].theClients.end(); it++) {
// cout << *it << endl;
// }
//}
}
void watchedFlow::cleanWatchedKey(string table, redisClient * c)
{
int count = watchedObjs.size();
// 先把这个客户端都移除(该客户端之前所监视的所有的键)
for (int i = 0; i < count; i++) {
if (watchedObjs[i].table == table) {
list<redisClient*>::iterator it;
for (it = watchedObjs[i].theClients.begin(); it != watchedObjs[i].theClients.end(); it++) {
if ((*it)->id == c->id)
watchedObjs[i].theClients.erase(it);
break;
}
continue;
}
}
}
void watchedFlow::CleanwatchedKey(redisClient * c, queue<string> keys)
{
//cout << "需要删除的监视表:" ;
//print(keys);
//cout << "删除前的监视字典为:" << endl;
//int count1 = watchedObjs.size();
//for (int i = 0; i < count1; i++) {
// list<redisClient*>::iterator it;
//cout << watchedObjs[i].table << " ";
//for (it = watchedObjs[i].theClients.begin(); it != watchedObjs[i].theClients.end(); it++) {
// cout << *it << endl;
//}
//}
int count = keys.size();
for (int i = 0; i < count; i++) {
//cout << "本轮中删除的表为:" << keys.front() << endl;
cleanWatchedKey(keys.front(), c);
keys.pop();
}
//cout << "删除后的监视字典为:" << endl;
//count = watchedObjs.size();
//for (int i = 0; i < count; i++) {
// list<redisClient*>::iterator it;
// for (it = watchedObjs[i].theClients.begin(); it != watchedObjs[i].theClients.end(); it++) {
// cout << *it << endl;
// }
//}
}
|
// Lexer for Configuration Files.
#include <string.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 "CharacterSet.h"
#include "LexerModule.h"
using namespace Scintilla;
static inline bool IsConfOp(int ch) {
return ch == '=' || ch == ':' || ch == ';' || ch == '{' || ch == '}' || ch == '(' || ch == ')' ||
ch == '!' || ch == ',' || ch == '|' || ch == '*' || ch == '$' || ch == '.';
}
static inline bool IsUnit(int ch) {
return ch == 'K' || ch == 'M' || ch == 'G' || ch == 'k' || ch == 'm' || ch == 'g';
}
static inline bool IsDelimiter(int ch) {
return IsASpace(ch) || IsConfOp(ch);
}
static void ColouriseConfDoc(Sci_PositionU startPos, Sci_Position length, int initStyle, LexerWordList, Accessor &styler) {
int state = initStyle;
int chNext = styler[startPos];
styler.StartAt(startPos);
styler.StartSegment(startPos);
Sci_PositionU endPos = startPos + length;
if (endPos == (Sci_PositionU)styler.Length())
++endPos;
int visibleChars = 0;
bool insideTag = false;
Sci_Position lineCurrent = styler.GetLine(startPos);
for (Sci_PositionU i = startPos; i < endPos; i++) {
int ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
const bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n');
const bool atLineStart = i == (Sci_PositionU)styler.LineStart(lineCurrent);
switch (state) {
case SCE_CONF_OPERATOR:
styler.ColourTo(i - 1, state);
state = SCE_CONF_DEFAULT;
break;
case SCE_CONF_NUMBER:
if (!(IsADigit(ch) || ch == '.')) {
if (IsUnit(ch) && IsDelimiter(chNext)) {
styler.ColourTo(i, state);
state = SCE_CONF_DEFAULT;
continue;
} else if (iswordchar(ch)) {
state = SCE_CONF_IDENTIFIER;
} else {
styler.ColourTo(i - 1, state);
state = SCE_CONF_DEFAULT;
}
}
break;
case SCE_CONF_HEXNUM:
if (!IsHexDigit(ch)) {
styler.ColourTo(i - 1, state);
state = SCE_CONF_DEFAULT;
}
break;
case SCE_CONF_STRING:
if (atLineStart) {
styler.ColourTo(i - 1, state);
state = SCE_CONF_DEFAULT;
} else if (ch == '\\' && (chNext == '\\' || chNext == '\"')) {
i++;
ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
} else if (ch == '\"') {
styler.ColourTo(i, state);
state = SCE_CONF_DEFAULT;
continue;
}
break;
case SCE_CONF_DIRECTIVE:
if (insideTag && ch == ':') {
styler.ColourTo(i - 1, state);
if (chNext == ':') {
i++;
ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
}
styler.ColourTo(i, SCE_CONF_OPERATOR);
state = SCE_CONF_DIRECTIVE;
} else if (IsDelimiter(ch) || (insideTag && ch == '>')) {
styler.ColourTo(i - 1, state);
if (ch == '.') {
styler.ColourTo(i, SCE_CONF_OPERATOR);
} else {
state = SCE_CONF_DEFAULT;
}
}
break;
case SCE_CONF_SECTION:
case SCE_CONF_COMMENT:
if (atLineStart) {
styler.ColourTo(i - 1, state);
state = SCE_CONF_DEFAULT;
}
break;
case SCE_CONF_IDENTIFIER:
if (IsDelimiter(ch) || (insideTag && ch == '>') || (ch == '<' && chNext == '/')) {
styler.ColourTo(i - 1, state);
if (ch == '.') {
styler.ColourTo(i, SCE_CONF_OPERATOR);
} else {
state = SCE_CONF_DEFAULT;
}
}
break;
}
if (state != SCE_CONF_COMMENT && ch == '\\' && (chNext == '\n' || chNext == '\r')) {
i++;
lineCurrent++;
ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
if (ch == '\r' && chNext == '\n') {
i++;
chNext = styler.SafeGetCharAt(i + 1);
}
continue;
}
if (state == SCE_CONF_DEFAULT) {
if (ch == '#') {
styler.ColourTo(i - 1, state);
state = SCE_CONF_COMMENT;
} else if (ch == '\"') {
styler.ColourTo(i - 1, state);
state = SCE_CONF_STRING;
} else if (IsConfOp(ch)) {
styler.ColourTo(i - 1, state);
state = SCE_CONF_OPERATOR;
} else if ((visibleChars == 0 && !IsASpace(ch)) || (ch == '<' && chNext == '/')) {
styler.ColourTo(i - 1, state);
if (ch == '[') {
state = SCE_CONF_SECTION;
} else {
state = SCE_CONF_DIRECTIVE;
insideTag = ch == '<';
if (chNext == '/') {
i++;
ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
}
}
} else if (insideTag && (ch == '>' || ((ch == '/' || ch == '?') && chNext == '>'))) {
styler.ColourTo(i - 1, state);
if (ch == '/' || ch == '?') {
i++;
ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
}
styler.ColourTo(i, SCE_CONF_DIRECTIVE);
state = SCE_CONF_DEFAULT;
insideTag = false;
} else if ((ch == '+' || ch == '-') && IsAlphaNumeric(chNext)) {
styler.ColourTo(i - 1, state);
state = SCE_CONF_OPERATOR;
} else if (IsADigit(ch)) {
styler.ColourTo(i - 1, state);
if (ch == '0' && (chNext == 'x' || chNext == 'X')) {
state = SCE_CONF_HEXNUM;
i++;
ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
} else {
state = SCE_CONF_NUMBER;
}
} else if (!IsASpace(ch)) {
styler.ColourTo(i - 1, state);
state = SCE_CONF_IDENTIFIER;
}
}
if (atEOL || i == endPos-1) {
lineCurrent++;
visibleChars = 0;
}
if (!isspacechar(ch)) {
visibleChars++;
}
}
// Colourise remaining document
styler.ColourTo(endPos - 1, state);
}
#define IsCommentLine(line) IsLexCommentLine(line, styler, SCE_CONF_COMMENT)
static void FoldConfDoc(Sci_PositionU startPos, Sci_Position length, int initStyle, LexerWordList, Accessor &styler) {
if (styler.GetPropertyInt("fold") == 0)
return;
const bool foldComment = styler.GetPropertyInt("fold.comment") != 0;
const bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
Sci_PositionU endPos = startPos + length;
int visibleChars = 0;
Sci_Position lineCurrent = styler.GetLine(startPos);
int levelCurrent = SC_FOLDLEVELBASE;
if (lineCurrent > 0)
levelCurrent = styler.LevelAt(lineCurrent-1) >> 16;
int levelNext = levelCurrent;
char chNext = styler[startPos];
int styleNext = styler.StyleAt(startPos);
int style = initStyle;
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 && atEOL && IsCommentLine(lineCurrent)) {
if (!IsCommentLine(lineCurrent - 1) && IsCommentLine(lineCurrent + 1))
levelNext++;
else if (IsCommentLine(lineCurrent - 1) && !IsCommentLine(lineCurrent + 1))
levelNext--;
}
if (style == SCE_CONF_DIRECTIVE) {
if (visibleChars == 0 && ch == '<' && !(chNext == '/' || chNext == '?')) {
levelNext++;
} else if (ch == '<' && chNext == '/') {
levelNext--;
} else if (ch == '/' && chNext == '>') {
Sci_PositionU pos = i;
while (pos > startPos) {
pos--;
char c = styler.SafeGetCharAt(pos);
if (!(c == ' ' || c == '\t')) {
break;
}
}
if (!(IsAlphaNumeric(styler.SafeGetCharAt(pos)) && styler.StyleAt(pos) == SCE_CONF_DIRECTIVE)) {
levelNext--;
}
}
}
if (style == SCE_CONF_OPERATOR) {
if (ch == '{')
levelNext++;
else if (ch == '}')
levelNext--;
}
if (!isspacechar(ch))
visibleChars++;
if (atEOL || (i == endPos-1)) {
int levelUse = levelCurrent;
int lev = levelUse | levelNext << 16;
if (visibleChars == 0 && foldCompact)
lev |= SC_FOLDLEVELWHITEFLAG;
if (levelUse < levelNext)
lev |= SC_FOLDLEVELHEADERFLAG;
if (lev != styler.LevelAt(lineCurrent)) {
styler.SetLevel(lineCurrent, lev);
}
lineCurrent++;
levelCurrent = levelNext;
visibleChars = 0;
}
}
}
LexerModule lmConf(SCLEX_CONF, ColouriseConfDoc, "conf", FoldConfDoc);
|
#include <iostream>
#include <vector>
using namespace std;
int main(int argc, const char *argv[])
{
vector< int > iv;
int i;
while(cin >> i)
{
iv.push_back(i);
}
vector< int >::iterator iter = iv.begin();
while(iter != iv.end())
{
cout << *iter++ << endl;
}
return 0;
}
|
#include<iostream>
#include<algorithm>
#include<vector>
#include<unordered_map>
#include<unordered_set>
using namespace std;
class Node {
public:
int val;
vector<Node*> neighbors;
Node() {
val = 0;
neighbors = vector<Node*>();
}
Node(int _val) {
val = _val;
neighbors = vector<Node*>();
}
Node(int _val, vector<Node*> _neighbors) {
val = _val;
neighbors = _neighbors;
}
};
void InitGraph(Node* node, vector<int> vec)
{
vector<Node*> graph;
graph.push_back(node);
for (int i = 1; i < vec.size(); i++)
{
Node* n = new Node(vec[i]);
graph.push_back(n);
}
graph[0]->neighbors = { graph[1],graph[3] };
graph[1]->neighbors = { graph[0],graph[2] };
graph[2]->neighbors = { graph[1],graph[3] };
graph[3]->neighbors = { graph[0],graph[2] };
}
class Solution {
public:
unordered_map<Node*, bool> visited; //标记旧图中节点是否访问过
unordered_map<int, Node*> HashMap; //保存生成的新节点,val和node映射
Node* cloneGraph(Node* node) {
//基本思想:递归+HashMap,先递归生成新节点保存在HashMap中,然后递归将生成的新节点连接起来成新图
if (node == NULL)
return NULL;
//递归生成新节点保存在HashMap中
CreateHashMap(node);
Node* newNode = HashMap[node->val];
//递归将生成的新节点连接起来成新图
CloneNode(node, &newNode);
return newNode;
}
void CreateHashMap(Node* node)
{
if (visited.find(node) == visited.end())
{
visited[node] = false;
Node* temp = new Node(node->val);
HashMap[temp->val] = temp;
}
else
return;
for (auto i = node->neighbors.begin(); i != node->neighbors.end(); i++)
{
CreateHashMap(*i);
}
}
void CloneNode(Node* node,Node** newNode)
{
if (visited[node] == false)
{
visited[node] = true;
for (auto i = node->neighbors.begin(); i != node->neighbors.end(); i++)
{
(*newNode)->neighbors.push_back(HashMap[(*i)->val]);
CloneNode(*i, &HashMap[(*i)->val]);
}
}
}
};
class Solution1 {
public:
unordered_map<Node*, Node*> HashMap; //保存旧节点与新生成的节点之间映射
Node* cloneGraph(Node* node) {
//优化版本:这道题充分说明建立好的数据结构对解决问题事半功倍
//上面的想法是自己想出来的,建立的是val与node的HashMap,导致代码不够简洁,这是参考别人的想法
if (node == NULL)
return NULL;
//已经生成的节点不再生成
if (HashMap.find(node) != HashMap.end())
return HashMap[node];
Node* newNode = new Node(node->val);
HashMap[node] = newNode;
//生成与node相连接的节点
for (auto i = node->neighbors.begin(); i != node->neighbors.end(); i++)
{
newNode->neighbors.push_back(cloneGraph(*i));
}
return newNode;
}
};
int main()
{
Solution1 solute;
vector<int> vec = { 1,2,3,4 };
Node* node = new Node(1);
InitGraph(node, vec);
node = solute.cloneGraph(node);
cout << node->val << endl;
for (auto n = node->neighbors.begin(); n != node->neighbors.end(); n++)
{
cout << (*n)->val << endl;
cout << (*n)->neighbors.front()->val << endl;
cout << (*n)->neighbors.back()->val << endl;
}
return 0;
}
|
#pragma once
#include "Tree.h"
#include <windows.h>
#include <d3d11.h>
#include <d3dx11.h>
#include <d3dcompiler.h>
#include <xnamath.h>
#include <D3DX10math.h>
#include "resource.h"
#include <dxerr.h>
#include "Structures.h"
#include "GameObject.h"
#include "Camera.h"
#include "OBJLoader.h"
#include "Car.h"
struct Vector3{ float x, y, z; };
struct Vertex1
{
XMFLOAT3 Pos; // 0-byte offset
XMFLOAT3 Normal; // 12-byte offset
XMFLOAT2 TexC; // 24-byte offset
};
// Vertex2 example from book, might need later for textures?
struct Vertex2
{
XMFLOAT3 Pos; // 0-byte offset
XMFLOAT3 Normal; // 12-byte offset
XMFLOAT2 Text0; // 24-byte offset
XMFLOAT2 Text1; // 32-byte offset
};
/*
struct ConstantBuffer
{
XMMATRIX mWorld;
XMMATRIX mView;
XMMATRIX mProjection;
XMFLOAT4 diffuseMaterial;
XMFLOAT4 diffuseLight;
XMFLOAT4 ambientMaterial;
XMFLOAT4 ambientLight;
XMFLOAT4 specularMtrl;
XMFLOAT4 specularLight;
float specularPower;
XMFLOAT3 eyePosW;
XMFLOAT3 lightVecW;
}; */
// Book colours bit, YOLO
namespace Colors
{
XMGLOBALCONST XMVECTORF32 White = {1.0f, 1.0f, 1.0f, 1.0f};
XMGLOBALCONST XMVECTORF32 Black = {0.0f, 0.0f, 0.0f, 1.0f};
XMGLOBALCONST XMVECTORF32 Red = {1.0f, 0.0f, 0.0f, 1.0f};
XMGLOBALCONST XMVECTORF32 Green = {0.0f, 1.0f, 0.0f, 1.0f};
XMGLOBALCONST XMVECTORF32 Blue = {0.0f, 0.0f, 1.0f, 1.0f};
XMGLOBALCONST XMVECTORF32 Yellow = {1.0f, 1.0f, 0.0f, 1.0f};
XMGLOBALCONST XMVECTORF32 Cyan = {0.0f, 1.0f, 1.0f, 1.0f};
XMGLOBALCONST XMVECTORF32 Magenta = {1.0f, 0.0f, 1.0f, 1.0f};
}
class Application
{
private:
HINSTANCE _hInst;
HWND _hWnd;
D3D_DRIVER_TYPE _driverType;
D3D_FEATURE_LEVEL _featureLevel;
ID3D11Device* _pd3dDevice;
ID3D11DeviceContext* _pImmediateContext;
IDXGISwapChain* _pSwapChain;
ID3D11RenderTargetView* _pRenderTargetView;
ID3D11VertexShader* _pVertexShader;
ID3D11PixelShader* _pPixelShader;
ID3D11InputLayout* _pVertexLayout;
ID3D11Buffer* _pVertexBuffer;
ID3D11Buffer* _pIndexBuffer;
ID3D11Buffer* _pConstantBuffer;
ID3D11DepthStencilView* _depthStencilView;
ID3D11Texture2D* _depthStencilBuffer;
XMFLOAT4X4 _world;
XMFLOAT4X4 _world2; // my stuffs
XMFLOAT4X4 _world3;
XMFLOAT4X4 _world4;
XMFLOAT4X4 _world5;
XMFLOAT4X4 _world6;
ID3D11RasterizerState* mWireframeRS;
ID3D11RasterizerState* mSolidRS;
Vertex1* vertices2;
WORD* indices;
XMFLOAT4X4 _view;
XMFLOAT4X4 _projection;
WORD* indicesTest;
Vertex1 * vertexTest;
ID3D11ShaderResourceView* g_pTextureRV;
ID3D11ShaderResourceView* g_pTextureRV2;
ID3D11SamplerState* g_pSamplerAnisotropic;
MeshData objMeshData;
GameObject objTest;
GameObject objCube;
GameObject treeOne;
GameObject treeTwo;
GameObject trackPlane;
Tree tree1;
Tree tree2;
Tree tree3;
Car car1;
Car car2;
private:
HRESULT InitWindow(HINSTANCE hInstance, int nCmdShow);
HRESULT InitDevice();
void Cleanup();
HRESULT CompileShaderFromFile(WCHAR* szFileName, LPCSTR szEntryPoint, LPCSTR szShaderModel, ID3DBlob** ppBlobOut);
HRESULT InitShadersAndInputLayout();
HRESULT InitVertexBuffer();
HRESULT InitIndexBuffer();
D3D11_TEXTURE2D_DESC depthStencilDesc;
UINT _WindowHeight;
UINT _WindowWidth;
public:
Application();
~Application();
HRESULT Initialise(HINSTANCE hInstance, int nCmdShow);
void texture();
void Update();
void calcNorms();
void Draw();
};
|
/* -*- Mode: c++; tab-width: 4; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2011 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*
* @author Arjan van Leeuwen (arjanl)
*/
#ifndef NON_BROWSER_APPLICATION_H
#define NON_BROWSER_APPLICATION_H
#include "adjunct/quick/Application.h"
class OpPoint;
class OpRect;
class NonBrowserApplication
{
public:
virtual ~NonBrowserApplication() {}
/**
* @return an OpUiWindowListener object that should be used in this
* application. The caller is responsible for deletion.
*/
virtual OpUiWindowListener* CreateUiWindowListener() = 0;
/**
* @return an OpAuthenticationListener object that should be used in this
* application. Caller is responsible for deletion.
*/
virtual DesktopOpAuthenticationListener* CreateAuthenticationListener() = 0;
/**
* Indicates to the application that it's environment is now completely
* set up and it can start operation.
*/
virtual OP_STATUS Start() = 0;
/**
* @return A DesktopMenuHandler that should be used in this application.
*/
virtual DesktopMenuHandler* GetMenuHandler() = 0;
virtual DesktopWindow* GetActiveDesktopWindow(BOOL toplevel_only) = 0;
virtual BOOL HasCrashed() const = 0;
virtual Application::RunType DetermineFirstRunType() = 0;
virtual BOOL IsExiting() const = 0;
virtual OperaVersion GetPreviousVersion() = 0;
/**
* @return this application's global input context
*/
virtual UiContext* GetInputContext() = 0;
/**
* Establishes this application's global input context.
*
* @param input_context this application's global input context
*/
virtual void SetInputContext(UiContext& input_context) = 0;
virtual BOOL OpenURL(const OpStringC &address) = 0;
};
#endif // NON_BROWSER_APPLICATION_H
|
#pragma once
namespace qp
{
class CMatchingQuestion;
typedef std::shared_ptr<CMatchingQuestion> CMatchingQuestionPtr;
typedef std::shared_ptr<const CMatchingQuestion> CConstMatchingQuestionPtr;
}
|
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
int d(int n)
{
int sum = n;
while (n)
{
sum += n % 10;
n /= 10;
}
return sum;
}
int main()
{
std::ios_base::sync_with_stdio(false);
std::cin.tie(0);
std::cout.tie(0);
std::vector<bool> check(10001, false);
for (int i = 1; i <= 10000; ++i)
{
if (!check[i])
{
int last = i;
while (last <= 10000)
{
last = d(last);
check[last] = true;
}
}
if (!check[i])
{
std::cout << i << '\n';
}
}
return 0;
}
|
#pragma once
namespace Hourglass
{
enum RenderPassType
{
kRenderPass_Opaque,
kRenderPass_OpaqueSkinned,
kRenderPass_Transparent,
kRenderPass_Effect,
kRenderPassCount,
};
}
|
#include <string>
#include <vector>
#include <map>
using namespace std;
int solution(vector<vector<string>> clothes) {
int answer = 1;
map<string, int> m;
for(int i=0, len=clothes.size(); i<len; i++){
//의상종류(key)가 같은 것을 map에서 찾아 iterator 저장
map<string, int>::iterator it = m.find(clothes[i][1]);
//iterator가 end()이면 map의 처음부터 끝까지 검색하여도 발견되지 않은 경우
if(it==m.end())
m.insert(make_pair(clothes[i][1],1));
else
(it->second)++;
}
for(map<string, int>::iterator i=m.begin(); i!=m.end(); i++)
answer*=(i->second)+1;
return answer-1;
}
|
#ifndef __BASEGAMEENTITY_H_
#define __BASEGAMEENTITY_H_
class Event;
class BaseGameEntity
{
public:
BaseGameEntity(int id)
{
SetID(id);
}
virtual ~BaseGameEntity() {}
private:
int m_ID;
void SetID(int);
public:
virtual void Update() = 0;
int ID()const { return m_ID; }
virtual bool HandleEvent(const Event& msg) = 0;
};
#endif
|
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "Item.h"
#include "Engine/StaticMeshActor.h"
#include "Door.generated.h"
/**
*
*/
UENUM(BlueprintType)
enum class EDoorDirection : uint8 {
DD_North UMETA(DisplayName = "North"), //-Y
DD_South UMETA(DisplayName = "South"), //+Y
DD_East UMETA(DisplayName = "East"), //+X
DD_West UMETA(DisplayName = "West") //-X
};
UCLASS()
class HYPOXIA_API ADoor : public AItem
{
GENERATED_BODY()
//UPROPERTY(VisibleAnywhere, Category = Mesh)
//class UStaticMeshComponent* Door;
protected:
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Enum)
EDoorDirection DoorHandleDirection;
protected:
AStaticMeshActor *Door;
float DoorRotation = 0.0f;
float MoveTime = 0.0f;
bool Opened = true;
bool Moving = true;
//bool Moving = false;
FVector InitialPosition;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Bool)
bool Locked;
public:
virtual void BeginPlay() override;
void Unlock();
protected:
ADoor();
virtual void Tick(float) override;
virtual void Use() override;
void Open();
void Close();
virtual void UpdatePosition(FVector) override;
};
|
#include <string.h>
#include "pipe_tally_subscriber.h"
//----------------------------------------------
// Singleton Instance
//----------------------------------------------
CPipeTallyStateSubscriber *CPipeTallyStateSubscriber::m_pInstance = nullptr;
std::mutex CPipeTallyStateSubscriber::m_mutex;
CPipeTallyStateSubscriber *CPipeTallyStateSubscriber::Instance()
{
m_mutex.lock();
if (m_pInstance == nullptr)
{
m_pInstance = new CPipeTallyStateSubscriber();
}
m_mutex.unlock();
return m_pInstance;
}
void CPipeTallyStateSubscriber::Destroy()
{
m_mutex.lock();
if (m_pInstance != nullptr)
{
delete m_pInstance;
m_pInstance = nullptr;
}
m_mutex.unlock();
}
CPipeTallyStateSubscriber::CPipeTallyStateSubscriber()
{
}
CPipeTallyStateSubscriber::~CPipeTallyStateSubscriber()
{
}
bool CPipeTallyStateSubscriber::GetSerialNumber(const char *serialNumber)
{
serialNumber = DDS_String_dup(m_data.serialNumber);
return (m_sampleInfo.valid_data == DDS_BOOLEAN_TRUE);
}
bool CPipeTallyStateSubscriber::GetJointNumber(uint32_t &jointNumber)
{
jointNumber = m_data.jointNumber;
return (m_sampleInfo.valid_data == DDS_BOOLEAN_TRUE);
}
bool CPipeTallyStateSubscriber::GetStandNumber(uint32_t &standNumber)
{
standNumber = m_data.standNumber;
return (m_sampleInfo.valid_data == DDS_BOOLEAN_TRUE);
}
bool CPipeTallyStateSubscriber::GetWeight(double &weight)
{
weight = m_data.weight;
return (m_sampleInfo.valid_data == DDS_BOOLEAN_TRUE);
}
bool CPipeTallyStateSubscriber::GetInnerDiameter(double &innerDiameter)
{
innerDiameter = m_data.innerDiameter;
return (m_sampleInfo.valid_data == DDS_BOOLEAN_TRUE);
}
bool CPipeTallyStateSubscriber::GetOuterDiameter(double &outerDiameter)
{
outerDiameter = m_data.outerDiameter;
return (m_sampleInfo.valid_data == DDS_BOOLEAN_TRUE);
}
bool CPipeTallyStateSubscriber::GetKellyDown(double &kellyDown)
{
kellyDown = m_data.kellyDown;
return (m_sampleInfo.valid_data == DDS_BOOLEAN_TRUE);
}
bool CPipeTallyStateSubscriber::GetLength(double &length)
{
length = m_data.length;
return (m_sampleInfo.valid_data == DDS_BOOLEAN_TRUE);
}
bool CPipeTallyStateSubscriber::GetPipeLength(double &pipeLength)
{
pipeLength = m_data.pipeLength;
return (m_sampleInfo.valid_data == DDS_BOOLEAN_TRUE);
}
bool CPipeTallyStateSubscriber::GetStringLength(double &stringLength)
{
stringLength = m_data.stringLength;
return (m_sampleInfo.valid_data == DDS_BOOLEAN_TRUE);
}
bool CPipeTallyStateSubscriber::GetDescription(const char *description)
{
description = m_data.description;
return (m_sampleInfo.valid_data == DDS_BOOLEAN_TRUE);
}
bool CPipeTallyStateSubscriber::GetPipeType(DataTypes::PipeType &pipeType)
{
pipeType = m_data.pipeType;
return (m_sampleInfo.valid_data == DDS_BOOLEAN_TRUE);
}
bool CPipeTallyStateSubscriber::Create(int32_t domain)
{
return TSubscriber::Create(domain,
nec::process::PIPE_TALLY,
"EdgeBaseLibrary",
"EdgeBaseProfile");
}
void CPipeTallyStateSubscriber::OnDataAvailable(onDataAvailableEvent event)
{
m_pOnDataAvailable = event;
}
void CPipeTallyStateSubscriber::DataAvailable(const nec::process::PipeTally &data,
const DDS::SampleInfo &sampleInfo)
{
m_sampleInfo = sampleInfo;
if (sampleInfo.valid_data == true)
{
m_data.id = DDS_String_dup(data.id);
m_data.timestamp.sec = data.timestamp.sec;
m_data.timestamp.nanosec = data.timestamp.nanosec;
m_data.serialNumber = DDS_String_dup(data.serialNumber);
m_data.jointNumber = data.jointNumber;
m_data.standNumber = data.standNumber;
m_data.weight = data.weight;
m_data.innerDiameter = data.innerDiameter;
m_data.outerDiameter = data.outerDiameter;
m_data.kellyDown = data.kellyDown;
m_data.length = data.length;
m_data.pipeLength = data.pipeLength;
m_data.stringLength = data.stringLength;
m_data.description = DDS_String_dup(data.description);
m_data.pipeType = data.pipeType;
if (m_pOnDataAvailable != nullptr)
{
m_pOnDataAvailable(data);
}
}
}
void CPipeTallyStateSubscriber::DataDisposed(const DDS::SampleInfo &sampleInfo)
{
LOG_INFO("Sample disposed");
m_sampleInfo = sampleInfo;
}
|
#include <boost/bind.hpp>
#include <boost/asio/placeholders.hpp>
#include "secure_socket.hpp"
#include "logging.hpp"
namespace asio = boost::asio;
namespace sp
{
secure_socket::secure_socket(boost::asio::io_service& ios)
: ctxt_(asio::ssl::context::sslv23)
, ssl_strm_(ios, ctxt_)
{
// @TODO: decide tls stuff
// ctxt_.set_options(
// boost::asio::ssl::context::default_workarounds
// | boost::asio::ssl::context::no_sslv2
// | boost::asio::ssl::context::single_dh_use);
// ctxt_.use_certificate_chain_file("server.pem");
// ctxt_.use_private_key_file("server.pem", boost::asio::ssl::context::pem);
// ctxt_.use_tmp_dh_file("dh512.pem");
}
void secure_socket::async_connect(const acceptor::endpoint_type& peer_endpoint, connect_handler handler) {
LOG_TRACE << __PRETTY_FUNCTION__;
ssl_strm_.lowest_layer().async_connect(
peer_endpoint,
boost::bind(
&secure_socket::handle_connect,
this,
asio::placeholders::error,
handler
)
);
}
void secure_socket::async_accept(acceptor& acc, acceptor::endpoint_type& remote_ep, accept_handler handler) {
LOG_TRACE << __PRETTY_FUNCTION__;
acc.async_accept(
ssl_strm_.lowest_layer(),
remote_ep,
boost::bind(
&secure_socket::handle_accept,
this,
asio::placeholders::error,
handler
)
);
}
void secure_socket::async_read_some(const boost::asio::mutable_buffers_1& buffers, read_handler handler) {
LOG_TRACE << __PRETTY_FUNCTION__;
ssl_strm_.async_read_some(buffers, handler);
}
void secure_socket::async_write_some(const boost::asio::const_buffers_1& buffers, write_handler handler) {
LOG_TRACE << __PRETTY_FUNCTION__;
ssl_strm_.async_write_some(buffers, handler);
}
void secure_socket::cancel(boost::system::error_code& ec) {
LOG_TRACE << __PRETTY_FUNCTION__;
ssl_strm_.lowest_layer().cancel(ec);
}
void secure_socket::shutdown(boost::system::error_code& ec) {
LOG_TRACE << __PRETTY_FUNCTION__;
ssl_strm_.shutdown(ec);
ssl_strm_.lowest_layer().shutdown(asio::socket_base::shutdown_both, ec);
}
void secure_socket::close(boost::system::error_code& ec) {
LOG_TRACE << __PRETTY_FUNCTION__;
ssl_strm_.lowest_layer().close(ec);
}
void secure_socket::handle_connect(const boost::system::error_code& ec, socket::connect_handler h) {
LOG_TRACE << __PRETTY_FUNCTION__;
if(ec) {
return h(ec);
}
ssl_strm_.async_handshake(asio::ssl::stream_base::client, h);
}
void secure_socket::handle_accept(const boost::system::error_code& ec, accept_handler h) {
LOG_TRACE << __PRETTY_FUNCTION__;
if(ec) {
return h(ec);
}
ssl_strm_.async_handshake(asio::ssl::stream_base::server, h);
}
}
|
//
// Created by jean_j on 21.01.17.
//
#include <sstream>
#include "Parser.hh"
Parser::Parser(const std::string &filename, PhysicsEngine &physics)
: physicsEngine(physics), file(rapidxml::file<>(filename.c_str()))
{
try
{
rapidxml::xml_document<> doc;
doc.parse<0>(file.data());
root_node = doc.first_node("map");
}
catch (const std::runtime_error& e)
{
std::cerr << "Runtime error was: " << e.what() << std::endl;
}
catch (const rapidxml::parse_error& e)
{
std::cerr << "Parse error was: " << e.what() << std::endl;
}
catch (const std::exception& e)
{
std::cerr << "Error was: " << e.what() << std::endl;
}
catch (...)
{
std::cerr << "An unknown error occurred." << std::endl;
}
}
Parser::~Parser() {
}
std::vector<Sprite *> Parser::parseSprites() {
int width, height, i, j;
rapidxml::xml_node<> *tileset_node = root_node->first_node("tileset");
rapidxml::xml_node<> *image_node = tileset_node->first_node("image");
sf::Texture *tileset = new sf::Texture();
sf::Sprite *newSprite;
if (!tileset->loadFromFile(image_node->first_attribute("source")->value()))
throw(std::runtime_error("Error: cannot load " + std::string(image_node->first_attribute("source")->value())));
width = (atoi(image_node->first_attribute("width")->value()) / atoi(tileset_node->first_attribute("tilewidth")->value()));
height = (atoi(image_node->first_attribute("height")->value()) / atoi(tileset_node->first_attribute("tileheight")->value()));
i = 0;
sprites.push_back(NULL);
while (i < height)
{
j = 0;
while (j < width)
{
newSprite = new sf::Sprite();
newSprite->setTexture(*tileset);
newSprite->setTextureRect(sf::IntRect(j * TILE_WIDTH, i * TILE_HEIGHT, TILE_WIDTH, TILE_HEIGHT));
newSprite->setScale(1.f, -1.f);
//newSprite->setOrigin(TILE_WIDTH / 2, TILE_HEIGHT / 2);
sprites.push_back(new Sprite(newSprite));
j++;
}
i++;
}
for(rapidxml::xml_node<> * tile_node = tileset_node->first_node("tile"); tile_node; tile_node = tile_node->next_sibling())
{
int id = atoi(tile_node->first_attribute("id")->value());
id += 1;
rapidxml::xml_node<> *obj = tile_node->first_node("objectgroup")->first_node("object");
sprites[id]->addCollider(new CollideBox(
sf::Vector2f(atoi(obj->first_attribute("x")->value()), atoi(obj->first_attribute("y")->value())),
atoi(obj->first_attribute("width")->value()),
atoi(obj->first_attribute("height")->value()),
obj->first_attribute("rotation") ? atoi(obj->first_attribute("rotation")->value()) : 0
));
}
return (sprites);
}
std::vector<std::string> Parser::split(const std::string &s, char delim) {
std::stringstream ss(s);
std::string item;
std::vector<std::string> tokens;
while (std::getline(ss, item, delim)) {
tokens.push_back(item);
}
return tokens;
}
bool Parser::isDynamic(int id)
{
if (id == 15)
return (true);
return (false);
}
std::vector<std::vector<Tile *>> Parser::parseMap()
{
rapidxml::xml_node<> *layer_node = root_node->first_node("layer");
rapidxml::xml_node<> *data_node = layer_node->first_node("data");
int width = atoi(layer_node->first_attribute("width")->value());
int height = atoi(layer_node->first_attribute("height")->value());
std::vector<std::string> data = split(std::string((data_node->value())), ',');
int i = 0;
int j;
Sprite *tmpSprite;
tiles.resize((unsigned long) height);
while (i < height)
{
j = 0;
while (j < width)
{
int id = atoi(data[i * width + j].c_str());
tmpSprite = sprites[id];
Tile *tile = new Tile(sf::Vector2f(j * TILE_WIDTH, (height - i) * TILE_HEIGHT), tmpSprite);
if (!isDynamic(id))
tiles[i].push_back(tile);
if (id)
{
int x;
int y;
for (std::vector<CollideBox *>::const_iterator it = tmpSprite->getColliders().begin();
it != tmpSprite->getColliders().end(); ++it) {
x = j * TILE_WIDTH + (*it)->getPos().x;
y = i * TILE_HEIGHT + (*it)->getPos().y;
if ((*it)->getRotation())
y += (sin((*it)->getRotation()) * 0.0174533) * (*it)->getPos().x / 2;
physicsEngine.createRectangle(x, y, (*it)->getWidth(),
(*it)->getHeight(), (*it)->getRotation(), isDynamic(id))->SetUserData(tmpSprite);
}
}
j++;
}
i++;
}
return (tiles);
}
|
#pragma once
#include "Transform.h"
class Camera : public Transform
{
private:
Matrix matView;
Matrix matProjection;
Matrix matViewProjection;
public:
Camera();
~Camera();
void UpdateMatrix();
// Device에 view랑 matrix 세팅, 카메라 메인화면에 띄우겠다.
void UpdateCamToDevice();
Matrix GetViewMatrix() { return matView; }
Matrix GetProjection() { return matProjection; }
Matrix GetViewProjection() { return matViewProjection; }
};
|
#include "stdafx.h"
#include "Texture.h"
Texture::Texture(string name) {
regex texName(name + "_(.+)\\.tga");
OutputDebugStringA(("\n\n" + name + "\n\n").c_str());
for (auto& p : std::experimental::filesystem::directory_iterator("./Texture")) {
string s = p.path().filename().generic_string();
smatch strMatch;
if (regex_match(s, strMatch, texName)) {
OutputDebugStringA(s.c_str());
OutputDebugStringA("\n");
OutputDebugStringA(strMatch[1].str().c_str());
OutputDebugStringA("\n");
}
}
}
void Texture::OnInitRenderer(ComPtr<ID3D11Device> d3dDevice) {
}
void Texture::OnRender(ComPtr<ID3D11DeviceContext> d3dContext) {
}
|
/** @see "data.hh" for detailed documentation of each function.
* (I wish I knew which file to put function documentation in.
* Hate repeating myself. Maybe I should have defined all my
* functions in the header to avoid this confusion.)
* @author Daniel "3ICE" Berezvai
* @student_id 262849
* @email daniel.berezvai@student.tut.fi
*/
#include "data.hh"
using namespace std;
/**
* @brief data::process checks the input for possible errors
* @param line, a CSV string
* @return success
* @see "data.hh" for full documentation
*/
bool data::process(string line){
//cout<<line<<endl;
Splitter s(line);
s.split(';');
//3ICE: error checking step: "must contain 3 semicolons" (testcases: bad_2, bad_3, bad_4, and bad_5)
if(s.number_of_fields()!=4) return false;
double price;
//3ICE: error checking step: "last field must be double" (testcase: bad_1)
try{
//3ICE: Convert from string:
price = stod(s.fetch_field(3));
}
catch(exception) {
return false;
}
//3ICE: error checking step: "can't contain spaces" (testcases: bad_6, and bad_8)
if(line.find_first_of(" \t") != string::npos) return false;
//3ICE: error checking step: "none of the fields are allowed to be empty" (testcase: bad_7)
if( s.fetch_field(0).length()==0 ||
s.fetch_field(1).length()==0 ||
s.fetch_field(2).length()==0 ||
s.fetch_field(3).length()==0) return false;
return add(s.fetch_field(0), s.fetch_field(1), s.fetch_field(2), price);
}
/**
* @brief data::add stores parameters in database
* @param market string name of marketplace
* @param store string name of store
* @param name string product name
* @param cost double price of product
* @return success
* @see "data.hh" for real documentation
*/
bool data::add(string market, string store, string name, double cost){
if(database.find(market) != database.end()){
//3ICE: Marketplace already exists.
if(database.at(market).find(store) != database.at(market).end()){
//3ICE: Store already exists.
//if(database.at(market).at(store).find(name) != database.at(market).at(store).end())
bool overwrite = false;
for (unsigned int i = 0; i < database[market][store].size(); ++i) {
if(database[market][store][i].name == name){
//3ICE: Product already exists. Gotta change its price:
overwrite = true;
database[market][store][i].price = cost;
} //3ICE: his check was required because:
//3ICE: If the same product is given to the same store more than once,
//3ICE: the last one of them will be used as an actual value (price).
}
//3ICE: Interestingly, this did not work:
//for(auto p : database[market][store]) if(p.name == name) p.price = cost;
//3ICE: Copy constructor called?
//3ICE: We did not find an already existing product with this name. Create it:
if(!overwrite) database.at(market).at(store).push_back(product(name, cost));
}else{
//3ICE: Store does not exist yet, create and fill it with one product:
database.at(market).insert({store, {product(name, cost)}} );
}
}else{
//3ICE: Marketplace doesn't exist. Create it,
database[market]=map<string, vector<product>>();
//3ICE: and fill the store inside it with first data point:
database[market][store] = {product(name, cost)};
}
return true;
}
/**
* @brief data::chains prints markets
* @see also "data.hh"
*/
void data::chains(){
vector<string> chain_names;
//3ICE: C++11 auto for loops are beautiful
for(auto marketplace : database){
chain_names.push_back(marketplace.first);
}
sort(chain_names.begin(), chain_names.end());
//cout << chain_names.size() << endl;
for(auto chain_name : chain_names){
cout << chain_name << endl;
}
}
/**
* @brief data::stores prints stores in a market
* @param market_name which market you want
* @see "data.hh"
*/
void data::stores(string market_name){
vector<string> stores;
if(database.find(market_name) == database.end()){
cout << "Error: Market " << market_name << " not found in database." << endl;
return;
}
for(market_iterator=database.at(market_name).begin();market_iterator!=database.at(market_name).end();++market_iterator){
stores.push_back(market_iterator->first);
}
sort(stores.begin(), stores.end());
for(auto store : stores){
cout << store << endl;
}
}
/**
* @brief alphabetical sorting for products like product::operator<
* but based on the name instead of price.
* @param a the left-side operand (product object)
* @param b the other product object
* @return comparator-like behavior (string-based, on name)
*/
bool alphabetical(const product&a, const product&b){
return a.name < b.name;
}
/**
* @brief data::products lists all products for sale in then given market's store
* @param market string name of
* @param store string name of
* @see "data.hh"
*/
void data::products(string market, string store){
vector<product> products;
//3ICE: Make sure they exist before using .at() recklessly:
if(database.find(market) == database.end()){
cout << "Error: Market " << market << " not found in database." << endl;
return;
}
if(database.at(market).find(store) == database.at(market).end()){
cout << "Error: Store " << store << " not found in database." << endl;
return;
}
//3ICE: Now it is safe to use db.at(m).at(s) as we are sure they both exist:
for(product_iterator = database.at(market).at(store).begin();
product_iterator != database.at(market).at(store).end();
++product_iterator){
products.push_back(*product_iterator);
}
sort(products.begin(), products.end(), alphabetical);
for(auto product : products){
//3ICE: Instead of doing any of these ugly things:
//(*product_iterator).print(); /* or */
//cout << product_iterator->name << endl << product_iterator->price << endl;
//3ICE: I can simply:
product.print();
}
}
/**
* @brief data::cheapest finds the best deals.
* @param name which product to look for
* @see "data.hh" as always
*/
void data::cheapest(string name){
double cheapest_price = numeric_limits<double>::max();//3ICE: I was hoping to do a min search instead, but:
//min_element(database.begin(), database.end(),
// [](double l, double r) -> bool { return l.second < r.second; });
vector<string> results;
for(store_iterator = database.begin();
store_iterator != database.end();
++store_iterator){
for(market_iterator = store_iterator->second.begin();
market_iterator != store_iterator->second.end();
++market_iterator){
for(product_iterator = market_iterator->second.begin();
product_iterator != market_iterator->second.end();
++product_iterator){
//cout<<product_iterator->name<<endl;
if(product_iterator->price <= cheapest_price && product_iterator->name == name){
//3ICE: Only reset if we found a cheaper minimum.
if(product_iterator->price < cheapest_price){
cheapest_price = product_iterator->price;
results.clear();
}
//3ICE: Record the marketplace and store information for later printing.
results.push_back(store_iterator->first + " " +market_iterator->first );
}
}
}
}
if(cheapest_price == numeric_limits<double>::max()) cout << "This product is not available anywhere." << endl;
else{
//3ICE: The price will be printed with two decimals.
cout << setprecision(2) << fixed << cheapest_price << endl;
//Store chain names are in alphabetical order and if there are multiple stores that have
//the same cheapest price for the product they will in turn be in alphabetical sub-order.
sort(results.begin(), results.end());
for(auto result : results){
cout << result << endl;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.